答:
The first result is expected as you are adding the list itself, not its values, to copy_l1. To get the desired result, use either of the following:

copy_l1 += list2

copy_l1.extend(list2)

The second result is harder to understand, but it has to do with the fact that lists are mutable in Python. To understand this, you must first understand what actually happens when you assign one variable to another.

Variable Assignment

When you use var_a = var_b, both names point to the same variable - that is, the same space in memory; they are just two different ways of accessing it. This can be tested using is, which checks for identity, not just value:

a = 1
b = a
print(a is b)
# True
```
<p>So you would expect that changing the value of one name would also affect the other. However, this is not usually the case.</p>
<h2>Changing the Value of an Immutable Variable</h2>
<p>Most basic data types in Python are <strong>immutable</strong>. This means that their value can't actually be changed once they are created. Some examples of immutable data types are <code>str</code>s, <code>int</code>s, <code>float</code>s and <code>bool</code>s.</p>
<p>If the data type of a variable is immutable, then its value can't be changed directly. Instead, when you alter the value of a name pointing it, this is what actually happens:</p>
<ol>
<li>A new variable is created</li>
<li>Its value is set to the new value</li>
<li>It is given the same name as the name which you are trying to alter - it effectively replaces it</li>
</ol>
<p>During this process, only one name has had its value changed (or rather, replaced) and any other names pointing to the same variable stay unchanged. You can test that the actual variable the name points to has changed using <code>is</code>:</p>
<pre class="lang-py prettyprint-override"><code>a = 5
b = a
print(a is b)
# True
a += 4
print(a is b)
# False
</code>```

Because of this, the fact that variable assignment works the way it does can almost always be ignored. But this changes when you use mutable variables, such as lists.

Changing the Value of a Mutable Variable

Because lists are mutable, their value can actually be changed so this three-step process is not necessary. Therefore, all names pointing to the list get changed. You can see this by using is once again:

a = [1, 2]
b = a
print(a is b)
# True
a += [3, 4]
print(a is b, "again")
# True again
```
<h2>How to Stop this Happening</h2>
<p>To stop this from happening, use <code>.copy()</code> to get a shallow copy of the list:</p>
<pre class="lang-py prettyprint-override"><code>copy_l1 = list1.copy()
</code>```

Now both names point to different variables, which happen to have the same value. Operations on one will not affect the other.

Title: Unexpected result when using list.append(). What am I doing wrong?

Body:
The first result is expected as you are adding the list itself, not its values, to copy_l1. To get the desired result, use either of the following:

copy_l1 += list2

copy_l1.extend(list2)

The second result is harder to understand, but it has to do with the fact that lists are mutable in Python. To understand this, you must first understand what actually happens when you assign one variable to another.

Variable Assignment

When you use var_a = var_b, both names point to the same variable - that is, the same space in memory; they are just two different ways of accessing it. This can be tested using is, which checks for identity, not just value:

a = 1
b = a
print(a is b)
# True

So you would expect that changing the value of one name would also affect the other. However, this is not usually the case.

Changing the Value of an Immutable Variable

Most basic data types in Python are immutable. This means that their value can't actually be changed once they are created. Some examples of immutable data types are strs, ints, floats and bools.

If the data type of a variable is immutable, then its value can't be changed directly. Instead, when you alter the value of a name pointing it, this is what actually happens:

A new variable is created

Its value is set to the new value

It is given the same name as the name which you are trying to alter - it effectively replaces it

During this process, only one name has had its value changed (or rather, replaced) and any other names pointing to the same variable stay unchanged. You can test that the actual variable the name points to has changed using is:

a = 5
b = a
print(a is b)
# True
a += 4
print(a is b)
# False

Because of this, the fact that variable assignment works the way it does can almost always be ignored. But this changes when you use mutable variables, such as lists.

Changing the Value of a Mutable Variable

Because lists are mutable, their value can actually be changed so this three-step process is not necessary. Therefore, all names pointing to the list get changed. You can see this by using is once again:

a = [1, 2]
b = a
print(a is b)
# True
a += [3, 4]
print(a is b, "again")
# True again

How to Stop this Happening

To stop this from happening, use .copy() to get a shallow copy of the list:

copy_l1 = list1.copy()

Now both names point to different variables, which happen to have the same value. Operations on one will not affect the other.


来源: stackexchange

问:
How can I invoke a callback within a React function component?
This is the code I have working right now from this answer, whose comments suggested using window.history. It works, but I'd prefer to go back correctly, using React router v6.

import {useNavigate} from "react-router-dom";
import Cookies from "universal-cookie";

function Foo() {
  const navigate = useNavigate();
  const cookies = new Cookies();

  if (cookies.get('foo') === 'bar') {
    window.history.go(-1);
    // () => navigate(-1); // this does not work
  }
  return (

  )
}
```

You can see commented out what I wanted to do, but that's not legal I think. And if I just use navigate(-1) it doesn't work, like the original question I linked.

So is there a way to use navigate inside Foo?

答:
```<code>() => navigate(-1); // this does not work
</code>```

This defines a function which will call navigate(-1) when it is called.

You never call it.

The dirty approach is to simply not wrap it in a function, but the main render function of a component shouldn't have side effects.

Wrap it in an effect hook instead.

```<code>const Foo = () => {
  const navigate = useNavigate();
  const cookies = new Cookies();

  const foo = cookies.get('foo');

  useEffect(() => {
      if (foo === 'bar') {
          navigate(-1);
      }
  }, [foo, navigate]);

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

ContentLicense: CC BY-SA 4.0

Body:
This is the code I have working right now from this answer, whose comments suggested using window.history. It works, but I'd prefer to go back correctly, using React router v6.

import {useNavigate} from "react-router-dom";
import Cookies from "universal-cookie";

function Foo() {
  const navigate = useNavigate();
  const cookies = new Cookies();

  if (cookies.get('foo') === 'bar') {
    window.history.go(-1);
    // () => navigate(-1); // this does not work
  }
  return (

  )
}

You can see commented out what I wanted to do, but that's not legal I think. And if I just use navigate(-1) it doesn't work, like the original question I linked.

So is there a way to use navigate inside Foo?

Body:
() => navigate(-1); // this does not work

This defines a function which will call navigate(-1) when it is called.

You never call it.

The dirty approach is to simply not wrap it in a function, but the main render function of a component shouldn't have side effects.

Wrap it in an effect hook instead.

const Foo = () => {
  const navigate = useNavigate();
  const cookies = new Cookies();

  const foo = cookies.get('foo');

  useEffect(() => {
      if (foo === 'bar') {
          navigate(-1);
      }
  }, [foo, navigate]);

  return (
    <div />
  );
};


问:
jqueryLazy not triggering when images gets visibles via css changes
I have a bunch of images, say 100 images, in a web page, and only 10 are visible without scrolling the page. The first 90 images have a "myclass" class.

I manage all images with jquery lazy (http://jquery.eisbehr.de/lazy/), and it works perfecty if I scroll the window.

However, If I make $(".myclass").hide() before scrolling down, I see the last 10 images, which don't have the "myclass" class, bug jquery lazy doesn't "reveal" them.

Why?

答:
Because lazyload triggers on scroll events.

$(window).scroll() (which triggers the scroll event on the window) is enough to solve the issue.

If the scrollable div is not the window object, use it instead of $(window).


问:
Pseudo Class Color Change on Hover
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

```<code><div class="task-resources-accordion">
  Title
</div>
<div class="task-resources-accordion-panel">
  <div class="task-resources-accordion-content">
    <p>Content</p>
  </div>
</div>

</code>```
```<code>/* Accordions */

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}

</code>```

答:
Some unicodes css properties are not changeable, and you picked one of those. Try a different code and as of css3 you have to use double colons, but that won't fix your problem, just a FYI. See [this pen][1] that I copied from yours for the fix. https://codepen.io/javascript-examples/pen/jOayVgq

```<code><div class="task-resources-accordion">
  Title
</div>
<div class="task-resources-accordion-panel">
  <div class="task-resources-accordion-content">
    <p>Content</p>
  </div>
</div>
</code>```

And the css:

```<code> /* Accordions */

 .task-resources-accordion {
 background-color: #eee;
 color: #1e1e1e;
 cursor: pointer;
 padding: 18px;
 width: 100%;
 box-sizing: border-box;
 text-align: left;
 border: none;
 outline: none;
 transition: 0.4s ease;
 font-family: "AleckCdBold", sans-serif;
 font-size: 18px;
 line-height: 24px;
 letter-spacing: 0;
 }

 .task-resources-accordion.active,
 .task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
 }

.task-resources-accordion::after {
 content: "\002B";
 font-size: 20px;
 float: left;
 margin-right: 5px;

 }

.task-resources-accordion::after:hover {
 content: "\002B";
 color: #fff;
 }

.task-resources-accordion.active::after {
 content: "\2212";
 font-size: 20px;
 margin-right: 5px;
 color: #fff;
 }

.task-resources-accordion-panel {
 padding: 0 18px;
 background-color: white;
 max-height: 0;
 overflow: hidden;
 transition: 0.4s ease;
 opacity: 0;
 margin-bottom: 10px;
 border: 1px solid #eaeaea;
 }

 .task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
  }

 .task-resources-accordion-content {
  padding: 15px;
  }
</code>```

Title: Pseudo Class Color Change on Hover

Body:
I have an accordion where upon hover, the text color changes. Sounds simple enough, but I have an issue with the content within a pseudo class changing color. I feel like I've added the :after:hover class in the to change the color, but it's not working? Any reason why?

There's a more detailed Codepen here.

  Title

Content

/* Accordions */

.task-resources-accordion {
  background-color: #eee;
  color: #1e1e1e;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  box-sizing: border-box;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s ease;
  font-size: 18px;
  line-height: 24px;
  letter-spacing: 0;
}

.task-resources-accordion.active,
.task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
}

.task-resources-accordion:after {
  content: "\2795";
  font-size: 13px;
  float: left;
  margin-right: 10px;
}

.task-resources-accordion:after:hover {
  color: #fff;
}

.task-resources-accordion.active:after {
  content: "\2796";
  color: #fff;
}

.task-resources-accordion-panel {
  padding: 0 18px;
  background-color: white;
  max-height: 0;
  overflow: hidden;
  transition: 0.4s ease;
  opacity: 0;
  margin-bottom: 10px;
  border: 1px solid #eaeaea;
}

.task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
}

