问:
Convert a shiny "tags$" in HTML()
I would like to write this code (that works):

```<code>  tags$li(
    class = "dropdown",
    tags$a(
      height = 40, href = "https://www.google.com.br",
      title = "Whatsapp", target = "_blank",
      tags$strong(
        icon("whatsapp"), ""
      )
    )
  )
</code>```

in the HTML() form. I tried:

```<code>HTML(
"<li class='dropdown'>
<a href='https://www.google.com.br' target='_blank'>Whatsapp</a>
<strong class='fas fa-whatsapp'></strong>
</li>"
)
</code>```

and this code:

```<code>  HTML(
    '<li class="dropdown">
      <a style="height:40px" href="https://www.google.com.br"
title="Whatsapp" target="_blank">
      <strong>
      <i class="fas fa-whatsapp"></i>
      </strong>
      </a>
      </li>'
  )
</code>```

But an error appear:

An error has occurred!

Expected an object with class 'shiny.tag'.

My app:

```<code>library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,

  HTML(
  "<li class='dropdown'>
  <a https://www.google.com.br' target='_blank'>Whatsapp</a>
  <strong class='fas fa-whatsapp'></strong>
  </li>"
  )

)

sidebar <- dashboardSidebar(

  width = 300

)

body <- dashboardBody(

  uiOutput(
    outputId = "hour"
  )

)

ui <- dashboardPage(

  header = header,
  sidebar = sidebar,
  body = body

)

server <- function(input, output) {

}

shinyApp(ui, server)
</code>```

I would just like to do this transformation to better edit my HTML document. I need to do this with just HTML().

How to solve this? I made two attempts, as I showed, but I couldn't solve it.

答:
Placing the HTML() content inside tags$li() with 'dropdown' class works

```<code>library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,
  tags$li(
    class = "dropdown",
    HTML("
      <a https://www.google.com.br' target='_blank'>Whatsapp</a>
      <strong class='fas fa-whatsapp'></strong>
    ")
  )
)

sidebar <- dashboardSidebar(
  width = 300
)

body <- dashboardBody(
  uiOutput(
    outputId = "hour"
  )
)

ui <- dashboardPage(
  header = header,
  sidebar = sidebar,
  body = body
)

server <- function(input, output) {

}

shinyApp(ui, server)
</code>```

Title: Convert a shiny "tags$" in HTML()

Body:
I would like to write this code (that works):

  tags$li(
    class = "dropdown",
    tags$a(
      height = 40, href = "https://www.google.com.br",
      title = "Whatsapp", target = "_blank",
      tags$strong(
        icon("whatsapp"), ""
      )
    )
  )

in the HTML() form. I tried:

HTML(
"

Whatsapp

"
)

and this code:

  HTML(
    '

'
  )

But an error appear:

An error has occurred!

Expected an object with class 'shiny.tag'.

My app:

library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,

  HTML(
  "

  Whatsapp

"
  )

)

sidebar <- dashboardSidebar(

  width = 300

)

body <- dashboardBody(

  uiOutput(
    outputId = "hour"
  )

)

ui <- dashboardPage(

  header = header,
  sidebar = sidebar,
  body = body

)

server <- function(input, output) {

}

shinyApp(ui, server)

I would just like to do this transformation to better edit my HTML document. I need to do this with just HTML().

How to solve this? I made two attempts, as I showed, but I couldn't solve it.

Body:
Placing the HTML() content inside tags$li() with 'dropdown' class works

library(shiny)
library(shinydashboard)

