问:
My scanner class isn't reading the next line from the .txt file
I'm trying to read a text file that looks like this

```<code>0,-16,-4,12,10,4,-14,8,44,8,8,12,-4
1,-16,-4,12,10,4,-14,6,43,10,10,12,-4
2,-16,-6,10,11,2,-13,4,43,10,11,12,-4
3,-16,-6,10,11,2,-13,6,43,10,11,11,-4
4,-16,-6,10,11,2,-13,6,42,8,10,10,-4
</code>```

However I am only able to the first line then it stops, I'm using the hasNextInt function in a for loop and it reaches the end of the first line and then hasNextInt = null. What method can I use to carry on reading into the next line?

Thanks in advance for any help you can give me.

Here's the code:

```<code>public final static int numChannels = 12;   // the data is stored in 12 channels, one for each lead
public final static int numSamples = 500*6; //500 = fs so *6 for 6 seconds of data
public File file;
private Scanner scanner;
short [] [] ecg = new short [numChannels] [numSamples];

 public ECGFilereader (String fname) throws FileNotFoundException
 {
    File file = new File(Environment.getExternalStorageDirectory() +"/ecg.txt");

    scanner = new Scanner(file);

    scanner.useDelimiter(",");

}
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 3000 samples)
{
    for (int m=0; m<numSamples && scanner.hasNextInt(); m++)
    {
        String x = scanner.next();
        for (int chan = 0; chan<numChannels && scanner.hasNextInt(); chan++)
        {
            ecg [chan] [m] = (short) scanner.nextInt();
        }
    }

    for (int chan=0; chan<numChannels; chan++)
        waves[chan].setSignal(ecg[chan]); // sets a signal equal to the ecg array of channels
    return true;

}
</code>```

}

答:
I would check for the case when hasNextInt() returns false, and add the following:

```<code>if (!scanner.hasNextInt())
{
    if (scanner.hasNextLine())
    {
        scanner.nextLine();
    }
}
</code>```

This will consume the rest of the line and set the scanner to be at the beginning of the next line.

Body:
I'm trying to read a text file that looks like this

0,-16,-4,12,10,4,-14,8,44,8,8,12,-4
1,-16,-4,12,10,4,-14,6,43,10,10,12,-4
2,-16,-6,10,11,2,-13,4,43,10,11,12,-4
3,-16,-6,10,11,2,-13,6,43,10,11,11,-4
4,-16,-6,10,11,2,-13,6,42,8,10,10,-4

However I am only able to the first line then it stops, I'm using the hasNextInt function in a for loop and it reaches the end of the first line and then hasNextInt = null. What method can I use to carry on reading into the next line?

Thanks in advance for any help you can give me.

Here's the code:

public final static int numChannels = 12;   // the data is stored in 12 channels, one for each lead
public final static int numSamples = 500*6; //500 = fs so *6 for 6 seconds of data
public File file;
private Scanner scanner;
short [] [] ecg = new short [numChannels] [numSamples];

 public ECGFilereader (String fname) throws FileNotFoundException
 {
    File file = new File(Environment.getExternalStorageDirectory() +"/ecg.txt");

    scanner = new Scanner(file);

    scanner.useDelimiter(",");

}
public boolean ReadFile(Waveform[] waves) // sorts data into and array of an array (12 channels each containing 3000 samples)
{
    for (int m=0; m<numSamples && scanner.hasNextInt(); m++)
    {
        String x = scanner.next();
        for (int chan = 0; chan<numChannels && scanner.hasNextInt(); chan++)
        {
            ecg [chan] [m] = (short) scanner.nextInt();
        }
    }

    for (int chan=0; chan<numChannels; chan++)
        waves[chan].setSignal(ecg[chan]); // sets a signal equal to the ecg array of channels
    return true;

}

}

Body:
I would check for the case when hasNextInt() returns false, and add the following:

if (!scanner.hasNextInt())
{
    if (scanner.hasNextLine())
    {
        scanner.nextLine();
    }
}

This will consume the rest of the line and set the scanner to be at the beginning of the next line.


来源: stackexchange

问:
MySQL RAND() from a range of latest entries (ORDER BY id DESC LIMIT 0,1) – Is this possible?
Here's what I'm trying to achieve:

I would like to show a random entry from the latest posts in four categories.

I've tried combining RAND() with ORDER BY contentID DESC LIMIT 0,1 but that doesn't work:

```<code>SELECT cc.pageID, cc.contentID, cc.contentTitle, cc.contentDate, cc.contentImage, cc.contentText, cs.pageName, cs.pageLabel_".$lang." AS pageLabel, cs.pageImage, ca.authorImage
FROM cheeseus_content cc
JOIN cheeseus_sections cs ON cc.pageID = cs.pageID
JOIN cheeseus_authors ca ON cc.contentAuthor = ca.authorID
WHERE cc.pageID IN (18, 19, 20, 21)
ORDER BY RAND(), cc.contentID DESC LIMIT 0,1
</code>```

Is what I'm looking for possible and how?

答:
Assuming you are running MySQL 8 or later, you may use ROW_NUMBER:

WITH cte AS (
    SELECT cc.pageID, cc.contentID, cc.contentTitle, cc.contentDate,
           cc.contentImage, cc.contentText, cs.pageName,
           cs.pageLabel_".$lang." AS pageLabel, cs.pageImage, ca.authorImage,
           ROW_NUMBER() OVER (PARTITION BY cc.pageID ORDER BY RAND()) rn
    FROM cheeseus_content cc
    INNER JOIN cheeseus_sections cs ON cc.pageID = cs.pageID
    INNER JOIN cheeseus_authors ca ON cc.contentAuthor = ca.authorID
    WHERE cc.pageID IN (18, 19, 20, 21)
)

SELECT *
FROM cte
WHERE rn = 1;
```

ContentLicense: CC BY-SA 4.0

Body:
Here's what I'm trying to achieve:

I would like to show a random entry from the latest posts in four categories.

I've tried combining RAND() with ORDER BY contentID DESC LIMIT 0,1 but that doesn't work:

SELECT cc.pageID, cc.contentID, cc.contentTitle, cc.contentDate, cc.contentImage, cc.contentText, cs.pageName, cs.pageLabel_".$lang." AS pageLabel, cs.pageImage, ca.authorImage
FROM cheeseus_content cc
JOIN cheeseus_sections cs ON cc.pageID = cs.pageID
JOIN cheeseus_authors ca ON cc.contentAuthor = ca.authorID
WHERE cc.pageID IN (18, 19, 20, 21)
ORDER BY RAND(), cc.contentID DESC LIMIT 0,1

Is what I'm looking for possible and how?


问:
JMeter: Does the **Save Responses to a File** storing the data in the cache first when the request is not yet done?
I'm currently testing a 1.5GB download. Does the Save Responses to a File storing the data in the cache first when the request is not yet done? Is it possible to configure the JMeter to write the file while receiving the data?

答:
As of JMeter 5.4.3 the Save Responses to a File listener:

Waits for the full response to arrive to JMeter

Writes it using BufferedOutpuStream via JOrphanUtils.write() function

It's not possible to easily amend this behaviour unless you're willing to write a custom plugin for JMeter

I can suggest a better option: instead of saving the whole file you could:

Tick Save response as MD5 hash? box under "Advanced" tab of the HTTP Request sampler

The downloaded file integrity can be checked using MD5Hex Assertion

The point is that same files have the same MD5 checksum, if the downloaded file's checksum will be different - it means that the file content differs and MD5Hex Assertion will fail the associated Sampler.

As a bonus, this trick will greatly reduce JMeter's memory consumption and you will be able to conduct higher load from the same machine.

More information on JMeter Assertions concept: How to Use JMeter Assertions in Three Easy Steps


问:
How can I add startDestination programmatically accoridng the value?
How can I add startDestination programmatically according the value for example if the integer variable was 0 then I want to start navigation_main_countries_fragment, Otherwise navigation_main_categories_fragment.

Inside activity_main

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/activity_main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:navGraph="@navigation/navigation_main" //I deleted this line already
    android:layout_weight="1" />
```
<p>Inside <code>navigation_main</code></p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/navigation_main_countries_fragment" //I deleted this line already
    tools:ignore="InvalidNavigation">

    <fragment
        android:id="@+id/navigation_main_countries_fragment"
        android:name="com.test.app.fragments.CountriesFragment"
        tools:layout="@layout/fragment_countries" />

    <fragment
        android:id="@+id/navigation_main_categories_fragment"
        android:name="com.test.app.fragments.CategoriesFragment"
        tools:layout="@layout/fragment_categories" />

</navigation>
</code>```

答:
You can use below code for start destination</p>
```<code>val navHostFragment = (supportFragmentManager.findFragmentById(R.id.home_nav_fragment) as NavHostFragment)
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_main)
graph.startDestination = R.id.fragment1

