问:
How to save https response to variable and use for another function?
I would like to save nodejs https response for global variable and use it later. I know it is assync function but I'm not fully understand therefore I can not implement it. I would thanksfull if somebody can help me out and show me how to make it work.

The code:

```<code>function getPageContent() {

    const postData = `some data`;

    const options = {
        protocol: 'https:',
        host: 'sitepage',
        path: "/path",
        method: 'POST',
        headers: {
            "Authorization": "Bearer " + 'apikey'
        }
    };

    const req = https.request(options, (res) => {
        console.log('getPageContent statusCode:', res.statusCode);

        res.on('data', (d) => {
            answer += d;
            return answer   => This is what I would like to save.
        });

    });

    req.write(postData);
    req.end();
};

getPageContent()
console.log(answer)
</code>```

As an answer of console log I would like to see the https answer but with my code it is blank.

Body:
I would like to save nodejs https response for global variable and use it later. I know it is assync function but I'm not fully understand therefore I can not implement it. I would thanksfull if somebody can help me out and show me how to make it work.

The code:

function getPageContent() {

    const postData = `some data`;

    const options = {
        protocol: 'https:',
        host: 'sitepage',
        path: "/path",
        method: 'POST',
        headers: {
            "Authorization": "Bearer " + 'apikey'
        }
    };

    const req = https.request(options, (res) => {
        console.log('getPageContent statusCode:', res.statusCode);

        res.on('data', (d) => {
            answer += d;
            return answer   => This is what I would like to save.
        });

    });

    req.write(postData);
    req.end();
};

getPageContent()
console.log(answer)

As an answer of console log I would like to see the https answer but with my code it is blank.


来源: stackexchange

问:
nodejs websocket - how to connect and send data
I writing some test automation and need to connect and send some data.  When I run the below code the console.log's aren't run.  What am I missing?</p>
```<code>  import _WebSocket, { WebSocket } from 'ws';

  const ws = new _WebSocket("someURL?token=" + aToken)

  ws.on('open', () => {
    console.log(`conncted`);
    ws.send({
      requestId: asyncRequestId
    })
  });

  ws.on('message', (msg) => {
    console.log(`message form server ${msg}`);
  })
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I writing some test automation and need to connect and send some data.  When I run the below code the console.log's aren't run.  What am I missing?

  import _WebSocket, { WebSocket } from 'ws';

  const ws = new _WebSocket("someURL?token=" + aToken)

  ws.on('open', () => {
    console.log(`conncted`);
    ws.send({
      requestId: asyncRequestId
    })
  });

  ws.on('message', (msg) => {
    console.log(`message form server ${msg}`);
  })


问:
R Igraph: Finding all shortest paths for a million pair of nodes in a large network
I have a large network with 17,765 nodes and 7,4876 edges. I'm using igraph to run most of my analysis. I got stuck on finding the number of shortest paths for different pairs of nodes (around 1 million pairs). I don't need the paths, only their counts for each pair (how many exist). To do so, I'm iterating through the node pairs using a parallelized strategy together with the all_shortest_paths() function. It works for subsets of a few thousand node pairs; however, it is extremely slow, and I don't know how to optimize it. The code can be found below:

```<code>library(igraph)
library(doParallel)
library(foreach)

count_paths <- function(g,start,end) {
  #create the cluster
  my.cluster <- parallel::makeCluster(
    n.cores,
    type = "PSOCK")

  doParallel::registerDoParallel(my.cluster)

  foreach(i=1:length(start),.combine = "c") %dopar% {
    length(igraph::all_shortest_paths(g,
                                      from = start[i],
                                      to=end[i],
                                      mode = "all")[["res"]])
  }
}

counts<-count_paths(graph_directed,names(v_start),names(v_end))
stopCluster(my.cluster)
</code>```

I have opted for the "all" option in the all_shortest_paths() because I'm treating my graph as undirected.

Thanks in advance for your help :)

Body:
I have a large network with 17,765 nodes and 7,4876 edges. I'm using igraph to run most of my analysis. I got stuck on finding the number of shortest paths for different pairs of nodes (around 1 million pairs). I don't need the paths, only their counts for each pair (how many exist). To do so, I'm iterating through the node pairs using a parallelized strategy together with the all_shortest_paths() function. It works for subsets of a few thousand node pairs; however, it is extremely slow, and I don't know how to optimize it. The code can be found below:

library(igraph)
library(doParallel)
library(foreach)

count_paths <- function(g,start,end) {
  #create the cluster
  my.cluster <- parallel::makeCluster(
    n.cores,
    type = "PSOCK")

  doParallel::registerDoParallel(my.cluster)

  foreach(i=1:length(start),.combine = "c") %dopar% {
    length(igraph::all_shortest_paths(g,
                                      from = start[i],
                                      to=end[i],
                                      mode = "all")[["res"]])
  }
}

counts<-count_paths(graph_directed,names(v_start),names(v_end))
stopCluster(my.cluster)

I have opted for the "all" option in the all_shortest_paths() because I'm treating my graph as undirected.

Thanks in advance for your help :)


问:
Receiver class does not define or inherit an implementation of the interface java.lang.Comparable
I have been stumped on this issue for quite a while. Could not find anything wrong with my code online, everything regarding structure seems correct. Spits out error message:  "Receiver class ComparableTriangle does not define or inherit an implementation of the resolved method 'abstract int compareTo(java.lang.Object)' of interface java.lang.Comparable." (Line 118)

The compareTo method works correctly, just the Collections.sort does not work.

Any idea?

`

```<code>import java.lang.Math.*;
import java.math.*;
import java.util.*;

 class GeometricObject {

}

class Triangle extends GeometricObject {
    ... triangle parameters
}

class ComparableTriangle extends Triangle implements Comparable<Triangle>,Cloneable {
  /** Construct a ComparableTriangle with specified properties */
  public ComparableTriangle(double side1, double side2, double side3) {
    super(side1, side2, side3);
  }
  // Compares the object (t) to the parameter being input (t2)
  @Override public int compareTo(ComparableTriangle param) {
    if (this.getArea() > param.getArea()) { // this > t1
      System.out.println("Triangle 1 is bigger.");
      return 1;
    }
    else if (this.getArea() < param.getArea()) {
      System.out.println("Triangle 2 is bigger.");
      return -1;
    }
    else {
      System.out.println("Both triangles are equal.");
      return 0;
    }
  }
  // Clones the object input. Throws exception if not supported.
  protected Object clone() throws CloneNotSupportedException {
    {
        System.out.println(this.getArea());
        System.out.println(this.getPerimeter());
        return super.clone();
    }
  }
}

public class TriangleClass7A {
    public static void main(String[] args) {
        {
          ... variables
          ArrayList<ComparableTriangle> tri = new ArrayList<ComparableTriangle>();
          Scanner in = new Scanner(System.in);
          while (true) {
            ... variable input by user
            }
            ComparableTriangle t = new ComparableTriangle(side1,side2,side3);
            tri.add(t);
          }
          System.out.println("Done.");
          Collections.sort(tri);
        }
    }

}
</code>```

`

I have tried many small changes, but the structure seems to match every other implementation I have found online, but doesn't work in my code. Using Visual Studio Code if that at all matters.

Edit 1:
I tried changing the class to "class ComparableTriangle extends Triangle implements Comparable,Cloneable", but exact same error. No change at all.
Clarification: The error spit out by Collections.sort is a runtime error, not compiler error. If I only create one triangle object, the program works just fine.

Body:
I have been stumped on this issue for quite a while. Could not find anything wrong with my code online, everything regarding structure seems correct. Spits out error message:  "Receiver class ComparableTriangle does not define or inherit an implementation of the resolved method 'abstract int compareTo(java.lang.Object)' of interface java.lang.Comparable." (Line 118)

The compareTo method works correctly, just the Collections.sort does not work.

Any idea?

`

import java.lang.Math.*;
import java.math.*;
import java.util.*;

 class GeometricObject {

}

class Triangle extends GeometricObject {
    ... triangle parameters
}

class ComparableTriangle extends Triangle implements Comparable<Triangle>,Cloneable {
  /** Construct a ComparableTriangle with specified properties */
  public ComparableTriangle(double side1, double side2, double side3) {
    super(side1, side2, side3);
  }
  // Compares the object (t) to the parameter being input (t2)
  @Override public int compareTo(ComparableTriangle param) {
    if (this.getArea() > param.getArea()) { // this > t1
      System.out.println("Triangle 1 is bigger.");
      return 1;
    }
    else if (this.getArea() < param.getArea()) {
      System.out.println("Triangle 2 is bigger.");
      return -1;
    }
    else {
      System.out.println("Both triangles are equal.");
      return 0;
    }
  }
  // Clones the object input. Throws exception if not supported.
  protected Object clone() throws CloneNotSupportedException {
    {
        System.out.println(this.getArea());
        System.out.println(this.getPerimeter());
        return super.clone();
    }
  }
}

public class TriangleClass7A {
    public static void main(String[] args) {
        {
          ... variables
          ArrayList<ComparableTriangle> tri = new ArrayList<ComparableTriangle>();
          Scanner in = new Scanner(System.in);
          while (true) {
            ... variable input by user
            }
            ComparableTriangle t = new ComparableTriangle(side1,side2,side3);
            tri.add(t);
          }
          System.out.println("Done.");
          Collections.sort(tri);
        }
    }

}

