text:
Q: Connecting to Websocket Via PHP - Server did not accept to upgrade connection I have the following code, this was previously working and now all of a sudden I am getting an error;
The error I am getting is;
Failed to connect to server Server responed with: Server did not accept to upgrade connection to websocket.HTTP/1.1 200 OK Date: Sun, 22 Aug 2021 01:07:27 GMT Content-Type: text/html Transfer-Encoding: chunked Connection: keep-alive Last-Modified: Fri, 05 Mar 2021 07:33:32 GMT X-By: @XRPLF X-Upgrade: WebSocket X-Conn: upgrade CF-Cache-Status: DYNAMIC Expect-CT: max-age=604800, report-uri="https://report-uri.cloudflare.com/cdn-cgi/beacon/expect-ct" Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v3?s=ahbUvdpOxo1wZb%2B54qo5pEWE0KGc%2BTpWu2vgw47WhbCgjbfPwdQOGLCAZlivJyijhHs4PTt4nYVIW3ak%2BwAtlz6qhz36saYBmLZ3%2FyKJc8ZB6OJA0%2FNVp14%3D"}],"group":"cf-nel","max_age":604800} NEL: {"success_fraction":0,"report_to":"cf-nel","max_age":604800} Server: cloudflare CF-RAY: 682834517edc2ce3-LHR alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400, h3=":443"; ma=86400 6980

I am not too sure what is causing it below is the code;
<?php

    include('/websocket_client.php');

    $server = 'xrpl.ws';

    $command = json_encode(array(
        'id' => 2,
        'command' => "server_info"

    ));

    if( $sp = websocket_open($server, 443,'',$errstr, 10, true) ) {
      websocket_write($sp,$command);
      $result = websocket_read($sp,$errstr);
    }else {
      echo "Failed to connect to server\n";
      echo "Server responed with: $errstr\n";
    }

    $result_data = json_decode($result, true);

    echo '<pre>';
    echo $result_data;
    echo '</pre>';
?>

Below is the Websocket_Client.php page I am sorry for the length ; But I thought it might be important to include it all.
<?php
/*----------------------------------------------------------------------------*\
  Websocket client - https://github.com/paragi/PHP-websocket-client
  By Paragi 2013, Simon Riget MIT license.
  This is a demonstration of a websocket clinet.
  If you find flaws in it, please let me know at simon.riget (at) gmail
  Websockets use hybi10 frame encoding:
        0                   1                   2                   3
        0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
       +-+-+-+-+-------+-+-------------+-------------------------------+
       |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
       |I|S|S|S|  (4)  |A|     (7)     |             (16/63)           |
       |N|V|V|V|       |S|             |   (if payload len==126/127)   |
       | |1|2|3|       |K|             |                               |
       +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
       |     Extended payload length continued, if payload len == 127  |
       + - - - - - - - - - - - - - - - +-------------------------------+
       |                               |Masking-key, if MASK set to 1  |
       +-------------------------------+-------------------------------+
       | Masking-key (continued)       |          Payload Data         |
       +-------------------------------- - - - - - - - - - - - - - - - +
       :                     Payload Data continued ...                :
       + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
       |                     Payload Data continued ...                |
       +---------------------------------------------------------------+
  See: https://tools.ietf.org/rfc/rfc6455.txt
  or:  http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-10#section-4.2
\*----------------------------------------------------------------------------*/

/*============================================================================*\
  Open websocket connection
  resource websocket_open(string $host [,int $port [,$additional_headers [,string &error_string ,[, int $timeout]]]]
  host
    A host URL. It can be a domain name like www.example.com or an IP address,
    with port number. Local host example: 127.0.0.1:8080
  port
  headers (optional)
    additional HTTP headers to attach to the request.
    For example to parse a session cookie: "Cookie: SID=" . session_id()
  error_string (optional)
    A referenced variable to store error messages, i any
  timeout (optional)
    The maximum time in seconds, a read operation will wait for an answer from
    the server. Default value is 10 seconds.
  ssl (optional)
  persistant (optional)
  path (optional)
  Context (optional)
  Open a websocket connection by initiating a HTTP GET, with an upgrade request
  to websocket.
  If the server accepts, it sends a 101 response header, containing
  "Sec-WebSocket-Accept"
\*============================================================================*/
function websocket_open($host='',$port=80,$headers='',&$error_string='',$timeout=10,$ssl=false, $persistant = false, $path = '/', $context = null){

  // Generate a key (to convince server that the update is not random)
  // The key is for the server to prove it i websocket aware. (We know it is)
  $key=base64_encode(openssl_random_pseudo_bytes(16));

  $header = "GET " . $path . " HTTP/1.1\r\n"
    ."Host: $host\r\n"
    ."pragma: no-cache\r\n"
    ."Upgrade: WebSocket\r\n"
    ."Connection: Upgrade\r\n"
    ."Sec-WebSocket-Key: $key\r\n"
    ."Sec-WebSocket-Version: 13\r\n";

  // Add extra headers
  if(!empty($headers)) foreach($headers as $h) $header.=$h."\r\n";

  // Add end of header marker
  $header.="\r\n";

  // Connect to server
  $host = $host ? $host : "127.0.0.1";
  $port = $port <1 ? ( $ssl ? 443 : 80 ): $port;
  $address = ($ssl ? 'ssl://' : '') . $host . ':' . $port;

  $flags = STREAM_CLIENT_CONNECT | ( $persistant ? STREAM_CLIENT_PERSISTENT : 0 );
  $ctx = $context ?? stream_context_create();
  $sp = stream_socket_client($address, $errno, $errstr, $timeout, $flags, $ctx);

  if(!$sp){
    $error_string = "Unable to connect to websocket server: $errstr ($errno)";
    return false;
  }

  // Set timeouts
  stream_set_timeout($sp,$timeout);

  if (!$persistant or ftell($sp) === 0) {

    //Request upgrade to websocket
    $rc = fwrite($sp,$header);
    if(!$rc){
      $error_string
        = "Unable to send upgrade header to websocket server: $errstr ($errno)";
      return false;
    }

    // Read response into an assotiative array of headers. Fails if upgrade failes.
    $reaponse_header=fread($sp, 1024);

    // status code 101 indicates that the WebSocket handshake has completed.
    if (stripos($reaponse_header, ' 101 ') === false
      || stripos($reaponse_header, 'Sec-WebSocket-Accept: ') === false) {
      $error_string = "Server did not accept to upgrade connection to websocket."
        .$reaponse_header. E_USER_ERROR;
      return false;
    }
    // The key we send is returned, concatenate with "258EAFA5-E914-47DA-95CA-
    // C5AB0DC85B11" and then base64-encoded. one can verify if one feels the need...

  }
  return $sp;
}

/*============================================================================*\
  Write to websocket
  int websocket_write(resource $handle, string $data ,[boolean $final])
  Write a chunk of data through the websocket, using hybi10 frame encoding
  handle
    the resource handle returned by websocket_open, if successful
  data
    Data to transport to server
  final (optional)
    indicate if this block is the final data block of this request. Default true
  binary (optional)
    indicate if this block is sent in binary or text mode.  Default true/binary
\*============================================================================*/
function websocket_write($sp,$data,$final=true,$binary=true){
  // Assemble header: FINal 0x80 | Mode (0x02 binary, 0x01 text)

  if ($binary)
      $header=chr(($final?0x80:0) | 0x02); // 0x02 binary mode
  else
      $header=chr(($final?0x80:0) | 0x01); // 0x01 text mode

  // Mask 0x80 | payload length (0-125)
  if(strlen($data)<126) $header.=chr(0x80 | strlen($data));
  elseif (strlen($data)<0xFFFF) $header.=chr(0x80 | 126) . pack("n",strlen($data));
  else $header.=chr(0x80 | 127) . pack("N",0) . pack("N",strlen($data));

  // Add mask
  $mask=pack("N",rand(1,0x7FFFFFFF));
  $header.=$mask;

  // Mask application data.
  for($i = 0; $i < strlen($data); $i++)
    $data[$i]=chr(ord($data[$i]) ^ ord($mask[$i % 4]));

  return fwrite($sp,$header.$data);
}

/*============================================================================*\
  Read from websocket
  string websocket_read(resource $handle [,string &error_string])
  read a chunk of data from the server, using hybi10 frame encoding
  handle
    the resource handle returned by websocket_open, if successful
  error_string (optional)
    A referenced variable to store error messages, i any
  Read
  Note:
    - This implementation waits for the final chunk of data, before returning.
    - Reading data while handling/ignoring other kind of packages
 \*============================================================================*/
function websocket_read($sp,&$error_string=NULL){
  $data="";

  do{
    // Read header
    $header=fread($sp,2);
    if(!$header){
      $error_string = "Reading header from websocket failed.";
      return false;
    }

    $opcode = ord($header[0]) & 0x0F;
    $final = ord($header[0]) & 0x80;
    $masked = ord($header[1]) & 0x80;
    $payload_len = ord($header[1]) & 0x7F;

    // Get payload length extensions
    $ext_len = 0;
    if($payload_len >= 0x7E){
      $ext_len = 2;
      if($payload_len == 0x7F) $ext_len = 8;
      $header=fread($sp,$ext_len);
      if(!$header){
        $error_string = "Reading header extension from websocket failed.";
        return false;
      }

      // Set extented paylod length
      $payload_len= 0;
      for($i=0;$i<$ext_len;$i++)
        $payload_len += ord($header[$i]) << ($ext_len-$i-1)*8;
    }

    // Get Mask key
    if($masked){
      $mask=fread($sp,4);
      if(!$mask){
        $error_string = "Reading header mask from websocket failed.";
        return false;
      }
    }

    // Get payload
    $frame_data='';
    while($payload_len>0){
      $frame= fread($sp,$payload_len);
      if(!$frame){
        $error_string = "Reading from websocket failed.";
        return false;
      }
      $payload_len -= strlen($frame);
      $frame_data.=$frame;
    }

    // Handle ping requests (sort of) send pong and continue to read
    if($opcode == 9){
      // Assamble header: FINal 0x80 | Opcode 0x0A + Mask on 0x80 with zero payload
      fwrite($sp,chr(0x8A) . chr(0x80) . pack("N", rand(1,0x7FFFFFFF)));
      continue;

    // Close
    } elseif($opcode == 8){
      fclose($sp);

    // 0 = continuation frame, 1 = text frame, 2 = binary frame
    }elseif($opcode < 3){
      // Unmask data
      $data_len=strlen($frame_data);
      if($masked)
        for ($i = 0; $i < $data_len; $i++)
          $data.= $frame_data[$i] ^ $mask[$i % 4];
      else
        $data.= $frame_data;

    }else
      continue;

  }while(!$final);

  return $data;
}
?>

I thought initially I had been blacklisted or something for the amount of requests I was making and the fact that it in the message I saw something about CloudFlare but I used a VPN to navigate to xrpl.ws via the IP of the host and I was able to access this without problems. I have not made any changes to the PHP ini file either so I really am stuck to what is causing this. Thanks for any help and sorry for the length of the examples. Thanks again.
I did see this previous answer which mentioned about the way the key is generated but I looked into it and I believe its using a good generation method. So I really am at a loss.

A: The error message is pretty clear:
Server did not accept to upgrade connection to websocket.

You'd need Ratchet, because there likely is no web-socket support available on this server.
Or it may send out unexpected HTTP headers.