navHostFragment.navController.graph = graph
</code>```

Body:
How can I add startDestination programmatically according the value for example if the integer variable was 0 then I want to start navigation_main_countries_fragment, Otherwise navigation_main_categories_fragment.

Inside activity_main

<androidx.fragment.app.FragmentContainerView
    android:id="@+id/activity_main_container"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:navGraph="@navigation/navigation_main" //I deleted this line already
    android:layout_weight="1" />

Inside navigation_main

<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    app:startDestination="@id/navigation_main_countries_fragment" //I deleted this line already
    tools:ignore="InvalidNavigation">

    <fragment
        android:id="@+id/navigation_main_countries_fragment"
        android:name="com.test.app.fragments.CountriesFragment"
        tools:layout="@layout/fragment_countries" />

    <fragment
        android:id="@+id/navigation_main_categories_fragment"
        android:name="com.test.app.fragments.CategoriesFragment"
        tools:layout="@layout/fragment_categories" />

</navigation>

Body:
You can use below code for start destination

val navHostFragment = (supportFragmentManager.findFragmentById(R.id.home_nav_fragment) as NavHostFragment)
val inflater = navHostFragment.navController.navInflater
val graph = inflater.inflate(R.navigation.nav_main)
graph.startDestination = R.id.fragment1

navHostFragment.navController.graph = graph


问:
MockGeolocation API did not show the "Allow location" popup on browser
I have created the test scripts where in Mock Geolocation API is supposed to be used. The code did not populate the "Allow location" popup.
Here's the snippet:

```<code>  "navigator.geolocation.getCurrentPosition = success =>  success({ coords: { latitude: 30,
 longitude: -105, }, timestamp: Date.now() });";

 fixture`blah`.page`google.com`.clientScripts({
  content: mockGeolocationScript,
});
</code>```

Am I missing something?

答:
You are right, the "Allow location" dialog doesn't appear when the test is running because it's a native dialog, so the TestCafe framework cannot process it. This behavior is correct.

You correctly mocked the "navigator.geolocation.getCurrentPosition" function, so it should return your mocked data during test execution.

Body:
I have created the test scripts where in Mock Geolocation API is supposed to be used. The code did not populate the "Allow location" popup.
Here's the snippet:

  "navigator.geolocation.getCurrentPosition = success =>  success({ coords: { latitude: 30,
 longitude: -105, }, timestamp: Date.now() });";

 fixture`blah`.page`google.com`.clientScripts({
  content: mockGeolocationScript,
});

Am I missing something?


问:
Best way to handle api callbacks in wordpos library?
I'm new handling promises in javascript and I've found a problem with this node js lib https://www.npmjs.com/package/wordpos I'm trying to find all the verbs that are found inside an arrays of strings, and for this I've created this function:

```<code>function calculateVerbsAmount(stringsArray) {
return stringsArray.map(function(item) {
    let element = wordpos.getVerbs(item, function(result){
        return result;
    });
});
</code>```

}

What I expect is to have a new array, this time of verb strings, but since the lib handles the methods as callbacks I'm getting

```<code>[Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> }]
</code>```

I've tried added async/await but they always return the same result, any idea on how to do some synchronous call to the wordpos.getVerbs method?

答:
Calling wordpos.getVerbs() returns a promise. Since you are doing this inside a .map function your stringsArray will be an array of promises (as you actually get as return.).

A single Promise can be unwraped using await. For an array of Promises you can use Promise.all helper which allows waiting for each Promise within an array.

Example

async function calculateVerbsAmount(stringsArray) {
    const verbPromises = stringsArray.map(function(item) {
        let element = wordpos.getVerbs(item, function(result){
            return result;
        });
    });

    // await every Promise within the verbPromises array. Promise.all
    // returns a single Promise which holds an array with the native values
    return Promise.all(verbPromises)
}

// the keyword "await" can only be used within an async function.
// So for showcasing it i created the main() function ..
async function main() {

    // Now call the calculateVerbsAmount() and await it for receiving the expected
    // array of strings.
    const verbs = await calculateVerbsAmount()
}

```

Body:
I'm new handling promises in javascript and I've found a problem with this node js lib https://www.npmjs.com/package/wordpos I'm trying to find all the verbs that are found inside an arrays of strings, and for this I've created this function:

function calculateVerbsAmount(stringsArray) {
return stringsArray.map(function(item) {
    let element = wordpos.getVerbs(item, function(result){
        return result;
    });
});

}

What I expect is to have a new array, this time of verb strings, but since the lib handles the methods as callbacks I'm getting

[Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> },
Promise { <pending> }, Promise { <pending> }]

I've tried added async/await but they always return the same result, any idea on how to do some synchronous call to the wordpos.getVerbs method?


问:
Pandas Split String in colum into colums with 0/1 ; get dummies on all characters of a string
Very likely this question was answered, but I can not find a good title. I have this pandas data structure, based on a given excel sheet:

other columns
Code

...
ABC

...
CAB

...
R

I want to get this:

other columns
A
B
C
R

...
1
1
1
0

...
1
1
1
0

...
0
0
0
1

Of course, I could iterate over each row and so this manually, but all ideas in my head will either be slow or memory consuming or both.

What is the one line solution here?

答:
You can use str.get_dummies with an empty separator to get all letters:

```<code>df['Code'].str.get_dummies(sep='')
</code>```

joining to original data:

```<code>df2 = df.drop('Code', axis=1).join(df['Code'].str.get_dummies(sep=''))
</code>```

output:

```<code>  other columns   A  B  C  R
0           ...   1  1  1  0
1           ...   1  1  1  0
2           ...   0  0  0  1
</code>```

Body:
You can use str.get_dummies with an empty separator to get all letters:

df['Code'].str.get_dummies(sep='')

joining to original data:

df2 = df.drop('Code', axis=1).join(df['Code'].str.get_dummies(sep=''))

output:

  other columns   A  B  C  R
0           ...   1  1  1  0
1           ...   1  1  1  0
2           ...   0  0  0  1


Title: Is there a method that replace NaN values with values of previous 24 hours?

Body:
I would like to replace the value NaN of day 20211021 - HOUR 1 with the value of day 20211020 - HOUR 1, the value of day day 20211021 - HOUR 2 with the value of day 20211020 - HOUR 2...

timestamp
data
year
month
day
hour
solar_total

2021-10-20 00:00:00
20211020
2021
10
20
1
0.0

2021-10-20 01:00:00
20211020
2021
10
20
2
0.0

2021-10-20 02:00:00
20211020
2021
10
20
3
0.0

2021-10-20 03:00:00
20211020
2021
10
20
4
0.0

2021-10-20 04:00:00
20211020
2021
10
20
5
0.0

2021-10-20 05:00:00
20211020
2021
10
20
6
0.0

2021-10-20 06:00:00
20211020
2021
10
20
7
0.0

2021-10-20 07:00:00
20211020
2021
10
20
8
65.0

2021-10-20 08:00:00
20211020
2021
10
20
9
1498.0

2021-10-20 09:00:00
20211020
2021
10
20
10
4034.0

2021-10-20 10:00:00
20211020
2021
10
20
11
6120.0

2021-10-20 11:00:00
20211020
2021
10
20
12
7450.0

2021-10-20 12:00:00
20211020
2021
10
20
13
7943.0

2021-10-20 13:00:00
20211020
2021
10
20
14
7821.0

2021-10-20 14:00:00
20211020
2021
10
20
15
7058.0

2021-10-20 16:00:00
20211020
2021
10
20
17
3664.0

2021-10-20 17:00:00
20211020
2021
10
20
18
1375.0

2021-10-20 18:00:00
20211020
2021
10
20
19
11.0

2021-10-20 19:00:00
20211020
2021
10
20
20
0.0

2021-10-20 20:00:00
20211020
2021
10
20
21
0.0

2021-10-20 21:00:00
20211020
2021
10
20
22
0.0

2021-10-20 22:00:00
20211020
2021
10
20
23
0.0

2021-10-20 23:00:00
20211020
2021
10
20
24
0.0

2021-10-21 00:00:00
20211021
2021
10
21
1
NaN

2021-10-21 01:00:00
20211021
2021
10
21
2
NaN

2021-10-21 02:00:00
20211021
2021
10
21
3
NaN

2021-10-21 03:00:00
20211021
2021
10
21
4
NaN

2021-10-21 04:00:00
20211021
2021
10
21
5
NaN

2021-10-21 05:00:00
20211021
2021
10
21
6
NaN

2021-10-21 06:00:00
20211021
2021
10
21
7
NaN

2021-10-21 07:00:00
20211021
2021
10
21
8
NaN

2021-10-21 08:00:00
20211021
2021
10
21
9
NaN

2021-10-21 09:00:00
20211021
2021
10
21
10
NaN

2021-10-21 10:00:00
20211021
2021
10
21
11
NaN

2021-10-21 11:00:00
20211021
2021
10
21
12
NaN

2021-10-21 12:00:00
20211021
2021
10
21
13
NaN

2021-10-21 13:00:00
20211021
2021
10
21
14
NaN

2021-10-21 14:00:00
20211021
2021
10
21
15
NaN

2021-10-21 15:00:00
20211021
2021
10
21
16
NaN

2021-10-21 16:00:00
20211021
2021
10
21
17
NaN

2021-10-21 17:00:00
20211021
2021
10
21
18
NaN

2021-10-21 18:00:00
20211021
2021
10
21
19
NaN

2021-10-21 19:00:00
20211021
2021
10
21
20
NaN

2021-10-21 20:00:00
20211021
2021
10
21
21
NaN

2021-10-21 21:00:00
20211021
2021
10
21
22
NaN

2021-10-21 22:00:00
20211021
2021
10
21
23
NaN

2021-10-21 23:00:00
20211021
2021
10
21
24
NaN

Body:
If you have no missing timestamp, shift your rows by 23:

df['solar_total'] = df['solar_total'].fillna(df['solar_total'].shift(23))