`

I have tried many small changes, but the structure seems to match every other implementation I have found online, but doesn't work in my code. Using Visual Studio Code if that at all matters.

Edit 1:
I tried changing the class to "class ComparableTriangle extends Triangle implements Comparable,Cloneable", but exact same error. No change at all.
Clarification: The error spit out by Collections.sort is a runtime error, not compiler error. If I only create one triangle object, the program works just fine.


问:
Execute a PHP file built on the fly?
I have a web page that has input parameters for a php file that I want to execute on the server.

For example:
THe web asks for 2 variables (X & Y)

I then need to call a php file with X & Y
Php test.php -x "X" -y "Y"

But I'm stumped!

Title: Execute a PHP file built on the fly?


问:
Extracting the attributes(right most values) from pandas column using Python regex
Need to extract entities and attributes data using python regex and find all from pandas column.

```<code>source_data:
If `abc.num_id` is populated, then populate `"abc-e"`:
[xyz*bbbb_DEMO].[tag1/tag2/aaa/test]
[abc*XML].[/txn:msg/func/func2:xyz/attr:country]
[avc*ABCD_EF.[ISINSERT]
</code>```

Code used is:

df1['source_data'] = df1['source_data'].str.findall(r'\w*?.\w*?\ |\[\w*?\].\[\w*?\]').str.join(",")
df2 = df1.assign(source_data=df1['source_data'].str.split(',')).explode('source_data')
```
<p>Expected output:</p>
```print(df1) with entity:
abc.num_id
xyz*bbbb_DEMO.test
abc*XMLcountry
avc*ABCD_EF.ISINSERT

print(df2) only attributes right most
num_id
test
country
ISINSERT
```

Body:
Need to extract entities and attributes data using python regex and find all from pandas column.

source_data:
If `abc.num_id` is populated, then populate `"abc-e"`:
[xyz*bbbb_DEMO].[tag1/tag2/aaa/test]
[abc*XML].[/txn:msg/func/func2:xyz/attr:country]
[avc*ABCD_EF.[ISINSERT]

Code used is:

df1['source_data'] = df1['source_data'].str.findall(r'\w*?.\w*?\ |\[\w*?\].\[\w*?\]').str.join(",")
df2 = df1.assign(source_data=df1['source_data'].str.split(',')).explode('source_data')

Expected output:

print(df1) with entity:
abc.num_id
xyz*bbbb_DEMO.test
abc*XMLcountry
avc*ABCD_EF.ISINSERT

print(df2) only attributes right most
num_id
test
country
ISINSERT


问:
what is _ pattern in python?
I am new to python and I was trying to understand decorators. In serveral answers, I have seen people defining functions like _xyx_(someparams)

Example

```<code>class Pizza(object):
  def __init__(self):
    self.toppings = []

 def __call__(self, topping): # When using
</code>```

Title: what is _ pattern in python?

Body:
I am new to python and I was trying to understand decorators. In serveral answers, I have seen people defining functions like _xyx_(someparams)

Example

class Pizza(object):
  def __init__(self):
    self.toppings = []

 def __call__(self, topping): # When using


问:
ESN slow to train model
I have been using Keras Conv1D layer to train a forecast model. Like this:

```<code>model = Sequential(name='Conv1D_NE')
        model.add(InputLayer((57, 1), name='Input_Layer'))
        model.add(Conv1D(filters=256, kernel_size=4, activation=['tanh'], name='1_Camada_Conv'))
        model.add(MaxPooling1D(pool_size=1))
        model.add(Flatten())
        model.add(Dropout(0.25))
        model.add(Dense(units=48, activation=['tanh'], name='1_Dense'))
        model.add(Dense(units=72, activation=['tanh'], name='2_Dense'))
        model.add(Dense(units=24, activation=['tanh'], name='Output_Layer'))
        model.compile(optimizer='adam', loss='mean_squared_error')
</code>```

The above model has:

```<code>Total params: 670,160
Trainable params: 670,160
</code>```

And it takes around 1.64 min to train.
I also need to train an ESN (from tensor flow addons) to compare it with my Conv1D model. So, i created the following model:

```<code>model = Sequential(name='ESN_NE')
        model.add(InputLayer((57, 1), name='Input_Layer'))
        model.add(ESN(units=200, activation=['tanh'], name='ESN'))
        # model.add(Flatten())
        model.add(Dense(units=100, activation=['tanh'], name='1_Dense'))
        model.add(Dense(units=48, activation=['tanh'], name='2_Dense'))
        model.add(Dense(units=24, activation=['tanh'], name='Output_Layer'))
        model.compile(optimizer='adam', loss='mean_squared_error')
</code>```

This model has:

```<code>Total params: 66,524
Trainable params: 26,124
</code>```

and it takes around 7.29 min to train.

As aditional info, my x_train has shape (1823, 57, 1) and y_train has shape (1823, 24). Both models were trained with the same batch_size=32 and epochs=500.

Why is my ESN models taking so long to train? This kind of model are harder to train than a Conv1D, even having a lot less trainable parameters?
And related to the Flatten() layer, should i also use it in my ESN model before the Dense layers (like i did in the Conv1D model)?

Title: ESN slow to train model

Body:
I have been using Keras Conv1D layer to train a forecast model. Like this:

model = Sequential(name='Conv1D_NE')
        model.add(InputLayer((57, 1), name='Input_Layer'))
        model.add(Conv1D(filters=256, kernel_size=4, activation=['tanh'], name='1_Camada_Conv'))
        model.add(MaxPooling1D(pool_size=1))
        model.add(Flatten())
        model.add(Dropout(0.25))
        model.add(Dense(units=48, activation=['tanh'], name='1_Dense'))
        model.add(Dense(units=72, activation=['tanh'], name='2_Dense'))
        model.add(Dense(units=24, activation=['tanh'], name='Output_Layer'))
        model.compile(optimizer='adam', loss='mean_squared_error')

The above model has:

Total params: 670,160
Trainable params: 670,160

And it takes around 1.64 min to train.
I also need to train an ESN (from tensor flow addons) to compare it with my Conv1D model. So, i created the following model:

model = Sequential(name='ESN_NE')
        model.add(InputLayer((57, 1), name='Input_Layer'))
        model.add(ESN(units=200, activation=['tanh'], name='ESN'))
        # model.add(Flatten())
        model.add(Dense(units=100, activation=['tanh'], name='1_Dense'))
        model.add(Dense(units=48, activation=['tanh'], name='2_Dense'))
        model.add(Dense(units=24, activation=['tanh'], name='Output_Layer'))
        model.compile(optimizer='adam', loss='mean_squared_error')

This model has:

Total params: 66,524
Trainable params: 26,124

and it takes around 7.29 min to train.

As aditional info, my x_train has shape (1823, 57, 1) and y_train has shape (1823, 24). Both models were trained with the same batch_size=32 and epochs=500.

Why is my ESN models taking so long to train? This kind of model are harder to train than a Conv1D, even having a lot less trainable parameters?
And related to the Flatten() layer, should i also use it in my ESN model before the Dense layers (like i did in the Conv1D model)?


问:
Citations/References using Pandoc (via LaTeX) to export to PDF from Obsidian (markdown): How to have Pandoc just use my text for citations
The source are markdown files created in Obsidian.

I would like to use Pandoc and LaTeX to automatically cite my sources. I have the bib file all set up, and the LaTeX part too, and directly in a LaTeX editor I can use \cite{Smith2020}to reference a source, and it is then rendered as Smith 2020.

Now I’d just like to be able to include that type of citation in my markdown files so I can then export those to PDF via LaTeX.

Right now when I export this kind of citation it just outputs the citekey itself, with no change.

How can I fix this?

Thank you!

Edit: minimal example:

```<code>This is a citation \cite{Murray1837Encyclopedia}
This is another citation [@Murray1837Encyclopedia]
</code>```

arguments used for pandoc: --biblatex

Edit2: another example:

Example .md file:

```<code>---
bibliography: path/to/.bib/file
csl: https://gist.githubusercontent.com/bwiernik/6b60a0e21ad6b63516a85c305a0d25ad/raw/6e9168cde23fb327d9c483e64cbdfd09e3437851/chicago-author-date-footnotes.csl
---
This is a citation \cite{Murray1837Encyclopedia}
[[@Murray1837Encyclopedia]]This is another citation
</code>```

With the frontmatter as such this, Pandoc can render the second citation [[@blabla]] as Bla bla, p. x. I got this to work a couple hours ago, now it will no longer do it.

Regardless, I would like Pandoc to just ignore citations that look like this \cite{blabla} and have LaTeX handle it.

LaTeX can then turn \cite{blabla} into my desired format, namely Bla Bla 2020, 5-10, etc.

How do I get Pandoc to ignore these citations? As it stands, Pandoc removes the command part, and leaves only the citekey, the thing in the brackets.

Body:
The source are markdown files created in Obsidian.

I would like to use Pandoc and LaTeX to automatically cite my sources. I have the bib file all set up, and the LaTeX part too, and directly in a LaTeX editor I can use \cite{Smith2020}to reference a source, and it is then rendered as Smith 2020.

Now I’d just like to be able to include that type of citation in my markdown files so I can then export those to PDF via LaTeX.

Right now when I export this kind of citation it just outputs the citekey itself, with no change.

How can I fix this?

Thank you!

Edit: minimal example:

This is a citation \cite{Murray1837Encyclopedia}
This is another citation [@Murray1837Encyclopedia]

arguments used for pandoc: --biblatex

Edit2: another example:

Example .md file:

---
bibliography: path/to/.bib/file
csl: https://gist.githubusercontent.com/bwiernik/6b60a0e21ad6b63516a85c305a0d25ad/raw/6e9168cde23fb327d9c483e64cbdfd09e3437851/chicago-author-date-footnotes.csl
---
This is a citation \cite{Murray1837Encyclopedia}
[[@Murray1837Encyclopedia]]This is another citation

With the frontmatter as such this, Pandoc can render the second citation [[@blabla]] as Bla bla, p. x. I got this to work a couple hours ago, now it will no longer do it.

Regardless, I would like Pandoc to just ignore citations that look like this \cite{blabla} and have LaTeX handle it.

LaTeX can then turn \cite{blabla} into my desired format, namely Bla Bla 2020, 5-10, etc.

How do I get Pandoc to ignore these citations? As it stands, Pandoc removes the command part, and leaves only the citekey, the thing in the brackets.


问:
Identify index in Indexed K8s Job contributing to BackoffLimitExceeded Job failure
I have an indexed k8s job with thousands of indexes. When job fails due to BackoffLimitExceeded, it is hard to identify the exact index or set of indexes that caused the failure. Is there an easier way to identify the failing indexes from the Job APIs?

Currently, I have to go through logs from over 1k pods to identify the erroring pod(s).


问:
How do I add a scoring system to my python game that deducts points when I am wrong and gives me points when I am right
I have been working on this project for the past 2 days and I am nearly finished but I would really like to add a working scoring system but I couldn't find any answers on google. Pls Send Help.

```<code>import random

score = 0

def main():

    bet = input("Place Your Bet On A Number From 1-10 (quit to exit): ")

    number = random.randint(1, 10)

    if(bet == number):

        global score
        score+=1
        print("Correct!, ", score)
        print(" ")

    else:
        score-=1
        print("Incorrect!, ", score)
        print(" ")
        print("Your Bet: ", bet)
        print("The ACTUAL number: ", number)
        print(" ")

    if(bet == "quit"):
        exit()

while True:
    main()

</code>```

I tried adding a scoring system to my game but it kept deducting points even though I was right. I searched on google but all of the answers were outdated and didn't work on my program.

Body:
I have been working on this project for the past 2 days and I am nearly finished but I would really like to add a working scoring system but I couldn't find any answers on google. Pls Send Help.

import random

score = 0

def main():

    bet = input("Place Your Bet On A Number From 1-10 (quit to exit): ")

    number = random.randint(1, 10)

    if(bet == number):

        global score
        score+=1
        print("Correct!, ", score)
        print(" ")

    else:
        score-=1
        print("Incorrect!, ", score)
        print(" ")
        print("Your Bet: ", bet)
        print("The ACTUAL number: ", number)
        print(" ")

    if(bet == "quit"):
        exit()

while True:
    main()

I tried adding a scoring system to my game but it kept deducting points even though I was right. I searched on google but all of the answers were outdated and didn't work on my program.


问:
Django modelAdmin create or update exist instance in creation form
I need a creation form in my model admin, so that if a user exists with that phone(email) use it or create a new one because I have an inline form that needs an instance of the user model.

In the fact, I have a model that foreign key to the User Model I create an inline form for it, and its shows in my admin for the User model. And when I try to create a new user with a different unique field it's created as well with the inline data for it but when trying to create with field with the same unique its throws an error to me that the user with this data exists but I want in that situation use existing user and add inline data to that


问:
'listdlg' function, multiple selection
I am using 'listdlg' function with the Mutiple selection, so the user can select two different items from a list with Mutiple items. When two items are selected, I want the program to plot one bar graph. How would use 'if' or 'case' statements to do this.
The list:
rain
sun
snow
wind

for example, if 'rain and sun' are selected, it plots (x,y)
whereas if 'snow' and 'wind' are selected, it plots (s,t)
any help would be much appreciated thanks alot.

I used 'case statements', the case statements work however they just don't do what's expected

Title: 'listdlg' function, multiple selection


问:
GTest cannot load imported share library
I am trying to use a few imported shared libraries in a project which is to be tested through GTest. If I create test executables manually (e.g. without GTest), everything works fine. However, when enabling executables that rely on GTest, the build crashes with the following error:

```<code><path to build dir>/test_gtest: error while loading shared libraries: ./libDependencyL2.so: >cannot open shared object file: No such file or directory
CMake Error at /usr/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:112 (message):
 Error running test executable.
   Path: '<path to build dir>/test_gtest/test_gtest'
   Result: 127
   Output:
Call Stack (most recent call first):
   /usr/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:225 (gtest_discover_tests_impl)
</code>```

I am using CMake as the build system. Compilation and running take place on a x86 Ubuntu 20.04.

Project structure

My directory structure is:

```<code>test_project/
    CMakeLists.txt
    src/
        test_handcrafted/
            CMakeLists.txt
            test_handcrafted.cpp
        test_gtest/
            CMakeLists.txt
            test_gtest.cpp
        test_utils
            CMakeLists.txt
            test_utils.cpp
            test_utils.hpp
    lib/
        libTarget.so
        Target.hpp
        libDependencyLevel1.so
        DependencyLevel1.hpp
        libDependencyLevel2.so
        DependencyLevel2.hpp
    build/
</code>```

libTarget.so contains the functionalities to be verified. libDependencyLevel1.so contains utils for visualizing test outputs and it depends on libDependencyLevel2.so. test_utils contains all functions and classes that are actually called by the tests.

For instance, the command $ldd libDependencyLevel1.so returns:

```<code>linux-vdso.so.1 (0x00007fff17bb6000)
libDependencyLevel2.so => not found
libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fe5f3357000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fe5f333c000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe5f314a000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fe5f2ffb000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe5f358d000)
</code>```

Build system

test_project/CMakeLists.txt

```<code>project(MY_TEST)
cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(ExternalProject)

add_library(libTarget SHARED IMPORTED)
set_target_properties(libTarget PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libTarget.so"
)

add_library(libDependencyLevel2 SHARED IMPORTED)
set_target_properties(libDependencyLevel2 PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libDependencyLevel2.so"
)

add_library(libDependencyLevel1 SHARED IMPORTED)
set_target_properties(libDependencyLevel2 PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libDependencyLevel2.so"
)
add_dependencies(libDependencyLevel1 libDependencyLevel2)

include(FetchContent)
FetchContent_Declare(
    googletest
    URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)

set(MY_LIBRARIES_HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/lib)

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_utils)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_handcrafted)
# add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_gtest) # UNCOMMENTING THIS LINE CAUSES BUILD ERROR
</code>```

src/test_utils/CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_library(test_utils test_utils.cpp)

target_include_directories(test_utils PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    MY_LIBRARIES_HEADERS_DIR
)

target_link_libraries(test_utils PUBLIC libTarget libDependencyLevel1 libDependencyLevel2)
</code>```

src/test_handcrafted/CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(test_handcrafted test_handcrafted.cpp)

target_link_libraries(test_handcrafted PRIVATE libTarget test_utils)
</code>```

src/test_gtest/CMakeLists.txt

```<code>cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(test_gtest test_gtest.cpp)

target_link_libraries(test_gtest PRIVATE libTarget test_utils GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(test_gtest)

</code>```

Finally, when building test_handcrafted.cpp we can also check its dependencies ldd test_handcrafted:

```<code>linux-vdso.so.1 (0x00007ffdaa561000)
libTarget.so => <path to repo dir>/lib/libTarget.so (0x00007ff7ab7ab000)
../lib/libDependencyLevel1.so (0x00007ff7ab76d000)
../lib/libDependencyLevel2.so (0x00007ff7ab612000)
libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ff7ab3e5000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007ff7ab294000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007ff7ab279000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff7ab087000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007ff7ab064000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007ff7ab05e000)
./libDependencyLevel2.so => not found
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007ff7ab040000)
libjpeg.so.8 => /lib/x86_64-linux-gnu/libjpeg.so.8 (0x00007ff7aafbb000)
/lib64/ld-linux-x86-64.so.2 (0x00007ff7ac01b000)
</code>```

Unsuccessful solution attempts

Here is a list of things I have tried without success to solve the issue:

target_link_libraries on test_project/CMakeLists.txt

```<code>target_link_libraries(libDependencyLevel1 PUBLIC libDependencyLevel2) # INTERFACE and PRIVATE specifiers were also evaluated
</code>```

link_directories on test_project/CMakeLists.txt

```<code>link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib)
</code>```

Reasoning and questions

According to the error message shown in the beginning of this post, the build system is not finding the shared libraries needed when GTest is used. But why is this happening? And why not using GTest solves the linking error, even if the IMPORTED SHARED libraries are imported in the same way for building both executables?

Finally, what can I do to solve the building issue when using GTest?

Body:
I am trying to use a few imported shared libraries in a project which is to be tested through GTest. If I create test executables manually (e.g. without GTest), everything works fine. However, when enabling executables that rely on GTest, the build crashes with the following error:

<path to build dir>/test_gtest: error while loading shared libraries: ./libDependencyL2.so: >cannot open shared object file: No such file or directory
CMake Error at /usr/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:112 (message):
 Error running test executable.
   Path: '<path to build dir>/test_gtest/test_gtest'
   Result: 127
   Output:
Call Stack (most recent call first):
   /usr/share/cmake-3.24/Modules/GoogleTestAddTests.cmake:225 (gtest_discover_tests_impl)

I am using CMake as the build system. Compilation and running take place on a x86 Ubuntu 20.04.

Project structure

My directory structure is:

test_project/
    CMakeLists.txt
    src/
        test_handcrafted/
            CMakeLists.txt
            test_handcrafted.cpp
        test_gtest/
            CMakeLists.txt
            test_gtest.cpp
        test_utils
            CMakeLists.txt
            test_utils.cpp
            test_utils.hpp
    lib/
        libTarget.so
        Target.hpp
        libDependencyLevel1.so
        DependencyLevel1.hpp
        libDependencyLevel2.so
        DependencyLevel2.hpp
    build/

libTarget.so contains the functionalities to be verified. libDependencyLevel1.so contains utils for visualizing test outputs and it depends on libDependencyLevel2.so. test_utils contains all functions and classes that are actually called by the tests.

For instance, the command $ldd libDependencyLevel1.so returns:

linux-vdso.so.1 (0x00007fff17bb6000)
libDependencyLevel2.so => not found
libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007fe5f3357000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007fe5f333c000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007fe5f314a000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007fe5f2ffb000)
/lib64/ld-linux-x86-64.so.2 (0x00007fe5f358d000)

Build system

test_project/CMakeLists.txt

project(MY_TEST)
cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

include(ExternalProject)

add_library(libTarget SHARED IMPORTED)
set_target_properties(libTarget PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libTarget.so"
)

add_library(libDependencyLevel2 SHARED IMPORTED)
set_target_properties(libDependencyLevel2 PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libDependencyLevel2.so"
)

add_library(libDependencyLevel1 SHARED IMPORTED)
set_target_properties(libDependencyLevel2 PROPERTIES
    IMPORTED_LOCATION "${CMAKE_CURRENT_SOURCE_DIR}/lib/libDependencyLevel2.so"
)
add_dependencies(libDependencyLevel1 libDependencyLevel2)

include(FetchContent)
FetchContent_Declare(
    googletest
    URL https://github.com/google/googletest/archive/03597a01ee50ed33e9dfd640b249b4be3799d395.zip
)

set(MY_LIBRARIES_HEADERS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/lib)

add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_utils)
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_handcrafted)
# add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/src/test_gtest) # UNCOMMENTING THIS LINE CAUSES BUILD ERROR

