问:
How to download file with Indy. Error "iohandler value is not valid"
I had this function that worked for HTTP. Now, with the wide spread of HTTPS it didn't work anymore. I was getting an "IOHandler value is not valid" error.

So, I created an SSLIOHandler object as shown below, but now I get a new error:

Exception class EIdOSSLUnderlyingCryptoError with message 'Error connecting with SSL. error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version'

How do I setup the SSLIOHandler object properly?

```<code>{ Only suitable for small files because the whole download will be saved to RAM before writing it to disk. }
function DownloadFile(CONST SourceURL, DestFileName: string; OUT ErrorMsg: String): Boolean;
VAR
  Indy: TIDHTTP;
  Stream: TFileStream;
  IDAntiFreeze: TIDAntiFreeze;
  IOHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  Indy:= TIDHTTP.Create(NIL);
  IOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create(NIL);
  IDAntiFreeze:= TIDAntiFreeze.Create(NIL);
  Stream:= TFileStream.Create(DestFileName, fmCreate);
  TRY
    IOHandler.Destination := SourceURL;
    IOHandler.Host := SourceURL;
    IOHandler.MaxLineAction := maException;
    //IOHandler.Port := 587;
    //IOHandler.DefaultPort := 0;
    //IOHandler.OnStatusInfo := SSLIOHandlerStatusInfo;

    Indy.ConnectTimeout          := 0;                   { Indy default value: zero }
    Indy.ReadTimeout             := -1;                  { Indy default value: -1 }
    Indy.HandleRedirects         := TRUE;                { http://stackoverflow.com/questions/4549809/indy-idhttp-how-to-handle-page-redirects }
    Indy.AllowCookies            := FALSE;
    Indy.Request.UserAgent       := 'Mozilla/4.0';
    Indy.Request.Connection      := 'Keep-Alive';
    Indy.Request.ProxyConnection := 'Keep-Alive';
    Indy.Request.CacheControl    := 'no-cache';
    Indy.IOHandler:= IOHandler;

    // Indy.OnWork:= HttpWork;

    TRY
      Indy.Get(SourceURL, Stream);
      Result:= TRUE;
    EXCEPT
      On E: Exception DO
        begin
          Result:= FALSE;
          ErrorMsg := E.Message + ' (' + IntToStr(Indy.ResponseCode) + ')';
        end;
    END;
  FINALLY
    FreeAndNil(Stream);
    FreeAndNil(IDAntiFreeze);
    FreeAndNil(IOHandler);
    FreeAndNil(Indy);
  END;
end;
</code>```

PS: The libeay32.dll and ssleay32.dll are present in the app's folder.

答:
You are not configuring the TIdSSLIOHandlerSocketOpenSSL's TLS settings in any way.  By default, it enables only TLS 1.0 (known issue: https://github.com/IndySockets/Indy/issues/181), but chances are that the website in question requires TLS 1.1+ instead.

Try adding this:

IOHandler.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];
```

Also, just on a side note, you DO NOT need to configure the IOHandler's Destination, Host, or Port properties at all.  TIdHTTP will handle that internally for you.

Body:
I had this function that worked for HTTP. Now, with the wide spread of HTTPS it didn't work anymore. I was getting an "IOHandler value is not valid" error.

So, I created an SSLIOHandler object as shown below, but now I get a new error:

Exception class EIdOSSLUnderlyingCryptoError with message 'Error connecting with SSL. error:1409442E:SSL routines:ssl3_read_bytes:tlsv1 alert protocol version'

How do I setup the SSLIOHandler object properly?

{ Only suitable for small files because the whole download will be saved to RAM before writing it to disk. }
function DownloadFile(CONST SourceURL, DestFileName: string; OUT ErrorMsg: String): Boolean;
VAR
  Indy: TIDHTTP;
  Stream: TFileStream;
  IDAntiFreeze: TIDAntiFreeze;
  IOHandler: TIdSSLIOHandlerSocketOpenSSL;
begin
  Indy:= TIDHTTP.Create(NIL);
  IOHandler:= TIdSSLIOHandlerSocketOpenSSL.Create(NIL);
  IDAntiFreeze:= TIDAntiFreeze.Create(NIL);
  Stream:= TFileStream.Create(DestFileName, fmCreate);
  TRY
    IOHandler.Destination := SourceURL;
    IOHandler.Host := SourceURL;
    IOHandler.MaxLineAction := maException;
    //IOHandler.Port := 587;
    //IOHandler.DefaultPort := 0;
    //IOHandler.OnStatusInfo := SSLIOHandlerStatusInfo;

    Indy.ConnectTimeout          := 0;                   { Indy default value: zero }
    Indy.ReadTimeout             := -1;                  { Indy default value: -1 }
    Indy.HandleRedirects         := TRUE;                { http://stackoverflow.com/questions/4549809/indy-idhttp-how-to-handle-page-redirects }
    Indy.AllowCookies            := FALSE;
    Indy.Request.UserAgent       := 'Mozilla/4.0';
    Indy.Request.Connection      := 'Keep-Alive';
    Indy.Request.ProxyConnection := 'Keep-Alive';
    Indy.Request.CacheControl    := 'no-cache';
    Indy.IOHandler:= IOHandler;

    // Indy.OnWork:= HttpWork;

    TRY
      Indy.Get(SourceURL, Stream);
      Result:= TRUE;
    EXCEPT
      On E: Exception DO
        begin
          Result:= FALSE;
          ErrorMsg := E.Message + ' (' + IntToStr(Indy.ResponseCode) + ')';
        end;
    END;
  FINALLY
    FreeAndNil(Stream);
    FreeAndNil(IDAntiFreeze);
    FreeAndNil(IOHandler);
    FreeAndNil(Indy);
  END;
end;

PS: The libeay32.dll and ssleay32.dll are present in the app's folder.

Body:
You are not configuring the TIdSSLIOHandlerSocketOpenSSL's TLS settings in any way.  By default, it enables only TLS 1.0 (known issue: https://github.com/IndySockets/Indy/issues/181), but chances are that the website in question requires TLS 1.1+ instead.

Try adding this:

IOHandler.SSLOptions.SSLVersions := [sslvTLSv1, sslvTLSv1_1, sslvTLSv1_2];

Also, just on a side note, you DO NOT need to configure the IOHandler's Destination, Host, or Port properties at all.  TIdHTTP will handle that internally for you.


来源: stackexchange

问:
SageMaker ValidationException : Value '[]' at 'subnetIds' failed to satisfy constraint

1 validation error detected
Value '[]' at 'subnetIds' failed to satisfy constraint: Member must have length greater than or equal to 1

I want to make Sagemaker studio Domain in Ohio region, but I got ↑ error.
I also confirmed that vpc existed (no default) and one subnet existed.

How can I fix the error? Please share your knowledge.

答: On the setup SageMaker Domain screen, if you've been trying with the "Quick Setup" instead try using the "Standard Setup". That got me past this issue.</p>

ContentLicense: CC BY-SA 4.0


问:
Laravel Project on local Xampp mysql error : file_put_contents: Failed to open stream: Permission denied
I have developed a laravel project on one laptop using local xampp mysql and want to install it on another laptop. I am having this error: file_put_contents(/Applications/XAMPP/xamppfiles/htdocs/sfms/storage/framework/sessions/VS0cObLn8ItoKMt5HQJOlZ0srelpMLsSwm5ZQcPa): Failed to open stream: Permission:
I have tried the following but they did not work:

php artisan cache:clear

php artisan config:clear

manually deleted vendor\laravel\framework\src\Illuminate\Foundation\Console\ConfigClearCommand.php
among others.
Please, I need your assistance. Thanks in advance.

答:
I run the following code in the terminal and it worked for me:

chmod -R 777 storage


问:
Why are Angular directives considered classes and not functions?
The way the Ng directives are used within HTML tags (view) makes them look like functions to be invoked upon rather than instances of a class. Or maybe they are static methods that can be invoked without a class instance.
Sorry I am coming from backend, OOP languages (C++, Python, Java, C#) and now working to learn Javascript and Typescript and sometimes the philosophy of web-dev is a different paradigm to me.</p>

答: Angular Directives are classes that are decorated with the @Directive decorator. Angular is as well a very Object Oriented Framework which suites devs coming from other OOP languages.


问:
How does this code work? The result doesnt make sense to me and doesnt appear in the debugger
```<code>    #include <iostream>

using namespace std;

int f(int n, int m){
    if (n==1)
        return 0;
    else
        return f(n-1, m) + m;
}

int main()
{

cout << f(3874, 1000);
cout << endl;
    return 0;
}
</code>```

The result is 3873000. Why is n multiplied by m after deducting 1 and how does the function work in detail please?

答:
The else block is executed at all levels of recursion, except the deepest one.

The number of levels in the recursion tree is n. So we have n-1 times that the else block is executed.

This else block first makes the recursive call, and then adds m to the result it gets back, and returns that sum to the caller, who will do the same, ...etc until the walk upwards the recursion tree is complete.

The original caller will thus see a base number (0) to which m was repeatedly added, exactly n-1 times.

So the function calculates m(n-1), provided that n is greater than 0. If not, the recursion will run into a stack overflow error.

Visualisation

To visualise this, let's split the second return statement into two parts, where first the result of the recursive call is stored in a variable, and then the sum is returned. Also, let's take a small value for n, like 3.

So this is then the code:

```<code>int f(int n, int m){
    if (n==1)
        return 0;
    else {
        int result = f(n-1, m)
        return result + m;
    }
}