timestamp
data
year
month
day
hour
solar_total

2021-10-20 00:00:00
20211020
2021
10
20
1
0

2021-10-20 01:00:00
20211020
2021
10
20
2
0

2021-10-20 02:00:00
20211020
2021
10
20
3
0

2021-10-20 03:00:00
20211020
2021
10
20
4
0

2021-10-20 04:00:00
20211020
2021
10
20
5
0

2021-10-20 05:00:00
20211020
2021
10
20
6
0

2021-10-20 06:00:00
20211020
2021
10
20
7
0

2021-10-20 07:00:00
20211020
2021
10
20
8
65

2021-10-20 08:00:00
20211020
2021
10
20
9
1498

2021-10-20 09:00:00
20211020
2021
10
20
10
4034

2021-10-20 10:00:00
20211020
2021
10
20
11
6120

2021-10-20 11:00:00
20211020
2021
10
20
12
7450

2021-10-20 12:00:00
20211020
2021
10
20
13
7943

2021-10-20 13:00:00
20211020
2021
10
20
14
7821

2021-10-20 14:00:00
20211020
2021
10
20
15
7058

2021-10-20 16:00:00
20211020
2021
10
20
17
3664

2021-10-20 17:00:00
20211020
2021
10
20
18
1375

2021-10-20 18:00:00
20211020
2021
10
20
19
11

2021-10-20 19:00:00
20211020
2021
10
20
20
0

2021-10-20 20:00:00
20211020
2021
10
20
21
0

2021-10-20 21:00:00
20211020
2021
10
20
22
0

2021-10-20 22:00:00
20211020
2021
10
20
23
0

2021-10-20 23:00:00
20211020
2021
10
20
24
0

2021-10-21 00:00:00
20211021
2021
10
21
1
0

2021-10-21 01:00:00
20211021
2021
10
21
2
0

2021-10-21 02:00:00
20211021
2021
10
21
3
0

2021-10-21 03:00:00
20211021
2021
10
21
4
0

2021-10-21 04:00:00
20211021
2021
10
21
5
0

2021-10-21 05:00:00
20211021
2021
10
21
6
0

2021-10-21 06:00:00
20211021
2021
10
21
7
0

2021-10-21 07:00:00
20211021
2021
10
21
8
65

2021-10-21 08:00:00
20211021
2021
10
21
9
1498

2021-10-21 09:00:00
20211021
2021
10
21
10
4034

2021-10-21 10:00:00
20211021
2021
10
21
11
6120

2021-10-21 11:00:00
20211021
2021
10
21
12
7450

2021-10-21 12:00:00
20211021
2021
10
21
13
7943

2021-10-21 13:00:00
20211021
2021
10
21
14
7821

2021-10-21 14:00:00
20211021
2021
10
21
15
7058

2021-10-21 15:00:00
20211021
2021
10
21
16
3664

2021-10-21 16:00:00
20211021
2021
10
21
17
1375

2021-10-21 17:00:00
20211021
2021
10
21
18
11

2021-10-21 18:00:00
20211021
2021
10
21
19
0

2021-10-21 19:00:00
20211021
2021
10
21
20
0

2021-10-21 20:00:00
20211021
2021
10
21
21
0

2021-10-21 21:00:00
20211021
2021
10
21
22
0

2021-10-21 22:00:00
20211021
2021
10
21
23
0

2021-10-21 23:00:00
20211021
2021
10
21
24
nan


问:
Sending/Receiving Image over TCP Socket in C#
I am trying to Send the image to the Client which is connected to my TCP Listner (Server). I am successfully sending and receiving text over Network but I am unable to send the picture to the client from my server. I want to Dislpay the picture in PictureBox placed in the Client Window.
Here is a Code I am using to Send and Receive text BUT NOT PICTURE

SERVER:

RECEIVER:

```<code>void TListner()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpListener tl = new TcpListener(ipendp);
            tl.Start();
            Socket s1 = tl.AcceptSocket(); ;
            NetworkStream ns = new NetworkStream(s1);
            StreamReader sr = new StreamReader(ns);

            while (true)
            {
                    textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }

    }
</code>```

SENDER:

```<code>        MemoryStream ms = new MemoryStream();
        sw.Write("TEST STRING");
        sw.Flush();
</code>```

CLIENT:

RECEIVER:

```<code>    void TCP_CLIENT()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpClient tcpc = new TcpClient();
            tcpc.Connect(ipendp);
            NetworkStream ns = tcpc.GetStream();
            StreamReader sr = new StreamReader(ns);
            while (true)
            {
                textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }
</code>```

I want to display the picture in a PictureBox named PBox1 in Client Window.

答:
You're find to send and receive text because you're using StreamReader and StreamWriter. Those deal with text. You haven't actually shown the code you're trying to use for sending pictures, but fundamentally you mustn't use Reader/Writer unless you're performing some sort of extra encoding first (e.g. base64).

Also, unless you're going to close the writing socket immediately after sending, you should probably write the data length (e.g. as 4 bytes) before the data so that the receiving socket knows how much it needs to receive.

ContentLicense: CC BY-SA 3.0

Body:
I am trying to Send the image to the Client which is connected to my TCP Listner (Server). I am successfully sending and receiving text over Network but I am unable to send the picture to the client from my server. I want to Dislpay the picture in PictureBox placed in the Client Window.
Here is a Code I am using to Send and Receive text BUT NOT PICTURE

SERVER:

RECEIVER:

void TListner()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpListener tl = new TcpListener(ipendp);
            tl.Start();
            Socket s1 = tl.AcceptSocket(); ;
            NetworkStream ns = new NetworkStream(s1);
            StreamReader sr = new StreamReader(ns);

            while (true)
            {
                    textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }

    }

SENDER:

        MemoryStream ms = new MemoryStream();
        sw.Write("TEST STRING");
        sw.Flush();

CLIENT:

RECEIVER:

    void TCP_CLIENT()
    {
        try
        {
            IPEndPoint ipendp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080);
            TcpClient tcpc = new TcpClient();
            tcpc.Connect(ipendp);
            NetworkStream ns = tcpc.GetStream();
            StreamReader sr = new StreamReader(ns);
            while (true)
            {
                textBox1.Text = sr.ReadLine();
            }
        }
        catch
        {
            Application.Exit();
        }

I want to display the picture in a PictureBox named PBox1 in Client Window.


问:
asp.net core check route attribute in middleware
I'm trying to build some ASP.Net core middleware.

It needs see if the current route is marked as [Authorize].

eg:

```<code>public async Task Invoke(HttpContext context)
{
    if(context.Request.Path.Value.StartsWith("/api"))
    {
        // check if route is marked as [Authorize]
        // and then do some logic
    }

    await _next.Invoke(context);
}
</code>```

Does anyone know how this could be achieved or if it's even possible?

If not, what would be a good alternative approach?

答:
HansElsen's answer is correct, but I would like to add some things to note about it:

You can use the extension method context.GetEndpoint() which is exactly the same as context.Features.Get<IEndpointFeature>().Endpoint

The endpoint will always be null if you set up your middleware before calling app.UseRouting() in your Startup.cs:

Don't do:

```<code>app.UseMiddleware<MyMiddleware>();
app.UseRouting();
</code>```

Do:

```<code>app.UseRouting();
app.UseMiddleware<MyMiddleware>();
</code>```

Body:
I'm trying to build some ASP.Net core middleware.

It needs see if the current route is marked as [Authorize].

eg:

public async Task Invoke(HttpContext context)
{
    if(context.Request.Path.Value.StartsWith("/api"))
    {
        // check if route is marked as [Authorize]
        // and then do some logic
    }

    await _next.Invoke(context);
}

Does anyone know how this could be achieved or if it's even possible?

If not, what would be a good alternative approach?

Body:
HansElsen's answer is correct, but I would like to add some things to note about it:

You can use the extension method context.GetEndpoint() which is exactly the same as context.Features.Get<IEndpointFeature>().Endpoint

The endpoint will always be null if you set up your middleware before calling app.UseRouting() in your Startup.cs:

Don't do:

app.UseMiddleware<MyMiddleware>();
app.UseRouting();

Do:

app.UseRouting();
app.UseMiddleware<MyMiddleware>();


问:
Conditional fill a value in Data frame based on ranges
I want to make groups according to age ranges in a data frame.
I tried:

```<code>DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", NA)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", NA)
...
</code>```

but the next line replaces data assigned by the previous code.
I could manage the groupings into separate columns and then merge them but there must be a simple and straightforward way to do so. Can anyone help?

答:
In your code, you have to replace NA with the name of the variable, in this case AgeGroup. This way, the ifelse function replaces the FALSE values with the previous ones.

You have to do this from the second line on...

```<code>DF$AgeGroup <- ""
DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", DF$AgeGroup)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", DF$AgeGroup)
</code>```

...

Body:
I want to make groups according to age ranges in a data frame.
I tried:

DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", NA)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", NA)
...

but the next line replaces data assigned by the previous code.
I could manage the groupings into separate columns and then merge them but there must be a simple and straightforward way to do so. Can anyone help?

Body:
In your code, you have to replace NA with the name of the variable, in this case AgeGroup. This way, the ifelse function replaces the FALSE values with the previous ones.

You have to do this from the second line on...