header <- dashboardHeader(

  title = "Dashboard",
  titleWidth = 300,
  tags$li(
    class = "dropdown",
    HTML("
      <a https://www.google.com.br' target='_blank'>Whatsapp</a>
      <strong class='fas fa-whatsapp'></strong>
    ")
  )
)

sidebar <- dashboardSidebar(
  width = 300
)

body <- dashboardBody(
  uiOutput(
    outputId = "hour"
  )
)

ui <- dashboardPage(
  header = header,
  sidebar = sidebar,
  body = body
)

server <- function(input, output) {

}

shinyApp(ui, server)


来源: stackexchange

问:
Redis gem 4.6.0: Multi pipeline commands warnings in sidekiq logs
I'm using sidekiq to run background jobs in ROR application. Recently redis gem version got updated to 4.6.0 (automatically as sidekiq dependency), but its producing some multi pipeline commands warning continuously as sidekiq logs flooded with these logs and its difficult to track Worker logs. Please let me know how can i remove these warnings?

Sidekiq logs:

```<code>(called from /Users/username/.rvm/gems/ruby-2.7.0/gems/sidekiq-6.4.0/lib/sidekiq/launcher.rb:141:in `block in ❤'}
Pipelining commands on a Redis instance is deprecated and will be removed in Redis 5.0.0.

redis.multi do
  redis.get("key")
end

should be replaced by

redis.multi do |pipeline|
  pipeline.get("key")
end

</code>```

答:
I was having the same issue. The response from onerinas is correct. For simplicity, below is the code needed to upgrade the sidekiq gem. This fixed the issue for me.

```<code>gem 'sidekiq', '>= 6.4.1'
</code>```

https://github.com/mperham/sidekiq/issues/5169#issuecomment-1029171282

ContentLicense: CC BY-SA 4.0

Body:
I'm using sidekiq to run background jobs in ROR application. Recently redis gem version got updated to 4.6.0 (automatically as sidekiq dependency), but its producing some multi pipeline commands warning continuously as sidekiq logs flooded with these logs and its difficult to track Worker logs. Please let me know how can i remove these warnings?

Sidekiq logs:

(called from /Users/username/.rvm/gems/ruby-2.7.0/gems/sidekiq-6.4.0/lib/sidekiq/launcher.rb:141:in `block in ❤'}
Pipelining commands on a Redis instance is deprecated and will be removed in Redis 5.0.0.

redis.multi do
  redis.get("key")
end

should be replaced by

redis.multi do |pipeline|
  pipeline.get("key")
end

Body:
I was having the same issue. The response from onerinas is correct. For simplicity, below is the code needed to upgrade the sidekiq gem. This fixed the issue for me.

gem 'sidekiq', '>= 6.4.1'

https://github.com/mperham/sidekiq/issues/5169#issuecomment-1029171282


问:
Efficient nested loops with bootstrap resampling on DataFrame in PySpark
I have a DataFrame with the following schema:

```<code>+--------------------+--------+-------+-------+-----------+--------------------+
|              userid|datadate|  runid|variant|device_type|          prediction|
+--------------------+--------+-------+-------+-----------+--------------------+
|0001d15b-e2da-4f4...|20220111|1196752|      1|     Mobile|  0.8827571312010658|
|00021723-2a0d-497...|20220111|1196752|      1|     Mobile| 0.30763173370229735|
|00021723-2a0d-497...|20220111|1196752|      0|     Mobile|  0.5336206154783815|
</code>```

I would like to perform the following operation:
I want to do for each "runid", for each "device_type", some calculations with variant==1 and variant==0, including a resampling loop.
The ultimate goal is to store these calculations in another DF.

So in a naive approach the code would look like that:

```<code>for runid in df.select('runid').distinct().rdd.flatMap(list).collect():
    for device in ["Mobile","Desktop"]:
        a_variant = df.filter((df.runid  == runid) & (df.device_type  == device) & (df.variant  == 0))
        b_variant = df.filter((df.runid  == runid) & (df.device_type  == device) & (df.variant  == 1))

        ## do some more calculations here

        # bootstrap loop:
        for samp in range(100):
            sampled_vector_a = a_variant.select("prediction").sample(withReplacement = True, fraction = 1.0, seed = 123)
            sampled_vector_b = b_variant.select("prediction").sample(withReplacement = True, fraction = 1.0, seed = 123)

            ## do some more calculations here

      ## do some more calculations here
      ## store calculations in a new DataFrame

</code>```

Currently the process is too slow.
How can I optimize this process by utilizing spark in the best way?
Thanks!

答:
Here is a way to sample from each group in a dataframe after applying groupBy.

```<code>from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName("Demo").getOrCreate()
df = spark.createDataFrame(data,columns)
data = [["uid1","runid1",1,"Mobile",0.8],["uid2","runid1",1,"Mobile",0.3],
      ["uid3","runid1",0,"Mobile",0.5],["uid4","runid2",0,"Mobile",0.7],
      ["uid5","runid2",0,"Mobile",0.9]]
columns = ["userid","runid","variant","device_type","prediction"]

df.show()
# +------+------+-------+-----------+----------+
# |userid| runid|variant|device_type|prediction|
# +------+------+-------+-----------+----------+
# |  uid1|runid1|      1|     Mobile|       0.8|
# |  uid2|runid1|      1|     Mobile|       0.3|
# |  uid3|runid1|      0|     Mobile|       0.5|
# |  uid4|runid2|      0|     Mobile|       0.7|
# |  uid5|runid2|      0|     Mobile|       0.9|
# +------+------+-------+-----------+----------+
</code>```

Define a sampling function that is going to be called by applyInPandas. The function my_sample extracts one sample for each input dataframe:

```<code>def my_sample(key, df):
    x = df.sample(n=1)
    return x
</code>```

applyInPandas also needs a schema for its output, since it is returning the whole dataframe it will have the same fields as df:

```<code>from pyspark.sql.types import *
schema = StructType([StructField('userid', StringType()),
                     StructField('runid', StringType()),
                     StructField('variant', LongType()),
                     StructField('device_type', StringType()),
                     StructField('prediction', DoubleType())])
</code>```

Just to check, try grouping the data, there are three groups:

```<code>df.groupby("runid", "device_type", "variant").mean("prediction").show()
# +------+-----------+-------+---------------+
# | runid|device_type|variant|avg(prediction)|
# +------+-----------+-------+---------------+
# |runid1|     Mobile|      0|            0.5|
# |runid1|     Mobile|      1|           0.55|
# |runid2|     Mobile|      0|            0.8|
# +------+-----------+-------+---------------+
</code>```

Now apply my_sample to each group using applyInPandas:

```<code>df.groupby("runid","device_type","variant").applyInPandas(my_sample, schema=schema).show()
# +------+------+-------+-----------+----------+
# |userid| runid|variant|device_type|prediction|
# +------+------+-------+-----------+----------+
# |  uid3|runid1|      0|     Mobile|       0.5|
# |  uid2|runid1|      1|     Mobile|       0.3|
# |  uid4|runid2|      0|     Mobile|       0.7|
# +------+------+-------+-----------+----------+
</code>```

Note: I used applyInPandas since pyspark.sql.GroupedData.apply.html is deprecated

Body:
I have a DataFrame with the following schema:

+--------------------+--------+-------+-------+-----------+--------------------+
|              userid|datadate|  runid|variant|device_type|          prediction|
+--------------------+--------+-------+-------+-----------+--------------------+
|0001d15b-e2da-4f4...|20220111|1196752|      1|     Mobile|  0.8827571312010658|
|00021723-2a0d-497...|20220111|1196752|      1|     Mobile| 0.30763173370229735|
|00021723-2a0d-497...|20220111|1196752|      0|     Mobile|  0.5336206154783815|

I would like to perform the following operation:
I want to do for each "runid", for each "device_type", some calculations with variant==1 and variant==0, including a resampling loop.
The ultimate goal is to store these calculations in another DF.

So in a naive approach the code would look like that:

for runid in df.select('runid').distinct().rdd.flatMap(list).collect():
    for device in ["Mobile","Desktop"]:
        a_variant = df.filter((df.runid  == runid) & (df.device_type  == device) & (df.variant  == 0))
        b_variant = df.filter((df.runid  == runid) & (df.device_type  == device) & (df.variant  == 1))

        ## do some more calculations here

        # bootstrap loop:
        for samp in range(100):
            sampled_vector_a = a_variant.select("prediction").sample(withReplacement = True, fraction = 1.0, seed = 123)
            sampled_vector_b = b_variant.select("prediction").sample(withReplacement = True, fraction = 1.0, seed = 123)

            ## do some more calculations here

      ## do some more calculations here
      ## store calculations in a new DataFrame

Currently the process is too slow.
How can I optimize this process by utilizing spark in the best way?
Thanks!

Body:
Here is a way to sample from each group in a dataframe after applying groupBy.

from pyspark.sql import SparkSession
import pandas as pd
spark = SparkSession.builder.appName("Demo").getOrCreate()
df = spark.createDataFrame(data,columns)
data = [["uid1","runid1",1,"Mobile",0.8],["uid2","runid1",1,"Mobile",0.3],
      ["uid3","runid1",0,"Mobile",0.5],["uid4","runid2",0,"Mobile",0.7],
      ["uid5","runid2",0,"Mobile",0.9]]
columns = ["userid","runid","variant","device_type","prediction"]

df.show()
# +------+------+-------+-----------+----------+
# |userid| runid|variant|device_type|prediction|
# +------+------+-------+-----------+----------+
# |  uid1|runid1|      1|     Mobile|       0.8|
# |  uid2|runid1|      1|     Mobile|       0.3|
# |  uid3|runid1|      0|     Mobile|       0.5|
# |  uid4|runid2|      0|     Mobile|       0.7|
# |  uid5|runid2|      0|     Mobile|       0.9|
# +------+------+-------+-----------+----------+

Define a sampling function that is going to be called by applyInPandas. The function my_sample extracts one sample for each input dataframe:

def my_sample(key, df):
    x = df.sample(n=1)
    return x

applyInPandas also needs a schema for its output, since it is returning the whole dataframe it will have the same fields as df:

from pyspark.sql.types import *
schema = StructType([StructField('userid', StringType()),
                     StructField('runid', StringType()),
                     StructField('variant', LongType()),
                     StructField('device_type', StringType()),
                     StructField('prediction', DoubleType())])

Just to check, try grouping the data, there are three groups:

df.groupby("runid", "device_type", "variant").mean("prediction").show()
# +------+-----------+-------+---------------+
# | runid|device_type|variant|avg(prediction)|
# +------+-----------+-------+---------------+
# |runid1|     Mobile|      0|            0.5|
# |runid1|     Mobile|      1|           0.55|
# |runid2|     Mobile|      0|            0.8|
# +------+-----------+-------+---------------+

Now apply my_sample to each group using applyInPandas:

df.groupby("runid","device_type","variant").applyInPandas(my_sample, schema=schema).show()
# +------+------+-------+-----------+----------+
# |userid| runid|variant|device_type|prediction|
# +------+------+-------+-----------+----------+
# |  uid3|runid1|      0|     Mobile|       0.5|
# |  uid2|runid1|      1|     Mobile|       0.3|
# |  uid4|runid2|      0|     Mobile|       0.7|
# +------+------+-------+-----------+----------+

Note: I used applyInPandas since pyspark.sql.GroupedData.apply.html is deprecated


问:
if typeOf f == io then f else return . f in Haskell?
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

```<code>return . f
</code>```

and now, I want to make this f generic including IO

```<code>f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)
</code>```

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);```

答:
Here's another version of Prophet's answer, without overlapping instances.</p>
```<code>{-# language MultiParamTypeClasses, DataKinds, KindSignatures, TypeFamilies, TypeApplications, ScopedTypeVariables, AllowAmbiguousTypes, FlexibleInstances, FlexibleContexts #-}

type family GetUnderlying a where
  GetUnderlying (IO a) = a
  GetUnderlying a = a

type family IsIO a where
  IsIO (IO _) = True
  IsIO _ = False

class Pureish (isIO :: Bool) u a where
  pureish' :: a -> IO u

instance Pureish False u u where
  pureish' = pure

instance Pureish True u (IO u) where
  pureish' = id

pureish :: forall a u. (Pureish (IsIO a) u a, u ~ GetUnderlying a) => a -> IO u
pureish = pureish' @(IsIO a)
</code>```

Body:
Related to

https://stackoverflow.com/a/71020780/17053359

We can lift non-IO functions : f to IO ones with return, as in

return . f

and now, I want to make this f generic including IO

f :: A -> IO A -- not IO to IO
f :: IO a -> IO a -- (no change, `id` instead of `return`)

in other words:

if typeOf f == io then f

else return . f

What would the code be in Haskell?

EDIT:

console.log(
 Object(1)
);

console.log(
 Object(Object(1))
);

console.log(
 Object(Object(Object(1)))
);

Body:
Here's another version of Prophet's answer, without overlapping instances.

{-# language MultiParamTypeClasses, DataKinds, KindSignatures, TypeFamilies, TypeApplications, ScopedTypeVariables, AllowAmbiguousTypes, FlexibleInstances, FlexibleContexts #-}

type family GetUnderlying a where
  GetUnderlying (IO a) = a
  GetUnderlying a = a

type family IsIO a where
  IsIO (IO _) = True
  IsIO _ = False

class Pureish (isIO :: Bool) u a where
  pureish' :: a -> IO u

instance Pureish False u u where
  pureish' = pure

instance Pureish True u (IO u) where
  pureish' = id

pureish :: forall a u. (Pureish (IsIO a) u a, u ~ GetUnderlying a) => a -> IO u
pureish = pureish' @(IsIO a)


问:
c# async await confuses me, seems to do nothing
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

```<code>using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}
</code>```

答:
Here's the short short intro to async/await

You know when you're playing some God type game where you e.g. set your settlers building a load of buildings, or cutting trees/making food etc and then you have literally nothing else to do except sit and watch them finish, then you can start again, getting the buildings to churn out knights or catapults or whatever?

It's a bit of a waste of life, you sitting there doing nothing other than waiting for something to finish, then you can carry on with some other task..

As a human you probably don't do that; you go make a cup of coffee, call a friend, hit the punchbag, maybe even go play the space exploration game, set the autopilot of whatever ship to guide you to some star system on a journey that'll take 5 mintues of waiting and watching stars pass.. Autopilot set, coffee made, buildings still not finished, bored of the punchbag.. So you go clean up..

This isn't doing things in parallel; you aren't wiping the floor with a cloth while stirring the coffe and chatting on the phone, but it's making great use of your time, cracking through the todo list by pouring a load of energy into one thing, getting as far as you can, then switching to the next thing. You do one thing at once, but when you get stuck you move onto another thing. If you sat and waited for everything you'd need 10 copies of you to get 10 stop/start jobs done

async/await is the same thing. It takes syncronous code - something that is done from start to finish in one long operation that is the sole focus of your thread's attention, even if there's a 5 minute Wait() in the middle of it where it literally sits and does nothing for 5 minutes - and chops it up into a bunch of separate methods that are controlled by a process that allows the thread to pick up where it left off of

Marking a method async is the indicator to C# that the compiler is allowed to invisbly cut the method up into pieces that can be put down and picked up when needed

await is the indicator where you're saying "I've reached a point where I need some operation to finish before I can progress any further with this; go and find something else to do". When it encounters an await your thread will stop work on your code because it's being told it to do nothing more until the background operation completes (it's not important what is doing the work, lets imagine it's some background thread) and your thread will go and do something else until the result is ready. This really simplifies a lot of programming related stuff because you only ever deal with one thread - it's code that behaves like syncronous code but goes and does something else instead of doing nothing when it gets stuck

As a keyword await has to be followed by something that is awaitable, usually a Task or Task<T> - it represents the operation that is already set to happen. When the operation is finished and the thread returns await also helpfully unwraps the Task object that was controlling this process, and gives you the result..

If you take nothing else away from this, at the very least learn:

you must mark a method as async if you want to use await inside it. You should generally make the return type of an sync method as either Task (if it returns no value) or Task<X> (if it returns a value of type X). You should also call the method a name ending in ..Async

When you start some operation that works asyncronously (you call some method that is called ..Async), and you get a Task<X> object in return, use await on it to get the X you actually want

Making an async method means the method that calls it also has to be async, and the method that calls that also has to be async.. and.. All the way up the tree and out of your code. That's how your thread can "escape" when it has to go find something else to do - it needs to escape out of your code, so you make a route for that to happen by declaring "async all the way up"

I said in the comments not to use a console app. Let's imagine you have a Windows Forms app. Win Forms apps typically have one thread that does everything. One thread draws the UI, and when you click a button it comes and runs all the code you put in the button_Click() handler. While it's doing that it's not doing its normal job of drawing the UI. You can set statusLabel.Text = "Downloading data.." as the very first line of the method, and you can launch a download of a 1 gig file, and then you can set the status Label to "Finished " + downloadedFile.Length. You click the button, and you see nothing - the UI of your app jams frozen for 30 seconds while the file downloads. Then it suddenly says "Finished 1024000000" in the label:

```<code>void button_Click(object sender, EventArgs e){
  statusLabel.Text = "Starting download";
  string downloadedFile = new SomeHttpDownloadStringThing("http://..");
  statusLabel.Text = "Finished " + downloadedFile.Length;
}
</code>```

Why? Well.. the thread that draws the UI and would have painted the label pixels on the screen got really busy downloading the file. It went into that SomeHttpDownloadStringThing method and didn't come out for 30 seconds, then it came out, set the status label text again, then it left your code and went back to whatever land it normally lives in. It drew the pixels on screen "Finished..". It never even knew it had to draw "Starting download".. That data was overwritten well before it picked up its paintbrush again

Let's turn it async:

```<code>async void button_Click(object sender, EventArgs e){
  statusLabel.Text = "Starting download";
  string downloadedFile = await SomeHttpDownloadStringThingAsync("http://..");
  statusLabel.Text = "Finished " + downloadedFile.Length;
}
</code>```

SomeHttpDownloadStringThing returned a string. SomeHttpDownloadStringThingAsync returned a Task<string>. When the UI thread hits that await imagine it tells some background thread to go download the file, puts this method on pause, and returns out of it and goes back to drawing the UI. It paints the label as "Starting ..." so you see it, and then maybe finds some other stuff to do. If you had a Timer ticking up counting how long the download had been then your timer would increment nicely too - bcause the UI thread is free to do it, it's not sitting awaiting for Windows to do the download while it does nothing other than wait.

When the download finishes, the thread is called back to where it was and it picks up from there. It doesn't run the first code again, it doesn't set the status label to "Starting" again.

It literally starts from the SomeHttpDownloadStringThingAsync part as if it had never left, the await converts the Task<string> into a string of the downlaoded file, and then the UI thread can set the "Finished.." text

The whole thing is just like the syncronous version, except that little bit in the middle where the UI thread was allowed to go back to its regular job of drawing pixels on the screen and handling other user interaction

This is why I say console apps are hard work for understanding async/await because their UI doesn't obviously do anything else while an await is in progress, unless you've arranged for something to happen, but that's more work. UI apps automatically have other stuff going on, and if you jam up the threads that do that stuff, they freeze, and turn "Not responding"

If you have an eagle eye, you'll have spotted async void on the handler even though I said "if you have a void method, make it return Task when you make it async" - winforms event handlers are a bit of a special case in that regard, you cannot make them async Task but they're an exception rather than a rule. For now, rule of thumb - avoid async void

Body:
EDIT: Updating LongTask() to be await Task.Delay(2000); makes it work how I need, so thanks for the answers, y'all!

I am trying to call an async function from within a sync function to let the sync function keep going before the async function is finished. I don't know why the code below waits for LongTask() to complete before continuing. I thought it should only do that if I did await LongTask(). Can someone help me understand what I'm missing?

C# fiddle here

using System;
using System.Diagnostics;
using System.Threading.Tasks;

public class Program
{
    public static void Main()
    {
        var timer = new Stopwatch();
        timer.Start();
        LongTask();
        timer.Stop();

        long ms = timer.ElapsedMilliseconds;

        Console.WriteLine(ms.ToString());
    }

    async static void LongTask()
    {
        Task.Delay(2000).Wait();
    }
}

Body:
Here's the short short intro to async/await

You know when you're playing some God type game where you e.g. set your settlers building a load of buildings, or cutting trees/making food etc and then you have literally nothing else to do except sit and watch them finish, then you can start again, getting the buildings to churn out knights or catapults or whatever?

It's a bit of a waste of life, you sitting there doing nothing other than waiting for something to finish, then you can carry on with some other task..

As a human you probably don't do that; you go make a cup of coffee, call a friend, hit the punchbag, maybe even go play the space exploration game, set the autopilot of whatever ship to guide you to some star system on a journey that'll take 5 mintues of waiting and watching stars pass.. Autopilot set, coffee made, buildings still not finished, bored of the punchbag.. So you go clean up..

This isn't doing things in parallel; you aren't wiping the floor with a cloth while stirring the coffe and chatting on the phone, but it's making great use of your time, cracking through the todo list by pouring a load of energy into one thing, getting as far as you can, then switching to the next thing. You do one thing at once, but when you get stuck you move onto another thing. If you sat and waited for everything you'd need 10 copies of you to get 10 stop/start jobs done

async/await is the same thing. It takes syncronous code - something that is done from start to finish in one long operation that is the sole focus of your thread's attention, even if there's a 5 minute Wait() in the middle of it where it literally sits and does nothing for 5 minutes - and chops it up into a bunch of separate methods that are controlled by a process that allows the thread to pick up where it left off of

Marking a method async is the indicator to C# that the compiler is allowed to invisbly cut the method up into pieces that can be put down and picked up when needed

await is the indicator where you're saying "I've reached a point where I need some operation to finish before I can progress any further with this; go and find something else to do". When it encounters an await your thread will stop work on your code because it's being told it to do nothing more until the background operation completes (it's not important what is doing the work, lets imagine it's some background thread) and your thread will go and do something else until the result is ready. This really simplifies a lot of programming related stuff because you only ever deal with one thread - it's code that behaves like syncronous code but goes and does something else instead of doing nothing when it gets stuck

As a keyword await has to be followed by something that is awaitable, usually a Task or Task<T> - it represents the operation that is already set to happen. When the operation is finished and the thread returns await also helpfully unwraps the Task object that was controlling this process, and gives you the result..

If you take nothing else away from this, at the very least learn:

you must mark a method as async if you want to use await inside it. You should generally make the return type of an sync method as either Task (if it returns no value) or Task<X> (if it returns a value of type X). You should also call the method a name ending in ..Async

When you start some operation that works asyncronously (you call some method that is called ..Async), and you get a Task<X> object in return, use await on it to get the X you actually want

Making an async method means the method that calls it also has to be async, and the method that calls that also has to be async.. and.. All the way up the tree and out of your code. That's how your thread can "escape" when it has to go find something else to do - it needs to escape out of your code, so you make a route for that to happen by declaring "async all the way up"

I said in the comments not to use a console app. Let's imagine you have a Windows Forms app. Win Forms apps typically have one thread that does everything. One thread draws the UI, and when you click a button it comes and runs all the code you put in the button_Click() handler. While it's doing that it's not doing its normal job of drawing the UI. You can set statusLabel.Text = "Downloading data.." as the very first line of the method, and you can launch a download of a 1 gig file, and then you can set the status Label to "Finished " + downloadedFile.Length. You click the button, and you see nothing - the UI of your app jams frozen for 30 seconds while the file downloads. Then it suddenly says "Finished 1024000000" in the label:

void button_Click(object sender, EventArgs e){
  statusLabel.Text = "Starting download";
  string downloadedFile = new SomeHttpDownloadStringThing("http://..");
  statusLabel.Text = "Finished " + downloadedFile.Length;
}

Why? Well.. the thread that draws the UI and would have painted the label pixels on the screen got really busy downloading the file. It went into that SomeHttpDownloadStringThing method and didn't come out for 30 seconds, then it came out, set the status label text again, then it left your code and went back to whatever land it normally lives in. It drew the pixels on screen "Finished..". It never even knew it had to draw "Starting download".. That data was overwritten well before it picked up its paintbrush again

Let's turn it async:

async void button_Click(object sender, EventArgs e){
  statusLabel.Text = "Starting download";
  string downloadedFile = await SomeHttpDownloadStringThingAsync("http://..");
  statusLabel.Text = "Finished " + downloadedFile.Length;
}

SomeHttpDownloadStringThing returned a string. SomeHttpDownloadStringThingAsync returned a Task<string>. When the UI thread hits that await imagine it tells some background thread to go download the file, puts this method on pause, and returns out of it and goes back to drawing the UI. It paints the label as "Starting ..." so you see it, and then maybe finds some other stuff to do. If you had a Timer ticking up counting how long the download had been then your timer would increment nicely too - bcause the UI thread is free to do it, it's not sitting awaiting for Windows to do the download while it does nothing other than wait.

When the download finishes, the thread is called back to where it was and it picks up from there. It doesn't run the first code again, it doesn't set the status label to "Starting" again.

It literally starts from the SomeHttpDownloadStringThingAsync part as if it had never left, the await converts the Task<string> into a string of the downlaoded file, and then the UI thread can set the "Finished.." text

The whole thing is just like the syncronous version, except that little bit in the middle where the UI thread was allowed to go back to its regular job of drawing pixels on the screen and handling other user interaction

This is why I say console apps are hard work for understanding async/await because their UI doesn't obviously do anything else while an await is in progress, unless you've arranged for something to happen, but that's more work. UI apps automatically have other stuff going on, and if you jam up the threads that do that stuff, they freeze, and turn "Not responding"

If you have an eagle eye, you'll have spotted async void on the handler even though I said "if you have a void method, make it return Task when you make it async" - winforms event handlers are a bit of a special case in that regard, you cannot make them async Task but they're an exception rather than a rule. For now, rule of thumb - avoid async void


问:
Improper identifier with SQL compilation error in Snowflake
I am trying join two table in SQL using the following code:

```<code>SELECT
  lo.PATIENT_ID AS pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" AS lo