src/test_utils/CMakeLists.txt

cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_library(test_utils test_utils.cpp)

target_include_directories(test_utils PUBLIC
    ${CMAKE_CURRENT_SOURCE_DIR}
    MY_LIBRARIES_HEADERS_DIR
)

target_link_libraries(test_utils PUBLIC libTarget libDependencyLevel1 libDependencyLevel2)

src/test_handcrafted/CMakeLists.txt

cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(test_handcrafted test_handcrafted.cpp)

target_link_libraries(test_handcrafted PRIVATE libTarget test_utils)

src/test_gtest/CMakeLists.txt

cmake_minimum_required(VERSION 3.22)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

add_executable(test_gtest test_gtest.cpp)

target_link_libraries(test_gtest PRIVATE libTarget test_utils GTest::gtest_main)

include(GoogleTest)
gtest_discover_tests(test_gtest)

Finally, when building test_handcrafted.cpp we can also check its dependencies ldd test_handcrafted:

linux-vdso.so.1 (0x00007ffdaa561000)
libTarget.so => <path to repo dir>/lib/libTarget.so (0x00007ff7ab7ab000)
../lib/libDependencyLevel1.so (0x00007ff7ab76d000)
../lib/libDependencyLevel2.so (0x00007ff7ab612000)
libstdc++.so.6 => /lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007ff7ab3e5000)
libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007ff7ab294000)
libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007ff7ab279000)
libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff7ab087000)
libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007ff7ab064000)
libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007ff7ab05e000)
./libDependencyLevel2.so => not found
libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (0x00007ff7ab040000)
libjpeg.so.8 => /lib/x86_64-linux-gnu/libjpeg.so.8 (0x00007ff7aafbb000)
/lib64/ld-linux-x86-64.so.2 (0x00007ff7ac01b000)