.task-resources-accordion-content {
  padding: 15px;
}

Body:
Some unicodes css properties are not changeable, and you picked one of those. Try a different code and as of css3 you have to use double colons, but that won't fix your problem, just a FYI. See [this pen][1] that I copied from yours for the fix. https://codepen.io/javascript-examples/pen/jOayVgq

<div class="task-resources-accordion">
  Title
</div>
<div class="task-resources-accordion-panel">
  <div class="task-resources-accordion-content">
    <p>Content</p>
  </div>
</div>

And the css:

 /* Accordions */

 .task-resources-accordion {
 background-color: #eee;
 color: #1e1e1e;
 cursor: pointer;
 padding: 18px;
 width: 100%;
 box-sizing: border-box;
 text-align: left;
 border: none;
 outline: none;
 transition: 0.4s ease;
 font-family: "AleckCdBold", sans-serif;
 font-size: 18px;
 line-height: 24px;
 letter-spacing: 0;
 }

 .task-resources-accordion.active,
 .task-resources-accordion:hover {
  background-color: #21bfb2;
  color: #fff;
 }

.task-resources-accordion::after {
 content: "\002B";
 font-size: 20px;
 float: left;
 margin-right: 5px;

 }

.task-resources-accordion::after:hover {
 content: "\002B";
 color: #fff;
 }

.task-resources-accordion.active::after {
 content: "\2212";
 font-size: 20px;
 margin-right: 5px;
 color: #fff;
 }

.task-resources-accordion-panel {
 padding: 0 18px;
 background-color: white;
 max-height: 0;
 overflow: hidden;
 transition: 0.4s ease;
 opacity: 0;
 margin-bottom: 10px;
 border: 1px solid #eaeaea;
 }

 .task-resources-accordion-panel.show {
  opacity: 1;
  max-height: 1000px;
  }

 .task-resources-accordion-content {
  padding: 15px;
  }


问:
How to launch libgdx example?
I am trying to learn how to use socket in libgdx.
I'm trying to run the example, I can't figure out what I'm doing wrong.

i try to run this example:
https://github.com/libgdx/libgdx/blob/04094910142d11ee4028a4263ceb2597c2d9815f/tests/gdx-tests/src/com/badlogic/gdx/tests/net/PingPongSocketExample.java#L36

DesktopLauncher.java:

```<code>package com.nexlab.testing.desktop;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.nexlab.testing.PingPongSocketExample;
import com.nexlab.testing.Testing;

public class DesktopLauncher {
    public static void main (String[] arg) {

        PingPongSocketExample sss = new PingPongSocketExample();
        sss.create();

        Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
        new Lwjgl3Application(new Testing(), config);
    }
}
</code>```

PingPongSocketExample.java:

```<code>package com.nexlab.testing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.Protocol;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;

/** Demonstrates how to do very simple socket programming. Implements a classic PING-PONG sequence, client connects to server,
 * sends message, server sends message back to client. Both client and server run locally. We quit as soon as the client received
 * the PONG message from the server. This example won't work in HTML. Messages are delimited by the new line character, so we can
 * use a {@link BufferedReader}.
 * @author badlogic */
public class PingPongSocketExample extends GdxTest {
    @Override
    public void create () {
        System.out.println("!!!!!: 000");
        // setup a server thread where we wait for incoming connections
        // to the server
        new Thread(new Runnable() {
            @Override
            public void run () {
                System.out.println("!!!!!: 111");
                ServerSocketHints hints = new ServerSocketHints();
                ServerSocket server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 1381, hints);
                // wait for the next client connection
                Socket client = server.accept(null);
                // read message and send it back
                try {
                    String message = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
                    Gdx.app.log("PingPongSocketExample", "got client message: " + message);
                    System.out.println("!!!!!: got client message: " + message);
                    client.getOutputStream().write("PONG\n".getBytes());
                } catch (IOException e) {
                    Gdx.app.log("PingPongSocketExample", "an error occured", e);
                    System.out.println("!!!!!: an error occured");
                }
            }
        }).start();

        // create the client send a message, then wait for the
        // server to reply
        System.out.println("!!!!!: 222");
        SocketHints hints = new SocketHints();
        Socket client = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 1381, hints);
        try {
            client.getOutputStream().write("PING\n".getBytes());
            String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
            Gdx.app.log("PingPongSocketExample", "got server message: " + response);
            System.out.println("!!!!!: got server message: " + response);
        } catch (IOException e) {
            Gdx.app.log("PingPongSocketExample", "an error occured", e);
            System.out.println("!!!!!: an error occured");
        }
    }
}
</code>```

Log:

```<code>Executing tasks: [DesktopLauncher.main()] in project /Users/nexus/Nexus/dev_android/libgdx/testing

> Task :core:compileJava
> Task :core:processResources NO-SOURCE
> Task :core:classes
> Task :core:jar
> Task :desktop:compileJava UP-TO-DATE
> Task :desktop:processResources UP-TO-DATE
> Task :desktop:classes UP-TO-DATE

> Task :desktop:DesktopLauncher.main() FAILED
!!!!!: 000
!!!!!: 222
!!!!!: 111
Exception in thread "main" Exception in thread "Thread-0" java.lang.NullPointerException
    at com.nexlab.testing.PingPongSocketExample.create(PingPongSocketExample.java:50)
    at com.nexlab.testing.desktop.DesktopLauncher.main(DesktopLauncher.java:14)
java.lang.NullPointerException
    at com.nexlab.testing.PingPongSocketExample$1.run(PingPongSocketExample.java:30)
    at java.base/java.lang.Thread.run(Thread.java:829)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':desktop:DesktopLauncher.main()'.
> Process 'command '/Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 269ms
5 actionable tasks: 3 executed, 2 up-to-date
</code>```

What am I doing wrong?

答:
I don't know what your Testing class is, but to run this example directly, it needs to be your ApplicationListener that you pass to initialize():

```<code>public class DesktopLauncher {
    public static void main (String[] arg) {
        Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
        new Lwjgl3Application(new PingPongSocketExample(), config);
    }
}
</code>```

Title: How to launch libgdx example?

Body:
I am trying to learn how to use socket in libgdx.
I'm trying to run the example, I can't figure out what I'm doing wrong.

i try to run this example:
https://github.com/libgdx/libgdx/blob/04094910142d11ee4028a4263ceb2597c2d9815f/tests/gdx-tests/src/com/badlogic/gdx/tests/net/PingPongSocketExample.java#L36

DesktopLauncher.java:

package com.nexlab.testing.desktop;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3Application;
import com.badlogic.gdx.backends.lwjgl3.Lwjgl3ApplicationConfiguration;
import com.nexlab.testing.PingPongSocketExample;
import com.nexlab.testing.Testing;

public class DesktopLauncher {
    public static void main (String[] arg) {

        PingPongSocketExample sss = new PingPongSocketExample();
        sss.create();

        Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
        new Lwjgl3Application(new Testing(), config);
    }
}

PingPongSocketExample.java:

package com.nexlab.testing;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Net.Protocol;
import com.badlogic.gdx.net.ServerSocket;
import com.badlogic.gdx.net.ServerSocketHints;
import com.badlogic.gdx.net.Socket;
import com.badlogic.gdx.net.SocketHints;

/** Demonstrates how to do very simple socket programming. Implements a classic PING-PONG sequence, client connects to server,
 * sends message, server sends message back to client. Both client and server run locally. We quit as soon as the client received
 * the PONG message from the server. This example won't work in HTML. Messages are delimited by the new line character, so we can
 * use a {@link BufferedReader}.
 * @author badlogic */
public class PingPongSocketExample extends GdxTest {
    @Override
    public void create () {
        System.out.println("!!!!!: 000");
        // setup a server thread where we wait for incoming connections
        // to the server
        new Thread(new Runnable() {
            @Override
            public void run () {
                System.out.println("!!!!!: 111");
                ServerSocketHints hints = new ServerSocketHints();
                ServerSocket server = Gdx.net.newServerSocket(Protocol.TCP, "localhost", 1381, hints);
                // wait for the next client connection
                Socket client = server.accept(null);
                // read message and send it back
                try {
                    String message = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
                    Gdx.app.log("PingPongSocketExample", "got client message: " + message);
                    System.out.println("!!!!!: got client message: " + message);
                    client.getOutputStream().write("PONG\n".getBytes());
                } catch (IOException e) {
                    Gdx.app.log("PingPongSocketExample", "an error occured", e);
                    System.out.println("!!!!!: an error occured");
                }
            }
        }).start();

        // create the client send a message, then wait for the
        // server to reply
        System.out.println("!!!!!: 222");
        SocketHints hints = new SocketHints();
        Socket client = Gdx.net.newClientSocket(Protocol.TCP, "localhost", 1381, hints);
        try {
            client.getOutputStream().write("PING\n".getBytes());
            String response = new BufferedReader(new InputStreamReader(client.getInputStream())).readLine();
            Gdx.app.log("PingPongSocketExample", "got server message: " + response);
            System.out.println("!!!!!: got server message: " + response);
        } catch (IOException e) {
            Gdx.app.log("PingPongSocketExample", "an error occured", e);
            System.out.println("!!!!!: an error occured");
        }
    }
}

Log:

Executing tasks: [DesktopLauncher.main()] in project /Users/nexus/Nexus/dev_android/libgdx/testing

> Task :core:compileJava
> Task :core:processResources NO-SOURCE
> Task :core:classes
> Task :core:jar
> Task :desktop:compileJava UP-TO-DATE
> Task :desktop:processResources UP-TO-DATE
> Task :desktop:classes UP-TO-DATE

> Task :desktop:DesktopLauncher.main() FAILED
!!!!!: 000
!!!!!: 222
!!!!!: 111
Exception in thread "main" Exception in thread "Thread-0" java.lang.NullPointerException
    at com.nexlab.testing.PingPongSocketExample.create(PingPongSocketExample.java:50)
    at com.nexlab.testing.desktop.DesktopLauncher.main(DesktopLauncher.java:14)