INNER JOIN
  "DB"."SCHEMA"."TABLE" AS de
ON
  lo.pid = de.pid
WHERE
  lo.SERVICE_CODE = `2345.7';
</code>```

I am getting an error stating "SQL compilation error: invalid identifier 'LO.PID'. Line 13 is referring to the ON statement "lo.pid = de.pid" The data types are the same. Is there a glaring issue in the code. I've tried changing the alias on both the tables and variables but that didn't seem to work.

答:
the problem is as everyone else says "you on clauses have to referrer to the table.column not the alias from the select region.

reproduction:

This SQL is wrong and gives your error:

```<code>with table_a (id, val_a) AS (
    SELECT * FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, val_b) AS (
    SELECT * FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as a_id
       ,b.id as b_id
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a_id = b_id;
</code>```

SQL compilation error: error line 18 at position 7 invalid identifier 'A_ID'

corrected:

it's a single change on the ON you use a.id = b.id

```<code>with table_a (id, val_a) AS (
    SELECT * FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, val_b) AS (
    SELECT * FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as a_id
       ,b.id as b_id
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a.id = b.id
;
</code>```

gives the correct results:

A_ID
B_ID
VAL_A
VAL_B

2
2
two
XX

3
3
three
XXX

counter points:

Now to be fair, you can use alias's from the SELECT in the WHERE region, but in the JOIN you are correctly use the table alias lo and de but pid needs to be something on those tables. Which it doesn't feel like it is, as you have an alias of patient_id to pid

