问:
Solana web3.js parse onProgramAccountChange notifications to JSON
How can I parse the connection.onProgramAccountChange notifications data to JSON?

https://solana-labs.github.io/solana-web3.js/modules.html#AccountInfo

The docs specify the data as type T, which for me has usually been a Buffer.

Example code:

```<code>let progKey = new PublicKey("<program key here>");
conn.onProgramAccountChange(progKey, programCallback);
function programCallback(keyedAccountInfo: KeyedAccountInfo, context: Context) {
  let data = keyedAccountInfo.accountInfo.data.toString("hex");
  let ownerId = keyedAccountInfo.accountInfo.owner.toBase58();
  let accId = keyedAccountInfo.accountId.toBase58();
  console.log(`======
  owner: ${ownerId}
  accId: ${accId}
  data: ${data}`);
}
</code>```

Is the data type literally just a buffer in this specific instance, or is there something extra that I need to do to decode it? Decoding it to hex, utf8, base64, and base58 don't work.

答: Even though this is programSubscribe, the notification format is the same as getProgramAccounts. Hence, the answer can be found in my other answer: https://stackoverflow.com/a/71028298/7841421

Body:
How can I parse the connection.onProgramAccountChange notifications data to JSON?

https://solana-labs.github.io/solana-web3.js/modules.html#AccountInfo

The docs specify the data as type T, which for me has usually been a Buffer.

Example code:

let progKey = new PublicKey("<program key here>");
conn.onProgramAccountChange(progKey, programCallback);
function programCallback(keyedAccountInfo: KeyedAccountInfo, context: Context) {
  let data = keyedAccountInfo.accountInfo.data.toString("hex");
  let ownerId = keyedAccountInfo.accountInfo.owner.toBase58();
  let accId = keyedAccountInfo.accountId.toBase58();
  console.log(`======
  owner: ${ownerId}
  accId: ${accId}
  data: ${data}`);
}

Is the data type literally just a buffer in this specific instance, or is there something extra that I need to do to decode it? Decoding it to hex, utf8, base64, and base58 don't work.


来源: stackexchange

问:
Create an editable wpf treeview item
I'm checking this page and I like the only answer there is.

Editable WPF treeview item on doubleclick? (with styles?)

But I don't like the idea to use c# lines, Might there be a possible to write that code using XAML?

答:
You can use EventSetter, or AttachedBehavior. But they are assumes that you need c# code-behind.

How to do it in XAML - hard to say. One more possible way - to use x:Code clause to write c# code inside xaml.

ContentLicense: CC BY-SA 3.0

Title: Create an editable wpf treeview item


问:
Unknown cause for Segfault in Gaussian Equation in C
I am currently making a program that approximates the Schroedinger equation, and for my initial conditions, my professor said to begin with a gaussian. The formula I'm using for that is this (apologies, I don't know how to do equations in markdown):

p(x) = ( 1/sqrt(2 * PI) ) * e^( -1/2 * (x-u)^2 / o )

I am starting with u=0 and o=1 for simplicities sake, and so the way I use it in my program is like this:

```<code>double gaussian(double x) {
    return (1/sqrt(2*M_PI)) * exp((-.5) * pow(x, 2));
}

void initial_conditions(int m, complex *values[], double dx) {
    for (size_t i = 0; i < m; i++)
    {
        values[i]->real = gaussian(i * dx);
    }
}
</code>```

Compiled by: gcc project1.c -lm -o project1

But that produces a segfault every time I have run it. As far as I can tell, it should work, but I am somewhat of a novice to C. I have determined it is specifically that equation that is producing the error by using printf statements to narrow the place of error down, and it always gets to that specific whole formula and return statement and then dies.

Any advice or help would be appreciated.

答:
complex *values[] is weird and unnatural. I can't see the invocation, but I have managed to convince myself that this really should be complex values[].

A complex is far too simple a thing to want to allocate each one individually on the heap; almost always an array of complex would be allocated in a single call to malloc() (or possibly even a stack allocated array by caller).

Proceeding on from the names, I can project with decent confidence the calling code didn't allocate each individual complex in values but just allocated values, and thus the crash is the -> dereference at values[i]->real and values[i] is uninitialized. It's like you want (carrying forward the single array) values[i].real = ... ; values[i].imag = 0;

ContentLicense: CC BY-SA 4.0

Body:
I am currently making a program that approximates the Schroedinger equation, and for my initial conditions, my professor said to begin with a gaussian. The formula I'm using for that is this (apologies, I don't know how to do equations in markdown):

p(x) = ( 1/sqrt(2 * PI) ) * e^( -1/2 * (x-u)^2 / o )

I am starting with u=0 and o=1 for simplicities sake, and so the way I use it in my program is like this:

double gaussian(double x) {
    return (1/sqrt(2*M_PI)) * exp((-.5) * pow(x, 2));
}

void initial_conditions(int m, complex *values[], double dx) {
    for (size_t i = 0; i < m; i++)
    {
        values[i]->real = gaussian(i * dx);
    }
}

Compiled by: gcc project1.c -lm -o project1

But that produces a segfault every time I have run it. As far as I can tell, it should work, but I am somewhat of a novice to C. I have determined it is specifically that equation that is producing the error by using printf statements to narrow the place of error down, and it always gets to that specific whole formula and return statement and then dies.

Any advice or help would be appreciated.


问:
Creating New columns via dictionary pandas
I have a DataFrame with 2 columns

```<code>combined | out_dict
--------------------
"sentence 1" | {class1: 30, class2: 42, class3: 5, class4:42}
"sentence 2" | {class1: 60, class2: 10, class3: 40, class4:40}
</code>```

Now I want to convert it to a new dataframe as follows. If probability is greater or equal to 40, then make 2 new columns for it. i.e

```<code>combined      | class1 | class1_score | class2 | class2_score | class3 | class3_score |class4 | class4_score
-------------------------------------------------------------------------------------------------------
"sentence 1" | Nan       |  NaN       | 1     |   42          | Nan    | Nan          | 1     | 42

"sentence 2" | 1       |  60       | Nan     |   Nan          | 1    | 40          | 1     | 40
</code>```

I have tried using some manual logic, like looping over the whole dataframe, but that seems much inefficient. Kindly guide me in creating an optimal solution for this.

Edit

My solution:

```<code>self.df[list(ref_garm_dict.keys())] = "" # a dictionary with classes name
    for _, row in self.df.iterrows():
        for key, value in row["out_dict"].items():
            if value >= 40:
                row[key] = 1
                row[key + "_score"] = value # has no effect so _score columns are not created.
</code>```

答:
You may first convert all dictionaries into columns as is

```<code>df = df.set_index('combined')['out_dict'].apply(pd.Series)
</code>```

Then add/modify column as you need

```<code>for col in df.columns:
    score_name = f'{col}_score'
    df[score_name] = df[col]
    df[score_name].loc[df[col]<40] = np.nan
    df[col] = df[score_name].isna().map({False: 1})

</code>```

Lastly to take care of the formatting.

```<code>df.sort_index(axis=1).reset_index()
</code>```

Body:
I have a DataFrame with 2 columns

combined | out_dict
--------------------
"sentence 1" | {class1: 30, class2: 42, class3: 5, class4:42}
"sentence 2" | {class1: 60, class2: 10, class3: 40, class4:40}

Now I want to convert it to a new dataframe as follows. If probability is greater or equal to 40, then make 2 new columns for it. i.e

combined      | class1 | class1_score | class2 | class2_score | class3 | class3_score |class4 | class4_score
-------------------------------------------------------------------------------------------------------
"sentence 1" | Nan       |  NaN       | 1     |   42          | Nan    | Nan          | 1     | 42

"sentence 2" | 1       |  60       | Nan     |   Nan          | 1    | 40          | 1     | 40

I have tried using some manual logic, like looping over the whole dataframe, but that seems much inefficient. Kindly guide me in creating an optimal solution for this.

Edit

My solution:

self.df[list(ref_garm_dict.keys())] = "" # a dictionary with classes name
    for _, row in self.df.iterrows():
        for key, value in row["out_dict"].items():
            if value >= 40:
                row[key] = 1
                row[key + "_score"] = value # has no effect so _score columns are not created.

Body:
You may first convert all dictionaries into columns as is

df = df.set_index('combined')['out_dict'].apply(pd.Series)

Then add/modify column as you need

for col in df.columns:
    score_name = f'{col}_score'
    df[score_name] = df[col]
    df[score_name].loc[df[col]<40] = np.nan
    df[col] = df[score_name].isna().map({False: 1})

Lastly to take care of the formatting.

df.sort_index(axis=1).reset_index()


问:
How to get each hashtag inside the element and hide it?
so I have a div containing a description of the item in which there is a hashtag. I want to get every existing hashtag and want to hide all existing hashtags so that they have a hidden class. How can I do that?

var element = $('#product-nav-description');
var rgxp = new RegExp(/^#\!/, 'g');
var hashtag = '#';
var repl = '' + hashtag + '';

element.html(element.html().replace(hashtag, repl));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  background-color: yellow;
  font-weight: bold;
}</code>```

    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech

```

答:
Use replaceAll

EDIT replaces all #words