java.lang.NullPointerException
    at com.nexlab.testing.PingPongSocketExample$1.run(PingPongSocketExample.java:30)
    at java.base/java.lang.Thread.run(Thread.java:829)

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':desktop:DesktopLauncher.main()'.
> Process 'command '/Applications/Android Studio.app/Contents/jre/Contents/Home/bin/java'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 8.0.

You can use '--warning-mode all' to show the individual deprecation warnings and determine if they come from your own scripts or plugins.

See https://docs.gradle.org/7.2/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 269ms
5 actionable tasks: 3 executed, 2 up-to-date

What am I doing wrong?

Body:
I don't know what your Testing class is, but to run this example directly, it needs to be your ApplicationListener that you pass to initialize():

public class DesktopLauncher {
    public static void main (String[] arg) {
        Lwjgl3ApplicationConfiguration config = new Lwjgl3ApplicationConfiguration();
        new Lwjgl3Application(new PingPongSocketExample(), config);
    }
}


问:
android layout: This tag and its children can be replaced by one <TextView/> and a compound drawable
When I run layout on a specific XML file, I get this:

```<code> This tag and its children can be replaced by one <TextView/>
and a compound drawable
</code>```

What change should be done for the following xml code:

```<code><LinearLayout android:id="@+id/name_layout"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:background="@drawable/grouplist_single_left_grey_area" >
                <ImageView android:id="@+id/photo_image"
                    android:layout_width="@dimen/thumbnail_width"
                    android:layout_height="@dimen/thumbnail_height"
                    android:paddingBottom="5dip"
                    android:paddingTop="5dip"
                    android:paddingRight="5dip"
                    android:paddingLeft="5dip"
                    android:layout_marginRight="5dip"
                    android:clickable="true"
                    android:focusable="true"
                    android:scaleType="fitCenter"
                    android:src="@*android:drawable/nopicture_thumbnail"
                    android:background="@drawable/photo_highlight" />
                <TextView android:id="@+id/name"
                    android:paddingLeft="5dip"
                    android:layout_weight="1"
                    android:layout_width="0dip"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:textAppearance="?android:attr/textAppearanceLarge" />
            </LinearLayout>
</code>```

This is how it looks like on the screen:

The camera icon is the default. Clicking on that will give the user an option to choose another image.

答: I don't know if this is an efficient solution. But using <androidx.appcompat.widget.LinearLayoutCompat> to wrap the imageView and TextView instead of <LinearLayout> will fix this error. Also by using LinearLayoutCompat, you will be able to adjust the image's width and height which you can't when using a drawableRight, drawableLeft, drawableTop or drawableBottom inside a TextView.

ContentLicense: CC BY-SA 3.0

Body:
When I run layout on a specific XML file, I get this:

 This tag and its children can be replaced by one <TextView/>
and a compound drawable

What change should be done for the following xml code:

<LinearLayout android:id="@+id/name_layout"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:background="@drawable/grouplist_single_left_grey_area" >
                <ImageView android:id="@+id/photo_image"
                    android:layout_width="@dimen/thumbnail_width"
                    android:layout_height="@dimen/thumbnail_height"
                    android:paddingBottom="5dip"
                    android:paddingTop="5dip"
                    android:paddingRight="5dip"
                    android:paddingLeft="5dip"
                    android:layout_marginRight="5dip"
                    android:clickable="true"
                    android:focusable="true"
                    android:scaleType="fitCenter"
                    android:src="@*android:drawable/nopicture_thumbnail"
                    android:background="@drawable/photo_highlight" />
                <TextView android:id="@+id/name"
                    android:paddingLeft="5dip"
                    android:layout_weight="1"
                    android:layout_width="0dip"
                    android:layout_height="wrap_content"
                    android:gravity="center_vertical"
                    android:textAppearance="?android:attr/textAppearanceLarge" />
            </LinearLayout>

This is how it looks like on the screen:

The camera icon is the default. Clicking on that will give the user an option to choose another image.


问:
R Data.Table: Dynamically Update a Different Column for each Row
I'm working on some code where I need to find the maximum value over a set of columns and then update that maximum value. Consider this toy example:

```<code>test <- data.table(thing1=c('AAA','BBB','CCC','DDD','EEE'),
                        A=c(9,5,4,2,5),
                        B=c(2,7,2,6,3),
                        C=c(6,2,5,4,1),
                      ttl=c(1,1,3,2,1))
</code>```

where the resulting data.table looks like this:

thing1
A
B
C
ttl

AAA
9
2
6
1

BBB
5
7
2
1

CCC
4
2
5
3

DDD
2
6
4
2

EEE
5
3
1
1

The goal is to find the column (A, B, or C) with the maximum value and replace that value by the current value minus 0.1 times the value in the ttl column (i.e. new_value=old_value - 0.1*ttl). The other columns (not containing the maximum value) should remain the same. The resulting DT should look like this:

thing1
A
B
C
ttl

AAA
8.9
2
6
1

BBB
5
6.9
2
1

CCC
4
2
4.7
3

DDD
2
5.8
4
2

EEE
4.9
3
1
1

The "obvious" way of doing this is to write a for loop and loop through each row of the DT. That's easy enough to do and is what the code I'm adapting this from did. However, the real DT is much larger than my toy example and the for loop takes some time to run, which is why I'm trying to adapt the code to take advantage of vectorization and get rid of the loop.

Here's what I have so far:

```<code>test[,max_position:=names(.SD)[apply(.SD,1,function(x) which.max(x))],.SDcols=(2:4)]
test[,newmax:=get(max_position)-ttl*.1,by=1:nrow(test)]
</code>```

which produces this DT:

thing1
A
B
C
ttl
max_position
newmax

AAA
9
2
6
1
A
8.9

BBB
5
7
2
1
B
6.9

CCC
4
2
5
3
C
4.7

DDD
2
6
4
2
B
5.8

EEE
5
3
1
1
A
4.9

The problem comes in assigning the value of the newmax column back to where it needs to go. I naively tried this, along with some other things, which tells me that "'max_position' not found":

```<code>test[,(max_position):=newmax,by=1:nrow(test)]
</code>```

It's straightforward to solve the problem by reshaping the DT, which is the solution I have in place for now (see below), but I worry that with my full DT two reshapes will be slow as well (though presumably better than the for loop). Any suggestions on how to make this work as intended?

Reshaping solution, for reference:

```<code>test[,max_position:=names(.SD)[apply(.SD,1,function(x) which.max(x))],.SDcols=(2:4)]
test[,newmax:=get(max_position)-ttl*.1,by=1:nrow(test)]
test <- setDT(gather(test,idgroup,val,c(A,B,C)))
test[,maxval:=max(val),by='thing1']
test[val==maxval,val:=newmax][,maxval:=NULL]
test <- setDT(spread(test,idgroup,val))
</code>```

答:
With the OP's code, replace can work

```<code>test[, (2:4) := replace(.SD, which.max(.SD), max(.SD, na.rm = TRUE) - 0.1 * ttl),
    by = 1:nrow(test),.SDcols = 2:4]
</code>```

-output

```<code>> test
   thing1   A   B   C ttl
1:    AAA 8.9 2.0 6.0   1
2:    BBB 5.0 6.9 2.0   1
3:    CCC 4.0 2.0 4.7   3
4:    DDD 2.0 5.8 4.0   2
5:    EEE 4.9 3.0 1.0   1
</code>```

In base R, this may be faster with row/column indexing

```<code>test1 <- as.data.frame(test)
m1 <- cbind(seq_len(nrow(test1)), max.col(test1[2:4], "first"))
test1[2:4][m1] <- test1[2:4][m1] - 0.1 * test1$ttl
</code>```

Body:
I'm working on some code where I need to find the maximum value over a set of columns and then update that maximum value. Consider this toy example:

test <- data.table(thing1=c('AAA','BBB','CCC','DDD','EEE'),
                        A=c(9,5,4,2,5),
                        B=c(2,7,2,6,3),
                        C=c(6,2,5,4,1),
                      ttl=c(1,1,3,2,1))

where the resulting data.table looks like this:

thing1
A
B
C
ttl

AAA
9
2
6
1

BBB
5
7
2
1

CCC
4
2
5
3

DDD
2
6
4
2

EEE
5
3
1
1

The goal is to find the column (A, B, or C) with the maximum value and replace that value by the current value minus 0.1 times the value in the ttl column (i.e. new_value=old_value - 0.1*ttl). The other columns (not containing the maximum value) should remain the same. The resulting DT should look like this:

thing1
A
B
C
ttl

AAA
8.9
2
6
1

BBB
5
6.9
2
1

CCC
4
2
4.7
3

DDD
2
5.8
4
2

EEE
4.9
3
1
1

The "obvious" way of doing this is to write a for loop and loop through each row of the DT. That's easy enough to do and is what the code I'm adapting this from did. However, the real DT is much larger than my toy example and the for loop takes some time to run, which is why I'm trying to adapt the code to take advantage of vectorization and get rid of the loop.

Here's what I have so far:

test[,max_position:=names(.SD)[apply(.SD,1,function(x) which.max(x))],.SDcols=(2:4)]
test[,newmax:=get(max_position)-ttl*.1,by=1:nrow(test)]

which produces this DT:

thing1
A
B
C
ttl
max_position
newmax

AAA
9
2
6
1
A
8.9

BBB
5
7
2
1
B
6.9

CCC
4
2
5
3
C
4.7

DDD
2
6
4
2
B
5.8

EEE
5
3
1
1
A
4.9

The problem comes in assigning the value of the newmax column back to where it needs to go. I naively tried this, along with some other things, which tells me that "'max_position' not found":

test[,(max_position):=newmax,by=1:nrow(test)]

It's straightforward to solve the problem by reshaping the DT, which is the solution I have in place for now (see below), but I worry that with my full DT two reshapes will be slow as well (though presumably better than the for loop). Any suggestions on how to make this work as intended?

Reshaping solution, for reference:

test[,max_position:=names(.SD)[apply(.SD,1,function(x) which.max(x))],.SDcols=(2:4)]
test[,newmax:=get(max_position)-ttl*.1,by=1:nrow(test)]
test <- setDT(gather(test,idgroup,val,c(A,B,C)))
test[,maxval:=max(val),by='thing1']
test[val==maxval,val:=newmax][,maxval:=NULL]
test <- setDT(spread(test,idgroup,val))