text:
Q: How do I use Guice Persist (Guice 3.0) with Wicket 1.5? I want to find out how to use Guice Persist (Guice 3.0) with Wicket 1.5.
I have not been able to find any 'hello world' type examples explaining how to do this, if you can link/provide such an example that would be great, and happily accepted as an answer.
In the meantime I'll be trying to create a 'hello world' type example myself, posting the code here as I progress. Help with making my code function properly will also be accepted as an answer.

I have set up a simple wicket project, very similar to the 'hello world' guice example from Wicket Examples, that uses guice for dependency injection. I now want to extend this project to also use JPA and Guice Persist, instead of "Hello World" I want to fetch a User from the database and display its username. I'm trying to achieve this using the instructions from the Guice wiki about Guice persist.
UPDATE: So, I kinda got it working. In WebApplication.init() I injected a ServetModule like this getComponentInstantiationListeners().add(new GuiceComponentInjector(this, new MyServletModule())); and I also added GuiceFilter at the top of the web.xml file, before wickets filter.
Now when I run the application everything works, but I get this warning about using deprecated methods. Will look into this further.

WARNING: You are attempting to use a deprecated API (specifically,
  attempting to @Inject ServletContext inside an eagerly created
  singleton. While we allow this for backwards compatibility, be warned
  that this MAY have unexpected behavior if you have more than one
  injector (with ServletModule) running in the same JVM. Please consult
  the Guice documentation at
  http://code.google.com/p/google-guice/wiki/Servlets for more
  information.

Directory tree
.
├── pom.xml
└── src
    └── main
        ├── java
        │   └── se
        │       └── lil
        │           ├── HomePage.html
        │           ├── HomePage.java
        │           ├── MyServletModule.java
        │           ├── WicketApplication.java
        │           ├── domain
        │           │   └── User.java
        │           └── service
        │               ├── IService.java
        │               └── JpaService.java
        ├── resources
        │   ├── META-INF
        │   │   └── persistence.xml
        │   └── log4j.properties
        └── webapp
            └── WEB-INF
                └── web.xml

WicketApplication.java
public class WicketApplication extends WebApplication {
    @Override
    protected void init() {
        super.init();
        getComponentInstantiationListeners().add(new GuiceComponentInjector(this,
                new MyServletModule()));
    }

    @Override
    public Class<? extends Page> getHomePage() {
        return se.lil.HomePage.class;
    }
}

HomePage.java
public class HomePage extends WebPage {
    private static final long serialVersionUID = -918138816287955837L;

    @Inject
    private IService service;

    private IModel<User> model = new LoadableDetachableModel<User>() {
        private static final long serialVersionUID = 1913317225318224531L;

        @Override
        protected User load() {
            return service.getUser();
        }
    };

    public HomePage() {
        setDefaultModel(new CompoundPropertyModel<User>(model));
        add(new Label("name"));
    }
}

HomePage.html
<?xml version="1.0" encoding="UTF-8"?>

<title>Wicket Examples - guice</title>

        Value: name goes here

MyServletModule.java
public class MyServletModule extends ServletModule {
    protected void configureServlets() {
        install(new JpaPersistModule("manager1"));
        filter("/*").through(PersistFilter.class);
    }
}

IService.java
@ImplementedBy(JpaService.class)
public interface IService {
    public User getUser();
}

JpaService.java
public class JpaService implements IService {
    @Inject
    private EntityManager em;

    @Override
    @Transactional
    public User getUser() {
        Query q = em.createQuery("FROM User");
        q.setMaxResults(1);
        User u = (User) q.getSingleResult();
        return u;
    }
}

User.java
@Entity
@Table (name = "users")
public class User {
    private Long id;
    private String name;

    public User() {
    }

    public User(String name) {
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Long getId() {
        return id;
    }
    @SuppressWarnings("unused")
    private void setId(Long id) {
        this.id = id;
    }

    @Basic
    @Column(name = "name")
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">

    <display-name>wicketwithguice</display-name>

    <filter>
        <filter-name>guiceFilter</filter-name>
        <filter-class>com.google.inject.servlet.GuiceFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>guiceFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <filter>
        <filter-name>wicket.wicketwithguice</filter-name>
        <filter-class>org.apache.wicket.protocol.http.WicketFilter</filter-class>
        <init-param>
            <param-name>applicationClassName</param-name>
            <param-value>se.lil.WicketApplication</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>wicket.wicketwithguice</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
             version="2.0">
    <persistence-unit name="manager1" transaction-type="RESOURCE_LOCAL">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <class>se.lil.domain.User</class>
        <properties>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
            <property name="hibernate.hbm2ddl.auto" value="validate"/>
            <property name="hibernate.show_sql" value="true"/>

            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/test"/>
            <property name="javax.persistence.jdbc.user" value="test"/>
            <property name="javax.persistence.jdbc.password" value="1234"/>
        </properties>
    </persistence-unit>
</persistence>

pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>se.lil</groupId>
    <artifactId>wicketwithquice</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>

    <name>quickstart</name>
    <description></description>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <hibernate-core.version>3.6.4.Final</hibernate-core.version>
        <mysql-connector-java.version>5.1.16</mysql-connector-java.version>
        <slf4j.version>1.6.1</slf4j.version>
        <log4j.version>1.6.1</log4j.version>
        <guice.version>3.0</guice.version>
        <wicket.version>1.5.2</wicket.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>com.google.inject</groupId>
            <artifactId>guice</artifactId>
            <version>${guice.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-servlet</artifactId>
            <version>${guice.version}</version>
        </dependency>
        <dependency>
            <groupId>com.google.inject.extensions</groupId>
            <artifactId>guice-persist</artifactId>
            <version>${guice.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate-core.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-java.version}</version>
        </dependency>

        <dependency>
            <groupId>org.apache.wicket</groupId>
            <artifactId>wicket-core</artifactId>
            <version>${wicket.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.wicket</groupId>
            <artifactId>wicket-guice</artifactId>
            <version>${wicket.version}</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>1.6</source>
                    <target>1.6</target>
                    <optimize>true</optimize>
                    <debug>true</debug>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.8</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                </configuration>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>Apache Nexus</id>
            <url>https://repository.apache.org/content/repositories/snapshots/</url>
            <releases>
                <enabled>false</enabled>
            </releases>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>
</project>

A: You should have a look on this post and the comments:
http://blog.yanivkessler.com/2010/05/wicket-and-guice-alternate-route.html

A: Wicket 1.5.3 and Guice 3 work. For wicket wicket-ioc, wicket-util and wicket-dev-utils were used besides  wicket core and wicket-guice.Jars were downloaded and created as a library in Netbeans7.0 and added to the web project.

A: As the same message is learnt to be appearing when guice is integrated with shiro, the following mailing-list may be useful
"http://mail-archives.apache.org/mod_mbox/shiro-user/201108.mbox/%3C4E454692.8090806@peachjean.com%3E"

A: When Injector is obtained from ServletContext and added to GuiceComponentInjector no such message appears.The code for AppListener and others furnished here:
package cookbook;

import com.google.inject.persist.jpa.*;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.google.inject.persist.PersistFilter;
public class AppListener extends GuiceServletContextListener{
    @Override
    public Injector getInjector() {
    return Guice.createInjector(
      new  JpaPersistModule("WickGui3PU"  ),
      new ServletModule() {
        @Override
        protected void configureServlets() {

          filter("/*").through(PersistFilter.class);

          bind(BookDAO.class).to (BookDAOImpl.class);
        }
    });
    }
}

Add  in web.xml
<listener>
      <listener-class>cookbook.AppListener</listener-class>
  </listener>

The init() in WicketApplication should be as under:
 protected void init() {
        super.init();

                Injector injector = (Injector)getServletContext().getAttribute(Injector.class.getName());

        getComponentInstantiationListeners().add(new GuiceComponentInjector(this,injector));
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: Random walk on a cube Start a random walk on a vertex of a cube, with equal probability going along the three edges that you can see (to another vertex). what is the expected number of steps to reach the opposite vertex that you start with?

A: It is clear that the expectation is finite. It will be handy to have a cube to play with.
There are $4$ types of vertex: Type A, the vertex we start at; Type B, the ones at distance $1$ from the start; Type C, the ones at distance $2$ from the start; and finally Type D, the vertex opposite from the start.
Let $a$ be the expected number of steps from A to D (this is what we want). Let $b$ be the expected number of (additional) steps to get to D given that we are at a Type B vertex. And let $c$ be the expected number of additional steps given that we are at a Type C vertex.
If we are at A, then with probability $1$, we will be in one step at a Type B vertex, so
$$a=b+1.$$
If we are at a tyoe B vertex, then with probability $\frac{1}{3}$ at the next stage we return to A, and with probability $\frac{2}{3}$ we  go to a Type C vertex. It follows that
$$b=\frac{1}{3}(a+1)+\frac{2}{3}(c+1).$$
Finally, if we are at a Type C vertex, with probability $\frac{2}{3}$ we next go to a Type B, and with probability $\frac{1}{3}$ we get to D. Thus
$$c=\frac{2}{3}(b+1)+\frac{1}{3}.$$
We have three linear equations in $3$ unknowns. Solve for $a$.

A: $\hskip1.75in$
A random  walk on the cube has  eight states, but by symmetry
we can reduce this to four states: start, nearest neighbors, further neighbors, and opposite.
The "boundary" is the single state {o}.

Define $h$ as the expected time to hit the boundary  starting
 at $x$, i.e., $h(x)=\mathbb{E}_x(T).$
First step analysis gives
\begin{eqnarray*}
h(s)&=&1+h(n)\vphantom{1\over3}\\[3pt]
h(n)&=&1+{1\over3}\, h(s)+{2\over 3}\, h(f)\\[3pt]
h(f)&=&1+{1\over3}\, 0+{2\over 3}\, h(n).
\end{eqnarray*}
You can  work out that $h(s)=10$.


text:
Q: Unable to copy in bluestacks I am unable to copy more than 500mb files in bluestacks. I want to copy my obb folder to shared folder. But, I can not copy. I tried many file explorer but bluestacks stops working when copying progress reaches to 500mb.

A: How are you copying data into Blue stacks? Are you connected through LAN as you can also try to connect to your PC in bluestacks through searching for your PC under LAN (it searches for IP address of local system connected to bluestacks). Also you can put your files inside a folder and share it for all of the users. Bluestacks will detect it and you can copy files into Bluestacks.
Also you can try the method on this site.

A: I have ran into this problem when copying movies from Showbox and have not found a solution until now. I have tried increasing the RAM size with no luck. The only thing that did work was uploading to Dropbox.
But I recently tried trick which seems to work consistently:

*

*Open ES explorer (Install it if you don't have it) and click on the homepage within it.

*Then click Clean Now over on the right hand side - this brings up the ES cleaner.

*Clean all, then go back to the folder with your file and try copying.

This seems to work for me. I have increased my RAM size before this - although it did not work - but it could be the combination of both. I will try resetting my Bluestacks RAM back to stock and try it.


text:
Q: InvalidOperationException C# Word Add in I am encountering this error in my code. I'm trying to get the contents of a word file and add them to an existing one note file. Here is what I have so far:
namespace WordAddIn1
{
    public partial class ThisAddIn
    {

        //creates a new OneNote Application object
        static OneNote.Application onenoteApp;
        static XNamespace ns = null;
        static string resultWordText = "";
        static Microsoft.Office.Interop.Word.Application word_app;

        private void ThisAddIn_Startup(object sender, System.EventArgs e)
        {
            onenoteApp = new OneNote.Application();
            getWordText();
            writeToOneNote();
        }

        public static void getWordText()
        {
            try
            {

                word_app = (Microsoft.Office.Interop.Word.Application)Marshal.GetActiveObject("Word.Application");
                word_app.Visible = true;

                object inputFile = "C:\\Users\\t-aaalle\\Desktop\\GreetingFile2.docx";// "selected_doc" contains the document name
                object confirmConversions = false;
                object readOnly = false;
                object missing = Type.Missing;

                Document doc = word_app.Documents.Open(ref inputFile, ref confirmConversions, ref readOnly, ref missing);
            }
            catch (Exception e)
            {
                var trace = new System.Diagnostics.StackTrace(e);
            }
        }

        public static void writeToOneNote()
        {
            GetNamespace();
            //Gets the notebook, section, and firstpage
            string notebookId = GetObjectId(null, OneNote.HierarchyScope.hsNotebooks, "Aaron @ Microsoft");
            string sectionId = GetObjectId(notebookId, OneNote.HierarchyScope.hsSections, "New Section 1");
            string firstPageId = GetObjectId(sectionId, OneNote.HierarchyScope.hsPages, "My Page");

            //Reads the contents of the first page
            GetPageContent(firstPageId);

            Console.Read();
        }

        //Gets the name of the notebook
        static void GetNamespace()
        {
            string xml = "";

            onenoteApp.GetHierarchy(null, OneNote.HierarchyScope.hsNotebooks, out xml);
            var doc = XDocument.Parse(xml);
            ns = doc.Root.Name.Namespace;
        }

        //Gets the OneNote document
        static string GetObjectId(string parentId, HierarchyScope scope, string objectName)
        {
            string xml = "";

            onenoteApp.GetHierarchy(parentId, scope, out xml);

            var doc = XDocument.Parse(xml);
            var nodeName = "";

            switch (scope)
            {
                case (HierarchyScope.hsNotebooks): nodeName = "Notebook"; break;
                case (HierarchyScope.hsPages): nodeName = "Page"; break;
                case (HierarchyScope.hsSections): nodeName = "Section"; break;
                default:
                    return null;
            }

            var node = doc.Descendants(ns + nodeName).Where(n => n.Attribute("name").Value == objectName).FirstOrDefault();

            return node.Attribute("ID").Value;
        }

        //Get's the pages content
        static string GetPageContent(string pageId)
        {
            string xml= "";
            onenoteApp.GetPageContent(pageId, out xml, OneNote.PageInfo.piAll);
            var doc = XDocument.Parse(xml);
            var outLine = doc.Descendants(ns + "Outline").First();
            var content = outLine.Descendants(ns + "T").First();
            //THE LINE ABOVE IS WHERE THE ERROR IS BEING THROWN
            string contentVal = content.Value;
            content.Value = resultWordText;
            onenoteApp.UpdatePageContent(doc.ToString());

            return null;
        }

        private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
        {

        }

        #region VSTO generated code

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InternalStartup()
        {
            this.Startup += new System.EventHandler(ThisAddIn_Startup);
            this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
        }

        #endregion
    }
}

I am very new to C#, the full error reads:
An exception of type 'System.InvalidOperationException' occurred in System.Core.dll but was not handled in user code

and this error is confusing because I have searched and couldn't find anything that could help me. Help with this error would be amazing!


text:
Q: How to perform multiple tasks in CMD through Python in the same terminal and without the window closing I am exploring the use of Python to perform tasks in CMD, using os.system()
However, I found a few issues that prevents you from executing more than one command through python, along with the problem that as soon as the task is completed, the window closes.
import os

os.system('ipconfig', 'netstat')

The error that arose from this was that system() takes at most 1 argument (2 given)
import os

os.system('ipconfig')
os.system('netstat')

The problem that arose from this idea was that as soon as ipconfig had completed, I was ejected from the window and netstat began in a new terminal. After netstat had finished, before I could read the data recieved I was ejected from this terminal too.
How can I run two commands that follow one after the other, but in the same window? (I'd be able to scroll up and view the previous command and it's data.) And how can I prevent CMD from ejecting me from the window?

A: Use os.system('command & pause')
'&' Allows you to string multiple commands within the same window which will execute one after the other.
'Pause' Asks for user input to exit from the terminal.


text:
Q: Carousel type scrolling Using c#, what would be the best way to achieve a 2D carousel.
What would be better WPF or Windows Form. And how would be the best way to animate it? Just gradually move the pixels using a timer style ticks?
like (psuedo code):
//draw carousel here
using Timer every tick move the images left slightly

Thanks
MORE INFO:
I want it to be going quite fast as there will be 30 images and i want it to scroll through and loop once or twice before selecting a random one

A: WPF all the way! The easiest way is to create a UserControl with a ListBox and bind your collection of items to it. The trick is how you contain those items.
Here's a sample I coded a while back:
<ListBox ItemsSource="{Binding Files}" HorizontalContentAlignment="Stretch" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  SelectionMode="Single" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Disabled">
    <ListBox.ItemTemplate>

    </ListBox.ItemTemplate>
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Columns="10" VerticalAlignment="Center" IsItemsHost="True"/>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemContainerStyle>

    </ListBox.ItemContainerStyle>
</ListBox>

The same can also be done using a StackPanel with Orientation="Horizontal" and ScrollViewer.HorizontalScrollBarVisibility="Auto".
Any questions, let a brother know.
Sorry, missed this part:

And how would be the best way to animate it? Just gradually move the pixels using a timer style ticks?

The best way would be to use WPF's Storyboard and Animation classes. The general idea is to:

*

*Have forward/backward arrows.

*Depending on arrow clicked, either remove first item and add new item to end of list, or remove last item and insert item at beginning of list.

*Use animations to simulating adding/removing, i.e., fade out an item (or slide to left/right, whatever), then when the animation has completed, remove the actual item from the bound collection.

Also, make sure the bound collection has variable number of items (10 in my sample) and use another collection to keep track of the next item to be removed and added.


text:
Q: strongSwan IPsec server with AWS EC2 VPC VPN client I'm trying to create a VPN tunnel between 2 AWS regions. The way I'm trying to do this is by setting up a IPsec server in Linux with strongSwan in one region, and then a VPC VPN in the other region.
The problem is I can't come up with a configuration that works right.
AWS provides the following info for setting up the IPsec VPN:
#1: Internet Key Exchange Configuration

Configure the IKE SA as follows
  - Authentication Method    : Pre-Shared Key
  - Pre-Shared Key           : ***********************
  - Authentication Algorithm : sha1
  - Encryption Algorithm     : aes-128-cbc
  - Lifetime                 : 28800 seconds
  - Phase 1 Negotiation Mode : main
  - Perfect Forward Secrecy  : Diffie-Hellman Group 2

#2: IPSec Configuration

Configure the IPSec SA as follows:
  - Protocol                 : esp
  - Authentication Algorithm : hmac-sha1-96
  - Encryption Algorithm     : aes-128-cbc
  - Lifetime                 : 3600 seconds
  - Mode                     : tunnel
  - Perfect Forward Secrecy  : Diffie-Hellman Group 2

IPSec Dead Peer Detection (DPD) will be enabled on the AWS Endpoint. We
recommend configuring DPD on your endpoint as follows:
  - DPD Interval             : 10
  - DPD Retries              : 3

IPSec ESP (Encapsulating Security Payload) inserts additional
headers to transmit packets. These headers require additional space,
which reduces the amount of space available to transmit application data.
To limit the impact of this behavior, we recommend the following
configuration on your Customer Gateway:
  - TCP MSS Adjustment       : 1387 bytes
  - Clear Don't Fragment Bit : enabled
  - Fragmentation            : Before encryption

#3: Tunnel Interface Configuration

Your Customer Gateway must be configured with a tunnel interface that is
associated with the IPSec tunnel. All traffic transmitted to the tunnel
interface is encrypted and transmitted to the Virtual Private Gateway.

The Customer Gateway and Virtual Private Gateway each have two addresses that relate
to this IPSec tunnel. Each contains an outside address, upon which encrypted
traffic is exchanged. Each also contain an inside address associated with
the tunnel interface.

The Customer Gateway outside IP address was provided when the Customer Gateway
was created. Changing the IP address requires the creation of a new
Customer Gateway.

The Customer Gateway inside IP address should be configured on your tunnel
interface.

Outside IP Addresses:
  - Customer Gateway                : 54.241.138.199
  - Virtual Private Gateway         : 87.238.85.44

Inside IP Addresses
  - Customer Gateway                : 169.254.254.6/30
  - Virtual Private Gateway         : 169.254.254.5/30

Configure your tunnel to fragment at the optimal size:
  - Tunnel interface MTU     : 1436 bytes

#4: Static Routing Configuration:

To route traffic between your internal network and your VPC,
you will need a static route added to your router.

Static Route Configuration Options:

  - Next hop       : 169.254.254.5

You should add static routes towards your internal network on the VGW.
The VGW will then send traffic towards your internal network over
the tunnels.

The private subnet on the local strongSwan side is 10.2.0.0/16.
The private subnet on the remote VPN side is 10.4.0.0/16.
With this I tried using a configuration as follows:
conn eu-west-1-1
        left=10.2.0.40
        leftsubnet=0.0.0.0/0
        right=87.238.85.40
        rightsubnet=10.4.0.0/16
        auto=add
        type=tunnel
        keyexchange=ikev1
        authby=secret
        ikelifetime=28800s
        keylife=28800s
        ike=aes128
        esp=aes128

However this results in the following error:
pluto[1763]: "eu-west-1-1" #12: cannot respond to IPsec SA request because no connection is known for 0.0.0.0/0===10.2.0.40[10.2.0.40]...87.238.85.40[87.238.85.40]===0.0.0.0/0

Following one idea I found on the strongSwan mailing list, I tried putting 0.0.0.0/0 for the leftsubnet and rightsubnet, and this does cause the tunnel to come up (as reported by the AWS web GUI), but I lose all connectivity to the server (I'm guessing it's creating a route to 0.0.0.0/0 that blackholes all traffic).
Can anyone provide any hints on how to adjust the config to get this working?
Yes, I know I can just use 2 strongSwan, OpenVPN, or other software VPN on both ends, but by using AWS's VPN functionality, I only have to worry about maintaining one end of the VPN instead of both.

A: I know it's been a while since you posted this, but I have done what you describe, here is a sample connection block using your values:
conn vpc1
        type=tunnel
        compress=no
        keyexchange=ikev1
        ike=aes128-sha1-modp1024!
        auth=esp
        authby=psk
        left=54.241.138.199
        leftid=54.241.138.199
        leftsubnet=169.254.254.6/32,10.2.0.0/16
        rightsubnet=169.254.254.5/32,10.4.0.0/16
        right=87.238.85.44
        rightid=87.238.85.44
        esp=aes128-sha1-modp1024!
        auto=route

Then you can do ipsec up vpc1 ; ipsec route vpc1.
Left is your local side, right is the Amazon VPC VPN side. Hopefully I've gotten the IP's right.
The problem is that the ipsec has to create the correct ip xfrm policy in the kernel, without the proper settings it will not know how to do the tunnel. That and the encryption settings have to be perfect.
It took me many attempts and finally working with strongswan devs to figure this one out.
Caveats: This connection is not doing DPD properly, and sometimes drops. It also doesn't start+route when service ipsec start is called.
Good luck!


text:
Q: Is there a theorem you can use to state that if two polynomials are equal, then their homogenous parts are equal? Consider for example, polynomials of this form:
$$ a_o + (a_{1} x^1 + b_{1} y^1) + (a_2 x^2 + b_{11} x^1 y^1 + b_{2} y^2)... = a_o^{'} + (a_{1}^{'} x^1 + b_{1}^{'} y^1) + (a_2^{'} x^2 + b_{11}^{'} x^1 y^1 + b_{2}^{'} y^2)..$$
Then, could we say that:
$$ a_o = a_o^{'}$$
$$ a_1 x^1 + b_1 y^1 = a_1^{'} x^1 + b_1^{'} y^1$$
And so on.
Further, how would we justify such an idea?


text:
Q: Correct way to execute multiple reactive operations I get from a reactive repository a Mono<FooBar> based on it's value I have to create two other objects save them using reactive repositories, modify FooBar object and save it as well.
As I'm new to reactive programming I landed with the following solution, which is working, but I'm not sure if I'm using correctly the reactive API:
@Test
void createAndSave() {
    Mono<FooBar> fooBarMono = findFooBar()  // returns Mono<FooBar>
            .map(fooBar -> {
        createAndSaveLoremBar(fooBar).subscribe();   // returns Mono<LoremBar>
        createAndSaveDoloremBar(fooBar).subscribe(); // returns Mono<DoloremBar>

        fooBar.setActive(true);

        return saveFooBar(fooBar);          // returns Mono<FooBar>
    }).flatMap(Function.identity());

    StepVerifier.create(fooBarMono)
            .expectNextMatches(Objects::nonNull)
            .expectComplete()
            .verify();

}

from console log:
   saved lorem bar
   saved dolorem bar
   saved foo bar

A: I think the bellow solution is a little bit more readable. Anyway Alexander is correct you should never ever modify the input. You see we are borrowing a lot of concept form functional programming. For example you call Function.identity() this is called
identity functor. Both Fluxand Mono are monads. And there is a concept that is secret for these guys called Referential transparency that imperative update break.
    final Mono<FooBar> fooBarMono1 = findFooBar()
            .zipWhen((fooBar) -> createAndSaveLoremBar(fooBar))
            .map(tuple -> tuple.getT1())
            .zipWhen((fooBar) -> createAndSaveDoloremBar(fooBar))
            .map(tuple -> tuple.getT1())
            .map(fooBar -> new FooBar(true))
            .flatMap(fooBar -> saveFooBar(fooBar));

Or more concise:
    final Mono<FooBar> fooBarMono1 = findFooBar()
            .zipWhen((fooBar) -> createAndSaveLoremBar(fooBar)
                                    .then(createAndSaveDoloremBar(fooBar)))
            .map(tuple -> tuple.getT1())
            .map(fooBar -> new FooBar(true))
            .flatMap(fooBar -> saveFooBar(fooBar));

A: At first, mutating objects in the asynchronous (reactive) world is not a good idea.
Anyway, in your solution possible errors on lorem and dolorem saving are ignored. You can improve it like so:
Mono<FooBar> fooBarMono = findFooBar()
        .flatMap(fooBar -> Flux.merge(
                createAndSaveLoremBar(fooBar),
                createAndSaveDoloremBar(fooBar)) // asynchronously saving lorem and dolorem
                .then(Mono.fromCallable(() -> {  // if there wasn't errors, mutate and save fooBar
                    fooBar.setActive(true);
                    return fooBar;
                }).flatMap(fooBar1 -> saveFooBar(fooBar1))));

If you could create copy of your fooBar with true active flag, the code could be simpler. For example with lombok.
@Builder(toBuilder = true)
public class FooBar {
...
}

Mono<FooBar> fooBarMono = findFooBar()
        .flatMap(fooBar -> Flux.merge(
                createAndSaveLoremBar(fooBar),
                createAndSaveDoloremBar(fooBar))
                .then(saveFooBar(fooBar.toBuilder().active(true).build())));

And if you are not interested in the result of your saveFooBar(...) but only in the completion signal, you could make all three saves asynchronously:
Flux<Object> flux = findFooBar()
        .flatMapMany(fooBar -> Flux.merge(
                createAndSaveLoremBar(fooBar),
                createAndSaveDoloremBar(fooBar),
                saveFooBar(fooBar.toBuilder().active(true).build())));

Actually, in the last approach you could collect all three results and you should prefer this approach, but I don't have enough information about your classes and requirements for creating full example.


text:
Q: SCons, Boost::ASIO, Windows Precompiled Headers, and Linker Errors I'm investigating using SCons for our build process as we develop C++ for multiple platforms.  I'm 99% of the way there in the build configuration, but I'm running into a VERY strange error on Windows having to do with the precompiled header file.  Even stranger still is that it only happens on one project.
In the SConscript file for this project, I have the following to compile the PCH on windows:
if env['PLATFORM'] == 'win32':
    env['PCH'] = env.PCH('MyPCH-LSCommon.pch', 'Common/src/MyPCH.h')[0]
    env['PCHSTOP'] = '"MyPCH.h"'

I also have a compiler flag set to force include MyPCH.h on all files in the project:
if env['PLATFORM'] == 'win32':
    cxxflags = [ '/FI"MyPCH.h"' ]

Everything goes along and compiles absolutely fine.  It isn't until the final DLL link stage that I get pages and pages of linker errors such as the following:
error LNK2001: unresolved external symbol "private: static class
boost::asio::detail::tss_ptr<class boost::asio::detail::call_stack<class
boost::asio::detail::win_iocp_io_service>::context> boost::asio::detail::call_stack<class
boost::asio::detail::win_iocp_io_service>::top_"
(?top_@?$call_stack@Vwin_iocp_io_service@detail@asio@boost@@@detail@asio@boost@@0V?$tss_ptr@
Vcontext@?$call_stack@Vwin_iocp_io_service@detail@asio@boost@@@detail@asio@boost@@@234@A)

and:
     error LNK2001: unresolved external symbol "private: static class
boost::asio::detail::winsock_init<2,0> boost::asio::detail::winsock_init<2,0>::instance_"
(?instance_@?$winsock_init@$01$0A@@detail@asio@boost@@0V1234@A)

This is puzzling because none of the classes that I'm getting link warnings from don't even use boost::asio, although it is included in the precompiled header file and up the chain in some #includes.
Even more puzzling is that if I disable compilation of the precompiled header file, yet still force it's include, everything compiles and links just fine.  It just takes freaking forever.
Does anyone have a clue as to what could be causing these linker errors?
Thanks in advance.
--- EDIT ---
Here's the command line that SCons is spitting out for building the PCH (Minus Include Paths):
    cl /nologo /W4 /Od /RTC1 /MDd /TP /EHsc /FD /RTC1 /RTCc /Gy /openmp /TP
/Fd"\vc80.pdb" /nologo /Wp64 /wd4231 /wd4616 /errorReport:prompt /Zm256 /MDd /Od
/FI"CedrusPCH.h" /DOS_WINDOWS=OS_WINDOWS /D_WIN32 /DWIN32 /D_WIN32_WINNT=0X500 /D_WINDOWS
/D_UNICODE /DBOOST_ALL_DYN_LINK /DBOOST_REGEX_DYN_LINK /DBOOST_LIB_DIAGNOSTIC
/D_VC80_UPGRADE=0x710 /DUNICODE /DWXUSINGDLL /DwxUSE_SERVICE_DISCOVERY=1 /D_DEBUG /D_DEBUG
/DSL_ENABLE_NETWORKING=1 /DWXMAKINGDLL_LSCOMMON /DSLSDK_USEDLL
/c C:\Projects\licenser\Common\src\CedrusPCH.h /Foscons-out\dbg\obj\CedrusPCH-LSCommon.obj
/Yc"CedrusPCH.h" /Fpscons-out\dbg\obj\CedrusPCH-LSCommon.pch /ZI CedrusPCH.h

Here's the command line for a file being compiled (again minus include paths):
cl /Foscons-out\dbg\obj\Licenser\src\secure\windows_crypto
\PlatformCryptoKeyProvider_wincrypt.obj /c C:\Projects\licenser\Licenser\src\secure
\windows_crypto\PlatformCryptoKeyProvider_wincrypt.cpp /nologo /W4 /Od /RTC1 /MDd /TP
/EHsc /FD /RTC1 /RTCc /Gy /openmp /TP /Fd"\vc80.pdb" /nologo /Wp64 /wd4231 /wd4616
/errorReport:prompt /Zm256 /MDd /Od /FI"CedrusPCH.h" /nologo /W4 /Od /RTC1 /MDd
/DOS_WINDOWS=OS_WINDOWS /D_WIN32 /DWIN32 /D_WIN32_WINNT=0X500 /D_WINDOWS /D_UNICODE
/DBOOST_ALL_DYN_LINK /DBOOST_REGEX_DYN_LINK /DBOOST_LIB_DIAGNOSTIC /D_VC80_UPGRADE=0x710
/DUNICODE /DWXUSINGDLL /DwxUSE_SERVICE_DISCOVERY=1 /D_DEBUG /D_DEBUG
/DSL_ENABLE_NETWORKING=1 /DWXMAKINGDLL_LSCOMMON /DSLSDK_USEDLL /D_USRDLL /D_WINDLL
 /Yu"CedrusPCH.h" /Fpscons-out\dbg\obj\CedrusPCH-LSCommon.pch /ZI
PlatformCryptoKeyProvider_wincrypt.cpp

And finally, here's the link command line:
link /nologo /MACHINE:X86 /DEBUG -manifest /dll /out:scons-out\dbg\obj\LSCommon.dll
/implib:scons-out\dbg\obj\LSCommon.lib /LIBPATH:scons-out\dbg\lib
/LIBPATH:C:\Projects\licenser\scons-out\dbg\lib /LIBPATH:scons-out\dbg\obj
/LIBPATH:. /LIBPATH:C:\Projects\licenser /LIBPATH:C:\Projects\licenser\scons-out\dbg\obj
/LIBPATH:C:\Projects\wxWidgets\lib\vc_dll_vc8 /LIBPATH:C:\Projects\boost\install\lib
"/LIBPATH:C:\Program Files\Microsoft Platform SDK for Windows Server 2003 R2\Lib"
"/LIBPATH:C:\Program Files\Bonjour SDK\lib\win32" unicows.lib winmm.lib comctl32.lib
rpcrt4.lib ws2_32.lib oleacc.lib kernel32.lib user32.lib gdi32.lib winspool.lib
comdlg32.lib advapi32.lib shell32.lib oleacc.lib ole32.lib oleaut32.lib uuid.lib
odbc32.lib odbccp32.lib boost_signals-vc80-mt-gd-1_39.lib boost_system-vc80-mt-gd-1_39.lib
boost_date_time-vc80-mt-gd-1_39.lib boost_regex-vc80-mt-gd-1_39.lib
boost_wserialization-vc80-mt-gd-1_39.lib boost_serialization-vc80-mt-gd-1_39.lib
boost_thread-vc80-mt-gd-1_39.lib wxbase28ud.lib wxbase28ud_net.lib wxbase28ud_xml.lib
wxmsw28ud_adv.lib wxmsw28ud_aui.lib wxmsw28ud_core.lib wxmsw28ud_html.lib wxmsw28ud_qa.lib
wxmsw28ud_richtext.lib wxmsw28ud_xrc.lib LSBase.lib disphelper.lib Crypt32.lib
/PDB:scons-out\dbg\obj\LSCommon.pdb /DEBUG
scons-out\dbg\obj\Licenser\src\dll_template_instantiation_export_LSCommon.obj
scons-out\dbg\obj\Licenser\src\secure\ConcreteMessageSigningAlgorithm_DSA_with_SHA1.obj
scons-out\dbg\obj\Licenser\src\secure\CryptoObjectFactory.obj
scons-out\dbg\obj\Licenser\src\secure\EntropyCalculation.obj
scons-out\dbg\obj\Licenser\src\data\LSAccount.obj
scons-out\dbg\obj\Licenser\src\data\LSAccountHistory.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSAccountHistoryRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSAccountRequestPacket.obj
scons-out\dbg\obj\Licenser\src\data\LSActivation.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSActivationRequestPacket.obj
scons-out\dbg\obj\Licenser\src\data\LSBlob.obj
scons-out\dbg\obj\Licenser\src\data\LSCompositePrimaryKey.obj
scons-out\dbg\obj\Licenser\src\data\LSDatabaseElementBase.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSDoActivateReplyPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSDoActivateRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSDoManualActivateReplyPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSDoManualActivateRequestPacket.obj
scons-out\dbg\obj\Licenser\src\data\LSLicense.obj
scons-out\dbg\obj\Licenser\src\data\LSLicenseHistory.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSLicenseHistoryRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSLicenseRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSLoginReplyPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSLoginRequestPacket.obj
scons-out\dbg\obj\Licenser\src\data\LSMachine.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSMachineRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSNet.obj
scons-out\dbg\obj\Licenser\src\data\LSPhyActivation.obj
scons-out\dbg\obj\Licenser\src\data\deprecated_streamables\LSPhyActivation_LegacyStreamingHelper.obj
scons-out\dbg\obj\Licenser\src\data\LSPrimaryKey.obj
scons-out\dbg\obj\Licenser\src\data\LSPrimaryKeyDefinitions.obj
scons-out\dbg\obj\Licenser\src\data\LSProduct.obj
scons-out\dbg\obj\Licenser\src\data\LSProductHistory.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSProductHistoryRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSProductRequestPacket.obj
scons-out\dbg\obj\Licenser\src\data\LSSimplePrimaryKey.obj
scons-out\dbg\obj\Licenser\src\data\LSUser.obj
scons-out\dbg\obj\Licenser\src\data\LSUserHistory.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSUserHistoryRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSUserRequestPacket.obj
scons-out\dbg\obj\Licenser\src\server_daemon\streaming_versioning\StreamableClassInfoVersionTranslator.obj
scons-out\dbg\obj\Licenser\src\data\deprecated_streamables\LSProduct_deprecated_v_2.obj
scons-out\dbg\obj\Licenser\src\secure\deprecated_streamables\DSA.obj
scons-out\dbg\obj\Licenser\src\secure\deprecated_streamables\DSAKeyPair.obj
scons-out\dbg\obj\Licenser\src\secure\deprecated_streamables\DSAPublicKey.obj
scons-out\dbg\obj\Licenser\src\secure\deprecated_streamables\Hash.obj
scons-out\dbg\obj\Licenser\src\secure\deprecated_streamables\SHA1.obj
scons-out\dbg\obj\Licenser\src\server_daemon\LSActivationApprovalStrategy.obj
scons-out\dbg\obj\Licenser\src\data\LSDatabaseElementT.obj
scons-out\dbg\obj\Licenser\src\data\LSPairPrimaryKeyT.obj
scons-out\dbg\obj\Licenser\src\data\LSSimplePrimaryKeyT.obj
scons-out\dbg\obj\Licenser\src\secure\windows_crypto\PlatformCryptoKeyProvider_wincrypt.obj
scons-out\dbg\obj\Licenser\src\secure\windows_crypto\Scoped_RAII_AutoReleaseWincryptHandleFactory.obj

Also, the PCH header isn't explicitly included by each individual file, but on the command line options, I have /FI that force includes the PCH on every file compiled in the project.

A: I seem to have solved my own problem.  When precompiling the header file, cl.exe generates a .obj file.  Because we're using boost's internal magic to automatically link to needed libraries on Windows and our boost header #includes are also in the precompiled header, those links are also included in the .obj file.  Unfortunately, this .obj file is not added to the list of .obj files that need to be linked (to make a .dll in this case).
What got it working was manually appending the .obj file generated during compilation of the PCH to the LINKFLAGS argument. Doing this 100% completely solves the problem I've been having.  Maybe it's time to update the msvc.py tool and send a patch into SCons!

A: There are 2 defines when compiling that are there when building the pre-compiled headers:
/D_USRDLL
/D_WINDLL

As far as I know, these are MFC relics. I don't really know anything about them, but I wouldn't be surprised if wxWidgets had some dependencies on them. I doubt that Boost does (but I havn't looked, either).


text:
Q: Using a string within as a function name (Javascript) Okay so, this title maybe incorrect but I don't really know how to ask this question: I'm writing a bot using Discord.js and I'm trying to reply a string from an enum based on the message given.
const Heroes = {
VengefulSpirit: {
inCaptainsMode: true,
primaryAttribute:'Agility',
    attributeGains:{
    Strength: 2.6,
    Agility: 3.3,
    Intelligence: 1.5
    },

},
}

Here is the Input
case 'venge': case 'vengeful spirit': case 'Vengeful Spirit':
message.reply(getHeroDetails('VengefulSpirit'));

And sadly a not working output
function getHeroDetails(heroName){
var heroDetails = '';
heroDetails += 'Primary Attribute: ';
heroDetails += Heroes.heroName.primaryAttribute.toString();
heroDetails += '\n In captain\'s mode: ';
heroDetails += Heroes.heroName.inCaptainsMode.toString();
heroDetails += '\n Strength gain: ';
heroDetails += Heroes.heroName.attributeGains.Strength.toString();
heroDetails += '\n Agility gain: ';
heroDetails += Heroes.heroName.attributeGains.Agility.toString();
heroDetails += '\n Intelligence gain: ';
heroDetails += Heroes.heroName.attributeGains.Intelligence.toString();
return heroDetails;
}

Now I'm using heroName as the input string so in this scenario it would be VengefulSpirit and if I used it in replacement of heroName in all those calls, the function works correctly. I just don't know how to use heroName instead of hardcoding a function for every hero (there's like 112 of them). I'm trying to create a dynamic function so that It's shorter.

A: Use Heroes[heroName] to access keys of your Heroes object instead of Heroes.heroName .

A: Use: Heroes[heroName]. Dot notation won't work in this situation...
Good Luck with your RPG though ;)


text:
Q: как устроен модуль Tkinter (python) озадачен вопросом как устроен встроенный в дистрибутив питона модуль tkinter. Инфы хоть по какой нибудь внутренней его части нигде попросту я не нашел. Вопрос первый: рисует контролы операционная система, а не OpenGl, верно? тогда следует второй вопрос, в исходниках модуля (https://github.com/python/cpython/blob/master/Modules/_tkinter.c) вроде как ясно что используется winAPI, а как быть с линуксом, где для иксов что используется? А где для макоси? Где то лежит отдельно сборка для иных винде осей или я смотрю куда то не туда?

A: *

*Tkinter использует Tk, который под каждой системой использует свой способ отображения элементов управления. Tkinter (Tk interface) - только "обертка" над Tk.

*В программах на C/C++ есть возможность для разных платформ при помощи #ifdef/#ifndef (см. Препроцессор Си) включать или не включать в готовую программу какие-то блоки кода. По приведенной вами ссылке все обращения конкретно к WinAPI обернуты в блоки #ifdef MS_WINDOWS, при компиляции под другие системы эти блоки в бинарный файл не попадают.


text:
Q: Access logger from Elasticsearch script I use the scripts aggressively for scoring and aggregation. One thing i cant figure out is how to emit logs from the script. I tried console.log , but then it didnt work out. Kindly let me know , how i can emit logs from my groovy  script.

A: This can be done by accessing global Elasticsearch logger instance.
Its groovy example is given below
You should be able to do something similar for javascript and other scripting languages too.
import  org.elasticsearch.common.logging.*;
ESLogger logger=ESLoggerFactory.getLogger('myscript');
logger.info('This is a log message');

So when you do a terms aggregation , you can do something like below -
  "aggregations": {
      "debug":{
          "terms":{
              "script":"import  org.elasticsearch.common.logging.*; ESLogger logger=ESLoggerFactory.getLogger('myscript'); logger.info('This is a log message'); return doc['myField'].value;"
          }
      }
}

Some good folks from Elasticsearch has given a good documentation on it against a issue.
LINK - https://github.com/elasticsearch/elasticsearch/issues/9068
I have also given some examples here.


text:
Q: Need regex that ignores date/sequence number, but matches the rest of the string I'm looking for a regex that ignores part of a larger string of text, specifically a date/sequence number. For example, the string looks like this:
E0618456458784NOS REGRESSION COMPANY  5454545455SAL         3-MAAAA2018/2/00192
I would like the regex to ignore the "2018/2/00192" but still match up the rest of the string. In the next file I use the regex for, the date/sequence number might be in a different location and the string may change, but the format will always be the same, meaning "2018/#/#####". I'm using C++ and I've gotten close with this regex (found on this site):
[^2018/2/00192]+
It ignores the date/sequence number, but it's also ignore the "0", "1", and "8" at the beginning of the line. I basically don't care about the "2018/2/00192" in the string because I know that's going to change. Everything else though, I want to match. Appreciate any suggestions.
Thanks.

A: I dont know how you would do this in c++, but the sed equivalent of this would be
sed -e "s/[0-9]\{4\}\/[0-9]\/[0-9]\{5\}//" text

In programming languages like Perl, you could use \d in place of [0-9]


text:
Q: Usability and bias of test set for limited data I understand that optimizing model parameters, for example in k-fold cross-validation should be done in absence of a final test set in order not to overfit the model. Only at the very end, the model is applied to the test set to evaluate the performance. In contrast, including all data in the cross-validation might give a too optimistic estimate of the model skill. Louic summarized this in his helpful answer here: https://datascience.stackexchange.com/a/52643
However, when having little data, as often the case in social science contexts, final evaluations on a single test set can vary heavily. See below how in my use case the relevant f1 metric varies up to 30% between worst and best performing run. Relying on this evaluation can lead to an overly optimistic or pessimistic appraisal of the model performance. (see also https://stats.stackexchange.com/a/236645/268442)

My questions:

*

*In a situation where I have an unbiased sample of the target population and given the disadvantages of both methods (overfitting vs. non-robust model evaluation and less training data), isn't it more meaningful to evaluate the validity and performance of my model when using cross-validation on all data? I risk overfitting the data but get very robust results when checking the performance of the final model on 100 different train/test splits.

*Maybe a bit more provocative: What is the use of a hold-out test set if it, because of small n, produces a biased appraisal of the model performance anyways (and makes less data available for training)?
Thank you!


text:
Q: Factoring with rational exponents I'm not quite sure how to do this question.  Every way that I tried doing it didn't yield an answer that is equivalent to the original question.
$$(2x+1)^{2/3}-4(2x+1)^{-1/3}$$
When I tried doing it, I ended up with $$(2x+1)^{2/3}\left(-\frac{8x+4}{2x+1}\right)$$ or with $$4(2x+1)^{1/3}$$
How can I factor it properly?

A: First way
Multiply and divide both pieces by $(2 x + 1)^{1/3}$. You so obtain
$$\frac{2x+1 - 4}{(2 x + 1)^{1/3}} = \frac{2 x - 3}{(2 x + 1)^{1/3}}$$
Second way
Factor $(2 x + 1)^{2/3}$. You so obtain
$$ (2x+1)^{2/3}\cdot \frac{1-4}{2 x + 1} = (2 x + 1)^{2/3}\cdot \frac{2 x + 1 - 4}{2 x + 1} = \frac{2 x - 3}{(2 x + 1)^{1/3}} $$

A: Start by rewritting the equation a bit more clearly.
$$(2x+1)^{2/3} -4(2x+1)^{-1/3} = \sqrt[3]{\left ( 2x+1 \right)^2} - \frac{4}{\sqrt[3]{2x+1}}$$
Then, put everything on the same denominator.
$$\sqrt[3]{\left ( 2x+1 \right)^2} - \frac{4}{\sqrt[3]{2x+1}} = \frac{\sqrt[3]{\left ( 2x+1 \right)^2} \sqrt[3]{2x+1} - 4}{\sqrt[3]{2x+1}}$$
Simplify.
$$ \frac{\sqrt[3]{\left ( 2x+1 \right)^2} \sqrt[3]{2x+1} - 4}{\sqrt[3]{2x+1}} = \frac{\sqrt[3]{\left ( 2x+1 \right)^3} - 4}{\sqrt[3]{2x+1}}$$
I'll let you continue the work. Let me know in the comments if you want more info or a confirmation of your answer.

A: Let $\ \color{#c00}{y} = (\color{#0a0}{2x+1})^{1/\color{#c00}3}.\,$ Then $\ y^2-\dfrac{4}y\, =\, \dfrac{\color{#c00}{y^3}-4}y\, =\, \dfrac{2x-3}y\ $ by $\ \color{#c00}{y^3} = \color{#0a0}{2x+1}$

A: As a general method you can get good results by factoring off the the binomial to the power that is leftmost on the real number line like so:
\begin{align*}
(2x+1)^{\frac{2}{3}}-4(2x+1)^{-\frac{1}{3}} &= (2x+1)^{-\frac{1}{3}}\left( (2x+1)^{\frac{3}{3}} -4\right) \\
&= (2x+1)^{-\frac{1}{3}}( 2x+1 -4) \\
&= (2x+1)^{-\frac{1}{3}}( 2x-3) \\
&=\frac{2x-3}{\sqrt[3]{2x+1}}.
\end{align*}


text:
Q: Phaser login/signup form I am developing a game in phaser but I am newbie yet. I want to create a login/signup/fb form in the main screen of the game. I did a html form in the index.html of phaser, but I have some doubts. How could I achieve the communication between the html and the scenes of phaser? I created global variables, but I think that is not a good practice.
Are there any options to use a state from html like MyGame.MainPage.startGame()?
This is the js script of the index, the function is associated to login button:
function login(){
    user = check_user_in_db();
    if(user){   //If the login is correct
        variable.startGame();
    }
}

This is the MainPage scene of Phaser:
/*********************NAMESPACE********************/
var MyGame = MyGame || {};
/**************************************************/

/******************INIT APP SCENE******************/
MyGame.MainPage = function(game)
{
    variable = this;
};

MyGame.MainPage.prototype =
{
    init: function()
    {

    }, // init

    preload: function()
    {
       //load Sprites
    }, //preload

    create: function()
    {
       //create Buttons
    }, // create

    shutdown: function()
    {

    }, // shutdown

    startGame: function(){
        this.state.start("Menu", true, false);
    }
};

A: You can try this Phaser plugin
https://github.com/orange-games/phaser-input


text:
Q: simple primefaces dialog does not affect value to property I have a simple input text inside a primefaces dialog with a command button to test if the variable gets his value but when i click the command button with(process="@this" when i delete it the button dont work any more)to print the value of the property it shows always null ... the dialog is rented by a command link from a data grid and when i delete the dialog every thing works fine and the property get th value this is the jsf page :
<p:layoutUnit id="center" position="center"
                style="min-height:400px;min-width:300px;overflow-y:hidden !important"
                header="#{messages['layout.center.header']}">

 <f:view>
<h:form >

                    <p:dataGrid var="c" value="#{rentMB.carsList}" columns="3"
                        layout="grid" rows="12" paginator="true" id="cars"
                        paginatorTemplate="{CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink} {RowsPerPageDropdown}"
                        rowsPerPageTemplate="6,12,16">

                        <f:facet name="header">
                 Available Cars
                 </f:facet>

                        <p:panel header="#{c.car_brand.brand_name}"
                            style="text-align:center">
                            <h:panelGrid columns="1" style="width:100%">
                                <p:graphicImage url="/images/#{c.image}.jpg" />
                                <p:commandLink
                                    oncomplete="PF('carDialog').show()" title="View Detail">
                                    <h:outputText styleClass="ui-icon ui-icon-key"
                                        style="margin:0 auto;" />
                                    <f:setPropertyActionListener value="#{c}"
                                        target="#{rentMB.selectedCar}"  />
                                </p:commandLink>
                            </h:panelGrid>
                        </p:panel>

                    </p:dataGrid>
</h:form>

 <h:form>
                    <p:dialog header="Car Info" id="carInfo" widgetVar="carDialog" width="900px"
                        height="400px" showEffect="fade" hideEffect="fade"
                        resizable="false" appendToBody="true">
              <p:outputPanel>
<h:panelGrid columns="3" >

                                    <f:facet name="header">
        Client informations
                      </f:facet>

                                 <h:outputLabel for="adress" value="Adress : *" />
                                    <p:inputText id="adress" value="#{rentMB.adress}"
                                        />
                                        <p:watermark for="adress" value="Adress" />

                                    <p:commandButton action="#{rentMB.affiche}"   process="@this" value="Rent" oncomplete="carInfo.hide();" >  </p:commandButton>

                                    <p:commandButton type="reset" value="Reset">  </p:commandButton>
                            </h:panelGrid>
                            </p:outputPanel>
                        </p:dialog>
                </h:form>
                </f:view>
            </p:layoutUnit>
        </p:layout>
    </h:body>
</f:view>
</html>

the code of rentMB.affiche() :
public void affiche()
    {
        System.out.println(this.getAdress());
    }

A: the solution is to put the content of the p:dialog between <h:form></h:form> and add to dialog appendToBody="false"


text:
Q: rényi entropy as a derivative Let $x=(x_i)$ be a probability measure on $\{1,\ldots,n\}$. Suppose $1<p<\infty$. The Rényi entropy of $x$ is
$$
H^p(x)=\frac{1}{1-p}\log \sum_{i} x_i^p.
$$
Does there exist a formula for $H^p(x)$ using a derivative and a norm ($\ell_{p,q}$, Orlicz,...) of $x$?
Remark:
I know that for the classical entropy $H(x)=-\sum_{i}\log(x_i) x_i$, we have
$$
H(x)=\left. \frac{d}{dp}\right|_{p=1}\vert\vert x \vert\vert^p_{\ell_p}
$$


text:
Q: Speed up for loop iterating over two large (10000s) lists I'm trying to check one list of IP addresses against another list of Networks that it could belong to. The lengths:
len(IP_addresses_list) = 31995
len(Network_list) = 54099

    big_dict = {}
    for ip in IP_addresses_list:
        address_and_networks = self.is_subnet_of(ip, Network_list)
        big_dict.update(address_and_networks)

    df = pd.DataFrame.from_dict(big_dict, orient="index")

And the loop is verifying whether it belongs to the network by:
def is_subnet_of(self, ip, Network_list):
    address_and_networks = {}
    address = ipaddress.ip_address(ip)
    for net in Network_list:
        network = ipaddress.ip_network(net)
        res = network.supernet_of(ipaddress.ip_network(f"{address}/{address.max_prefixlen}"))
        if res:
            if ip in address_and_networks:
                address_and_networks[ip].append(net)
            else:
                address_and_networks[ip] = [net]

    return address_and_networks

The address_and_networks dict may look like:
{
  "xxx.xxx.xxx.xxx": ["xxx.xxx.xxx.xxx/24", "xxx.xxx.xxx.xxx/23"],
  "yyy.yyy.yyy.yyy": ["yyy.yyy.yyy.yyy/24", "yyy.yyy.yyy.yyy/23"]
}

This method is currently painstakingly slow, so slow it's just not feasible to use. I'd like to accelerate this somehow, perhaps by dumping the original lists (IP_addresses_list, Network_list) into a dataframe then perform some sweeping execution on the dataframe, by applying the is_subnet_of method (maybe something like dataframe.select or dataframe.apply). Any idea how I can speed this up?
EDIT
I streamlined the code further, but I'm still resorting to looping over the dataframes:
    df = pd.DataFrame({"IP_Address": ip_s.map(ipaddress.ip_address),
                            "Network": net_s.map(ipaddress.ip_network),
                            "Associated": np.nan})

    for i, address in df["IP_Address"].iteritems():
        if address != address:
            continue
        net_list = []
        for j, network in df["Network"].iteritems():
            if network.supernet_of(ipaddress.ip_network(f"{address}/{address.max_prefixlen}")):
                net_list.append(str(network))
                df.loc[i, "Associated"] = net_list

Example data:
Addresses = ['172.16.56.40','172.16.16.16']

Networks = ['172.16.56.0/24', '172.16.56.32/27']

A: Bit operations will make it much faster, it also allows some expensive operations to be performed only once.
Consider the bellow function:
def is_subnet_of(ip: str, network: str) -> bool:
    def bin_ip(ip: str) -> int:
        return int("".join(map(lambda n: bin(int(n)).replace("0b", "").zfill(8), ip.split("."))), 2)

    net, mask_len = network.split("/")
    mask_len = int(mask_len)

    # Convert ip and net to binary-format
    ip_bin = bin_ip(ip)
    net_bin = bin_ip(net)

    # Build mask
    mask = int(mask_len * '1' + (32 - mask_len) * '0', 2)

    # check (Bit operations are faster)
    return net_bin ^ (mask & ip_bin) == 0

# `is_subnet_of("172.16.56.40", "172.16.56.0/24")` will return True.

It takes 3 steps to decided whether the given ip is in the network:

*

*Convert ip and net to binary-format(We need another functionbin_ipto do this job)

*Build the net mask

*Do the check:(net ^ (mask & ip))
Even better, step1 and step2 only have to be performed once, which will save us most of the time:
from typing import Tuple

def check_subnet(ip, network_list):
    def bin_ip(ip: str) -> int:
        return int(
            "".join(map(lambda n: bin(int(n)).replace("0b", "").zfill(8), ip.split("."))), 2
        )

    def bin_net(net: str) -> Tuple[int, int]:
        net_ip, mask_len = net.split("/")
        mask_len = int(mask_len)

        net_bin = bin_ip(net_ip)
        mask = int(mask_len * "1" + (32 - mask_len) * "0", 2)

        return net_bin, mask

    def is_subnet_of(ip: int, network: Tuple[int, int]) -> bool:
        return network[0] ^ (network[1] & ip) == 0

    ip = bin_ip(ip)
    networks = tuple(map(bin_net, network_list))

    return tuple(is_subnet_of(ip, network) for network in networks)

# Below are the test section
address_and_networks = {"172.16.56.40": ["172.16.56.0/24", "172.16.56.32/27"]}

result = tuple(check_subnet(ip, network_list) for ip, network_list in address_and_networks.items())

print(result)

If you insist using pandas vectorization operations, then I suggest:

*

*Use the bin_ip function I mentioned above to construct matrixs of ip, network, and mask (this step will be O(n) complexity)

*Use numpy matrix operations (as we all know, pandas actually uses numpy to complete numerical calculations) to calculate the result:result = ((ip & mask) == net.T)
In this way, we will do the O(n) complexity ourselves and leave the O(n^2) part to pandas/numpy vectorization operations.

A: You are running into O(n^2) complexity.
As you mentioned, len(IP_addresses_list) = 31995 and len(Network_list) = 54099. Currently you are looping all 31995 * 54099 iterations and so causing the slowness.
Just for rough idea the same length loop doing nothing(just a pass statement) took almost 4 mins on online python compiler website. It still took a little over 1 min on my machine.
You need to reduce the iterations happening inside is_subnet_of function.

*

*One approach here is break from the loop whenever possible. Do you see any conditions when your result is complete or you no longer need to continue the loop on Network_list (inside is_subnet_of function)?

*Another approach is reduce your search list (Network_list). Convert it into dictionary with key as first 3 parts of IP address. And in is_subnet_of loop only the shorter list matching first 3 parts of IP address.
For example:
Addresses = ['172.16.56.40','172.16.16.16']
Networks = ['172.16.56.0/24', '172.16.56.32/27']

Convert your Network lists to dictionary for Networks
Networks = ['172.16.56.0/24', '172.16.56.32/27']
network_dict = {}
for n in Networks:
    network_dict.setdefault(n[:n.rfind(".")], []).append(n)
print(network_dict)

Output:
{'172.16.56': ['172.16.56.0/24', '172.16.56.32/27']}

So your is_subnet_of function will loop through for 172.16.56.40 and no loop for 172.16.16.16

A: Without the actual data, it is a bit hard to understand what exactly is happening, but some general advise could be:

*

*DataFrame.merge with how='inner' allows you to relatively fast check which values appear in two separate lists. So if you have one column containing the first three parts of IP addresses and another column containing network IPs (again only XXX.XXX.XXX and not the last part), this could already do the job. You might need to do some checking afterwards, but the number of operations would be much less. merge is vectorized making it a suitable candidate.

*dask.apply could be used on a Dask DataFrame. This could be combined with merge similar to the above-mentioned idea.

Once you provide example data, the suggestions above could be refined.


text:
Q: Typesetting lemmas in latex with shadethm package I am trying to get the shadethm package to typeset lemmas in shaded boxes, but am failing so far.
The following document produces
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage[normalem]{ulem}
\usepackage{amsmath}
\usepackage{amssymb}
\usepackage[margin=0.75in]{geometry}
\usepackage{blindtext}
\setlength{\parindent}{20pt}
\usepackage{amsthm}
\usepackage{shadethm}
\renewcommand\qedsymbol{$\blacksquare$}

\newshadetheorem{theorem}{Theorem}
\newshadetheorem{corollary}{Corollary}[theorem]

\title{\vspace{-1.5cm}Test Document}
\begin{document}

\maketitle

\blindtext

\begin{theorem}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\section{New Section}

\begin{theorem}[Pythagorean theorem]
\label{pythagorean}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\begin{proof}
To prove it by contradiction try and assume that the statemenet is false,
proceed from there and at some point you will arrive to a contradiction.
\end{proof}

\blindtext

\begin{corollary}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]

\end{corollary}
\end{document}

However, when I try to typeset lemmas as theorems as
\newshadetheorem{lemma}[theorem]{Lemma} (following overleaf) and then using \begin{lemma}...\end{lemma}
I get the compilation error
 [long compilation output]
! TeX capacity exceeded, sorry [input stack size=5000].
    \cl@theorem ->\cl@theorem
                              \@elt {shadecorollary}
    l.57 \begin{lemma}

    !  ==> Fatal error occurred, no output PDF file produced!
    Transcript written on test.log.

Where am I going wrong? I would like Theorems and Lemmas to be labelled together sequentially like
Theorem 1, Lemma 2, Lemma 3, Theorem 4 irrespective of the section number they are in.

A: You might be interested in giving a try at the ntheorem package, which enables you to fully customise the layout of theorems. For shaded theorems, it relies on the framed package. Note the automatic placement of the 'end-of-proof'   symbol, even when the proof ends with an equation (two compilations required):
\documentclass[11pt]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[margin=0.75in]{geometry}
\usepackage{graphicx}
\usepackage[svgnames]{xcolor}
\usepackage[normalem]{ulem}
\usepackage{amsmath, amssymb, nccmath}
\usepackage{blindtext}
\setlength{\parindent}{20pt}

\usepackage{framed}
\usepackage[framed, thmmarks]{ntheorem}
\colorlet{shadecolor}{Gainsboro!50!Lavender}
\def\theoremframecommand{\colorbox{shadecolor}}
\theoreminframepreskip{\medskipamount}
\theoreminframepostskip{\medskipamount}
\theoremseparator{.}
\newshadedtheorem{theorem}{Theorem}
\newshadedtheorem{corollary}{Corollary}[theorem]
\newshadedtheorem{lemma}{Lemma}[theorem]

\theoremstyle{nonumberplain}
\theoremheaderfont{\itshape}
\theorembodyfont{\upshape}
\theoremseparator{:}
\theoremsymbol{\ensuremath{\blacksquare}}
\newtheorem{proof}{Proof}

\title{\vspace{-1.5cm}Test Document}
\author{My Self}
\date{}

\begin{document}

\maketitle

\blindtext

\begin{theorem}
This is a theorema about right triangles and can be summarised in the next
equation\useshortskip
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\begin{lemma}
 This lemma doesn't provoke a general panic.
\end{lemma}

\section{New Section}

\begin{theorem}[Pythagorean theorem]
\label{pythagorean}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\begin{proof}
To prove it by contradiction try and assume that the statement is false,
proceed from there and at some point you will arrive to a contradiction. Hence
    \[ a^2 = b^2 + c^2. \]%
\end{proof}

\blindtext

\begin{corollary}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]

\end{corollary}

\end{document}

A: It is not very clear from the manual, but the source file (shadethm.sty) has some more information (from line 180 onwards):
The invocation possibilities are:
 \newshadetheorem{NAME}{TEXT}[COUNTER]
    e.g., \newshadetheorem{theorem}{Theorem}[section] meaning to allow
    one to say \begin{theorem} $e=mc^2$ \end{theorem} to produce
      Theorem 1.1.1 e=mc2
    shaded and numbered by section.
 \newshadetheorem{NAME}[OLDNAME]{TEXT}
    e.g., \newshadetheorem{remark}[theorem]{Remark} meaning to allow
    one to say \begin{remark} Obvious. \end{remark} to produce
      Remark 1.1.2  Obvious.
    shaded and numbered with the same counter used for theorems.

So when you want the theorems to be counted using an external counter then you put the argument after the theorem name, and when you want to use an internal counter then you put the argument in the middle.
There seems to be a bug when you want to use the same counter both externally and internally. If you want to do this a possible solution is to create a separate counter for the new environment by not using the optional argument, and then prefix this counter with the theorem counter by redefining the display macro (here \theshadecorollary).
MWE:
\documentclass[11pt]{article}
\usepackage{amsthm}
\usepackage{amssymb}
\usepackage{shadethm}
\renewcommand\qedsymbol{$\blacksquare$}

\newshadetheorem{theorem}{Theorem}
\newshadetheorem{corollary}{Corollary}
\newshadetheorem{lemma}[theorem]{Lemma}
% redefine display of corollary counter
\def\theshadecorollary{\arabic{shadetheorem}.\arabic{shadecorollary}}
% reset corollary counter when theorem counter is increased
\makeatletter
\@addtoreset{shadecorollary}{shadetheorem}
\makeatother

\title{Test Document}
\begin{document}

\maketitle
\begin{lemma}
This is a lemma
\end{lemma}

\begin{theorem}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\section{New Section}

\begin{theorem}[Pythagorean theorem]
\label{pythagorean}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]
\end{theorem}

\begin{proof}
To prove it by contradiction try and assume that the statement is false,
proceed from there and at some point you will arrive to a contradiction.
\end{proof}

\begin{corollary}
This is a theorema about right triangles and can be summarised in the next
equation
\[ x^2 + y^2 = z^2 \]

\end{corollary}

\begin{corollary}[Pythagorean theorem]
The following also holds:
\[ a^2 + b^2 = c^2 \]
\end{corollary}
\end{document}

Result:


text:
Q: How to sort Spring boot Pageable results I am returning a Page object from a JPA method(jpa method has some complex query and don't have the option to send sort within Pageable). I need to sort the results from the returned Page Object.
ex: Here we can do some manipulations in each object
public Page<SomeDTO> getResults() {
  return this.repository.someCustomRepoMethod(
            new OffsetBasedPageRequest(offset, size, SortUtils.getSort(sortOn, sortDir))
      ).map((element) -> someMethod(element));
}

I am expecting to have something similar but need to return Page with list sorted like
public Page<SomeDTO> getResults() {
  return this.repository.someCustomRepoMethod(
            new OffsetBasedPageRequest(offset, size, SortUtils.getSort(sortOn, sortDir))
      ).map((list) -> someSortingMethod(list));
}

public List<SomeDTO> someSortingMethod(list) {
  return list.sort(...).reversed())
}

is it possible, thanks.


text:
Q: How can I define a specific range for storing values in database? I want to know, how can I define a limited range (max and min) for storing values in table?
I want this range: [min: -99 , max: 999]
Also here is some example:
CREATE TABLE MyTable(
   id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
   code INT(11) NOT NULL
)

INSERT INTO MyTable (id,code)
             VALUES (1, 42),
             VALUES (2, -332),
             VALUES (3, -83),
             VALUES (4, 44324),
             VALUES (5, 0),
             VALUES (6, 999);

So, I want this output:
// MyTable
+----+------+
| id | code |
+----+------+
| 1  | 42   |
| 2  | -99  |
| 3  | -83  |
| 4  | 999  |
| 5  | 0    |
| 6  | 999  |
+----+------+

Well, How can I restrict my table for just accepting valid (in range) values or before storing, converts them to max/min value?

Or, If what I considered in above is not possible, Then how can I show the result as valid in range?
// MyTable
+----+------+
| id | code |
+----+------+
| 1  | 42   |
| 2  | -332 |
| 3  | -83  |
| 4  | 44324|
| 5  | 0    |
| 6  | 999  |
+----+------+

I want something like this query:
SELECT id, IF(LENGTH(code) > 999, '999', code)) AS FilteredCode FROM MyTable
// also I can not implement to filter negative values (-99) in my query

A: You can use the CHECK constraint like this:
CONSTRAINT code_fk CHECK (code  BETWEEN -99 AND 999)

So your table will be created as:
CREATE TABLE MyTable(
   id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
   code INT(11) NOT NULL,
   CONSTRAINT code_fk CHECK (code  BETWEEN -99 AND 999)
)

See the SQL FIDDLE DEMO

A: Using check constraint to do this below like:
CREATE TABLE MyTable(
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
code INT(11) NOT NULL,
CONSTRAINT code_fk CHECK (code  BETWEEN -99 AND 999)
)


text:
Q: SocketIO with Flask for specific page of a website I'm having a flask website with different apps in different routes:
@app.route('/')
def index():
    ......

@app.route('app1')
def app1():
    ......
    return render_template('app1.html')

@app.route('app2')
def app1():
    ......
    return render_template('app2.html')

......

app = Flask(__name__)

if __name__ == "__main__":
    app.run()

My question is how I can have another app3, if user go to that page, then use SocketIO (because that web page will handle real-time bidirectional communication) but without change existing structures (the other pages do NOT use socket).
I see the doc is using:
app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'
socketio = SocketIO(app)

if __name__ == '__main__':
    socketio.run(app)

Which run all of app with the socket.

A: What you did is the correct thing. The Socket.IO server will be activated only when a client connects to it. If your app1 and app2 pages do not initiate connections, then the Socket.IO server will pass-through those connections to Flask and only engage with the clients that are on the app3 page, assuming you add a Socket.IO client to that page.


text:
Q: Why is not working toogle button in navagation menu if I resize a windows? I have such navigation and it would be responsive, but if I resize the windoes toogle button appear but it does not working.

                 Welcome

            <button class="navbar-toggler"
                    type="button"
                    data-mdb-toggle="collapse"
                    data-mdb-target="#navbarButtonsExample"
                    aria-controls="navbarButtonsExample"
                    aria-expanded="false"
                    aria-label="Toggle navigation">

            </button>

                        Learning HUB

                        Upload files

                    <form method="post" asp-action="logout" asp-controller="account">
                        <button type="submit" class="nav-link btn btn-link py-0" style="width:auto">
                            @User.Identity.Name
                        </button>
                    </form>

JS Fiddler attached https://jsfiddle.net/mygus/z9o4wk7u/3/
What am I doing wrong?
Thank you,
M.

A: this worked for me.

                 Welcome

            <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarTogglerDemo01" aria-controls="navbarTogglerDemo01" aria-expanded="false" aria-label="Toggle navigation">

            </button>

                        Learning HUB

                        Upload files

                        List roles

                    <form method="post" asp-action="logout" asp-controller="account">
                        <button type="submit" class="nav-link btn btn-link py-0" style="width:auto">
                            @User.Identity.Name
                        </button>
                    </form>


text:
Q: Variable between worksheet and module not cooperating My Module1 macro doesn't see the value of variable stated in Worksheet code. Any idea why that is? Everything is public.
In my Worksheet I have this:
Public oldVal As Variant

Public Sub Worksheet_SelectionChange(ByVal Target As Range)
oldVal = Target.Value
End Sub

And in Module1 I have a macro connected to a button, that should (for testing purposes) just print the oldVal, but it isn't working. The message box is empty.
Public Sub button_Click1()
MsgBox oldVal
End Sub

Any idea why it isn't taking the value of the variable "OldVal" from the worksheet?
Thanks.

A: You should declare your Public variables in a regular module to avoid this.
Because Sheet's modules, ThisSession, ThisWorkbook, ... are class's modules and so the variable that you declare is considered as a property of that class/object.

Your regular module code
Public oldVal As Variant

Public Sub button_Click1()
    MsgBox oldVal
End Sub

Your Sheet module code
Public Sub Worksheet_SelectionChange(ByVal Target As Range)
     oldVal = Target.Value
End Sub

A: The oldVal is like a property of a class where class is the worksheet. Therefore use the name of the worksheet as well e.g. MsgBox Sheet1.oldVal
Maybe the variable oldVal should be implemented as read-only property in class of the worksheet. So it will be only possible to set the value in the class when the selection changes and not from outside of the worksheet class. Something like the following.

Worksheet class module:

Private m_oldVal As Variant

Public Property Get OldVal() As Variant
    OldVal = m_oldVal
End Property

Public Sub Worksheet_SelectionChange(ByVal Target As Range)
    m_oldVal = Target.Value
End Sub


text:
Q: Refresh content URI I receive multiple content URIs to gallery images with ACTION_GET_CONTENT and EXTRA_ALLOW_MULTIPLE. These images will later be uploaded to a server. The problem is that killing the activity seems to invalidate the URIs, I can't load the images anymore. Getting the same image again from the gallery returns the same URI and both the old and new URIs can be used again. I want these URIs valid after activity restart, so the selection holds for as long as the images aren't deleted. Is there some way to "refresh" the URIs I have saved? Copying the photos does not sound like a pleasant solution.

A: It works now, posted my solution here. Basically, you need two different intents for pre-kitkat and post-kitkat.


text:
Q: Hot add options for VCD using Terraform I've only started with Terraform and I'm trying to integrate its use into our VCD (VMware vCloud Director) environment.
I've found the provider config and have created a vapp and vm using Terraform but don't see any options to enable memory and cpu hot add. Is this something that can be done?

A: It will be better to provide the details, such as the terraform code you run with, what's the plan output.
I went through the offical document, and this resource supports cpu/memory.
resource "vsphere_virtual_machine" "vm" {
  name             = "terraform-test"
  resource_pool_id = "${data.vsphere_resource_pool.pool.id}"
  datastore_id     = "${data.vsphere_datastore.datastore.id}"

  num_cpus = 2
  memory   = 1024
  guest_id = "other3xLinux64Guest"

  network_interface {
    network_id = "${data.vsphere_network.network.id}"
  }

  disk {
    label = "disk0"
    size  = 20
  }
}

So what resource are you talking about?
Reference: https://www.terraform.io/docs/providers/vsphere/index.html


text:
Q: Mime-type problems with IE and wikipedia If I search for something on wikipedia with google and try to click through to one of the articles, IE8 prompts me to download the page as it doesn't understand the mime-type.
This has not always been the case. It started about 2 weeks ago. I had not changed any settings or installed any software.
At the time I checked my windows restore points and there were none within a few weeks of the symptom occuring.
Does anyone have any possible explanation for such behaviour?
32bit Vista SP2, IE8
UPDATE
OK. So this only happens when I try to click through to Wikipedia from some other site.
If I type wikipedia.org into my address bar and hit return it shows the page no problem.

A: I try guessing:
If you go to "Tools -> Internet Options -> Programs -> Manage Add-ons" you can see (using the "Show" drop-down box) which add-ons are currently loaded. Maybe IE does not load the appropriate add-on when needed. Have a look, if you can force it to do so.

A: First, have you tried to reproduce the issue by running Internet Explorer 8 in safe mode? I believe there is a shortcut in your start menu.  If the problem doesn't occur in safe mode, then start to eliminate add-ons...  (If you can't find the safe-mode option just skip to the add-ons section)
Add-Ons
You can modify add-ons by:

*

*Use alt key to bring up the drop down menu.

*Click on Tools -> Manage Add-Ons -> Enable / Disable Add ons.

You should then be looking at a page like the following.

From there, disable / remove any odd, unusual or unwanted add ons. If the problem continues to persist, I'd disable all add-ons to see if it resolves the actual problem.


text:
Q: Let other computers view local / Apache sites on my machine I'm currently using DAMP to build Drupal sites locally and wondered how I might go about letting users on other machines on my network view these sites?
Thanks!

A: -Simply add new VirtualHost for each site - for example "drupal1.test.local"
-than find out your local IP address - something like "192.168.1.25
-on other machines you have to edit "hosts" file > add a new line on the end of this file by pattern:
your-ip-address website

So by my example, it would look like:
192.168.1.25 drupal1.test.local

Hope it will help:)


text:
Q: Composer update gives error saying plugin could not be initialized, class not found for every package I've loaded up a vagrant box from scratch with an existing codebase that has been running on several machines for quite a while. When running composer update it always gives a similar issue:
  - Removing kylekatarnls/update-helper (1.1.1)

  [UnexpectedValueException]
  Plugin kylekatarnls/update-helper could not be initialized, class not found: UpdateHelper\ComposerPlugin

php -v:
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.1.0, Copyright (c) 1998-2018 Zend Technologies
    with Zend OPcache v7.1.30-1+ubuntu16.04.1+deb.sury.org+1, Copyright (c) 1999-2018, by Zend Technologies
    with Xdebug v2.7.1, Copyright (c) 2002-2019, by Derick Rethans

Composer version 1.8.6
I've tried changing versions of vagrant, virtualbox, php, xdebug, composer all to match versions running on other machines. I've tried composer clearcache, composer dump-autoload, various different composer update methods. Have tried deleting vendor folder and doing composer install

A: I had this issue in a Vagrant box, I removed php7.2-zip from installing and installed ONLY zip.
If I have them both installed, it fails, if I install only php-zip it failed. Not sure if this will help, but might give it a try.

A: Run composer update --no-plugins.


text:
Q: go html template table I want to make the table in HTML in go package "temlate" and i want to add rows in loop, but i didn't find how doing this
my code:
package main
import (
     "net/http"
     "html/template"
)
type Devicevalue_view struct {
    Devicetype string
    Iddevice   string
    Devicename string
    Oidname    string
    Value      string
  }
func page_1(w http.ResponseWriter, r *http.Request){
    for i:=1; i<10; i++{
        data := Devicevalue_view{
            Devicetype: "devicetype",
            Iddevice: "iddevice",
            Devicename: "devicename",
            Oidname: "oidname",
            Value: "value",
        }
        tmpl, _ := template.ParseFiles("./index.html")
        tmpl.Execute(w, data)
    }
}
func main() {
    http.HandleFunc("/table", page_1)
    http.ListenAndServe(":3000", nil)
}

i'm getting this :

Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
...

but i want somthing like this
Devices
Type    Name    Param   Time    Value
devicetype  iddevice    devicename  oidname value
devicetype  iddevice    devicename  oidname value
...

I don't undestand how connect all cells in one table
index.html:
https://drive.google.com/file/d/1HzEL0i3VhiafPzlV8iC0kU8WaSQwoYZY/view?usp=sharing

A: Because you are executing template inside for loop. Also you can pass a single struct. To pass array you have to pass it as a member of the struct.
package main

import (
    "html/template"
    "net/http"
)

type Data struct {
    Items []Devicevalue_view
}

type Devicevalue_view struct {
    Devicetype string
    Iddevice   string
    Devicename string
    Oidname    string
    Value      string
}

func page_1(w http.ResponseWriter, r *http.Request) {
    data := Data{}
    for i := 1; i < 10; i++ {
        view := Devicevalue_view{
            Devicetype: "devicetype",
            Iddevice:   "iddevice",
            Devicename: "devicename",
            Oidname:    "oidname",
            Value:      "value",
        }

        data.Items = append(data.Items, view)
    }

    tmpl, _ := template.ParseFiles("./index.html")
    tmpl.Execute(w, data)
}
func main() {
    http.HandleFunc("/table", page_1)
    http.ListenAndServe(":3000", nil)
}

Also you have to iterate through data and generate row dynamically.
<!DOCTYPE html>

        Type
        Name
        Param
        Time
        Value

    {{ range .Items}}

            {{ .Devicetype }}
            {{ .Iddevice }}
            {{ .Devicename }}
            {{ .Oidname }}
            {{ .Value }}

    {{ end}}