问:
ASP.Net MVC switching Cultures after compile for initial load
I have a hybrid ASP.Net web forms/MVC app. On one of the MVC "pages"/views, I have it render a bunch of dates using the ToShortDateString() and ToLongDateString(). These work correctly most of the time, but the first time I load the view after compiling the app, they are formatted incorrectly.

I traced this down and checked the current thread's culture. For 99% of the time it's en-US, but on the first load of the MVC view after compiling it is set to en-GB. If I reload the page immediately after that, it's back to en-US.

I have tried setting the culture and uiculture in the web.config file to en-US to force it to be correct, but no luck.

Anyone have any ideas on this one? Bug in MVC?

Edit (additional code and attempts):
Even if I go completely overboard and include this in the base class of the view

```<code>public class DNViewPage<T> : ViewPage<T> where T : class
    {

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
        }

        protected void Page_Load(object sender, EventArgs e) {
            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
        }

        protected override void InitializeCulture() {

            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;

            base.InitializeCulture();
        }
    }
</code>```

and include this in the web.config

```<code><globalization requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="en-US" culture="en-US"/>
</code>```

and this in the header of the .aspx file

```<code><%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Culture="en-US" UICulture="en-US"
</code>```

Again, this is only on the initial load after compiling the code, when that page first loads. Other web forms pages are unaffected, even if they descend from System.Web.Mvc.ViewPage. All subsequent loads treat the culture correctly. Just changing the .aspx file doesn't cause this, the c# code has to be compiled to cause this.

More data:
I have it tracked down to the Render method. Before the Render method, the culture is en-US and afterwards it is en-GB (again only on initial pageload after compilation).

答: This turned out to be caused by an a dependency on an out of date, third party .dll. Once I tracked it down, and got the updated .dll, all was good again.</p>

Body:
I have a hybrid ASP.Net web forms/MVC app. On one of the MVC "pages"/views, I have it render a bunch of dates using the ToShortDateString() and ToLongDateString(). These work correctly most of the time, but the first time I load the view after compiling the app, they are formatted incorrectly.

I traced this down and checked the current thread's culture. For 99% of the time it's en-US, but on the first load of the MVC view after compiling it is set to en-GB. If I reload the page immediately after that, it's back to en-US.

I have tried setting the culture and uiculture in the web.config file to en-US to force it to be correct, but no luck.

Anyone have any ideas on this one? Bug in MVC?

Edit (additional code and attempts):
Even if I go completely overboard and include this in the base class of the view

public class DNViewPage<T> : ViewPage<T> where T : class
    {

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
        }

        protected void Page_Load(object sender, EventArgs e) {
            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;
        }

        protected override void InitializeCulture() {

            CultureInfo cultureInfo = new CultureInfo("en-US");
            this.Culture = "en-US";
            this.UICulture = "en-US";
            Thread.CurrentThread.CurrentUICulture = cultureInfo;
            Thread.CurrentThread.CurrentCulture = cultureInfo;

            base.InitializeCulture();
        }
    }

and include this in the web.config

<globalization requestEncoding="utf-8" responseEncoding="utf-8" uiCulture="en-US" culture="en-US"/>

and this in the header of the .aspx file

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Culture="en-US" UICulture="en-US"

Again, this is only on the initial load after compiling the code, when that page first loads. Other web forms pages are unaffected, even if they descend from System.Web.Mvc.ViewPage. All subsequent loads treat the culture correctly. Just changing the .aspx file doesn't cause this, the c# code has to be compiled to cause this.

More data:
I have it tracked down to the Render method. Before the Render method, the culture is en-US and afterwards it is en-GB (again only on initial pageload after compilation).


来源: stackexchange

问:
chisel printf fail (built using chisel3 then verilator to C++)
This is a slightly modified version of the HelloWorld.scala example from https://github.com/freechipsproject/chisel3/wiki/Frequently-Asked-Questions

```<code>// say hello
package HelloWorld

import chisel3._

class HelloWorld extends Module {
  val io = IO(new Bundle{
    val halt = Output(Bool())
    val may_halt = Input(Bool())
  })
  printf("hello, world!\n");
  when (io.may_halt) {
    io.halt := true.B
  } .otherwise {
    io.halt := false.B
  }
}

// code for building HelloWorld
object HelloWorld extends App {
  chisel3.Driver.execute(args, () => new HelloWorld)
}
</code>```

I build it using chisel3 then verilator to generate C++.  Here is the interesting part of the C++ harness:

```<code>VHelloWorld *top;               // Instantiation of module

int main(int argc, char** argv) {
  Verilated::commandArgs(argc, argv); // Remember args

  top = new VHelloWorld;              // Create instance

  printf("eval loop start\n");
  long long cycle = 0;
  for (; !Verilated::gotFinish(); ++cycle) {
    printf("\tcycle: %lld\n", cycle);
    if (2 <= cycle) {
      printf("\t\tput io_may_halt = 1\n");
      top->io_may_halt = 1;
    }
    top->eval();                      // Evaluate model
    if (top->io_halt) {
      printf("\t\tgot an io_halt, so halting\n");
      break;                   // halt when we get the signal to do so
    }
  }

  printf("eval loop stop\n");
  top->final();                       // Done simulating

  delete top;                         // (Though this example doesn't get here)
  return 0;
}
</code>```

I run it for a few cycles before signaling it to halt.  Yet the "hello, world!" message never comes out.

```<code>HelloWorld.cppdir/HelloWorld.exe
eval loop start
    cycle: 0
    cycle: 1
    cycle: 2
        put io_may_halt = 1
        got an io_halt, so halting
eval loop stop
</code>```

答:
I figured it out: the printf() only happens on a rising clock, so the C++ harness wrapped around the verilator code must explicitly (1) drive the clock low, (2) eval(), (2) drive the clock high, (3) eval(), and then the printf() will print. (Actually I am not sure (2) is required, but it would be weird to not do it.).

I had said in my comment above that the verilator examples do not show the C++ harness doing this, however in a more complex example and in a more complex way, they do.

ContentLicense: CC BY-SA 4.0

Body:
This is a slightly modified version of the HelloWorld.scala example from https://github.com/freechipsproject/chisel3/wiki/Frequently-Asked-Questions

// say hello
package HelloWorld

import chisel3._

class HelloWorld extends Module {
  val io = IO(new Bundle{
    val halt = Output(Bool())
    val may_halt = Input(Bool())
  })
  printf("hello, world!\n");
  when (io.may_halt) {
    io.halt := true.B
  } .otherwise {
    io.halt := false.B
  }
}

// code for building HelloWorld
object HelloWorld extends App {
  chisel3.Driver.execute(args, () => new HelloWorld)
}

I build it using chisel3 then verilator to generate C++.  Here is the interesting part of the C++ harness:

VHelloWorld *top;               // Instantiation of module

int main(int argc, char** argv) {
  Verilated::commandArgs(argc, argv); // Remember args

  top = new VHelloWorld;              // Create instance

  printf("eval loop start\n");
  long long cycle = 0;
  for (; !Verilated::gotFinish(); ++cycle) {
    printf("\tcycle: %lld\n", cycle);
    if (2 <= cycle) {
      printf("\t\tput io_may_halt = 1\n");
      top->io_may_halt = 1;
    }
    top->eval();                      // Evaluate model
    if (top->io_halt) {
      printf("\t\tgot an io_halt, so halting\n");
      break;                   // halt when we get the signal to do so
    }
  }

  printf("eval loop stop\n");
  top->final();                       // Done simulating

  delete top;                         // (Though this example doesn't get here)
  return 0;
}

I run it for a few cycles before signaling it to halt.  Yet the "hello, world!" message never comes out.

HelloWorld.cppdir/HelloWorld.exe
eval loop start
    cycle: 0
    cycle: 1
    cycle: 2
        put io_may_halt = 1
        got an io_halt, so halting
eval loop stop


问:
Laravel: querying for all records with a timestamp from today
I have an Orders table that has a field scan_date in unix timecode.  I am trying to get all Orders with a scan_date WITHIN the current day.  I was originally using whereBetween() to grab orders within the last 24 hours of whenever it's run but I realized that's not doing exactly what I need.

```<code>->whereBetween('scan_date', [Carbon::now()->addDays(-1), Carbon::now()])
</code>```

If an order has a scan_date between 12:01AM and 11:59pm on the current day, I want to grab all those orders -- is this possible to query for?

答:
Similar to what you were doing, with a small modification:</p>

```<code>$today = \Carbon\Carbon::today();
$startOfDayTimestamp = $today->copy()->startOfDay()->timestamp;
$endOfDayTimestamp = $today->copy()->endOfDay()->timestamp;

->whereBetween('scan_date', [
    $startOfDayTimestamp,
    $endOfDayTimestamp
])
</code>```

Body:
I have an Orders table that has a field scan_date in unix timecode.  I am trying to get all Orders with a scan_date WITHIN the current day.  I was originally using whereBetween() to grab orders within the last 24 hours of whenever it's run but I realized that's not doing exactly what I need.

->whereBetween('scan_date', [Carbon::now()->addDays(-1), Carbon::now()])

If an order has a scan_date between 12:01AM and 11:59pm on the current day, I want to grab all those orders -- is this possible to query for?

Body:
Similar to what you were doing, with a small modification:

$today = \Carbon\Carbon::today();
$startOfDayTimestamp = $today->copy()->startOfDay()->timestamp;
$endOfDayTimestamp = $today->copy()->endOfDay()->timestamp;

->whereBetween('scan_date', [
    $startOfDayTimestamp,
    $endOfDayTimestamp
])


问:
Wrap N-arg function into another function
I have a function which executes another function in worker thread:

```<code>void run_in_worker_thread( std::function< void( ) > proc )
</code>```

Now I would like to implement function schedule() which takes proc() function as argument and returns function which executes proc() in worker thread via run_in_worker_thread().

Here is my implementation:

```<code>#include <iostream>
#include <functional>

using namespace std;

class Test
{
  public:
    void run_in_worker_thread( std::function< void( ) > proc )
    {
            std::cout << "execute in worker thread\n";
            proc();
    }

    template < class... TArgs >
    std::function< void( TArgs... ) >
    schedule( std::function< void( TArgs... ) > proc )
    {
        std::function< void( TArgs... ) > f
                = [this, proc]( TArgs... args ) { run_in_worker_thread( [=]( ) { proc( args... ); } ); };
        return f;
    }
};

int main()
{
    Test test;
    std::function<void(int, int)> my_funciton =
         [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );
    f2(1, 2);
    return 0;
}
</code>```

The problem is that my schedule() requires std::function as argument. For instance, the following call leads to a compilation error:

```<code>    auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );
</code>```

答:
The issue is that a std::function is a polymorphic wrapper around a callable object. Lambdas are not std::functions. Just like string literals are not std::strings. In your first example, you do this:

```<code>std::function<void(int, int)> my_funciton =
     [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
</code>```

You're constructing a std::function from the lambda. The schedule function is able to deduce the signature of the function without problems.

In your second example, you do this:

```<code>auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
</code>```

Then you get an error because std::function<void (Args...)> can't be matched against the lambda. The solution to this is to allow schedule to accept any callable object, not just std::function.

```<code>template <typename Func>
auto schedule(Func proc) {
  return [this, proc](auto... args) {
    run_in_worker_thread([=]() {
      proc(args...);
    });
  };
}
</code>```

Body:
I have a function which executes another function in worker thread:

void run_in_worker_thread( std::function< void( ) > proc )

Now I would like to implement function schedule() which takes proc() function as argument and returns function which executes proc() in worker thread via run_in_worker_thread().

Here is my implementation:

#include <iostream>
#include <functional>

using namespace std;

class Test
{
  public:
    void run_in_worker_thread( std::function< void( ) > proc )
    {
            std::cout << "execute in worker thread\n";
            proc();
    }

    template < class... TArgs >
    std::function< void( TArgs... ) >
    schedule( std::function< void( TArgs... ) > proc )
    {
        std::function< void( TArgs... ) > f
                = [this, proc]( TArgs... args ) { run_in_worker_thread( [=]( ) { proc( args... ); } ); };
        return f;
    }
};

int main()
{
    Test test;
    std::function<void(int, int)> my_funciton =
         [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );
    f2(1, 2);
    return 0;
}

The problem is that my schedule() requires std::function as argument. For instance, the following call leads to a compilation error:

    auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};
    auto f2 = test.schedule( my_funciton );

Body:
The issue is that a std::function is a polymorphic wrapper around a callable object. Lambdas are not std::functions. Just like string literals are not std::strings. In your first example, you do this:

std::function<void(int, int)> my_funciton =
     [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};

You're constructing a std::function from the lambda. The schedule function is able to deduce the signature of the function without problems.

In your second example, you do this:

auto my_funciton = [](int a, int b) {std::cout << "got " << a << " and " << b << "\n";};

Then you get an error because std::function<void (Args...)> can't be matched against the lambda. The solution to this is to allow schedule to accept any callable object, not just std::function.

template <typename Func>
auto schedule(Func proc) {
  return [this, proc](auto... args) {
    run_in_worker_thread([=]() {
      proc(args...);
    });
  };
}


问:
use grep or awk to split a column into multiple columns with the headers in the original file headers
I have the following output

```<code>SRR51XXXX
5
6
7
SRR51XXYY
8
9
1
2
</code>```

and so on..

SO each header file begins with SRR51 and then with unique 4 digit numbers.I want to turn this single column output into separate columns
such as

```<code>SRR513XXXX            SRR513XXXY
5                        8
6                        9
7                        1
</code>```

Fig to show the data

答:
awk version:

```<code>BEGIN {
    field = -1
    row = 0
    maxrow = 0;
}

/^SRR/ {
    row = 0
    field++
}

{
    if (!width[field] || width[field] < length($0)) {
        width[field] = length($0);
    }
    a[row++,field] = $0;
    if (row > maxrow) {
        maxrow = row
    }
}

END {
    for (j = 0; j <= field; j++) {
        printf " %-"width[j]"s ", a[0,j]
    }
    printf "\n";

    for (i = 1; i < maxrow; i++) {
        for (j = 0; j <= field; j++) {
            printf(" %"width[j]"s ", a[i,j])
        }
        printf "\n";
    }
}
</code>```

To run, save into a file col.awk, and then run awk -f col.awk sample.txt

Note: headers are left aligned, numbers are right aligned.

Online demo - https://ideone.com/H6hUcq

Body:
I have the following output

SRR51XXXX
5
6
7
SRR51XXYY
8
9
1
2

and so on..

SO each header file begins with SRR51 and then with unique 4 digit numbers.I want to turn this single column output into separate columns
such as

SRR513XXXX            SRR513XXXY
5                        8
6                        9
7                        1

Fig to show the data

Body:
awk version:

BEGIN {
    field = -1
    row = 0
    maxrow = 0;
}

/^SRR/ {
    row = 0
    field++
}

{
    if (!width[field] || width[field] < length($0)) {
        width[field] = length($0);
    }
    a[row++,field] = $0;
    if (row > maxrow) {
        maxrow = row
    }
}

END {
    for (j = 0; j <= field; j++) {
        printf " %-"width[j]"s ", a[0,j]
    }
    printf "\n";

    for (i = 1; i < maxrow; i++) {
        for (j = 0; j <= field; j++) {
            printf(" %"width[j]"s ", a[i,j])
        }
        printf "\n";
    }
}

To run, save into a file col.awk, and then run awk -f col.awk sample.txt

Note: headers are left aligned, numbers are right aligned.

Online demo - https://ideone.com/H6hUcq


问:
PDO will not execute, but works just fine in phpmyadmin
I have the following code:

```<code><?php
// ... other code...
$prepared_statement = <<< MYSQL
SELECT `Organization`, `City`, `Region`, `Country`, `Contact`, `Manager`, `Description`
FROM `businesses`
WHERE (
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Manager` LIKE ? OR `Description` LIKE ?)
  AND
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Source` LIKE ? OR `Description` LIKE ?)
)
ORDER BY `Timestamp`;
MYSQL;
$value_list = ["Missouri","Missouri","Missouri","Missouri","Missouri","Missouri","US","US","US","US","US","US"]; // Populated through some passed in parameters, simplified to a known result here for simplicity sake.
try {
  $query = $this_pdo -> prepare();
  $query->execute($value_list); // <-- This line is where it breaks, but doesn't trigger the catch and doesn't output any error. Doing it in phpmyadmin returns 1 result.
  $result = $query->fetchAll(PDO::FETCH_ASSOC);
  return $result;
} catch (PDOException $e) {
  return ["A database problem has occurred: " . $e->getMessage()];
}
</code>```

I've tried running the query directly in the database, replacing the "?" marks with values in the array, and it works. But execute doesn't?

答:
Found my problem. Simple mistake... forgot to put my prepared statement into the prepare call.

* pdo->prepare() does not return an error if it is empty, despite it being empty fails subsequent execute calls.*

Body:
I have the following code:

<?php
// ... other code...
$prepared_statement = <<< MYSQL
SELECT `Organization`, `City`, `Region`, `Country`, `Contact`, `Manager`, `Description`
FROM `businesses`
WHERE (
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Manager` LIKE ? OR `Description` LIKE ?)
  AND
  (`Organization` LIKE ? OR `City` LIKE ? OR `Region` LIKE ? OR `Country` LIKE ? OR `Source` LIKE ? OR `Description` LIKE ?)
)
ORDER BY `Timestamp`;
MYSQL;
$value_list = ["Missouri","Missouri","Missouri","Missouri","Missouri","Missouri","US","US","US","US","US","US"]; // Populated through some passed in parameters, simplified to a known result here for simplicity sake.
try {
  $query = $this_pdo -> prepare();
  $query->execute($value_list); // <-- This line is where it breaks, but doesn't trigger the catch and doesn't output any error. Doing it in phpmyadmin returns 1 result.
  $result = $query->fetchAll(PDO::FETCH_ASSOC);
  return $result;
} catch (PDOException $e) {
  return ["A database problem has occurred: " . $e->getMessage()];
}

I've tried running the query directly in the database, replacing the "?" marks with values in the array, and it works. But execute doesn't?


问:
How to convert text files in a folder into a CSV file
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

```<code>TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe
</code>```

And here is what I have so far, though I know that it doesn't work:

```<code>$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}
</code>```

The final product would look something like this:

```<code>       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe
</code>```

Full sample of VOID file:

```<code>BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END
</code>```

Sample AUTHORIZE file:

```<code>BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END
</code>```

Sample adjust file:

```<code>BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END
</code>```

答:
If I'm reading this correctly you have some files each has a single record of data delimited between the aptly positions words "BEGIN" & "END" You want each file to be translated into a single CSV file?

I think I've cooked up something worth while.  Though I'm sure it's not perfect.

```<code>$Select   = 'TYPE','DOB','DATE','TIME','TERMINAL','ORGTERM','EMPLOYEE'
ForEach( $InputFile in (Get-ChildItem $CurrentDirectory) )
{
    $OutputFile = $InputFile.BaseName + '.csv'
    $Table    = Get-Content $InputFile
    $TempHash = [Ordered]@{}

    ForEach( $Column in $Table )
    {
        If( $Column -notmatch '(^BEGIN$|^END$)' )
        {
            $TempArr = $Column.Split( ' ', 2, [System.StringSplitOptions]::RemoveEmptyEntries ) | ForEach{$_.Trim()}

            If( $Select -contains $TempArr[0] )
            {
                $TempHash.Add($TempArr[0], $TempArr[1] )
            }
        }
    }

    #Now $TempHash should have enough to create the object and export to CSV
    [PSCustomObject]$TempHash | Export-Csv -Path $OutputFile -NoTypeInformation
}
</code>```

A few points:

I'm ignoring the lines BEGIN & END

I'm manipulating each line thereafter into an array, which for the
most part should be 2 elements.

If the first element [0] is in the collection of fileds your looking
for I'll add as a key/value pair to the hash.  Otherwise do nothing.

After processing the lines Convert the object to a PSCustomObject and
export to a CSV file.

I only tested it on a single file I created from your question.  I wrapped up the outer loop just as pseudo code.

This works, but the output looks a little choppy, like numbers being strings and such.  That said, as a rev one I think we've got something to work with.

If misread your comment, and you want a single output CSV file the adjustment is just to declare the filename before the loop and use the append param on the Export-CSV cmdlet.  See below, though I didn't test it any further:

```<code>$OutputFile = 'YourOutput.csv'
$Select   = 'TYPE','DOB','DATE','TIME','TERMINAL','ORGTERM','EMPLOYEE'