int main()
{
    cout << f(3, 10);
}
</code>```

We can imagine each function execution (starting with main) as a box (a frame), in which local variables live their lives. Each recursive call creates a new box, and when return is executed that box vanishes again.

So we can imagine the above code to execute like this:

```<code>+-[main]----------------------------+
|  f(3, 10) ...                     |
|  +-[f]-------------------------+  |
|  |  n = 3, m = 10              |  |
|  |  f(3-1, 10) ...             |  |
|  |  +-[f]-------------------+  |  |
|  |  |  n = 2, m = 10        |  |  |
|  |  |  f(2-1, 10) ...       |  |  |
|  |  |  +-[f]-------------+  |  |  |
|  |  |  |  n = 1, m = 10  |  |  |  |
|  |  |  |  return 0       |  |  |  |
|  |  |  +-----------------+  |  |  |
|  |  |  result = 0           |  |  |
|  |  |  return 0 + 10        |  |  |
|  |  +-----------------------+  |  |
|  |  result = 10                |  |
|  |  return 10 + 10             |  |
|  +-----------------------------+  |
|  cout << 20                       |
+-----------------------------------+
</code>```

I hope this clarifies it.

Body:
    #include <iostream>

using namespace std;

int f(int n, int m){
    if (n==1)
        return 0;
    else
        return f(n-1, m) + m;
}

int main()
{

cout << f(3874, 1000);
cout << endl;
    return 0;
}

The result is 3873000. Why is n multiplied by m after deducting 1 and how does the function work in detail please?

Body:
The else block is executed at all levels of recursion, except the deepest one.

The number of levels in the recursion tree is n. So we have n-1 times that the else block is executed.

This else block first makes the recursive call, and then adds m to the result it gets back, and returns that sum to the caller, who will do the same, ...etc until the walk upwards the recursion tree is complete.

The original caller will thus see a base number (0) to which m was repeatedly added, exactly n-1 times.

So the function calculates m(n-1), provided that n is greater than 0. If not, the recursion will run into a stack overflow error.

Visualisation

To visualise this, let's split the second return statement into two parts, where first the result of the recursive call is stored in a variable, and then the sum is returned. Also, let's take a small value for n, like 3.

So this is then the code:

int f(int n, int m){
    if (n==1)
        return 0;
    else {
        int result = f(n-1, m)
        return result + m;
    }
}

int main()
{
    cout << f(3, 10);
}

We can imagine each function execution (starting with main) as a box (a frame), in which local variables live their lives. Each recursive call creates a new box, and when return is executed that box vanishes again.

So we can imagine the above code to execute like this:

+-[main]----------------------------+
|  f(3, 10) ...                     |
|  +-[f]-------------------------+  |
|  |  n = 3, m = 10              |  |
|  |  f(3-1, 10) ...             |  |
|  |  +-[f]-------------------+  |  |
|  |  |  n = 2, m = 10        |  |  |
|  |  |  f(2-1, 10) ...       |  |  |
|  |  |  +-[f]-------------+  |  |  |
|  |  |  |  n = 1, m = 10  |  |  |  |
|  |  |  |  return 0       |  |  |  |
|  |  |  +-----------------+  |  |  |
|  |  |  result = 0           |  |  |
|  |  |  return 0 + 10        |  |  |
|  |  +-----------------------+  |  |
|  |  result = 10                |  |
|  |  return 10 + 10             |  |
|  +-----------------------------+  |
|  cout << 20                       |
+-----------------------------------+

I hope this clarifies it.


问:
SSIS challenges and small projects
I have done some searching on the web for challenges and small projects, that will be great to have for people who are learning SSIS(Sql Server Integration Services) but could not find any.

So,Anyone has a suggestions of sites that could have SSIS challenges, that can be helpful for people who are learning it?

Or you could also post challenges that you have that you would love to share

答:
here are a few links depending on you current ssis level

Creating a Simple ETL Package

Beyond basics of SSIS

Advanced_SSIS_Package_Design_Tutorial

ContentLicense: CC BY-SA 3.0

Title: SSIS challenges and small projects


问:
Async function with multiple fetch in an array - Best way to do that?
I'm learning JavaScript and async functions is not my strength.

I have an array of gameIds, and I have to fetch each individual id and get the data of all that games.

```<code>async function gameInfo() {
    gamesIds = [19,12,13,15,16];

    //what should be here?

    const response = await fetch(`http://localhost:8080/game/${individualGameId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        withCredentials: true,
        credentials: 'include',
        "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5c"
      },
    });

    const allGamesInfo = await response.json();
    console.log(allGamesInfo);
}
</code>```

Can someone help me with this ?

答:
The best idea for your problem is creating a Array of Promises and execute it with Promise.all

gamesIds = [19,12,13,15,16];

    const promises = gamesIds.map(id =>
      fetch(`http://localhost:8080/game/${id}`, {
        method: 'GET',
        headers: {
          'Content-Type': 'application/json',
          withCredentials: true,
          credentials: 'include',
          "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5c"
        },
    }))

    const response = await Promise.all(promises);```

Body:
I'm learning JavaScript and async functions is not my strength.

I have an array of gameIds, and I have to fetch each individual id and get the data of all that games.

async function gameInfo() {
    gamesIds = [19,12,13,15,16];

    //what should be here?

    const response = await fetch(`http://localhost:8080/game/${individualGameId}`, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        withCredentials: true,
        credentials: 'include',
        "authorization": "Bearer eyJhbGciOiJIUzI1NiIsInR5c"
      },
    });

    const allGamesInfo = await response.json();
    console.log(allGamesInfo);
}

Can someone help me with this ?


问:
I am stumped by a seemingly simple active_record association
I have 2 tables.  One contains genealogy data (families), the other contains people data.
I want to create an association so that I can access the people data based on pointers from the genealogy table.  For instance:

```<code>    <% @families.each do |family| %>
...
    <td> <%= family.father.first_name %></td>
</code>```

Here is the conroller code:

```<code>  def index
      @families = Family.joins(:people)
  end
</code>```

Here are the 2 schemas:

```<code>CREATE TABLE "people" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name_prefix" varchar, "first_name" varchar, "middle_name" varchar, "last_name" varchar, "name_suffix" varchar, "date_of_birth" varchar, "date_of_death" varchar, "gender" varchar, "notes" varchar, "sync_outlook" varchar, "sync_phone" varchar, "flags" varchar, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL, "place_of_birth" varchar, "aliases" varchar);

CREATE TABLE "families" ("id" integer NOT NULL PRIMARY KEY, "fam_notes" varchar DEFAULT NULL, "fam_fatherid" integer DEFAULT NULL, "fam_motherid" integer DEFAULT NULL, "fam_weddingdate" varchar DEFAULT NULL, "fam_weddingplace" varchar DEFAULT NULL, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL);
</code>```

Here is the model code:

```<code>class Family < ApplicationRecord
    has_many :childlinks, foreign_key: "child_family"
    has_many :people, through: :childlinks

    #has_one :father, through: :families, source: "fam_fatherid"
    has_one :father, foreign_key: "fam_fatherid"
    has_one :person, through: :father
end
</code>```

When I put a break in the web page, @families exists, but the associated father does not.

```<code>>> @families[0].father
NameError: uninitialized constant Family::Father
</code>```

I have tried every combination of has_one, through, foreign_key, source, etc. that I can think of, and nothing has produced a 'family' object with a linked (or associated) 'father' object.

What am I doing wrong?

答:
I'm going to assume here that we are just modeling biological assocations and not the whole can of worms that is the real world and I'm going to stick to the Rails conventions instead of unfuddling your schema.

If you want to put the mother/father combo as different columns on one table this is how you would do it:

```<code>class CreateFamilies < ActiveRecord::Migration[6.1]
  def change
    create_table :families do |t|
      t.belongs_to :father,
        null: false,
        foreign_key: { to_table: :persons }
      t.belongs_to :mother,
        null: false,
        foreign_key: { to_table: :persons }
      t.timestamps
    end
  end
end
</code>```
```<code>class Family < ApplicationRecord
  belongs_to :father,
    class_name: 'Person'
  belongs_to :mother,
    class_name: 'Person'
  has_many :children,
    class_name: 'Person',
    inverse_of: :family
end
</code>```
```<code>class Person < ApplicationRecord
  # @todo add a family_id foreign key column to persons
  # this is a persons link to their parents
  # Must be nullable to avoid a chicken-vs-egg scenario
  belongs_to :family,
    optional: true,
    inverse_of: :children
  has_one :father, through: :family
  has_one :mother, through: :family
end
</code>```

Note that you don't actually need a join table between children and the family as the relationshop is one to many and not many to many. Each child can only belong to one set of parents. You also need to use belongs_to when the foreign key is on this models table.

So far its pretty simple. However once you start adding relations to a persons children it gets crazy:

```<code>class Person < ApplicationRecord
  # this is a persons link to their parents
  # Must be nullable to avoid a chicken-vs-egg scenario
  belongs_to :family,
    optional: true,
    inverse_of: :children

  has_one :father, through: :family
  has_one :mother, through: :family

  has_many :maternal_families,
    class_name: 'Family',
    foreign_key: :mother_id

  has_many :maternal_children,
    through: :maternal_families,
    source: :children

  has_many :paternal_families,
    class_name: 'Family',
    foreign_key: :father_id

  has_many :paternal_children,
    through: :paternal_families,
    source: :children
end
</code>```

The reason you need so many assocations is that each has_many assocation must point to a single foreign key in ActiveRecord.

Body:
I have 2 tables.  One contains genealogy data (families), the other contains people data.
I want to create an association so that I can access the people data based on pointers from the genealogy table.  For instance:

    <% @families.each do |family| %>
...
     <%= family.father.first_name %>

Here is the conroller code:

  def index
      @families = Family.joins(:people)
  end

Here are the 2 schemas:

CREATE TABLE "people" ("id" integer PRIMARY KEY AUTOINCREMENT NOT NULL, "name_prefix" varchar, "first_name" varchar, "middle_name" varchar, "last_name" varchar, "name_suffix" varchar, "date_of_birth" varchar, "date_of_death" varchar, "gender" varchar, "notes" varchar, "sync_outlook" varchar, "sync_phone" varchar, "flags" varchar, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL, "place_of_birth" varchar, "aliases" varchar);

CREATE TABLE "families" ("id" integer NOT NULL PRIMARY KEY, "fam_notes" varchar DEFAULT NULL, "fam_fatherid" integer DEFAULT NULL, "fam_motherid" integer DEFAULT NULL, "fam_weddingdate" varchar DEFAULT NULL, "fam_weddingplace" varchar DEFAULT NULL, "created_at" datetime(6) NOT NULL, "updated_at" datetime(6) NOT NULL);

Here is the model code:

class Family < ApplicationRecord
    has_many :childlinks, foreign_key: "child_family"
    has_many :people, through: :childlinks

    #has_one :father, through: :families, source: "fam_fatherid"
    has_one :father, foreign_key: "fam_fatherid"
    has_one :person, through: :father
end

When I put a break in the web page, @families exists, but the associated father does not.

>> @families[0].father
NameError: uninitialized constant Family::Father

I have tried every combination of has_one, through, foreign_key, source, etc. that I can think of, and nothing has produced a 'family' object with a linked (or associated) 'father' object.

What am I doing wrong?

Body:
I'm going to assume here that we are just modeling biological assocations and not the whole can of worms that is the real world and I'm going to stick to the Rails conventions instead of unfuddling your schema.

If you want to put the mother/father combo as different columns on one table this is how you would do it:

class CreateFamilies < ActiveRecord::Migration[6.1]
  def change
    create_table :families do |t|
      t.belongs_to :father,
        null: false,
        foreign_key: { to_table: :persons }
      t.belongs_to :mother,
        null: false,
        foreign_key: { to_table: :persons }
      t.timestamps
    end
  end
end

class Family < ApplicationRecord
  belongs_to :father,
    class_name: 'Person'
  belongs_to :mother,
    class_name: 'Person'
  has_many :children,
    class_name: 'Person',
    inverse_of: :family
end