Body:
With the OP's code, replace can work

test[, (2:4) := replace(.SD, which.max(.SD), max(.SD, na.rm = TRUE) - 0.1 * ttl),
    by = 1:nrow(test),.SDcols = 2:4]

-output

> test
   thing1   A   B   C ttl
1:    AAA 8.9 2.0 6.0   1
2:    BBB 5.0 6.9 2.0   1
3:    CCC 4.0 2.0 4.7   3
4:    DDD 2.0 5.8 4.0   2
5:    EEE 4.9 3.0 1.0   1

In base R, this may be faster with row/column indexing

test1 <- as.data.frame(test)
m1 <- cbind(seq_len(nrow(test1)), max.col(test1[2:4], "first"))
test1[2:4][m1] <- test1[2:4][m1] - 0.1 * test1$ttl


问:
C comparison between -1 and 65535/4294967295/18446744073709551615
I have a misunderstanding about the following statements:

```<code>printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);
</code>```

The output is:

```<code>0
0
0
1
</code>```

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

答:
This seems to be an example of inconsistent behavior of the compiler leading to surprising results:

printf("%d\n", -1 == 18446744073709551615); compiled with gcc produces a warning integer constant is so large that it is unsigned because it exceeds the range of type long long int. If you were to store this number into an unsigned long long, you would probably get the expected unsigned long long value, but it is used in a test and you are comparing -1 with a positive integer of an extended type, so the compiler might just optimize the test as false in all cases. gcc outputs 1 for printf("%d\n", 18446744073709551615 == 36893488147419103231) so the compiler does not exactly use 128 bit arithmetics to evaluate this test.

compiling with clang produces a similar warning integer literal is too large to be represented in a signed integer type, interpreting as unsigned but the code generated is different and the output is 1, meaning that 18446744073709551615 is typed as unsigned long long internally, consistently with the comment emitted.

Here is a program to substantiate my statement:

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

#define typeof(X)  _Generic((X),                                        \
                   long double: "long double",                          \
                   double: "double",                                    \
                   float: "float",                                      \
                   unsigned long long int: "unsigned long long int",    \
                   long long int: "long long int",                      \
                   unsigned long int: "unsigned long int",              \
                   long int: "long int",                                \
                   unsigned int: "unsigned int",                        \
                   int: "int",                                          \
                   unsigned short: "unsigned short",                    \
                   short: "short",                                      \
                   unsigned char: "unsigned char",                      \
                   signed char: "signed char",                          \
                   char: "char",                                        \
                   bool: "bool",                                        \
                   default: "other")

int main() {
#define TEST(x)  printf("%8s has type %s and size %zu\n", #x, typeof(x), sizeof(x))
    TEST(9223372036854775807);
    TEST(18446744073709551615U);
    TEST(18446744073709551615);
}
</code>```

Output with clang:

```<code>typeof.c:27:10: warning: integer literal is too large to be represented in a signed integer type, interpreting as unsigned
      [-Wimplicitly-unsigned-literal]
    TEST(18446744073709551615);
         ^
typeof.c:27:10: warning: integer literal is too large to be represented in a signed integer type, interpreting as unsigned
      [-Wimplicitly-unsigned-literal]
2 warnings generated.

9223372036854775807 has type long int and size 8
18446744073709551615U has type unsigned long int and size 8
18446744073709551615 has type unsigned long long int and size 8
</code>```

Output with gcc:

```<code>typeof.c: In function `main':
typeof.c:27:30: warning: integer constant is so large that it is unsigned
     TEST(18446744073709551615);
                              ^
typeof.c:27:30: warning: integer constant is so large that it is unsigned
9223372036854775807 has type long int and size 8
18446744073709551615U has type unsigned long int and size 8
18446744073709551615 has type other and size 16
</code>```

Body:
I have a misunderstanding about the following statements:

printf("%d\n", -1 == 65535);
printf("%d\n", -1 == 4294967295UL);
printf("%d\n", -1 == 18446744073709551615);
printf("%d\n", -1 == 18446744073709551615UL);

The output is:

0
0
0
1

If if don't add the UL suffixes the compiler gives the following warning: main.c:36:28: warning: integer constant is so large that it is unsigned

Can someone explain this to me please? Why for 18446744073709551615 the result is 0 but for 18446744073709551615UL the results is 1? It's ok not to add that suffix?

Thanks

Body:
This seems to be an example of inconsistent behavior of the compiler leading to surprising results:

printf("%d\n", -1 == 18446744073709551615); compiled with gcc produces a warning integer constant is so large that it is unsigned because it exceeds the range of type long long int. If you were to store this number into an unsigned long long, you would probably get the expected unsigned long long value, but it is used in a test and you are comparing -1 with a positive integer of an extended type, so the compiler might just optimize the test as false in all cases. gcc outputs 1 for printf("%d\n", 18446744073709551615 == 36893488147419103231) so the compiler does not exactly use 128 bit arithmetics to evaluate this test.

compiling with clang produces a similar warning integer literal is too large to be represented in a signed integer type, interpreting as unsigned but the code generated is different and the output is 1, meaning that 18446744073709551615 is typed as unsigned long long internally, consistently with the comment emitted.

Here is a program to substantiate my statement:

#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>

#define typeof(X)  _Generic((X),                                        \
                   long double: "long double",                          \
                   double: "double",                                    \
                   float: "float",                                      \
                   unsigned long long int: "unsigned long long int",    \
                   long long int: "long long int",                      \
                   unsigned long int: "unsigned long int",              \
                   long int: "long int",                                \
                   unsigned int: "unsigned int",                        \
                   int: "int",                                          \
                   unsigned short: "unsigned short",                    \
                   short: "short",                                      \
                   unsigned char: "unsigned char",                      \
                   signed char: "signed char",                          \
                   char: "char",                                        \
                   bool: "bool",                                        \
                   default: "other")

int main() {
#define TEST(x)  printf("%8s has type %s and size %zu\n", #x, typeof(x), sizeof(x))
    TEST(9223372036854775807);
    TEST(18446744073709551615U);
    TEST(18446744073709551615);
}

Output with clang:

typeof.c:27:10: warning: integer literal is too large to be represented in a signed integer type, interpreting as unsigned
      [-Wimplicitly-unsigned-literal]
    TEST(18446744073709551615);
         ^
typeof.c:27:10: warning: integer literal is too large to be represented in a signed integer type, interpreting as unsigned
      [-Wimplicitly-unsigned-literal]
2 warnings generated.

9223372036854775807 has type long int and size 8
18446744073709551615U has type unsigned long int and size 8
18446744073709551615 has type unsigned long long int and size 8

Output with gcc:

typeof.c: In function `main':
typeof.c:27:30: warning: integer constant is so large that it is unsigned
     TEST(18446744073709551615);
                              ^
typeof.c:27:30: warning: integer constant is so large that it is unsigned
9223372036854775807 has type long int and size 8
18446744073709551615U has type unsigned long int and size 8
18446744073709551615 has type other and size 16


问:
Getting an error while trying to map a list of objects
I'm trying to map below list :

```<code>mappedCustomers = customers.stream().map(e ->e.setLastName("e")).collect(Collectors.toList());
</code>```

Customer Class

```<code>@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue
Long id;

String firstName;