which if you have had valid named columns available like in the SQL below, it just works fine:

```<code>with table_a (id, pid, val_a) AS (
    SELECT column1, column1, column2 FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, pid, val_b) AS (
    SELECT column1, column1, column2 FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as pid
       ,b.id as pid
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a.pid = b.pid
;
</code>```

Body:
I am trying join two table in SQL using the following code:

SELECT
  lo.PATIENT_ID AS pid,
  lo.SERVICE_CODE,
  de.PATIENT_ID as pid,
  de.STATE,
  de.GENDER,
  de.ETHNICITY
FROM
  "DB"."SCHEMA"."TABLE" AS lo
INNER JOIN
  "DB"."SCHEMA"."TABLE" AS de
ON
  lo.pid = de.pid
WHERE
  lo.SERVICE_CODE = `2345.7';

I am getting an error stating "SQL compilation error: invalid identifier 'LO.PID'. Line 13 is referring to the ON statement "lo.pid = de.pid" The data types are the same. Is there a glaring issue in the code. I've tried changing the alias on both the tables and variables but that didn't seem to work.

Body:
the problem is as everyone else says "you on clauses have to referrer to the table.column not the alias from the select region.

reproduction:

This SQL is wrong and gives your error:

with table_a (id, val_a) AS (
    SELECT * FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, val_b) AS (
    SELECT * FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as a_id
       ,b.id as b_id
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a_id = b_id;

SQL compilation error: error line 18 at position 7 invalid identifier 'A_ID'

corrected:

it's a single change on the ON you use a.id = b.id

with table_a (id, val_a) AS (
    SELECT * FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, val_b) AS (
    SELECT * FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as a_id
       ,b.id as b_id
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a.id = b.id
;

gives the correct results:

A_ID
B_ID
VAL_A
VAL_B

2
2
two
XX

3
3
three
XXX

counter points:

Now to be fair, you can use alias's from the SELECT in the WHERE region, but in the JOIN you are correctly use the table alias lo and de but pid needs to be something on those tables. Which it doesn't feel like it is, as you have an alias of patient_id to pid

which if you have had valid named columns available like in the SQL below, it just works fine:

with table_a (id, pid, val_a) AS (
    SELECT column1, column1, column2 FROM VALUES
        (1,'one'),
        (2,'two'),
        (3,'three')
), table_b (id, pid, val_b) AS (
    SELECT column1, column1, column2 FROM VALUES
        (4,'XXXX'),
        (2,'XX'),
        (3,'XXX')
)
SELECT a.id as pid
       ,b.id as pid
       ,a.val_a
       ,b.val_b
FROM table_a AS a
JOIN table_b AS b
    on a.pid = b.pid
;


问:
my data in the console is displayed in the wrong sequence
Why is my data in the console displayed in the wrong sequence?

I have the following code:

```<code>#include <iostream>