ForEach( $InputFile in (Get-ChildItem $CurrentDirectory) )
{
    $Table    = Get-Content $InputFile
    $TempHash = [Ordered]@{}

    ForEach( $Column in $Table )
    {
        If( $Column -notmatch '(^BEGIN$|^END$)' )
        {
            $TempArr = $Column.Split( ' ', 2, [System.StringSplitOptions]::RemoveEmptyEntries ) | ForEach{$_.Trim()}

            If( $Select -contains $TempArr[0] )
            {
                $TempHash.Add($TempArr[0], $TempArr[1] )
            }
        }
    }

    #Now $TempHash should have enough to create the object and export to CSV
    [PSCustomObject]$TempHash | Export-Csv -Path $OutputFile -NoTypeInformation -Append

}
</code>```

Sorry about the variable names, that could obviously use a refactor...

Let me know what you think.

Body:
I am trying to write a script to take a bunch of text files in a folder (which are all in the same format) and output them to a csv file. Each file has the same "header" information. I have been able to get information in a more easily usable format (removing the first and last lines, which aren't needed), but am having some trouble after that.

Here is the beginning of the text file, though there will be more than just these 7 lines, there will be a total of 36 lines per file:

TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 John Doe

And here is what I have so far, though I know that it doesn't work:

$currentdir = '.\'
$results = @()
$outputfilename = 'data.csv'

foreach ($req in Get-ChildItem($currentdir)) {

(Get-Content $req)[1..((Get-Content $req).count - 2)] |
    ForEach-Object {
        $header = $_[0] -split '`t'
        $data = $_[1] -split '`t'
        $results = $header, $data
    }
}

The final product would look something like this:

       A               B            C            D          E            F             G
1     TYPE            DOB          DATE         TIME     TERMINAL     ORGTERM       EMPLOYEE
2     VOID          20200131     20200131     21:19:42      3            2          1234 John Doe
3     AUTHORIZE     20200131     20200131     23:29:22      2                       4678 Jane Doe

Full sample of VOID file:

BEGIN
TYPE       VOID
DOB        20200131
DATE       20200131
TIME       21:19:42
TERMINAL   3
ORGTERM    2
EMPLOYEE   1234 Jane Doe
TABLE      TBL 101
CHECK      20030
PAYMENT    20029
AUTHAMT    20.68
BATCHAMT   20.68
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0423
REF        482
STANDALONE YES
PINDEX     1
APPROVEAMT 20.68
LOGTIME    21:07:01
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
ACTIONCODE 000
LASTSEND   1580585993
ORIGDATE   20200131
ORIGTIME   21:02:11
ORIGTYPE   AUTHORIZE
ORIGREF    482
ORGREFTIME 21:02:11
TENDER_NUM 12
CRCY       840
VPD        Sequence #: 107
REVID      2
REVNAME    712 Bar
END

Sample AUTHORIZE file:

BEGIN
TYPE       AUTHORIZE
DOB        20200131
DATE       20200131
TIME       23:29:22
TERMINAL   2
EMPLOYEE   1234 Jane Doe
TABLE      Table 121
CHECK      20045
PAYMENT    20038
AUTHAMT    72.42
BATCHAMT   72.42
CARDTYPE   VISA
CARDMASK   XXXXXXXXXXXXXXXX
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0124
REF        485900
STANDALONE YES
PINDEX     1
LOGTIME    23:29:22
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580586235
TENDER_NUM 13
CRCY       840
REVID      1
REVNAME    712 Restaurant
COMMERROR  TRUE
END

Sample adjust file:

BEGIN
TYPE       ADJUST
DOB        20200131
DATE       20200131
TIME       22:18:27
TERMINAL   8
ORGTERM    8
EMPLOYEE   789 Judy Garland
TABLE      BAR GUEST
CHECK      80161
PAYMENT    80036
BATCHAMT   30.43
BATCHTIP   6
CARDTYPE   MASTERCARD
CARDMASK   XXXXXXXXXXXX8699
{XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX}
EXP        0323
REF        1504602
STANDALONE YES
PINDEX     1
LOGTIME    22:18:27
FOHFEATS   10000000000000000000000000000000
TERMCAPS   00000000000000000000000000000000
FOHVERSION 15.1.34.2.97
LASTSEND   1580638928
TENDER_NUM 12
CRCY       840
REVID      4
REVNAME    712 Second Bar
END

Body:
If I'm reading this correctly you have some files each has a single record of data delimited between the aptly positions words "BEGIN" & "END" You want each file to be translated into a single CSV file?

I think I've cooked up something worth while.  Though I'm sure it's not perfect.

$Select   = 'TYPE','DOB','DATE','TIME','TERMINAL','ORGTERM','EMPLOYEE'
ForEach( $InputFile in (Get-ChildItem $CurrentDirectory) )
{
    $OutputFile = $InputFile.BaseName + '.csv'
    $Table    = Get-Content $InputFile
    $TempHash = [Ordered]@{}

    ForEach( $Column in $Table )
    {
        If( $Column -notmatch '(^BEGIN$|^END$)' )
        {
            $TempArr = $Column.Split( ' ', 2, [System.StringSplitOptions]::RemoveEmptyEntries ) | ForEach{$_.Trim()}

            If( $Select -contains $TempArr[0] )
            {
                $TempHash.Add($TempArr[0], $TempArr[1] )
            }
        }
    }

    #Now $TempHash should have enough to create the object and export to CSV
    [PSCustomObject]$TempHash | Export-Csv -Path $OutputFile -NoTypeInformation
}

A few points:

I'm ignoring the lines BEGIN & END

I'm manipulating each line thereafter into an array, which for the
most part should be 2 elements.

If the first element [0] is in the collection of fileds your looking
for I'll add as a key/value pair to the hash.  Otherwise do nothing.

After processing the lines Convert the object to a PSCustomObject and
export to a CSV file.

I only tested it on a single file I created from your question.  I wrapped up the outer loop just as pseudo code.

This works, but the output looks a little choppy, like numbers being strings and such.  That said, as a rev one I think we've got something to work with.

If misread your comment, and you want a single output CSV file the adjustment is just to declare the filename before the loop and use the append param on the Export-CSV cmdlet.  See below, though I didn't test it any further:

$OutputFile = 'YourOutput.csv'
$Select   = 'TYPE','DOB','DATE','TIME','TERMINAL','ORGTERM','EMPLOYEE'

ForEach( $InputFile in (Get-ChildItem $CurrentDirectory) )
{
    $Table    = Get-Content $InputFile
    $TempHash = [Ordered]@{}

    ForEach( $Column in $Table )
    {
        If( $Column -notmatch '(^BEGIN$|^END$)' )
        {
            $TempArr = $Column.Split( ' ', 2, [System.StringSplitOptions]::RemoveEmptyEntries ) | ForEach{$_.Trim()}

            If( $Select -contains $TempArr[0] )
            {
                $TempHash.Add($TempArr[0], $TempArr[1] )
            }
        }
    }

    #Now $TempHash should have enough to create the object and export to CSV
    [PSCustomObject]$TempHash | Export-Csv -Path $OutputFile -NoTypeInformation -Append

}

Sorry about the variable names, that could obviously use a refactor...

Let me know what you think.


问:
Flutter- FutureBuilder-Not getting AsyncSnapshot data
I am trying to get single string data from firestore database using Future and after getting used that data inside FutureBuilder. But getting null value in snapshot data. Provided the complete code below. Tell me where I am making mistake.

I can print the data in fetchPost() function. After getting the data from firestore it gets into FutureBuilder ,

but the snapshot data is null- AsyncSnapshot<String>(ConnectionState.done, null, null)

```<code>import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future <String>fetchPost() async  {
  final DocumentReference documentReference = Firestore.instance.document("myData/dummy");
   documentReference.get().then((datasnapshot){
    if(datasnapshot.exists){
        print("get data" +datasnapshot.data['url']); ///this printing data //in console
        return datasnapshot.data['url'];

    }
  }).catchError((e){
    print("Error");
    print(e);
  });

}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<String> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: post,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
              print ("snapshot has data");
              print (snapshot); // this printing 'AsyncSnapshot<String>(ConnectionState.done, null, null)'
              print (snapshot.data);// this printing null
              if (snapshot.hasData) {

                return Text(snapshot.data);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}
</code>```

答:
I took a more detail approach using your example Widget build and showed how to display the progress messages.

```<code>    child: FutureBuilder<String>(
        future: post,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                        switch (snapshot.connectionState){
                          case ConnectionState.none:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'No Connection Message')
                                    )
                                )
                            );
                          case ConnectionState.active:
                          case ConnectionState.waiting:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'Loading_message..'
                                    )
                                )
                            );
                          case ConnectionState.done:
                            if (snapshot.data.isEmpty){
                              return Container(
                                  child: Center(
                                      child: Text(
                                          'No Data available'
                                      )
                                  )
                              );
                            } else {
                              return ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return ListTile(
                                      title: Text(snapshot.data[index].displayValue,
                                          softWrap: true),
                                      onTap: () {
                                        Navigator.push(context, new MaterialPageRoute(builder: (context) {
                                          return DetailItem(dataItem: snapshot.data[index]);
                                        }));
                                      },
                                    );
                                  }
                              );
                            }
                        }
                        return null;
                      }
</code>```