DF$AgeGroup <- ""
DF$AgeGroup <- ifelse(DF$Age >= 20 & DF$Age <= 29, "G2", NA)
DF$AgeGroup <- ifelse(DF$Age >= 30 & DF$Age <= 39, "G3", DF$AgeGroup)
DF$AgeGroup <- ifelse(DF$Aag >= 40 & DF$Age <= 49, "G4", DF$AgeGroup)

...


问:
Create Random number sequence without duplicates in excel for almost million rows or records
I would want to create a random sequence of numbers in 11 digit format and that should run from 10000000000 to 999999999999 and each of the values should be unique and i would like to populate almost 20-50 million worth of records in excel without having to keep dragging all the way down at the bottom of the cell by clicking + button

I tried using  RANDBETWEEN but seems like there are duplicates and i have to keep dragging which is a time consuming activity,is there any alternative better way to accomplish this ?

```<code>=RANDBETWEEN(10000000000,999999999999)
</code>```

答:
For that many unique numbers I suggest using an encryption, where the output is guaranteed unique for unique inputs.

Simply encrypt the numbers 0, 1, 2, ... for different unique inputs.  You will need to use the same encryption key and other inputs (IV, nonce etc.) to guarantee unique outputs.

You will need to do some processing on the outputs to get them into the required range.  Have a look at Format Preserving Encryption for some help with this.

As @BigBen pointed out, Excel is probably the wrong tool for this.

Body:
I would want to create a random sequence of numbers in 11 digit format and that should run from 10000000000 to 999999999999 and each of the values should be unique and i would like to populate almost 20-50 million worth of records in excel without having to keep dragging all the way down at the bottom of the cell by clicking + button

I tried using  RANDBETWEEN but seems like there are duplicates and i have to keep dragging which is a time consuming activity,is there any alternative better way to accomplish this ?

=RANDBETWEEN(10000000000,999999999999)


问:
Login button not giving submit info while hitting enter works for getting credentials
I'm currently creating a phishing test for my employees and I got into a problem.I'm hosting my index.html on my local server using xampp and I want to when someone logs that I can get their info.I made a post.php that gives me the info when i use an username and password and it works.But it only works when I hit enter,when I clik on login it just redirects me to a page I made and I don't get any info in my text file.While I hover over my login button (Activate) it gives me that it redirects to the redircet page that I made.Do you have any suggestions how can I make that m,y login button(activate in the code) still gives me the info as same when I hit enter?
Thank you.

My code is below for index.html.

```<code>    <html><head>
        </div>
                <form id="loginForm" name="loginForm" method="post" action="post.php" onsubmit="return doLogin2();">
                    <div id="panelbody">
                        <div id="branding" class="clearfix branding">
                            <img id="loginWheel" src="web%20FTP%20WebInterface_files/wheel.gif" style="display: none;">
                            <a id="defaultLogoLink" href="http://www.crushftp.com/">
                                <img id="imgLogo" src="web%20FTP%20WebInterface_files/logo.png" style="border-width:0px;float:left;">
                            </a>
                        </div>
                        <div id="panelLogin">
                            <div>
                                <label id="UserNameText">Username</label>
                                <input tabindex="1" autocomplete="on" type="text" class="textbox" name="username" id="username" value="/">
                            </div>
                            <div>
                                <label id="PasswordText">Password</label>
                                <input tabindex="2" autocomplete="on" type="password" class="textbox" name="password" id="password" value="">
                            </div>
                            <div id="rememberMePanel">
                                <label><input tabindex="3" type="checkbox" name="remember" id="remember" checked="checked"> <span id="RememberMeText">Remember Me</span></label>
                            </div>
                            <div id="acceptTC" style="display: none">
                                <label><input tabindex="4" type="checkbox" name="tandc" id="tandc"> <span id="TnCText"></span></label>
                            </div>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <div id="recaptcha_div"></div>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <div class="submit clearfix">
                                <input type="submit" value="login" style="display:none;">
                                <input type="hidden" name="command" value="login">
                                <input type="hidden" name="skip_login" value="true">
                                <input type="hidden" name="encoded" value="false">
                                <input type="submit" value="login now" style="position:absolute;left:-1000px;top:-1000px;">
                                <a class="button" id="btnLogin" href="javascript:void(0);">
                                    <span id="LoginButtonText">Login</span>
                                </a>
                            </div>
                            <p class="lostpassword" style="visibility:hidden;">
                                <a href="#" class="showResetPanel" id="ForgotPasswordLinkText">I forgot my password</a>
                            </p>
                        </div>
                        <div id="panelResetPass" style="display:none;">
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <h3 class="resetTitle" id="RequestPasswordHeaderText">Request Password</h3>
                            <div>
                                <label id="ResetUserNameText">Username</label>
                                <input autocomplete="off" type="text" class="textbox" name="resetUserName" id="resetUserName">
                            </div>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <p></p>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <div class="submit clearfix">
                                <a class="button" id="btnResetPassword" href="javascript:void(0);">
                                    <span id="ResetPasswordButtonText">Reset Password</span>
                                </a>
                                <a class="button" id="btnBackToLogin" href="javascript:void(0);">
                                    <span id="BackToLoginButtonText">Back to Login</span>
                                </a>
                            </div>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <p></p>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                            <p></p>
                            <div style="clear:both;height:1px;padding:0px;margin:0px;"></div>
                        </div>
                    </div>
                </form>
                <form id="changePassForm" method="post" target="dummyIframe" action="/WebInterface/function/" onsubmit="doLogin();">
                    <div id="changepasswordPanel" style="display:none;margin-bottom:10px;">
                        <div class="clearfix branding" style="clear:both;">
                            <a id="defaultLogoLink" href="http://www.crushftp.com/">
                                <img id="imgLogo" src="web%20FTP%20WebInterface_files/logo.png" style="border-width:0px;float:left;margin:3px 0px 10px 0px;">
                            </a>
                        </div>
                        <h2 class="popupHeader" style="clear:both;margin-top:15px;" id="ChangePasswordHeaderText">Change your password</h2>
                        <div class="passwordChangeNote" id="ChangePasswordNoteText">You must change your password to continue</div>
                        <div class="buttonPanel">
                            <label for="current_password" id="CurrentPasswordText">Current Password : </label>
                            <input id="current_password" class="textbox" type="password">
                            <br>
                            <br>
                            <label for="new_password1" id="NewPasswordText">New Password : </label>
                            <input id="new_password1" class="textbox" type="password">
                            <br>
                            <br>
                            <label for="new_password2" id="ConfirmPasswordText">Confirm Password : </label>
                            <input id="new_password2" class="textbox" type="password">
                            <div style="text-align:right;margin-top:10px;">
                                <a id="btnChangePasswordCancel" class="button" href="javascript:void(0);">
                                    <span id="CancelButtonText">Cancel</span>
                                </a>
                                <a id="btnChangePassword" class="button" href="javascript:void(0);">
                                    <span id="ChanngePasswordButtonText">Change Password</span>
                                </a>
                            </div>
                            <div style="clear:both"></div>
                            <div class="spacing">
                                <br>
                                <hr>
                                <br>
                            </div>
                            <div id="generatePasswordPanel">
                                <a id="btnGeneratePassword" class="button" href="javascript:void(0);" style="float:left">
                                    <span id="GeneratePasswordButtonText">Generate password</span>
                                </a>
                                <div id="passwordGeneratePanel" style="display:none;">
                                    <br>
                                    <br>
                                    <input id="generated_password" type="text" class="textboxSmall" style="float:left;">
                                    <a id="usePassword" class="button" href="javascript:void(0);" style="float:left">
                                        <span id="GeneratePasswordUseButtonText">Use this</span>
                                    </a>
                                    <a id="cancelPassword" class="button" href="javascript:void(0);" style="float:left">
                                        <span id="GeneratePasswordCancelButtonText">Cancel</span>
                                    </a>
                                </div>
                                <div style="clear:both"></div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
            <div id="OTPBox" style="display:none;">
                <img class="closeButton" alt="close" src="web%20FTP%20WebInterface_files/cancel.png" onclick="$.unblockUI();">
                <h2 class="popupHeader" id="OTPDialogHeaderText">Enter your OTP here</h2>
                <div class="buttonPanel">
                    <div style="width:100%;">
                        <input id="otp" type="password" style="width:95%;padding:5px;">
                    </div>
                    <br>
                    <div id="OTPDialogDescText"></div>
                    <br>
                    <div style="text-align: right; margin-top: 10px;">
                        <button id="btnSubmitOTP">
                        <span id="OTPSubmitButtonText">Submit</span>
                        </button>
                    </div>
                </div>
            </div>
            <div id="loginPageFooterText">

            </div>
            <iframe id="dummyIframe" name="dummyIframe" src="javascript:false;" style="display:none;"></iframe>
</body></html>
</code>```

this is my post.php

```<code><?php

// Set the location to redirect the page
header ('Location: http://localhost/redirect.html');

// Open the text file in writing mode
$file = fopen("log.txt", "a");

foreach($_POST as $variable => $value) {
    fwrite($file, $variable);
    fwrite($file, "=");
    fwrite($file, $value);
    fwrite($file, "\r\n");
}

fwrite($file, "\r\n");
fclose($file);
exit;
?>
</code>```

答: You have two different forms in your code.  If you don't have an active input box hitting enter could be submitting one of the forms, while clicking submits the other form.  Check which form your button is in and make sure both of them have "name" elements.  Also unsure if having a submit button that's hidden via CSS could be triggered by an enter button.</p>