template <typename T, typename T2>
T2 printArr(const T* array, int i) {
    for (int j = 0; j < i; j++) {
        std::cout << array[j] << " ";
    }
    std::cout << std::endl;
    return array[i - 1];
}

int main() {
    const int iSize = 3;

    int i_arr[iSize] = {23, 45, 78};

    std::cout << "Int array: ";
    std::cout << "Last element: " << printArr<int, int>(i_arr, iSize) << std::endl;
}
</code>```

What do I get by compiling it:

```<code>Int array: 23 45 78
Last element: 78
</code>```

What should I get in my opinion:

```<code>Int array: Last element: 23 45 78
78
</code>```

Most likely, I do not understand how the computer that compiles my code thinks.

Here you can see that the result is the same as I described in my question: http://cpp.sh/2lfbcf

And I also try to compile the code in Visual Studio 2019 and the result is identical

答:
Before C++17, given an expression E1 << E2, it is unspecified whether every value computation and side-effect of E1 is sequenced before every value computation and side effect of E2.

See cppreference note 19

In your code, using a standard before C++17, it is unspecified whether the return value of printArr() is calculated (which as a side-effect, streams to std::cout) before or after std::cout << "Last element: ".

Body:
Why is my data in the console displayed in the wrong sequence?

I have the following code:

#include <iostream>

template <typename T, typename T2>
T2 printArr(const T* array, int i) {
    for (int j = 0; j < i; j++) {
        std::cout << array[j] << " ";
    }
    std::cout << std::endl;
    return array[i - 1];
}

int main() {
    const int iSize = 3;

    int i_arr[iSize] = {23, 45, 78};

    std::cout << "Int array: ";
    std::cout << "Last element: " << printArr<int, int>(i_arr, iSize) << std::endl;
}

What do I get by compiling it:

Int array: 23 45 78
Last element: 78

What should I get in my opinion:

Int array: Last element: 23 45 78
78

Most likely, I do not understand how the computer that compiles my code thinks.

Here you can see that the result is the same as I described in my question: http://cpp.sh/2lfbcf

And I also try to compile the code in Visual Studio 2019 and the result is identical


问:
Write csv with different separators in same df in R
I have a dataframe in R and I need to export it as .csv with "," separator to the column names and ";" separator to the rest of the dataframe (all the data rows).

So I need something like this:

```<code>name_col1,name_col2,name_col3
v1;v2;v3
v4;v5;v6
</code>```

答:
Simply use 2 write.tables

```<code>d
  name_col1 name_col2 name_col3
1        v1        v2        v3
2        v4        v5        v6

write.table(t(colnames(d)), file="d.dat", sep=",", col.names=F, row.names=F)
write.table(d, file="d.dat", sep=";", col.names=F, row.names=F, append=T)
</code>```

Body:
I have a dataframe in R and I need to export it as .csv with "," separator to the column names and ";" separator to the rest of the dataframe (all the data rows).

So I need something like this:

name_col1,name_col2,name_col3
v1;v2;v3
v4;v5;v6

Body:
Simply use 2 write.tables

d
  name_col1 name_col2 name_col3
1        v1        v2        v3
2        v4        v5        v6

write.table(t(colnames(d)), file="d.dat", sep=",", col.names=F, row.names=F)
write.table(d, file="d.dat", sep=";", col.names=F, row.names=F, append=T)


问:
Html horizontal scroll wont move even so its showing
This is my html and css code.I am trying to have the effect like scrolling through pages horizontally . The Scrollbar is showing that its on half but it wont budge.
I am sure I am missing something really primitive any help?
Thanks in advance

```<code>            <div className='scroll-horizontal'>
            <div className='pages white'>
            </div>
            <div className='pages black'>
            <Models />
            </div>
            </div>