Enjoy!

Body:
I am trying to get single string data from firestore database using Future and after getting used that data inside FutureBuilder. But getting null value in snapshot data. Provided the complete code below. Tell me where I am making mistake.

I can print the data in fetchPost() function. After getting the data from firestore it gets into FutureBuilder ,

but the snapshot data is null- AsyncSnapshot<String>(ConnectionState.done, null, null)

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';

Future <String>fetchPost() async  {
  final DocumentReference documentReference = Firestore.instance.document("myData/dummy");
   documentReference.get().then((datasnapshot){
    if(datasnapshot.exists){
        print("get data" +datasnapshot.data['url']); ///this printing data //in console
        return datasnapshot.data['url'];

    }
  }).catchError((e){
    print("Error");
    print(e);
  });

}

void main() => runApp(MyApp(post: fetchPost()));

class MyApp extends StatelessWidget {
  final Future<String> post;

  MyApp({Key key, this.post}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Fetch Data Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: Scaffold(
        appBar: AppBar(
          title: Text('Fetch Data Example'),
        ),
        body: Center(
          child: FutureBuilder<String>(
            future: post,
            builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
              print ("snapshot has data");
              print (snapshot); // this printing 'AsyncSnapshot<String>(ConnectionState.done, null, null)'
              print (snapshot.data);// this printing null
              if (snapshot.hasData) {

                return Text(snapshot.data);
              } else if (snapshot.hasError) {
                return Text("${snapshot.error}");
              }

              // By default, show a loading spinner
              return CircularProgressIndicator();
            },
          ),
        ),
      ),
    );
  }
}

Body:
I took a more detail approach using your example Widget build and showed how to display the progress messages.

    child: FutureBuilder<String>(
        future: post,
        builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                        switch (snapshot.connectionState){
                          case ConnectionState.none:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'No Connection Message')
                                    )
                                )
                            );
                          case ConnectionState.active:
                          case ConnectionState.waiting:
                            return Container(
                                child: Center(
                                    child: Text(
                                        'Loading_message..'
                                    )
                                )
                            );
                          case ConnectionState.done:
                            if (snapshot.data.isEmpty){
                              return Container(
                                  child: Center(
                                      child: Text(
                                          'No Data available'
                                      )
                                  )
                              );
                            } else {
                              return ListView.builder(
                                  itemCount: snapshot.data.length,
                                  itemBuilder: (BuildContext context, int index) {
                                    return ListTile(
                                      title: Text(snapshot.data[index].displayValue,
                                          softWrap: true),
                                      onTap: () {
                                        Navigator.push(context, new MaterialPageRoute(builder: (context) {
                                          return DetailItem(dataItem: snapshot.data[index]);
                                        }));
                                      },
                                    );
                                  }
                              );
                            }
                        }
                        return null;
                      }

Enjoy!


问:
Can I hide Flutter app contents when the app is in Background?
I'm developing an app that works with sensitive information.

One of the requirements is that when a user puts the app in background the content that the app is currently displaying has to be hidden, so if another person navigate through the apps in background he can't see the last screen where the user was.

Any ideas on how to do that?

I tried to show an overlay when the app moves to AppLifecycleState.paused, but it doesn't work for me, the app prints a message if I want but it can't update the UI.

答:
Edit
Shameless plug: i did a library for doing just that as I also needed it:

https://pub.dev/packages/secure_application

Answear

Build is not called after paused, at least on Android.

For Android I used a flutter_windowmanager package (modified to still be able to build on IOS):

https://github.com/neckaros/flutter_windowmanager

When my app need securing I add the flag secure:

```<code>FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE)

</code>```

And my app is now a black screen in the app switcher.
You should still hide content your way for when the user get back to the app.

Otherwise you can go native:
https://medium.com/@mehmetf_71205/securing-flutter-apps-ada13e806a69

Body:
Edit
Shameless plug: i did a library for doing just that as I also needed it:

https://pub.dev/packages/secure_application

Answear

Build is not called after paused, at least on Android.

For Android I used a flutter_windowmanager package (modified to still be able to build on IOS):

https://github.com/neckaros/flutter_windowmanager

When my app need securing I add the flag secure:

FlutterWindowManager.addFlags(FlutterWindowManager.FLAG_SECURE)

And my app is now a black screen in the app switcher.
You should still hide content your way for when the user get back to the app.

Otherwise you can go native:
https://medium.com/@mehmetf_71205/securing-flutter-apps-ada13e806a69


问:
LLDB and the memory addresses of library functions
I have a "Hello World" program to which I've attached lldb. I'm trying to answer a few questions for myself about the results I get when I try to get the address of library functions:

```<code>(lldb) image lookup -n printf
1 match found in /usr/lib/system/libsystem_c.dylib:
        Address: libsystem_c.dylib[0x000000000003f550] (libsystem_c.dylib.__TEXT.__text + 253892)
        Summary: libsystem_c.dylib`printf