class Person < ApplicationRecord
  # @todo add a family_id foreign key column to persons
  # this is a persons link to their parents
  # Must be nullable to avoid a chicken-vs-egg scenario
  belongs_to :family,
    optional: true,
    inverse_of: :children
  has_one :father, through: :family
  has_one :mother, through: :family
end

Note that you don't actually need a join table between children and the family as the relationshop is one to many and not many to many. Each child can only belong to one set of parents. You also need to use belongs_to when the foreign key is on this models table.

So far its pretty simple. However once you start adding relations to a persons children it gets crazy:

class Person < ApplicationRecord
  # this is a persons link to their parents
  # Must be nullable to avoid a chicken-vs-egg scenario
  belongs_to :family,
    optional: true,
    inverse_of: :children

  has_one :father, through: :family
  has_one :mother, through: :family

  has_many :maternal_families,
    class_name: 'Family',
    foreign_key: :mother_id

  has_many :maternal_children,
    through: :maternal_families,
    source: :children

  has_many :paternal_families,
    class_name: 'Family',
    foreign_key: :father_id

  has_many :paternal_children,
    through: :paternal_families,
    source: :children
end

The reason you need so many assocations is that each has_many assocation must point to a single foreign key in ActiveRecord.


问:
Expected `async` block, found a different `async` block
I was trying to use futures::future::select_ok (playground):

use std::time::Duration;
use tokio; // 1.16.1
use futures; // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
}
```
<p>and encountered the error:</p>
```error[E0308]: mismatched types
  --> src/main.rs:19:47
   |
7  |       let first_future = async {
   |  ______________________________-
8  | |         tokio::time::sleep(Duration::from_secs(1)).await;
9  | |         Ok(3)
10 | |     };
   | |_____- the expected `async` block
...
19 |       futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
   |                                                 ^^^^^^^^^^^^^^^^^^^ expected opaque type, found enum `Result`
   |
   = note: expected opaque type `impl futures::Future<Output = [async output]>`
                     found enum `Result<_, ()>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error
```

I have no idea what I'm missing here, would really appreciate any help.

答:
Each of the async blocks are treated as a different type, the same way closures are (IIRC). All of them implements Future, so you may want to actually dynamically dispatch them. For that you need to wrap them in Pin<Box>:

use futures;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use tokio; // 1.16.1 // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    let futures: [Pin<Box<dyn Future<Output = Result<usize, ()>>>>; 3] = [
        Box::pin(first_future),
        Box::pin(second_future),
        Box::pin(third_future),
    ];
    futures::future::select_ok(futures).await;
}

```

Playground

Body:
I was trying to use futures::future::select_ok (playground):

use std::time::Duration;
use tokio; // 1.16.1
use futures; // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
}

and encountered the error:

error[E0308]: mismatched types
  --> src/main.rs:19:47
   |
7  |       let first_future = async {
   |  ______________________________-
8  | |         tokio::time::sleep(Duration::from_secs(1)).await;
9  | |         Ok(3)
10 | |     };
   | |_____- the expected `async` block
...
19 |       futures::future::select_ok(&[first_future,second_future.await,third_future]).await;
   |                                                 ^^^^^^^^^^^^^^^^^^^ expected opaque type, found enum `Result`
   |
   = note: expected opaque type `impl futures::Future<Output = [async output]>`
                     found enum `Result<_, ()>`

For more information about this error, try `rustc --explain E0308`.
error: could not compile `playground` due to previous error

I have no idea what I'm missing here, would really appreciate any help.

Body:
Each of the async blocks are treated as a different type, the same way closures are (IIRC). All of them implements Future, so you may want to actually dynamically dispatch them. For that you need to wrap them in Pin<Box>:

use futures;
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;
use tokio; // 1.16.1 // 0.3.19

#[tokio::main]
async fn main() {
    let first_future = async {
        tokio::time::sleep(Duration::from_secs(1)).await;
        Ok(3)
    };
    let second_future = async {
        tokio::time::sleep(Duration::from_millis(100)).await;
        Err(())
    };
    let third_future = async {
        tokio::time::sleep(Duration::from_secs(300)).await;
        Ok(3)
    };
    let futures: [Pin<Box<dyn Future<Output = Result<usize, ()>>>>; 3] = [
        Box::pin(first_future),
        Box::pin(second_future),
        Box::pin(third_future),
    ];
    futures::future::select_ok(futures).await;
}

Playground


问:
ASM Start Process hidden
I have a already compiled C++ console application wich is shown as a little black window.
Now i want to disassemble the app and add code to get the Process start hidden. Maybe you can help me finding the api call or if you can explain me how that works. The current Debuger I use is OllyDBG but I also have knowledge in IDA and WDASM32.

Thanks forward!

答:
There are two ways to do this. You can do a code injection to hide the window after it's created or you can change the subsystem that is defined in the PE header.

The PE header has a flag defining the subsystem the code was compiled against. This will currently be WINDOWS_CUI and you want to change it to WINDOWS_GUI.

To do the code injection, find a codecave, then patch a JMP at entry point (EP) to this codecave. In the codecave, write the instruction that was overwritten by the JMP then make a call to FreeConsole then JMP back to the instruction after the JMP you patched in at the EP earlier.

Let me give you an example. I compiled a C program in VC++:

```<code>#include <Windows.h>

int main() {
  Sleep(INFINITE);
  return 0;
}
</code>```

If we open up the result binary in OllyDbg, we get something like this:

Press the big M at the top to get the Memory Map:

Since our main module is Some_console_App then double click the PE header there which takes us to this:

Scroll down a bit to find the subsystem:

As you can see it's set to IMAGE_SUBSYSTEM_WINDOWS_CUI which is defined as 3. We want to set it to IMAGE_SUBSYSTEM_WINDOWS_GUI which is 2. Go back to the CPU window and in the hex dump, go to the address that the subsystem flag was set on. In this case it's 0x0136013C:

Select the byte you want to change, hit Ctrl-E and change the 3 to 2. Then right-click >> Copy to Executable File. In the File window that pops up, right-click and select Save File.

Tada! Done. Sorry for large resolutions of pictures.

Title: ASM Start Process hidden

Body:
There are two ways to do this. You can do a code injection to hide the window after it's created or you can change the subsystem that is defined in the PE header.

The PE header has a flag defining the subsystem the code was compiled against. This will currently be WINDOWS_CUI and you want to change it to WINDOWS_GUI.

To do the code injection, find a codecave, then patch a JMP at entry point (EP) to this codecave. In the codecave, write the instruction that was overwritten by the JMP then make a call to FreeConsole then JMP back to the instruction after the JMP you patched in at the EP earlier.

Let me give you an example. I compiled a C program in VC++:

#include <Windows.h>

int main() {
  Sleep(INFINITE);
  return 0;
}

If we open up the result binary in OllyDbg, we get something like this:

Press the big M at the top to get the Memory Map:

Since our main module is Some_console_App then double click the PE header there which takes us to this:

Scroll down a bit to find the subsystem:

As you can see it's set to IMAGE_SUBSYSTEM_WINDOWS_CUI which is defined as 3. We want to set it to IMAGE_SUBSYSTEM_WINDOWS_GUI which is 2. Go back to the CPU window and in the hex dump, go to the address that the subsystem flag was set on. In this case it's 0x0136013C:

Select the byte you want to change, hit Ctrl-E and change the 3 to 2. Then right-click >> Copy to Executable File. In the File window that pops up, right-click and select Save File.

Tada! Done. Sorry for large resolutions of pictures.


问:
Unable to start a Cloud Run container on M1 Macbook
I haven't installed Rosetta on my M1 Macbook. Have Docker and all deps installed and this even worked a few times but not sure what caused this error suddenly:

```<code>Starting to run the app using configuration 'Cloud Run: Run/Debug Locally' from .vscode/launch.json...
To view more detailed logs, go to Output channel : "Cloud Run: Run/Debug Locally - Detailed"
Dependency check started
Dependency check succeeded
Starting minikube, this may take a while.............
minikube successfully started
The minikube profile 'cloud-run-dev-internal' has been scheduled to stop automatically after exiting Cloud Code. To disable this on future deployments, set autoStop to false in your launch configuration /Users/myname/Code/myprojectAPI/.vscode/launch.json
Configuring minikube gcp-auth addon
Using GCP project 'myproject-com' with minikube gcp-auth

Update initiated
Build started for artifact myprojectapi
Build completed for artifact myprojectapi

Deploy started
Deploy completed

Status check started
Resource pod/myprojectapi-8695998b94-9lk7d status updated to In Progress
Resource pod/myprojectapi-8695998b94-9lk7d status updated to In Progress
Resource deployment/myprojectapi status failed with waiting for rollout to finish: 0 of 1 updated replicas are available...
Status check failed

The image was built but failed to start on the cluster. Because you are on an ARM64 machine, it is likely that you built an ARM64 image for an x86_64 cluster.
Update failed with error code STATUSCHECK_CONTAINER_TERMINATED
1/1 deployment(s) failed
Skaffold exited with code 1.
Cleaning up...
Finished clean up.
</code>```

Dockerfile:

```<code>FROM gcr.io/google.com/cloudsdktool/cloud-sdk:slim