</code>```

---css

```<code>             .scroll-horizontal{
             display: grid;
             grid-auto-flow: column;
             grid-auto-columns: 100%;
             gap: 5vw;
             overflow-x:auto;
             height: 100vh;
             white-space: nowrap;
             }

             .pages{
             width: 100vw;
             height: 100vh;
            display: inline-block;
            justify-content: center;
            align-items: center;
             }
</code>```

答:
I have updated your code to be valid HTML and pasted it into the below snippet, it should work as expected.

body {
  margin: 0;
  background-color: antiquewhite;
}

.scroll-horizontal {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 100%;
  gap: 5vw;
  overflow-x: auto;
  height: 100vh;
  white-space: nowrap;
}

.pages {
  width: 100vw;
  height: 100vh;
  display: inline-block;
  justify-content: center;
  align-items: center;
}

.white {
  background-color: aqua;
  color: white;
}

.black {
  background-color: #000;
  color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='scroll-horizontal'>
  <div class='pages white'>
    Scroll left to go right
  </div>
  <div class='pages black'>
    Scroll right to go left
  </div>
</div></code>```

Body:
This is my html and css code.I am trying to have the effect like scrolling through pages horizontally . The Scrollbar is showing that its on half but it wont budge.
I am sure I am missing something really primitive any help?
Thanks in advance

            <Models />

---css

             .scroll-horizontal{
             display: grid;
             grid-auto-flow: column;
             grid-auto-columns: 100%;
             gap: 5vw;
             overflow-x:auto;
             height: 100vh;
             white-space: nowrap;
             }

             .pages{
             width: 100vw;
             height: 100vh;
            display: inline-block;
            justify-content: center;
            align-items: center;
             }

Body:
I have updated your code to be valid HTML and pasted it into the below snippet, it should work as expected.

body {
  margin: 0;
  background-color: antiquewhite;
}

.scroll-horizontal {
  display: grid;
  grid-auto-flow: column;
  grid-auto-columns: 100%;
  gap: 5vw;
  overflow-x: auto;
  height: 100vh;
  white-space: nowrap;
}

.pages {
  width: 100vw;
  height: 100vh;
  display: inline-block;
  justify-content: center;
  align-items: center;
}

.white {
  background-color: aqua;
  color: white;
}

.black {
  background-color: #000;
  color: red;
}

<div class='scroll-horizontal'>
  <div class='pages white'>
    Scroll left to go right
  </div>
  <div class='pages black'>
    Scroll right to go left
  </div>
</div>


问:
warning: unused variable
see in one code i have written

```<code>void my_function()
{
INT32 i;    /* Variable for iteration */
/* If system is little-endian, store bytes in array as reverse order */
#ifdef LITTLE
   {
    // i m using i for operating one loop
   }
#endif

 /* If the system is big-endian, store bytes in array as forward order */
#ifdef  BIG
   {
   // using i for loop
   }
#endif
return;
 }
</code>```

by compiling this code with -Wall flag it shows

```<code> warning: unused variable ‘i’
</code>```

why?
how can i remove this?

答:
hey i got the answer...

see BIG & LITTLE are preposser flag & they are given at compile time.
when i was compiling my project with make file i was giving this flag at compile time but while testing each individual file i was compiling like

```<code>gcc -Wall -c filename.c
</code>```

This was comming because i havent given any flag so compiler going to neglet that much portion of code & i was getting warning.

```<code>gcc -Wall -c -LITTLE filename.c
</code>```

works perfectly...

Title: warning: unused variable

Body:
see in one code i have written

void my_function()
{
INT32 i;    /* Variable for iteration */
/* If system is little-endian, store bytes in array as reverse order */
#ifdef LITTLE
   {
    // i m using i for operating one loop
   }
#endif

 /* If the system is big-endian, store bytes in array as forward order */
#ifdef  BIG
   {
   // using i for loop
   }
#endif
return;
 }

by compiling this code with -Wall flag it shows

 warning: unused variable ‘i’

why?
how can i remove this?

Body:
hey i got the answer...

see BIG & LITTLE are preposser flag & they are given at compile time.
when i was compiling my project with make file i was giving this flag at compile time but while testing each individual file i was compiling like

gcc -Wall -c filename.c

This was comming because i havent given any flag so compiler going to neglet that much portion of code & i was getting warning.

gcc -Wall -c -LITTLE filename.c

works perfectly...

ContentLicense: CC BY-SA 3.0


问:
I want to write a python code using tkinter to get textbox value and output it. But Its not working properly
.</p>
```<code>from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self):
        self.gui=Tk()
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        global username
        global password
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username)

signup=sign()
</code>```

答:
I am going to answer your question and improve your code a bit (with explanation)

sections:

problem solving

classes and tkinter

I assume you want the code to run like this:

start gui.

input username and password.

show username in messagebox.

run program

problem solving

I think you mean with "not working properly" that it outputs "PY_VAR0". What happens here is that you're not actually extracting the input of the textbox, but the name that python gives it to identify it. To solve this just use the get() function.

def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username.get())
```
<h4>classes and tkinter</h4>
<p>In tkinter there's something called <code>mainloop()</code>. that makes sure that the gui gets displayed and the program responds to the users input. If you use classes,  you should add a parameter <code>master</code> in the <code>__init__()</code> function. then below your class you can specify your master. I will call him <code>root</code> because it's the commonly used name for a master.</p>
<pre class="lang-py prettyprint-override"><code>class sign:
    def __init__(self,master):
        self.gui=master
        self.gui.geometry("800x450")
        self.gui.title("Quiz")

root = Tk()
signup = sign(root)
root.mainloop()
</code>```

Tip: if you want to use multiple windows, use toplevels.

This is the complete code:

from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self,master):
        self.gui=master
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username.get())
        username = self.username.get()
        password = self.password.get()