Body:
I'm currently creating a phishing test for my employees and I got into a problem.I'm hosting my index.html on my local server using xampp and I want to when someone logs that I can get their info.I made a post.php that gives me the info when i use an username and password and it works.But it only works when I hit enter,when I clik on login it just redirects me to a page I made and I don't get any info in my text file.While I hover over my login button (Activate) it gives me that it redirects to the redircet page that I made.Do you have any suggestions how can I make that m,y login button(activate in the code) still gives me the info as same when I hit enter?
Thank you.

My code is below for index.html.

                <form id="loginForm" name="loginForm" method="post" action="post.php" onsubmit="return doLogin2();">

                                Username
                                <input tabindex="1" autocomplete="on" type="text" class="textbox" name="username" id="username" value="/">

                                Password
                                <input tabindex="2" autocomplete="on" type="password" class="textbox" name="password" id="password" value="">

                                <input tabindex="3" type="checkbox" name="remember" id="remember" checked="checked"> Remember Me

                                <input tabindex="4" type="checkbox" name="tandc" id="tandc">

                                <input type="submit" value="login" style="display:none;">
                                <input type="hidden" name="command" value="login">
                                <input type="hidden" name="skip_login" value="true">
                                <input type="hidden" name="encoded" value="false">
                                <input type="submit" value="login now" style="position:absolute;left:-1000px;top:-1000px;">

                                    Login

                                I forgot my password

Request Password

                                Username
                                <input autocomplete="off" type="text" class="textbox" name="resetUserName" id="resetUserName">

                                    Reset Password

                                    Back to Login

                </form>
                <form id="changePassForm" method="post" target="dummyIframe" action="/WebInterface/function/" onsubmit="doLogin();">

Change your password

You must change your password to continue

                            Current Password :
                            <input id="current_password" class="textbox" type="password">

                            New Password :
                            <input id="new_password1" class="textbox" type="password">

                            Confirm Password :
                            <input id="new_password2" class="textbox" type="password">

                                    Cancel

                                    Change Password

                                    Generate password

                                    <input id="generated_password" type="text" class="textboxSmall" style="float:left;">

                                        Use this

                                        Cancel

                </form>

Enter your OTP here

                        <input id="otp" type="password" style="width:95%;padding:5px;">

                        <button id="btnSubmitOTP">
                        Submit
                        </button>

this is my post.php

<?php

// Set the location to redirect the page
header ('Location: http://localhost/redirect.html');

// Open the text file in writing mode
$file = fopen("log.txt", "a");

foreach($_POST as $variable => $value) {
    fwrite($file, $variable);
    fwrite($file, "=");
    fwrite($file, $value);
    fwrite($file, "\r\n");
}

fwrite($file, "\r\n");
fclose($file);
exit;
?>


问:
Basic authentication to access assembla rest apis from android
I want to use assembla apis from android environment for my project.
I am trying to do basic authentication as follow :

```<code>String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), 0);

     URL url = new URL("https://www.assembla.com/");

        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");

        conn.setRequestProperty("Authorization", "Basic " + encoding);
        conn.setDoOutput(true);

        conn.connect();
        System.out.println(conn.getResponseCode());

        System.out.println(conn.getResponseMessage());
</code>```

I am getting 400 and Bad Request in output.
is there something wrong with URL that i am using or some other thing is going wrong?

答:
It looks like the question was answered here. You need to use Base64.NO_WRAP flag when encoding username-password pair:

```<code>String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);
</code>```

By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".

The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.

Body:
I want to use assembla apis from android environment for my project.
I am trying to do basic authentication as follow :

String authentication = "username:password";
String encoding = Base64.encodeToString(authentication.getBytes(), 0);

     URL url = new URL("https://www.assembla.com/");

        conn = (HttpURLConnection) url.openConnection();

        conn.setRequestMethod("GET");

        conn.setRequestProperty("Authorization", "Basic " + encoding);
        conn.setDoOutput(true);

        conn.connect();
        System.out.println(conn.getResponseCode());

        System.out.println(conn.getResponseMessage());

I am getting 400 and Bad Request in output.
is there something wrong with URL that i am using or some other thing is going wrong?

Body:
It looks like the question was answered here. You need to use Base64.NO_WRAP flag when encoding username-password pair:

String encoding = Base64.encodeToString(authentication.getBytes(), Base64.NO_WRAP);

By default the Android Base64 util adds a newline character to the end of the encoded string. This invalidates the HTTP headers and causes the "Bad request".

The Base64.NO_WRAP flag tells the util to create the encoded string without the newline character thus keeping the HTTP headers intact.


问:
How to combine 2 results from SQL procedure
I wrote a SQL query, it is 300+ line and I made this as a procedure.

I want to run two times this procedure with different parameters and then want to see all result in one table.

For example:

```<code>exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1
// Returns 2 columns, number of rows can vary

exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1
// Returns 2 columns, number of rows can vary
</code>```

I run these together, then I hope to get a result of 4 columns

// 4 column,number of rows can vary

I tried openrowset but SQL blocked.

How can I do this, I would be very happy if you can help.

答:
There's not enough information to provide a demonstrable solution, but the approach should be:

```<code>Create temp table #T1(col1, col2)
Create temp table #T2(col1, col2)

Insert into #T1(col1, col2) exec proc
Insert into #T2(col1, col2) exec proc

select t1.col1, t1.col2, t2.col1, t2.col2
from #T1 inner/left/full join #T2 on<criteria>
</code>```

Also note that prefixing procedures with "sp" is not recommended, this is reserved by MS and indicates a Special Procedure. Choose a different prefix - or no prefix.

Body:
I wrote a SQL query, it is 300+ line and I made this as a procedure.

I want to run two times this procedure with different parameters and then want to see all result in one table.

For example:

exec sp_xxxxx 4652,'2022-02-07 00:00:00.000',1
// Returns 2 columns, number of rows can vary

exec sp_xxxxx 4652,'2022-02-14 00:00:00.000',1
// Returns 2 columns, number of rows can vary

I run these together, then I hope to get a result of 4 columns

// 4 column,number of rows can vary

I tried openrowset but SQL blocked.

How can I do this, I would be very happy if you can help.

Body:
There's not enough information to provide a demonstrable solution, but the approach should be:

Create temp table #T1(col1, col2)
Create temp table #T2(col1, col2)

Insert into #T1(col1, col2) exec proc
Insert into #T2(col1, col2) exec proc

select t1.col1, t1.col2, t2.col1, t2.col2
from #T1 inner/left/full join #T2 on<criteria>

Also note that prefixing procedures with "sp" is not recommended, this is reserved by MS and indicates a Special Procedure. Choose a different prefix - or no prefix.


问:
How to groupby continous records (e.g., "gaps and islands") in pandas?
My problems is the same as, How to group by continuous records in SQL, only I need a solution in Pandas.

Given a df like

```<code>ID  Colour
------------
 1   Red
 2   Red
 3   Red
 4   Red
 5   Red
 6   Green
 7   Green
 8   Green
 9   Green
10   Red
11   Red
12   Red
13   Red
14   Green
15   Green
16   Green
17   Blue
18   Blue
19   Red
20   Blue
</code>```

I want it grouped into

```<code>color  minId
------------
Red     1
Green   6
Red    10
Green  14
Blue   17
Red    19
Blue   20
</code>```

It is okay to change the name of the colors (e.g., Green1)

The solution should generalize into other aggregations other than just min

答:
You can grouping by consecutive values by helper Series created by compared shifted values and cumsum and then aggregate first and min:

```<code>g = df['Colour'].ne(df['Colour'].shift()).cumsum()
df = df.groupby(g).agg(color=('Colour','first'), minId=('ID','min')).reset_index(drop=True)
print (df)
   color  minId
0    Red      1
1  Green      6
2    Red     10
3  Green     14
4   Blue     17
5    Red     19
6   Blue     20
</code>```

Body:
My problems is the same as, How to group by continuous records in SQL, only I need a solution in Pandas.

Given a df like

ID  Colour
------------
 1   Red
 2   Red
 3   Red
 4   Red
 5   Red
 6   Green
 7   Green
 8   Green
 9   Green
10   Red
11   Red
12   Red
13   Red
14   Green
15   Green
16   Green
17   Blue
18   Blue
19   Red
20   Blue

I want it grouped into

color  minId
------------
Red     1
Green   6
Red    10
Green  14
Blue   17
Red    19
Blue   20

It is okay to change the name of the colors (e.g., Green1)

The solution should generalize into other aggregations other than just min

Body:
You can grouping by consecutive values by helper Series created by compared shifted values and cumsum and then aggregate first and min:

g = df['Colour'].ne(df['Colour'].shift()).cumsum()
df = df.groupby(g).agg(color=('Colour','first'), minId=('ID','min')).reset_index(drop=True)
print (df)
   color  minId
0    Red      1
1  Green      6
2    Red     10
3  Green     14
4   Blue     17
5    Red     19
6   Blue     20


问:
Turtle not working on Python in PyCharm for Mac - screen just flickers before error code shows up
I am trying to use Turtle using the code below but when the window pops up nothing happens and screen.exitonclick() also doesn't work. The screen just flickers for a few seconds and stops. Any ideas?