String lastName;

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}
</code>```

}

But I'm getting this error:

no instance(s) of type variable(s) R exist so that void conforms to R

答:
Map function from the Stream API, is expecting a function that return a value.

```<code><R> Stream<R> map(Function<? super T,? extends R> mapper)
</code>```

However setters return value is void (no return value at all), therefore your code does not comply with the map method signature, if you want to iterate over a collection and execute an operation you could use forEach

```<code>void forEach(Consumer<? super T> action)
</code>```

No need to do the collection as you initial collection will be the same but it will contain your modification.

```<code>customers.stream().forEach(x -> x.setLastName("e"))
</code>```

Body:
I'm trying to map below list :

mappedCustomers = customers.stream().map(e ->e.setLastName("e")).collect(Collectors.toList());

Customer Class

@Entity
@Table(name = "customer")
public class Customer {

@Id
@GeneratedValue
Long id;

String firstName;

String lastName;

public Long getId() {
    return id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

}

But I'm getting this error:

no instance(s) of type variable(s) R exist so that void conforms to R

Body:
Map function from the Stream API, is expecting a function that return a value.

<R> Stream<R> map(Function<? super T,? extends R> mapper)

However setters return value is void (no return value at all), therefore your code does not comply with the map method signature, if you want to iterate over a collection and execute an operation you could use forEach

void forEach(Consumer<? super T> action)

No need to do the collection as you initial collection will be the same but it will contain your modification.

customers.stream().forEach(x -> x.setLastName("e"))


问:
Observing changes of derived properties: CALayer KVO example
Is there a way to observe changes in derived properties?  For example, I want to know when a CALayer has been added as a sublayer so that I can adjust its geometry relative to its (new) parent.

So, I have a subclassed CALayer, say CustomLayer, and I figured I could register an observer  for the property in init:

```<code>[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]
</code>```

and implement observeValueForKeyPath:ofObject:change:context.  Nothing ever happens because, presumably, superlayer is a derived property (the attr dictionary stores an opaque ID for the parent).  Similarly, I can't subclass setSuperlayer: because it is never called.  In fact, as far as I can tell there are no instance methods called or public properties set on the sublayer when a parent does [self addSublayer:aCustomLayer].

Then I thought, OK, I'll subclass addSublayer like this:

```<code>- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}
</code>```

but still nothing!  (Perhaps it's a clue that when I make a simple standalone test class and use the will[did]ChangeValueForKey: then it works.)  This is maybe a more general Cocoa KVO question.  What should I be doing?  Thanks in advance!

答:
```<code>[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]
</code>```

Don't observe yourself through KVO. Change your accessors instead.

Similarly, I can't subclass setSuperlayer: because it is never called.

I take it you tried this and added NSLog and found that it wasn't called?

Then I thought, OK, I'll subclass addSublayer like this:

```<code>- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}
</code>```

And the parent layer is also a CustomLayer, right? If the parent layer is a plain CALayer, anything you do in CustomLayer will have no effect.

OwnerDisplayName: dk

ContentLicense: CC BY-SA 2.5

Body:
Is there a way to observe changes in derived properties?  For example, I want to know when a CALayer has been added as a sublayer so that I can adjust its geometry relative to its (new) parent.

So, I have a subclassed CALayer, say CustomLayer, and I figured I could register an observer  for the property in init:

[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]

and implement observeValueForKeyPath:ofObject:change:context.  Nothing ever happens because, presumably, superlayer is a derived property (the attr dictionary stores an opaque ID for the parent).  Similarly, I can't subclass setSuperlayer: because it is never called.  In fact, as far as I can tell there are no instance methods called or public properties set on the sublayer when a parent does [self addSublayer:aCustomLayer].

Then I thought, OK, I'll subclass addSublayer like this:

- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}

but still nothing!  (Perhaps it's a clue that when I make a simple standalone test class and use the will[did]ChangeValueForKey: then it works.)  This is maybe a more general Cocoa KVO question.  What should I be doing?  Thanks in advance!

Body:
[self addObserver:self forKeyPath:@"superlayer" options:0 context:nil]

Don't observe yourself through KVO. Change your accessors instead.

Similarly, I can't subclass setSuperlayer: because it is never called.

I take it you tried this and added NSLog and found that it wasn't called?

Then I thought, OK, I'll subclass addSublayer like this:

- (void)addSublayer:(CALayer *)aLayer {
    [aLayer willChangeValueForKey:@"superlayer"];
    [super addSublayer:aLayer];
    [aLayer didChangeValueForKey:@"superlayer"];
}

And the parent layer is also a CustomLayer, right? If the parent layer is a plain CALayer, anything you do in CustomLayer will have no effect.

OwnerDisplayName: Peter Hosey


问:
Facebook Application Post To Wall
Can anyone explain how to make an application, that updates users status, let's say every 10 mins, once he authorizes the access using the latest FB SDK.</p>

答:
You can find the proper method for posting to a user here:

https://developers.facebook.com/docs/reference/api/user/#posts

Once you have your application working you should be able to use something like CRON to enable it to run and update the user status at various intervals.

As mentioned in one of the comments every 10 minutes seems excessive so be sure you're abiding by Facebook's terms of service with whatever your doing.  Most of the time as long as the action your going to be taking is explained clearly to the user as they're authorizing your application you should be alright.

Title: Facebook Application Post To Wall


问:
Igx Button to open a link and download a file
Is it possible to download a file (e.g. Power point presentation) through a link when an igx Button is clicked? I could not find any related topic to my question.

Here is my example code:

```<code>  <button igxButton="raised" (click)="downloadFile()" class="downloadBtn">
    Download File
  </button>
</code>```

and the function:

```<code>downloadFile() {
   let exampleLink = "https://downloadexamplefile.com/fileid123"
  }
</code>```

Thank you!

答:
This functionality is not specific to the igxButton. The button may be a tirgger for the download action, although the actual action is something that you will need to handle.

An example would be creating a Service and specifying the responseType option  that upon GET request can return a blob representing the downloaded file. Then you can call this service, subscribe to the corresponding observable, and eventually save the file upon igxButton click

Example:
https://www.thecodehubs.com/download-file-with-httpclient-in-angular/

Body:
Is it possible to download a file (e.g. Power point presentation) through a link when an igx Button is clicked? I could not find any related topic to my question.

Here is my example code:

  <button igxButton="raised" (click)="downloadFile()" class="downloadBtn">
    Download File
  </button>

and the function:

downloadFile() {
   let exampleLink = "https://downloadexamplefile.com/fileid123"
  }

Thank you!


问:
how to share a bool value between UIControl classes
I have two classes , I need to pass the bool value from class one to  class two. if it is true then need to print something in the second class.

How can I pass Bool Value between two classes in swift

答:
You need to assign a value to your property before the superclass initializer is called. So it should be probably:

```<code>public required init?(coder : NSCoder){
 self.radioSelected = false
super.init(coder : coder)
_init()
}
</code>```

and

```<code>public override init (frame : CGRect){
self.radioSelected = false
super.init(frame : frame)
_init()
}
</code>```

and the errors should vanish

or even shorter:

```<code>@Binding  var radioSelected : Bool = false
</code>```

Body:
You need to assign a value to your property before the superclass initializer is called. So it should be probably:

public required init?(coder : NSCoder){
 self.radioSelected = false
super.init(coder : coder)
_init()
}

and

public override init (frame : CGRect){
self.radioSelected = false
super.init(frame : frame)
_init()
}

and the errors should vanish

or even shorter:

@Binding  var radioSelected : Bool = false


问:
Why am I having problems passing argument to or from a FORTRAN DLL from VB.NET
I have a DLL written in fortran that I know works because I am getting it from a working software package that we use daily.  I am trying to call it from anything but am having problems i believe with passing the correctly formatted arguments in and out of it, so i decided to try and access it from a VB program.  I chose VB because I have contacted the developer of the software package we are using and he gave me his DLL function call in VB6, even though he is not allowed to show me the FORTRAN source.

Problem is (perhaps, i think) that I am writing in VB.NET, which has different data types than VB6.  Can anyone see why i am am having problems.

The error i get upon running is: "AccessViolationException was unhandled: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Here is the function call i was supplied with:

```<code>Declare Sub FCC_Curves Lib "FCC_Curves.dll" (Read_Flag As Boolean, First_Flag As Boolean, Frequency_MHz As Single, IQT As Integer,  ByVal Radiation_Opt As String, ByVal L1 As Long,  ERP_Watts As Single, T_PowerWatts As Single, Tx_GaindBi As Single, T_Loss As Single, ByVal Service As String, ByVal L2 As Long, Reliability As Integer, ByVal FCC_CurvesDataPath As String, ByVal L3 As Long,  ByVal TerrainRoughness As String, ByVal L4 As Long, Haatm As Single, NPRfl As Integer, NFCCCurve As Integer, HPRfl As Single,  Crve As Single, FCC_Loss As Single, Code As Integer, FS As Single)
</code>```

and here is my code:

```<code>Module Module1

    Declare Sub FCC_Curves Lib "FCC_Curves.dll" (ByVal Read_Flag As Boolean, ByVal First_Flag As Boolean, ByVal Frequency_MHz As Single, ByVal IQT As Int16, ByVal Radiation_Opt As String, ByVal L1 As Int32, ByVal ERP_Watts As Single, ByVal T_PowerWatts As Single, ByVal Tx_GaindBi As Single, ByVal T_Loss As Single, ByVal Service As String, ByVal L2 As Int32, ByVal Reliability As Int16, ByVal FCC_CurvesDataPath As String, ByVal L3 As Int32, ByVal TerrainRoughness As String, ByVal L4 As Int32, ByVal Haatm As Single, ByVal NPRfl As Int16, ByVal NFCCCurve As Int16, ByVal HPRfl() As Single, ByVal Crve() As Single, ByRef FCC_Loss As Single, ByRef Code As Int16, ByRef FS() As Single)

    Sub Main()

        Dim Read_Flag As Boolean
        Dim First_Flag As Boolean
        Dim Frequency_MHz As Single
        Dim IQT As Int16
        Dim Radiation_Opt As String
        Dim L1 As Int32
        Dim ERP_Watts As Single
        Dim T_PowerWatts As Single
        Dim Tx_GaindBi As Single
        Dim T_Loss As Single
        Dim Service As String
        Dim L2 As Int32
        Dim Reliability As Int16
        Dim FCC_CurvesDataPath As String
        Dim L3 As Int32
        Dim TerrainRoughness As String
        Dim L4 As Int32
        Dim Haatm As Single
        Dim NPRfl As Int16
        Dim NFCCCurve As Int16
        Dim HPRfl(12) As Single
        Dim Crve(5) As Single
        Dim FCC_Loss As Single
        Dim Code As Int16
        Dim FS(15) As Single
        'Dim HPRfl As Single
        'Dim Crve As Single
        'Dim FCC_Loss As Single
        'Dim Code As Int16
        'Dim FS As Single

        Read_Flag = True
        First_Flag = True
        Frequency_MHz = 98.1
        IQT = 0
        Radiation_Opt = "ERP"
        L1 = 3
        ERP_Watts = 1000
        T_PowerWatts = 1000
        Tx_GaindBi = 2.15
        T_Loss = 0
        Service = "Broadcast"
        L2 = 9
        Reliability = 50
        FCC_CurvesDataPath = "C:\Program Files\CSPT_Extension\data\"
        L3 = 37
        TerrainRoughness = "Off"
        L4 = 3
        Haatm = 1500
        NPRfl = 13
        NFCCCurve = 6
        Dim i As Int16
        HPRfl(0) = 11
        HPRfl(1) = 128
        For i = 2 To 12
            HPRfl(i) = 1500
        Next
        For i = 0 To 5
            Crve(i) = i * 15
        Next

        FCC_Curves(Read_Flag, First_Flag, Frequency_MHz, IQT, Radiation_Opt, L1, ERP_Watts, T_PowerWatts, Tx_GaindBi, T_Loss, Service, L2, Reliability, FCC_CurvesDataPath, L3, TerrainRoughness, L4, Haatm, NPRfl, NFCCCurve, HPRfl, Crve, FCC_Loss, Code, FS)

    End Sub

End Module
</code>```

答:
Thought I'd post my experience passing arguments from VB.net (.net v5, VS 64bit v17.0.5) to dll created with gfortran 7.3.0(in code::blocks).  The example shows  passing integers, a byte array, and a way to handle a character string passing via the byte array.  I'm not a pro-programmer, programming is just a tool for me, so my "programming vernacular" may not be correct.  Note I'm running these codes on a 64bit machine using Windows 10 (64bit).

First, the fortran code for the dll:

```<code>  subroutine intmul(i,j,k,n)
!GCC$ ATTRIBUTES STDCALL, DLLEXPORT :: intmul
      integer, intent(inout) :: i,j,n
      integer*1, intent(inout) :: k(j)
      character test*100
      test=''
      do 1 m=1,j
      test(m:m)=char(k(m))
    1 continue
      n=22
      i=16
      open (unit=10,file='testchr.txt',status='unknown',
     cform='formatted')
      write (10,2) trim(test)
    2 format (a)
      close (unit=10)

      end subroutine