Unsuccessful solution attempts

Here is a list of things I have tried without success to solve the issue:

target_link_libraries on test_project/CMakeLists.txt

target_link_libraries(libDependencyLevel1 PUBLIC libDependencyLevel2) # INTERFACE and PRIVATE specifiers were also evaluated

link_directories on test_project/CMakeLists.txt

link_directories(${CMAKE_CURRENT_SOURCE_DIR}/lib)

Reasoning and questions

According to the error message shown in the beginning of this post, the build system is not finding the shared libraries needed when GTest is used. But why is this happening? And why not using GTest solves the linking error, even if the IMPORTED SHARED libraries are imported in the same way for building both executables?

Finally, what can I do to solve the building issue when using GTest?


问:
How can docker understand if request call is make for internal or external if using ip only
I am newbie in Docker and trying to catch up. Considering a docker container with a Java application, and a external database server (not in host system, but remote to host system) with ip 10.24.198.1 and it is passed to docker as environment parameter

```<code>docker run ... -e JDBC_URL="jdbc:mysql://10.24.198.1:3306/serverTimezone=UTC&useSSL=true"
</code>```

I have a few questions

How can docker tell if the datasource is made to be internal (based on ip) or external (so to make attempt to connect externally)?

How to inform Docker container that the jdbc datasource is external so do not make attempt to make internal validation.

What is functional difference to set the JDBC value via -e parameter or define it in Dockerfile, other than flexibility (dynamic setting via -e vs hard coded in Dockerfile)

Body:
I am newbie in Docker and trying to catch up. Considering a docker container with a Java application, and a external database server (not in host system, but remote to host system) with ip 10.24.198.1 and it is passed to docker as environment parameter

docker run ... -e JDBC_URL="jdbc:mysql://10.24.198.1:3306/serverTimezone=UTC&useSSL=true"

I have a few questions

How can docker tell if the datasource is made to be internal (based on ip) or external (so to make attempt to connect externally)?

How to inform Docker container that the jdbc datasource is external so do not make attempt to make internal validation.

What is functional difference to set the JDBC value via -e parameter or define it in Dockerfile, other than flexibility (dynamic setting via -e vs hard coded in Dockerfile)


问:
letter_opener tab displaying nothing
I am new to rails and I have an application that is supposed to send a confirmation email after creating a booking however, when I go to the /letter_opener tab after creating a booking nothing shows up

application_mailer.rb

```<code>class ApplicationMailer < ActionMailer::Base
default from: "support@flightbooker.com"
layout "mailer"
end
</code>```

passenger_mailer.rb

```<code>class PassengerMailer < ApplicationMailer

 def booking_confirmation
    @passenger = params[:passenger]
    @booking = params[:booking]
    @flight = params[:flight]

    mail(to: @passenger.email, subject: "Confirmation Email")
end

end
</code>```

bookings_controller.rb

```<code> class BookingsController < ApplicationController

 include BookingsHelper

 def new
    @booking = Booking.new
    @selected_flight = Flight.find(params[:flight])
    @passengers_count = params[:passengers].to_i
    @passengers_count.times{@booking.passengers.build}
 end

 def create

    @booking = Booking.new(booking_params)

    if @booking.save

    @booking.passengers.each do |pax|
        PassengerMailer.with(passenger: pax).booking_confirmation.deliver_now
      end

        flash[:success] = 'Booking saved!'
        redirect_to booking_path(@booking)
    else
        flash[:alert] = "An error has occured!"
        render "new"
    end
 end

 def show

    @booking = Booking.find(params[:id])
 end

end
</code>```

Gemfile

```<code> source "https://rubygems.org"
 git_source(:github) { |repo| "https://github.com/#{repo}.git" }

 ruby "3.1.2"

 # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
 gem "rails", "~> 7.0.4"

 # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
 gem "sprockets-rails"

 # Use sqlite3 as the database for Active Record
 gem "sqlite3", "~> 1.4"

 # Use the Puma web server [https://github.com/puma/puma]
 gem "puma", "~> 5.0"

 # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
 gem "importmap-rails"

# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"

# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"

# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"

# Use Kredis to get higher-level data types in Redis
[https://github.com/rails/kredis]
# gem "kredis"

# Use Active Model has_secure_password
[https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false

# Use Sass to process CSS
# gem "sassc-rails"

# Use Active Storage variants
[https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"

group :development, :test do
</code>```

See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-

```<code>the-debug-gem
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  # Use console on exceptions pages [https://github.com/rails/web-console]
 gem "web-console"

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"

  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
  # gem "spring"

  gem 'letter_opener_web'

end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"

end
</code>```

development.rb

```<code>require "active_support/core_ext/integer/time"

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded any time
  # it changes. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable server timing
  config.server_timing = true

  # Enable/disable caching. By default caching is disabled.
  # Run rails dev:cache to toggle caching.
     if Rails.root.join("tmp/caching-dev.txt").exist?
    config.action_controller.perform_caching = true
    config.action_controller.enable_fragment_cache_logging = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      "Cache-Control" => "public, max-age=#{2.days.to_i}"
     }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Store uploaded files on the local file system (see config/storage.yml for
options).
  config.active_storage.service = :local

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.perform_deliveries = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise exceptions for disallowed deprecations.
  config.active_support.disallowed_deprecation = :raise

  # Tell Active Support which deprecation messages to disallow.
  config.active_support.disallowed_deprecation_warnings = []

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Highlight code that triggered database queries in logs.
   config.active_record.verbose_query_logs = true

 # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations.
  # config.i18n.raise_on_missing_translations = true

  # Annotate rendered view with file names.
  # config.action_view.annotate_rendered_view_with_filenames = true

  # Uncomment if you wish to allow Action Cable access from any origin.
  # config.action_cable.disable_request_forgery_protection = true

end
</code>```

routes.rb

```<code>Rails.application.routes.draw do
  # Define your application routes per the DSL in
https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  root "flights#index"

  resources :flights
  resources :airports
  resources :bookings

  mount LetterOpenerWeb::Engine, at: "/letter_opener" if Rails.env.development?
end
</code>```

if you still need more code here is a link to my github  https://github.com/Michael-Mehta/odin-flight-booker

Title: letter_opener tab displaying nothing

Body:
I am new to rails and I have an application that is supposed to send a confirmation email after creating a booking however, when I go to the /letter_opener tab after creating a booking nothing shows up

application_mailer.rb

class ApplicationMailer < ActionMailer::Base
default from: "support@flightbooker.com"
layout "mailer"
end

passenger_mailer.rb

class PassengerMailer < ApplicationMailer

 def booking_confirmation
    @passenger = params[:passenger]
    @booking = params[:booking]
    @flight = params[:flight]

    mail(to: @passenger.email, subject: "Confirmation Email")
end

end

bookings_controller.rb

 class BookingsController < ApplicationController

 include BookingsHelper

 def new
    @booking = Booking.new
    @selected_flight = Flight.find(params[:flight])
    @passengers_count = params[:passengers].to_i
    @passengers_count.times{@booking.passengers.build}
 end

 def create

    @booking = Booking.new(booking_params)

    if @booking.save

    @booking.passengers.each do |pax|
        PassengerMailer.with(passenger: pax).booking_confirmation.deliver_now
      end

        flash[:success] = 'Booking saved!'
        redirect_to booking_path(@booking)
    else
        flash[:alert] = "An error has occured!"
        render "new"
    end
 end

 def show

    @booking = Booking.find(params[:id])
 end

end

Gemfile

 source "https://rubygems.org"
 git_source(:github) { |repo| "https://github.com/#{repo}.git" }

 ruby "3.1.2"

 # Bundle edge Rails instead: gem "rails", github: "rails/rails", branch: "main"
 gem "rails", "~> 7.0.4"

 # The original asset pipeline for Rails [https://github.com/rails/sprockets-rails]
 gem "sprockets-rails"

 # Use sqlite3 as the database for Active Record
 gem "sqlite3", "~> 1.4"

 # Use the Puma web server [https://github.com/puma/puma]
 gem "puma", "~> 5.0"

 # Use JavaScript with ESM import maps [https://github.com/rails/importmap-rails]
 gem "importmap-rails"

# Hotwire's SPA-like page accelerator [https://turbo.hotwired.dev]
gem "turbo-rails"

# Hotwire's modest JavaScript framework [https://stimulus.hotwired.dev]
gem "stimulus-rails"

# Build JSON APIs with ease [https://github.com/rails/jbuilder]
gem "jbuilder"

# Use Redis adapter to run Action Cable in production
# gem "redis", "~> 4.0"