RUN set -ex; \
  apt-get -y update; \
  curl -fsSL https://deb.nodesource.com/setup_17.x | bash -; \
  apt-get -y install nodejs; \
  apt-get -y install ghostscript; \
  apt-get -y install pngquant; \
  rm -rf /var/lib/apt/lists/*

# Create and change to the app directory.
WORKDIR /usr/src/app

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this separately prevents re-running npm install on every code change.
COPY package*.json ./

# Install dependencies.
# If you add a package-lock.json speed your build by switching to 'npm ci'.
RUN npm ci --only=production
# RUN npm install --production

# Copy local code to the container image.
COPY . ./

# Run the web service on container startup.
CMD [ "npm", "start" ]
</code>```

I'm doing 'Cloud Run Emulator' deploy in VS Code using the Cloud Code extension.

What am I doing wrong?

答:
I can confirm that the gcr.io/google.com/cloudsdktool/cloud-sdk:slim image used in your Dockerfile is an x86_64 image, which is incompatible with an ARM64-based M1 Mac. Since CloudSDK does not currently have any ARM64-based images, creating your own base image with CloudSDK will be necessary. The steps to do that are:

Update the line in your Dockerfile pointing to gcr.io/google.com/cloudsdktool/cloud-sdk:slim to a new base image (debian:buster-slim for example)

Install the CloudSDK tooling onto the image. It should look something like this in your Dockerfile:

```<code># Downloads the gCloud package
RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz

# Installs the package
RUN mkdir -p /usr/local/gcloud \
  && tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
  && /usr/local/gcloud/google-cloud-sdk/install.sh --quiet

# Adds the package path to local
ENV PATH $PATH:/usr/local/gcloud/google-cloud-sdk/bin
</code>```

Once those steps have run, you should be left with a new base image with CloudSDK installed! If you're curious about some of the context or additional configuration options, please take a look at the Docker documentation page about multi-arch support

Body:
I haven't installed Rosetta on my M1 Macbook. Have Docker and all deps installed and this even worked a few times but not sure what caused this error suddenly:

Starting to run the app using configuration 'Cloud Run: Run/Debug Locally' from .vscode/launch.json...
To view more detailed logs, go to Output channel : "Cloud Run: Run/Debug Locally - Detailed"
Dependency check started
Dependency check succeeded
Starting minikube, this may take a while.............
minikube successfully started
The minikube profile 'cloud-run-dev-internal' has been scheduled to stop automatically after exiting Cloud Code. To disable this on future deployments, set autoStop to false in your launch configuration /Users/myname/Code/myprojectAPI/.vscode/launch.json
Configuring minikube gcp-auth addon
Using GCP project 'myproject-com' with minikube gcp-auth

Update initiated
Build started for artifact myprojectapi
Build completed for artifact myprojectapi

Deploy started
Deploy completed

Status check started
Resource pod/myprojectapi-8695998b94-9lk7d status updated to In Progress
Resource pod/myprojectapi-8695998b94-9lk7d status updated to In Progress
Resource deployment/myprojectapi status failed with waiting for rollout to finish: 0 of 1 updated replicas are available...
Status check failed

The image was built but failed to start on the cluster. Because you are on an ARM64 machine, it is likely that you built an ARM64 image for an x86_64 cluster.
Update failed with error code STATUSCHECK_CONTAINER_TERMINATED
1/1 deployment(s) failed
Skaffold exited with code 1.
Cleaning up...
Finished clean up.

Dockerfile:

FROM gcr.io/google.com/cloudsdktool/cloud-sdk:slim

RUN set -ex; \
  apt-get -y update; \
  curl -fsSL https://deb.nodesource.com/setup_17.x | bash -; \
  apt-get -y install nodejs; \
  apt-get -y install ghostscript; \
  apt-get -y install pngquant; \
  rm -rf /var/lib/apt/lists/*

# Create and change to the app directory.
WORKDIR /usr/src/app

# Copy application dependency manifests to the container image.
# A wildcard is used to ensure both package.json AND package-lock.json are copied.
# Copying this separately prevents re-running npm install on every code change.
COPY package*.json ./

# Install dependencies.
# If you add a package-lock.json speed your build by switching to 'npm ci'.
RUN npm ci --only=production
# RUN npm install --production

# Copy local code to the container image.
COPY . ./

# Run the web service on container startup.
CMD [ "npm", "start" ]

I'm doing 'Cloud Run Emulator' deploy in VS Code using the Cloud Code extension.

What am I doing wrong?

Body:
I can confirm that the gcr.io/google.com/cloudsdktool/cloud-sdk:slim image used in your Dockerfile is an x86_64 image, which is incompatible with an ARM64-based M1 Mac. Since CloudSDK does not currently have any ARM64-based images, creating your own base image with CloudSDK will be necessary. The steps to do that are:

Update the line in your Dockerfile pointing to gcr.io/google.com/cloudsdktool/cloud-sdk:slim to a new base image (debian:buster-slim for example)

Install the CloudSDK tooling onto the image. It should look something like this in your Dockerfile:

# Downloads the gCloud package
RUN curl https://dl.google.com/dl/cloudsdk/release/google-cloud-sdk.tar.gz > /tmp/google-cloud-sdk.tar.gz

# Installs the package
RUN mkdir -p /usr/local/gcloud \
  && tar -C /usr/local/gcloud -xvf /tmp/google-cloud-sdk.tar.gz \
  && /usr/local/gcloud/google-cloud-sdk/install.sh --quiet

# Adds the package path to local
ENV PATH $PATH:/usr/local/gcloud/google-cloud-sdk/bin

Once those steps have run, you should be left with a new base image with CloudSDK installed! If you're curious about some of the context or additional configuration options, please take a look at the Docker documentation page about multi-arch support


问:
Clickhouse leadInFrame inside COALESCE return Unknown identifier
I'm following Altinity's examples on how to implement Lag/Lead functions https://kb.altinity.com/altinity-kb-queries-and-syntax/lag-lead/ But I can't find a way to replace NULLs with other values.

Using that example and adding toNullable(a) you can see that many values are going to be NULL.

SELECT
    g,
    a,
    lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prev,
    leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next
FROM llexample
ORDER BY
    g ASC,
    a ASC

Query id: 65c75108-520f-4115-8996-328e8e62aa25

┌─g─┬──────────a─┬───────prev─┬───────next─┐
│ 0 │ 2020-01-01 │       ᴺᵁᴸᴸ │ 2020-01-04 │
│ 0 │ 2020-01-04 │ 2020-01-01 │ 2020-01-07 │
│ 0 │ 2020-01-07 │ 2020-01-04 │ 2020-01-10 │
│ 0 │ 2020-01-10 │ 2020-01-07 │ 1970-01-01 │
│ 1 │ 2020-01-02 │       ᴺᵁᴸᴸ │ 2020-01-05 │
│ 1 │ 2020-01-05 │ 2020-01-02 │ 2020-01-08 │
│ 1 │ 2020-01-08 │ 2020-01-05 │ 1970-01-01 │
│ 2 │ 2020-01-03 │       ᴺᵁᴸᴸ │ 2020-01-06 │
│ 2 │ 2020-01-06 │ 2020-01-03 │ 2020-01-09 │
│ 2 │ 2020-01-09 │ 2020-01-06 │ 1970-01-01 │
└───┴────────────┴────────────┴────────────┘

```
<p>I tried to add <code>leadInFrame</code> inside a <code>COALESCE</code>. But when I try to do that I get the error:</p>
<pre class="lang-sql prettyprint-override"><code>SELECT
    g,
    a,
    COALESCE(
      lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
      today()
    ) AS prev,
    leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next
FROM llexample
ORDER BY
    g ASC,
    a ASC

Query id: 9685b822-7f31-45d3-9103-89f06b373876

0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 22.1.2):
Code: 47. DB::Exception: Received from localhost:9000. DB::Exception: Unknown identifier: lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING); there are columns: g, a, toNullable(a): While processing g, a, coalesce(lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), today()) AS prev, leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next. (UNKNOWN_IDENTIFIER)

</code>```

I also tried other conditionals and got the same error.

Best

答:
https://github.com/ClickHouse/ClickHouse/issues/19857
You simply need to use subquery, because window functions are not fully functional.

select
  g,
  a,
  COALESCE( prev,  today()) prev,
  next
from (
    SELECT
        g,
        a,
        lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) prev,
        leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next
    FROM llexample
    ORDER BY
        g ASC,
        a ASC
)
```

Body:
I'm following Altinity's examples on how to implement Lag/Lead functions https://kb.altinity.com/altinity-kb-queries-and-syntax/lag-lead/ But I can't find a way to replace NULLs with other values.

Using that example and adding toNullable(a) you can see that many values are going to be NULL.

SELECT
    g,
    a,
    lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS prev,
    leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next
FROM llexample
ORDER BY
    g ASC,
    a ASC

Query id: 65c75108-520f-4115-8996-328e8e62aa25

┌─g─┬──────────a─┬───────prev─┬───────next─┐
│ 0 │ 2020-01-01 │       ᴺᵁᴸᴸ │ 2020-01-04 │
│ 0 │ 2020-01-04 │ 2020-01-01 │ 2020-01-07 │
│ 0 │ 2020-01-07 │ 2020-01-04 │ 2020-01-10 │
│ 0 │ 2020-01-10 │ 2020-01-07 │ 1970-01-01 │
│ 1 │ 2020-01-02 │       ᴺᵁᴸᴸ │ 2020-01-05 │
│ 1 │ 2020-01-05 │ 2020-01-02 │ 2020-01-08 │
│ 1 │ 2020-01-08 │ 2020-01-05 │ 1970-01-01 │
│ 2 │ 2020-01-03 │       ᴺᵁᴸᴸ │ 2020-01-06 │
│ 2 │ 2020-01-06 │ 2020-01-03 │ 2020-01-09 │
│ 2 │ 2020-01-09 │ 2020-01-06 │ 1970-01-01 │
└───┴────────────┴────────────┴────────────┘

I tried to add leadInFrame inside a COALESCE. But when I try to do that I get the error:

SELECT
    g,
    a,
    COALESCE(
      lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING),
      today()
    ) AS prev,
    leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next
FROM llexample
ORDER BY
    g ASC,
    a ASC

Query id: 9685b822-7f31-45d3-9103-89f06b373876

0 rows in set. Elapsed: 0.002 sec.

Received exception from server (version 22.1.2):
Code: 47. DB::Exception: Received from localhost:9000. DB::Exception: Unknown identifier: lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING); there are columns: g, a, toNullable(a): While processing g, a, coalesce(lagInFrame(toNullable(a)) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING), today()) AS prev, leadInFrame(a) OVER (PARTITION BY g ORDER BY a ASC Rows BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS next. (UNKNOWN_IDENTIFIER)

I also tried other conditionals and got the same error.

Best


问:
react-email-editor loadDesign dynamically with fetch data
I try to integrate the react-email-editor as a component.
It only works if i use design defined as const.

This is the sample
https://github.com/unlayer/react-email-editor/blob/master/demo/src/example/index.js

I have no deeper experience with reactjs useRef.
I tried different ways to load the data, but without success:

loading the data in a wrapper component and passing it as props

handle the data with useEffect and useState

Is there a successful sample?

```<code>  ...

  const [selected, setSelected] = useState();

  const emailEditorRef = useRef(null);

  useEffect(() => {
    loadSelectedDesign(selected);
  }, [selected]);

  const loadSelectedDesign = (design) => {
    console.log("loadSelectedDesign", design);
    // does not work:
    if (emailEditorRef.current && emailEditorRef.current.editor)
      emailEditorRef.current.editor.loadDesign(design);
  }

  ...
  const select = () => {
    const fetchSelectedTemplate = async () => {
      const emailTemplate = (
        await dataProvider.getEmailTemplate("XYZ")
      ).data;
      setSelected(emailTemplate);

    };
    fetchSelectedTemplate();
  };

  ...

   <Button onClick={select}>
       Load
   </Button>
   <React.StrictMode>
       <EmailEditor ref={emailEditorRef} onLoad={onLoad} onReady={onReady} options={props.unlayerOptions} />
   </React.StrictMode>
</code>```

答:
I was able to solve it myself.
It was just a formatting issue when loading the JSON.</p>

Body:
I try to integrate the react-email-editor as a component.
It only works if i use design defined as const.

This is the sample
https://github.com/unlayer/react-email-editor/blob/master/demo/src/example/index.js

I have no deeper experience with reactjs useRef.
I tried different ways to load the data, but without success:

loading the data in a wrapper component and passing it as props

handle the data with useEffect and useState

Is there a successful sample?

  ...

  const [selected, setSelected] = useState();

  const emailEditorRef = useRef(null);

  useEffect(() => {
    loadSelectedDesign(selected);
  }, [selected]);

  const loadSelectedDesign = (design) => {
    console.log("loadSelectedDesign", design);
    // does not work:
    if (emailEditorRef.current && emailEditorRef.current.editor)
      emailEditorRef.current.editor.loadDesign(design);
  }

  ...
  const select = () => {
    const fetchSelectedTemplate = async () => {
      const emailTemplate = (
        await dataProvider.getEmailTemplate("XYZ")
      ).data;
      setSelected(emailTemplate);

    };
    fetchSelectedTemplate();
  };

  ...

   <Button onClick={select}>
       Load
   </Button>
   <React.StrictMode>
       <EmailEditor ref={emailEditorRef} onLoad={onLoad} onReady={onReady} options={props.unlayerOptions} />
   </React.StrictMode>


问:
How do I generate the lowest id that satisfies a multi-part unqiue key?
The following schema and INSERTs:

```<code>DROP TABLE IF EXISTS foo_bar;
DROP TABLE IF EXISTS foo;

CREATE TABLE foo (
    foo_id INT PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY,
    baz VARCHAR UNIQUE NOT NULL
);

CREATE TABLE foo_bar (
    foo_id INT NOT NULL,
    bar_id INT NOT NULL GENERATED ALWAYS AS IDENTITY,
    quux VARCHAR UNIQUE NOT NULL,
    FOREIGN KEY(foo_id) REFERENCES foo(foo_id),
    PRIMARY KEY(bar_id, foo_id)
);

INSERT INTO foo(baz) VALUES('baz1');
INSERT INTO foo(baz) VALUES('baz2');
INSERT INTO foo_bar(foo_id, quux) VALUES(1, 'quux 1/1');
INSERT INTO foo_bar(foo_id, quux) VALUES(1, 'quux 1/2');
INSERT INTO foo_bar(foo_id, quux) VALUES(2, 'quux 2/1');
INSERT INTO foo_bar(foo_id, quux) VALUES(2, 'quux 2/2');
</code>```

give the results:

```<code>mud=> select * from foo;
 foo_id | baz
--------+------
      1 | baz1
      2 | baz2
(2 rows)

mud=> select * from foo_bar;
 foo_id | bar_id |   quux
--------+--------+----------
      1 |      1 | quux 1/1
      1 |      2 | quux 1/2
      2 |      3 | quux 2/1
      2 |      4 | quux 2/2
(4 rows)
</code>```

I want the generated bar_ids to be the lowest values which satisfy the unique primary key constraint on (foo_id, bar_id).

i.e. I want the results to be:

```<code>mud=> select * from foo;
 foo_id | baz
--------+------
      1 | baz1
      2 | baz2
(2 rows)

mud=> select * from foo_bar;
 foo_id | bar_id |   quux
--------+--------+----------
      1 |      1 | quux 1/1
      1 |      2 | quux 1/2
      2 |     *1*| quux 2/1
      2 |     *2*| quux 2/2
(4 rows)
</code>```

How can I alter my schema to achieve this?

答:
Don't do it.

Primary keys only requirement is that their values need to be unique. They are internal identifiers that are not meant to be exposed to the users in the UI or through an external API, or other.

If you are asking this you probably want to expose them somewhere, and that's a big red flag in your design.

If you really need to show a customized ID, then you can create an extra generated column that can be formatted with prefixes, suffixes, dashes, and take any sequence or custom logic you want.

Body:
The following schema and INSERTs:

DROP TABLE IF EXISTS foo_bar;
DROP TABLE IF EXISTS foo;

CREATE TABLE foo (
    foo_id INT PRIMARY KEY NOT NULL GENERATED ALWAYS AS IDENTITY,
    baz VARCHAR UNIQUE NOT NULL
);

CREATE TABLE foo_bar (
    foo_id INT NOT NULL,
    bar_id INT NOT NULL GENERATED ALWAYS AS IDENTITY,
    quux VARCHAR UNIQUE NOT NULL,
    FOREIGN KEY(foo_id) REFERENCES foo(foo_id),
    PRIMARY KEY(bar_id, foo_id)
);

INSERT INTO foo(baz) VALUES('baz1');
INSERT INTO foo(baz) VALUES('baz2');
INSERT INTO foo_bar(foo_id, quux) VALUES(1, 'quux 1/1');
INSERT INTO foo_bar(foo_id, quux) VALUES(1, 'quux 1/2');
INSERT INTO foo_bar(foo_id, quux) VALUES(2, 'quux 2/1');
INSERT INTO foo_bar(foo_id, quux) VALUES(2, 'quux 2/2');

give the results:

mud=> select * from foo;
 foo_id | baz
--------+------
      1 | baz1
      2 | baz2
(2 rows)

mud=> select * from foo_bar;
 foo_id | bar_id |   quux
--------+--------+----------
      1 |      1 | quux 1/1
      1 |      2 | quux 1/2
      2 |      3 | quux 2/1
      2 |      4 | quux 2/2
(4 rows)

I want the generated bar_ids to be the lowest values which satisfy the unique primary key constraint on (foo_id, bar_id).

i.e. I want the results to be:

mud=> select * from foo;
 foo_id | baz
--------+------
      1 | baz1
      2 | baz2
(2 rows)

mud=> select * from foo_bar;
 foo_id | bar_id |   quux
--------+--------+----------
      1 |      1 | quux 1/1
      1 |      2 | quux 1/2
      2 |     *1*| quux 2/1
      2 |     *2*| quux 2/2
(4 rows)

How can I alter my schema to achieve this?


问:
SSRS - How to change between report displayed based on the results of a dataset
I have three very different reports to display depending on a LOB code.  LOB is not an input parameter, and I want to avoid it being one if possible.  I also do not want to create 3 separate reports.  Rather, I would like my report to be able to accept the user input, read the database to determine LOB, and display the appropriate subreport for the LOB.  Is this doable?  The only way i could find to do it was to have LOB as a parameter, and show\hide the subreports based on that parameter.</p>

答:
If you adopt the show/hide subreports based on the LOB approach where LOB is a parameter, then you should be able to do this but without requiring the use to enter the LOB type/value or whatever form it takes.

Based on your question it sounds like if you accept some user input via a parameter, you can then determine the LOB. If your LOB parameter has a default value based on a query such as

```<code>SELECT LOB from myTable WHERE someValue = @myUserInput
</code>```

then you can hide the LOB parameter but still use it to control the visibility of the subreports.

If this does not help, then describe the workflow in more detail.

Body:
If you adopt the show/hide subreports based on the LOB approach where LOB is a parameter, then you should be able to do this but without requiring the use to enter the LOB type/value or whatever form it takes.

Based on your question it sounds like if you accept some user input via a parameter, you can then determine the LOB. If your LOB parameter has a default value based on a query such as

SELECT LOB from myTable WHERE someValue = @myUserInput

then you can hide the LOB parameter but still use it to control the visibility of the subreports.

If this does not help, then describe the workflow in more detail.


问:
Odoo 11: How to correctly implement @api.onchange?
I want to compute a telephone number, if the number in the 8 position is either "0" or "1" I want to print  just the last 4 numbers with a  "(3)" before them, otherwise just print the 4 numbers, but what is happening is that my code is printing "0.0" and I don't know why, I'll appreciate your help...

This is my python code:

class Employee(models.Model):
    _inherit = "hr.employee"

    marcado_rapido = fields.Float("MarcadoRapido",compute='_compute_marcado_rapido')
    @api.onchange("emp.marcado_rapido")
    def onchange_compute_marcado_rapido(self):
        for num in self:
            num = "809-257-1457"
            if num[8] in ('0','1'):
                "(3)"+num[8:]
```
<p>This is my xml code:</p>
<pre class="lang-xml prettyprint-override"><code><td>
    <t t-foreach="env['hr.employee'].search([('department_id', '=', dep.id)])" t-as="emp">
        <div class="contact_form">
            <img t-if="emp.image" t-att-src="'data:image/png;base64,%s' % to_text(emp.image)"/>
            <div class="bloqueP">
                <div class="bloque" t-field="emp.marcado_rapido"/>
            </div>
        </div>
    </t>
</td>
</code>```

答:
@onchange only supports simple field names, dotted names (fields of relational fields e.g. partner_id.tz) are not supported and will be ignored

You can check the official documentation on how the onchange decorator works and what are the limitations.

0.0 is the default value for float fields and the value of marcado_rapido is computed using _compute_marcado_rapido function. If the field updated in onchange method depends on marcado_rapido field value, you can compute its value using the same method

Body:
I want to compute a telephone number, if the number in the 8 position is either "0" or "1" I want to print  just the last 4 numbers with a  "(3)" before them, otherwise just print the 4 numbers, but what is happening is that my code is printing "0.0" and I don't know why, I'll appreciate your help...

This is my python code:

class Employee(models.Model):
    _inherit = "hr.employee"

    marcado_rapido = fields.Float("MarcadoRapido",compute='_compute_marcado_rapido')
    @api.onchange("emp.marcado_rapido")
    def onchange_compute_marcado_rapido(self):
        for num in self:
            num = "809-257-1457"
            if num[8] in ('0','1'):
                "(3)"+num[8:]

This is my xml code:

    <t t-foreach="env['hr.employee'].search([('department_id', '=', dep.id)])" t-as="emp">

    </t>


问:
Ruby On Rails - CRUD - Destroy/Delete Not Working?
I've gone through a good chunk of this tutorial, and have gotten to the part where functionality for deleting articles is added:

https://guides.rubyonrails.org/getting_started.html

...but whenever the 'Delete' link is clicked on, the article is not deleted.  Nothing happens, and a GET request is sent rather than a DELETE.

From the erb file:

```<code><%= link_to 'Destroy', article_path(@article), data:{
  turbo_method: :delete,
  turbo_confirm: 'Are you sure?'
} %>
</code>```

From the controller:

```<code>def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to root_path, status: :see_other
end
</code>```

After trying a solution that was mentioned in SO and in various Web pages (adding the below to my 'application.html.erb' file:

```<code><%= javascript_include_tag 'application', "data-turbo-track": "reload" %>
</code>```

...I get this error:

ActionView::Template::Error (The asset "application.js" is not present in the asset pipeline.

I did some digging and realized that the application scaffolder (rails new blog in this case) didn't create any Javascript directories much less add any JS files to them.  I'm  fine with adding them myself, but I don't even know what JS files Rails and/or Turbo is looking for.  JQuery? Some other library?

Ideally, however, I'd like to know how to properly scaffold an app so that any necessary Javascript is included.

Thanks,
Bryan

EDIT
I was able to get the delete functionality working by using the 'non-turbo' method of deleting items and using 'button_to' instead of 'link_to' for the 'Delete' link.  However-- I would still like to know why the app as shown in the tutorial doesn't work as expected, and how to use a link rather than a button to trigger the item deletion (not to mention why using turbo doesn't work).

答: So my answer is that there is no answer--- but I believe mechnicov is correct in saying that the app was not created correctly; I recreated the project in Linux, and everything works as expected.  Apparently there is something wrong with my Ruby/Rails installation in Windows.</p>

Body:
I've gone through a good chunk of this tutorial, and have gotten to the part where functionality for deleting articles is added:

https://guides.rubyonrails.org/getting_started.html

...but whenever the 'Delete' link is clicked on, the article is not deleted.  Nothing happens, and a GET request is sent rather than a DELETE.

From the erb file:

<%= link_to 'Destroy', article_path(@article), data:{
  turbo_method: :delete,
  turbo_confirm: 'Are you sure?'
} %>

From the controller:

def destroy
    @article = Article.find(params[:id])
    @article.destroy
    redirect_to root_path, status: :see_other
end

After trying a solution that was mentioned in SO and in various Web pages (adding the below to my 'application.html.erb' file:

<%= javascript_include_tag 'application', "data-turbo-track": "reload" %>

...I get this error:

ActionView::Template::Error (The asset "application.js" is not present in the asset pipeline.

I did some digging and realized that the application scaffolder (rails new blog in this case) didn't create any Javascript directories much less add any JS files to them.  I'm  fine with adding them myself, but I don't even know what JS files Rails and/or Turbo is looking for.  JQuery? Some other library?

Ideally, however, I'd like to know how to properly scaffold an app so that any necessary Javascript is included.

Thanks,
Bryan

EDIT
I was able to get the delete functionality working by using the 'non-turbo' method of deleting items and using 'button_to' instead of 'link_to' for the 'Delete' link.  However-- I would still like to know why the app as shown in the tutorial doesn't work as expected, and how to use a link rather than a button to trigger the item deletion (not to mention why using turbo doesn't work).


问:
How to avoid duplicate payments/subscriptions using Paypal Smart Buttons
I am using Paypal Smart Buttons (Javascript SDK) to create recurring subscriptions. My issue is that (very infrequently) a user manages to create a duplicate subscription and recurring payments.

When I look at my logs I can see the transactions are happening within 60 seconds so I assume it's an accidental double click on the Paypal pay button (or something).

I read the docs and saw that for standard payments you can add:

A unique invoice_id that hasn't been used for a previously-completed transaction to identify the order for accounting purposes and to prevent duplicate payments.

However there doesn't seem to be a way to stop duplicate subscriptions/recurring payments because the subscription API only supports custom_id.

See documentation here and another similar question here.

Here is my code:

```<code>    paypal.Buttons({
        style: {
            shape: 'rect',
            color: 'silver',
            label:  'subscribe'
        },
        onError: function (err) {
            // show error message
        },
        onClick: function(data)  {
            // do something when the button is clicked
        },
        // Create the subscription
        createSubscription: function(data, actions) {
            return actions.subscription.create({
                plan_id: "P-12345355RK523772MMDZIKUA",
                start_time: "2022-01-17T09:00:00Z",
                custom_id: order_reference,
                plan: {
                    billing_cycles: [
                    {
                        frequency: {
                            interval_unit: "MONTH",
                            interval_count: 1
                        },
                        tenure_type: "REGULAR",
                        sequence: 1,
                        pricing_scheme: {
                            fixed_price: {
                                value: 149,
                                currency_code: "USD"
                            }
                        }
                    }]
                },
                application_context:  {
                    shipping_preference: "NO_SHIPPING"
                }
            });
        },

        // Finalize the transaction
        onApprove: function(details, actions) {
            console.log("subscription_id: "+details.subscriptionID)
            $('#thanks').load("/paypal/thanks?reference="+order_reference, details,
              function(responseText, textStatus, request) {
                if (textStatus == "error") {
                    // show error message
                }
            });
        }
    }).render('#paypal-button-container');
</code>```

My current solution is to check in the paypal/thanks controller whether the order has already been associated with a subscription. If that happens I sent myself an error alert via email and have to manually fix the mess

Someone else suggested I automate that process, but I am hoping there's a better solution.

Thanks

答:
You are creating the subscription on the client side with actions.subscription.create, which means two independent clicks of the button will create separate subscription intents, which can be approved independently.

The better solution is to have createSubscription fetch a subscription ID from your server (which it will create via the PayPal API) . If the order_reference is a duplicate, you can return the subscription id you already created. It can only be approved once!

Example of such a createSubscription function that calls a server that would return an id with idempotence (if the same call is repeated, return the same id)

      createSubscription: function(data, actions) {
          return fetch('/path/on/your/server/paypal/subscription/create/' + unique_invoice_id, {
              method: 'post'
          }).then(function(res) {
              return res.json();
          }).then(function(serverData) {
              console.log(serverData);
              return serverData.id;
          });
      },
```

Body:
I am using Paypal Smart Buttons (Javascript SDK) to create recurring subscriptions. My issue is that (very infrequently) a user manages to create a duplicate subscription and recurring payments.

When I look at my logs I can see the transactions are happening within 60 seconds so I assume it's an accidental double click on the Paypal pay button (or something).

I read the docs and saw that for standard payments you can add:

A unique invoice_id that hasn't been used for a previously-completed transaction to identify the order for accounting purposes and to prevent duplicate payments.

However there doesn't seem to be a way to stop duplicate subscriptions/recurring payments because the subscription API only supports custom_id.

See documentation here and another similar question here.

Here is my code:

    paypal.Buttons({
        style: {
            shape: 'rect',
            color: 'silver',
            label:  'subscribe'
        },
        onError: function (err) {
            // show error message
        },
        onClick: function(data)  {
            // do something when the button is clicked
        },
        // Create the subscription
        createSubscription: function(data, actions) {
            return actions.subscription.create({
                plan_id: "P-12345355RK523772MMDZIKUA",
                start_time: "2022-01-17T09:00:00Z",
                custom_id: order_reference,
                plan: {
                    billing_cycles: [
                    {
                        frequency: {
                            interval_unit: "MONTH",
                            interval_count: 1
                        },
                        tenure_type: "REGULAR",
                        sequence: 1,
                        pricing_scheme: {
                            fixed_price: {
                                value: 149,
                                currency_code: "USD"
                            }
                        }
                    }]
                },
                application_context:  {
                    shipping_preference: "NO_SHIPPING"
                }
            });
        },

        // Finalize the transaction
        onApprove: function(details, actions) {
            console.log("subscription_id: "+details.subscriptionID)
            $('#thanks').load("/paypal/thanks?reference="+order_reference, details,
              function(responseText, textStatus, request) {
                if (textStatus == "error") {
                    // show error message
                }
            });
        }
    }).render('#paypal-button-container');

My current solution is to check in the paypal/thanks controller whether the order has already been associated with a subscription. If that happens I sent myself an error alert via email and have to manually fix the mess

Someone else suggested I automate that process, but I am hoping there's a better solution.

Thanks


问:
Usage of Dictionary along with KeyPairValue
I have a dictionary declared as follows:

```<code>public:
     static Dictionary<String ^, List<String ^>^> ^ language_string_table;
</code>```

so by using for each loop key and values are loaded into that (which is written by someone else). Now I need by using the same for each loop I am able to access "key" of the Dictionary alone, please help me out how to access "value" of the Dictionary.

答:
Your question is not very clear.

If you want to loop only over the keys, use language_string_table->Keys. If you want to loop only over the values, use language_string_table->Values. If you want to get the value for a key, use language_string_table->default[key].

Body:
I have a dictionary declared as follows:

public:
     static Dictionary<String ^, List<String ^>^> ^ language_string_table;

so by using for each loop key and values are loaded into that (which is written by someone else). Now I need by using the same for each loop I am able to access "key" of the Dictionary alone, please help me out how to access "value" of the Dictionary.


问:
ETH-BROWNIE install issue - windows - pipx
So I am trying to install eth-brownie via pipx as recommended, this on Windows.
I tried everything also multiple re-installs of EVERYTHING including python.
This one error just isn't fixable for me and googling this doesn't help.

```<code>PS C:\Users\XXXX\Desktop\solidity> python -m pipx install eth-brownie

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\__main__.py", line 14, in <module>
    sys.exit(cli())
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\main.py", line 779, in cli
    return run_pipx_command(parsed_pipx_args)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\main.py", line 202, in run_pipx_command
    return commands.install(
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\commands\install.py", line 60, in install
    venv.install_package(
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\venv.py", line 238, in install_package
    subprocess_post_check_handle_pip_error(pip_process)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\util.py", line 349, in subprocess_post_check_handle_pip_error
    print(completed_process.stderr, file=pip_error_fh, end="")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2502' in position 559: character maps to <undefined>
</code>```

This last python install was via Microsoft store, don't ask me why, but this error is the same if I download python via the normal way.

If anyone can help me I would be very grateful.
Works fine on my laptop, but it's an old and slow one so need it on PC.

答:
I'm pretty sure I just did it using pip instead of pipx:

 python -m pip install eth-brownie

Body:
So I am trying to install eth-brownie via pipx as recommended, this on Windows.
I tried everything also multiple re-installs of EVERYTHING including python.
This one error just isn't fixable for me and googling this doesn't help.

PS C:\Users\XXXX\Desktop\solidity> python -m pipx install eth-brownie

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 196, in _run_module_as_main
    return _run_code(code, main_globals, None,
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\runpy.py", line 86, in _run_code
    exec(code, run_globals)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\__main__.py", line 14, in <module>
    sys.exit(cli())
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\main.py", line 779, in cli
    return run_pipx_command(parsed_pipx_args)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\main.py", line 202, in run_pipx_command
    return commands.install(
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\commands\install.py", line 60, in install
    venv.install_package(
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\venv.py", line 238, in install_package
    subprocess_post_check_handle_pip_error(pip_process)
  File "C:\Users\XXXX\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.10_qbz5n2kfra8p0\LocalCache\local-packages\Python310\site-packages\pipx\util.py", line 349, in subprocess_post_check_handle_pip_error
    print(completed_process.stderr, file=pip_error_fh, end="")
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.752.0_x64__qbz5n2kfra8p0\lib\encodings\cp1252.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2502' in position 559: character maps to <undefined>

This last python install was via Microsoft store, don't ask me why, but this error is the same if I download python via the normal way.

If anyone can help me I would be very grateful.
Works fine on my laptop, but it's an old and slow one so need it on PC.


问:
Is it possible to create a synonym for a sequence in sql server (2014 and onwards)
I have 2 SQL server databases on a single windows server. the user that is used to login has sufficient rights on both databases. The application is only able to have a single database connection but requires content from both databases. To get data from the other database  views or synonyms can be used. That all works fine.
The application then needs to write a result into a table that is not in the database where it is connected to. This table has an ID column that requires an unique value which comes from a sequence. The application code actually does a get next value call so it must use the sequence. see below error message from the log.

```<code>could not get next sequence value[SQL: select next value for SEQ_xxx as seq]
</code>```

I found a post where somebody stated that sql server 2012 it was not possible to create a synonym for a sequence, I tried it on 2014 and 2017 without any luck. Does anybody know if it possible or will be possible in a new version?

And does anybody has a suggestion to solve this in a different way. Swapping the connection to the other database will not work, as both databases are updated with sequences.

答:
You might try doing this:

Create a stored procedure that can be called to get the sequence(s)

```<code>CREATE OR ALTER PROCEDURE [dbo].[GetNextValueForSomeSequence]
(
    @numberOfNextValueNeeded INT = NULL
)
AS
BEGIN TRY
   SET NOCOUNT ON;
   SET XACT_ABORT ON;

   WITH Pass0 AS (SELECT 1 AS C UNION ALL SELECT 1) --2 rows
       ,Pass1 AS (SELECT 1 AS C FROM Pass0 AS A, Pass0 AS B)--4 rows
       ,Pass2 AS (SELECT 1 AS C FROM Pass1 AS A, Pass1 AS B)--16 rows
       ,Pass3 AS (SELECT 1 AS C FROM Pass2 AS A, Pass2 AS B)--256 rows
       ,Pass4 AS (SELECT 1 AS C FROM Pass3 AS A, Pass3 AS B)--65536 rows
       ,Pass5 AS (SELECT 1 AS C FROM Pass4 AS A, Pass4 AS B)--4,294,967,296 rows
       --I removed Pass5, since I'm only populating the Numbers table to 10,000
       ,Tally AS (SELECT ROW_NUMBER() OVER(ORDER BY C) AS Number FROM Pass5)
   SELECT NEXT VALUE FOR [dbo].[SomeSequence_Seq] [SeqValue]
         ,T.Number [RowNum]
      INTO [dbo].[#TempSequence]
      FROM Tally T
     WHERE T.Number <= COALESCE(@numberOfNextValueNeeded, 1);

   SELECT [RowNum], [SeqValue]
     FROM [dbo].[#TempSequence]

   DROP TABLE [dbo].[#TempSequence]

END TRY
BEGIN CATCH

   THROW;
END CATCH;
GO
</code>```

Create a synonym for it

```<code>CREATE SYNONYM [SYN].[GetNextValueForSomeSequence] FOR [database].[dbo].[SomeSequence_Seq]
</code>```

And use it somewhere like this:

```<code>CREATE TABLE [dbo].[#TempSequence]
(
   [RowNum] INT
  ,[SeqValue]  INT
);
INSERT INTO [Import].[#TempSequence] ([RowNum], [SeqValue])
EXEC [SYN].[GetNextValueForSomeSequence] 1;
</code>```

Then use it from the temp table.

Body:
I have 2 SQL server databases on a single windows server. the user that is used to login has sufficient rights on both databases. The application is only able to have a single database connection but requires content from both databases. To get data from the other database  views or synonyms can be used. That all works fine.
The application then needs to write a result into a table that is not in the database where it is connected to. This table has an ID column that requires an unique value which comes from a sequence. The application code actually does a get next value call so it must use the sequence. see below error message from the log.

could not get next sequence value[SQL: select next value for SEQ_xxx as seq]

I found a post where somebody stated that sql server 2012 it was not possible to create a synonym for a sequence, I tried it on 2014 and 2017 without any luck. Does anybody know if it possible or will be possible in a new version?

And does anybody has a suggestion to solve this in a different way. Swapping the connection to the other database will not work, as both databases are updated with sequences.

Body:
You might try doing this:

Create a stored procedure that can be called to get the sequence(s)

CREATE OR ALTER PROCEDURE [dbo].[GetNextValueForSomeSequence]
(
    @numberOfNextValueNeeded INT = NULL
)
AS
BEGIN TRY
   SET NOCOUNT ON;
   SET XACT_ABORT ON;

   WITH Pass0 AS (SELECT 1 AS C UNION ALL SELECT 1) --2 rows
       ,Pass1 AS (SELECT 1 AS C FROM Pass0 AS A, Pass0 AS B)--4 rows
       ,Pass2 AS (SELECT 1 AS C FROM Pass1 AS A, Pass1 AS B)--16 rows
       ,Pass3 AS (SELECT 1 AS C FROM Pass2 AS A, Pass2 AS B)--256 rows
       ,Pass4 AS (SELECT 1 AS C FROM Pass3 AS A, Pass3 AS B)--65536 rows
       ,Pass5 AS (SELECT 1 AS C FROM Pass4 AS A, Pass4 AS B)--4,294,967,296 rows
       --I removed Pass5, since I'm only populating the Numbers table to 10,000
       ,Tally AS (SELECT ROW_NUMBER() OVER(ORDER BY C) AS Number FROM Pass5)
   SELECT NEXT VALUE FOR [dbo].[SomeSequence_Seq] [SeqValue]
         ,T.Number [RowNum]
      INTO [dbo].[#TempSequence]
      FROM Tally T
     WHERE T.Number <= COALESCE(@numberOfNextValueNeeded, 1);

   SELECT [RowNum], [SeqValue]
     FROM [dbo].[#TempSequence]

   DROP TABLE [dbo].[#TempSequence]

END TRY
BEGIN CATCH

   THROW;
END CATCH;
GO

Create a synonym for it

CREATE SYNONYM [SYN].[GetNextValueForSomeSequence] FOR [database].[dbo].[SomeSequence_Seq]

And use it somewhere like this:

CREATE TABLE [dbo].[#TempSequence]
(
   [RowNum] INT
  ,[SeqValue]  INT
);
INSERT INTO [Import].[#TempSequence] ([RowNum], [SeqValue])
EXEC [SYN].[GetNextValueForSomeSequence] 1;

Then use it from the temp table.


问:
Check if two numbers have same digits
I need to write a program which will check if two numbers have same digits.
For example:

```<code>a = 4423, b = 2433;
</code>```

Even though their digits don't appear the same amount if times, they have same digits.

```<code>#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}
</code>```

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

答:
Your code is a bit more complicated than it needs to be.

Just compute a "has a digit" vector for each number (e.g. each element is 1 if the corresponding digit is in the number). This is a histogram/frequency table except that instead of the count of the digits in a number, it's just 0 or 1.

Then, compare the vectors for equality.

Here's some refactored code:

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

void
count(int x,int *hasdig)
{
    int dig;

    // handle negative numbers
    if (x < 0)
        x = -x;

    // special case for zero
    // NOTE: may not be necessary
#if 1
    if (x == 0)
        hasdig[0] = 1;
#endif

    for (;  x != 0;  x /= 10) {
        dig = x % 10;
        hasdig[dig] = 1;
    }
}

int
same_digit(int a, int b)
{
    int dig_a[10] = { 0 };
    int dig_b[10] = { 0 };
    int dig;
    int same = 1;

    count(a,dig_a);
    count(b,dig_b);

    for (dig = 0;  dig < 10;  ++dig) {
        same = (dig_a[dig] == dig_b[dig]);
        if (! same)
            break;
    }

    return same;
}

int
main()
{
    int a, b;

    scanf("%d", &a);
    scanf("%d", &b);

    if (same_digit(a, b))
        printf("Yes\n");
    else
        printf("No\n");

    return 0;
}
</code>```

UPDATE:

Also beware UB if either or both numbers is INT_MIN

Yes, -INT_MIN is still negative :-(

I've come up with an alternate way to deal with it. However, IMO, [almost] any approach seems to be extra work, just to make one special case work. So, I've kept the original [faster/simpler] code above

And, I've added some extra test/debug code.

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

int opt_t;

void
count(int x,int *hasdig)
{
    int dig;

    // handle negative numbers
    if (x < 0)
        x = -x;

    // special case for zero
    // NOTE: may not be necessary
#if 1
    if (x == 0)
        hasdig[0] = 1;
#endif

    for (;  x != 0;  x /= 10) {
        dig = x % 10;

        // my -INT_MIN fix ...
        if (dig < 0)
            dig = -dig;

        hasdig[dig] = 1;
    }
}

int
same_digit(int a, int b)
{
    int dig_a[10] = { 0 };
    int dig_b[10] = { 0 };
    int dig;
    int same = 1;

    count(a,dig_a);
    count(b,dig_b);

    for (dig = 0;  dig < 10;  ++dig) {
        same = (dig_a[dig] == dig_b[dig]);
        if (! same)
            break;
    }

    return same;
}

void
dotest(int a,int b)
{

    printf("a=%d b=%d -- %s\n",
        a,b,same_digit(a,b) ? "Yes" : "No");
}

int
main(int argc,char **argv)
{
    char *cp;

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        cp = *argv;
        if (*cp != '-')
            break;

        if ((cp[1] == '-') && (cp[2] == 0)) {
            --argc;
            ++argv;
            break;
        }

        cp += 2;
        switch(cp[-1]) {
        case 't':
            opt_t = ! opt_t;
            break;
        }
    }

    do {
        int a, b;

        if (opt_t) {
            dotest(4423,2433);
            dotest(INT_MIN,1234678);
            dotest(INT_MIN,INT_MIN);
            dotest(INT_MAX,INT_MAX);
            break;
        }

        if (argc > 0) {
            for (;  argc > 0;  --argc, ++argv) {
                cp = *argv;
                if (sscanf(cp,"%d,%d",&a,&b) != 2)
                    break;
                dotest(a,b);
            }
            break;
        }

        scanf("%d", &a);
        scanf("%d", &b);
        dotest(a,b);
    } while (0);

    return 0;
}
</code>```

Title: Check if two numbers have same digits

Body:
I need to write a program which will check if two numbers have same digits.
For example:

a = 4423, b = 2433;

Even though their digits don't appear the same amount if times, they have same digits.

#include <stdio.h>
#include <stdlib.h>
int same_digit(int a, int b) {
  int n = abs(a), i;
  int count[10];
  for (i = 0; i < 10; ++i) {
    count[i] = 0;
  }
  while (n > 0) {
    count[n % 10]++;
    n = n / 10;
  }
  n = abs(b);
  while (n > 0) {
    count[n % 10]--;
    n = n / 10;
  }
  for (i = 0; i < 10; ++i)
    if (count[i] != 0)
      return 0;
  return 1;
}
int main() {
  int a, b;
  scanf("%d", &a);
  scanf("%d", &b);
  if (same_digit(a, b)) printf("Yes");
  else printf("No");
  return 0;
}

Problem with my code is that this literally checks if they have same digits. How could I modify this code to return 1 if all digits from a are present in b, and all digits from b are present in a, no matter how many times they are present.

Body:
Your code is a bit more complicated than it needs to be.

Just compute a "has a digit" vector for each number (e.g. each element is 1 if the corresponding digit is in the number). This is a histogram/frequency table except that instead of the count of the digits in a number, it's just 0 or 1.

Then, compare the vectors for equality.

Here's some refactored code:

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

void
count(int x,int *hasdig)
{
    int dig;

    // handle negative numbers
    if (x < 0)
        x = -x;

    // special case for zero
    // NOTE: may not be necessary
#if 1
    if (x == 0)
        hasdig[0] = 1;
#endif

    for (;  x != 0;  x /= 10) {
        dig = x % 10;
        hasdig[dig] = 1;
    }
}

int
same_digit(int a, int b)
{
    int dig_a[10] = { 0 };
    int dig_b[10] = { 0 };
    int dig;
    int same = 1;

    count(a,dig_a);
    count(b,dig_b);

    for (dig = 0;  dig < 10;  ++dig) {
        same = (dig_a[dig] == dig_b[dig]);
        if (! same)
            break;
    }

    return same;
}

int
main()
{
    int a, b;

    scanf("%d", &a);
    scanf("%d", &b);

    if (same_digit(a, b))
        printf("Yes\n");
    else
        printf("No\n");

    return 0;
}

UPDATE:

Also beware UB if either or both numbers is INT_MIN

Yes, -INT_MIN is still negative :-(

I've come up with an alternate way to deal with it. However, IMO, [almost] any approach seems to be extra work, just to make one special case work. So, I've kept the original [faster/simpler] code above

And, I've added some extra test/debug code.

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

int opt_t;

void
count(int x,int *hasdig)
{
    int dig;

    // handle negative numbers
    if (x < 0)
        x = -x;

    // special case for zero
    // NOTE: may not be necessary
#if 1
    if (x == 0)
        hasdig[0] = 1;
#endif

    for (;  x != 0;  x /= 10) {
        dig = x % 10;

        // my -INT_MIN fix ...
        if (dig < 0)
            dig = -dig;

        hasdig[dig] = 1;
    }
}

int
same_digit(int a, int b)
{
    int dig_a[10] = { 0 };
    int dig_b[10] = { 0 };
    int dig;
    int same = 1;

    count(a,dig_a);
    count(b,dig_b);

    for (dig = 0;  dig < 10;  ++dig) {
        same = (dig_a[dig] == dig_b[dig]);
        if (! same)
            break;
    }

    return same;
}

void
dotest(int a,int b)
{

    printf("a=%d b=%d -- %s\n",
        a,b,same_digit(a,b) ? "Yes" : "No");
}

int
main(int argc,char **argv)
{
    char *cp;

    --argc;
    ++argv;

    for (;  argc > 0;  --argc, ++argv) {
        cp = *argv;
        if (*cp != '-')
            break;

        if ((cp[1] == '-') && (cp[2] == 0)) {
            --argc;
            ++argv;
            break;
        }

        cp += 2;
        switch(cp[-1]) {
        case 't':
            opt_t = ! opt_t;
            break;
        }
    }

    do {
        int a, b;

        if (opt_t) {
            dotest(4423,2433);
            dotest(INT_MIN,1234678);
            dotest(INT_MIN,INT_MIN);
            dotest(INT_MAX,INT_MAX);
            break;
        }

        if (argc > 0) {
            for (;  argc > 0;  --argc, ++argv) {
                cp = *argv;
                if (sscanf(cp,"%d,%d",&a,&b) != 2)
                    break;
                dotest(a,b);
            }
            break;
        }

        scanf("%d", &a);
        scanf("%d", &b);
        dotest(a,b);
    } while (0);

    return 0;
}


问:
Space Invaders Game Strange TypeError: 'int' object is not subscriptable Error in Python
Game starts runs fine then after I have killed between 3-12 enemies it crashes and gives me the typeError: 'int' object is not subscriptable error This is the line of code that it says is causing the issue,
enemyX[i] += enemyX_change[i]

I'm very confused how the program can run perfectly fine until a certain number of enemies are hit. If I just leave the program running without shooitng it runs until all the enemies make it too to the bottom the screen.

Heres all the code

```<code>import pygame
import random
import math
#pygame.time.Clock(30)

# Initialize the game
pygame.init()
# Screen
screen = pygame.display.set_mode((800, 600))
# background
background = pygame.image.load('background.png')

# Title and icon
pygame.display.set_caption("Space Invaders")

# player
playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 510
playerX_change = 0

# enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('ufo.png'))
    enemyX.append(random.randint(0, 735))
    enemyY.append(random.randint(40, 100))
    enemyX_change.append(2)
    enemyY_change.append(40)

# missile
missileImg = pygame.image.load('missile.png')
missileX = playerX
missileY = 483
missileY_change = 6
missile_state = "ready"

def player(x, y):
    screen.blit(playerImg, (x, y))

def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))

def fire_missile(x, y):
    global missile_state
    missile_state = "fire"
    screen.blit(missileImg, (x + 16, y + 10))

def is_collision(enemyX, enemyY, missileX, missileY):
    distance = math.sqrt((math.pow(enemyX - missileX, 2)) + (math.pow(enemyY - missileY, 2)))
    if distance < 27:
        return True
    else:
        return False

# Game loop
clock = pygame.time.Clock()
running = True
while running:
    clock.tick(60)

    screen.fill((0, 0, 0))
    # background image
    screen.blit(background, (-100, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # if keystroke is pressed check what key it is
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                playerX_change = -3
            if event.key == pygame.K_d:
                playerX_change = +3
            if event.key == pygame.K_SPACE:
                if missile_state == "ready":
                    missileX = playerX
                    missileY = playerY - 27
                    fire_missile(missileX, missileY)
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a or event.key == pygame.K_d:
                playerX_change = 0

    # spaceship boundary
    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 740:
        playerX = 740
    # enemy movement
    for i in range(num_of_enemies):
        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = 2
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 740:
            enemyX_change[i] = -2
            enemyY[i] += enemyY_change[i]

        collision = is_collision(enemyX[i], enemyY[i], missileX, missileY)
        if collision:
            missileY = 483
            missile_state = "ready"
            score += 1
            print(score)
            enemyX[i] = random.randint(0, 735)
            enemyY[i] = random.randint(40, 100)

        enemy(enemyX[i], enemyY[i], i)

    # missile movement
    if missileY < -10:
        missileY = 483
        missile_state = "ready"
    if missile_state is "fire":
        fire_missile(missileX, missileY)
        missileY -= missileY_change

    collision = is_collision(enemyX[i], enemyY[i], missileX, missileY)
    if collision:
        missileY = 483
        missile_state = "ready"
        score += 1
        print(score)
        enemyX = random.randint(0, 735)
        enemyY = random.randint(40, 100)

    player(playerX, playerY)
    pygame.display.update()
</code>```

Thanks for any help I can't figure it out.

答:
```<code>enemyX = random.randint(0, 735)
enemyY = random.randint(40, 100)
</code>```

I think you have to change this lines to something like this.

```<code>enemyX[i] = random.randint(0, 735)
enemyY[i] = random.randint(40, 100)
</code>```

Otherwise you turn the array to an integer.

Body:
Game starts runs fine then after I have killed between 3-12 enemies it crashes and gives me the typeError: 'int' object is not subscriptable error This is the line of code that it says is causing the issue,
enemyX[i] += enemyX_change[i]

I'm very confused how the program can run perfectly fine until a certain number of enemies are hit. If I just leave the program running without shooitng it runs until all the enemies make it too to the bottom the screen.

Heres all the code

import pygame
import random
import math
#pygame.time.Clock(30)

# Initialize the game
pygame.init()
# Screen
screen = pygame.display.set_mode((800, 600))
# background
background = pygame.image.load('background.png')

# Title and icon
pygame.display.set_caption("Space Invaders")

# player
playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 510
playerX_change = 0

# enemy
enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('ufo.png'))
    enemyX.append(random.randint(0, 735))
    enemyY.append(random.randint(40, 100))
    enemyX_change.append(2)
    enemyY_change.append(40)

# missile
missileImg = pygame.image.load('missile.png')
missileX = playerX
missileY = 483
missileY_change = 6
missile_state = "ready"

def player(x, y):
    screen.blit(playerImg, (x, y))

def enemy(x, y, i):
    screen.blit(enemyImg[i], (x, y))

def fire_missile(x, y):
    global missile_state
    missile_state = "fire"
    screen.blit(missileImg, (x + 16, y + 10))

def is_collision(enemyX, enemyY, missileX, missileY):
    distance = math.sqrt((math.pow(enemyX - missileX, 2)) + (math.pow(enemyY - missileY, 2)))
    if distance < 27:
        return True
    else:
        return False

# Game loop
clock = pygame.time.Clock()
running = True
while running:
    clock.tick(60)

    screen.fill((0, 0, 0))
    # background image
    screen.blit(background, (-100, 0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        # if keystroke is pressed check what key it is
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                playerX_change = -3
            if event.key == pygame.K_d:
                playerX_change = +3
            if event.key == pygame.K_SPACE:
                if missile_state == "ready":
                    missileX = playerX
                    missileY = playerY - 27
                    fire_missile(missileX, missileY)
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a or event.key == pygame.K_d:
                playerX_change = 0

    # spaceship boundary
    playerX += playerX_change
    if playerX <= 0:
        playerX = 0
    elif playerX >= 740:
        playerX = 740
    # enemy movement
    for i in range(num_of_enemies):
        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = 2
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 740:
            enemyX_change[i] = -2
            enemyY[i] += enemyY_change[i]

        collision = is_collision(enemyX[i], enemyY[i], missileX, missileY)
        if collision:
            missileY = 483
            missile_state = "ready"
            score += 1
            print(score)
            enemyX[i] = random.randint(0, 735)
            enemyY[i] = random.randint(40, 100)

        enemy(enemyX[i], enemyY[i], i)

    # missile movement
    if missileY < -10:
        missileY = 483
        missile_state = "ready"
    if missile_state is "fire":
        fire_missile(missileX, missileY)
        missileY -= missileY_change

    collision = is_collision(enemyX[i], enemyY[i], missileX, missileY)
    if collision:
        missileY = 483
        missile_state = "ready"
        score += 1
        print(score)
        enemyX = random.randint(0, 735)
        enemyY = random.randint(40, 100)

    player(playerX, playerY)
    pygame.display.update()

Thanks for any help I can't figure it out.

Body:
enemyX = random.randint(0, 735)
enemyY = random.randint(40, 100)

I think you have to change this lines to something like this.

enemyX[i] = random.randint(0, 735)
enemyY[i] = random.randint(40, 100)

Otherwise you turn the array to an integer.