(lldb) image lookup -n scanf
1 match found in /usr/lib/system/libsystem_c.dylib:
        Address: libsystem_c.dylib[0x000000000003fc69] (libsystem_c.dylib.__TEXT.__text + 255709)
        Summary: libsystem_c.dylib`scanf
(lldb) expr &printf
(int (*)(const char *__restrict, ...)) $2 = 0x00007fff6f8c5550 (libsystem_c.dylib`printf)
(lldb) expr &scanf
error: unsupported expression with unknown type
</code>```

I have three questions here:

What kind of address is 0x00007fff6f8c5550? I assume it is the function pointer to printf. Is this a virtual address that exists only in the mapped space of the current process? If yes, why does another program return the same address for printf?

Assuming it's some global shared address that is the same for every process, would modifying the contents of the data at this address (which I haven't been able to do yet) create a copy of the modified memory page and will the address change? (i'm on Mac OS and I assume one process cannot change shared memory for another process)

Why does expr &scanf not work, but expr &printf does?

答:
What kind of address is 0x00007fff6f8c5550? I assume it is the function pointer to printf.

Yes, that's correct.

Is this a virtual address that exists only
  in the mapped space of the current process?

Well, yes and no. It is a virtual address specific to your process and you should not assume it's valid in another process. But:

If yes, why does another
  program return the same address for printf?

As an optimization, macOS uses a shared mapping for a lot of the system libraries. They are loaded once at boot and used by all processes. For a given boot, the address is constant across all such processes. However, the address is randomized each boot for security.

Assuming it's some global shared address that is the same for every process, would modifying the contents of the data at this address
  (which I haven't been able to do yet) create a copy of the modified
  memory page and will the address change?

Well, it is mapped copy-on-write. So, modifying it would create a copy. However, that wouldn't change its address. The OS would simply modify the mapping so that the memory around that address is private to your process.

(i'm on Mac OS and I assume
  one process cannot change shared memory for another process)

Well, processes can cooperate to have writable shared memory. But, in general, you're correct that security precautions prevent unwanted modifications to a process's memory.

Why does expr &scanf not work, but expr &printf does?

Your program (presumably) doesn't use scanf, so there's no debugging information regarding it. The main thing lldb is missing is the type of scanf. If you use a cast expression, it can work:

```<code>(lldb) p scanf
error: 'scanf' has unknown type; cast it to its declared type to use it
(lldb) p &scanf
error: unsupported expression with unknown type
(lldb) p (int(*)(const char * __restrict, ...))scanf
(int (*)(const char *__restrict, ...)) $3 = 0x00007fffd7e958d4 (libsystem_c.dylib`scanf)
</code>```

Conversely, it works for printf because your program does use it.

Body:
I have a "Hello World" program to which I've attached lldb. I'm trying to answer a few questions for myself about the results I get when I try to get the address of library functions:

(lldb) image lookup -n printf
1 match found in /usr/lib/system/libsystem_c.dylib:
        Address: libsystem_c.dylib[0x000000000003f550] (libsystem_c.dylib.__TEXT.__text + 253892)
        Summary: libsystem_c.dylib`printf
(lldb) image lookup -n scanf
1 match found in /usr/lib/system/libsystem_c.dylib:
        Address: libsystem_c.dylib[0x000000000003fc69] (libsystem_c.dylib.__TEXT.__text + 255709)
        Summary: libsystem_c.dylib`scanf
(lldb) expr &printf
(int (*)(const char *__restrict, ...)) $2 = 0x00007fff6f8c5550 (libsystem_c.dylib`printf)
(lldb) expr &scanf
error: unsupported expression with unknown type

I have three questions here:

What kind of address is 0x00007fff6f8c5550? I assume it is the function pointer to printf. Is this a virtual address that exists only in the mapped space of the current process? If yes, why does another program return the same address for printf?

Assuming it's some global shared address that is the same for every process, would modifying the contents of the data at this address (which I haven't been able to do yet) create a copy of the modified memory page and will the address change? (i'm on Mac OS and I assume one process cannot change shared memory for another process)

Why does expr &scanf not work, but expr &printf does?

Body:
What kind of address is 0x00007fff6f8c5550? I assume it is the function pointer to printf.

Yes, that's correct.

Is this a virtual address that exists only
  in the mapped space of the current process?

Well, yes and no. It is a virtual address specific to your process and you should not assume it's valid in another process. But:

If yes, why does another
  program return the same address for printf?

As an optimization, macOS uses a shared mapping for a lot of the system libraries. They are loaded once at boot and used by all processes. For a given boot, the address is constant across all such processes. However, the address is randomized each boot for security.

Assuming it's some global shared address that is the same for every process, would modifying the contents of the data at this address
  (which I haven't been able to do yet) create a copy of the modified
  memory page and will the address change?

Well, it is mapped copy-on-write. So, modifying it would create a copy. However, that wouldn't change its address. The OS would simply modify the mapping so that the memory around that address is private to your process.

(i'm on Mac OS and I assume
  one process cannot change shared memory for another process)

Well, processes can cooperate to have writable shared memory. But, in general, you're correct that security precautions prevent unwanted modifications to a process's memory.

Why does expr &scanf not work, but expr &printf does?

Your program (presumably) doesn't use scanf, so there's no debugging information regarding it. The main thing lldb is missing is the type of scanf. If you use a cast expression, it can work:

(lldb) p scanf
error: 'scanf' has unknown type; cast it to its declared type to use it
(lldb) p &scanf
error: unsupported expression with unknown type
(lldb) p (int(*)(const char * __restrict, ...))scanf
(int (*)(const char *__restrict, ...)) $3 = 0x00007fffd7e958d4 (libsystem_c.dylib`scanf)

Conversely, it works for printf because your program does use it.


问:
Kubernetes Persistent Volume Claims creates a new Persistent Volume instead of binding to the available Persistent Volume
I am running mac OSX Catalina using the docker application with the Kubernetes option turned on. I create a PersistentVolume with the following yaml and command.

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  capacity:
    storage: 10Gi
  persistentVolumeReclaimPolicy: Retain
  nfs:
    server: 192.168.1.250
    path: "/volume1/docker"
</code>```

kubectl apply -f pv.yml

This create and PersistentVolume with name pv-nfs-data. Next I then create a PersistentVolumeClaim with the following yaml and command

```<code>apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 10Gi
</code>```

kubectl apply -f pvc.yml

This create a PersistentVolumeClaim with the name pvc-nfs-data however it doen't bind it to the available PersistentVolume (pv-nfs-data). Instead it creates an new one and binds it to that. How do I make the PersistentVolumeClaim bind to the available PersistentVolume

答:
The Docker for Mac default storage class is the dynamic provisioning type, like you would get on AKS/GKE, where it allocates the physical storage as well.

```<code>→ kubectl get StorageClass
NAME                 PROVISIONER          AGE
hostpath (default)   docker.io/hostpath   191d
</code>```

For a PVC to use an existing PV, you can disable the storage class and specify in the PV which PVC can use it with a claimRef.

Claim Ref

The PV includes a claimRef for the PVC you will create

```<code>apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  capacity:
    storage: 10Gi
  claimRef:
    namespace: insert-your-namespace-here
    name: pv-nfs-data-claim
  persistentVolumeReclaimPolicy: Retain
  nfs:
    server: 192.168.1.250
    path: "/volume1/docker"
</code>```

The PVC sets storageClassName to ''

```<code>kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pv-nfs-data-claim
  namespace: insert-your-namespace-here
spec:
  storageClassName: ''
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
</code>```

Dynamic

You can go the dynamic route with NFS by adding an NFS dynamic provisioner,   create a storage class for it and let kubernetes work the rest out. More recent version of Kubernetes (1.13+) can use the CSI NFS driver

Body:
I am running mac OSX Catalina using the docker application with the Kubernetes option turned on. I create a PersistentVolume with the following yaml and command.

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  capacity:
    storage: 10Gi
  persistentVolumeReclaimPolicy: Retain
  nfs:
    server: 192.168.1.250
    path: "/volume1/docker"

kubectl apply -f pv.yml

This create and PersistentVolume with name pv-nfs-data. Next I then create a PersistentVolumeClaim with the following yaml and command

apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: pvc-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  resources:
    requests:
      storage: 10Gi

kubectl apply -f pvc.yml

This create a PersistentVolumeClaim with the name pvc-nfs-data however it doen't bind it to the available PersistentVolume (pv-nfs-data). Instead it creates an new one and binds it to that. How do I make the PersistentVolumeClaim bind to the available PersistentVolume

Body:
The Docker for Mac default storage class is the dynamic provisioning type, like you would get on AKS/GKE, where it allocates the physical storage as well.

→ kubectl get StorageClass
NAME                 PROVISIONER          AGE
hostpath (default)   docker.io/hostpath   191d

For a PVC to use an existing PV, you can disable the storage class and specify in the PV which PVC can use it with a claimRef.

Claim Ref

The PV includes a claimRef for the PVC you will create

apiVersion: v1
kind: PersistentVolume
metadata:
  name: pv-nfs-data
spec:
  accessModes:
    - ReadWriteMany
  capacity:
    storage: 10Gi
  claimRef:
    namespace: insert-your-namespace-here
    name: pv-nfs-data-claim
  persistentVolumeReclaimPolicy: Retain
  nfs:
    server: 192.168.1.250
    path: "/volume1/docker"

The PVC sets storageClassName to ''

kind: PersistentVolumeClaim
apiVersion: v1
metadata:
  name: pv-nfs-data-claim
  namespace: insert-your-namespace-here
spec:
  storageClassName: ''
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi

Dynamic

You can go the dynamic route with NFS by adding an NFS dynamic provisioner,   create a storage class for it and let kubernetes work the rest out. More recent version of Kubernetes (1.13+) can use the CSI NFS driver


问:
How to fix Unity Rigidbody.AddForce problem?
I'm making a bounce pad (jump pad if you like it like that). I wanted do make it bounce you OnTriggerEnter, which i have done using Rigidbody.AddForce.

And my problem is that it once bounces you higher, once lower, and sometimes does not bounce at all, you just fall on it.

Here's my code :

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BouncerBouncing : MonoBehaviour
{
    public float bounceForce;

    public Rigidbody playerRigidbody;

    void OnTriggerEnter(Collider collider)
    {
        if(collider.gameObject.tag == "Player")
        {
            playerRigidbody.AddForce(0, bounceForce, 0, ForceMode.Impulse);
        }
    }
}
</code>```

Thanks for your help!

答:
Applying an inpulse of force won't cancel any contrary motion. For example, if you're falling down and your Y velocity is -10, applying an impulse with a velocity of 10 upwards will give you a total of 0. If you want to replace your Y velocity, you can directly set the velocity instead of applying force.

```<code>playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, bounceForce, playerRigidbody.velocity.z);
</code>```

This line simply replaces the Y velocity with the jump force while keeping the X and Z values as they were. This way, the bounce height will remain constant.

Body:
I'm making a bounce pad (jump pad if you like it like that). I wanted do make it bounce you OnTriggerEnter, which i have done using Rigidbody.AddForce.

And my problem is that it once bounces you higher, once lower, and sometimes does not bounce at all, you just fall on it.

Here's my code :

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BouncerBouncing : MonoBehaviour
{
    public float bounceForce;

    public Rigidbody playerRigidbody;

    void OnTriggerEnter(Collider collider)
    {
        if(collider.gameObject.tag == "Player")
        {
            playerRigidbody.AddForce(0, bounceForce, 0, ForceMode.Impulse);
        }
    }
}

Thanks for your help!

Body:
Applying an inpulse of force won't cancel any contrary motion. For example, if you're falling down and your Y velocity is -10, applying an impulse with a velocity of 10 upwards will give you a total of 0. If you want to replace your Y velocity, you can directly set the velocity instead of applying force.

playerRigidbody.velocity = new Vector3(playerRigidbody.velocity.x, bounceForce, playerRigidbody.velocity.z);

This line simply replaces the Y velocity with the jump force while keeping the X and Z values as they were. This way, the bounce height will remain constant.


问:
A few questions about CodeSmith
I have recently started studying CodeSmith and I have a few questions.
I would like to make a template with 4 blocks.
Each block will be selected by the user.

How can I set the text block
(function) to selecting user?

How can I move blocks in separate
files?

For example there is a template

```<code>using System;

public class Hello3
{
   public static void Main(string[] args)
   {
    Blocl 1
    Blocl 2
    Blocl 3
    Blocl 4
   }
}
</code>```

Each of these blocks should be selected by the user. Each block is stored in a separate file.
Each block is a function. The output of one block enters to the input of another block.

P.S. Sorry for my bad english.

答:
I don't know how to do it using CodeSmith, but you would be better off using a "building-blocks" approach. AtomWeaver offers a way to build a code generator by smaller parts, called "Atoms". These Atoms are Templates that you can combine together.

In you case, I would build an Atom Template called cs_class:

The Template's Exec Code would be:

```<code>code([[
using System;

public class Hello3
{
   public static void Main(string[] args)
   {
     {{code_blocks}}
   }
}
]])
</code>```

Notice the {{code_blocks}} marker. Another Template will put some code there.

Then, create the cs_code_block Atom Template. Use this code:

For the Admin Section:

```<code>under("cs_class")
</code>```

For the Exec Section:

```<code>cursor("code_blocks")
code([[
  <put user code here>
]])
</code>```

The under() command helps you build an interactive modeling environment in AtomWeaver. Now, your user can create a model with one cs_class Atom, and then he can add as many cs_code_block Atoms as he wish. Executing the model will generate the desired code.

AtomWeaver lets you evolve your models and code generators. It's easy to start with a few lines and then grow it to obtain complete generators.

I know this is a very, very simplistic example of what you can build with AtomWeaver, but it's just to give you a quick idea of what you can accomplish.

ContentLicense: CC BY-SA 3.0

Title: A few questions about CodeSmith

Body:
I have recently started studying CodeSmith and I have a few questions.
I would like to make a template with 4 blocks.
Each block will be selected by the user.

How can I set the text block
(function) to selecting user?

How can I move blocks in separate
files?

For example there is a template

using System;

public class Hello3
{
   public static void Main(string[] args)
   {
    Blocl 1
    Blocl 2
    Blocl 3
    Blocl 4
   }
}

Each of these blocks should be selected by the user. Each block is stored in a separate file.
Each block is a function. The output of one block enters to the input of another block.

P.S. Sorry for my bad english.

Body:
I don't know how to do it using CodeSmith, but you would be better off using a "building-blocks" approach. AtomWeaver offers a way to build a code generator by smaller parts, called "Atoms". These Atoms are Templates that you can combine together.

In you case, I would build an Atom Template called cs_class:

The Template's Exec Code would be:

code([[
using System;

public class Hello3
{
   public static void Main(string[] args)
   {
     {{code_blocks}}
   }
}
]])

Notice the {{code_blocks}} marker. Another Template will put some code there.

Then, create the cs_code_block Atom Template. Use this code:

For the Admin Section:

under("cs_class")

For the Exec Section:

cursor("code_blocks")
code([[
  <put user code here>
]])

The under() command helps you build an interactive modeling environment in AtomWeaver. Now, your user can create a model with one cs_class Atom, and then he can add as many cs_code_block Atoms as he wish. Executing the model will generate the desired code.

AtomWeaver lets you evolve your models and code generators. It's easy to start with a few lines and then grow it to obtain complete generators.

I know this is a very, very simplistic example of what you can build with AtomWeaver, but it's just to give you a quick idea of what you can accomplish.


问:
How to iterate through a range of given keys in a nested dictionary
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

```<code>starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.
</code>```

答:
The issue with your code is that you were trying to access keys from strings.

```<code>data = {
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "TSLA",
        "3. Last Refreshed": "2020-02-14",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-02-14": {
            "1. open": "787.2200",
            "2. high": "812.9700",
            "3. low": "785.5000",
            "4. close": "800.0300",
            "5. volume": "15631446"
        },
        "2020-02-13": {
            "1. open": "741.8400",
            "2. high": "818.0000",
            "3. low": "735.0000",
            "4. close": "804.0000",
            "5. volume": "26289348"
        },
        "2020-02-12": {
            "1. open": "777.8700",
            "2. high": "789.7500",
            "3. low": "763.3700",
            "4. close": "767.2900",
            "5. volume": "12022470"
        }
    }
}

starting_date  = '2020-02-12'
ending_date = '2020-02-14'

opening_prices = []
closing_prices = []
for date in data['Time Series (Daily)']:
    if (date == starting_date):
        opening_prices.append(float(data['Time Series (Daily)'][date]['1. open']))
    if (date == ending_date):
        closing_prices.append(float(data['Time Series (Daily)'][date]['4. close']))

print(opening_prices)
print(closing_prices)
</code>```

Which yields:

```<code>[777.87]
[800.03]
</code>```

All dates between

```<code>between_dates = []
from datetime import date
s_date_split = starting_date.split('-')
e_date_split = ending_date.split('-')
dstart = date(int(s_date_split[0]), int(s_date_split[1]), int(s_date_split[2]))
dend = date(int(e_date_split[0]), int(e_date_split[1]), int(e_date_split[2]))

for _date in data['Time Series (Daily)']:
    curr_date_split = _date.split('-')
    d_curr = date(int(curr_date_split[0]), int(curr_date_split[1]), int(curr_date_split[2]))
    if dstart < d_curr < dend:
        between_dates.append(float(data['Time Series (Daily)'][_date]['4. close']))

print(between_dates)
</code>```

Which yields:

```<code>[804.0]
</code>```

Body:
I am iterating through a nested dictionary of stock prices that has the key: dates.

I am having trouble in being able to only get the prices of stocks at start date and end date.

This is a link to the nested dictionary.
https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=TSLA&apikey=IMS80WN3J6S2ILKW

I've been trying a lot of different ways but not able to solve it for past 2 hrs:

starting_date  = '2020-02-13'
ending_date = '2020-02-11'

#data = the nested dictionary

opening_prices = []
series = data['Time Series (Daily)'] #Now were given the nested dictionary of the keys being dates and value being a dictionary of info: price.
for date in series:
    if date == starting_date:
        for data, price in date.items()
            opening_prices.append(float(price['1. open']))
#we are retrieving the opening prices of the nested dict.
#For this attempt, I get the error of date being str type.
#I still don't know how to stop at the end_date as I tried a while loop, but it failed.

Body:
The issue with your code is that you were trying to access keys from strings.

data = {
    "Meta Data": {
        "1. Information": "Daily Prices (open, high, low, close) and Volumes",
        "2. Symbol": "TSLA",
        "3. Last Refreshed": "2020-02-14",
        "4. Output Size": "Compact",
        "5. Time Zone": "US/Eastern"
    },
    "Time Series (Daily)": {
        "2020-02-14": {
            "1. open": "787.2200",
            "2. high": "812.9700",
            "3. low": "785.5000",
            "4. close": "800.0300",
            "5. volume": "15631446"
        },
        "2020-02-13": {
            "1. open": "741.8400",
            "2. high": "818.0000",
            "3. low": "735.0000",
            "4. close": "804.0000",
            "5. volume": "26289348"
        },
        "2020-02-12": {
            "1. open": "777.8700",
            "2. high": "789.7500",
            "3. low": "763.3700",
            "4. close": "767.2900",
            "5. volume": "12022470"
        }
    }
}

starting_date  = '2020-02-12'
ending_date = '2020-02-14'

opening_prices = []
closing_prices = []
for date in data['Time Series (Daily)']:
    if (date == starting_date):
        opening_prices.append(float(data['Time Series (Daily)'][date]['1. open']))
    if (date == ending_date):
        closing_prices.append(float(data['Time Series (Daily)'][date]['4. close']))

print(opening_prices)
print(closing_prices)

Which yields:

[777.87]
[800.03]

All dates between

between_dates = []
from datetime import date
s_date_split = starting_date.split('-')
e_date_split = ending_date.split('-')
dstart = date(int(s_date_split[0]), int(s_date_split[1]), int(s_date_split[2]))
dend = date(int(e_date_split[0]), int(e_date_split[1]), int(e_date_split[2]))

for _date in data['Time Series (Daily)']:
    curr_date_split = _date.split('-')
    d_curr = date(int(curr_date_split[0]), int(curr_date_split[1]), int(curr_date_split[2]))
    if dstart < d_curr < dend:
        between_dates.append(float(data['Time Series (Daily)'][_date]['4. close']))

print(between_dates)

Which yields:

[804.0]


问:
Python3 + Pillow + QT5: Crash when I resize a label containing an image
I'm getting a message box: "Python has stopped working" when I load an image into a QLabel in a window that is already visible. Selecting debug shows: an unhandled Win32 exception occurred in Python.exe.

If I load the image into the label before showing the window, it displays correctly.

Here's the stripped down code:

```<code>#!/usr/bin/etc python
import sys
import os
import stat
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PIL import *
from PIL.ImageQt import *

def update(label):
    filename = r"C:\Users\me\Pictures\images\00000229.jpg"
    im1 = Image.open(filename)
    print ("Read ({},{})".format(im1.width, im1.height))
    im2 = im1.rotate(90, expand=True)
    print("Rotate ({},{})".format(im2.width, im2.height))

    im2.thumbnail((1200,1200))
    print("Thumbnail({},{})".format(im2.width, im2.height))

    qimage = ImageQt(im2)
    pixmap = QPixmap.fromImage(qimage)
    label.setPixmap(pixmap)

app = QApplication(sys.argv)

desktop = QDesktopWidget()
deskGeometry = desktop.availableGeometry()
print("desktop ({},{})".format(deskGeometry.width(), deskGeometry.height()))

window = QFrame()
# If you let QT pick the sizes itself, it picks dumb ones, then complains
# 'cause they are dumb
window.setMinimumSize(300, 200)
window.setMaximumSize(deskGeometry.width(), deskGeometry.height())

label = QLabel()
#call update here: no crash

caption = QLabel()
caption.setText("Hello world")

box = QVBoxLayout()
box.addWidget(label)
box.addWidget(caption)
#call update here, no crash
window.setLayout(box)
#call update here, no crash

window.show()
#this call to update results in a crash
update(label)

#window.updateGeometry()
print("App: exec")
app.exec_()
</code>```

Output:

```<code>desktop (3623,2160)
Read (1515,1051)
Rotate (1051,1515)
Thumbnail(832,1200)
App: exec
</code>```

Do I need to do anything special to tell QT that the window size will be changing?   Any suggestions for diagnosing the problem from here...

Update:

If I copy the body of the update function and paste it in place of the call to update, it no long crashes -- it works as expected.

From this I conclude that there is an object-lifetime issue.  Somewhere behind the scenes QT and/or Pillow is keeping a pointer to an internal buffer rather than making a copy or "stealing" the buffer.  When the object containing the buffer is deleted the pointer becomes invalid and "Bad Things Happen[TM]"

Now to determine who's being lazy...

答:
In case anybody else stumbles upon this:

I struggled with a very similar issue and was able to solve it using slots and signals (based on this great article) since the .copy() solution did not work for me. My solution was to separate the creation of the QPixmap and the QLabel.setPixmap into different functions. When the function that creates the QPixmap finishes, it emits a signal that triggers the function that sets the pixmap to the label.

For instance, if you wanted to use threading:

```<code>class WorkerSignals(QObject):
    ready = pyqtSignal()

class Worker(QRunnable):
    def __init__(self, some_function, *args, **kwargs):
        super(Worker, self).__init__()
        self.some_function = some_function
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        self.kwargs['ready'] = self.signals.ready

    @pyqtSlot()
    def run(self):
        self.some_function(*self.args, **self.kwargs)

def make_pixmap(qimage, ready, **kwargs):
    pixmap = QPixmap.fromImage(qimage) # qimage is some QImage
    ready.emit()

def set_pixmap(pixmap):
    label.setPixmap(pixmap) # 'label' is some QLabel

threadpool = QThreadPool

worker = Worker(make_pixmap, image)
worker.signals.ready.connect(set_pixmap)

threadpool.start(worker)
</code>```

Obviously using threading is not necessary in this scenario, but this is just to show that it's possible in case you want to process and show images without hanging the rest of the GUI.

Edit: The crashes came back, disregard the above. Working on another fix.

Body:
I'm getting a message box: "Python has stopped working" when I load an image into a QLabel in a window that is already visible. Selecting debug shows: an unhandled Win32 exception occurred in Python.exe.

If I load the image into the label before showing the window, it displays correctly.

Here's the stripped down code:

#!/usr/bin/etc python
import sys
import os
import stat
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PIL import *
from PIL.ImageQt import *

def update(label):
    filename = r"C:\Users\me\Pictures\images\00000229.jpg"
    im1 = Image.open(filename)
    print ("Read ({},{})".format(im1.width, im1.height))
    im2 = im1.rotate(90, expand=True)
    print("Rotate ({},{})".format(im2.width, im2.height))

    im2.thumbnail((1200,1200))
    print("Thumbnail({},{})".format(im2.width, im2.height))

    qimage = ImageQt(im2)
    pixmap = QPixmap.fromImage(qimage)
    label.setPixmap(pixmap)

app = QApplication(sys.argv)

desktop = QDesktopWidget()
deskGeometry = desktop.availableGeometry()
print("desktop ({},{})".format(deskGeometry.width(), deskGeometry.height()))

window = QFrame()
# If you let QT pick the sizes itself, it picks dumb ones, then complains
# 'cause they are dumb
window.setMinimumSize(300, 200)
window.setMaximumSize(deskGeometry.width(), deskGeometry.height())

label = QLabel()
#call update here: no crash

caption = QLabel()
caption.setText("Hello world")

box = QVBoxLayout()
box.addWidget(label)
box.addWidget(caption)
#call update here, no crash
window.setLayout(box)
#call update here, no crash

window.show()
#this call to update results in a crash
update(label)

#window.updateGeometry()
print("App: exec")
app.exec_()

Output:

desktop (3623,2160)
Read (1515,1051)
Rotate (1051,1515)
Thumbnail(832,1200)
App: exec

Do I need to do anything special to tell QT that the window size will be changing?   Any suggestions for diagnosing the problem from here...

Update:

If I copy the body of the update function and paste it in place of the call to update, it no long crashes -- it works as expected.

From this I conclude that there is an object-lifetime issue.  Somewhere behind the scenes QT and/or Pillow is keeping a pointer to an internal buffer rather than making a copy or "stealing" the buffer.  When the object containing the buffer is deleted the pointer becomes invalid and "Bad Things Happen[TM]"

Now to determine who's being lazy...

Body:
In case anybody else stumbles upon this:

I struggled with a very similar issue and was able to solve it using slots and signals (based on this great article) since the .copy() solution did not work for me. My solution was to separate the creation of the QPixmap and the QLabel.setPixmap into different functions. When the function that creates the QPixmap finishes, it emits a signal that triggers the function that sets the pixmap to the label.

For instance, if you wanted to use threading:

class WorkerSignals(QObject):
    ready = pyqtSignal()

class Worker(QRunnable):
    def __init__(self, some_function, *args, **kwargs):
        super(Worker, self).__init__()
        self.some_function = some_function
        self.args = args
        self.kwargs = kwargs
        self.signals = WorkerSignals()

        self.kwargs['ready'] = self.signals.ready

    @pyqtSlot()
    def run(self):
        self.some_function(*self.args, **self.kwargs)

def make_pixmap(qimage, ready, **kwargs):
    pixmap = QPixmap.fromImage(qimage) # qimage is some QImage
    ready.emit()

def set_pixmap(pixmap):
    label.setPixmap(pixmap) # 'label' is some QLabel

threadpool = QThreadPool

worker = Worker(make_pixmap, image)
worker.signals.ready.connect(set_pixmap)

threadpool.start(worker)

Obviously using threading is not necessary in this scenario, but this is just to show that it's possible in case you want to process and show images without hanging the rest of the GUI.

Edit: The crashes came back, disregard the above. Working on another fix.


问:
How to put a Google Cloud Run service behind Cloud CDN?
I want to put a CDN in front of a Google Cloud Run service in order to cache some responses.

Right now it seems Cloud CDN requires a Google Load Balancer, and they cannot point to a Google Cloud Run service (https://github.com/ahmetb/cloud-run-faq/tree/e7a0fc43d3054456613c09e073db289ddf76dd33#how-can-i-configure-cdn-for-cloud-run-services).

Is there another way?

答:
[updated]

You can use Cloud CDN with Cloud Run via Google Cloud Load Balancer


问:
Getting at C binary data from OCaml
(Ignoring endianness for the sake of argument - this is just a test case/proof of concept - and I would never use strcpy in real code either!)

Consider the following trivial C code:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* variables of type message_t will be stored contiguously in memory */
typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));
  m->message_id = 1;
  strcpy(m->message_text,"the rain in spain falls mainly on the plain");

  /* write the memory to disk */
  FILE* fp = fopen("data.dat", "wb");
  fwrite((void*)m, sizeof(int) + strlen(m->message_text) + 1, 1, fp);
  fclose(fp);

  exit(EXIT_SUCCESS);
}
</code>```

The file it writes can easily be read back in from disk:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));

  FILE* fp = fopen("data.dat", "rb");
  fread((void*)m, sizeof(message_t), 1, fp);
  fclose(fp);

  /* block of memory has structure "overlaid" onto it */
  printf("message_id=%d, message_text='%s'\n", m->message_id, m->message_text);

  exit(EXIT_SUCCESS);
}
</code>```