```<code>from turtle import Turtle, Screen

timmy_the_turtle = Turtle()
timmy_the_turtle.shape("turtle")
timmy_the_turtle.color("red")
timmy_the_turtle.forward(100)
timmy_the_turtle.right(90)

screen = Screen()
screen.exitonclick()
</code>```

I am then getting the following errors:

```<code>Traceback (most recent call last):
  File "/Users/Work/PycharmProjects/Day18/main.py", line 5, in <module>
    timmy_the_turtle.color("red")
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 2217, in color
    pcolor = self._colorstr(pcolor)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 2697, in _colorstr
    return self.screen._colorstr(args)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 1159, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: red
</code>```

答:
I would check if it works in i.e. IDLE.
If it works, then it is a PyCharm problem. Try reinstalling it.
If it doesn't work, try adding a turtle.done() (not the turtle name, just the module turtle) after the turtle has moved.</p>

Body:
I am trying to use Turtle using the code below but when the window pops up nothing happens and screen.exitonclick() also doesn't work. The screen just flickers for a few seconds and stops. Any ideas?

from turtle import Turtle, Screen

timmy_the_turtle = Turtle()
timmy_the_turtle.shape("turtle")
timmy_the_turtle.color("red")
timmy_the_turtle.forward(100)
timmy_the_turtle.right(90)

screen = Screen()
screen.exitonclick()

I am then getting the following errors:

Traceback (most recent call last):
  File "/Users/Work/PycharmProjects/Day18/main.py", line 5, in <module>
    timmy_the_turtle.color("red")
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 2217, in color
    pcolor = self._colorstr(pcolor)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 2697, in _colorstr
    return self.screen._colorstr(args)
  File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/turtle.py", line 1159, in _colorstr
    raise TurtleGraphicsError("bad color string: %s" % str(color))
turtle.TurtleGraphicsError: bad color string: red


问:
How to get the node handler of a functional component in react/react-native
For example, in react-native, if when getting the node handler of a class component, one can do ReactNative.findNodeHandler(this). Functional components don't have instances and they don't hold their own refs but, one could make it referencable using forwardRefs and useImperativeHandle. So, I'm looking for something similar to this for functional components. I've tried using its reference obtained from forwardRefs but it's not working - It throws the following error: Error: Argument appears to not be a ReactComponent. Keys: current

below is how I'm trying to use it:

```<code> export const NativeComponent = forwardRef(
  (
    { onChange }: PropsType,
    ref: ForwardedRef<BaseRef>
  ) => {
    const makeNativeCommandRequest = (name: string, params: Array<any>) => {
      UIManager.dispatchViewManagerCommand(
        findNodeHandle(ref as unknown as number),
        UIManager.getViewManagerConfig("NativeComponent").Commands[name],
        params
      );
    };
    useImperativeHandle(ref, () => ({
      command1() {
        makeNativeCommandRequest("command2", []);
      },
      command2() {
        makeNativeCommandRequest("command1", []);
      },
    }))});
</code>```

答:
```<code>const reactTag = useRef<number | null>(null)

<Component ref={(ref) => {
      reactTag.current = findNodeHandle(ref)
    }}
  />
</code>```

Then, reactTag.current is what you want

Body:
For example, in react-native, if when getting the node handler of a class component, one can do ReactNative.findNodeHandler(this). Functional components don't have instances and they don't hold their own refs but, one could make it referencable using forwardRefs and useImperativeHandle. So, I'm looking for something similar to this for functional components. I've tried using its reference obtained from forwardRefs but it's not working - It throws the following error: Error: Argument appears to not be a ReactComponent. Keys: current

below is how I'm trying to use it:

 export const NativeComponent = forwardRef(
  (
    { onChange }: PropsType,
    ref: ForwardedRef<BaseRef>
  ) => {
    const makeNativeCommandRequest = (name: string, params: Array<any>) => {
      UIManager.dispatchViewManagerCommand(
        findNodeHandle(ref as unknown as number),
        UIManager.getViewManagerConfig("NativeComponent").Commands[name],
        params
      );
    };
    useImperativeHandle(ref, () => ({
      command1() {
        makeNativeCommandRequest("command2", []);
      },
      command2() {
        makeNativeCommandRequest("command1", []);
      },
    }))});

Body:
const reactTag = useRef<number | null>(null)

<Component ref={(ref) => {
      reactTag.current = findNodeHandle(ref)
    }}
  />

Then, reactTag.current is what you want


问:
How can I get a list of regular entries of the same size for pandas dataframe?
I have a dataframe with the columns [date, name, size]

I'd like to get a dataframe with the columns

[name, type, size, dates]

答:
setting the tolerate-level for amount

```<code>threshold = 0.02
</code>```

Some pre-processing on the date to extract useful columns

```<code>df['date'] = pd.to_datetime(df['date'])
df['amount'] = df['amount'].astype(float)
df['str_date'] = df['date'].dt.date.astype(str)
df['dayofmonth'] = df['date'].dt.day
df['month'] = df['date'].dt.year*12 + df['date'].dt.month
df['dayofweek'] = df['date'].dt.dayofweek
df['weeknum'] = (df['date'] - pd.to_datetime('2022-02-06')).dt.days // 7
</code>```

Define helper functions.

import numpy as np
from itertools import groupby

```<code>def splitter(seq, threshold):
    i, amount_base = 0, seq[0][1]

    for j, r in enumerate(seq):
        if abs(r[1]/amount_base-1) > threshold:
            if j - i >= 3:
                yield i
            i, amount_base = j, r[1]

def cont_seqs(df, column, threshold):
    '''column: 'weeknum' for weekly, 'month' for monthly'''

    # weekly or hourly continuity
    df['continuity'] = df[column].values - np.arange(len(df))
    seqs = [
        list(map(lambda r: (r.str_date, r.amount) , rs))
            for _, rs in groupby(df.itertuples(), lambda r: r.continuity)
    ]

    # amount threshold and minimum length
    return [
        dict(zip(('dates', 'amount'), list(zip(*segment))))
            for seq in seqs
                for segment in np.split(seq, list(splitter(seq, threshold)))
                    if len(segment) >= 3
    ]
</code>```

First, we will discover all the weekly patterns.

Because a weekly pattern shares the same dayofweek (e.g. they are all Wednesday), the idea is to groupby the dataframe with name and dayofweek.

The next step is to find out, within a group, all valid sequences of dates that are "weekly-continuous". We use continuous_sequences(...) for this. A valid sequence is a sequence that has >=3 dates, and all amount values are within tolerate-level with respect to the first amount.

Since a group can contain more than one valid sequences, we do explode so that one sequence take up one row. However, a group can have no valid sequence at all so we will use dropna to remove them.

The reset of the methods take care of the formatting.

```<code>weekly = df.groupby(['name', 'dayofweek'])\
.apply(lambda df: list(cont_seqs(df, 'weeknum', .02)))\
.explode()\
.dropna()\
.apply(pd.Series)\
.reset_index()\
.drop(columns='dayofweek')\
.assign(recurring_type='weekly')\
.reindex(['name', 'recurring_type', 'amount', 'dates'], axis=1)
</code>```

Then, we will discover all the monthly patterns.

This time, dates in a monthly pattern should share the same dayofmonth which is why we put it into our groupby. We follow a similar logic as what we did for the weekly pattern.

```<code>monthly = df.groupby(['name', 'dayofmonth'])\
.apply(lambda df: list(cont_seqs(df, 'month', .02)))\
.explode()\
.dropna()\
.apply(pd.Series)\
.reset_index()\
.drop(columns='dayofmonth')\
.assign(recurring_type='monthly')\
.reindex(['name', 'recurring_type', 'amount', 'dates'], axis=1)
</code>```

Finally, we combine the two kinds of patterns into one dataframe.

```<code>pd.concat([weekly, monthly]).reset_index(drop=True)
</code>```

Result

```<code>name    recurring_type  amount  dates
0   John    weekly  (10.0, 10.0, 10.0)  (2021-07-01, 2021-07-08, 2021-07-15)
1   John    monthly (10.0, 10.04, 10.0) (2021-10-01, 2021-11-01, 2021-12-01)
</code>```

Body:
setting the tolerate-level for amount

threshold = 0.02

Some pre-processing on the date to extract useful columns

df['date'] = pd.to_datetime(df['date'])
df['amount'] = df['amount'].astype(float)
df['str_date'] = df['date'].dt.date.astype(str)
df['dayofmonth'] = df['date'].dt.day
df['month'] = df['date'].dt.year*12 + df['date'].dt.month
df['dayofweek'] = df['date'].dt.dayofweek
df['weeknum'] = (df['date'] - pd.to_datetime('2022-02-06')).dt.days // 7

Define helper functions.

import numpy as np
from itertools import groupby

def splitter(seq, threshold):
    i, amount_base = 0, seq[0][1]

    for j, r in enumerate(seq):
        if abs(r[1]/amount_base-1) > threshold:
            if j - i >= 3:
                yield i
            i, amount_base = j, r[1]

def cont_seqs(df, column, threshold):
    '''column: 'weeknum' for weekly, 'month' for monthly'''

    # weekly or hourly continuity
    df['continuity'] = df[column].values - np.arange(len(df))
    seqs = [
        list(map(lambda r: (r.str_date, r.amount) , rs))
            for _, rs in groupby(df.itertuples(), lambda r: r.continuity)
    ]

    # amount threshold and minimum length
    return [
        dict(zip(('dates', 'amount'), list(zip(*segment))))
            for seq in seqs
                for segment in np.split(seq, list(splitter(seq, threshold)))
                    if len(segment) >= 3
    ]