</code>```

The arguments n and j are just for demonstration purposes.  Argument j is input and represents the length of the string (i.e. the number of elements in the Integer*1 (byte) array k.  The byte array is reconstructed as a text string and written to a file.

The calling VB code is:

```<code>    Module Module0
        '
        ' test passing integers and character string via byte array
        'j=length of character string (i.e. n will have j elements 0 to j-1)
        'i and kk are just some dummy test arguments
        Declare Auto Sub intmul Lib "D:\test\vb-fortan\dlls\intandarraychr\bin\Debug\fd1.dll" Alias _
          "intmul_" (ByRef i As Int32, ByRef j As Int32, ByVal n() As Byte, ByRef kk As Int32)
    End Module

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        End
    End Sub

        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim i, j, k As Int32
            Dim m(100) As Byte
            Dim testtext As String
            testtext = TextBox4.Text
            i = TextBox3.Text
            j = testtext.Length   'length of string ==> number of elements in byte array to pass
            k = TextBox5.Text
            '  Convert unicode text (2 bytes/character) to byte array with each element
            'of the array containing the code for each character
            m = System.Text.Encoding.ASCII.GetBytes(testtext)

            MsgBox("proceed")
            Call intmul(i, j, m, k)
            TextBox3.Text = i
            TextBox5.Text = k
        End Sub

    End Class
</code>```

Note: VB code was compiled using the "Any CPU" platform setting.
Note the array is passed "byval" --- I noticed even though I specified STDCALL when I tried to pass an array byref the address of the address of the array was pushed to the stack rather than the address of the array.  If I pass byval the address of the array is pushed to the stack which is what I thought was proper STDCALL..???  Anyway passing an array byval has the same effect as passing byref.

As to determining the dependencies in the fortran dll -- my solution, albeit brute force, is to copy ALL the dlls within the gfortran folders to a folder on another machine without any of the development tools and which contains the necessary files for the VB code itself.  Run the code that calls the fortran dll of interest.   Then examine the last access date/time of the all the dll's to see which have been accessed.  If it wasn't accessed then you don't need it...this is an alternative to wading through the output of Dependency Walker.
Hope this helps save someone the amount of time I spent running this to ground.

Body:
I have a DLL written in fortran that I know works because I am getting it from a working software package that we use daily.  I am trying to call it from anything but am having problems i believe with passing the correctly formatted arguments in and out of it, so i decided to try and access it from a VB program.  I chose VB because I have contacted the developer of the software package we are using and he gave me his DLL function call in VB6, even though he is not allowed to show me the FORTRAN source.

Problem is (perhaps, i think) that I am writing in VB.NET, which has different data types than VB6.  Can anyone see why i am am having problems.

The error i get upon running is: "AccessViolationException was unhandled: Attempted to read or write protected memory. This is often an indication that other memory is corrupt."

Here is the function call i was supplied with:

Declare Sub FCC_Curves Lib "FCC_Curves.dll" (Read_Flag As Boolean, First_Flag As Boolean, Frequency_MHz As Single, IQT As Integer,  ByVal Radiation_Opt As String, ByVal L1 As Long,  ERP_Watts As Single, T_PowerWatts As Single, Tx_GaindBi As Single, T_Loss As Single, ByVal Service As String, ByVal L2 As Long, Reliability As Integer, ByVal FCC_CurvesDataPath As String, ByVal L3 As Long,  ByVal TerrainRoughness As String, ByVal L4 As Long, Haatm As Single, NPRfl As Integer, NFCCCurve As Integer, HPRfl As Single,  Crve As Single, FCC_Loss As Single, Code As Integer, FS As Single)

and here is my code:

Module Module1

    Declare Sub FCC_Curves Lib "FCC_Curves.dll" (ByVal Read_Flag As Boolean, ByVal First_Flag As Boolean, ByVal Frequency_MHz As Single, ByVal IQT As Int16, ByVal Radiation_Opt As String, ByVal L1 As Int32, ByVal ERP_Watts As Single, ByVal T_PowerWatts As Single, ByVal Tx_GaindBi As Single, ByVal T_Loss As Single, ByVal Service As String, ByVal L2 As Int32, ByVal Reliability As Int16, ByVal FCC_CurvesDataPath As String, ByVal L3 As Int32, ByVal TerrainRoughness As String, ByVal L4 As Int32, ByVal Haatm As Single, ByVal NPRfl As Int16, ByVal NFCCCurve As Int16, ByVal HPRfl() As Single, ByVal Crve() As Single, ByRef FCC_Loss As Single, ByRef Code As Int16, ByRef FS() As Single)

    Sub Main()

        Dim Read_Flag As Boolean
        Dim First_Flag As Boolean
        Dim Frequency_MHz As Single
        Dim IQT As Int16
        Dim Radiation_Opt As String
        Dim L1 As Int32
        Dim ERP_Watts As Single
        Dim T_PowerWatts As Single
        Dim Tx_GaindBi As Single
        Dim T_Loss As Single
        Dim Service As String
        Dim L2 As Int32
        Dim Reliability As Int16
        Dim FCC_CurvesDataPath As String
        Dim L3 As Int32
        Dim TerrainRoughness As String
        Dim L4 As Int32
        Dim Haatm As Single
        Dim NPRfl As Int16
        Dim NFCCCurve As Int16
        Dim HPRfl(12) As Single
        Dim Crve(5) As Single
        Dim FCC_Loss As Single
        Dim Code As Int16
        Dim FS(15) As Single
        'Dim HPRfl As Single
        'Dim Crve As Single
        'Dim FCC_Loss As Single
        'Dim Code As Int16
        'Dim FS As Single

        Read_Flag = True
        First_Flag = True
        Frequency_MHz = 98.1
        IQT = 0
        Radiation_Opt = "ERP"
        L1 = 3
        ERP_Watts = 1000
        T_PowerWatts = 1000
        Tx_GaindBi = 2.15
        T_Loss = 0
        Service = "Broadcast"
        L2 = 9
        Reliability = 50
        FCC_CurvesDataPath = "C:\Program Files\CSPT_Extension\data\"
        L3 = 37
        TerrainRoughness = "Off"
        L4 = 3
        Haatm = 1500
        NPRfl = 13
        NFCCCurve = 6
        Dim i As Int16
        HPRfl(0) = 11
        HPRfl(1) = 128
        For i = 2 To 12
            HPRfl(i) = 1500
        Next
        For i = 0 To 5
            Crve(i) = i * 15
        Next

        FCC_Curves(Read_Flag, First_Flag, Frequency_MHz, IQT, Radiation_Opt, L1, ERP_Watts, T_PowerWatts, Tx_GaindBi, T_Loss, Service, L2, Reliability, FCC_CurvesDataPath, L3, TerrainRoughness, L4, Haatm, NPRfl, NFCCCurve, HPRfl, Crve, FCC_Loss, Code, FS)

    End Sub

End Module

Body:
Thought I'd post my experience passing arguments from VB.net (.net v5, VS 64bit v17.0.5) to dll created with gfortran 7.3.0(in code::blocks).  The example shows  passing integers, a byte array, and a way to handle a character string passing via the byte array.  I'm not a pro-programmer, programming is just a tool for me, so my "programming vernacular" may not be correct.  Note I'm running these codes on a 64bit machine using Windows 10 (64bit).

First, the fortran code for the dll:

  subroutine intmul(i,j,k,n)
!GCC$ ATTRIBUTES STDCALL, DLLEXPORT :: intmul
      integer, intent(inout) :: i,j,n
      integer*1, intent(inout) :: k(j)
      character test*100
      test=''
      do 1 m=1,j
      test(m:m)=char(k(m))
    1 continue
      n=22
      i=16
      open (unit=10,file='testchr.txt',status='unknown',
     cform='formatted')
      write (10,2) trim(test)
    2 format (a)
      close (unit=10)

      end subroutine

The arguments n and j are just for demonstration purposes.  Argument j is input and represents the length of the string (i.e. the number of elements in the Integer*1 (byte) array k.  The byte array is reconstructed as a text string and written to a file.

The calling VB code is:

    Module Module0
        '
        ' test passing integers and character string via byte array
        'j=length of character string (i.e. n will have j elements 0 to j-1)
        'i and kk are just some dummy test arguments
        Declare Auto Sub intmul Lib "D:\test\vb-fortan\dlls\intandarraychr\bin\Debug\fd1.dll" Alias _
          "intmul_" (ByRef i As Int32, ByRef j As Int32, ByVal n() As Byte, ByRef kk As Int32)
    End Module

Public Class Form1
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        End
    End Sub

        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim i, j, k As Int32
            Dim m(100) As Byte
            Dim testtext As String
            testtext = TextBox4.Text
            i = TextBox3.Text
            j = testtext.Length   'length of string ==> number of elements in byte array to pass
            k = TextBox5.Text
            '  Convert unicode text (2 bytes/character) to byte array with each element
            'of the array containing the code for each character
            m = System.Text.Encoding.ASCII.GetBytes(testtext)

            MsgBox("proceed")
            Call intmul(i, j, m, k)
            TextBox3.Text = i
            TextBox5.Text = k
        End Sub

    End Class

Note: VB code was compiled using the "Any CPU" platform setting.
Note the array is passed "byval" --- I noticed even though I specified STDCALL when I tried to pass an array byref the address of the address of the array was pushed to the stack rather than the address of the array.  If I pass byval the address of the array is pushed to the stack which is what I thought was proper STDCALL..???  Anyway passing an array byval has the same effect as passing byref.

As to determining the dependencies in the fortran dll -- my solution, albeit brute force, is to copy ALL the dlls within the gfortran folders to a folder on another machine without any of the development tools and which contains the necessary files for the VB code itself.  Run the code that calls the fortran dll of interest.   Then examine the last access date/time of the all the dll's to see which have been accessed.  If it wasn't accessed then you don't need it...this is an alternative to wading through the output of Dependency Walker.
Hope this helps save someone the amount of time I spent running this to ground.


问:
No module named 'scipy.spatial.transform._rotation_groups after compile python script with pyinstaller
After days of looking for an answer on internet and, of course, in overflow I make this post. I hope someone could help me.
I made a little program that fits some data that I got from chemistry experimentation with a math model using scipy.optimize. Then I got a plot of the points from the data and the fit. When I run it on the IDLE everything goes okay and when I run from windows command, too.
The thing is that a want to make an .exe file so I could share my program with my university classmates. For this I used pyinstaller. When I run pyinstaller to make mi .exe file evertything is ok, but when I want to run it from windows command I get the next output:

```<code>Traceback (most recent call last):
  File "solver_tp2fq_ver2.py", line 9, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\optimize\__init__.py", line 421, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\optimize\_shgo.py", line 9, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\spatial\__init__.py", line 107, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\spatial\transform\__init__.py", line 19, in <module>
  File "rotation.pyx", line 5, in init scipy.spatial.transform.rotation