E.g.

```<code>$ ./write
$ ./read
message_id=1, message_text='the rain in spain falls mainly on the plain'
</code>```

My question is, in OCaml, if all I have is:

```<code>type message_t = {message_id:int; message_text:string}
</code>```

How would I get at that data? Marshal can't do it, nor can input_binary_int. I can call out to helper functions in C like "what is sizeof(int)" then get n bytes and call a C function to "convert these bytes into an int" for example but in this case I can't add any new C code, the "unpacking" has to be done in OCaml, based on what I know it "should" be. Is it just a matter of iterating over the string either in blocks of sizeofs or looking for '\0' or is there a clever way? Thanks!

答:
Before you can figure out how to code this in Ocaml, you need to figure out what your data representation is. Your C code isn't consistent between the reader and the writer: the writer only writes strlen(m->message_text)+1 bytes for the string, whereas the reader expects the full maximum 80 bytes.

My advice is to do all your marshalling in the same language, either C or Ocaml. I recommend Ocaml's marshalling library, which is already working, cross-platform and easy to use.

If you need interoperability between C and Ocaml marshalling code, then you need to sit down a marshalling format, and implement that same specification in both languages. Before you do that, consider if you can use a text representation, which will be less error-prone and easier to inspect and manipulate with third-party tools, but bulkier. JSON is a lightweight data representation format, or you can turn to the heavyweight XML. If all your data is truly as simple as an integer and a string, and the strings don't contain newlines, you can write the integer in decimal followed by a space (or a : or a ,) followed by the string followed by a newline.