username = ""
password = ""
root = Tk()
signup = sign(root)
root.mainloop()
```

Tip: take a look at this course about the difference between global and local variables

Body:
.

from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self):
        self.gui=Tk()
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        global username
        global password
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username)

signup=sign()

Body:
I am going to answer your question and improve your code a bit (with explanation)

sections:

problem solving

classes and tkinter

I assume you want the code to run like this:

start gui.

input username and password.

show username in messagebox.

run program

problem solving

I think you mean with "not working properly" that it outputs "PY_VAR0". What happens here is that you're not actually extracting the input of the textbox, but the name that python gives it to identify it. To solve this just use the get() function.

def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username.get())

classes and tkinter

In tkinter there's something called mainloop(). that makes sure that the gui gets displayed and the program responds to the users input. If you use classes,  you should add a parameter master in the __init__() function. then below your class you can specify your master. I will call him root because it's the commonly used name for a master.

class sign:
    def __init__(self,master):
        self.gui=master
        self.gui.geometry("800x450")
        self.gui.title("Quiz")

root = Tk()
signup = sign(root)
root.mainloop()

Tip: if you want to use multiple windows, use toplevels.

This is the complete code:

from tkinter import *
import tkinter.messagebox

class sign:
    def __init__(self,master):
        self.gui=master
        self.gui.geometry("800x450")
        self.gui.title("Quiz")
        self.signup_form()

    def signup_form(self):
        self.username = StringVar()
        self.password = StringVar()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Username :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.username).pack()
        Label(self.gui, text="").pack()
        Label(self.gui, text="Password :", fg="black", font=('arial', 12, 'bold')).pack()
        Entry(self.gui, textvariable=self.password, show="*").pack()
        Label(self.gui, text="").pack()
        Button(self.gui, text="sign up", bg="white", fg='blue', relief="solid", font=('arial', 12, 'bold'),command=self.msg).pack()
        Label(self.gui, text="")

    def msg(self):
        tkinter.messagebox.showinfo("Msg",self.username.get())
        username = self.username.get()
        password = self.password.get()

username = ""
password = ""
root = Tk()
signup = sign(root)
root.mainloop()

Tip: take a look at this course about the difference between global and local variables


问:
Git: rename tag keeping original date
In this question How do you rename a Git tag? instructions are given to rename an old tag.

I'd like to know it these steps will keep the original date in the edited tag in place.

For example, in my git repo the git tag command shows:

```<code>v0.1
v1.0.0-beta
</code>```

and Github shows:

I want to update the old v0.1 tag to a more descriptive v1.0.0-alpha (which also follows the Semantic Versioning guidelines) but I'd also like to keep the original date (4 Dec 2013) in place.

Is this possible using the commands given in the answer to the question mentioned above? These would be the commands in my case as I understand:

```<code>git tag v1.0.0-alpha v0.1
git tag -d v0.1
git push origin :refs/tags/v0.1
git push --tags
</code>```

答:
In our repository I noticed that one of our older releases had an incorrect version tag. The name was v.1.28.0 instead of v1.28.0. I wanted to correct the issue without somehow messing up the GitHub release.

These are the steps I did to correct it:

check out the incorrect tag, e.g. git checkout v.1.28.0

create a temporary branch, e.g. git checkout -b release/v1.28.0

push the temporary branch, e.g. git push -u origin release/v1.28.0

edit the release in GitHub, change the tag name and point it to the temporary branch

save the changes on GitHub

check out a different branch, e.g. git checkout develop

remove the temporary branch, e.g. git branch -d release/v1.28.0

remove the old incorrect tag, e.g. git tag -d v.1.28.0

Title: Git: rename tag keeping original date

Body:
In this question How do you rename a Git tag? instructions are given to rename an old tag.

I'd like to know it these steps will keep the original date in the edited tag in place.

For example, in my git repo the git tag command shows:

v0.1
v1.0.0-beta

and Github shows:

I want to update the old v0.1 tag to a more descriptive v1.0.0-alpha (which also follows the Semantic Versioning guidelines) but I'd also like to keep the original date (4 Dec 2013) in place.

Is this possible using the commands given in the answer to the question mentioned above? These would be the commands in my case as I understand:

git tag v1.0.0-alpha v0.1
git tag -d v0.1
git push origin :refs/tags/v0.1
git push --tags


问:
What's wrong with Hello World in scala?
I am learning scala from docs.scala-lang.org. There is an example

```<code>object HelloYou extends App {
    if (args.size == 0)
        println("Hello, you")
    else
        println("Hello, " + args(0))
}
</code>```

After compiling with scalac I run scala HelloYou Al and get

java.lang.NullPointerException

followed by

```<code>    at java.lang.reflect.Array.getLength(Native Method)
    at scala.collection.ArrayOps$.size$extension(ArrayOps.scala:197)
    at HelloYou$.<clinit>(HelloYou.scala:2)
    at HelloYou.main(HelloYou.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
</code>```

What's wrong? It's my first experience of a language where Hello, World is not working...

Details

```<code>scala -version
Scala code runner version 3.1.1 -- Copyright 2002-2022, LAMP/EPFL

java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)
</code>```

答:
App was never a good idea to begin with, just write a normal main method.

object HelloYou:
  def main(args: Array[String]): Unit =
    args.toList match
      case Nil =>
        println("Hello, you")

      case name :: Nil =>
        println(s"Hello, ${name}")

      case _ =>
        println("Hello, you all")
  end main
end HelloYou
```

Title: What's wrong with Hello World in scala?

Body:
I am learning scala from docs.scala-lang.org. There is an example

object HelloYou extends App {
    if (args.size == 0)
        println("Hello, you")
    else
        println("Hello, " + args(0))
}

After compiling with scalac I run scala HelloYou Al and get

java.lang.NullPointerException