ModuleNotFoundError: No module named 'scipy.spatial.transform._rotation_groups'
[10152] Failed to execute script solver_tp2fq_ver2
</code>```

As you can see I get the next error:
ModuleNotFoundError: No module named 'scipy.spatial.transform._rotation_groups'

I don't understand why I get this error. I installed all the modules, checked that path is correct, upgraded the modules and also reinstalled python (Because this, actually I'm using python 3.9). I don't know what else I can do.

Well, I think it's all. I will be very thankfull if someone helps me.

答:
I was running my script inside of a virtualenv and ran into this error. I tried --hiddenimports and .spec files with no luck. I decided to just:

run pip freeze > requirements

rm -f venv (This is where I seen this error again)

Pushed the requirements.txt to github.

Pulled from github into a new folder. (so now libraries are no installed yet)

Reinstalled Libraries with pip install -r requirements.txt

For whatever reason the scipy folder was installed wrong and starting from scratch in my virtual environment worked.

Body:
After days of looking for an answer on internet and, of course, in overflow I make this post. I hope someone could help me.
I made a little program that fits some data that I got from chemistry experimentation with a math model using scipy.optimize. Then I got a plot of the points from the data and the fit. When I run it on the IDLE everything goes okay and when I run from windows command, too.
The thing is that a want to make an .exe file so I could share my program with my university classmates. For this I used pyinstaller. When I run pyinstaller to make mi .exe file evertything is ok, but when I want to run it from windows command I get the next output:

Traceback (most recent call last):
  File "solver_tp2fq_ver2.py", line 9, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\optimize\__init__.py", line 421, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\optimize\_shgo.py", line 9, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\spatial\__init__.py", line 107, in <module>
  File "c:\users\lenovo\appdata\local\programs\python\python39\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 493, in exec_module
    exec(bytecode, module.__dict__)
  File "scipy\spatial\transform\__init__.py", line 19, in <module>
  File "rotation.pyx", line 5, in init scipy.spatial.transform.rotation
ModuleNotFoundError: No module named 'scipy.spatial.transform._rotation_groups'
[10152] Failed to execute script solver_tp2fq_ver2

As you can see I get the next error:
ModuleNotFoundError: No module named 'scipy.spatial.transform._rotation_groups'

I don't understand why I get this error. I installed all the modules, checked that path is correct, upgraded the modules and also reinstalled python (Because this, actually I'm using python 3.9). I don't know what else I can do.

Well, I think it's all. I will be very thankfull if someone helps me.


问:
Snapping Effect in HorizontalScrollView
I want to achieve Snapping effect in HorizontalScrollView i.e when the user scrolls horizontally the item which is most visible (item visible > 50%) comes to the center.

I tried to do this using:

```<code>hsv.getViewTreeObserver().addOnScrollChangedListener(
    new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollX = hsv.getScrollX(); // For HorizontalScrollView
            Log.e("scrollX",String.valueOf(scrollX));
            // DO SOMETHING WITH THE SCROLL COORDINATES
        }
    }
);
</code>```

But the value is not constant even when we do not touch the screen.

Here is some part of logcat:

```<code>03-28 11:11:22.116 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.133 26639-26639/package_name E/scrollX: 792
03-28 11:11:22.133 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.151 26639-26639/package_name E/scrollX: 795
03-28 11:11:22.151 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.166 26639-26639/package_name E/scrollX: 799
03-28 11:11:22.166 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.183 26639-26639/package_name E/scrollX: 801
03-28 11:11:22.183 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.199 26639-26639/package_name E/scrollX: 803
03-28 11:11:22.199 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.216 26639-26639/package_name E/scrollX: 804
03-28 11:11:22.216 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.233 26639-26639/package_name E/scrollX: 805
03-28 11:11:22.233 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.249 26639-26639/package_name E/scrollX: 806
03-28 11:11:22.249 26639-26639/package_name E/scrollX: 0
</code>```

I've already tried these solutions, either I am not getting the point or I don't know to do it:

HorizontalScrollView within ScrollView Touch Handling

HorizontalScrollView with snapping effect

Creating Custom Horizontal Scroll View With Snap or paging

Creating a “Snapping” Horizontal Scroll View

My Usecase:
I have an HorizontalScrollView which is attached to the adapter of Recyclerview(Vertical) so snapHelper can be done in vertical but I don't know how to make it for horizontal.

答:
Building on the answer from @AdibFaramarzi, here is a version where you create the inner LinearLayout yourself and add / remove items dynamically:

```<code>import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class SnapHorizontalScrollView extends HorizontalScrollView {
    private static final int SWIPE_MIN_DISTANCE = 5;
    private static final int SWIPE_THRESHOLD_VELOCITY = 300;

    private final ArrayList<LinearLayout> mItems = new ArrayList<>();
    private GestureDetector mGestureDetector;
    private int mActiveFeature = 0;

    public SnapHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SnapHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SnapHorizontalScrollView(Context context) {
        super(context);
    }

    public void removeFeatureItem(LinearLayout featureLayout) {
        this.mItems.remove(featureLayout);
    }

    @SuppressLint("ClickableViewAccessibility")
    public void addFeatureItem(LinearLayout featureLayout) {
        this.mItems.add(featureLayout);
        setOnTouchListener((v, event) -> {
            //If the user swipes
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            }
            else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
                int scrollX = getScrollX();
                int featureWidth = v.getMeasuredWidth();
                mActiveFeature = ((scrollX + (featureWidth / 2)) / featureWidth);
                int scrollTo = mActiveFeature * featureWidth;
                smoothScrollTo(scrollTo, 0);
                return true;
            }
            else{
                return false;
            }
        });
        mGestureDetector = new GestureDetector(new MyGestureDetector());
    }
    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                // right to left
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = getMeasuredWidth();
                    mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
                    smoothScrollTo(mActiveFeature*featureWidth, 0);
                    return true;
                }
                // left to right
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = getMeasuredWidth();
                    mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
                    smoothScrollTo(mActiveFeature * featureWidth, 0);
                    return true;
                }
            } catch (Exception e) {
                Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
            }
            return false;
        }
    }
}
</code>```

In XML, this would be implemented in place of the HorizontalScrollView and then the usual LinearLayout would be placed inside it. For the following, we will assume that you set internalWrapper as the variable for the inner LinearLayout.

When adding an item to the LinearLayout, follow the internalWrapper.addView(layout) with snapScroller.addFeatureItem(layout) and similarly follow the internalWrapper.removeView(layout) with snapScroller.removeFeatureItem(layout)

Title: Snapping Effect in HorizontalScrollView

Body:
I want to achieve Snapping effect in HorizontalScrollView i.e when the user scrolls horizontally the item which is most visible (item visible > 50%) comes to the center.

I tried to do this using:

hsv.getViewTreeObserver().addOnScrollChangedListener(
    new ViewTreeObserver.OnScrollChangedListener() {
        @Override
        public void onScrollChanged() {
            int scrollX = hsv.getScrollX(); // For HorizontalScrollView
            Log.e("scrollX",String.valueOf(scrollX));
            // DO SOMETHING WITH THE SCROLL COORDINATES
        }
    }
);

But the value is not constant even when we do not touch the screen.

Here is some part of logcat:

03-28 11:11:22.116 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.133 26639-26639/package_name E/scrollX: 792
03-28 11:11:22.133 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.151 26639-26639/package_name E/scrollX: 795
03-28 11:11:22.151 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.166 26639-26639/package_name E/scrollX: 799
03-28 11:11:22.166 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.183 26639-26639/package_name E/scrollX: 801
03-28 11:11:22.183 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.199 26639-26639/package_name E/scrollX: 803
03-28 11:11:22.199 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.216 26639-26639/package_name E/scrollX: 804
03-28 11:11:22.216 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.233 26639-26639/package_name E/scrollX: 805
03-28 11:11:22.233 26639-26639/package_name E/scrollX: 0
03-28 11:11:22.249 26639-26639/package_name E/scrollX: 806
03-28 11:11:22.249 26639-26639/package_name E/scrollX: 0

I've already tried these solutions, either I am not getting the point or I don't know to do it:

HorizontalScrollView within ScrollView Touch Handling

HorizontalScrollView with snapping effect

Creating Custom Horizontal Scroll View With Snap or paging

Creating a “Snapping” Horizontal Scroll View

My Usecase:
I have an HorizontalScrollView which is attached to the adapter of Recyclerview(Vertical) so snapHelper can be done in vertical but I don't know how to make it for horizontal.

Body:
Building on the answer from @AdibFaramarzi, here is a version where you create the inner LinearLayout yourself and add / remove items dynamically:

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;

import java.util.ArrayList;

public class SnapHorizontalScrollView extends HorizontalScrollView {
    private static final int SWIPE_MIN_DISTANCE = 5;
    private static final int SWIPE_THRESHOLD_VELOCITY = 300;

    private final ArrayList<LinearLayout> mItems = new ArrayList<>();
    private GestureDetector mGestureDetector;
    private int mActiveFeature = 0;

    public SnapHorizontalScrollView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SnapHorizontalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SnapHorizontalScrollView(Context context) {
        super(context);
    }

    public void removeFeatureItem(LinearLayout featureLayout) {
        this.mItems.remove(featureLayout);
    }

    @SuppressLint("ClickableViewAccessibility")
    public void addFeatureItem(LinearLayout featureLayout) {
        this.mItems.add(featureLayout);
        setOnTouchListener((v, event) -> {
            //If the user swipes
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            }
            else if (event.getAction() == MotionEvent.ACTION_UP || event.getAction() == MotionEvent.ACTION_CANCEL ){
                int scrollX = getScrollX();
                int featureWidth = v.getMeasuredWidth();
                mActiveFeature = ((scrollX + (featureWidth / 2)) / featureWidth);
                int scrollTo = mActiveFeature * featureWidth;
                smoothScrollTo(scrollTo, 0);
                return true;
            }
            else{
                return false;
            }
        });
        mGestureDetector = new GestureDetector(new MyGestureDetector());
    }
    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                // right to left
                if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = getMeasuredWidth();
                    mActiveFeature = (mActiveFeature < (mItems.size() - 1))? mActiveFeature + 1:mItems.size() -1;
                    smoothScrollTo(mActiveFeature*featureWidth, 0);
                    return true;
                }
                // left to right
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    int featureWidth = getMeasuredWidth();
                    mActiveFeature = (mActiveFeature > 0)? mActiveFeature - 1:0;
                    smoothScrollTo(mActiveFeature * featureWidth, 0);
                    return true;
                }
            } catch (Exception e) {
                Log.e("Fling", "There was an error processing the Fling event:" + e.getMessage());
            }
            return false;
        }
    }
}

In XML, this would be implemented in place of the HorizontalScrollView and then the usual LinearLayout would be placed inside it. For the following, we will assume that you set internalWrapper as the variable for the inner LinearLayout.

When adding an item to the LinearLayout, follow the internalWrapper.addView(layout) with snapScroller.addFeatureItem(layout) and similarly follow the internalWrapper.removeView(layout) with snapScroller.removeFeatureItem(layout)


问:
exchanging data between web application and individual process
SERVER SIDE
a 24-hour running linux program (say A): processes and holds data
web server: handles web request

CLIENT SIDE(browser)
request http://mydomain.com/getdata to get the data

for each web request, the web server(or web application running on it) should ask program A for the latest data

is there any framework can help me build such a architecture quickly?
thank you!

答:
The LAMP Stack will give you what you want.  LAMP = Linux, Apache, MySQL and PHP.

It is widely used for applications that match your needs, and is supported by a large active community.

You should have no problem finding good tutorials that help you get the platform established, once that's done all you need to do is go looking for tutorials on how to develop PHP websites that include database access.

With PHP there's lots of open source Content Management Systems that might give you what you need (such as Drupal) and in terms of PHP frameworks there's stuff like the Zend Framework.


问:
How does Kotlin's `lazy` implementation work without getValue and setValue?
In Kotlin properties with pre-set custom get/set behavior are implemented using delegated properties. According to the doc, a delegate for a property is just a class with getValue and setValue methods

But when I looked inside the implementation of lazy, I only found value property. So I tried to implement a delegate this way myself. It failed to compile, because getValue and setValue were not implemented explicitly. How does the official implementation of lazy work then?

答:
getValue is declared as an extension function (yes that works too!) on all Lazy<T>s:

Source:

```<code>public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value
</code>```

As you can see, it returns value, which is exactly what you would expect.

There is no setValue, and that is fine. That just means you can't use lazy { ... } as a property delegate for a var, and you indeed cannot:

```<code>var foo by lazy { 10 } // compiler error
</code>```

After all, this doesn't make much sense anyway.

Body:
getValue is declared as an extension function (yes that works too!) on all Lazy<T>s:

Source:

public inline operator fun <T> Lazy<T>.getValue(thisRef: Any?, property: KProperty<*>): T = value

As you can see, it returns value, which is exactly what you would expect.

There is no setValue, and that is fine. That just means you can't use lazy { ... } as a property delegate for a var, and you indeed cannot:

var foo by lazy { 10 } // compiler error

After all, this doesn't make much sense anyway.


问:
Cloudwatch Logs config: timestamp_format match
i am missing the part in the AWS docs where it is described how the timestamp_format is evaluated within a given line.

Here i have a sample log line:

```<code>[4138] 2021/07/19 15:20:57.996872 [INF] Listening for client connections on ...
</code>```

As you can see the datetime info is located in the second column. Does Cloudwatch automagically match the configured timestamp_format pattern within the complete line or does it always assume that the datetime column needs to be in the first column?
How can i tell Cloudwatch Agent to use the second column for timestamp_format matching?

答:
From experience, it will find the first timestamp that matches timestamp_format. From what I've read the documentation is a little ambiguous. There are two statements in the documentation that seem to validate this claim.

Under the timestamp_format bullet there is the statement:

```<code>If a single log entry contains two time stamps that match the format, the first time stamp is used.
</code>```

That indicates to me it is looking through the entire log entry for a match, not just parsing the first date field.

Under the multi_line_start_pattern bullet there is the statement:

```<code>If you include this field, you can specify {timestamp_format} to use the same regular expression as your timestamp format. Otherwise, you can specify a different regular expression for CloudWatch Logs to use to determine the start lines of multi-line entries.
</code>```

That indicates to me again timestamp_format used to do pattern matching across the entire log entry.

Body:
i am missing the part in the AWS docs where it is described how the timestamp_format is evaluated within a given line.

Here i have a sample log line:

[4138] 2021/07/19 15:20:57.996872 [INF] Listening for client connections on ...

As you can see the datetime info is located in the second column. Does Cloudwatch automagically match the configured timestamp_format pattern within the complete line or does it always assume that the datetime column needs to be in the first column?
How can i tell Cloudwatch Agent to use the second column for timestamp_format matching?

Body:
From experience, it will find the first timestamp that matches timestamp_format. From what I've read the documentation is a little ambiguous. There are two statements in the documentation that seem to validate this claim.

Under the timestamp_format bullet there is the statement:

If a single log entry contains two time stamps that match the format, the first time stamp is used.

That indicates to me it is looking through the entire log entry for a match, not just parsing the first date field.

Under the multi_line_start_pattern bullet there is the statement:

If you include this field, you can specify {timestamp_format} to use the same regular expression as your timestamp format. Otherwise, you can specify a different regular expression for CloudWatch Logs to use to determine the start lines of multi-line entries.

That indicates to me again timestamp_format used to do pattern matching across the entire log entry.


问:
Nested div is not respecting border on safari 9 only
I am using flex to separate some divs horizontally and it looks fine in every other browser including IE, but for some reason it is not working on Safari. I am using Safari 9.0.3 on El Capitan. Below is a code.

HTML

```<code><div class="grid-box">
 <div class="display-price">
  <div class="saleprice-wrap">
   <div id="saleprice">
    <span style="color: rgb(51, 51, 51);">$4.49</span>
   </div>
  </div>
  <div id="sellprice" style="display: none;">$4.49</div>
 </div>
 <div class="info-wrapper">
  <div class="type">Vinyl Sticker</div>
  <div class="stock-status">
   <div>
    <h5>In stock</h5>
   </div>
  </div>
 </div>
 <div class="qty-wrapper">
  <div class="form-qty">
   <span class="label">Quantity:</span>
   <input id="input_qty" type="tel" maxlength="3" class="textinput" value="1">
  </div>
  <div class="a2c">
   <a id="" rel="nofollow" title="Add to Cart" class="" style="display: block;">Add to Cart</a>
  </div>
 </div>