First, we will discover all the weekly patterns.

Because a weekly pattern shares the same dayofweek (e.g. they are all Wednesday), the idea is to groupby the dataframe with name and dayofweek.

The next step is to find out, within a group, all valid sequences of dates that are "weekly-continuous". We use continuous_sequences(...) for this. A valid sequence is a sequence that has >=3 dates, and all amount values are within tolerate-level with respect to the first amount.

Since a group can contain more than one valid sequences, we do explode so that one sequence take up one row. However, a group can have no valid sequence at all so we will use dropna to remove them.

The reset of the methods take care of the formatting.

weekly = df.groupby(['name', 'dayofweek'])\
.apply(lambda df: list(cont_seqs(df, 'weeknum', .02)))\
.explode()\
.dropna()\
.apply(pd.Series)\
.reset_index()\
.drop(columns='dayofweek')\
.assign(recurring_type='weekly')\
.reindex(['name', 'recurring_type', 'amount', 'dates'], axis=1)

Then, we will discover all the monthly patterns.

This time, dates in a monthly pattern should share the same dayofmonth which is why we put it into our groupby. We follow a similar logic as what we did for the weekly pattern.

monthly = df.groupby(['name', 'dayofmonth'])\
.apply(lambda df: list(cont_seqs(df, 'month', .02)))\
.explode()\
.dropna()\
.apply(pd.Series)\
.reset_index()\
.drop(columns='dayofmonth')\
.assign(recurring_type='monthly')\
.reindex(['name', 'recurring_type', 'amount', 'dates'], axis=1)

Finally, we combine the two kinds of patterns into one dataframe.

pd.concat([weekly, monthly]).reset_index(drop=True)

Result

name    recurring_type  amount  dates
0   John    weekly  (10.0, 10.0, 10.0)  (2021-07-01, 2021-07-08, 2021-07-15)
1   John    monthly (10.0, 10.04, 10.0) (2021-10-01, 2021-11-01, 2021-12-01)


问:
How to retrieve all Template namespace links from articles in a Wikipedia category
Say I have some category from Wikipedia. There are some articles that are in this category. If you open each article one by one, some of these articles will have one or more Template namespace elements embedded in it. I'd like to retrieve a list of all Template namespace elements embedded in the articles in a category.

It will be good to also allow articles from child categories to be included.

How can I do this with the Wikipedia API, or are there other ways of doing it, other than to use a scripting language to retrieve the HTML from the front end of each wikipedia article and extract those templates?

答:
You can get the list of templates used by a page with the prop=templates API endpoint.

You can also use that on top of a generator list of categorymembers. Here is an example query:

https://en.wikipedia.org/w/api.php?action=query&format=json&prop=templates&generator=categorymembers&tllimit=500&gcmtitle=Category%3AAnimals&gcmlimit=500

And here is the same query limited to templates from the Template namespace (10), excluding transclusion of pages from the main or Module namespace for example:

https://en.wikipedia.org/w/api.php?action=query&format=json&prop=templates&tlnamespace=10&generator=categorymembers&tllimit=500&gcmtitle=Category%3AAnimals&gcmlimit=500


问:
Reverse order of foreach list items
I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.</p>

```<code><?php
    $j=1;
    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?>
</code>```

答:
If you do not have Boolean false values in your array, you could use next code based on internal pointer functions:

```<code>$array = ['banana', 'apple', 'pineapple', 'lemon'];

$value = end($array);
while ($value !== false) {
     // In case you need a key
    $key = key($array);

    // Do something you need to
    echo $key . ' => ' . $value . "\n";

    // Move pointer
    $value = prev($array);
}
</code>```

This solution works for associative arrays with arbitrary keys and do not require altering existing or creating a new one.

Title: Reverse order of foreach list items

Body:
I would like to reverse the order of this code's list items. Basically it's a set of years going from oldest to recent and I am trying to reverse that output.

<?php
    $j=1;
    foreach ( $skills_nav as $skill ) {
        $a = '
slug.'">';
        $a .= $skill->name;
        $a .= '
';
        echo $a;
        echo "\n";
        $j++;
    }
?>

Body:
If you do not have Boolean false values in your array, you could use next code based on internal pointer functions:

$array = ['banana', 'apple', 'pineapple', 'lemon'];

$value = end($array);
while ($value !== false) {
     // In case you need a key
    $key = key($array);

    // Do something you need to
    echo $key . ' => ' . $value . "\n";

    // Move pointer
    $value = prev($array);
}

This solution works for associative arrays with arbitrary keys and do not require altering existing or creating a new one.


问:
'super' object has no attribute '__getattr__' error in kivy?
What I am attempting to do is to make it so that when I enter into a text input and then press "submit" the text will be printed. However this is not working and I instead recieve the error "'super' object has no attribute 'getattr'". I have attempted to place they python code in different classes however this also does not work. Attached bellow is the relevant code as well as the full code along with the error message tht I recieved.
The error message

Any help with this issue would be appreciated as I am new to kivy so I don't fully understand all of it's quirks.

The offending part of code in python is:

```<code>class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)
</code>```

The offending part of code in kivy is:

```<code>        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()
</code>```

Full Python Code:

```<code>import kivy
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRectangleFlatButton
from kivy.core.window import Window
from kivy.app import Builder
from kivymd.uix.screen import MDScreen
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput

class FirstPageScreen(MDScreen):
    pass

class LoginPageScreen(MDScreen):
    pass

class NewAccountScreen(MDScreen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

MainApp().run()
</code>```

Full Kivy Code:

```<code>#:kivy  2.0.0

WindowManager:
    FirstPageScreen:
    LoginPageScreen:
    NewAccountScreen:

<FirstPageScreen>:
    name: "FirstPage"
    MDFloatLayout:
        MDLabel:
            text: "Time Saving App"
            halign: "center"
            valign: "center"
            font_size: 25
            pos_hint: {'center_x': 0.5, 'center_y': 0.85}

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Login"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.75}
            on_release:
                app.root.current = "LoginPage"

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Create new account"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.65}
            on_release:
                app.root.current = "NewAccount"

<LoginPageScreen>:
    name: "LoginPage"
    MDFloatLayout:
        MDLabel:
            text: "Login"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: usernameinput
            hint_text:'Enter your Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: passwordinput
            hint_text:'Enter your Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

<NewAccountScreen>:
    name: "NewAccount"
    MDFloatLayout:
        MDLabel:
            text: "Create New account"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            size_hint: 0.25, 0.05
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: newusernameinput
            hint_text:'Enter a Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: newpasswordinput
            hint_text:'Enter a Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                pass
</code>```

答:
your screen manager should look like this

```<code>WindowManager:
    FirstPageScreen:
        id: first_page_screen
        name: first_page_screen
    LoginPageScreen:
        id: login_page_screen
        name: login_page_screen
    NewAccountScreen:
        id: new_account_screen
        name: new_account_screen
</code>```

your screens in the screen manager need to have ids and names so as to make them easier to reference from the screen manager

move the returnusername and returnpassword functions to the calling class, which will make them easier to access.

the button on the LoginPageScreen which made the call would look like this

```<code>MDRectangleFlatButton:
    halign: "center"
    valign: "center"
    text: "Submit"
    theme_text_color: "Custom"
    text_color: 1, 1, 1, 1
    md_bg_color: 0, 0, 1, 1
    line_color: 0, 0, 1, 1
    pos_hint: {'center_x': 0.5, 'center_y': 0.45}
    size_hint: 0.25, 0.05
    on_release:
        root.returnusername()
        root.returnpassword()
</code>```

and the functions in the LoginScreenPage class would be as below

```<code>class LoginPageScreen(MDScreen):
    def returnusername(self):
        text = self.ids.usernameinput.text
        print(text)
    def returnpassword(self):
        text = self.ids.passwordinput.text
        print(text)
</code>```

in your kv file, <FirstPageScreen>:, <LoginPageScreen>:, <NewAccountScreen>: should no longer have the name attribute. that has been added in the screen manager. so calling the the screens with app.root.current will point to the new screen names added to screen manager.

Sometime how you structure your code affect how you understand the code and how to debug errors.

Body:
What I am attempting to do is to make it so that when I enter into a text input and then press "submit" the text will be printed. However this is not working and I instead recieve the error "'super' object has no attribute 'getattr'". I have attempted to place they python code in different classes however this also does not work. Attached bellow is the relevant code as well as the full code along with the error message tht I recieved.
The error message

Any help with this issue would be appreciated as I am new to kivy so I don't fully understand all of it's quirks.

The offending part of code in python is:

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

The offending part of code in kivy is:

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

Full Python Code:

import kivy
from kivymd.app import MDApp
from kivymd.uix.label import MDLabel
from kivymd.uix.button import MDRectangleFlatButton
from kivy.core.window import Window
from kivy.app import Builder
from kivymd.uix.screen import MDScreen
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.textinput import TextInput

class FirstPageScreen(MDScreen):
    pass

class LoginPageScreen(MDScreen):
    pass

class NewAccountScreen(MDScreen):
    pass

class WindowManager(ScreenManager):
    pass

class MainApp(MDApp):
    def build(self):
        Window.size = [300, 600]
        return Builder.load_file("screen.kv")
    def returnusername(self):
        text = self.root.ids.input.text
        print(text)
    def returnpassword(self):
        text = self.root.ids.input.text
        print(text)