If the C marshalling format is predefined and you can't change it, note that it's platform-dependent (depends on the architecture and the C compiler), and Ocaml doesn't give you access to such platform details. So your best bet is to link your Ocaml program with a C helper, making sure that your helper uses the same C type representation (sizeof(int), endianness, structure padding) as the original application.

Title: Getting at C binary data from OCaml

Body:
(Ignoring endianness for the sake of argument - this is just a test case/proof of concept - and I would never use strcpy in real code either!)

Consider the following trivial C code:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* variables of type message_t will be stored contiguously in memory */
typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));
  m->message_id = 1;
  strcpy(m->message_text,"the rain in spain falls mainly on the plain");

  /* write the memory to disk */
  FILE* fp = fopen("data.dat", "wb");
  fwrite((void*)m, sizeof(int) + strlen(m->message_text) + 1, 1, fp);
  fclose(fp);

  exit(EXIT_SUCCESS);
}

The file it writes can easily be read back in from disk:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  int message_id;
  char message_text[80];
} message_t;

int main(int argc, char**argv) {
  message_t* m = (message_t*)malloc(sizeof(message_t));

  FILE* fp = fopen("data.dat", "rb");
  fread((void*)m, sizeof(message_t), 1, fp);
  fclose(fp);

  /* block of memory has structure "overlaid" onto it */
  printf("message_id=%d, message_text='%s'\n", m->message_id, m->message_text);

  exit(EXIT_SUCCESS);
}

E.g.

$ ./write
$ ./read
message_id=1, message_text='the rain in spain falls mainly on the plain'

My question is, in OCaml, if all I have is:

type message_t = {message_id:int; message_text:string}

How would I get at that data? Marshal can't do it, nor can input_binary_int. I can call out to helper functions in C like "what is sizeof(int)" then get n bytes and call a C function to "convert these bytes into an int" for example but in this case I can't add any new C code, the "unpacking" has to be done in OCaml, based on what I know it "should" be. Is it just a matter of iterating over the string either in blocks of sizeofs or looking for '\0' or is there a clever way? Thanks!


问:
More efficient way to mean center a sub-set of columns in a pandas dataframe and retain column names
I have a dataframe that has about 370 columns. I'm testing a series of hypothesis that require me to use subsets of the model to fit a cubic regression model. I'm planning on using statsmodels to model this data.

Part of the process for polynomial regression involves mean centering variables (subtracting the mean from every case for a particular feature).

I can do this with 3 lines of code but it seems inefficient, given that I need to replicate this process for half a dozen hypothesis. Keep in mind that I need to data at the coefficient level from the statsmodel output so I need to retain the column names.

Here's a peek at the data.
It's the sub-set of columns I need for one of my hypothesis tests.

```<code>      i  we  you  shehe  they  ipron
0  0.51   0    0   0.26  0.00   1.02
1  1.24   0    0   0.00  0.00   1.66
2  0.00   0    0   0.00  0.72   1.45
3  0.00   0    0   0.00  0.00   0.53
</code>```

Here is the code that mean centers and keeps the column names.

```<code>from sklearn import preprocessing
#create df of features for hypothesis, from full dataframe
h2 = df[['i', 'we', 'you', 'shehe', 'they', 'ipron']]

#center the variables
x_centered = preprocessing.scale(h2, with_mean='True', with_std='False')

#convert back into a Pandas dataframe and add column names
x_centered_df = pd.DataFrame(x_centered, columns=h2.columns)
</code>```

Any recommendations on how to make this more efficient / faster would be awesome!

答:
I know this question is a little old, but by now Scikit is the fastest solution. Plus, you can condense the code in one line:

```<code>pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)

%timeit pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)
684 µs ± 30.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

test.subtract(df.mean())

%timeit df.subtract(df.mean())
1.63 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
</code>```

df I used for testing:

```<code>df = pd.DataFrame(np.random.randint(low=1, high=10, size=(20,5)),columns = list('abcde'))
</code>```

Body:
I have a dataframe that has about 370 columns. I'm testing a series of hypothesis that require me to use subsets of the model to fit a cubic regression model. I'm planning on using statsmodels to model this data.

Part of the process for polynomial regression involves mean centering variables (subtracting the mean from every case for a particular feature).

I can do this with 3 lines of code but it seems inefficient, given that I need to replicate this process for half a dozen hypothesis. Keep in mind that I need to data at the coefficient level from the statsmodel output so I need to retain the column names.

Here's a peek at the data.
It's the sub-set of columns I need for one of my hypothesis tests.

      i  we  you  shehe  they  ipron
0  0.51   0    0   0.26  0.00   1.02
1  1.24   0    0   0.00  0.00   1.66
2  0.00   0    0   0.00  0.72   1.45
3  0.00   0    0   0.00  0.00   0.53

Here is the code that mean centers and keeps the column names.

from sklearn import preprocessing
#create df of features for hypothesis, from full dataframe
h2 = df[['i', 'we', 'you', 'shehe', 'they', 'ipron']]

#center the variables
x_centered = preprocessing.scale(h2, with_mean='True', with_std='False')

#convert back into a Pandas dataframe and add column names
x_centered_df = pd.DataFrame(x_centered, columns=h2.columns)

Any recommendations on how to make this more efficient / faster would be awesome!

Body:
I know this question is a little old, but by now Scikit is the fastest solution. Plus, you can condense the code in one line:

pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)

%timeit pd.DataFrame(preprocessing.scale(df, with_mean=True, with_std=False),columns = df.columns)
684 µs ± 30.7 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

test.subtract(df.mean())

%timeit df.subtract(df.mean())
1.63 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

df I used for testing:

df = pd.DataFrame(np.random.randint(low=1, high=10, size=(20,5)),columns = list('abcde'))


问:
Accept inputs from the user until 5 unique inputs
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

```<code>while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)
</code>```

答:
Right now your stumbling block might be in this comparison:

```<code>if mySet == 5:
</code>```

That line, as written, asks if the variable mySet, which may contain zero, one, two, or many more different elements, is equal to the integer 5.  But mySet isn't an integer itself--it is a set object--so it will probably never be equal to 5.

If we want to know if there are exactly five unique elements in the set, we can use Python's built-in len keyword, which gives the length of a collection (for example, the length of a set, but also possibly the length of a list or a tuple.)

```<code>>mySet = set([1,1,2,3,4,5,5,5])
>print(mySet)
set([1,2,3,4,5])
>len(mySet)
5
</code>```

Something else to think about, though, is that you overwrite mySet every time you iterate your while loop.  This line mySet = set(input("Enter a number:")) will overwrite the value of mySet with each new user input.  With your current "Enter a number:" prompt, the user may only enter one value at a time.  Maybe the user will never enter exactly five unique numbers!  In this case you may want to prompt the user differently ("Enter five unique numbers: ") or look at options on how to add or remove elements from a set.

Body:
How would I do this using a while function. Do we have to use a set somewhere for this?

This is what I have so far

while True:
    mySet = set(input("Enter a number:"))
    if mySet == 5:
        break
    print(mySet)

Body:
Right now your stumbling block might be in this comparison:

if mySet == 5:

That line, as written, asks if the variable mySet, which may contain zero, one, two, or many more different elements, is equal to the integer 5.  But mySet isn't an integer itself--it is a set object--so it will probably never be equal to 5.

If we want to know if there are exactly five unique elements in the set, we can use Python's built-in len keyword, which gives the length of a collection (for example, the length of a set, but also possibly the length of a list or a tuple.)

>mySet = set([1,1,2,3,4,5,5,5])
>print(mySet)
set([1,2,3,4,5])
>len(mySet)
5

Something else to think about, though, is that you overwrite mySet every time you iterate your while loop.  This line mySet = set(input("Enter a number:")) will overwrite the value of mySet with each new user input.  With your current "Enter a number:" prompt, the user may only enter one value at a time.  Maybe the user will never enter exactly five unique numbers!  In this case you may want to prompt the user differently ("Enter five unique numbers: ") or look at options on how to add or remove elements from a set.


问:
Liquibase Snowflake integration - specifically: generateChangeLog
When invoking:mvn liquibase:generateChangeLog I get this error:

```<code>*Object 'DATAWAREHOUSE_DB_DEV.INFORMATION_SCHEMA.CONSTRAINTS' does not exist or not authorized.*
</code>```

Has anyone found a workaround for this issue? It seems Snowflake has a view DATAWAREHOUSE_DB_DEV.INFORMATION_SCHEMA.TABLE_CONSTRAINTS but Snowflake does not support synonyms and you can't create any new views in the INFORMATION_SCHEMA (to match what liquibase is looking for).

答:
This seems to me like a Liquibase version issue or something similar.

If you do need a workaround, can you create a view in a different schema that would work with your solution?

Akin to this:

```<code>create view public.constraints(constraint_catalog, constraint_schema, constraint_name) as (
      -- Start at the top of the hierarchy ...
      select constraint_catalog, constraint_schema, constraint_name
        from information_schema.table_constraints
  );

select * from public.constraints;
</code>```

Body:
When invoking:mvn liquibase:generateChangeLog I get this error:

*Object 'DATAWAREHOUSE_DB_DEV.INFORMATION_SCHEMA.CONSTRAINTS' does not exist or not authorized.*

Has anyone found a workaround for this issue? It seems Snowflake has a view DATAWAREHOUSE_DB_DEV.INFORMATION_SCHEMA.TABLE_CONSTRAINTS but Snowflake does not support synonyms and you can't create any new views in the INFORMATION_SCHEMA (to match what liquibase is looking for).

Body:
This seems to me like a Liquibase version issue or something similar.

If you do need a workaround, can you create a view in a different schema that would work with your solution?

Akin to this:

create view public.constraints(constraint_catalog, constraint_schema, constraint_name) as (
      -- Start at the top of the hierarchy ...
      select constraint_catalog, constraint_schema, constraint_name
        from information_schema.table_constraints
  );

select * from public.constraints;


问:
NuGet Package Dependency Auto Upgrade
I have a private NuGet package that I'm installing on an existing project.  The project already contains several of the dependencies the private NuGet package requires but at a lower version than what the private package requires.  When I try to install the private package the installation throws an error (no error number)

Package restore failed. Rolling back package changes for
  'ConsoleApp1'.

In the package manager output it is reporting a

Detected package downgrade

Since the package that it's referencing is a public package on NuGet.org I would expect at a minimum to be prompted to upgrade the dependency during the installation process instead of erroring and rolling back.  I've know packages that are not already included in the project are being installed automatically and can see that in the logs.

I've seen other posting that range from ignoring the warning/error to a pre-build script that does the upgrade (which is not a option for installing new packages)

Can the package manager be instructed to automatically upgrade the existing packages to at least the minimum version the dependency list has defined?

答:
Afraid not.

It's not really a trivial problem to solve - suppose it uses the approach you suggested and your project currently references packageA v1.0.0 and packageB v1.0.0.

You add a new package with a dependency on package A v2.0.0.

It prompts you to upgrade packageAfrom 1.0.0 to 2.0.0 to avoid a downgrade.
But package A 2.0.0 has a new dependency on packageBat 2.0.0, which causes a downgrade for you on that package.

Every new upgrade in turn can trigger new upgrades. You can also engineer scenarios where there isn't even a way to upgrade other packages to make it all work. On top of that all of this requires fetching lots of information from your package source.

Since there's not a clear, general way to fix this the tooling leaves you to work out what you want to do yourself.

Title: NuGet Package Dependency Auto Upgrade


问:
Replace special characters from clipboard before pasting
I use a little js function which permits to paste the content of the clipboard in a textarea. see below.
the datas I paste are from excel, and are delimited with special characters \r\n
My need is to replace this special characters with a comma "," directly before the paste
Is there an easy way to do it ? thanks per advance

 function Coller() {
  navigator.clipboard.readText().then(clipText =>
  document.getElementById("textarea").innerText = clipText);
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="Coller()">Coller</button>

<textarea id="textarea" rows="10" cols="40"></textarea></code>```

答:
You can solve this problem with the String.prototype.replace() functions. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

you can use it like this:

```<code>function Coller() {
    navigator.clipboard.readText().then(clipText =>
    document.getElementById("textarea").innerText = clipText.replace(/["]/gm, '').replace(/[\r\n]+/gm, ','));
}
</code>```

In this case \r(created on Mac), \n(created on Linux) and \r\n (created on Windows) will be replaced.

g stands for global, so every special character in your string will be replaced

m stand for multi line, so even though your text has several lines, all special characters will be replaced

Body:
I use a little js function which permits to paste the content of the clipboard in a textarea. see below.
the datas I paste are from excel, and are delimited with special characters \r\n
My need is to replace this special characters with a comma "," directly before the paste
Is there an easy way to do it ? thanks per advance

 function Coller() {
  navigator.clipboard.readText().then(clipText =>
  document.getElementById("textarea").innerText = clipText);
 }

<button onclick="Coller()">Coller</button>

<textarea id="textarea" rows="10" cols="40"></textarea>

Body:
You can solve this problem with the String.prototype.replace() functions. (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace)

you can use it like this:

function Coller() {
    navigator.clipboard.readText().then(clipText =>
    document.getElementById("textarea").innerText = clipText.replace(/["]/gm, '').replace(/[\r\n]+/gm, ','));
}

In this case \r(created on Mac), \n(created on Linux) and \r\n (created on Windows) will be replaced.

g stands for global, so every special character in your string will be replaced

m stand for multi line, so even though your text has several lines, all special characters will be replaced