# Use Kredis to get higher-level data types in Redis
[https://github.com/rails/kredis]
# gem "kredis"

# Use Active Model has_secure_password
[https://guides.rubyonrails.org/active_model_basics.html#securepassword]
# gem "bcrypt", "~> 3.1.7"

# Windows does not include zoneinfo files, so bundle the tzinfo-data gem
gem "tzinfo-data", platforms: %i[ mingw mswin x64_mingw jruby ]

# Reduces boot times through caching; required in config/boot.rb
gem "bootsnap", require: false

# Use Sass to process CSS
# gem "sassc-rails"

# Use Active Storage variants
[https://guides.rubyonrails.org/active_storage_overview.html#transforming-images]
# gem "image_processing", "~> 1.2"

group :development, :test do

See https://guides.rubyonrails.org/debugging_rails_applications.html#debugging-with-

the-debug-gem
gem "debug", platforms: %i[ mri mingw x64_mingw ]
end

group :development do
  # Use console on exceptions pages [https://github.com/rails/web-console]
 gem "web-console"

  # Add speed badges [https://github.com/MiniProfiler/rack-mini-profiler]
  # gem "rack-mini-profiler"

  # Speed up commands on slow machines / big apps [https://github.com/rails/spring]
  # gem "spring"

  gem 'letter_opener_web'

end

group :test do
  # Use system testing [https://guides.rubyonrails.org/testing.html#system-testing]
  gem "capybara"
  gem "selenium-webdriver"
  gem "webdrivers"

end

development.rb

require "active_support/core_ext/integer/time"

Rails.application.configure do
  # Settings specified here will take precedence over those in config/application.rb.

  # In the development environment your application's code is reloaded any time
  # it changes. This slows down response time but is perfect for development
  # since you don't have to restart the web server when you make code changes.
  config.cache_classes = false

  # Do not eager load code on boot.
  config.eager_load = false

  # Show full error reports.
  config.consider_all_requests_local = true

  # Enable server timing
  config.server_timing = true

  # Enable/disable caching. By default caching is disabled.
  # Run rails dev:cache to toggle caching.
     if Rails.root.join("tmp/caching-dev.txt").exist?
    config.action_controller.perform_caching = true
    config.action_controller.enable_fragment_cache_logging = true

    config.cache_store = :memory_store
    config.public_file_server.headers = {
      "Cache-Control" => "public, max-age=#{2.days.to_i}"
     }
  else
    config.action_controller.perform_caching = false

    config.cache_store = :null_store
  end

  # Store uploaded files on the local file system (see config/storage.yml for
options).
  config.active_storage.service = :local

  # Don't care if the mailer can't send.
  config.action_mailer.raise_delivery_errors = true

  config.action_mailer.delivery_method = :letter_opener
  config.action_mailer.perform_deliveries = true

  config.action_mailer.perform_caching = false

  # Print deprecation notices to the Rails logger.
  config.active_support.deprecation = :log

  # Raise exceptions for disallowed deprecations.
  config.active_support.disallowed_deprecation = :raise

  # Tell Active Support which deprecation messages to disallow.
  config.active_support.disallowed_deprecation_warnings = []

  # Raise an error on page load if there are pending migrations.
  config.active_record.migration_error = :page_load

  # Highlight code that triggered database queries in logs.
   config.active_record.verbose_query_logs = true

 # Suppress logger output for asset requests.
  config.assets.quiet = true

  # Raises error for missing translations.
  # config.i18n.raise_on_missing_translations = true

  # Annotate rendered view with file names.
  # config.action_view.annotate_rendered_view_with_filenames = true

  # Uncomment if you wish to allow Action Cable access from any origin.
  # config.action_cable.disable_request_forgery_protection = true

end

routes.rb

Rails.application.routes.draw do
  # Define your application routes per the DSL in
https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  root "flights#index"

  resources :flights
  resources :airports
  resources :bookings

  mount LetterOpenerWeb::Engine, at: "/letter_opener" if Rails.env.development?
end

if you still need more code here is a link to my github  https://github.com/Michael-Mehta/odin-flight-booker


问:
Cannot connect to ASP.Net gRPC app in IIS
I have read that it is possible to host a gRPC app in IIS if you meet the criteria: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-7.0

I have met the criteria (.Net7.0, windows server 2022), but I cannot create a connection. I can connect to the service if ran as a console app, but I would like to run it in IIS.

Here is what I have done:
Properly set the binding in IIS. I am connecting to https://192.168.1.30:5001
I have tried using HttpsSys with and without Kestrel:

```<code>builder.WebHost.UseHttpSys(options =>
{
    options.AllowSynchronousIO = false;
    options.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None;
    options.Authentication.AllowAnonymous = true;
    options.MaxConnections = null;
    options.MaxRequestBodySize = 30000000;
    options.UrlPrefixes.Add("https://192.168.1.30:5001");
});

builder.WebHost.UseIIS();
</code>```

I have tried using Kestrel without HTTP.sys:

```<code>builder.WebHost.ConfigureKestrel(options =>
{
    options.Listen(IPAddress.Parse(address), port, listenOptions =>
    {
        listenOptions.Protocols = HttpProtocols.Http2;
        if (builder.Environment.IsProduction())
            listenOptions.UseHttps(certFile, password);
    }); ;
});
</code>```

Here is what my web.config looks like:

```<code><configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>
</code>```

There are no errors in the stdout file (or in Windows Event Viewer).

When I connect to the app by running the .exe console in the server, I can connect to the gRPC service from the client. In IIS, by app is under a subdirectory, so I connect like this:
https://learn.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-7.0

```<code>var httpClient = new HttpClient(new SubdirectoryHandler(new HttpClientHandler(), "/MySubDirectory"));

var channel = GrpcChannel.ForAddress(_dataServiceAddress, new GrpcChannelOptions
{
    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
    HttpClient = httpClient
});
</code>```

The port does not appear to be open when I run the app in IIS. The specific error from the client is Error starting gRPC call. HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

What am I missing?

Body:
I have read that it is possible to host a gRPC app in IIS if you meet the criteria: https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/iis/?view=aspnetcore-7.0

I have met the criteria (.Net7.0, windows server 2022), but I cannot create a connection. I can connect to the service if ran as a console app, but I would like to run it in IIS.

Here is what I have done:
Properly set the binding in IIS. I am connecting to https://192.168.1.30:5001
I have tried using HttpsSys with and without Kestrel:

builder.WebHost.UseHttpSys(options =>
{
    options.AllowSynchronousIO = false;
    options.Authentication.Schemes = Microsoft.AspNetCore.Server.HttpSys.AuthenticationSchemes.None;
    options.Authentication.AllowAnonymous = true;
    options.MaxConnections = null;
    options.MaxRequestBodySize = 30000000;
    options.UrlPrefixes.Add("https://192.168.1.30:5001");
});

builder.WebHost.UseIIS();

I have tried using Kestrel without HTTP.sys:

builder.WebHost.ConfigureKestrel(options =>
{
    options.Listen(IPAddress.Parse(address), port, listenOptions =>
    {
        listenOptions.Protocols = HttpProtocols.Http2;
        if (builder.Environment.IsProduction())
            listenOptions.UseHttps(certFile, password);
    }); ;
});

Here is what my web.config looks like:

<configuration>
  <location path="." inheritInChildApplications="false">
    <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModuleV2" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\MyApp.dll" stdoutLogEnabled="true" stdoutLogFile=".\logs\stdout" hostingModel="inprocess" />
    </system.webServer>
  </location>
</configuration>

There are no errors in the stdout file (or in Windows Event Viewer).

When I connect to the app by running the .exe console in the server, I can connect to the gRPC service from the client. In IIS, by app is under a subdirectory, so I connect like this:
https://learn.microsoft.com/en-us/aspnet/core/grpc/troubleshoot?view=aspnetcore-7.0

var httpClient = new HttpClient(new SubdirectoryHandler(new HttpClientHandler(), "/MySubDirectory"));

var channel = GrpcChannel.ForAddress(_dataServiceAddress, new GrpcChannelOptions
{
    Credentials = ChannelCredentials.Create(new SslCredentials(), credentials),
    HttpClient = httpClient
});

The port does not appear to be open when I run the app in IIS. The specific error from the client is Error starting gRPC call. HttpRequestException: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

What am I missing?


问:
Sequences with common sub sequence and same overhang
I'm looking some implementation in Python for finding out sets of sequences of equal length and which share a common sub sequence and a common overhang when aligned (without gaps) from a large collection of sequences as follows.

Their alphabetically sorted sequence will be the same , but that will include just any permuted sequence as well, which I don't want. Can the Python 'difflib' library be of any help?
Thanks

```<code>XYZASDFL
   :::::
   ASDFLXYZ
    :::::::
    SDFLXYZA
</code>```

Body:
I'm looking some implementation in Python for finding out sets of sequences of equal length and which share a common sub sequence and a common overhang when aligned (without gaps) from a large collection of sequences as follows.

Their alphabetically sorted sequence will be the same , but that will include just any permuted sequence as well, which I don't want. Can the Python 'difflib' library be of any help?
Thanks

XYZASDFL
   :::::
   ASDFLXYZ
    :::::::
    SDFLXYZA


问:
Error with plotting plotting anBernoulli GLM with predicted
I am trying to plot the significant variable against the probability of conflict (0,1). My Bernoulli #GLM without interaction works without error. My goal is to end with  something this but I currently can not get past predicting my values.</p>
```<code>#works-expands gird with mean of variables
MyData1 <- expand.grid(Road_density = seq(0, 100, length = 1000),
Livestock_density = 81.98442,
Distance_roads = 3453.99,
Distance_recreational = 7490.875,
Elevation = 379.1109)

#works
X <- model.matrix(~ Livestock_density + Distance_roads + Distance_recreational +
                  Elevation + Road_density, data = MyData1)
head(MyData1)

coef(Bern3) #output works

#Calculate predicted values for model M1
MyData1$Pred <-X %*% coef(Bern3) #does not work

MyData1$Pred <-coef(Bern3) %*% X  #found sugesstion to swap but does not work either

#can not run code below here, due to error- Error in X %*% coef(Bern3) : non-conformable arguments

#Calculate on the predictor scale
MyData1$Pi  <- exp(MyData1$Pred) / (1 + exp(MyData1$Pred))

#Calculate standard error spot (SE) for predicted values for model M2
MyData1$se <- sqrt( (X %*% vcov(Bern3) %*% t(X))  )

#Calculate the SEs on the scale of the predictor function
MyData1$SeUp  <- exp(MyData1$Pred + 1.96 *MyData1$se) /
  (1 + exp(MyData1$Pred  + 1.96 *MyData$se))
MyData1$SeLo  <- exp(MyData1$Pred - 1.96 *MyData1$se) /
  (1 + exp(MyData1$Pred  - 1.96 *MyData1$se))
</code>```

Body:
I am trying to plot the significant variable against the probability of conflict (0,1). My Bernoulli #GLM without interaction works without error. My goal is to end with  something this but I currently can not get past predicting my values.

#works-expands gird with mean of variables
MyData1 <- expand.grid(Road_density = seq(0, 100, length = 1000),
Livestock_density = 81.98442,
Distance_roads = 3453.99,
Distance_recreational = 7490.875,
Elevation = 379.1109)

#works
X <- model.matrix(~ Livestock_density + Distance_roads + Distance_recreational +
                  Elevation + Road_density, data = MyData1)
head(MyData1)

coef(Bern3) #output works

#Calculate predicted values for model M1
MyData1$Pred <-X %*% coef(Bern3) #does not work

MyData1$Pred <-coef(Bern3) %*% X  #found sugesstion to swap but does not work either

#can not run code below here, due to error- Error in X %*% coef(Bern3) : non-conformable arguments

#Calculate on the predictor scale
MyData1$Pi  <- exp(MyData1$Pred) / (1 + exp(MyData1$Pred))

#Calculate standard error spot (SE) for predicted values for model M2
MyData1$se <- sqrt( (X %*% vcov(Bern3) %*% t(X))  )

#Calculate the SEs on the scale of the predictor function
MyData1$SeUp  <- exp(MyData1$Pred + 1.96 *MyData1$se) /
  (1 + exp(MyData1$Pred  + 1.96 *MyData$se))
MyData1$SeLo  <- exp(MyData1$Pred - 1.96 *MyData1$se) /
  (1 + exp(MyData1$Pred  - 1.96 *MyData1$se))


问:
Parameterize a debug variable and insert it into the rest of the functions
$isDebug currently exists as a variable in the CleanStaleDevices function,

I need to make the variable into a optional parameter with a default value of $false.
Add the same parameter to the remaining functions.

I would like to set $isDebug as a variable at the initial function call, where CleanStaleDevices is called, then you can pass the value you set down the chain to the other functions. However, if you want to isolate debugging to an individual function you can override.

I tried converting $idDebug to a function itself but it didn't behave the way I was expecting

`function CleanStaleDevices($numDays) {
##Set debug flag
$isDebug = $true

```<code>#######Begin
Connect-AzureAD
###Get-AzureADDevice to get list of devices stale by 3 months and make sure devices aren't autopilot managed###
$dt = (Get-Date).AddDays($numDays)
$devices = Get-AzureADDevice -All:$true | Where-Object { $_.ApproximateLastLogonTimeStamp -le $dt } | select-object -Property AccountEnabled, DeviceId, DeviceOSType, DeviceOSVersion, DisplayName, DeviceTrustType, IsManaged, ApproximateLastLogonTimestamp

$fileNameDate = Get-Date -format "yyyyddMM"
$fileNameMiddle = "_AAD_Stale_Devices-"
##Get Intune devices
$intuneDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Intune.csv"
$devices | ? { $_.IsManaged -eq $true } | Export-Csv c:\temp\$intuneDevicesFileName -NoTypeInformation

#######OUTSIDE ACTION#######
##Use Invoke-Device script to retire devices from generated CSV
##https://www.niallbrady.com/2017/08/23/getting-started-with-microsoft-graph-and-using-powershell-to-automate-things-in-intune/
#######END##################
$confirmation = Read-Host "Have you retired the detected Intune devices (y/n)?"
if ($confirmation -eq 'y') {
    $hybridDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Hybrid.csv"
    $devices | ? { $_.DeviceTrustType -eq "ServerAd" } | Export-Csv c:\temp\$hybridDevicesFileName -NoTypeInformation
    #######OUTSIDE ACTION#######
    ##Use DisableADComputersFromCSV.ps1 to disable the devices generated in the hybrid device csv
    #######END##################
    $confirmation = Read-Host "Have you disabled the on prem devices and ran a directory sync (y/n)?"
    if ($confirmation -eq 'y') {
        # proceed
        ###We don't have to open a new connection for each loop of the devices
        $Connection = New-Object System.Data.SQLClient.SQLConnection
        $serverName = "XXXXXXX"
        $databaseName = "XXXXXXX"

        $Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
        $Connection.Open()

        if ($isDebug -eq $true) {
            ##debug array
            $devicesweredisabled = @()
        }

        ##Sort on DeviceTrustType so that AD Joined devices are disabled before AD registered
        $devices = $devices | Sort-Object DeviceTrustType
        foreach ($device in $devices) {
            #if device is enabled
            if ($device.AccountEnabled -eq $true) {

                if ($isDebug -eq $true) {
                    ##write to debug array
                    $devicesweredisabled += $device
                    Write-Host "Disable device" $device.DeviceId $device.DisplayName $device.AccountEnabled
                }
                else {
                    ##don't disable Hybrid devices since they were disabled earlier
                    if ($_.DeviceTrustType -ne "ServerAd")
                    {
                        Write-Host "DISABLE " $device.DisplayName "with trust type" $device.DeviceTrustType
                        #$device.AccountEnabled = $false
                    }
                    ##Check to see if device is in table already, if so check how long its been there
                    $disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection

                    if ($null -eq $disabledDateTimeValue) {
                        ##Device hasn't been added to table
                        WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
                    }
                }
            }
            else {
                #device is not enabled
                ##Check to see if device is in table already, if so check how long its been there
                $disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection

                if ($null -eq $disabledDateTimeValue) {
                    ##Device is already disabled so we need to add it to the table for time tracking
                    WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
                }
                else {
                    $numDaysSince = (Get-Date) - [datetime]$disabledDateTimeValue | % days
                    if ($numDaysSince -ge 90) {
                        if ($isDebug -eq $true) {
                            Write-Host "DEVICE WAS DELETED" $device.DeviceId $device.DisplayName $device.AccountEnabled
                        }
                        else {
                            Write-Host "DELETED..."
                            #device has been in table for 90 days so delete
                            ##delete device
                        }
                    }
                }

            }

        }

        $Connection.Close()

        if ($isDebug -eq $true) {
            $devicesweredisabled | export-csv c:\temp\devicelist-olderthan-x-days-disabledtest.csv -NoTypeInformation
        }
    }
    else{
        Exit
    }
}
else{
    Exit
}
</code>```

}

function WriteDisabledAADDevice {
Param(
[parameter(position = 3)]
$conn,
[parameter(position = 2)]
$logOnly,
[parameter(position = 1)]
$displayName,
[parameter(position = 0)]
$deviceId
)

```<code>$newId = (New-Guid).Guid
$disableDateTime = (Get-Date)
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$insertquery = "
    INSERT INTO $tableName
        ([DisabledAADDeviceId],[AADDeviceId],[DiplayName],[DisabledDateTime])
    VALUES
        ('$newId','$deviceId','$displayName','$disableDateTime')"

if ($logOnly -eq $true) {
    Write-Host $insertquery
}
else {
    $Command.CommandText = $insertquery
    $Command.ExecuteNonQuery()
}
</code>```

}

function CheckIfDeviceISInTable {
Param(
[parameter(position = 1)]
$conn,
[parameter(position = 0)]
$deviceId
)

```<code>$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$selectQuery = "
    Select [DisabledDateTime] FROM $tableName
    WHERE [AADDeviceId] = '$deviceId'"

$Command.CommandText = $selectQuery
$resultValue = $Command.ExecuteScalar()

return $resultValue
</code>```

}

CleanStaleDevices(-365)`

Body:
$isDebug currently exists as a variable in the CleanStaleDevices function,

I need to make the variable into a optional parameter with a default value of $false.
Add the same parameter to the remaining functions.

I would like to set $isDebug as a variable at the initial function call, where CleanStaleDevices is called, then you can pass the value you set down the chain to the other functions. However, if you want to isolate debugging to an individual function you can override.

I tried converting $idDebug to a function itself but it didn't behave the way I was expecting

`function CleanStaleDevices($numDays) {
##Set debug flag
$isDebug = $true

#######Begin
Connect-AzureAD
###Get-AzureADDevice to get list of devices stale by 3 months and make sure devices aren't autopilot managed###
$dt = (Get-Date).AddDays($numDays)
$devices = Get-AzureADDevice -All:$true | Where-Object { $_.ApproximateLastLogonTimeStamp -le $dt } | select-object -Property AccountEnabled, DeviceId, DeviceOSType, DeviceOSVersion, DisplayName, DeviceTrustType, IsManaged, ApproximateLastLogonTimestamp

$fileNameDate = Get-Date -format "yyyyddMM"
$fileNameMiddle = "_AAD_Stale_Devices-"
##Get Intune devices
$intuneDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Intune.csv"
$devices | ? { $_.IsManaged -eq $true } | Export-Csv c:\temp\$intuneDevicesFileName -NoTypeInformation

#######OUTSIDE ACTION#######
##Use Invoke-Device script to retire devices from generated CSV
##https://www.niallbrady.com/2017/08/23/getting-started-with-microsoft-graph-and-using-powershell-to-automate-things-in-intune/
#######END##################
$confirmation = Read-Host "Have you retired the detected Intune devices (y/n)?"
if ($confirmation -eq 'y') {
    $hybridDevicesFileName = "$($fileNameDate)$($fileNameMiddle)Hybrid.csv"
    $devices | ? { $_.DeviceTrustType -eq "ServerAd" } | Export-Csv c:\temp\$hybridDevicesFileName -NoTypeInformation
    #######OUTSIDE ACTION#######
    ##Use DisableADComputersFromCSV.ps1 to disable the devices generated in the hybrid device csv
    #######END##################
    $confirmation = Read-Host "Have you disabled the on prem devices and ran a directory sync (y/n)?"
    if ($confirmation -eq 'y') {
        # proceed
        ###We don't have to open a new connection for each loop of the devices
        $Connection = New-Object System.Data.SQLClient.SQLConnection
        $serverName = "XXXXXXX"
        $databaseName = "XXXXXXX"

        $Connection.ConnectionString = "server='$serverName';database='$databaseName';trusted_connection=true;"
        $Connection.Open()

        if ($isDebug -eq $true) {
            ##debug array
            $devicesweredisabled = @()
        }

        ##Sort on DeviceTrustType so that AD Joined devices are disabled before AD registered
        $devices = $devices | Sort-Object DeviceTrustType
        foreach ($device in $devices) {
            #if device is enabled
            if ($device.AccountEnabled -eq $true) {

                if ($isDebug -eq $true) {
                    ##write to debug array
                    $devicesweredisabled += $device
                    Write-Host "Disable device" $device.DeviceId $device.DisplayName $device.AccountEnabled
                }
                else {
                    ##don't disable Hybrid devices since they were disabled earlier
                    if ($_.DeviceTrustType -ne "ServerAd")
                    {
                        Write-Host "DISABLE " $device.DisplayName "with trust type" $device.DeviceTrustType
                        #$device.AccountEnabled = $false
                    }
                    ##Check to see if device is in table already, if so check how long its been there
                    $disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection

                    if ($null -eq $disabledDateTimeValue) {
                        ##Device hasn't been added to table
                        WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
                    }
                }
            }
            else {
                #device is not enabled
                ##Check to see if device is in table already, if so check how long its been there
                $disabledDateTimeValue = CheckIfDeviceISInTable $device.DeviceId $Connection

                if ($null -eq $disabledDateTimeValue) {
                    ##Device is already disabled so we need to add it to the table for time tracking
                    WriteDisabledAADDevice $device.DeviceId $device.DisplayName $isDebug $Connection
                }
                else {
                    $numDaysSince = (Get-Date) - [datetime]$disabledDateTimeValue | % days
                    if ($numDaysSince -ge 90) {
                        if ($isDebug -eq $true) {
                            Write-Host "DEVICE WAS DELETED" $device.DeviceId $device.DisplayName $device.AccountEnabled
                        }
                        else {
                            Write-Host "DELETED..."
                            #device has been in table for 90 days so delete
                            ##delete device
                        }
                    }
                }

            }

        }

        $Connection.Close()

        if ($isDebug -eq $true) {
            $devicesweredisabled | export-csv c:\temp\devicelist-olderthan-x-days-disabledtest.csv -NoTypeInformation
        }
    }
    else{
        Exit
    }
}
else{
    Exit
}

}

function WriteDisabledAADDevice {
Param(
[parameter(position = 3)]
$conn,
[parameter(position = 2)]
$logOnly,
[parameter(position = 1)]
$displayName,
[parameter(position = 0)]
$deviceId
)

$newId = (New-Guid).Guid
$disableDateTime = (Get-Date)
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$insertquery = "
    INSERT INTO $tableName
        ([DisabledAADDeviceId],[AADDeviceId],[DiplayName],[DisabledDateTime])
    VALUES
        ('$newId','$deviceId','$displayName','$disableDateTime')"

if ($logOnly -eq $true) {
    Write-Host $insertquery
}
else {
    $Command.CommandText = $insertquery
    $Command.ExecuteNonQuery()
}

}

function CheckIfDeviceISInTable {
Param(
[parameter(position = 1)]
$conn,
[parameter(position = 0)]
$deviceId
)

$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $conn
$tableName = "DisabledAADDevice"
$selectQuery = "
    Select [DisabledDateTime] FROM $tableName
    WHERE [AADDeviceId] = '$deviceId'"

$Command.CommandText = $selectQuery
$resultValue = $Command.ExecuteScalar()

return $resultValue

}

CleanStaleDevices(-365)`


问:
Need efficient and quick way to return promise inside Observable
I have promise inside firebase database subscription as below:

```<code>this.proSubscription$ = this.dataService.getAllProducts().subscribe((res: any) => {
      if(res){

        this.products = res.map(pc => {
           return { key: pc.key, status: subscription, ...pc.payload.val() };
        });

        //HOW CAN I PUT BELOW CODE IN ABOVE MAP?????????????????
        this.products.forEach(async client => {
          const sizeDate:any = await this.geturl(client.dbName);
          let oneMonthBeforeDate = moment().subtract(1, 'months').format();
          client.dateStat = moment(sizeDate.lastDate).isAfter(oneMonthBeforeDate) ? false : true;
        });
        console.log(this.proClients)
      }
    });

geturl(dbName){
    return new Promise(resolve => {
        this.http.get(`https://abcdefg.com/productsSpec`).toPromise().then((data: any) => {
          const arr = _.map(data);
          const res = {
            size: arr.length,
            lastDate: arr[arr.length - 1].createdAt
          }
          resolve (res);
        }, error => {
          resolve(error);
        });
    });
  }