followed by

    at java.lang.reflect.Array.getLength(Native Method)
    at scala.collection.ArrayOps$.size$extension(ArrayOps.scala:197)
    at HelloYou$.<clinit>(HelloYou.scala:2)
    at HelloYou.main(HelloYou.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

What's wrong? It's my first experience of a language where Hello, World is not working...

Details

scala -version
Scala code runner version 3.1.1 -- Copyright 2002-2022, LAMP/EPFL

java -version
java version "1.8.0_321"
Java(TM) SE Runtime Environment (build 1.8.0_321-b07)
Java HotSpot(TM) 64-Bit Server VM (build 25.321-b07, mixed mode)


问:
What is the step by step instructions to upgrade my PyCharm from intel silicon to M1 Chip?
When I restored from a time machine pycharm was already there but it was the intel pycharm on my m1 mac. I don't want to lose all my project settings and deployment. Also, I don't understand if I have to uninstall the previous pycharm or how to install it once I downloaded the m1 dmg.

Are there unambiguous steps on how to install the m1 mac PyCharm if one already has a intel PyCharm on my new current m1 mac machine (that was restored from a time machine)?

cross: https://intellij-support.jetbrains.com/hc/en-us/community/posts/4417818919954-What-is-the-step-by-step-instructions-to-upgrade-my-PyCharm-from-intel-silicon-to-M1-Chip-

related: How do I get my settings from PyCharm in a file so not to lose them when updating PyCharm or creating a new Project?

答:
The instructions are simple (or they worked too well...)

uninstall pycharm by removing it from applications

download the arch m1 chip dmg and download it.

That's all.

Although I did save the setting by going to

```<code>File | Manage IDE Settings | Export Settings
</code>```

I did not need to import them since I opened the new pycharm and it already new everything. Also even though I saved the .idea folder of my previous project (which was at the root of the folder with the folder name of the github repo that created the project, if you can't find the .idea folder see Show .idea folder in PhpStorm project tool window) I didn't end up needed it. Creepy but I guess thats fine.

If you get the following error

```<code>xcrun: error: unable to load libxcrun (dlopen(/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib, 0x0005): tried: '/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/lib/libxcrun.dylib' (no such file)).
</code>```

do the following (source):

What I suggest is to uninstall the command line tools (CLT) and re-install them the official way (source).

So do (source):

```<code>sudo rm -rf /Library/Developer/CommandLineTools
</code>```

check it uninstalled, you should get an output as follows:

```<code>xcode-select -p
</code>```

output

```<code>xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)
</code>```

then install the command line tools (CLT) again:

```<code>xcode-select --install
</code>```

then agree to it and it should download after a couple of minutes. The download should take some time. For me ~13mins.

After that your issues with PyCharm, git, brew and likely other tools will be resolved.

Body:
The instructions are simple (or they worked too well...)

uninstall pycharm by removing it from applications

download the arch m1 chip dmg and download it.

That's all.

Although I did save the setting by going to

File | Manage IDE Settings | Export Settings

I did not need to import them since I opened the new pycharm and it already new everything. Also even though I saved the .idea folder of my previous project (which was at the root of the folder with the folder name of the github repo that created the project, if you can't find the .idea folder see Show .idea folder in PhpStorm project tool window) I didn't end up needed it. Creepy but I guess thats fine.

If you get the following error

xcrun: error: unable to load libxcrun (dlopen(/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib, 0x0005): tried: '/Library/Developer/CommandLineTools/usr/lib/libxcrun.dylib' (mach-o file, but is an incompatible architecture (have 'x86_64', need 'arm64e')), '/usr/lib/libxcrun.dylib' (no such file)).

do the following (source):

What I suggest is to uninstall the command line tools (CLT) and re-install them the official way (source).

So do (source):

sudo rm -rf /Library/Developer/CommandLineTools

check it uninstalled, you should get an output as follows:

xcode-select -p

output

xcode-select: error: unable to get active developer directory, use `sudo xcode-select --switch path/to/Xcode.app` to set one (or see `man xcode-select`)

then install the command line tools (CLT) again:

xcode-select --install

then agree to it and it should download after a couple of minutes. The download should take some time. For me ~13mins.

After that your issues with PyCharm, git, brew and likely other tools will be resolved.


问:
How to make Jenkins pipeline to build on arm + arm64 + amd64
I'm using Jenkins to build packages for Debian and Ubuntu. The new Raspberry PI nodes was added into my setup to build packages for Raspbian:

The problem is how to make pipeline which build noarch package on any node and binary package on nodes for each architecture ?

I'm using patched docker image for each distribution to build package and perform test install for Debian 10-11 and Ubuntu 20.04-21.04.
The armel/aarch64 versions of debian images also present on its Raspberry 3/4 nodes.

By default Jenkins pick one of nodes and triger build on it.

```<code>    stages {

        stage('debian-buster') {
            agent {
                docker { image 'vitexsoftware/debian:buster' }
            }
            steps {
                dir('build/debian/package') {
                    checkout scm
                buildPackage()
                installPackages()
                }
                stash includes: 'dist/**', name: 'dist-buster'
            }
            post {
                success {
                    archiveArtifacts 'dist/debian/'
                    copyArtifact()
                }
            }
        }
...
</code>```

How i can specify some architecture axe for build ?

Can i use jenkins node labels somehow ?

答:
There is not way how to solve this problem using Declarative Pipeline.

The scripted pipeline do the stuff:

```<code>
#!groovy
String[] architectures = ['amd64', 'armhf', 'aarch64']
String[] distributions = ['debian:buster', 'debian:bullseye', 'debian:bookworm', 'ubuntu:focal', 'ubuntu:hirsute', 'ubuntu:impish']

String vendor = 'vitexsoftware'
String distribution = ''
String architecture = ''
String dockerfile = ''
String buildArgs = ''

architectures.each {
    architecture = it
    distributions.each {
        distribution = it
        dockerfile =  distribution + '/Dockerfile'
        buildArgs = ' --platform linux/' + architecture +
/*        ' -t ' + vendor + '/' + distribution + */
        ' -f ' + dockerfile + ' ' + distribution

        def buildImage = ''

        node( architecture ) {
            ansiColor('xterm') {
                stage('Build ' + architecture + '/' + distribution) {
                    checkout scm
                    buildImage = docker.build(vendor + '/' + distribution, buildArgs)
                }
                stage('Test ' + architecture + '/' + distribution) {
                    buildImage.inside {
                        sh 'whoami'
                        sh 'sudo apt install -y linuxlogo'
                        sh 'linuxlogo'
                    }
                }
                stage('Docker push ' + architecture + '/' + distribution ) {
                    docker.withRegistry('https://registry.hub.docker.com', 'vitex_dockerhub') {
                        buildImage.push(  distribution + "-${env.BUILD_NUMBER}-SNAPSHOT")
                    }
                }
            }
        }
    }
}

[![Jenkins Buildfarm in Action][1]][1]
</code>```

Body:
I'm using Jenkins to build packages for Debian and Ubuntu. The new Raspberry PI nodes was added into my setup to build packages for Raspbian:

The problem is how to make pipeline which build noarch package on any node and binary package on nodes for each architecture ?

I'm using patched docker image for each distribution to build package and perform test install for Debian 10-11 and Ubuntu 20.04-21.04.
The armel/aarch64 versions of debian images also present on its Raspberry 3/4 nodes.

By default Jenkins pick one of nodes and triger build on it.

    stages {

        stage('debian-buster') {
            agent {
                docker { image 'vitexsoftware/debian:buster' }
            }
            steps {
                dir('build/debian/package') {
                    checkout scm
                buildPackage()
                installPackages()
                }
                stash includes: 'dist/**', name: 'dist-buster'
            }
            post {
                success {
                    archiveArtifacts 'dist/debian/'
                    copyArtifact()
                }
            }
        }
...

How i can specify some architecture axe for build ?

Can i use jenkins node labels somehow ?

Body:
There is not way how to solve this problem using Declarative Pipeline.

The scripted pipeline do the stuff:

#!groovy
String[] architectures = ['amd64', 'armhf', 'aarch64']
String[] distributions = ['debian:buster', 'debian:bullseye', 'debian:bookworm', 'ubuntu:focal', 'ubuntu:hirsute', 'ubuntu:impish']

String vendor = 'vitexsoftware'
String distribution = ''
String architecture = ''
String dockerfile = ''
String buildArgs = ''

architectures.each {
    architecture = it
    distributions.each {
        distribution = it
        dockerfile =  distribution + '/Dockerfile'
        buildArgs = ' --platform linux/' + architecture +
/*        ' -t ' + vendor + '/' + distribution + */
        ' -f ' + dockerfile + ' ' + distribution

        def buildImage = ''

        node( architecture ) {
            ansiColor('xterm') {
                stage('Build ' + architecture + '/' + distribution) {
                    checkout scm
                    buildImage = docker.build(vendor + '/' + distribution, buildArgs)
                }
                stage('Test ' + architecture + '/' + distribution) {
                    buildImage.inside {
                        sh 'whoami'
                        sh 'sudo apt install -y linuxlogo'
                        sh 'linuxlogo'
                    }
                }
                stage('Docker push ' + architecture + '/' + distribution ) {
                    docker.withRegistry('https://registry.hub.docker.com', 'vitex_dockerhub') {
                        buildImage.push(  distribution + "-${env.BUILD_NUMBER}-SNAPSHOT")
                    }
                }
            }
        }
    }
}

[![Jenkins Buildfarm in Action][1]][1]


问:
Is there a Python function equivalent to the ob_start() and ob_get_clean() in PHP?
I have this code:

```<code>line = input("Line of code: ")
output = exec(line)
</code>```

Naturally it doesn't work because if you write print("Hello World") it only prints "Hello World" and the output variable will have None value.
So, in PHP I could use the output buffering in this way:

```<code><?php
ob_start();
echo "Hello World";
output = ob_get_clean();
?>
</code>```

Is there an equivalent function or a similar way in Python? This is exactly what I need.
Thanks in advance.

答:
You could patch print to write into a temporary buffer:

```<code>from io import StringIO

#line = input("Line of code: ")
line = 'print("Hello World")'

# patch print. All following print statements are writing into in-memory text buffer!
out = StringIO('')

# Keep reference to old print function
_print = print

# overwrite print, in order to write into StringIO
print = lambda x: _print(x, file=out)
print("Before.")
exec(line)
print("After.")
print = _print # Switch back to original version
print(out.getvalue())
</code>```

Out:

```<code>Before.
Hello World
After.
</code>```

Body:
I have this code:

line = input("Line of code: ")
output = exec(line)

Naturally it doesn't work because if you write print("Hello World") it only prints "Hello World" and the output variable will have None value.
So, in PHP I could use the output buffering in this way:

<?php
ob_start();
echo "Hello World";
output = ob_get_clean();
?>

Is there an equivalent function or a similar way in Python? This is exactly what I need.
Thanks in advance.

Body:
You could patch print to write into a temporary buffer:

from io import StringIO

#line = input("Line of code: ")
line = 'print("Hello World")'

# patch print. All following print statements are writing into in-memory text buffer!
out = StringIO('')

# Keep reference to old print function
_print = print

# overwrite print, in order to write into StringIO
print = lambda x: _print(x, file=out)
print("Before.")
exec(line)
print("After.")
print = _print # Switch back to original version
print(out.getvalue())

Out:

Before.
Hello World
After.