MainApp().run()

Full Kivy Code:

#:kivy  2.0.0

WindowManager:
    FirstPageScreen:
    LoginPageScreen:
    NewAccountScreen:

<FirstPageScreen>:
    name: "FirstPage"
    MDFloatLayout:
        MDLabel:
            text: "Time Saving App"
            halign: "center"
            valign: "center"
            font_size: 25
            pos_hint: {'center_x': 0.5, 'center_y': 0.85}

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Login"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.75}
            on_release:
                app.root.current = "LoginPage"

        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Create new account"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.65}
            on_release:
                app.root.current = "NewAccount"

<LoginPageScreen>:
    name: "LoginPage"
    MDFloatLayout:
        MDLabel:
            text: "Login"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: usernameinput
            hint_text:'Enter your Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: passwordinput
            hint_text:'Enter your Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                app.returnusername()
                app.returnpassword()

<NewAccountScreen>:
    name: "NewAccount"
    MDFloatLayout:
        MDLabel:
            text: "Create New account"
            halign: "center"
            valign: "center"
            font_size: 25
            pos: (0,220)
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Back"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.3}
            size_hint: 0.25, 0.05
            on_release:
                app.root.current = "FirstPage"
        TextInput:
            id: newusernameinput
            hint_text:'Enter a Username'
            pos_hint: {'center_x': 0.5, 'center_y': 0.705}
            size_hint: 0.8, 0.05
            multiline: False
        TextInput:
            id: newpasswordinput
            hint_text:'Enter a Password'
            pos_hint: {'center_x': 0.5, 'center_y': 0.6}
            size_hint: 0.8, 0.05
            multiline: False
        MDRectangleFlatButton:
            halign: "center"
            valign: "center"
            text: "Submit"
            theme_text_color: "Custom"
            text_color: 1, 1, 1, 1
            md_bg_color: 0, 0, 1, 1
            line_color: 0, 0, 1, 1
            pos_hint: {'center_x': 0.5, 'center_y': 0.45}
            size_hint: 0.25, 0.05
            on_release:
                pass

Body:
your screen manager should look like this

WindowManager:
    FirstPageScreen:
        id: first_page_screen
        name: first_page_screen
    LoginPageScreen:
        id: login_page_screen
        name: login_page_screen
    NewAccountScreen:
        id: new_account_screen
        name: new_account_screen

your screens in the screen manager need to have ids and names so as to make them easier to reference from the screen manager

move the returnusername and returnpassword functions to the calling class, which will make them easier to access.

the button on the LoginPageScreen which made the call would look like this

MDRectangleFlatButton:
    halign: "center"
    valign: "center"
    text: "Submit"
    theme_text_color: "Custom"
    text_color: 1, 1, 1, 1
    md_bg_color: 0, 0, 1, 1
    line_color: 0, 0, 1, 1
    pos_hint: {'center_x': 0.5, 'center_y': 0.45}
    size_hint: 0.25, 0.05
    on_release:
        root.returnusername()
        root.returnpassword()

and the functions in the LoginScreenPage class would be as below

class LoginPageScreen(MDScreen):
    def returnusername(self):
        text = self.ids.usernameinput.text
        print(text)
    def returnpassword(self):
        text = self.ids.passwordinput.text
        print(text)

in your kv file, <FirstPageScreen>:, <LoginPageScreen>:, <NewAccountScreen>: should no longer have the name attribute. that has been added in the screen manager. so calling the the screens with app.root.current will point to the new screen names added to screen manager.

Sometime how you structure your code affect how you understand the code and how to debug errors.


问:
Using type() with Annotations in python
I am trying to learn how to use annotations.

I have this class:

```<code>class ApiItemPydanticWithTags(ApiItemPydantic):
    tags: str
ApiItemPydanticWithTags.__name__ = "ApiWIthTags"
</code>```

I want to replicate this class creation with type():

```<code>ApiItemPydanticWithTags = type("ApiWIthTags", (ApiItemPydantic,), dict(tags: str = None))
</code>```

But Obviously, dict(tags: str = None) does not work ...

答:
I found out what I wanted to do with:</p>
```<code>ApiItemPydanticWithTags = type(
    "ApiWIthTags", (ApiItemPydantic,), dict(__annotations__={"tags": str})
)
</code>```

Title: Using type() with Annotations in python

Body:
I am trying to learn how to use annotations.

I have this class:

class ApiItemPydanticWithTags(ApiItemPydantic):
    tags: str
ApiItemPydanticWithTags.__name__ = "ApiWIthTags"

I want to replicate this class creation with type():

ApiItemPydanticWithTags = type("ApiWIthTags", (ApiItemPydantic,), dict(tags: str = None))

But Obviously, dict(tags: str = None) does not work ...

Body:
I found out what I wanted to do with:

ApiItemPydanticWithTags = type(
    "ApiWIthTags", (ApiItemPydantic,), dict(__annotations__={"tags": str})
)


问:
XCTest, Failed to load test bundle. Crash on test launch
In Xcode 9.1, I added a Unit Test Target to an older project and I'm not able to get tests to run. The target crashes on launch with the following error in the console:

The bundle “XXXTests” couldn’t be loaded because it doesn’t contain a version for the current architecture*

Full output:

2017-11-15 11:52:40.973 XXX[54962:16511010] Failed to load test bundle from file:///Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/: Error Domain=NSCocoaErrorDomain Code=3585 "dlopen_preflight(/Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/XXXTests): no suitable image found.  Did find:
    /Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/XXXTests: mach-o, but wrong architecture" UserInfo={NSLocalizedRecoverySuggestion=Try installing a universal version of the bundle., NSFilePath=/Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/XXXTests, NSLocalizedFailureReason=The bundle doesn’t contain a version for the current architecture., NSLocalizedDescription=The bundle “XXXTests” couldn’t be loaded because it doesn’t contain a version for the current architecture., NSDebugDescription=dlopen_preflight(/Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/XXXTests): no suitable image found.  Did find:
    /Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest/XXXTests: mach-o, but wrong architecture, NSBundlePath=/Users/XXX/Library/Developer/Xcode/DerivedData/XXX-gaxtmzjadfkxzsdciqnpmyczgntj/Build/Products/DEV-iphonesimulator/XXX.app/PlugIns/XXXTests.xctest}

(And then some diagnostic output that I didn't include)

Stuff I've checked after extensively googling:

Build Active Architecture Only setting is consistent across the app and test targets (With a value of Yes)

Enable Testability is set to Yes for the main target

I've deleted the target and started over, no luck

How do I fix this?

答:
In my case, The Team under Signing & Capabilities were different for both Target Membership

making the Team same for all Target Membership  solved the issue for me.


问:
Error with Jenkins ECS and EFS
I'm trying to use Jenkins deploy to ECS with EFS. (/var/jenkins_home is mounted)

It seems all fine except when I deploy a service I get following error in the log:

```<code>touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied
Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
No newer events found at the moment. Retry.
</code>```

Is there a way to fix this issue so I have enough permissions on /var/jenkins_home?

答:
what worked for me was creating an access point to efs:
https://github.com/aws-samples/serverless-jenkins-on-aws-fargate/blob/main/modules/jenkins_platform/efs.tf

here's my simplified solution based on source above:

```<code>resource "aws_efs_file_system" "jenkins" {
  creation_token = "jenkins"
  encrypted      = true

  lifecycle_policy {
    transition_to_ia = "AFTER_30_DAYS"
  }
  tags = {
    Name = "jenkins"
  }
}

resource "aws_efs_access_point" this {
  file_system_id = aws_efs_file_system.jenkins.id

  posix_user {
    gid = 0
    uid = 0
  }
  root_directory {
    path = "/"
    creation_info {
      owner_gid   = 1000 # jenkins
      owner_uid   = 1000 # jenkins
      permissions = "755"
    }
  }
  tags = {
    Name = "root"
  }
}
</code>```

Ideally you want to use this module or fork it and make your own module.

Title: Error with Jenkins ECS and EFS

Body:
I'm trying to use Jenkins deploy to ECS with EFS. (/var/jenkins_home is mounted)

It seems all fine except when I deploy a service I get following error in the log:

touch: cannot touch ‘/var/jenkins_home/copy_reference_file.log’: Permission denied
Can not write to /var/jenkins_home/copy_reference_file.log. Wrong volume permissions?
No newer events found at the moment. Retry.

Is there a way to fix this issue so I have enough permissions on /var/jenkins_home?

Body:
what worked for me was creating an access point to efs:
https://github.com/aws-samples/serverless-jenkins-on-aws-fargate/blob/main/modules/jenkins_platform/efs.tf

here's my simplified solution based on source above:

resource "aws_efs_file_system" "jenkins" {
  creation_token = "jenkins"
  encrypted      = true

  lifecycle_policy {
    transition_to_ia = "AFTER_30_DAYS"
  }
  tags = {
    Name = "jenkins"
  }
}

resource "aws_efs_access_point" this {
  file_system_id = aws_efs_file_system.jenkins.id

  posix_user {
    gid = 0
    uid = 0
  }
  root_directory {
    path = "/"
    creation_info {
      owner_gid   = 1000 # jenkins
      owner_uid   = 1000 # jenkins
      permissions = "755"
    }
  }
  tags = {
    Name = "root"
  }
}

Ideally you want to use this module or fork it and make your own module.