</code>```

The above code works but I am trying to find an efficient and faster way to put promise inside my subscription map. Any recommendations?

Body:
I have promise inside firebase database subscription as below:

this.proSubscription$ = this.dataService.getAllProducts().subscribe((res: any) => {
      if(res){

        this.products = res.map(pc => {
           return { key: pc.key, status: subscription, ...pc.payload.val() };
        });

        //HOW CAN I PUT BELOW CODE IN ABOVE MAP?????????????????
        this.products.forEach(async client => {
          const sizeDate:any = await this.geturl(client.dbName);
          let oneMonthBeforeDate = moment().subtract(1, 'months').format();
          client.dateStat = moment(sizeDate.lastDate).isAfter(oneMonthBeforeDate) ? false : true;
        });
        console.log(this.proClients)
      }
    });

geturl(dbName){
    return new Promise(resolve => {
        this.http.get(`https://abcdefg.com/productsSpec`).toPromise().then((data: any) => {
          const arr = _.map(data);
          const res = {
            size: arr.length,
            lastDate: arr[arr.length - 1].createdAt
          }
          resolve (res);
        }, error => {
          resolve(error);
        });
    });
  }

The above code works but I am trying to find an efficient and faster way to put promise inside my subscription map. Any recommendations?


问:
Can’t move data in ExecuteInEditMode
I try to move all button data to another one and put it in Start(), it work.
like this:

```<code>void Start()
{
    for (int i = 0; i < allanimal.Length; i++)
    {
        allanimal[i].GetComponent<cat>().bodypart= BasebodyManager.singleton.ButtonStore[i].GetComponent<dog>().bodypart;
    }
}
</code>```

But when i put it in [ExecuteInEditMode] and try to edit it in editor, I get this:

NullReferenceException: Object reference not set to an instance of an object

someone say :"Unity is not serializing my class"

so i can't move all button data to another one use [ExecuteInEditMode]?

Title: Can’t move data in ExecuteInEditMode

Body:
I try to move all button data to another one and put it in Start(), it work.
like this:

void Start()
{
    for (int i = 0; i < allanimal.Length; i++)
    {
        allanimal[i].GetComponent<cat>().bodypart= BasebodyManager.singleton.ButtonStore[i].GetComponent<dog>().bodypart;
    }
}

But when i put it in [ExecuteInEditMode] and try to edit it in editor, I get this:

NullReferenceException: Object reference not set to an instance of an object

someone say :"Unity is not serializing my class"

so i can't move all button data to another one use [ExecuteInEditMode]?


问:
System.IO.StreamReader turns into unreadable Deserialized.System.IO.StreamReader when passed to a script block
I'm trying to process the output of a Process using a job because I need it to be parallel but the System.IO.StreamReader turns into a Deserialized.System.IO.StreamReader that doesn't have any way of reading from it and I can't find any documentation on it (Google and Bing give 0 results). It gets strange. It stays a System.IO.StreamReader if I don't try to read from it in the block.

I'm still relatively new to PowerShell and not sure if this is expected behavior.

PowerShell: 5.1.14393.5127

.NET: 4.7.3946.0

Given

```<code>function runProg(
    [parameter(Mandatory)][string]$exe,
    [object[]]$params=@(),
    [switch]$redirectOutput,
    [switch]$redirectError,
    [switch]$redirectInput
){
    $args= ($params.ForEach({ if($_ -is [System.IO.FileSystemInfo]){ ('"{0}"' -f $_.FullName) } elseif(($_.ToString().Contains(' '))){ ('"{0}"' -f $_) }else{ $_ } }) -join ' ')
    Write-Host "$exe $args"

    if ($redirectOutput -or $redirectError -or $redirectInput){
        $pinfo= New-Object System.Diagnostics.ProcessStartInfo;
        $pinfo.UseShellExecute= $false; #needed to redirect outputs and inputs
        $pinfo.FileName= $exe
        $pinfo.CreateNoWindow= $true
        $pinfo.RedirectStandardInput= $redirectInput
        $pinfo.RedirectStandardOutput= $redirectOutput
        $pinfo.RedirectStandardError= $redirectError
        $pinfo.Arguments= $args
        $proc= [System.Diagnostics.Process]::Start($pinfo);
    }else{
        $proc= Start-Process -FilePath $exe -PassThru -NoNewWindow -ArgumentList $args
    }
    $handle = $proc.Handle # force proc.Handle to populate https://stackoverflow.com/a/23797762/1479211
    return $proc
}

$p= runProg -redirectOutput 'powershell.exe' @((Get-Item 'test-long-output.ps1'))
</code>```

The below gets the expected System.IO.StreamReader

```<code>$streamReader= {
    param($stream)
    Write-Host "`$stream.GetType" $stream.GetType().FullName
    Write-Host "`$stream.ReadLine?" ($null -ne $stream.ReadLine)
}
$streamJob= Start-Job -ArgumentList @($p.StandardOutput) -ScriptBlock $streamReader
</code>```

The below gets the Deserialized.System.IO.StreamReader and errors on the missing ReadLine method.

```<code>$streamReader= {
    param($stream)
    Write-Host "`$stream.GetType" $stream.GetType().FullName
    Write-Host "`$stream.ReadLine?" ($null -ne $stream.ReadLine)
    do{
        $line= $stream.ReadLine();
        Write-Output $line
    }while($line -ne $null)
}
$streamJob= Start-Job -ArgumentList @($p.StandardOutput) -ScriptBlock $streamReader
</code>```

Body:
I'm trying to process the output of a Process using a job because I need it to be parallel but the System.IO.StreamReader turns into a Deserialized.System.IO.StreamReader that doesn't have any way of reading from it and I can't find any documentation on it (Google and Bing give 0 results). It gets strange. It stays a System.IO.StreamReader if I don't try to read from it in the block.

I'm still relatively new to PowerShell and not sure if this is expected behavior.

PowerShell: 5.1.14393.5127

.NET: 4.7.3946.0

Given

function runProg(
    [parameter(Mandatory)][string]$exe,
    [object[]]$params=@(),
    [switch]$redirectOutput,
    [switch]$redirectError,
    [switch]$redirectInput
){
    $args= ($params.ForEach({ if($_ -is [System.IO.FileSystemInfo]){ ('"{0}"' -f $_.FullName) } elseif(($_.ToString().Contains(' '))){ ('"{0}"' -f $_) }else{ $_ } }) -join ' ')
    Write-Host "$exe $args"

    if ($redirectOutput -or $redirectError -or $redirectInput){
        $pinfo= New-Object System.Diagnostics.ProcessStartInfo;
        $pinfo.UseShellExecute= $false; #needed to redirect outputs and inputs
        $pinfo.FileName= $exe
        $pinfo.CreateNoWindow= $true
        $pinfo.RedirectStandardInput= $redirectInput
        $pinfo.RedirectStandardOutput= $redirectOutput
        $pinfo.RedirectStandardError= $redirectError
        $pinfo.Arguments= $args
        $proc= [System.Diagnostics.Process]::Start($pinfo);
    }else{
        $proc= Start-Process -FilePath $exe -PassThru -NoNewWindow -ArgumentList $args
    }
    $handle = $proc.Handle # force proc.Handle to populate https://stackoverflow.com/a/23797762/1479211
    return $proc
}

$p= runProg -redirectOutput 'powershell.exe' @((Get-Item 'test-long-output.ps1'))

The below gets the expected System.IO.StreamReader

$streamReader= {
    param($stream)
    Write-Host "`$stream.GetType" $stream.GetType().FullName
    Write-Host "`$stream.ReadLine?" ($null -ne $stream.ReadLine)
}
$streamJob= Start-Job -ArgumentList @($p.StandardOutput) -ScriptBlock $streamReader

The below gets the Deserialized.System.IO.StreamReader and errors on the missing ReadLine method.

$streamReader= {
    param($stream)
    Write-Host "`$stream.GetType" $stream.GetType().FullName
    Write-Host "`$stream.ReadLine?" ($null -ne $stream.ReadLine)
    do{
        $line= $stream.ReadLine();
        Write-Output $line
    }while($line -ne $null)
}
$streamJob= Start-Job -ArgumentList @($p.StandardOutput) -ScriptBlock $streamReader