</div>
</code>```

CSS

```<code>.grid-box{
  padding: 12px 30px;
  margin: 0;
  background: #add8e6;
  display: flex;
  z-index: 1
}

.display-price{
  padding: 20px 15px 20px 0;
  border-right: solid 1px #999;
  align-self: center;
  text-align: center
 }

.saleprice-wrap, #sellprice {
  display: inline-block;
  font-size: 1.6em
}

#saleprice span{
  font-size: 1.6em;
  margin-right: 2px
}

.info-wrapper{
  align-self: center;
  width: 100%;
  padding-left: 20px
}

.qty-wrapper{
  margin-bottom: .5em;
  text-align: center;
  padding-left: 10px
}

.form-qty{
  display: inline-block;
  font-size: 15px;
  margin-bottom: 10px
}

.a2c{
  width: 160px;
  display: inline-block
}
</code>```

Here is the codepen as well http://codepen.io/sinake/full/mPMzzm/

When loading the pen in chrome, firefox, or IE the price is shown correctly with the border to the right but in Safari or other iOS devices the price overlaps the border. I have tried playing around with the display etc but to no avail. Any ideas? Thanks in advance.

答: Safari has updated over the years since this question was asked. I just checked the codepen link in Safari 13 and the issue is no longer happening. Closing this out.</p>

Body:
I am using flex to separate some divs horizontally and it looks fine in every other browser including IE, but for some reason it is not working on Safari. I am using Safari 9.0.3 on El Capitan. Below is a code.

HTML

    $4.49

$4.49

Vinyl Sticker

In stock

   Quantity:
   <input id="input_qty" type="tel" maxlength="3" class="textinput" value="1">

   Add to Cart

CSS

.grid-box{
  padding: 12px 30px;
  margin: 0;
  background: #add8e6;
  display: flex;
  z-index: 1
}

.display-price{
  padding: 20px 15px 20px 0;
  border-right: solid 1px #999;
  align-self: center;
  text-align: center
 }

.saleprice-wrap, #sellprice {
  display: inline-block;
  font-size: 1.6em
}

#saleprice span{
  font-size: 1.6em;
  margin-right: 2px
}

.info-wrapper{
  align-self: center;
  width: 100%;
  padding-left: 20px
}

.qty-wrapper{
  margin-bottom: .5em;
  text-align: center;
  padding-left: 10px
}

.form-qty{
  display: inline-block;
  font-size: 15px;
  margin-bottom: 10px
}

.a2c{
  width: 160px;
  display: inline-block
}

Here is the codepen as well http://codepen.io/sinake/full/mPMzzm/

When loading the pen in chrome, firefox, or IE the price is shown correctly with the border to the right but in Safari or other iOS devices the price overlaps the border. I have tried playing around with the display etc but to no avail. Any ideas? Thanks in advance.