var element = $('#product-nav-description');
var rgxp = new RegExp(/#[a-z]*/, 'gmi');
var hashtag = '#';
var repl = '' + hashtag + '';

element.html(element.html().replaceAll(rgxp, repl));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.hidden {
  background-color: yellow;
  font-weight: bold;
}</code>```

    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech

```

Body:
so I have a div containing a description of the item in which there is a hashtag. I want to get every existing hashtag and want to hide all existing hashtags so that they have a hidden class. How can I do that?

var element = $('#product-nav-description');
var rgxp = new RegExp(/^#\!/, 'g');
var hashtag = '#';
var repl = '' + hashtag + '';

element.html(element.html().replace(hashtag, repl));

.hidden {
  background-color: yellow;
  font-weight: bold;
}

    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech

Body:
Use replaceAll

EDIT replaces all #words

var element = $('#product-nav-description');
var rgxp = new RegExp(/#[a-z]*/, 'gmi');
var hashtag = '#';
var repl = '<span class="hidden">' + hashtag + '</span>';

element.html(element.html().replaceAll(rgxp, repl));

.hidden {
  background-color: yellow;
  font-weight: bold;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="product-nav-description">
  <p>
    Dummy Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum #machine #vendingmachine #mach #tech
  </p>
</div>


问:
OSError: Could not find geos_c.dll or load any of its variants
I'm trying to use shapley, and to use it for what I need it for, I have to import "from shapely import geometry" but I get the error OSError: Could not find lib geos_c.dll

I've tried to install "geos" via "pip install geos", didn't do anything: Requirement already satisfied

pip location: C:\Users\skoft\AppData\Local\Programs\Python\Python37-32\Scripts\pip.exe

```<code>import shapely

from shapely import geometry

OSError: Could not find lib geos_c.dll or load any of its variants ['C:\\Users\\skoft\\AppData\\Local\\Programs\\Python\\Python37-32\\Library\\lib\\geos_c.dll'].
</code>```

答:
I had the same issue in Python 3.6 with Windows 10 in the Shapely library. I have downloaded the geos_c.dll file online and replaced it in the shapely dll folder that is in environment library. Replacement DLL folder

```<code>env\Lib\site-packages\shapely\DLLs
</code>```

Download Link:

download geos_c.dll online, then put it into your lib address. it works for me

Body:
I'm trying to use shapley, and to use it for what I need it for, I have to import "from shapely import geometry" but I get the error OSError: Could not find lib geos_c.dll

I've tried to install "geos" via "pip install geos", didn't do anything: Requirement already satisfied

pip location: C:\Users\skoft\AppData\Local\Programs\Python\Python37-32\Scripts\pip.exe

import shapely

from shapely import geometry

OSError: Could not find lib geos_c.dll or load any of its variants ['C:\\Users\\skoft\\AppData\\Local\\Programs\\Python\\Python37-32\\Library\\lib\\geos_c.dll'].

Body:
I had the same issue in Python 3.6 with Windows 10 in the Shapely library. I have downloaded the geos_c.dll file online and replaced it in the shapely dll folder that is in environment library. Replacement DLL folder

env\Lib\site-packages\shapely\DLLs

Download Link:

download geos_c.dll online, then put it into your lib address. it works for me


问:
When do I need to worry about thread-safety in an iOS application?
When writing the usual view controller code, can I assume that this will only be called from a single event-loop thread? What kind of classes do I need to make thread-safe? What are the usual situations where multiple threads are involved?</p>

答: The Concurrency Programming Guide can be helpful.</p>


问:
asp net core 6.0 kestrel server is not working
I have this code running kestrel

```<code>builder.WebHost.UseKestrel().UseUrls("https://myfirstproj1.asp")
.UseIISIntegration();
</code>```

but I can't access the site through the url I specified. What am I doing wrong?

答:
.net 6 does not use UserUrls() method any more.
This is how to do it on .net 6.
On Program.cs

```<code>var builder = WebApplication.CreateBuilder(args);

//...
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5001); // to listen for incoming http connection on port 5001
    options.ListenAnyIP(7001, configure => configure.UseHttps()); // to listen for incoming https connection on port 7001
});
//...
var app = builder.Build();
</code>```

Body:
I have this code running kestrel

builder.WebHost.UseKestrel().UseUrls("https://myfirstproj1.asp")
.UseIISIntegration();

but I can't access the site through the url I specified. What am I doing wrong?

Body:
.net 6 does not use UserUrls() method any more.
This is how to do it on .net 6.
On Program.cs

var builder = WebApplication.CreateBuilder(args);

//...
builder.WebHost.ConfigureKestrel(options =>
{
    options.ListenAnyIP(5001); // to listen for incoming http connection on port 5001
    options.ListenAnyIP(7001, configure => configure.UseHttps()); // to listen for incoming https connection on port 7001
});
//...
var app = builder.Build();


Title: How to add legend to plotly graph_objects plot that describes the colors, not traces?

Body:
I would like to have a legend on the right side of my plot that has 10 different color points & (representing the 10 different clusters in the graph below). I've provided two lists before, one that contains the color of each point, and the other list contains the label of each point. So, I'd like for each color in the legend to also have the text corresponding to its label.

Color # of each image:
['#1f77b4', '#1f77b4', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5']
Cluster # of each image:
[0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9]

from jupyter_dash import JupyterDash
from dash import Dash, dcc, html, Input, Output, no_update
import plotly.graph_objects as go
import pandas as pd

## create sample random data
df=interactive_df

fig = go.Figure(data=[
    go.Scatter(
        x=df['x_lv'], #x_px and y_px for pixel data
        y=df['y_lv'],
        mode='markers',
        marker=dict(color=df['color']), showlegend=True
    )
])

fig.update_traces(marker=dict(size=9,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))

# turn off native plotly.js hover effects - make sure to use
# hoverinfo="none" rather than "skip" which also halts events.
fig.update_traces(hoverinfo="none", hovertemplate=None)

Body:
Creates a dictionary of unique values from a list of colors and labels. The next step is to create a scatter plot by looping through the data extracted from the data frame based on the colors. In the looping process, the labels are obtained for the colors and used as names.

import plotly.graph_objects as go
import pandas as pd
import numpy as np

# of each image:
Color = ['#1f77b4', '#1f77b4', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#ff7f0e', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#2ca02c', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#d62728', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#9467bd', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#c49c94', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#f7b6d2', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#c7c7c7', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#dbdb8d', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5', '#9edae5']
# of each image:
Cluster = [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9]

names = {k:str(v) for k,v in zip(set(Color),set(Cluster))}

## create sample random data
df= pd.DataFrame({'x_lv': np.random.randint(0,20, 100),
                  'y_lv':np.random.randint(0,20, 100),
                  'color': Color})

fig = go.Figure()

for c in df['color'].unique():
    df_color= df[df['color'] == c]
    fig.add_trace(
        go.Scatter(
            x=df_color['x_lv'],
            y=df_color['y_lv'],
            name=names[c],
            mode='markers',
            marker=dict(color=df_color['color']), showlegend=True
        )
    )

fig.update_traces(marker=dict(size=9,
                              line=dict(width=2,
                                        color='DarkSlateGrey')),
                  selector=dict(mode='markers'))

# turn off native plotly.js hover effects - make sure to use
# hoverinfo="none" rather than "skip" which also halts events.
fig.update_traces(hoverinfo="none", hovertemplate=None)

fig.show()


问:
My scanner only gives me my x when I want both my x and y
I am really new to Java, as well as programming. And I have been going at this problem for a while. It seems like a quick fix but I just couldn't find something similar online:

```<code>import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.Scanner;

import javax.swing.plaf.synth.SynthScrollBarUI;

public class main {
    public static void main(String[] args) {

        int x;
        int y;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your first number: ");

        x = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }
        System.out.println("Your first number is " + x);

        System.out.println("Enter your second number: ");
        y = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }

        System.out.println("Your numbers are " + x + " and " + y);

    }
}
</code>```

I am trying to tell the code to ask the user to enter x and y using the same scanner, but when I try to run my code, my output tells me to enter the x twice instead of asking for the y right after my first x input. Even when I go through with the code, when It states the x and y, it only shows the first two numbers added and not my y.

I'm thinking it may be because I have entered my scanner into the loops wrong, since I told the code to only accept integers from the user.

Any help would be great, sorry if it wasn't the best explanation I am still new.

答:
Your first if statement is asking if (scanner has a next int type token to read). Scanner.hasNext is a boolean to read if there is a next token to read. Here's the link for the Scanner class so you can get better informed on how the class work.https://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
int variables are set to 0 by default. So if you're expecting a value bigger than zero from the user then I would check if your x is less or equal  than 0 if(x <= 0) { print something}
Or if you expect any value , then you can use the Integer instead of the primitive type int. Integer wrapper class that take int primitive and creates an object that is initialized null if no value was given when declared. So in your if statement you can
if( x == null) { print something)
Here's the link for that https://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html</p>

Body:
I am really new to Java, as well as programming. And I have been going at this problem for a while. It seems like a quick fix but I just couldn't find something similar online:

import java.nio.file.attribute.UserDefinedFileAttributeView;
import java.util.Scanner;

import javax.swing.plaf.synth.SynthScrollBarUI;

public class main {
    public static void main(String[] args) {

        int x;
        int y;

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter your first number: ");

        x = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }
        System.out.println("Your first number is " + x);

        System.out.println("Enter your second number: ");
        y = scan.nextInt();

        if (scan.hasNextInt() == false) {
            System.out.println("Thats not a number, please try again.");
        }

        System.out.println("Your numbers are " + x + " and " + y);

    }
}

I am trying to tell the code to ask the user to enter x and y using the same scanner, but when I try to run my code, my output tells me to enter the x twice instead of asking for the y right after my first x input. Even when I go through with the code, when It states the x and y, it only shows the first two numbers added and not my y.

I'm thinking it may be because I have entered my scanner into the loops wrong, since I told the code to only accept integers from the user.

Any help would be great, sorry if it wasn't the best explanation I am still new.


问:
How to handle lots of messages being sent from android service?
I am developing an app that communicates using the MAVLINK protocol. I am using dronefleet for this purpose. My app has a service which runs a ReadThread that checks the incoming MAVLINK messages for their type. ReadThread then sends messages to the UI for updating some TextViews with the drone's information like battery status, etc. Here is my code.

ReadThread in DService.java

```<code>import io.dronefleet.mavlink.MavlinkMessage;
import io.dronefleet.mavlink.common.Attitude;
import io.dronefleet.mavlink.common.SysStatus;

public static final int ATTITUDE = 1;
public static final int SYS_STATUS = 2;

private class ReadThread extends Thread {
        private AtomicBoolean keep = new AtomicBoolean(true);
        @Override
        public void run() {
            while(keep.get()){
                if(inputStream == null)
                    return;
                MavlinkMessage message;
                try {
---------------------get MAVLINK message from stream here---------------
                    message = mavlinkConnection.next();

-------------------check MAVLINK message type and then send message to UI for updating related fields--------------------

                    if(message.getPayload() instanceof Attitude) {
                        MavlinkMessage<Attitude> attitudeMessage = (MavlinkMessage<Attitude>)message;

                        myHandler.obtainMessage(ATTITUDE, attitudeMessage).sendToTarget();
                    }

----------------removing comments causes app to crash---------------------

/*if(message.getPayload() instanceof SysStatus) {
                        MavlinkMessage<SysStatus> sysStatusMessage = (MavlinkMessage<SysStatus>)message;
                        int battery = sysStatusMessage.getPayload().batteryRemaining();

                        myHandler.obtainMessage(SYS_STATUS, Integer.toString(battery)).sendToTarget();*/
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void setKeep(boolean keep) {
            this.keep.set(keep);
        }
    }

</code>```

handleMessage() in MainActivity.java

```<code>            switch (msg.what) {

                case DService.SYS_STATUS:
                    String battery = (String) msg.obj + "%";
                    myActivity.get().batteryView.setText(battery);

                case DService.ATTITUDE:
                    MavlinkMessage<Attitude> message = (MavlinkMessage<Attitude>) msg.obj;
                    String pitch = Float.toString(message.getPayload().pitch());
                    String roll = Float.toString(message.getPayload().roll());
                    String yaw = Float.toString(message.getPayload().yaw());
                    myActivity.get().pitchView.setText(pitch);
                    myActivity.get().rollView.setText(roll);
                    myActivity.get().yawView.setText(yaw);
                    break;

            }
        }
</code>```

My problem is my app is crashing if I am checking for more than one type of MAVLINK message in my ReadThread. If I check for (say) either SYS_STATUS or ATTITUDE, then the corresponding TextViewss in the UI are getting updated seamlessly every second (which is the rate of messages sent by MAVLINK). But not for 2 message classes. If I remove comments from one if block, my app crashes.

Whats could be the reason? Is my handleMessage() wrong? Do I need to use MessageQueue or some other android mechanism? Should I run separate threads like ReadThread for each MAVLINK message type?

I am developing on Ubuntu 18, and using Android Studio.

答:
Does logcat have any exceptions being thrown by your program before it crashes?

I would not use multiple threads for each MAVLink message type's handlemessage because I'm guessing the dronefleet parser for the MAVLink connection is stateful (MAVLink uses a magic prefix and payload length to delimit packets) and it would probably either break or be nearly synchronous if called from multiple threads.

If you're worried that you might be sending updates too frequently you could have the read thread store the values from the different MAVLink messages and a separate thread send updates at a fixed interval based on either the latest value for each message or on the set of messages received since the last update.

Body:
I am developing an app that communicates using the MAVLINK protocol. I am using dronefleet for this purpose. My app has a service which runs a ReadThread that checks the incoming MAVLINK messages for their type. ReadThread then sends messages to the UI for updating some TextViews with the drone's information like battery status, etc. Here is my code.

ReadThread in DService.java

import io.dronefleet.mavlink.MavlinkMessage;
import io.dronefleet.mavlink.common.Attitude;
import io.dronefleet.mavlink.common.SysStatus;

public static final int ATTITUDE = 1;
public static final int SYS_STATUS = 2;

private class ReadThread extends Thread {
        private AtomicBoolean keep = new AtomicBoolean(true);
        @Override
        public void run() {
            while(keep.get()){
                if(inputStream == null)
                    return;
                MavlinkMessage message;
                try {
---------------------get MAVLINK message from stream here---------------
                    message = mavlinkConnection.next();

-------------------check MAVLINK message type and then send message to UI for updating related fields--------------------

                    if(message.getPayload() instanceof Attitude) {
                        MavlinkMessage<Attitude> attitudeMessage = (MavlinkMessage<Attitude>)message;

                        myHandler.obtainMessage(ATTITUDE, attitudeMessage).sendToTarget();
                    }

----------------removing comments causes app to crash---------------------

/*if(message.getPayload() instanceof SysStatus) {
                        MavlinkMessage<SysStatus> sysStatusMessage = (MavlinkMessage<SysStatus>)message;
                        int battery = sysStatusMessage.getPayload().batteryRemaining();

                        myHandler.obtainMessage(SYS_STATUS, Integer.toString(battery)).sendToTarget();*/
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        public void setKeep(boolean keep) {
            this.keep.set(keep);
        }
    }

handleMessage() in MainActivity.java

            switch (msg.what) {

                case DService.SYS_STATUS:
                    String battery = (String) msg.obj + "%";
                    myActivity.get().batteryView.setText(battery);

                case DService.ATTITUDE:
                    MavlinkMessage<Attitude> message = (MavlinkMessage<Attitude>) msg.obj;
                    String pitch = Float.toString(message.getPayload().pitch());
                    String roll = Float.toString(message.getPayload().roll());
                    String yaw = Float.toString(message.getPayload().yaw());
                    myActivity.get().pitchView.setText(pitch);
                    myActivity.get().rollView.setText(roll);
                    myActivity.get().yawView.setText(yaw);
                    break;

            }
        }

My problem is my app is crashing if I am checking for more than one type of MAVLINK message in my ReadThread. If I check for (say) either SYS_STATUS or ATTITUDE, then the corresponding TextViewss in the UI are getting updated seamlessly every second (which is the rate of messages sent by MAVLINK). But not for 2 message classes. If I remove comments from one if block, my app crashes.

Whats could be the reason? Is my handleMessage() wrong? Do I need to use MessageQueue or some other android mechanism? Should I run separate threads like ReadThread for each MAVLINK message type?

I am developing on Ubuntu 18, and using Android Studio.


问:
Inserting values to table using text file in Oracle SQL
I tried to do following task

First I created a table

```<code>CREATE TABLE my_table(
order_id Int,
id_number VARCHAR(50),
con_number VARCHAR(50),
action_code VARCHAR(50)
);

</code>```

I have a text file called index.txt. The contents of the text file are as follows

```<code>[ 2022-01-24 00:38:12 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28950294"
[ 2022-01-24 00:38:12 ]|[ LOG_PARAMS ]|{"order_id":28450294,"id_number":"466054543","con_number":"344354501983","action_code":"verifier_approved"}
[ 2022-01-24 00:38:12 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:32 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28948509"
[ 2022-01-24 01:15:32 ]|[ LOG_PARAMS ]|{"order_id":28945509,"id_number":"46653156V","con_number":"117546476356","action_code":"verifier_approved"}
[ 2022-01-24 01:15:32 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:45 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28951964"
[ 2022-01-24 01:15:45 ]|[ LOG_PARAMS ]|{"order_id":28948964,"id_number":"14896103756","con_number":"345434353024","action_code":"verifier_approved"}
[ 2022-01-24 01:15:45 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:16:02 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28952134"
[ 2022-01-24 01:16:02 ]|[ LOG_PARAMS ]|{"order_id":289745834,"id_number":"1187402899","con_number":"45445946461","action_code":"verifier_rejected"}
[ 2022-01-24 01:16:02 ]|[ RESPONSE ]|"Success\n202"

</code>```

I want to insert value to table (order_id ,id_number,con_number,action_code) using index.txt file.

Any one can help me

Thank you

答:
you can do this using unix: need to parse the unwanted text using grep and sed. after you parse it like this, you can load the output file to table using oracle sqlldr utility.

```<code>    grep "{" index.txt|cut -f2 -d'{'|cut -f1 -d'}'|sed 's/"order_id"://g'|sed 's/"id_number"://g'|sed 's/"con_number"://g'|sed 's/"action_code"://g' >> index_new.txt

    cat index_new.txt
</code>```

Body:
I tried to do following task

First I created a table

CREATE TABLE my_table(
order_id Int,
id_number VARCHAR(50),
con_number VARCHAR(50),
action_code VARCHAR(50)
);

I have a text file called index.txt. The contents of the text file are as follows

[ 2022-01-24 00:38:12 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28950294"
[ 2022-01-24 00:38:12 ]|[ LOG_PARAMS ]|{"order_id":28450294,"id_number":"466054543","con_number":"344354501983","action_code":"verifier_approved"}
[ 2022-01-24 00:38:12 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:32 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28948509"
[ 2022-01-24 01:15:32 ]|[ LOG_PARAMS ]|{"order_id":28945509,"id_number":"46653156V","con_number":"117546476356","action_code":"verifier_approved"}
[ 2022-01-24 01:15:32 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:15:45 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28951964"
[ 2022-01-24 01:15:45 ]|[ LOG_PARAMS ]|{"order_id":28948964,"id_number":"14896103756","con_number":"345434353024","action_code":"verifier_approved"}
[ 2022-01-24 01:15:45 ]|[ RESPONSE ]|"Success\n202"
[ 2022-01-24 01:16:02 ]|[ URL ]|"https:\/\/kafkawewy.dc.efwe.vb\/app.kyc\/28952134"
[ 2022-01-24 01:16:02 ]|[ LOG_PARAMS ]|{"order_id":289745834,"id_number":"1187402899","con_number":"45445946461","action_code":"verifier_rejected"}
[ 2022-01-24 01:16:02 ]|[ RESPONSE ]|"Success\n202"

I want to insert value to table (order_id ,id_number,con_number,action_code) using index.txt file.

Any one can help me

Thank you

Body:
you can do this using unix: need to parse the unwanted text using grep and sed. after you parse it like this, you can load the output file to table using oracle sqlldr utility.

    grep "{" index.txt|cut -f2 -d'{'|cut -f1 -d'}'|sed 's/"order_id"://g'|sed 's/"id_number"://g'|sed 's/"con_number"://g'|sed 's/"action_code"://g' >> index_new.txt

    cat index_new.txt


问:
Is there a way to use a cleaner to omit specific cases? (R)
I have a dataframe where I want to omit cases where ages 30 or less are omitted. I know you can use na.omit to omit NA cases, but how would I omit specific cases like this?</p>

Body:
With base R, you can filter out all rows where the age is greater than 50.

df[df$age < 30,]

    age values
  <int>  <dbl>
1    21  1.89
2    22  1.01
3    23  0.107
4    24  1.46
5    25  1.17
6    26  1.86
7    27  1.77
8    28  1.91
9    29  0.594

Or with data.table:

library(data.table)

dt <- data.table(df)
dt[age < 30]

However, if you are wanting to only filter NAs for the rows, where the age is greater than 30, then you can find the row index for age being greater than 30 and another column having NA. Then, you can exclude those rows.

df[!(df$age > 30 & is.na(df$values)),]

Or with subset:

subset(df, !(age > 30 & is.na(values)))

With tidyverse:

library(tidyverse)

df %>%
  filter(!(age > 30 & is.na(values)))

data.table:

dt <- data.table(df)
dt[!(age > 30 & is.na(values))]

Data

df <- structure(list(age = 21:40,
                     values = c(1.88648780807853, 1.01084147393703,
                                0.107075828593224, 1.46145519195125, 1.16910230834037, 1.85718628577888,
                                1.7749991081655, 1.91132036875933, 0.594451983459294, 0.976039483677596,
                                1.31880497187376, 1.82749796425924, 1.98314357083291, 0.57053042575717,
                                0.722490054555237, 1.66634088428691, 0.702816031407565, 0.622223159298301,
                                0.298387756571174, 1.6071562608704)),
                class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -20L))


问:
Parallelise enumerate loop with `multiprocessing` module
My code looks like that:

```<code># Features' construction - Multiprocessing #
import pandas as pd
import time
import multiprocessing

def features_construct(index, row):

    dict_features ={}

    ...

    return(dict_features)

data = []
for index, row in enumerate(raw_data):

    data.append(features_construct(index, row))

df_data = pd.DataFrame.from_records(data)
</code>```

raw_data is a list of two-element lists where each element is a json.

How can I parallelise this code with python's multiprocessing module?

答:
I found the solution but not multiprocessing the module with multi-thread also can improve the speed.

Here is code with enumerate in multi-thread:

from torch.utils.data import DataLoader
from datasets.config import GlobalConfig

# The initial data operations are done in the get_item of the dataset
from datasets.dataloader import CARLA_Data
# The initial data operations are done in the get_item of the dataset

import ray
ray.init()
sample_in_pre_run = 50
@ray.remote(num_cpus=48)
def write_pkl(save_dir, cur_num, dataset, run_num):
    # print(cur_num, cur_num + run_num)
    for i in range(cur_num, min(cur_num + run_num, len(dataset))):
        with open(f'{save_dir}/%d.pkl'%(i), 'wb') as fd:
            pickle.dump(dataset[i], fd)

ray_train_set = ray.put(train_set)
for cur_num in range(0, len(train_set), sample_in_pre_run):
      tasks_pre.append(write_pkl.remote(train_dir, cur_num, ray_train_set, sample_in_pre_run))
ray_val_set = ray.put(val_set)
for cur_num in range(0, len(val_set), sample_in_pre_run):
    tasks_pre.append(write_pkl.remote(val_dir, cur_num, val_set, sample_in_pre_run))

# together
ray.get(tasks_pre)
```

And with the proper tune on the thread, the speed can faster twice or ten in some computers.

Here is the ray tutorial on multi-thread: https://docs.ray.io/en/latest/walkthrough.html

Body:
My code looks like that:

# Features' construction - Multiprocessing #
import pandas as pd
import time
import multiprocessing

def features_construct(index, row):

    dict_features ={}

    ...

    return(dict_features)

data = []
for index, row in enumerate(raw_data):

    data.append(features_construct(index, row))

df_data = pd.DataFrame.from_records(data)

raw_data is a list of two-element lists where each element is a json.

How can I parallelise this code with python's multiprocessing module?

Body:
I found the solution but not multiprocessing the module with multi-thread also can improve the speed.

Here is code with enumerate in multi-thread:

from torch.utils.data import DataLoader
from datasets.config import GlobalConfig

# The initial data operations are done in the get_item of the dataset
from datasets.dataloader import CARLA_Data
# The initial data operations are done in the get_item of the dataset

import ray
ray.init()
sample_in_pre_run = 50
@ray.remote(num_cpus=48)
def write_pkl(save_dir, cur_num, dataset, run_num):
    # print(cur_num, cur_num + run_num)
    for i in range(cur_num, min(cur_num + run_num, len(dataset))):
        with open(f'{save_dir}/%d.pkl'%(i), 'wb') as fd:
            pickle.dump(dataset[i], fd)

ray_train_set = ray.put(train_set)
for cur_num in range(0, len(train_set), sample_in_pre_run):
      tasks_pre.append(write_pkl.remote(train_dir, cur_num, ray_train_set, sample_in_pre_run))
ray_val_set = ray.put(val_set)
for cur_num in range(0, len(val_set), sample_in_pre_run):
    tasks_pre.append(write_pkl.remote(val_dir, cur_num, val_set, sample_in_pre_run))

# together
ray.get(tasks_pre)

And with the proper tune on the thread, the speed can faster twice or ten in some computers.

Here is the ray tutorial on multi-thread: https://docs.ray.io/en/latest/walkthrough.html


问:
Server crashes when testing app expecting a number. Express, NodeJS
Prevent server from crashing.

I am testing an API with Postman where I am expecting a number with or without decimal places.

But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.

Postman:

```<code>{
        "concept": "Text",
        "incomeAmount": 1)0000,
        "expenseAmount": 89,
        "description":"Text"
}
</code>```

Failed response:

SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

I am using express validator like this:

```<code>router.post('/new-income',
    [
        check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
        check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),

    ],
    validation,
    newItem
);
</code>```

And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.

```<code>const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');

        if (!regAmount.test(incomeAmount)) {
            return res.json ( {
                'msg': 'Only positive numbers without signs are allowed'
            } );
        }
</code>```

Thanks for your help!

答:
This is expected.  You're sending illegal JSON so your JSON parsing middleware gets an exception.  To catch/handle this error, you need to either install custom middleware that catches the error in the middleware or catch the error from the existing JSON parser in the Express error handler by installing your own Express error handler.

Also, if you're using the express.json() middleware, it has a verify callback option that you can pre-check the JSON if you want, but frankly, it's probably easier to just have an Express error handler and get the error there.

Body:
Prevent server from crashing.

I am testing an API with Postman where I am expecting a number with or without decimal places.

But it happens that at the time of testing if I enter a sign like this in Postman: " ) " the server crashes automatically and it seems that it does not reach my validator.

Postman:

{
        "concept": "Text",
        "incomeAmount": 1)0000,
        "expenseAmount": 89,
        "description":"Text"
}

Failed response:

SyntaxError: Unexpected token ) in JSON at position 73
at JSON.parse ()
at parse (C:\project\node_modules\body-parser\lib\types\json.js:89:19)
at C:\project\node_modules\body-parser\lib\read.js:121:18
at invokeCallback (C:\project\node_modules\raw-body\index.js:224:16)
at done (C:\project\node_modules\raw-body\index.js:213:7)
at IncomingMessage.onEnd (C:\project\node_modules\raw-body\index.js:273:7)
at IncomingMessage.emit (node:events:402:35)
at IncomingMessage.emit (node:domain:475:12)
at endReadableNT (node:internal/streams/readable:1343:12)
at processTicksAndRejections (node:internal/process/task_queues:83:21)

I am using express validator like this:

router.post('/new-income',
    [
        check('incomeAmount', 'El Monto del Ingreso debe ser Númerico').isNumeric().not().isEmpty(),
        check('expenseAmount', 'El Monto del Egreso debe ser Númerico').isNumeric().optional({ checkFalsy: true }),

    ],
    validation,
    newItem
);

And in the controller, I use Regex to verify that it is a positive number without symbols, but apparently neither the request nor the route arrives.

const regAmount = new RegExp('^[+]?([1-9][0-9]*(?:[\.][0-9]*)?|0*\.0*[1-9][0-9]*)(?:[eE][+-][0-9]+)?$');

        if (!regAmount.test(incomeAmount)) {
            return res.json ( {
                'msg': 'Only positive numbers without signs are allowed'
            } );
        }

Thanks for your help!


问:
When building array program in Java, it does not return the last number of the array when following the array.length - 1 method
I am writing a small program to take an input array, nums and create a new array that is double the size and returns the last number from the previous array as the last and only different number in the new array.

When I try to return this number using the nums.length - 1 formula to get the end of the array, it returns the number in the middle of the new array. Below is my program.

```<code>public int[] makeLast(int[] nums) {

    int lengonewarr = nums.length;

    int officiallength = lengonewarr * 2;

    int [] makezero = new int [officiallength];

    makezero [nums.length-1] = nums[nums.length-1];

    return(makezero);

}
</code>```

These are the outputs I should be making:

```<code>makeLast([4, 5, 6]) → [0, 0, 0, 0, 0, 6]
makeLast([1, 2]) → [0, 0, 0, 2]
makeLast([3]) → [0, 3]
</code>```

But I instead get something like:

```<code>makeLast([1, 2, 3, 4]) → [0, 0, 0, 0, 0, 0, 0, 4] (My output) [0, 0, 0, 4, 0, 0, 0, 0]
makeLast([2, 4]) → [0, 0, 0, 4]  (My output)    [0, 4, 0, 0]
</code>```

Any advice is greatly appreciated.

答:
the array makezero's length is officiallength, not nums.length, just replace the first nums.length by makezero.length or officiallength.

```<code>makezero [makezero.length -1] = nums[nums.length-1];
</code>```

BTW: It's better to name the variable with camelCase style, which will make the code more readable. Like makeZero or officialLength

Body:
I am writing a small program to take an input array, nums and create a new array that is double the size and returns the last number from the previous array as the last and only different number in the new array.

When I try to return this number using the nums.length - 1 formula to get the end of the array, it returns the number in the middle of the new array. Below is my program.

public int[] makeLast(int[] nums) {

    int lengonewarr = nums.length;

    int officiallength = lengonewarr * 2;

    int [] makezero = new int [officiallength];

    makezero [nums.length-1] = nums[nums.length-1];

    return(makezero);

}

These are the outputs I should be making:

makeLast([4, 5, 6]) → [0, 0, 0, 0, 0, 6]
makeLast([1, 2]) → [0, 0, 0, 2]
makeLast([3]) → [0, 3]

But I instead get something like:

makeLast([1, 2, 3, 4]) → [0, 0, 0, 0, 0, 0, 0, 4] (My output) [0, 0, 0, 4, 0, 0, 0, 0]
makeLast([2, 4]) → [0, 0, 0, 4]  (My output)    [0, 4, 0, 0]

Any advice is greatly appreciated.

Body:
the array makezero's length is officiallength, not nums.length, just replace the first nums.length by makezero.length or officiallength.

makezero [makezero.length -1] = nums[nums.length-1];

BTW: It's better to name the variable with camelCase style, which will make the code more readable. Like makeZero or officialLength


问:
Teamcity custom reports tab
I am trying to create a custom tab in my Build reports. I followed this link given under teamcity manual. But the tab simply does not appear for me. What am I doing wrong?

I see an entry being created in the config/main-config.xml like this. But still this does not help me showing the specific tab.

```<code><report-tab title="Koverage" basePath="/usr/braga/helloworld" startPage="braga.html" />
</code>```

By the way, I am trying to integrate the .html generated for rcov code coverage gme within my Rails project.

答: I finally found out what I was doing wrong. Actually, I have to first create artifacts and have them saved in the artifact directory. Then, I will have to include those artifacts in the build I choose. The base path has be "." (meaning current directory) and the filename can be index.html. Here is a screenshot after I configured it.

Title: Teamcity custom reports tab

Body:
I am trying to create a custom tab in my Build reports. I followed this link given under teamcity manual. But the tab simply does not appear for me. What am I doing wrong?

I see an entry being created in the config/main-config.xml like this. But still this does not help me showing the specific tab.

<report-tab title="Koverage" basePath="/usr/braga/helloworld" startPage="braga.html" />

By the way, I am trying to integrate the .html generated for rcov code coverage gme within my Rails project.


答:
Here is the SQL:

```<code>with action_a
as
(
 SELECT user_id,
       Row_number()
         OVER (
           ORDER BY a) id,
       a
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'a' THEN time
               END "a"
        FROM   tabaction) x
),
action_b
as
(
  SELECT user_id,
       Row_number()
         OVER (
           ORDER BY b) id,
       b
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'b' THEN time
               END "b"
        FROM   tabaction) x
),
action_c
as
(
SELECT user_id,
       Row_number()
         OVER (
           ORDER BY c) id,
       c
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'c' THEN time
               END "c"
        FROM   tabaction) x

)
SELECT action_a.user_id,
       action_a.a,
       action_b.b,
       action_c.c
FROM   action_a
       FULL OUTER JOIN action_b
               ON action_a.id = action_b.id
                  AND action_a.user_id = action_b.user_id
       FULL OUTER JOIN action_c
               ON action_b.id = action_c.id
                  AND action_b.user_id = action_c.user_id;
</code>```

Output:

```<code> user_id |          a          |          b          |          c
---------+---------------------+---------------------+---------------------
       1 | 2022-01-01 12:30:00 | 2022-01-01 12:30:00 | 2022-01-01 12:00:00
       1 |                     | 2022-01-01 12:50:00 | 2022-01-01 13:10:00
       1 |                     |                     | 2022-01-01 13:20:00
       1 |                     |                     |
       1 |                     |                     |
       1 |                     |                     |
(6 rows)
</code>```

Setup:

```<code>create table tabaction
( user_id int, action varchar(5) , time timestamp);

insert into tabaction values(1,'a','2022-01-01 12:30'),(1,'b','2022-01-01 12:30'),(1,'b','2022-01-01 12:50'),(1,'c','2022-01-01 12:00'),(1,'c','2022-01-01 13:10'),(1,'c','2022-01-01 13:20');

postgres=# select * from tabaction;
 user_id | action |        time
---------+--------+---------------------
       1 | a      | 2022-01-01 12:30:00
       1 | b      | 2022-01-01 12:50:00
       1 | c      | 2022-01-01 12:00:00
       1 | c      | 2022-01-01 13:10:00
       1 | c      | 2022-01-01 13:20:00
       1 | b      | 2022-01-01 12:30:00
(6 rows)
</code>```

Ideal SQL should include user_id for action A, B, C so that those not missed out . Here the situation does not arise because USER_ID is only 1 and all actions are mapped to USER_ID. I believe might get different, in which case you might need this SQL:

```<code>with action_a
as
(
 SELECT user_id,
       Row_number()
         OVER (
           ORDER BY a) id,
       a
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'a' THEN time
               END "a"
        FROM   tabaction) x
),
action_b
as
(
  SELECT user_id,
       Row_number()
         OVER (
           ORDER BY b) id,
       b
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'b' THEN time
               END "b"
        FROM   tabaction) x
),
action_c
as
(
SELECT user_id,
       Row_number()
         OVER (
           ORDER BY c) id,
       c
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'c' THEN time
               END "c"
        FROM   tabaction) x

)
SELECT action_a.user_id a_userid,
       action_b.user_id b_userid,
       action_c.user_id c_userid,
       action_a.a,
       action_b.b,
       action_c.c
FROM   action_a
       FULL OUTER JOIN action_b
               ON action_a.id = action_b.id
                  AND action_a.user_id = action_b.user_id
       FULL OUTER JOIN action_c
               ON action_b.id = action_c.id
                  AND action_b.user_id = action_c.user_id;
</code>```

Title: Crosstable on multiple rows in PostgreSQL

Body:
Hi I want to know how can do a pivot table with crosstable in a table like:

user_id
action
time

1
a
2022-01-01 12:30

1
b
2022-01-01 12:40

1
b
2022-01-01 12:50

1
c
2022-01-01 13:00

1
c
2022-01-01 13:10

1
c
2022-01-01 13:20

2
b
2022-01-01 13:11

2
c
2022-01-01 13:21

The expected result should look like this:

user_id
a
b
c

1
2022-01-01 12:30
2022-01-01 12:40
2022-01-01 13:00

1
NULL
2022-01-01 12:50
2022-01-01 13:10

1
NULL
NULL
2022-01-01 13:20

2
NULL
2022-01-01 13:11
2022-01-01 13:21

Following several tutorials, they gave me this result:

user_id
a
b
c

1
2022-01-01 12:30
2022-01-01 12:40
2022-01-01 13:00

2
NULL
2022-01-01 13:11
2022-01-01 13:21

However, as you can note, there is plenty of data loss by the single line result.
Does any have an idea, please?
Thanks in advance

Body:
Here is the SQL:

with action_a
as
(
 SELECT user_id,
       Row_number()
         OVER (
           ORDER BY a) id,
       a
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'a' THEN time
               END "a"
        FROM   tabaction) x
),
action_b
as
(
  SELECT user_id,
       Row_number()
         OVER (
           ORDER BY b) id,
       b
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'b' THEN time
               END "b"
        FROM   tabaction) x
),
action_c
as
(
SELECT user_id,
       Row_number()
         OVER (
           ORDER BY c) id,
       c
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'c' THEN time
               END "c"
        FROM   tabaction) x

)
SELECT action_a.user_id,
       action_a.a,
       action_b.b,
       action_c.c
FROM   action_a
       FULL OUTER JOIN action_b
               ON action_a.id = action_b.id
                  AND action_a.user_id = action_b.user_id
       FULL OUTER JOIN action_c
               ON action_b.id = action_c.id
                  AND action_b.user_id = action_c.user_id;

Output:

 user_id |          a          |          b          |          c
---------+---------------------+---------------------+---------------------
       1 | 2022-01-01 12:30:00 | 2022-01-01 12:30:00 | 2022-01-01 12:00:00
       1 |                     | 2022-01-01 12:50:00 | 2022-01-01 13:10:00
       1 |                     |                     | 2022-01-01 13:20:00
       1 |                     |                     |
       1 |                     |                     |
       1 |                     |                     |
(6 rows)

Setup:

create table tabaction
( user_id int, action varchar(5) , time timestamp);

insert into tabaction values(1,'a','2022-01-01 12:30'),(1,'b','2022-01-01 12:30'),(1,'b','2022-01-01 12:50'),(1,'c','2022-01-01 12:00'),(1,'c','2022-01-01 13:10'),(1,'c','2022-01-01 13:20');

postgres=# select * from tabaction;
 user_id | action |        time
---------+--------+---------------------
       1 | a      | 2022-01-01 12:30:00
       1 | b      | 2022-01-01 12:50:00
       1 | c      | 2022-01-01 12:00:00
       1 | c      | 2022-01-01 13:10:00
       1 | c      | 2022-01-01 13:20:00
       1 | b      | 2022-01-01 12:30:00
(6 rows)

Ideal SQL should include user_id for action A, B, C so that those not missed out . Here the situation does not arise because USER_ID is only 1 and all actions are mapped to USER_ID. I believe might get different, in which case you might need this SQL:

with action_a
as
(
 SELECT user_id,
       Row_number()
         OVER (
           ORDER BY a) id,
       a
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'a' THEN time
               END "a"
        FROM   tabaction) x
),
action_b
as
(
  SELECT user_id,
       Row_number()
         OVER (
           ORDER BY b) id,
       b
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'b' THEN time
               END "b"
        FROM   tabaction) x
),
action_c
as
(
SELECT user_id,
       Row_number()
         OVER (
           ORDER BY c) id,
       c
FROM   (SELECT user_id,
               CASE
                 WHEN action = 'c' THEN time
               END "c"
        FROM   tabaction) x

)
SELECT action_a.user_id a_userid,
       action_b.user_id b_userid,
       action_c.user_id c_userid,
       action_a.a,
       action_b.b,
       action_c.c
FROM   action_a
       FULL OUTER JOIN action_b
               ON action_a.id = action_b.id
                  AND action_a.user_id = action_b.user_id
       FULL OUTER JOIN action_c
               ON action_b.id = action_c.id
                  AND action_b.user_id = action_c.user_id;


问:
How can I distinguish between attachment types in exchangelib?
I've just noticed that Microsoft OWA does not display some attachments. Some people use images in their footer (which are attachments). I'm not sure if the only difference between a "normal" attachment and this emedded attachment is that it is embedded in the email.

Is there another difference? How can I get only attachments which OWA* displays as attachements?

* and probably most other email clients; I think I've seen a similar behavior in Google Mail

答:
looking for cid:image_name inside mail body fails for embedded images with src referring to a link rather than cid.

so the best solution would be to use attachments.is_inline property which is built in exchangelib.

```<code>    for attachment in msg.attachments:
        if msg.has_attachments == True:
            if isinstance(attachment, FileAttachment):
                if attachment.is_inline:
                    print("Embeded Image")
                else:
                    print("Normal Attachment")
</code>```

reference: https://github.com/ecederstrand/exchangelib/issues/562

Body:
looking for cid:image_name inside mail body fails for embedded images with src referring to a link rather than cid.

so the best solution would be to use attachments.is_inline property which is built in exchangelib.

    for attachment in msg.attachments:
        if msg.has_attachments == True:
            if isinstance(attachment, FileAttachment):
                if attachment.is_inline:
                    print("Embeded Image")
                else:
                    print("Normal Attachment")

reference: https://github.com/ecederstrand/exchangelib/issues/562


问:
Select with mouse on a PDF (User Input)
I'm currently using PDFBox and I'm trying to open a PDF so that the user can select with his mouse areas to crop, I've no idea how to proceed to make a PDF viewer & let the user input the selected rectangle to crop.

PDPage#setCropBox(PDRectangle cropBox)

https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/PDPage.html#setCropBox(org.apache.pdfbox.pdmodel.common.PDRectangle)
https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/common/PDRectangle.html

The only thing I'm missing here is how the user can decide to which point he wants to crop (and I'm thinking of a mouse selection & so having the view of the PDF to select which area to crop), otherwise if he inputs random values, it won't be accurate.

package uk.mushow.pdftoexcel;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;
import java.io.IOException;

public class PDFToExcel extends Application {

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(final Stage stage) {
        stage.setTitle("PDF Test");

        final FileChooser fileChooser = new FileChooser();
        final Button openButton = new Button("Select pdf");

        openButton.setOnAction(event -> {
            configureFileChooser(fileChooser);
            File file = fileChooser.showOpenDialog(stage);
            if (file != null) {
                try {
                    openFile(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        final GridPane inputGridPane = new GridPane();

        GridPane.setConstraints(openButton, 0, 1);
        inputGridPane.setHgap(6);
        inputGridPane.setVgap(6);
        inputGridPane.getChildren().add(openButton);

        final Pane rootGroup = new VBox(60);
        rootGroup.getChildren().add(inputGridPane);
        rootGroup.setPadding(new Insets(60, 60, 60, 60));

        stage.setScene(new Scene(rootGroup));
        stage.show();
    }

    private void configureFileChooser(final FileChooser fileChooser) {
        fileChooser.setTitle("pdf selector");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF", "*.pdf"));
    }

    private void openFile(File file) throws IOException {
        PDDocument pdDocument = PDDocument.load(file);
        //This is where I don't know how to handle the file
        PDPage pdPage = pdDocument.getPage(0);
        //Need the user to select his own cropbox but can't be just values from his head otherwise it wouldn't be accurate);
    }
}
```

Thanks!

EDIT: ADDED IMAGE

How would a user know the coordinates to select that green rectangle?

答:
The best method for getting co-ordinates in most pdf view/annotators is by adding a highlight. and that usually provides some user feed back so the top left of this rescaled example is 45 mm from the left and 111.7mm down from the top (however that alone is not the full picture since the real units have been converted to mm so you need to export the highlight data into a different set of units, which a different viewer may use. Both are corrrect but just showing the values via different outputs.

You need to "Square" up those differences and an export of comments usually does that, however the maths can be a challenge as its done in PDF page co-ordinates.

```<code>    "rect": [
      227.495148,
      351.695496,
      386.449585,
      430.445496
    ],
    "subtype": "Popup",
    "annotationType": 16,
    "parentType": "Square",
    "parentId": "6R",
    "parentRect": [
      128.322571,
      24.175232,
      210.179276,
      485.779327
    ],
</code>```

You will need to experiment with your chosen libraries as to which is easiest, personally for my uses, I would look towards milking command line utilities to do the maths and text output for me.

Title: Select with mouse on a PDF (User Input)

Body:
I'm currently using PDFBox and I'm trying to open a PDF so that the user can select with his mouse areas to crop, I've no idea how to proceed to make a PDF viewer & let the user input the selected rectangle to crop.

PDPage#setCropBox(PDRectangle cropBox)

https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/PDPage.html#setCropBox(org.apache.pdfbox.pdmodel.common.PDRectangle)
https://pdfbox.apache.org/docs/2.0.2/javadocs/org/apache/pdfbox/pdmodel/common/PDRectangle.html

The only thing I'm missing here is how the user can decide to which point he wants to crop (and I'm thinking of a mouse selection & so having the view of the PDF to select which area to crop), otherwise if he inputs random values, it won't be accurate.

package uk.mushow.pdftoexcel;

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

import java.io.File;
import java.io.IOException;

public class PDFToExcel extends Application {

    public static void main(String[] args) {
        launch();
    }

    @Override
    public void start(final Stage stage) {
        stage.setTitle("PDF Test");

        final FileChooser fileChooser = new FileChooser();
        final Button openButton = new Button("Select pdf");

        openButton.setOnAction(event -> {
            configureFileChooser(fileChooser);
            File file = fileChooser.showOpenDialog(stage);
            if (file != null) {
                try {
                    openFile(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        final GridPane inputGridPane = new GridPane();

        GridPane.setConstraints(openButton, 0, 1);
        inputGridPane.setHgap(6);
        inputGridPane.setVgap(6);
        inputGridPane.getChildren().add(openButton);

        final Pane rootGroup = new VBox(60);
        rootGroup.getChildren().add(inputGridPane);
        rootGroup.setPadding(new Insets(60, 60, 60, 60));

        stage.setScene(new Scene(rootGroup));
        stage.show();
    }

    private void configureFileChooser(final FileChooser fileChooser) {
        fileChooser.setTitle("pdf selector");
        fileChooser.getExtensionFilters().add(new FileChooser.ExtensionFilter("PDF", "*.pdf"));
    }

    private void openFile(File file) throws IOException {
        PDDocument pdDocument = PDDocument.load(file);
        //This is where I don't know how to handle the file
        PDPage pdPage = pdDocument.getPage(0);
        //Need the user to select his own cropbox but can't be just values from his head otherwise it wouldn't be accurate);
    }
}

Thanks!

EDIT: ADDED IMAGE

How would a user know the coordinates to select that green rectangle?

Body:
The best method for getting co-ordinates in most pdf view/annotators is by adding a highlight. and that usually provides some user feed back so the top left of this rescaled example is 45 mm from the left and 111.7mm down from the top (however that alone is not the full picture since the real units have been converted to mm so you need to export the highlight data into a different set of units, which a different viewer may use. Both are corrrect but just showing the values via different outputs.

You need to "Square" up those differences and an export of comments usually does that, however the maths can be a challenge as its done in PDF page co-ordinates.

    "rect": [
      227.495148,
      351.695496,
      386.449585,
      430.445496
    ],
    "subtype": "Popup",
    "annotationType": 16,
    "parentType": "Square",
    "parentId": "6R",
    "parentRect": [
      128.322571,
      24.175232,
      210.179276,
      485.779327
    ],

You will need to experiment with your chosen libraries as to which is easiest, personally for my uses, I would look towards milking command line utilities to do the maths and text output for me.


问:
How to add several list params to link_to path
I have the model kit which has_and_belongs_to_many products.

I want to add all of the product_ids the kit has into a link_to path.

```<code><%= link_to "<button>Personalizar este pack</button>".html_safe, kit_builder_path(kit_id: @kit.id, products_ids: @kit.products, kit_name: @kit.name) %>
</code>```

¿Do I need to loop through the @kit.products ids and inject them?

Thanks a lot

答:
You can do:</p>
```<code>product_ids: @kit.products.collect(&:id)
</code>```

Body:
I have the model kit which has_and_belongs_to_many products.

I want to add all of the product_ids the kit has into a link_to path.

<%= link_to "<button>Personalizar este pack</button>".html_safe, kit_builder_path(kit_id: @kit.id, products_ids: @kit.products, kit_name: @kit.name) %>

¿Do I need to loop through the @kit.products ids and inject them?

Thanks a lot

Body:
You can do:

product_ids: @kit.products.collect(&:id)


问:
Makefile: return first two characters of a string
Given a string in a Makefile, is it possible to extract the first two characters of an unknown string using Makefile syntax (without using shell calls)?

for instance,

```<code>VAR := UnKnown
VAR_TERSE = $(call get_first_two_chars, $(VAR))

define get_first_two_char
...
endef
</code>```

答:
I really don't approve of forcing Make to do things it clearly doesn't want to do, but... I can't resist a good puzzle.</p>

```<code>$(eval FOO := $$$(VAR))
$(eval FOO := $$$(FOO))
VAR_TERSE:= $(VAR:$(FOO)=)
</code>```

Body:
Given a string in a Makefile, is it possible to extract the first two characters of an unknown string using Makefile syntax (without using shell calls)?

for instance,

VAR := UnKnown
VAR_TERSE = $(call get_first_two_chars, $(VAR))

define get_first_two_char
...
endef

Body:
I really don't approve of forcing Make to do things it clearly doesn't want to do, but... I can't resist a good puzzle.

$(eval FOO := $$$(VAR))
$(eval FOO := $$$(FOO))
VAR_TERSE:= $(VAR:$(FOO)=)


问:
Changing next page url within scraper and loading
I am trying to get within several urls of a webpage and follow the response to the next parser to grab another set of urls on a page. However, from this page I need to grab the next page urls but I wanted to try this by manipulating the page string by parsing it and then passing this as the next page. However, the scraper crawls but it returns nothing not even the output on the final parser when I load item.

Note: I know that I can grab the next page rather simply with an if-statement on the href. However, I wanted to try something different in case I had to face a situation where I would have to do this.

Here's my scraper:

```<code>import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.item import Field
from itemloaders.processors import TakeFirst
from scrapy.loader import ItemLoader

class ZooplasItem(scrapy.Item):
    stuff = Field()
class ZooplasSpider(scrapy.Spider):
    name = 'zooplas'
    start_urls = ['https://www.zoopla.co.uk/overseas/']

    def start_request(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url,
                callback = self.parse, )

    def parse(self, response):
        container = response.xpath("//ul[@class='list-inline list-unstyled']//li")
        for links in container:
            urls = links.xpath(".//a/@href").get()
            yield response.follow(
                urls, callback = self.parse_places
            )
    def parse_places(self, response):
        container = response.xpath("//ul[@class='listing-results clearfix js-gtm-list']//li")
        for links in container:
            urls = links.xpath('(//div[@class="listing-results-right clearfix"]//a)[position() mod 3=1]//@href').get()
            yield response.follow(
                urls, callback = self.parse_listings
            )
        if response.xpath("//div[@id='content']//div//h1//text()").extract_first():
            page_on = response.xpath("//div[@id='content']//div//h1//text()").extract_first()
            name_of_page = page_on.split()[-1]
        else:
            pass
        if response.xpath("(//div[@class='paginate bg-muted'])//a[last()-1]//href").extract_first():
            url_link = response.xpath("(//div[@class='paginate bg-muted'])//a[last()-1]//href").extract_first()
            url_link = url_link.split('/')
            last_page = url_link[-1].split('=')[-1]
        else:
            pass
        all_pages = []
        for index, n in enumerate(url_link):
            for page_name, page_num in zip(name_of_page, last_page):

                if index == 5:
                    url_link[index] = page_name
                    testit='/'.join(url_link)
                    equal_split = testit.split('=')
                    for another_i, n2 in enumerate(equal_split):
                        if another_i == 3:
                            for range_val in range(1, page_num+1):
                                equal_split[another_i] = str(2)
                                all_pages.append('='.join(equal_split))

        for urls in all_pages:
            yield response.follow(
                urls, callback = self.parse.places
            )
    def parse_listings(self, response):
        loader = ItemLoader(ZooplasItem(), response=response)
        loader.default.output_processor = TakeFirst()
        loader.add_xpath("//article[@class='dp-sidebar-wrapper__summary']//h1//text()")
        yield loader.load_item()

process = CrawlerProcess(
    settings = {
        'FEED_URI':'zoopla.jl',
        'FEED_FORMAT':'jsonlines'
    }
)
process.crawl(ZooplasSpider)
process.start()

</code>```

I know the way of grabbing the urls works as I have tried it on a single url using the following:

```<code>url = "https://www.zoopla.co.uk/overseas/property/ireland/?new_homes=include&include_sold=false&pn=16"

list_of_stuff = ['Ireland', 'Germany','France']
pages_of_stuff = [5, 7, 6]

test = []
all_pages = []
j=0
for index, n in enumerate(a):
    for l_stuff, p_stuff in zip(list_of_stuff,pages_of_stuff):
        if index == 5:
            a[index] = l_stuff
            testit='/'.join(a)
            equal_split = testit.split('=')
            for another_i, n2 in enumerate(equal_split):
                if another_i == 3:
                    for range_val in range(1, p_stuff+1):
                        equal_split[another_i] = str(range_val)
                        print('='.join(equal_split))

</code>```

Which is the same as the one used above just a change of variables. this outputs the following links and they work:

```<code>https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=1
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=2
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=3
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=4
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=5
https://www.zoopla.co.uk/overseas/property/Germany/?new_homes=include&include_sold=false&pn=1
https://www.zoopla.co.uk/overseas/property/Germany/?new_homes=include&include_sold=false&pn=2
...
</code>```

答:
Your use case is suited for using scrapy crawl spider. You can write rules on how to extract links to the properties and how to extract links to the next pages. I have changed your code to use a crawl spider class and I have changed your FEEDS settings to use the recommended settings. FEED_URI and FEED_FORMAT are deprecated in newer versions of scrapy.

Read more about the crawl spider from the docs

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.crawler import CrawlerProcess
from scrapy.spiders import CrawlSpider, Rule
from scrapy.item import Field
from itemloaders.processors import TakeFirst
from scrapy.loader import ItemLoader

class ZooplasItem(scrapy.Item):
    stuff = Field()
    country = Field()

class ZooplasSpider(CrawlSpider):
    name = 'zooplas'
    allowed_domains = ['zoopla.co.uk']
    start_urls = ['https://www.zoopla.co.uk/overseas/']

    rules = (
        Rule(LinkExtractor(restrict_css='a.link-novisit'), follow=True), # follow the countries links
        Rule(LinkExtractor(restrict_css='div.paginate'), follow=True), # follow pagination links
        Rule(LinkExtractor(restrict_xpaths="//a[contains(@class,'listing-result')]"), callback='parse_item', follow=True), # follow the link to actual property listing
    )

    def parse_item(self, response):
        # here you are on the details page for each property
        loader = ItemLoader(ZooplasItem(), response=response)
        loader.default_output_processor = TakeFirst()
        loader.add_xpath("stuff", "//article[@class='dp-sidebar-wrapper__summary']//h1//text()")
        loader.add_xpath("country","//li[@class='ui-breadcrumbs__item'][3]/a/text()")
        yield loader.load_item()

if __name__ == '__main__':
    process = CrawlerProcess(
        settings = {
            'USER_AGENT': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.80 Safari/537.36',
            'FEEDS': {
                'zoopla.jl': {
                    'format': 'jsonlines'
                }
            }
        }
    )
    process.crawl(ZooplasSpider)
    process.start()
```

Body:
I am trying to get within several urls of a webpage and follow the response to the next parser to grab another set of urls on a page. However, from this page I need to grab the next page urls but I wanted to try this by manipulating the page string by parsing it and then passing this as the next page. However, the scraper crawls but it returns nothing not even the output on the final parser when I load item.

Note: I know that I can grab the next page rather simply with an if-statement on the href. However, I wanted to try something different in case I had to face a situation where I would have to do this.

Here's my scraper:

import scrapy
from scrapy.crawler import CrawlerProcess
from scrapy.item import Field
from itemloaders.processors import TakeFirst
from scrapy.loader import ItemLoader

class ZooplasItem(scrapy.Item):
    stuff = Field()
class ZooplasSpider(scrapy.Spider):
    name = 'zooplas'
    start_urls = ['https://www.zoopla.co.uk/overseas/']

    def start_request(self):
        for url in self.start_urls:
            yield scrapy.Request(
                url,
                callback = self.parse, )

    def parse(self, response):
        container = response.xpath("//ul[@class='list-inline list-unstyled']//li")
        for links in container:
            urls = links.xpath(".//a/@href").get()
            yield response.follow(
                urls, callback = self.parse_places
            )
    def parse_places(self, response):
        container = response.xpath("//ul[@class='listing-results clearfix js-gtm-list']//li")
        for links in container:
            urls = links.xpath('(//div[@class="listing-results-right clearfix"]//a)[position() mod 3=1]//@href').get()
            yield response.follow(
                urls, callback = self.parse_listings
            )
        if response.xpath("//div[@id='content']//div//h1//text()").extract_first():
            page_on = response.xpath("//div[@id='content']//div//h1//text()").extract_first()
            name_of_page = page_on.split()[-1]
        else:
            pass
        if response.xpath("(//div[@class='paginate bg-muted'])//a[last()-1]//href").extract_first():
            url_link = response.xpath("(//div[@class='paginate bg-muted'])//a[last()-1]//href").extract_first()
            url_link = url_link.split('/')
            last_page = url_link[-1].split('=')[-1]
        else:
            pass
        all_pages = []
        for index, n in enumerate(url_link):
            for page_name, page_num in zip(name_of_page, last_page):

                if index == 5:
                    url_link[index] = page_name
                    testit='/'.join(url_link)
                    equal_split = testit.split('=')
                    for another_i, n2 in enumerate(equal_split):
                        if another_i == 3:
                            for range_val in range(1, page_num+1):
                                equal_split[another_i] = str(2)
                                all_pages.append('='.join(equal_split))

        for urls in all_pages:
            yield response.follow(
                urls, callback = self.parse.places
            )
    def parse_listings(self, response):
        loader = ItemLoader(ZooplasItem(), response=response)
        loader.default.output_processor = TakeFirst()
        loader.add_xpath("//article[@class='dp-sidebar-wrapper__summary']//h1//text()")
        yield loader.load_item()

process = CrawlerProcess(
    settings = {
        'FEED_URI':'zoopla.jl',
        'FEED_FORMAT':'jsonlines'
    }
)
process.crawl(ZooplasSpider)
process.start()

I know the way of grabbing the urls works as I have tried it on a single url using the following:

url = "https://www.zoopla.co.uk/overseas/property/ireland/?new_homes=include&include_sold=false&pn=16"

list_of_stuff = ['Ireland', 'Germany','France']
pages_of_stuff = [5, 7, 6]

test = []
all_pages = []
j=0
for index, n in enumerate(a):
    for l_stuff, p_stuff in zip(list_of_stuff,pages_of_stuff):
        if index == 5:
            a[index] = l_stuff
            testit='/'.join(a)
            equal_split = testit.split('=')
            for another_i, n2 in enumerate(equal_split):
                if another_i == 3:
                    for range_val in range(1, p_stuff+1):
                        equal_split[another_i] = str(range_val)
                        print('='.join(equal_split))

Which is the same as the one used above just a change of variables. this outputs the following links and they work:

https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=1
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=2
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=3
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=4
https://www.zoopla.co.uk/overseas/property/Ireland/?new_homes=include&include_sold=false&pn=5
https://www.zoopla.co.uk/overseas/property/Germany/?new_homes=include&include_sold=false&pn=1
https://www.zoopla.co.uk/overseas/property/Germany/?new_homes=include&include_sold=false&pn=2
...


问:
Why am I getting a NG0901 error when I am not performing any data change?
In the following code segment, I am iterating over ardene.section1.items. I have logged this array to the console to verify that it does exist. The "BEFORE FOR LOOP" test is printed to the screen but the "INSIDE FOR LOOP" test is never printed. And I get  and NG0901 error which Angular tells me is a ngDoCheck error.

```<code><div class="row mt-4">
BEFORE FOR LOOP
<div class="col text-center col-12 col-md-3 mb-4 mb-md-0"
    *ngFor="let item of ardene.section1.items">
    INSIDE FOR LOOP
    <img class="img-fluid"
        src=`{{ardene.assetPath}}{{item.img}}`>
    <div>
        <h5 class="text-center fw-bold mt-2">{{item.name}}</h5>
        <h6 class="text-center">{{item.description}}<br></h6>
        <a>
            <h6 class="fw-bold">Shop Now</h6>
        </a>
    </div>
</div>
</code>```

The component code that produces ardene.section1.items is shown below.

```<code>  constructor(
    private store:Store<{ardeneState}>
  ) { }

  ngOnInit(): void {
    this.subscribeToReduxStores();
  }

private subscribeToReduxStores = () => {
const ardene$ = this.store.select(state => {
  return state.ardeneState
})

ardene$.subscribe(ardene => {
  this.ardene = ardene;

  console.log('ardene.section1.heading', this.ardene.section1.heading)
  console.log('ardene.section1.items', this.ardene.section1.items)
  console.log('ardene', this.ardene)
})
  }
</code>```

The data originates from the redux store:

```<code>const initialState = {
  assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

  section1: {
    heading: 'New Denim Guide',
    subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
    items: {
      img: 'ardene-6.jpg',
      name: 'Mom Jeans',
      description: 'The vintage silhouette',
      link: '',
    },
  },
};
</code>```

Error:

```<code>ERROR Error: NG0901
at e.find (main.10edf50a2ef1763e.js:1:146206)
at h.ngDoCheck (main.10edf50a2ef1763e.js:1:43158)
at Vs (main.10edf50a2ef1763e.js:1:56860)
at Bs (main.10edf50a2ef1763e.js:1:56661)
at yr (main.10edf50a2ef1763e.js:1:56381)
at ro (main.10edf50a2ef1763e.js:1:76106)
at Gy (main.10edf50a2ef1763e.js:1:82951)
at _y (main.10edf50a2ef1763e.js:1:76845)
at ro (main.10edf50a2ef1763e.js:1:76856)
at Hy (main.10edf50a2ef1763e.js:1:76404)
</code>```

答:
If subscription really does return some items for you then syntax could go something more like this:

<ng-container *ngIf="(ardene$ | async)?.section1 as item">

    BEFORE FOR LOOP

    heading: {{ item?.heading }}

    subheadting: {{ item?.subheading }}

      <img
        class="img-fluid"
        src="`{{ (ardene$ | async).assetPath }}{{ item?.items?.img }}`"
      />

{{ item?.items?.name }}

{{ item?.items?.description }}

Shop Now

</ng-container>
```
<pre class="lang-js prettyprint-override"><code>@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {

  ardene$: Observable<any> | undefined;
  ardeneObservable = new ReplaySubject<any>(1);

  ngAfterViewInit() {
    const ardene = {
      assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

      section1: {
        heading: 'New Denim Guide',
        subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
        items: {
          img: 'ardene-6.jpg',
          name: 'Mom Jeans',
          description: 'The vintage silhouette',
          link: '',
        },
      },
    };

    this.ardeneObservable.next(ardene);
  }

  ngOnInit() {
    this.ardene$ = this.ardeneObservable.pipe((data) => {
      return data;
    });
  }
}
</code>```

Here is a working example: https://stackblitz.com/edit/angular-ivy-i872hc?file=src%2Fapp%2Fapp.component.ts

Body:
In the following code segment, I am iterating over ardene.section1.items. I have logged this array to the console to verify that it does exist. The "BEFORE FOR LOOP" test is printed to the screen but the "INSIDE FOR LOOP" test is never printed. And I get  and NG0901 error which Angular tells me is a ngDoCheck error.

BEFORE FOR LOOP

    INSIDE FOR LOOP
    <img class="img-fluid"
        src=`{{ardene.assetPath}}{{item.img}}`>

{{item.name}}

{{item.description}}

Shop Now

The component code that produces ardene.section1.items is shown below.

  constructor(
    private store:Store<{ardeneState}>
  ) { }

  ngOnInit(): void {
    this.subscribeToReduxStores();
  }

private subscribeToReduxStores = () => {
const ardene$ = this.store.select(state => {
  return state.ardeneState
})

ardene$.subscribe(ardene => {
  this.ardene = ardene;

  console.log('ardene.section1.heading', this.ardene.section1.heading)
  console.log('ardene.section1.items', this.ardene.section1.items)
  console.log('ardene', this.ardene)
})
  }

The data originates from the redux store:

const initialState = {
  assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

  section1: {
    heading: 'New Denim Guide',
    subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
    items: {
      img: 'ardene-6.jpg',
      name: 'Mom Jeans',
      description: 'The vintage silhouette',
      link: '',
    },
  },
};

Error:

ERROR Error: NG0901
at e.find (main.10edf50a2ef1763e.js:1:146206)
at h.ngDoCheck (main.10edf50a2ef1763e.js:1:43158)
at Vs (main.10edf50a2ef1763e.js:1:56860)
at Bs (main.10edf50a2ef1763e.js:1:56661)
at yr (main.10edf50a2ef1763e.js:1:56381)
at ro (main.10edf50a2ef1763e.js:1:76106)
at Gy (main.10edf50a2ef1763e.js:1:82951)
at _y (main.10edf50a2ef1763e.js:1:76845)
at ro (main.10edf50a2ef1763e.js:1:76856)
at Hy (main.10edf50a2ef1763e.js:1:76404)

Body:
If subscription really does return some items for you then syntax could go something more like this:

<ng-container *ngIf="(ardene$ | async)?.section1 as item">
  <div class="row mt-4">
    BEFORE FOR LOOP
    <br />
    heading: {{ item?.heading }}
    <br />
    subheadting: {{ item?.subheading }}
    <div class="col text-center col-12 col-md-3 mb-4 mb-md-0">
      <img
        class="img-fluid"
        src="`{{ (ardene$ | async).assetPath }}{{ item?.items?.img }}`"
      />
      <div>
        <h5 class="text-center fw-bold mt-2">{{ item?.items?.name }}</h5>
        <h6 class="text-center">{{ item?.items?.description }}<br /></h6>
        <a>
          <h6 class="fw-bold">Shop Now</h6>
        </a>
      </div>
    </div>
  </div>
</ng-container>

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent implements OnInit, AfterViewInit {

  ardene$: Observable<any> | undefined;
  ardeneObservable = new ReplaySubject<any>(1);

  ngAfterViewInit() {
    const ardene = {
      assetPath: 'app/category/ladies-apparel/ardene/assets/img/',

      section1: {
        heading: 'New Denim Guide',
        subheading: "EVERYBODY'S OBSESSING OVER THESE STYLES",
        items: {
          img: 'ardene-6.jpg',
          name: 'Mom Jeans',
          description: 'The vintage silhouette',
          link: '',
        },
      },
    };

    this.ardeneObservable.next(ardene);
  }

  ngOnInit() {
    this.ardene$ = this.ardeneObservable.pipe((data) => {
      return data;
    });
  }
}

Here is a working example: https://stackblitz.com/edit/angular-ivy-i872hc?file=src%2Fapp%2Fapp.component.ts


答:
I modified your and here it is:

```<code>public int[] makeLast(int[] nums) {

    int lengonewarr = nums.length;

    int officiallength = lengonewarr * 2;

    int [] makezero = new int [officiallength];

    makezero [makezero.length-1] = nums[nums.length-1];

    return(makezero);

}
</code>```

As the array makezero is double size, the length of lengonewarr is always in the middle of makezero.

Title: When building array program in Java, it does not return the last number of the array when following the array.length - 1 method

Body:
I modified your and here it is:

public int[] makeLast(int[] nums) {

    int lengonewarr = nums.length;

    int officiallength = lengonewarr * 2;

    int [] makezero = new int [officiallength];

    makezero [makezero.length-1] = nums[nums.length-1];

    return(makezero);

}

As the array makezero is double size, the length of lengonewarr is always in the middle of makezero.


问:
git clone fatal: unable to access 'https://github.com/snsnsjsn/allen.github.io/': OpenSSL SSL_read: Connection was reset, errno 10054
i first time to create github.io page follow https://pages.github.com/

i have create repository , and install git.exe local win10, them
git clone https://github.com/username/username.github.io

but get the wrong info.

```<code>Cloning into 'username.github.io'...
fatal: unable to access 'https://github.com/username/username.github.io/': OpenSSL SSL_read: Connection was reset, errno 10054```
```

答:
you can use by</p>
```<code> git config --global http.sslVerify "false"
 git config --global https.sslVerify "false"
</code>```

Body:
i first time to create github.io page follow https://pages.github.com/

i have create repository , and install git.exe local win10, them
git clone https://github.com/username/username.github.io

but get the wrong info.

Cloning into 'username.github.io'...
fatal: unable to access 'https://github.com/username/username.github.io/': OpenSSL SSL_read: Connection was reset, errno 10054```

Body:
you can use by

 git config --global http.sslVerify "false"
 git config --global https.sslVerify "false"


问:
Tailwindcss 3 with Angular 13 - new styles don't show after ctrl+s livereaload
I am using Tailwindcss 3 with Angular 13.
When I apply new class (for example bg-cyan-500) the style is not added into final .css file and the change is not visible.
I have to kill the "ng serve" command and re-run it. After I re-run "ng serve" command everything works fine.
But it impossible to rerun "ng serve" with every css change I made.</p>

答:
updating angular version via CLI source</p>
```<code>ng update
</code>```

Body:
updating angular version via CLI source

ng update


问:
Azure Graph, filtering on activity and group membership
Is it possible, within a single GET call, to only obtain users who are members of one group, not a member of a different group and have signed in within X days?

I have been trying to do this with a call similar to:-

"https://graph.microsoft.com/beta/users?$select=id,signInActivity&$expand=memberOf&$filter=signInActivity/lastSignInDateTime le 2021-04-26T17:30:09Z&$filter=contains(memberOf.id,'11111111-1111-1111-1111-111111') and NOT contains(memberOf,'222222-2222-2222-2222-22222222')&$top=999"

but however I try to formulate the filter parameters it always produces an error

答:
You can use the below MS GraphAPI to get the list of members of particular group who has signed in under particular date and time.

Note : Details for the signInActivity property require an Azure AD
Premium P1/P2 license and the AuditLog.Read.All permission

```<code>https://graph.microsoft.com/beta/groups/{groupObjectID}?$expand=members&$filters=signInActivity/lastSignInDateTime ge 2022-01-21T00:00:00Z&$select=id,displayName
</code>```

Note: The Microsoft Graph API only supports the resource type signInActivity in users end-point not in group end-point. This is reason we can not filter member based on LastSignInDateTime on a group level

For more information you can refer this Document

Body:
You can use the below MS GraphAPI to get the list of members of particular group who has signed in under particular date and time.

Note : Details for the signInActivity property require an Azure AD
Premium P1/P2 license and the AuditLog.Read.All permission

https://graph.microsoft.com/beta/groups/{groupObjectID}?$expand=members&$filters=signInActivity/lastSignInDateTime ge 2022-01-21T00:00:00Z&$select=id,displayName

Note: The Microsoft Graph API only supports the resource type signInActivity in users end-point not in group end-point. This is reason we can not filter member based on LastSignInDateTime on a group level

For more information you can refer this Document