问:
CSS Causing Website To Crash On Mobile Device?
I'm new to web design and have managed to create a simple website that I'm currently testing to see how it runs. I have no problems getting it to run on a computer but when I test it on a mobile device it often crashes. I've noticed that it runs well on most mobile web browsers except for Google Chrome.

After doing some research I've found many people talking about how they had trouble getting their websites to run based on the CSS they had used. I've tried fiddling around with my code to see if I can isolate the issue but have been unable to find the solution.

Could the mobile Google Chrome issue have anything to do with the -webkit-transform: script that I used? Could the issue have arisen from the display: block or display: none script that I used? Any knowledge that one could share would be very much appreciated.

```<code><!DOCTYPE html>
<html lang="en">

<meta name="viewport" content="width=device-width, initial-scale=1.0;" charset="utf-8">

<body>

<style>html{visibility: hidden; opacity: 0;}</style>

<title>MORIKOBOSHI・</title>

<div class="page-wrap">

<div class="cp_cont">
<input id="cp_toggle03" type="checkbox"/>
<div class="cp_mobilebar">
<label for="cp_toggle03" class="cp_menuicon">
<span></span>
</label>
</div>
<label id="h-menu_black" class="cp_toggle03" for="cp_menuicon"></label>
<div id="body" class="noscroll"></div>

<header class="cp_offcm03">

<nav>
<ul style="text-align: center; margin-left: 210px; overflow: hidden;">

<li style="border-bottom: .05px solid lightgray;"><a href="#">Home</a></li>
<li style="border-bottom: .05px solid lightgray;"><a href="#">Blog</a></li>
<li style="border-bottom: .05px solid lightgray;"><a href="#">About This Website</a></li>
<li style="border-bottom: .05px solid lightgray;"><a href="#">Bibliography</a></li>

<div class="searchbar">

<form id="frmSearch" class="search2" method="get" action="default.html" style=" padding-right: 10px; padding-top: 20px; text-align: center; position: inline;">
<input class="search2" id="txtSearch" type="text" placeholder="Custom Google Search" name="serach_bar" size="31" maxlength="255" value="" style="top: 185px; width: 180px; height: 26px;">
<input class="search1" type="submit" name="submition" value="Search" style="padding-left: 5px; top: 153px; height: 25px; width: 50px; display: inline-flex; justify-content: center;">
<input class="search2" type="hidden" name="sitesearch" value="default.html">

</form>
</div>

<script type="text/javascript">
 document.getElementById('frmSearch').onsubmit = function() {
 window.location = 'http://www.google.com/search?q=site:morikoboshi.com' + document.getElementById('txtSearch').value;
        return false;
    }

</script>

<script>
 document.getElementById('cp_toggle03').onchange = function() {
 if (document.getElementById('cp_toggle03').checked) {
 document.body.style.overflow = "hidden";
  } else {
 document.body.style.overflow = "";
  }
}

</script>

</ul>
</nav>
</header>

<div class="setsumei">

 <br><br><h1 style="text-align: center; font-size: 40px;">◯◯◯◯</h1>
    <br><p style="text-align: justify; font-size: 16px;"></p>

 <p style="text-align: center; font-size: 13px;">Author: ◯◯◯◯</p>
 <p style="text-align: center; font-size: 13px;">Photos/Videos Taken：◯◯◯◯/◯◯/◯◯</p>

 <br><br><p style="text-align: justify; font-size: 16px;">

    #
 </p>

</div>

<br><br><div class="image">

  <a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

 <br><br><a href="#"><img src="#" alt="#" width="90%"></a>

</div>

<br><br><footer class="site-footer" style="font-size: 12px;">MORIKOBOSHI© | <a href="#">日本語</a></footer>

</div>
</div>

<style>

html {visibility: visible;
      opacity: 1;}

.body{background-color: white;
      font-family: sans-serif;}

 .searchbar{float: right;}

 .image{text-align: center;}

 .setsumei{margin-left: 20px;
           margin-right: 20px;}

 .footer{width: 100%;
           height: 40px;
           text-align: center;
           border-top: 1px solid black;
           position: absolute;
           bottom: 0;
           padding: 10px;}

 .page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -40px;
}

 .page-wrap:after {
  content: "";
  display: block;
  }

 .site-footer, .page-wrap:after {
  /* .push must be the same height as footer */
  height: 20px;
}

 .site-footer {
  text-align: center;
  border-top: 1px solid black;
  padding: 10px;
}

 *, *:before, *:after {
    padding-left: 0;
    margin: 0;
    box-sizing: border-box;

}

 ol, ul {
    list-style: none;
}

 a {
    text-decoration: none;
    color: black;
}

 .cp_cont {
    height: auto;
}

/* menu */
 .cp_offcm03 {
    position: relative;
    z-index: 5000;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow: auto;
    width: 100%;
    height: auto;
    padding-top: 0;
    -webkit-transition: transform 0.3s ease-in;
            transition: transform 0.3s ease-in;
    text-align: center;
    color: black;
    background-color: white;
}
 .cp_offcm03 nav,
 .cp_offcm03 ul {
    height: 100%;
}

 .cp_offcm03 li {
    display: inline-block;
    margin-right: -6px;
}

 .cp_offcm03 a {
    display: block;
    padding: 15px 45px;
    margin-bottom: -5px;
    -webkit-transition: background-color .3s ease-in;
            transition: background-color .3s ease-in;
}

 .cp_offcm03 a:hover {
    background-color: lightgray;
}

/* menu toggle */
 #cp_toggle03 {
    display: none;
}

 #cp_toggle03:checked ~ .cp_offcm03 {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 #cp_toggle03:checked ~ .cp_container {
    -webkit-transform: translateX(0);
                    transform: translateX(0);
}

 .cp_mobilebar {
    display: none;

}

/* content */
 .cp_container {
    position: relative;
    top: 0;
    padding: 35px auto;
    -webkit-transition: transform .3s ease-in;
            transition: transform .3s ease-in;
}

 .cp_content {
    margin: 0 auto;
    padding: 20px;
    height: 65vh;
    text-align: center;

}

@media (max-width: 1130px)and (min-width: 280px) {
/* menu */
 .cp_offcm03 {
        position: fixed;
        left: -250px;
        overflow-y: hidden;
        width: 250px;
        height: 100%;
        padding-top: 40px;
        color: black;
        background-color: white;
        z-index: 1000;
    }

 .cp_offcm03 nav {
        background: white;
        border-right: 0.5px solid lightgray;
        margin-left: -210px;
    }

 .cp_offcm03 li {
        display: block;
        margin-right: 0;}

 .cp_offcm03 a {
        padding: 20px;

    }

/* menu toggle */
 .cp_mobilebar {
        display: block;
        z-index: 2000;
        position: relative;
        top: 0;
        left: 0;
        padding: 0 25px;
        width: 100%;
        height: 40px;
        background-color: white;
        border-bottom: .05px solid lightgray;

    }

 .cp_menuicon {
        display: block;
        position: relative;
        width: 25px;
        height: 100%;
        cursor: pointer;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }
 .cp_menuicon > span {
        display: block;
        position: absolute;
        top: 55%;
        margin-top: -0.3em;
        width: 100%;
        height: 0.2em;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease;
                transition: transform .3s ease;
    }
 .cp_menuicon > span:before,
 .cp_menuicon > span:after {
        content: "";
        position: absolute;
        width: 100%;
        height: 100%;
        border-radius: 1px;
        background-color: black;
        -webkit-transition: transform .3s ease-in;
                transition: transform .3s ease-in;
    }

 .cp_menuicon > span:before {
        -webkit-transform: translateY(-0.6em);
                transform: translateY(-0.6em);
    }

 .cp_menuicon > span:after {
        -webkit-transform: translateY(0.6em);
                transform: translateY(0.6em);
    }

 #cp_toggle03:checked + .cp_mobilebar .cp_menuicon {
        -webkit-transform: rotate(45deg);
                transform: rotate(45deg);
    }

 #cp_toggle03:checked + .cp_mobilebar span:before,
 #cp_toggle03:checked + .cp_mobilebar span:after {
        -webkit-transform: rotate(90deg);
                transform: rotate(90deg);
    }

 #cp_toggle03:checked ~ .cp_offcm03 {
        -webkit-transform: translateX(100%);
                transform: translateX(100%);
    }

 #cp_toggle03:checked ~ .cp_container {
        -webkit-transform: translateX(250px);
                transform: translateX(250px);
    }

 input:checked ~ #h-menu_black {
    display: block;/*カバーを表示*/
    opacity: .6;
}

 #h-menu_black {
    display: none;
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: black;
    opacity: 0;
    transition: .7s ease-in-out;
}

/* content */
 .cp_container {
        top: 60px;
        height: 92vh;
        text-align: center;
    }

 .noscroll{
        overflow: hidden;
        position: fixed;
    }

</style>

</body>
</html>
</code>```

Body:
I'm new to web design and have managed to create a simple website that I'm currently testing to see how it runs. I have no problems getting it to run on a computer but when I test it on a mobile device it often crashes. I've noticed that it runs well on most mobile web browsers except for Google Chrome.

After doing some research I've found many people talking about how they had trouble getting their websites to run based on the CSS they had used. I've tried fiddling around with my code to see if I can isolate the issue but have been unable to find the solution.

Could the mobile Google Chrome issue have anything to do with the -webkit-transform: script that I used? Could the issue have arisen from the display: block or display: none script that I used? Any knowledge that one could share would be very much appreciated.

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0;" charset="utf-8">

<title>MORIKOBOSHI・</title>

<input id="cp_toggle03" type="checkbox"/>

Home

Blog

About This Website

Bibliography

<form id="frmSearch" class="search2" method="get" action="default.html" style=" padding-right: 10px; padding-top: 20px; text-align: center; position: inline;">
<input class="search2" id="txtSearch" type="text" placeholder="Custom Google Search" name="serach_bar" size="31" maxlength="255" value="" style="top: 185px; width: 180px; height: 26px;">
<input class="search1" type="submit" name="submition" value="Search" style="padding-left: 5px; top: 153px; height: 25px; width: 50px; display: inline-flex; justify-content: center;">
<input class="search2" type="hidden" name="sitesearch" value="default.html">

</form>

◯◯◯◯

Author: ◯◯◯◯

Photos/Videos Taken：◯◯◯◯/◯◯/◯◯

    #

MORIKOBOSHI© | 日本語