问:
Issue with rails s (with sass apparently)
I tried to run rails s but sudently I'm getting an error message:

```<code>/home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': cannot load such file -- sass (LoadError)
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
        from
.....
</code>```

I know that there's something about sass about how it's going to disapear or something and I don't know if it's linked

Thanks if you can help :)

EDIT

here's my full Gemfile:

```<code>source 'https://rubygems.org'
ruby '2.4.5'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'rails', '5.2.1'
gem 'redis'

gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3'
gem 'font-awesome-sass', '~> 5.0.9'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'
gem 'devise'
gem 'money-rails'
gem "pundit"

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'
end
</code>```

答:
I deleted all of the files within the tmp folder.

And it worked!

Body:
I tried to run rails s but sudently I'm getting an error message:

/home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/bootsnap-1.3.2/lib/bootsnap/load_path_cache/core_ext/kernel_require.rb:32:in `require': cannot load such file -- sass (LoadError)
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:287:in `block in require'
        from /home/leiver/.rbenv/versions/2.4.5/lib/ruby/gems/2.4.0/gems/activesupport-5.2.1/lib/active_support/dependencies.rb:253:in `load_dependency'
        from
.....

I know that there's something about sass about how it's going to disapear or something and I don't know if it's linked

Thanks if you can help :)

EDIT

here's my full Gemfile:

source 'https://rubygems.org'
ruby '2.4.5'

gem 'bootsnap', require: false
gem 'jbuilder', '~> 2.0'
gem 'pg', '~> 0.21'
gem 'puma'
gem 'rails', '5.2.1'
gem 'redis'

gem 'autoprefixer-rails'
gem 'bootstrap-sass', '~> 3.3'
gem 'font-awesome-sass', '~> 5.0.9'
gem 'sassc-rails'
gem 'simple_form'
gem 'uglifier'
gem 'webpacker'
gem 'devise'
gem 'money-rails'
gem "pundit"

group :development do
  gem 'web-console', '>= 3.3.0'
end

group :development, :test do
  gem 'pry-byebug'
  gem 'pry-rails'
  gem 'listen', '~> 3.0.5'
  gem 'spring'
  gem 'spring-watcher-listen', '~> 2.0.0'
  gem 'dotenv-rails'
end


来源: stackexchange

问:
How do I deal with WS-Security when all I have is a wsdl?
I'm trying to develop a stand-alone client app that uses web services in a Glassfish container (Metro). About all I have to work from is a wsdl for the wervices I'm trying to use. The wsdl is rife with all kinds of 'wsp:Policy' tags. Looks like IssuedToken, Trust13, ecryption are all utilized.
So I generated some code from netbeans and JAX-WS. Everything went well, but when trying to run the client I get:
'WST0029:STS location could not be obtained from either IssuedToken or from client configuration for accessing the service http://localhost:8080/ ....'

That's when it occured to me that I know nothing about WSS. It doesn't look like any code was generated to deal with security. So, I'll have to go from scratch.
So where to start? Books? Tutorials?

TIA

答:
Metro applies the policy in runtime from either the WSDL or the wsit-client.xml config file. That's why no code is generated related to policies. According to this post it is not possible at the moment to do programatically.

This tutorial explains pretty well some of the things you can do with WSS, and though everything do probably not apply in this case it's still a good read.

The simplest way I've found of generating a client with WSS support is by using the wsimport script from Metro:

```<code>cd metro/bin/
mkdir src target
./wsimport.sh -s src -d target -extension -Xendorsed -verbose YourService.wsdl
</code>```

Then install Metro into your application server (copy the libs to the correct places or run the ant script):

```<code>ant -f metro-on-glassfish.xml
</code>```

Then put your local WSDL file in your classpath (e.g. your resource folder), so Metro can get it at runtime to apply the policies from your generated YourService class:

```<code>private final static URL YOURSERVICE_WSDL_LOCATION;

// This is enough, you don't need the wsdlLocation attribute
// on the @WebServiceClient annotation if you have this.
static {
    YOURSERVICE_WSDL_LOCATION =
        CustomerService.class.getClassLoader().getResource("YourService.wsdl");
}

public YourService() {
    super(YOURSERVICE_WSDL_LOCATION,
            new QName("http://tempuri.org/", "YourService"));
}
</code>```

And if you want WS-Addressing you might need to add the feature manually to your binding method (Metro has never generated it for me, so I always have to add it myself).

```<code>@WebEndpoint(name = "WSHttpBinding_IYourService")
public IYourService getWSHttpBindingIYourService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    IYourService service =
        super.getPort(new QName("http://xmlns.example.com/services/Your",
                "WSHttpBinding_IYourService"), IYourService.class,
                wsAddressing);

    return service;
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Metro applies the policy in runtime from either the WSDL or the wsit-client.xml config file. That's why no code is generated related to policies. According to this post it is not possible at the moment to do programatically.

This tutorial explains pretty well some of the things you can do with WSS, and though everything do probably not apply in this case it's still a good read.

The simplest way I've found of generating a client with WSS support is by using the wsimport script from Metro:

cd metro/bin/
mkdir src target
./wsimport.sh -s src -d target -extension -Xendorsed -verbose YourService.wsdl

Then install Metro into your application server (copy the libs to the correct places or run the ant script):

ant -f metro-on-glassfish.xml

Then put your local WSDL file in your classpath (e.g. your resource folder), so Metro can get it at runtime to apply the policies from your generated YourService class:

private final static URL YOURSERVICE_WSDL_LOCATION;

// This is enough, you don't need the wsdlLocation attribute
// on the @WebServiceClient annotation if you have this.
static {
    YOURSERVICE_WSDL_LOCATION =
        CustomerService.class.getClassLoader().getResource("YourService.wsdl");
}

public YourService() {
    super(YOURSERVICE_WSDL_LOCATION,
            new QName("http://tempuri.org/", "YourService"));
}

And if you want WS-Addressing you might need to add the feature manually to your binding method (Metro has never generated it for me, so I always have to add it myself).

@WebEndpoint(name = "WSHttpBinding_IYourService")
public IYourService getWSHttpBindingIYourService() {
    WebServiceFeature wsAddressing = new AddressingFeature(true);

    IYourService service =
        super.getPort(new QName("http://xmlns.example.com/services/Your",
                "WSHttpBinding_IYourService"), IYourService.class,
                wsAddressing);

    return service;
}

ContentLicense: CC BY-SA 3.0


问:
How to display scroll bar in flexible height with parent component is flex: 1
This is code example.

header

test

test

test

test

test

test

```
```.panel {
    flex: 1;
    width: 300px;
    display: flex;
    flex-direction: column;
    .content {
      flex: 1;
      background: #a1a1a1;
      overflow: auto;
      li {
          display: flex;
          align-items: center;
          height: 20vh;
      }
    }
}
```

More detail in codepen.io

I know it would be work with max-height:<number>px

But I want to panel's height flexible.
How to display scroll bar on panel content only ?

答:
Firstly - your html is invalid - the only valid parent of an li is a ul

To answer your question - you need to set a height (in px / % / em / rem of an ancestor element and then just setting height to 100% on your content will allow it to have overflow.

.panel {
height: 10rem;
overflow: hidden;
border: solid 1px blue
}

.header {
 padding: 8px 16px;
}
.content {
 height: 100%;
  border: solid 1px red;
  background: #a1a1a1;
  overflow: auto;
}

li {
    display: flex;
    align-items: center;
    height: 20vh;
    border: solid 1px black
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><main>
    <div class="panel">
      <div class="header">header</div>
      <div class="content">
        <ul>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
        </ul>
       </div>
    </div>
</main></code>```

ContentLicense: CC BY-SA 4.0

Body:
This is code example.

header

test

test

test

test

test

test

.panel {
    flex: 1;
    width: 300px;
    display: flex;
    flex-direction: column;
    .content {
      flex: 1;
      background: #a1a1a1;
      overflow: auto;
      li {
          display: flex;
          align-items: center;
          height: 20vh;
      }
    }
}

More detail in codepen.io

I know it would be work with max-height:<number>px

But I want to panel's height flexible.
How to display scroll bar on panel content only ?

Body:
Firstly - your html is invalid - the only valid parent of an li is a ul

To answer your question - you need to set a height (in px / % / em / rem of an ancestor element and then just setting height to 100% on your content will allow it to have overflow.

.panel {
height: 10rem;
overflow: hidden;
border: solid 1px blue
}

.header {
 padding: 8px 16px;
}
.content {
 height: 100%;
  border: solid 1px red;
  background: #a1a1a1;
  overflow: auto;
}

li {
    display: flex;
    align-items: center;
    height: 20vh;
    border: solid 1px black
}

<main>
    <div class="panel">
      <div class="header">header</div>
      <div class="content">
        <ul>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
          <li>test</li>
        </ul>
       </div>
    </div>
</main>


问:
Java one shot timer to terminate main function
I implemented a simple timer with Observer pattern. I wanted to terminate the main function when 5 minutes passes while it is running. Basically what I need is a simple one shot timeout functionality. How can I achieve this? My code is not working. Below is the timer class

```<code>public class OneShotTimer  extends Observable implements Runnable{

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        Thread.sleep(30);
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("Exception in timer");
    }
    notifyObservers();
}
</code>```

In main class's constructor I initialize that timer.

```<code>public GreenOverlayMain(){
    timer = new OneShotTimer();
    timer.addObserver(this);
    Thread t = new Thread(timer, "mythread");
    t.start();
}
</code>```

However the update() function of main class is never executed because timeout never happens. MainClass implements Observer interface. Below is the update function.

```<code>@Override
public void update(Observable o, Object arg) {
    // TODO Auto-generated method stub
    System.gc();
    System.exit(0);
}
</code>```

答:
Here is a reusable OneShotTimer.

    new OneShotTimer(3, () -> setChange());
```
<pre class="lang-java prettyprint-override"><code>import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OneShotTimer
{

    final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);

    /// Call [callback] after [duration] seconds.
    public OneShotTimer(int duration, OneShotCallback callback)
    {
        sheduler.schedule(() -> _callback(callback), duration, TimeUnit.SECONDS);
    }

    void _callback(OneShotCallback callback)
    {
        sheduler.shutdown();
        callback.callback();
    }

    public interface OneShotCallback
    {
        void callback();
    }

}

</code>```

Body:
I implemented a simple timer with Observer pattern. I wanted to terminate the main function when 5 minutes passes while it is running. Basically what I need is a simple one shot timeout functionality. How can I achieve this? My code is not working. Below is the timer class

public class OneShotTimer  extends Observable implements Runnable{

@Override
public void run() {
    // TODO Auto-generated method stub
    try {
        Thread.sleep(30);
    } catch (Exception e) {
        // TODO: handle exception
        System.out.println("Exception in timer");
    }
    notifyObservers();
}

In main class's constructor I initialize that timer.

public GreenOverlayMain(){
    timer = new OneShotTimer();
    timer.addObserver(this);
    Thread t = new Thread(timer, "mythread");
    t.start();
}

However the update() function of main class is never executed because timeout never happens. MainClass implements Observer interface. Below is the update function.

@Override
public void update(Observable o, Object arg) {
    // TODO Auto-generated method stub
    System.gc();
    System.exit(0);
}

Body:
Here is a reusable OneShotTimer.

    new OneShotTimer(3, () -> setChange());

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class OneShotTimer
{

    final ScheduledExecutorService sheduler = Executors.newScheduledThreadPool(1);

    /// Call [callback] after [duration] seconds.
    public OneShotTimer(int duration, OneShotCallback callback)
    {
        sheduler.schedule(() -> _callback(callback), duration, TimeUnit.SECONDS);
    }

    void _callback(OneShotCallback callback)
    {
        sheduler.shutdown();
        callback.callback();
    }

    public interface OneShotCallback
    {
        void callback();
    }

}


问:
Local Gitlab Container Registry behind reverse proxy
I've installed a local Gitlab in a docker solution. Then, in another server I got a nginx reverse proxy. From that reverse proxy, nginx listens 443 and 80 ports and Gitlab works just fine. However, I couldn't manage to run gitlab container registry from 6060 port.

Gitlab is working on let's just say https://mygitlab.example.com and the gitlab server ip is 2.2.2.2

docker-compose.yml for gitlab

```<code>version: '3.8'
services:
  web:
    image: 'gitlab/gitlab-ee:latest'
    container_name: gitlab
    restart: unless-stopped
    hostname: 'gitlab.mydomain'
    networks:
      default:
        ipv4_address: 192.168.0.2
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'http://mygitlab.example.com'
    ports:
      - '80:80'
      - '443:443'
      - '6060:6060'
    volumes:
      - '/data/gitlab/config:/etc/gitlab'
      - '/data/gitlab/logs:/var/log/gitlab'
      - '/data/gitlab/data:/var/opt/gitlab'
      - '/data/gitlab/registry:/var/opt/gitlab/gitlab-rails/shared/registry'
    healthcheck:
      test: curl -s http://localhost:80 >/dev/null; if [[$$? == 52 ]]; then echo 0; else echo 1; fi
      interval: 30s
      timeout: 10s
      retries: 5
networks:
  default:
    external:
      name: gitlab_network
</code>```

Here is my gitlab.rb file configuration for registry:

```<code>registry_external_url 'https://mygitlab.example.com:6060'
gitlab_rails['registry_enabled'] = true
gitlab_rails['registry_host'] = "mygitlab.example.com"
gitlab_rails['registry_port'] = "6060"
gitlab_rails['registry_path'] = "/var/opt/gitlab/gitlab-rails/shared/registry"
</code>```

Here is my nginx reverse proxy conf:

```<code>server {
        listen 6060 ssl;
        server_name  mygitlab.example.com;
        ssl_certificate      /etc/nginx/certs/example_com_2021.crt;
        ssl_certificate_key  /etc/nginx/private/example_com_private_key.key;
        location / {
                client_max_body_size 10m;
                proxy_pass http://2.2.2.2:6060;
        }
}
</code>```

Then when I reconfigure the gitlab and reload the nginx, I can see that reverse proxy listens 6060 port and sends the gitlab server. I can see the traffic with tcpdump and seems okay.  Also on the Gitlab web interface, registry seems working.

However when I try to login from a client machine, I got the following error:

Error response from daemon: login attempt to http://mygitlab.example.com:6060/v2/ failed with status: 400 Bad Request

What am I missing?

答:
I had similar issues with running Gitlab behind Nginx Proxy Manager . This is the configuration which solved it for me:

docker-compose.yml

```<code>version: '2.1'
services:
  gitlab:
    image: 'gitlab/gitlab-ce:latest'
    restart: always
    hostname: 'gitlab.domain.ch'
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'https://gitlab.domain.ch'
        letsencrypt['enabled'] = false
        # Reverse proxy nginx config
        nginx['listen_port'] = 80
        nginx['listen_https'] = false
        nginx['redirect_http_to_https'] = false
        nginx['proxy_set_headers'] = {
          "X-Forwarded-Proto" => "https",
          "X-Forwarded-Ssl" => "on",
          "Host" => "gitlab.ruckme.ch",
          "X-Real-IP" => "$$remote_addr",
          "X-Forwarded-For" => "$$proxy_add_x_forwarded_for",
          "Upgrade" => "$$http_upgrade",
          "Connection" => "$$connection_upgrade"
        }
    volumes:
      - './data/config:/etc/gitlab'
      - './data/logs:/var/log/gitlab'
      - './data/data:/var/opt/gitlab'
    networks:
      - proxy
networks:
  proxy:
    external: true

</code>```

nginx-proxy-manager settings

is also in the proxy network

Details

domain name: gitlab.domain.ch

Scheme: http

Forward Hostname: gitlab

Forward Port: 80

Block Common Exploits: enable

Websockets Support: enable

SSL

Force SSL: enable

HTTP/2 Support: enable

HSTS Enabled: enable

source: https://techoverflow.net/2018/12/17/running-gitlab-ce-via-docker-behind-a-reverse-proxy-on-ubuntu/

Body:
I've installed a local Gitlab in a docker solution. Then, in another server I got a nginx reverse proxy. From that reverse proxy, nginx listens 443 and 80 ports and Gitlab works just fine. However, I couldn't manage to run gitlab container registry from 6060 port.

Gitlab is working on let's just say https://mygitlab.example.com and the gitlab server ip is 2.2.2.2

docker-compose.yml for gitlab

version: '3.8'
services:
  web:
    image: 'gitlab/gitlab-ee:latest'
    container_name: gitlab
    restart: unless-stopped
    hostname: 'gitlab.mydomain'
    networks:
      default:
        ipv4_address: 192.168.0.2
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'http://mygitlab.example.com'
    ports:
      - '80:80'
      - '443:443'
      - '6060:6060'
    volumes:
      - '/data/gitlab/config:/etc/gitlab'
      - '/data/gitlab/logs:/var/log/gitlab'
      - '/data/gitlab/data:/var/opt/gitlab'
      - '/data/gitlab/registry:/var/opt/gitlab/gitlab-rails/shared/registry'
    healthcheck:
      test: curl -s http://localhost:80 >/dev/null; if [[$$? == 52 ]]; then echo 0; else echo 1; fi
      interval: 30s
      timeout: 10s
      retries: 5
networks:
  default:
    external:
      name: gitlab_network

Here is my gitlab.rb file configuration for registry:

registry_external_url 'https://mygitlab.example.com:6060'
gitlab_rails['registry_enabled'] = true
gitlab_rails['registry_host'] = "mygitlab.example.com"
gitlab_rails['registry_port'] = "6060"
gitlab_rails['registry_path'] = "/var/opt/gitlab/gitlab-rails/shared/registry"

Here is my nginx reverse proxy conf:

server {
        listen 6060 ssl;
        server_name  mygitlab.example.com;
        ssl_certificate      /etc/nginx/certs/example_com_2021.crt;
        ssl_certificate_key  /etc/nginx/private/example_com_private_key.key;
        location / {
                client_max_body_size 10m;
                proxy_pass http://2.2.2.2:6060;
        }
}

Then when I reconfigure the gitlab and reload the nginx, I can see that reverse proxy listens 6060 port and sends the gitlab server. I can see the traffic with tcpdump and seems okay.  Also on the Gitlab web interface, registry seems working.

However when I try to login from a client machine, I got the following error:

Error response from daemon: login attempt to http://mygitlab.example.com:6060/v2/ failed with status: 400 Bad Request

What am I missing?

Body:
I had similar issues with running Gitlab behind Nginx Proxy Manager . This is the configuration which solved it for me:

docker-compose.yml

version: '2.1'
services:
  gitlab:
    image: 'gitlab/gitlab-ce:latest'
    restart: always
    hostname: 'gitlab.domain.ch'
    environment:
      GITLAB_OMNIBUS_CONFIG: |
        external_url 'https://gitlab.domain.ch'
        letsencrypt['enabled'] = false
        # Reverse proxy nginx config
        nginx['listen_port'] = 80
        nginx['listen_https'] = false
        nginx['redirect_http_to_https'] = false
        nginx['proxy_set_headers'] = {
          "X-Forwarded-Proto" => "https",
          "X-Forwarded-Ssl" => "on",
          "Host" => "gitlab.ruckme.ch",
          "X-Real-IP" => "$$remote_addr",
          "X-Forwarded-For" => "$$proxy_add_x_forwarded_for",
          "Upgrade" => "$$http_upgrade",
          "Connection" => "$$connection_upgrade"
        }
    volumes:
      - './data/config:/etc/gitlab'
      - './data/logs:/var/log/gitlab'
      - './data/data:/var/opt/gitlab'
    networks:
      - proxy
networks:
  proxy:
    external: true

nginx-proxy-manager settings

is also in the proxy network

Details

domain name: gitlab.domain.ch

Scheme: http

Forward Hostname: gitlab

Forward Port: 80

Block Common Exploits: enable

Websockets Support: enable

SSL

Force SSL: enable

HTTP/2 Support: enable

HSTS Enabled: enable

source: https://techoverflow.net/2018/12/17/running-gitlab-ce-via-docker-behind-a-reverse-proxy-on-ubuntu/


问:
FileNotFoundError in Python Visul Studio
I get this when I try to run my python project code

with open("config.json", "r") as f:
```
<p>Exception raised:</p>
<pre class="lang-py prettyprint-override"><code>FileNotFoundError: [Errno 2] No such file or directory: 'config.json'
</code>```

what is a solution for this?

here is a screenshot of the code and everything.

答:
the file config.jason needs to be in your current working directory to be found by open if you do not use a full path.  Your cwd is probably where you launched python.  To check do

```<code>    import os
    print(os.getcwd())
</code>```

Your easiest solution is probably to use a full path name for the file.

Body:
I get this when I try to run my python project code

with open("config.json", "r") as f:

Exception raised:

FileNotFoundError: [Errno 2] No such file or directory: 'config.json'

what is a solution for this?

here is a screenshot of the code and everything.

Body:
the file config.jason needs to be in your current working directory to be found by open if you do not use a full path.  Your cwd is probably where you launched python.  To check do

    import os
    print(os.getcwd())

Your easiest solution is probably to use a full path name for the file.


问:
notify application directly when you delete a user in the firebase console?
Is there a way to notify the application directly if you delete a user from firebase using the firebase console? I have tried with an authlistener but the application does not notice the change in current user when I delete the user. I have to reinstall the application for the application to notice that there is no user anymore? Is there a way to solve this?

What I have tried

```<code>override fun getFirebaseAuthState() = callbackFlow {
    val authStateListener = FirebaseAuth.AuthStateListener { auth ->
        trySend(auth.currentUser == null)
    }
    auth.checkIfUserExists().addAuthStateListener(authStateListener)
       awaitClose {
         auth.checkIfUserExists().removeAuthStateListener(authStateListener)
       }
}
</code>```

The viewModel calling it

```<code>   init {
        getAuthState()
    }

    fun getAuthState() = liveData{
        useCases.getAuthState().collect{response ->
            emit(response)
        }

    }
</code>```

答:
The authentication state on the client is based on an ID token, that is valid for one hour and automatically refreshed by the SDK. When you delete (or disable) the user, the client can no longer refresh the ID token, but its current ID token will be valid for up to an hour.

You can force the client to try and refresh its token before that, but Firebase has no built-in way to immediately notify the client of the (so-called out-of-band) user deletion.

If you want to mark the user's ID token is having become invalid, have a look at the Firebase documentation on ID token revocation or one of these questions:

When a Firebase user is deleted from Firebase console (after user login), it is not reflected in the application

Firebase authentication not revoked when user deleted?

Why firebase user still signed in after I deleted it from firebase dashboard

Deletion of User in firebase does not trigger onAuth method

Body:
Is there a way to notify the application directly if you delete a user from firebase using the firebase console? I have tried with an authlistener but the application does not notice the change in current user when I delete the user. I have to reinstall the application for the application to notice that there is no user anymore? Is there a way to solve this?

What I have tried

override fun getFirebaseAuthState() = callbackFlow {
    val authStateListener = FirebaseAuth.AuthStateListener { auth ->
        trySend(auth.currentUser == null)
    }
    auth.checkIfUserExists().addAuthStateListener(authStateListener)
       awaitClose {
         auth.checkIfUserExists().removeAuthStateListener(authStateListener)
       }
}

The viewModel calling it

   init {
        getAuthState()
    }

    fun getAuthState() = liveData{
        useCases.getAuthState().collect{response ->
            emit(response)
        }

    }


问:
how do i adjust my code to become a recursive reverse sum loop
I have a simple recursion method for reversing a list

lst = [1,2,3,4,5] will print as [5, 4, 3, 2, 1]

lst = [1, 2, 3, 4, 5]

def revlist(lst):
    if len(lst) == 0:
        return []
    else:
        return revlist(lst[1:]) + [lst[0]]

print(revlist(lst))
```

Instead of it printing the reverse list i want it to add 5 + 4 + 3 + 2 + 1 but i dont know how to, at the end I should get 15 but not by just adding the sum of the list, only by adding at the last element and finishing at the first [0] element. Whatever I do to try and sum the array list it gives me errors and I dont really know how I can get any closer to code what I am trying to acheive.

答:
This is a strange requirement, but it could be accomplished like this:

```<code>def revsum(lst):
    if not lst:
        return 0
    return lst[-1] + revsum(lst[:-1])
</code>```

Of course, this is purely academic, and you should never use this in real Python code.

Body:
I have a simple recursion method for reversing a list

lst = [1,2,3,4,5] will print as [5, 4, 3, 2, 1]

lst = [1, 2, 3, 4, 5]

def revlist(lst):
    if len(lst) == 0:
        return []
    else:
        return revlist(lst[1:]) + [lst[0]]

print(revlist(lst))

Instead of it printing the reverse list i want it to add 5 + 4 + 3 + 2 + 1 but i dont know how to, at the end I should get 15 but not by just adding the sum of the list, only by adding at the last element and finishing at the first [0] element. Whatever I do to try and sum the array list it gives me errors and I dont really know how I can get any closer to code what I am trying to acheive.

Body:
This is a strange requirement, but it could be accomplished like this:

def revsum(lst):
    if not lst:
        return 0
    return lst[-1] + revsum(lst[:-1])

Of course, this is purely academic, and you should never use this in real Python code.


问:
TypeScript + React: How do I type a component that passes props to an html `img` element?
I have a simple component Bar that passes props to a

function Bar(props: React.HTMLAttributes<HTMLImageElement>) {
  return ;
}
```

Ideally when I use <Bar /> it should asks me to pass src and alt for the underlying img tag but it is not working that way. Also the autocomplete seems not working.

Live demo: https://codesandbox.io/s/type-images-66y2s?file=/src/App.tsx

Any ideas?

答:
Try the below code to define props for your Bar component</p>
```<code>function Bar(
props: React.DetailedHTMLProps<
    React.ImgHTMLAttributes<HTMLImageElement>,
    HTMLImageElement
>,) {
return <img {...props} />;
}
</code>```

Body:
I have a simple component Bar that passes props to a

function Bar(props: React.HTMLAttributes<HTMLImageElement>) {
  return ;
}

Ideally when I use <Bar /> it should asks me to pass src and alt for the underlying img tag but it is not working that way. Also the autocomplete seems not working.

Live demo: https://codesandbox.io/s/type-images-66y2s?file=/src/App.tsx

Any ideas?

Body:
Try the below code to define props for your Bar component

function Bar(
props: React.DetailedHTMLProps<
    React.ImgHTMLAttributes<HTMLImageElement>,
    HTMLImageElement
>,) {
return <img {...props} />;
}


问:
Merge 2 Arrays and Sum the Values (Numeric Keys)
I have 2 arrays

```<code>Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)
</code>```

Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:

```<code>Array
(
    [010156] => Array
    (
        [supp_number] =>  <<<TOTAL >>>
        [totalamount] =>     <<<TOTAL >>>
        [debtorcred] => <<<TOTAL >>>
        [amount1] =>      <<<TOTAL >>>
        [amount2] =>  <<<TOTAL >>>

        [amount3] =>  <<<TOTAL >>>
        [amount4] =>  <<<TOTAL >>>
        [amount5] =>  <<<TOTAL >>>
        [amount6] =>  <<<TOTAL >>>
    )
)
</code>```

This is the function I have at the moment but I cannot seem to make it work:

```<code>function array_merge_numeric_values()
{
  $arrays = func_get_args();
  $merged = array();
  foreach ($arrays as $array)
  {
    foreach ($array as $key => $value)
    {
      if ( ! isset($merged[$key]))
      {
        $merged[$key] = $value;
      }
      else
      {
        $merged[$key] += $value;
      }
    }
  }
</code>```

答:
$value in your case is an array, not a value. You can try this:

```<code>function array_merge_numeric_values()
{
    $arrays = func_get_args();

    $merged = array();
    foreach ($arrays as $array)
    {
        foreach ($array as $key => $value)
        {
            if(!isset($merged[$key]))
            {
                $merged[$key] = array();
            }

            foreach($value as $kk => $vv)
            {
                if ( ! isset($merged[$key][$kk]))
                {
                    $merged[$key][$kk] = $vv;
                }
                else
                {
                    $merged[$key][$kk] += $vv;
                }
            }
        }
    }
}
</code>```

Body:
I have 2 arrays

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Array
(
    [010156] => Array
    (
        [supp_number] => 010156
        [totalamount] =>     4.113,23
        [debtorcred] => H
        [amount1] =>     4.113,23-
        [amount2] =>

        [amount3] =>
        [amount4] =>
        [amount5] =>
        [amount6] =>
    )
)

Is it possible that I can combine these separate arrays into one and add the values together so that the outcome will be:

Array
(
    [010156] => Array
    (
        [supp_number] =>  <<<TOTAL >>>
        [totalamount] =>     <<<TOTAL >>>
        [debtorcred] => <<<TOTAL >>>
        [amount1] =>      <<<TOTAL >>>
        [amount2] =>  <<<TOTAL >>>

        [amount3] =>  <<<TOTAL >>>
        [amount4] =>  <<<TOTAL >>>
        [amount5] =>  <<<TOTAL >>>
        [amount6] =>  <<<TOTAL >>>
    )
)

This is the function I have at the moment but I cannot seem to make it work:

function array_merge_numeric_values()
{
  $arrays = func_get_args();
  $merged = array();
  foreach ($arrays as $array)
  {
    foreach ($array as $key => $value)
    {
      if ( ! isset($merged[$key]))
      {
        $merged[$key] = $value;
      }
      else
      {
        $merged[$key] += $value;
      }
    }
  }

Body:
$value in your case is an array, not a value. You can try this:

function array_merge_numeric_values()
{
    $arrays = func_get_args();

    $merged = array();
    foreach ($arrays as $array)
    {
        foreach ($array as $key => $value)
        {
            if(!isset($merged[$key]))
            {
                $merged[$key] = array();
            }

            foreach($value as $kk => $vv)
            {
                if ( ! isset($merged[$key][$kk]))
                {
                    $merged[$key][$kk] = $vv;
                }
                else
                {
                    $merged[$key][$kk] += $vv;
                }
            }
        }
    }
}


问:
Python logger, relative time (relativeCreated), can the reference be reset?
I note with interest that Python logging class can emit a relative timestamp:

https://docs.python.org/3/library/logging.html#logrecord-attributes

It is provided with the attribute relativeCreated, but this is documented as:

Time in milliseconds when the LogRecord was created, relative to the
  time the logging module was loaded.

I'd wondering there is a way to reset this reference time (which by default is when the logging module was loaded).

I'd like to reset that reference time and see times relative to the point in time I did the reset.

答:
A simple way to rest the time reference is to directly update the module data, which is a "private" logging._startTime variable shown in here in the source code. It can be modified like this:

```<code>import logging
import time

def reset_logging_time_reference():
    logging._startTime = time.time()

# As needed
reset_logging_time_reference()
</code>```

Keep in mind that this is a private variable, which could change with future versions without warning.

Body:
A simple way to rest the time reference is to directly update the module data, which is a "private" logging._startTime variable shown in here in the source code. It can be modified like this:

import logging
import time

def reset_logging_time_reference():
    logging._startTime = time.time()

# As needed
reset_logging_time_reference()

Keep in mind that this is a private variable, which could change with future versions without warning.


答:
Just press cmd on Mac or ctrl on Windows focusing on the img tag and then click the mouse, you will see IntrinsicElements set.

function Bar(props: React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>) {
  return
}
```

Title: TypeScript + React: How do I type a component that passes props to an html `img` element?

Body:
Just press cmd on Mac or ctrl on Windows focusing on the img tag and then click the mouse, you will see IntrinsicElements set.

function Bar(props: React.DetailedHTMLProps<React.ImgHTMLAttributes<HTMLImageElement>, HTMLImageElement>) {
  return <img {...props} />
}


问:
Writing output to a text file using Hadoop Grip command
I have a file in HDFS - /user//SimpleDir/SimpleFile.txt and I'm trying to use Grep command and search for "MapReduce" in that file and print the results to a different file (simpleoutput.txt) in the same directory.

Any help is much appreciated!

答:
You can try the following command

hadoop fs -cat /user/SimpleDir/SimpleFile.txt | grep -i Mapreduce > /user/SimpleDir/simpleoutput.txt


问:
Should we use custom NACL with rules on Port Numbers, if we have a NAT gateway attached to public subnet
Suppose we have a basic architecture, where we have VPC with two subnets(One private and one public). The private subnet is connected to internet with a NAT gateway residing in Public Subnet.(As shown in below image)

Now suppose we implement a Network ACL in public subnet. Would it be wise to deny some ports in it?

The reason I am asking is because I learned that NAT works using Port Numbers to connect many Private IP to Single public IP(Elastic Ip in our case, which is attached to NAT), So wouldn't the NACL create problem.

Here is what I learned about how Nat Functions - https://www.youtube.com/watch?v=01ajHxPLxAw

答:
Yeah we can use NACL but we need to take care that it does not interfere NAT port numbers. Its not just NAT gateway, but other resources might have problem functioning if NACL is not configured properly.

Nat uses Port numbers - 1024-65535.

Source - https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html#nacl-ephemeral-ports


问:
Apply function to all columns in a Postgres table dynamically
Using Postgres 13.1, I want to apply a forward fill function to all columns of a table. The forward fill function is explained in my earlier question:

How to do forward fill as a PL/PGSQL function

However, in that case the columns and table are specified. I want to take that code and apply it to an arbitrary table, ie. specify a table and the forward fill is applied to each of the columns.

Using this table as an example:

```<code>CREATE TABLE example(row_num int, id int, str text, val integer);
INSERT INTO example VALUES
  (1, 1, '1a', NULL)
, (2, 1, NULL,    1)
, (3, 2, '2a',    2)
, (4, 2, NULL, NULL)
, (5, 3, NULL, NULL)
, (6, 3, '3a',   31)
, (7, 3, NULL, NULL)
, (8, 3, NULL,   32)
, (9, 3, '3b', NULL)
, (10,3, NULL, NULL)
;
</code>```

I start with the following working base for the function.  I call it passing in some variable names. Note the first is a table name not a column name. The function takes the table name and creates an array of all the column names and then outputs the names.

```<code>create or replace function col_collect(tbl text, id text, row_num text)
    returns text[]
    language plpgsql as
$func$
declare
    tmp text[];
    col text;
begin
    select array (
            select column_name
            from information_schema."columns" c
            where table_name = tbl
            ) into tmp;
    foreach col in array tmp
    loop
        raise notice 'col: %', col;
    end loop;
    return tmp;
end
$func$;
</code>```

I want to apply the "forward fill" function I got from my earlier question to each column of a table. UPDATE seems to be the correct approach. So this is the preceding function where I replace raise notice by an update using execute so I can pass in the table name:

```<code>create or replace function col_collect(tbl text, id text, row_num text)
    returns void
    language plpgsql as
$func$
declare
    tmp text[];
    col text;
begin
    select array (
            select column_name
            from information_schema."columns" c
            where table_name = tbl
            ) into tmp;
    foreach col in array tmp
    loop
        execute 'update '||tbl||'
                set '||col||' = gapfill('||col||') OVER w AS '||col||'
                where '||tbl||'.row_num = '||col||'.row_num
                window w as (PARTITION BY '||id||' ORDER BY '||row_num||')
                returning *;';
    end loop;
end
$func$;

-- call the function
select col_collect('example','id','row_num')
</code>```

The preceding errors out with a syntax error. I have tried many variations on this but they all fail. Helpful answers on SO were here and here. The aggregate function I'm trying to apply (as window function) is:

```<code>CREATE OR REPLACE FUNCTION gap_fill_internal(s anyelement, v anyelement)
  RETURNS anyelement
  LANGUAGE plpgsql AS
$func$
BEGIN
RETURN COALESCE(v, s);  -- that's all!
END
$func$;

CREATE AGGREGATE gap_fill(anyelement) (
  SFUNC = gap_fill_internal,
  STYPE = anyelement
);
</code>```

My questions are:

is this a good approach and if so what am I doing wrong; or

is there a better way to do this?

答:
What you ask is not a trivial task. You should be comfortable with PL/pgSQL. I do not advise this kind of dynamic SQL queries for beginners, too powerful.

That said, let's dive in. Buckle up!

CREATE OR REPLACE FUNCTION f_gap_fill_update(_tbl regclass, _id text, _row_num text, OUT nullable_columns int, OUT updated_rows int)
  LANGUAGE plpgsql AS
$func$
DECLARE
   _pk  text  := quote_ident(_row_num);
   _sql text;
BEGIN
   SELECT INTO _sql, nullable_columns
          concat_ws(E'\n'
          , 'UPDATE ' || _tbl || ' t'
          , 'SET   (' || string_agg(        quote_ident(a.attname), ', ') || ')'
          , '    = (' || string_agg('u.' || quote_ident(a.attname), ', ') || ')'
          , 'FROM  ('
          , '   SELECT ' || _pk
          , '        , ' || string_agg(format('gap_fill(%1$I) OVER w AS %1$I', a.attname), ', ')
          , '   FROM   ' || _tbl
          , format('   WINDOW w AS (PARTITION BY %I ORDER BY %s)', _id, _pk)
          , '   ) u'
          , format('WHERE t.%1$s = u.%1$s', _pk)
          , 'AND  (' || string_agg('t.' || quote_ident(a.attname), ', ') || ') IS DISTINCT FROM'
          , '     (' || string_agg('u.' || quote_ident(a.attname), ', ') || ')'
          )
        , count(*) -- AS _col_ct
   FROM  (
      SELECT a.attname
      FROM   pg_attribute a
      WHERE  a.attrelid = _tbl
      AND    a.attnum > 0
      AND    NOT a.attisdropped
      AND    NOT a.attnotnull
      ORDER  BY a.attnum
      ) a;

   IF nullable_columns = 0 THEN
      RAISE EXCEPTION 'No nullable columns found in table >>%<<', _tbl;
   ELSIF _sql IS NULL THEN
      RAISE EXCEPTION 'SQL string is NULL. Should not occur!';
   END IF;

   -- RAISE NOTICE '%', _sql;       -- debug
   EXECUTE _sql;              -- execute
   GET DIAGNOSTICS updated_rows = ROW_COUNT;
END
$func$;
```
<p>Example call:</p>
```SELECT * FROM f_gap_fill_update('example', 'id', 'row_num');
```
<p><em>db<>fiddle here</em></p>
<p>The function is state of the art.
Generates <em><strong>and</strong></em> executes a query of the form:</p>
<pre class="lang-sql prettyprint-override"><code>UPDATE tbl t
SET   (str, val, col1)
    = (u.str, u.val, u.col1)
FROM  (
   SELECT row_num
        , gap_fill(str) OVER w AS str, gap_fill(val) OVER w AS val
        , gap_fill(col1) OVER w AS col1
   FROM   tbl
   WINDOW w AS (PARTITION BY id ORDER BY row_num)
   ) u
WHERE t.row_num = u.row_num
AND  (t.str, t.val, t.col1) IS DISTINCT FROM
     (u.str, u.val, u.col1)
</code>```

Using pg_catalog.pg_attribute instead of the information schema. See:

"Information schema vs. system catalogs"

Note the final WHERE clause to prevent (possibly expensive) empty updates. Only rows that actually change will be written. See:

How do I (or can I) SELECT DISTINCT on multiple columns?

Moreover, only nullable columns (not defined NOT NULL) will even be considered, to avoid unnecessary work.

Using ROW syntax in UPDATE to keep the code simple. See:

SQL update fields of one table from fields of another one

The function returns two integer values: nullable_columns and updated_rows, reporting what the names suggest.

The function defends against SQL injection properly. See:

Table name as a PostgreSQL function parameter

SQL injection in Postgres functions vs prepared queries

About GET DIAGNOSTICS:

Calculate number of rows affected by batch query in PostgreSQL

The above function updates, but does not return rows. Here is a basic demo how to return rows of varying type:

CREATE OR REPLACE FUNCTION f_gap_fill_select(_tbl_type anyelement, _id text, _row_num text)
  RETURNS SETOF anyelement
  LANGUAGE plpgsql AS
$func$
DECLARE
   _tbl regclass := pg_typeof(_tbl_type)::text::regclass;
   _sql text;
BEGIN
   SELECT INTO _sql
          'SELECT ' || string_agg(CASE WHEN a.attnotnull
                                  THEN format('%I', a.attname)
                                  ELSE format('gap_fill(%1$I) OVER w AS %1$I', a.attname) END
                                , ', ' ORDER BY a.attnum)
        || E'\nFROM ' || _tbl
        || format(E'\nWINDOW w AS (PARTITION BY %I ORDER BY %I)', _id, _row_num)
   FROM   pg_attribute a
   WHERE  a.attrelid = _tbl
   AND    a.attnum > 0
   AND    NOT a.attisdropped;

   IF _sql IS NULL THEN
      RAISE EXCEPTION 'SQL string is NULL. Should not occur!';
   END IF;

   RETURN QUERY EXECUTE _sql;
   -- RAISE NOTICE '%', _sql;       -- debug
END
$func$;
```
<p>Call (note special syntax!):</p>
```SELECT * FROM f_gap_fill_select(NULL::example, 'id', 'row_num');
```

db<>fiddle here

About returning a polymorphic row type:

Refactor a PL/pgSQL function to return the output of various SELECT queries

Body:
Using Postgres 13.1, I want to apply a forward fill function to all columns of a table. The forward fill function is explained in my earlier question:

How to do forward fill as a PL/PGSQL function

However, in that case the columns and table are specified. I want to take that code and apply it to an arbitrary table, ie. specify a table and the forward fill is applied to each of the columns.

Using this table as an example:

CREATE TABLE example(row_num int, id int, str text, val integer);
INSERT INTO example VALUES
  (1, 1, '1a', NULL)
, (2, 1, NULL,    1)
, (3, 2, '2a',    2)
, (4, 2, NULL, NULL)
, (5, 3, NULL, NULL)
, (6, 3, '3a',   31)
, (7, 3, NULL, NULL)
, (8, 3, NULL,   32)
, (9, 3, '3b', NULL)
, (10,3, NULL, NULL)
;

I start with the following working base for the function.  I call it passing in some variable names. Note the first is a table name not a column name. The function takes the table name and creates an array of all the column names and then outputs the names.

create or replace function col_collect(tbl text, id text, row_num text)
    returns text[]
    language plpgsql as
$func$
declare
    tmp text[];
    col text;
begin
    select array (
            select column_name
            from information_schema."columns" c
            where table_name = tbl
            ) into tmp;
    foreach col in array tmp
    loop
        raise notice 'col: %', col;
    end loop;
    return tmp;
end
$func$;

I want to apply the "forward fill" function I got from my earlier question to each column of a table. UPDATE seems to be the correct approach. So this is the preceding function where I replace raise notice by an update using execute so I can pass in the table name:

create or replace function col_collect(tbl text, id text, row_num text)
    returns void
    language plpgsql as
$func$
declare
    tmp text[];
    col text;
begin
    select array (
            select column_name
            from information_schema."columns" c
            where table_name = tbl
            ) into tmp;
    foreach col in array tmp
    loop
        execute 'update '||tbl||'
                set '||col||' = gapfill('||col||') OVER w AS '||col||'
                where '||tbl||'.row_num = '||col||'.row_num
                window w as (PARTITION BY '||id||' ORDER BY '||row_num||')
                returning *;';
    end loop;
end
$func$;

-- call the function
select col_collect('example','id','row_num')

The preceding errors out with a syntax error. I have tried many variations on this but they all fail. Helpful answers on SO were here and here. The aggregate function I'm trying to apply (as window function) is:

CREATE OR REPLACE FUNCTION gap_fill_internal(s anyelement, v anyelement)
  RETURNS anyelement
  LANGUAGE plpgsql AS
$func$
BEGIN
RETURN COALESCE(v, s);  -- that's all!
END
$func$;

CREATE AGGREGATE gap_fill(anyelement) (
  SFUNC = gap_fill_internal,
  STYPE = anyelement
);

My questions are:

is this a good approach and if so what am I doing wrong; or

is there a better way to do this?

Body:
What you ask is not a trivial task. You should be comfortable with PL/pgSQL. I do not advise this kind of dynamic SQL queries for beginners, too powerful.

That said, let's dive in. Buckle up!

CREATE OR REPLACE FUNCTION f_gap_fill_update(_tbl regclass, _id text, _row_num text, OUT nullable_columns int, OUT updated_rows int)
  LANGUAGE plpgsql AS
$func$
DECLARE
   _pk  text  := quote_ident(_row_num);
   _sql text;
BEGIN
   SELECT INTO _sql, nullable_columns
          concat_ws(E'\n'
          , 'UPDATE ' || _tbl || ' t'
          , 'SET   (' || string_agg(        quote_ident(a.attname), ', ') || ')'
          , '    = (' || string_agg('u.' || quote_ident(a.attname), ', ') || ')'
          , 'FROM  ('
          , '   SELECT ' || _pk
          , '        , ' || string_agg(format('gap_fill(%1$I) OVER w AS %1$I', a.attname), ', ')
          , '   FROM   ' || _tbl
          , format('   WINDOW w AS (PARTITION BY %I ORDER BY %s)', _id, _pk)
          , '   ) u'
          , format('WHERE t.%1$s = u.%1$s', _pk)
          , 'AND  (' || string_agg('t.' || quote_ident(a.attname), ', ') || ') IS DISTINCT FROM'
          , '     (' || string_agg('u.' || quote_ident(a.attname), ', ') || ')'
          )
        , count(*) -- AS _col_ct
   FROM  (
      SELECT a.attname
      FROM   pg_attribute a
      WHERE  a.attrelid = _tbl
      AND    a.attnum > 0
      AND    NOT a.attisdropped
      AND    NOT a.attnotnull
      ORDER  BY a.attnum
      ) a;

   IF nullable_columns = 0 THEN
      RAISE EXCEPTION 'No nullable columns found in table >>%<<', _tbl;
   ELSIF _sql IS NULL THEN
      RAISE EXCEPTION 'SQL string is NULL. Should not occur!';
   END IF;

   -- RAISE NOTICE '%', _sql;       -- debug
   EXECUTE _sql;              -- execute
   GET DIAGNOSTICS updated_rows = ROW_COUNT;
END
$func$;

Example call:

SELECT * FROM f_gap_fill_update('example', 'id', 'row_num');

db<>fiddle here

The function is state of the art.
Generates and executes a query of the form:

UPDATE tbl t
SET   (str, val, col1)
    = (u.str, u.val, u.col1)
FROM  (
   SELECT row_num
        , gap_fill(str) OVER w AS str, gap_fill(val) OVER w AS val
        , gap_fill(col1) OVER w AS col1
   FROM   tbl
   WINDOW w AS (PARTITION BY id ORDER BY row_num)
   ) u
WHERE t.row_num = u.row_num
AND  (t.str, t.val, t.col1) IS DISTINCT FROM
     (u.str, u.val, u.col1)

Using pg_catalog.pg_attribute instead of the information schema. See:

"Information schema vs. system catalogs"

Note the final WHERE clause to prevent (possibly expensive) empty updates. Only rows that actually change will be written. See:

How do I (or can I) SELECT DISTINCT on multiple columns?

Moreover, only nullable columns (not defined NOT NULL) will even be considered, to avoid unnecessary work.

Using ROW syntax in UPDATE to keep the code simple. See:

SQL update fields of one table from fields of another one

The function returns two integer values: nullable_columns and updated_rows, reporting what the names suggest.

The function defends against SQL injection properly. See:

Table name as a PostgreSQL function parameter

SQL injection in Postgres functions vs prepared queries

About GET DIAGNOSTICS:

Calculate number of rows affected by batch query in PostgreSQL

The above function updates, but does not return rows. Here is a basic demo how to return rows of varying type:

CREATE OR REPLACE FUNCTION f_gap_fill_select(_tbl_type anyelement, _id text, _row_num text)
  RETURNS SETOF anyelement
  LANGUAGE plpgsql AS
$func$
DECLARE
   _tbl regclass := pg_typeof(_tbl_type)::text::regclass;
   _sql text;
BEGIN
   SELECT INTO _sql
          'SELECT ' || string_agg(CASE WHEN a.attnotnull
                                  THEN format('%I', a.attname)
                                  ELSE format('gap_fill(%1$I) OVER w AS %1$I', a.attname) END
                                , ', ' ORDER BY a.attnum)
        || E'\nFROM ' || _tbl
        || format(E'\nWINDOW w AS (PARTITION BY %I ORDER BY %I)', _id, _row_num)
   FROM   pg_attribute a
   WHERE  a.attrelid = _tbl
   AND    a.attnum > 0
   AND    NOT a.attisdropped;

   IF _sql IS NULL THEN
      RAISE EXCEPTION 'SQL string is NULL. Should not occur!';
   END IF;

   RETURN QUERY EXECUTE _sql;
   -- RAISE NOTICE '%', _sql;       -- debug
END
$func$;

Call (note special syntax!):

SELECT * FROM f_gap_fill_select(NULL::example, 'id', 'row_num');

db<>fiddle here

About returning a polymorphic row type:

Refactor a PL/pgSQL function to return the output of various SELECT queries


Title: How would I center a multiline ascii art

Body:
I'm new to C++ I have a ASCII art that looks like this

    string title =
        "  _____ ____  _   _  _____ _      ______  _____ _____ _ \n"
        " / ____/ __ \\| \\ | |/ ____| |    |  ____|/ ____/ ____| |\n"
        "| |   | |  | |  \\| | (___ | |    | |__  | (___| (___ | |\n"
        "| |   | |  | | . ` |\\___ \\| |    |  __|  \\___ \\\\___ \\| |\n"
        "| |___| |__| | |\\  |____) | |____| |____ ____) |___) |_|\n"
        " \\_____\\____/|_| \\_|_____/|______|______|_____/_____/(_)\n";

I want to paste this ASCII art in the console but I don't want it to be on the left side I want it to be centered how would I go about centering this ASCII art in the console.

Body:
Alright I found this solution where you can make a array of the lines of the ascii art and then add 50 spaces before each line.

int main()
{
    string title[6] = {"  _____ ____  _   _  _____ _      ______  _____ _____ _ ", " / ____/ __ \\| \\ | |/ ____| |    |  ____|/ ____/ ____| |", "| |   | |  | |  \\| | (___ | |    | |__  | (___| (___ | |", "| |   | |  | | . ` |\\___ \\| |    |  __|  \\___ \\\\___ \\| |", "| |___| |__| | |\\  |____) | |____| |____ ____) |___) |_|", " \\_____\\____/|_| \\_|_____/|______|______|_____/_____/(_)"};

    for (size_t i = 0; i < 6; i++)
        cout << string(50, ' ') + title[i] << endl;

    return 0;
}


问:
How to format a long adding thousands separator on Arduino
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

```<code>long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string
</code>```

答:
I'm not sure what toolset gets used on Arduino. Sometimes the library will support a non-standard 'thousands grouping' flag - the single-quote character is the typical extension:

```<code>printf("%'ld",long_val);
</code>```

If your library doesn't support this, something like the following might do:

```<code>#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <assert.h>

size_t strlcpy( char* dest, char const* src, size_t dest_size);

size_t format_long( long x, char* buf, size_t bufsize)
{
    // This code assumes 32-bit long, is that the
    // case on Arduino?  Modifying it to be able to
    // handle 64-bit longs (or to not care) should be
    // pretty straightforward if that's necessary.

    char scratch[sizeof("-2,147,483,648")];
    char* p = scratch + sizeof(scratch);    // Work from end of buffer
    int neg = (x < 0);

    // Handle a couple special cases
    if (x == 0) {
        return strlcpy( buf, "0", bufsize);
    }
    if (x == INT_MIN) {
        // Lazy way of handling this special case
        return strlcpy( buf, "-2,147,483,648", bufsize);
    }

    // Work with positive values from here on
    if (x < 0) x = -x;

    int group_counter = 3;
    *(--p) = 0; // Null terminate the scratch buffer

    while (x != 0) {
        int digit = x % 10;
        x = x / 10;

        assert( p != &scratch[0]);
        *(--p) = "0123456789"[digit];

        if ((x != 0) && (--group_counter == 0)) {
            assert( p != &scratch[0]);
            *(--p) = ',';
            group_counter = 3;
        }
    }

    if (neg) {
        assert( p != &scratch[0]);
        *(--p) = '-';
    }
    return strlcpy(buf, p, bufsize);
}

/*
    A non-optimal strlcpy() implementation that helps copying string
    without danger of buffer overflow.

    This is provided just in case you don't have an implementation
    so the code above will actually compile and run.
*/
size_t strlcpy( char* dest, char const* src, size_t dest_size)
{
    size_t len = strlen(src);

    if (dest_size == 0) {
        // nothing to copy - just return how long the buffer should be
        //  (note that the return value doens't include the null terminator)
        return len;
    }

    size_t tocopy = (dest_size <= len) ? dest_size-1 : len;

    memmove( dest, src, tocopy);
    dest[tocopy] = 0;

    return len;
}
</code>```

Body:
I'm developing a project on Arduino that parses some JSON data from a remote web API displaying it on a 16x2 LCD.

I would like to format a long parsed with TextFinder adding the thousands separator (a comma separator would be fine).

In a nutshell, how do I code the formatLong function?

long longToBeFormatted = 32432423;

formattedLong = formatLong(longToBeFormatted); //How to implement this?

lcd.print(formattedLong) // formattedLong is a string

Body:
I'm not sure what toolset gets used on Arduino. Sometimes the library will support a non-standard 'thousands grouping' flag - the single-quote character is the typical extension:

printf("%'ld",long_val);

If your library doesn't support this, something like the following might do:

#include <stddef.h>
#include <string.h>
#include <limits.h>
#include <stdio.h>
#include <assert.h>

size_t strlcpy( char* dest, char const* src, size_t dest_size);

size_t format_long( long x, char* buf, size_t bufsize)
{
    // This code assumes 32-bit long, is that the
    // case on Arduino?  Modifying it to be able to
    // handle 64-bit longs (or to not care) should be
    // pretty straightforward if that's necessary.

    char scratch[sizeof("-2,147,483,648")];
    char* p = scratch + sizeof(scratch);    // Work from end of buffer
    int neg = (x < 0);

    // Handle a couple special cases
    if (x == 0) {
        return strlcpy( buf, "0", bufsize);
    }
    if (x == INT_MIN) {
        // Lazy way of handling this special case
        return strlcpy( buf, "-2,147,483,648", bufsize);
    }

    // Work with positive values from here on
    if (x < 0) x = -x;

    int group_counter = 3;
    *(--p) = 0; // Null terminate the scratch buffer

    while (x != 0) {
        int digit = x % 10;
        x = x / 10;

        assert( p != &scratch[0]);
        *(--p) = "0123456789"[digit];

        if ((x != 0) && (--group_counter == 0)) {
            assert( p != &scratch[0]);
            *(--p) = ',';
            group_counter = 3;
        }
    }

    if (neg) {
        assert( p != &scratch[0]);
        *(--p) = '-';
    }
    return strlcpy(buf, p, bufsize);
}

/*
    A non-optimal strlcpy() implementation that helps copying string
    without danger of buffer overflow.

    This is provided just in case you don't have an implementation
    so the code above will actually compile and run.
*/
size_t strlcpy( char* dest, char const* src, size_t dest_size)
{
    size_t len = strlen(src);

    if (dest_size == 0) {
        // nothing to copy - just return how long the buffer should be
        //  (note that the return value doens't include the null terminator)
        return len;
    }

    size_t tocopy = (dest_size <= len) ? dest_size-1 : len;

    memmove( dest, src, tocopy);
    dest[tocopy] = 0;

    return len;
}


问:
VS Code update broke dependencies
Last Thursday my VS Code auto updated.

The day after that one of my Python Scripts, which had been thoroughly tested and runs in production, stopped working.

It started complaining about a type error:

Exception has occurred: TypeError       (note: full exception trace is shown but execution is paused at: )
read_sql() got an unexpected keyword argument 'dtype'

for this this piece of code:

```<code>dtype_df= {}
dtype_df['some_field_1'] = np.dtype('U8')
...
dtype_df['some_field_n'] = np.dtype('U70')

df = pd.read_sql(sql = query, con = some_credentials(), dtype = dtype_df)
</code>```

I did my research and I found out that this issue is related to using the dtype parameter with an older version of pandas.

That didn't make sense because the code worked up until that VS Code update.

Nonetheless, I checked my Pandas version on VS Code and it met the requirements (1.3.0):

```<code>pip show pandas
</code>```

Name: pandas
Version: 1.3.4
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: https://pandas.pydata.org
Author: The Pandas Development Team
Author-email: pandas-dev@python.org
License: BSD-3-Clause
Location: c:\users*******\appdata\local\programs\python\python39\lib\site-packages
Requires: numpy, python-dateutil, pytz
Required-by:

That is when I realized the issue should be related to VS Code.
I also tried running it with a different Python interpreter 3.9.5 -> 3.10.1 but ran into different issues.

For that newer interpreter some dependencies were missing and that made sense for me.

I tried some stuff that I found here (https://github.com/microsoft/vscode/issues/97851) and here (VS 2012 Update 3 broke my VS).

That also did not work.

So, I am not hoping for a magical fix for this case, though if someone knows a different way to solve this issue, I am all ears.

Instead, I would like some feedback on what I think could help in this case:

Creating a virtual environment (currently I don't have one set up) and reinstalling all libraries OR

Uninstalling everything and reinstall again (all extensions and setup everything)

Which alternative would you recommend?

If am missing some key part for this question, please do tell me and I'll adjust it accordingly.

答: Maybe you need to take pd.read_sql_query instead of pd.read_sql, as read_sql has not dtype keyword argument.

Title: VS Code update broke dependencies

Body:
Last Thursday my VS Code auto updated.

The day after that one of my Python Scripts, which had been thoroughly tested and runs in production, stopped working.

It started complaining about a type error:

Exception has occurred: TypeError       (note: full exception trace is shown but execution is paused at: )
read_sql() got an unexpected keyword argument 'dtype'

for this this piece of code:

dtype_df= {}
dtype_df['some_field_1'] = np.dtype('U8')
...
dtype_df['some_field_n'] = np.dtype('U70')

df = pd.read_sql(sql = query, con = some_credentials(), dtype = dtype_df)

I did my research and I found out that this issue is related to using the dtype parameter with an older version of pandas.

That didn't make sense because the code worked up until that VS Code update.

Nonetheless, I checked my Pandas version on VS Code and it met the requirements (1.3.0):

pip show pandas

Name: pandas
Version: 1.3.4
Summary: Powerful data structures for data analysis, time series, and statistics
Home-page: https://pandas.pydata.org
Author: The Pandas Development Team
Author-email: pandas-dev@python.org
License: BSD-3-Clause
Location: c:\users*******\appdata\local\programs\python\python39\lib\site-packages
Requires: numpy, python-dateutil, pytz
Required-by:

That is when I realized the issue should be related to VS Code.
I also tried running it with a different Python interpreter 3.9.5 -> 3.10.1 but ran into different issues.

For that newer interpreter some dependencies were missing and that made sense for me.

I tried some stuff that I found here (https://github.com/microsoft/vscode/issues/97851) and here (VS 2012 Update 3 broke my VS).

That also did not work.

So, I am not hoping for a magical fix for this case, though if someone knows a different way to solve this issue, I am all ears.

Instead, I would like some feedback on what I think could help in this case:

Creating a virtual environment (currently I don't have one set up) and reinstalling all libraries OR

Uninstalling everything and reinstall again (all extensions and setup everything)

Which alternative would you recommend?

If am missing some key part for this question, please do tell me and I'll adjust it accordingly.


问:
How can I make my app present quote from an array and then proceed in order through the remaining quotes?
Part of my app is to provide the user with a random quote about sustainability. I have an array of quotes, but haven't thought about how to present it to the user yet so that they are presented with a quote and then can click the next button to see the next one. The app should also make it so that they can pick up where they left off. For example, if they got to quote 10/80 then the next time they go go the quote section they start on quote 10. I also want users to be able to save each quote. Is an array the best way to do this? Would it be completely wrong to use a new view controller for each quote? I'm very new to all this so any help would be great.</p>

答: As an update, I so far found the best way to do this in my case was to use a collection view. As you scroll through each cell in the collection view you see a new quote. You also see a unique save button for each quote that can hide when tapped, which also then unhides the "unlike" button.</p>


问:
How to write data with some type but export it as const
I would like to write some object that implement some type for now TestType
but export it as read only const

```<code>type TestType = { someProperty: { childProperty: string } }

const obj1: TestType = { someProperty: { childProperty: 'my custom text' } } //  will works
const take1: typeof obj1['someProperty']['childProperty'] = '' // will except string

const obj2 = { someProperty: { childProperty: 'my custom text' } } as const
const take2: typeof obj2['someProperty']['childProperty'] = 'my custom text' // will except 'my custom text'
</code>```

I want to get them both
the object will implement the type but will be export as const

```<code>const obj3 = ({ someProperty: { childProperty: 'my custom text' } } as TestType) as const // will casue type error
const take3: typeof obj2['someProperty']['childProperty'] = 'my custom text' // will except 'my custom text'
</code>```

答:
You can do it using an identity function which is already constrained by another type.

You'll still have to use an as const assertion on the input argument. This isn't very ergonomic, but it addresses your case:

TS Playground

function createConstrainedIdFn <Constraint extends Record<PropertyKey, unknown>>(): <T extends Constraint>(obj: T) => T {
  return obj => obj;
}

type TestType = { someProperty: { childProperty: string } };

const createTestType = createConstrainedIdFn<TestType>();

const obj1 = createTestType({ someProperty: { childProperty: 'my custom text' } } as const);

const take1: typeof obj1['someProperty']['childProperty'] = 'another string' /*
      ^^^^^
Type '"another string"' is not assignable to type '"my custom text"'.(2322) */

```
<hr />
<p>You can make the syntax a bit more concise by using a shorter function name and immediately invoking the returned function:</p>
<p>TS Playground</p>
<pre class="lang-ts prettyprint-override"><code>function id <Constraint extends Record<PropertyKey, unknown>>(): <T extends Constraint>(obj: T) => T {
  return obj => obj;
}

type TestType = { someProperty: { childProperty: string } };

const obj1 = id<TestType>()({ someProperty: { childProperty: 'my custom text' } } as const);
</code>```

Body:
I would like to write some object that implement some type for now TestType
but export it as read only const

type TestType = { someProperty: { childProperty: string } }

const obj1: TestType = { someProperty: { childProperty: 'my custom text' } } //  will works
const take1: typeof obj1['someProperty']['childProperty'] = '' // will except string

const obj2 = { someProperty: { childProperty: 'my custom text' } } as const
const take2: typeof obj2['someProperty']['childProperty'] = 'my custom text' // will except 'my custom text'

I want to get them both
the object will implement the type but will be export as const

const obj3 = ({ someProperty: { childProperty: 'my custom text' } } as TestType) as const // will casue type error
const take3: typeof obj2['someProperty']['childProperty'] = 'my custom text' // will except 'my custom text'

Body:
You can do it using an identity function which is already constrained by another type.

You'll still have to use an as const assertion on the input argument. This isn't very ergonomic, but it addresses your case:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true#code/GYVwdgxgLglg9mABBATgUwIZTQYQQZyhQxjDQBMBJcgMSQB48xDjSpE0APbMc-RAEpoIcFOXoAFFHAAOaFFACeAaTSKANInABrMHADuYAHxGAFAEoAXInoAVDtzS9+TFiTBQzcAEYAra7bmiAC8Roj2AN4AsABQiIjoUCAoSD6+IWFpANyxAL6xsUpy4WiEtorFwYgRiPhwALZoUrLyStY1EAAWMAA25M1yCorWLKQA5oi5kzkxsSLM7KiY2LalUOWVyOhYuARE7hTUdHZrG2hm5jNze4hpAIwhW8toq2UVaKY1dY0DrcPVyG6fV+Q2sAHJ6opkCBCA1ENhuGDJsiMPx5oRLgUYuj2FAMNo0HdrEU0HBgLc-HcANpg75NaSDJRggC6NK6vX6DL+LMeYIweignXktSI4yRAHoAFSxeKyxAAPUVitiZ0QYIARPy4ILhaMwGN1UiYPwBYhUfgYGMwBhvD00PC4PD3mr1ZDobD6vCuFBDQA6UwAJgAzAGA0FJeLYkA" rel="nofollow noreferrer">TS Playground

function createConstrainedIdFn <Constraint extends Record<PropertyKey, unknown>>(): <T extends Constraint>(obj: T) => T {
  return obj => obj;
}

type TestType = { someProperty: { childProperty: string } };

const createTestType = createConstrainedIdFn<TestType>();

const obj1 = createTestType({ someProperty: { childProperty: 'my custom text' } } as const);

const take1: typeof obj1['someProperty']['childProperty'] = 'another string' /*
      ^^^^^
Type '"another string"' is not assignable to type '"my custom text"'.(2322) */

You can make the syntax a bit more concise by using a shorter function name and immediately invoking the returned function:

<a href="https://www.typescriptlang.org/play?noUncheckedIndexedAccess=true&target=99&useUnknownInCatchVariables=true&exactOptionalPropertyTypes=true&ssl=7&ssc=93&pln=1&pc=1#code/GYVwdgxgLglg9mABDAJogPAYQQZygJwEMYwpEBTADynLBR0QCVyI58V0AFfOAB3PxQAngGlyQgDSJwAazBwA7mAB8ygBQBKAFwYAKhWq16ibGDxESUdXABGAKx26NiALzLE+gN4BYAFCJEfHIoEHwkWztXdwiAbj8AXz8-YX4PcjxdIVSXRE9EHDgAW3JuPgFhHTyIAAsYABsUUv5BIR1zEgBzRHjuuN8-VjMyCIBGV2QOXXSoTP51DTU8guKm8tbcxBr6xp5misQAckKhTZA8IsQaagPu28IGQbwNPoHcMihCGXIRnRTyOGAiFGAG0DssSrs1gcALqgrYNVYtGHjA6EeRQaoCfIETo3AD0ACo-AESYgAHoUil+WbkQ4AIjRcAxWPaYA6dJuMAY6MQ9xwMA6YEINjqtKgcEuWVpBzpx1O50KlyoUA5ADo1AAmADMGo1zgJeL8QA" rel="nofollow noreferrer">TS Playground

function id <Constraint extends Record<PropertyKey, unknown>>(): <T extends Constraint>(obj: T) => T {
  return obj => obj;
}

type TestType = { someProperty: { childProperty: string } };

const obj1 = id<TestType>()({ someProperty: { childProperty: 'my custom text' } } as const);


问:
Telling an Angular Reactive form to repaint?
In this reset password material stepper demo in the first step the email is collected in a emailForm.

When next is clicked the submitEmail function sets the value of the emailControl to the email entered.

This is the code for that:

```<code>  submitEmail() {
    if (this.emailForm.valid) {
      const email = this.emailForm.get('email')!.value;
      this.confirmCodeForm.get('email')!.setValue(email);
      console.log('THE EMAIL IS: ', this.confirmCodeForm.get('email').value);
      this.onEmailSubmit.emit(email);
    }
  }

</code>```

We can see that the control value email does have the email entered set through this logging statement:

```<code>this.confirmCodeForm.get('email').value);

</code>```

However in the second step the form does not repaint, and thus the email field (Which is readonly) does not reflect the email address entered.

How do we tell the confirmCodeForm to repaint after calling setValue on the email control?

I also tried using patchValue like this:

```<code>      const email = this.emailForm.get('email')!.value;
      this.confirmCodeForm.patchValue({ email });
      console.log('THE EMAIL IS: ', this.confirmCodeForm.get('email').value);
      this.onEmailSubmit.emit(email);

</code>```

And the control does have the entered email as its value, but the form does not repaint.

答:
Okay, it was quite hard to read what you wanted to achive here. But I think I got it. You want to take entered email from step 1 and copy it to step 2 into email input and form value. Problem was, that control value was set with .setValue(email) but the html code didn't reflect value change because formControlName wasn't pointing to that.

I changed html for the second step formControlName to email and added this.confirmCodeForm.updateValueAndValidity(); just in case (although last one is not explicitly required).

<mat-form-field>
        <input
          type="email"
          matInput
          placeholder="email"
          formControlName="email"
          readonly
        />
</mat-form-field>
```

Working example: https://stackblitz.com/edit/angular-ivy-qfeglo?file=src%2Fapp%2Freset-password%2Freset-password.component.ts

Body:
In this reset password material stepper demo in the first step the email is collected in a emailForm.

When next is clicked the submitEmail function sets the value of the emailControl to the email entered.

This is the code for that:

  submitEmail() {
    if (this.emailForm.valid) {
      const email = this.emailForm.get('email')!.value;
      this.confirmCodeForm.get('email')!.setValue(email);
      console.log('THE EMAIL IS: ', this.confirmCodeForm.get('email').value);
      this.onEmailSubmit.emit(email);
    }
  }

We can see that the control value email does have the email entered set through this logging statement:

this.confirmCodeForm.get('email').value);

However in the second step the form does not repaint, and thus the email field (Which is readonly) does not reflect the email address entered.

How do we tell the confirmCodeForm to repaint after calling setValue on the email control?

I also tried using patchValue like this:

      const email = this.emailForm.get('email')!.value;
      this.confirmCodeForm.patchValue({ email });
      console.log('THE EMAIL IS: ', this.confirmCodeForm.get('email').value);
      this.onEmailSubmit.emit(email);

And the control does have the entered email as its value, but the form does not repaint.

Body:
Okay, it was quite hard to read what you wanted to achive here. But I think I got it. You want to take entered email from step 1 and copy it to step 2 into email input and form value. Problem was, that control value was set with .setValue(email) but the html code didn't reflect value change because formControlName wasn't pointing to that.

I changed html for the second step formControlName to email and added this.confirmCodeForm.updateValueAndValidity(); just in case (although last one is not explicitly required).

<mat-form-field>
        <input
          type="email"
          matInput
          placeholder="email"
          formControlName="email"
          readonly
        />
</mat-form-field>

Working example: https://stackblitz.com/edit/angular-ivy-qfeglo?file=src%2Fapp%2Freset-password%2Freset-password.component.ts


答:
This will work

```<code>lst = [1, 2, 3, 4, 5]
print(sum(lst[::-1])
</code>```

It will reverse the lst using step counter(notice the two colons) then uses inbuilt sum function to add the list.

Title: how do i adjust my code to become a recursive reverse sum loop

Body:
I have a simple recursion method for reversing a list

lst = [1,2,3,4,5] will print as [5, 4, 3, 2, 1]

lst = [1, 2, 3, 4, 5]

def revlist(lst):
    if len(lst) == 0:
        return []
    else:
        return revlist(lst[1:]) + [lst[0]]

print(revlist(lst))

Instead of it printing the reverse list i want it to add 5 + 4 + 3 + 2 + 1 but i dont know how to, at the end I should get 15 but not by just adding the sum of the list, only by adding at the last element and finishing at the first [0] element. Whatever I do to try and sum the array list it gives me errors and I dont really know how I can get any closer to code what I am trying to acheive.

Body:
This will work

lst = [1, 2, 3, 4, 5]
print(sum(lst[::-1])

It will reverse the lst using step counter(notice the two colons) then uses inbuilt sum function to add the list.


问:
How to remove the DataTable's Row without using loops?
I have one datatable which has

DataTable:

```<code>         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC
</code>```

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

```<code>    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }
</code>```

But without loops, How to remove the row based on this condition?

答:
Another option is to use DataView instance.

```<code>//Set sort key and order
 DTItem.DefaultView.Sort = "SeqNo";
 DTItem.DefaultView.Delete(DTItem.DefaultView.Find(2));
</code>```

Body:
I have one datatable which has

DataTable:

         SeqNo        ItemID        ItemName
        -------       ------        --------
           1            10           AAA
           2            20           BBB
           3            30           CCC

Now I want to remove the Row which has the SeqNo "3".

Now I am doing like this in GridView RowCommand Event:

    if (e.CommandName == "Delete")
        {
            string SeqNo = e.CommandArgument.ToString();
            for (int i = 0; i < DTItem.Rows.Count; i++)
            {
                if (SeqNo == DTItem.Rows[i]["SeqNo"].ToString())
                {
                    DTItem.Rows.Remove(DTItem.Rows[i]);
                }
            }
        }

But without loops, How to remove the row based on this condition?

Body:
Another option is to use DataView instance.

//Set sort key and order
 DTItem.DefaultView.Sort = "SeqNo";
 DTItem.DefaultView.Delete(DTItem.DefaultView.Find(2));


Title: Getting a return for unique date and stock name

Body:
I'd like to get a percent return for a set of close stock prices whereby the returns are for each pair of date and ticker symbol.

An example of the dataframe:

       date      open  high    low     close    volume Name

0   2013-02-08  15.07   15.12   14.63   14.75   8407500 AAL
1   2013-02-11  14.89   15.01   14.26   14.46   8882000 AAL
2   2013-02-12  14.45   14.51   14.10   14.27   8126000 AAL
3   2013-02-13  14.30   14.94   14.25   14.66   10259500    AAL
4   2013-02-14  14.94   14.96   13.16   13.99   31879900    AAL

I can easily get the change via df.close.pct_change(1) for the column, but it needs to be grouped.

Things I've tried:

1.GroupBy and apply: df.groupby(by=['date', 'Name']).apply(lambda x: x.assign(ret= d['close'].pct_change(1)))

However, this produces all NaN values.

                       date      open   high    low close   volume  Name    ret
date    Name
2013-02-08  AAL 0   2013-02-08  15.07   15.12   14.63   14.75   8407500 AAL NaN
2013-02-11  AAL 1   2013-02-11  14.89   15.01   14.26   14.46   8882000 AAL NaN
2013-02-12  AAL 2   2013-02-12  14.45   14.51   14.10   14.27   8126000 AAL NaN
2013-02-13  AAL 3   2013-02-13  14.30   14.94   14.25   14.66   10259500    AAL NaN
2013-02-14  AAL 4   2013-02-14  14.94   14.96   13.16   13.99   31879900    AAL NaN

GroupBy close: df['ret'] = df.groupby(by=['date', 'Name']).close

Which produces.

    date        open    high    low     close   volume  Name    ret
0   2013-02-08  15.07   15.12   14.63   14.75   8407500 AAL ((2013-02-08, AAL), [14.75])
1   2013-02-11  14.89   15.01   14.26   14.46   8882000 AAL ((2013-02-11, AAL), [14.46])
2   2013-02-12  14.45   14.51   14.10   14.27   8126000 AAL ((2013-02-12, AAL), [14.27])
3   2013-02-13  14.30   14.94   14.25   14.66   10259500    AAL ((2013-02-13, AAL), [14.66])
4   2013-02-14  14.94   14.96   13.16   13.99   31879900    AAL ((2013-02-14, AAL), [13.99])

I believe the data I need is in the returned group object, but after trying some index slicing I haven't been able to extract the data.

Can I please have some assistance? Thank you!

Body:
To compute percent change for each group in Name:

df.groupby('Name')['close'].pct_change()

Runnable example with a second name added for demo purposes:

d = {'Name': ['AAL', 'AAL', 'AAL', 'AAL', 'AAL', 'TST', 'TST', 'TST'],
     'close': [14.75, 14.46, 14.27, 14.66, 13.99, 10, 11, 22],
     'date': [Timestamp('2013-02-08 00:00:00'),
              Timestamp('2013-02-11 00:00:00'),
              Timestamp('2013-02-12 00:00:00'),
              Timestamp('2013-02-13 00:00:00'),
              Timestamp('2013-02-14 00:00:00'),
              Timestamp('2013-02-11 00:00:00'),
              Timestamp('2013-02-12 00:00:00'),
              Timestamp('2013-02-13 00:00:00')],
     'high': [15.12, 15.01, 14.51, 14.94, 14.96, 11, 12, 23],
     'low': [14.63, 14.26, 14.1, 14.25, 13.16, 9, 10, 21],
     'open': [15.07, 14.89, 14.45, 14.3, 14.94, 10, 11, 22],
     'volume': [8407500,
                8882000,
                8126000,
                10259500,
                31879900,
                8126000,
                10259500,
                31879900]}

df = pd.DataFrame(d)

df['ret'] = df.groupby('Name')['close'].pct_change()

print(df)

        date   open   high    low  close    volume Name       ret
0 2013-02-08  15.07  15.12  14.63  14.75   8407500  AAL       NaN
1 2013-02-11  14.89  15.01  14.26  14.46   8882000  AAL -0.019661
2 2013-02-12  14.45  14.51  14.10  14.27   8126000  AAL -0.013140
3 2013-02-13  14.30  14.94  14.25  14.66  10259500  AAL  0.027330
4 2013-02-14  14.94  14.96  13.16  13.99  31879900  AAL -0.045703
5 2013-02-11  10.00  11.00   9.00  10.00   8126000  TST       NaN
6 2013-02-12  11.00  12.00  10.00  11.00  10259500  TST  0.100000
7 2013-02-13  22.00  23.00  21.00  22.00  31879900  TST  1.000000


问:
Rubocop command not found in ruby 3.0.3
I am trying to run rubocop on ruby 3.0.3 console

```<code> rubocop
</code>```

and I am getting the following.

```<code>rbenv: rubocop: command not found

The `rubocop' command exists in these Ruby versions:
  2.3.3
  2.5.1
  2.5.3
  2.6.5
  2.7.0
</code>```

答:
If you want to use RuboCop as a "naked" command from anywhere, you need to install it in your system gems:

```<code>gem install rubocop
</code>```

Ruby needs to install the gems for each Ruby version independently.

If you are using bundler, and in a project that has RuboCop installed from its Gemfile, you can invoke that particular version using bundler:

```<code>bundle exec rubocop
</code>```

Title: Rubocop command not found in ruby 3.0.3

Body:
I am trying to run rubocop on ruby 3.0.3 console

 rubocop

and I am getting the following.

rbenv: rubocop: command not found

The `rubocop' command exists in these Ruby versions:
  2.3.3
  2.5.1
  2.5.3
  2.6.5
  2.7.0

Body:
If you want to use RuboCop as a "naked" command from anywhere, you need to install it in your system gems:

gem install rubocop

Ruby needs to install the gems for each Ruby version independently.

If you are using bundler, and in a project that has RuboCop installed from its Gemfile, you can invoke that particular version using bundler:

bundle exec rubocop


问:
How to call a function inside another function in VBA?
I'm trying to call a function inside another function but the result I'm getting is 0

```<code>Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Call DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function
</code>```

So,  Where I'm doing wrong here ?

答:
You are calling the function with a =NewDVF(D1;D2) it should be  =NewDVF(D1, D2) (must be comma, not semicolon)

Also you are calling the DepositRate function with CALL (normally reserved for Subs), and discarding its result; you should assign it to something.

Also you should use the Value (not the Deposit) to make the final calculation.

```<code>Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Rtaxa = DepositRate(Value)
    ValorFuturo = Value * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function
</code>```

Body:
I'm trying to call a function inside another function but the result I'm getting is 0

Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Call DepositRate(Value)
    ValorFuturo = Deposit * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function

So,  Where I'm doing wrong here ?

Body:
You are calling the function with a =NewDVF(D1;D2) it should be  =NewDVF(D1, D2) (must be comma, not semicolon)

Also you are calling the DepositRate function with CALL (normally reserved for Subs), and discarding its result; you should assign it to something.

Also you should use the Value (not the Deposit) to make the final calculation.

Function DepositRate(Deposit):
    If Deposit > 100000 Then
        Rtaxa = 0.078
    ElseIf Deposit <= 100000 And Deposit > 10000 Then
        Rtaxa = 0.073
    ElseIf Deposit <= 10000 And Deposit > 1000 Then
        Rtaxa = 0.063
    ElseIf Deposit <= 1000 And Deposit > 0 Then
        Rtaxa = 0.055
    Else
        Rtaxa = "Negative Value"
    End If

    DepositRate = Rtaxa

End Function

Function NewDFV(Value, Year):
    Rtaxa = DepositRate(Value)
    ValorFuturo = Value * (1 + Rtaxa) ^ (Year)
    NewDFV = ValorFuturo

End Function


问:
How to switch between different ViewControllers or NavigationController in Swift?
I just got into Swift programming lately and I have an easy question I can't answer.

I understood that we start putting a ViewController to show something, then if I want to display another view I can use a segue linked to another view. But I don't like the fact that the view called by the segue doesn't take the full screen. It just looks like a pop-up screen.

So, how could I switch from a ViewController to another ViewController or NavigationController or whatever that keep the fullscreen view.
How could I change my view without passing through a segue and get the following view like a pop-up ?

Hope my wonder is clear enough to be answered :D

Thanks a lot to the community !!!

答:
You can make your segue's presentation style as fullscreen. But if you want to use UINavigationController, first you need to embed your ViewController in UINavigationController(rootViewController: ViewController()). After that you can navigate to another ViewController using pushViewController method.

When you use UINavigationController, it will stack on top of each other. When you use popViewController, the current ViewController will be popped off from the stack. That's how works in general.


问:
Set variable text column width in printf
In order to determine the size of the column in C language we use %<number>d.
For instance, I can type %3d and it will give me a column of width=3.
My problem is that my number after the % is a variable that I receive, so I need something like %xd (where x is the integer variable I received sometime before in my program).
But it's not working.

Is there any other way to do this?

答:
You can do this as follows:

```<code>printf("%*d", width, value);
</code>```

From Lee's comment:

You can also use a * for the precision:

```<code>printf("%*.*f", width, precision, value);
</code>```

Note that both width and precision must have type int as expected by printf for the * arguments, type size_t is inappropriate as it may have a different size and representation on the target platform.

Body:
You can do this as follows:

printf("%*d", width, value);

From Lee's comment:

You can also use a * for the precision:

printf("%*.*f", width, precision, value);

Note that both width and precision must have type int as expected by printf for the * arguments, type size_t is inappropriate as it may have a different size and representation on the target platform.


问:
Cannot find -ltk ubuntu
I got an error when try to run make VERSION=full. I share the picture of the command here.

Can anyone tell me what I need to install here?

答:
Please check weather tk and tcl libraries are installed,
or the directories they are installed are linked with -L.</p>

Title: Cannot find -ltk ubuntu


问:
Type not rendering correctly - Jquery error
I received an email with SEO concerns that the font on my site was too small. I checked it out and realized the font size in the navigation and in body greatly reduced in size. The font type also changed from Open Sans and Esteban to Arial.

Site: http://katherinecalvertlcsw.com/

I was told that this looks like an issue with the WP Simple Theme and not WordPress Core.
However, on investigating, as per the image linked below, I found that the font value is either not set in or being pulled from the theme options.

https://i.ibb.co/yQ56vYn/Screenshot-from-2022-02-02-23-25-46.png

In Chrome's Dev console, I found this error:

Uncaught TypeError: Cannot read properties of undefined (reading ‘msie’)

at jquery.tools.min.js?ver=1.2.6:20:204

at jquery.tools.min.js?ver=1.2.6:20:2814

I have posted this on a couple of WordPress forums but no one has provided a solution. My WP is 5.9 (up-to-date). I have a very basic understanding of JavaScript, HTML, and CSS, so I need step-by-step instructions on how to fix this. How can I fix this? Thank you in advance!

答:
Your theme is loading a jquery plugin called jQuery tools. This plugin was last updated 10 years ago. It supports upto jQuery version 1.7.1

Where your WordPress is loading the latest jQuery 3.6.0.

Now how you can fix the error ?

You can downgrade your jQuery using this plugin

https://wordpress.org/plugins/version-control-for-jquery/

Or you can try to add the following piece of code at the begining of this file.
http://katherinecalvertlcsw.com/wp-content/themes/wp_simple/js/jquery.tools.min.js using ftp. This may work or this may generate more errors.

```<code>jQuery.browser = {};
(function () {
    jQuery.browser.msie = false;
    jQuery.browser.version = 0;
    if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
        jQuery.browser.msie = true;
        jQuery.browser.version = RegExp.$1;
    }
})();
</code>```

let us know if this helps.

Body:
Your theme is loading a jquery plugin called jQuery tools. This plugin was last updated 10 years ago. It supports upto jQuery version 1.7.1

Where your WordPress is loading the latest jQuery 3.6.0.

Now how you can fix the error ?

You can downgrade your jQuery using this plugin

https://wordpress.org/plugins/version-control-for-jquery/

Or you can try to add the following piece of code at the begining of this file.
http://katherinecalvertlcsw.com/wp-content/themes/wp_simple/js/jquery.tools.min.js using ftp. This may work or this may generate more errors.

jQuery.browser = {};
(function () {
    jQuery.browser.msie = false;
    jQuery.browser.version = 0;
    if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
        jQuery.browser.msie = true;
        jQuery.browser.version = RegExp.$1;
    }
})();

let us know if this helps.


问:
How to add MULTIPLE strings to a set?
I have a set "y"

I can add one string no problem, but here is the input/output when I add multiple strings:

```<code>y.update(['tam','sam'])
print(y)

{'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}
</code>```

I created a list in the argument for update because I thought it is not iterable. Any thoughts/solutions?

答:
I think you can use tuple
y.update(('tam','sam'))

Title: How to add MULTIPLE strings to a set?

Body:
I have a set "y"

I can add one string no problem, but here is the input/output when I add multiple strings:

y.update(['tam','sam'])
print(y)

{'sam', 'baz', 'a', 'tam', 's', 'bar', 'jas', 'foo', 't', 'm'}

I created a list in the argument for update because I thought it is not iterable. Any thoughts/solutions?


问:
Using C# - Can I have help changing this code so my appointment update shows 15min Appointment reminder alerts before each appointment for the day
```<code>     // Check for upcoming appointments
       ``` foreach (DataRow row in dtblAppointments.Rows)
        {
            DateTime eventDT =
    DateTime.Parse(row["Start"].ToString());

            if(eventDT > DateTime.Now && eventDT.AddMinutes(15)
    >= DateTime.Now)
            {
                MessageBox.Show("Alert - Appointment " +
    row["ID"].ToString() + " " + row["Title"].ToString() + "
    starts in 15 minutes or less.");
            }

        }```
</code>```

Updated the code, i copied in the wrong lines. Can someone help me create an alert for a appointment that is occurring within 15 min. This just randomly alerts for the entire day

答:
This will match only events occurring between now and 15 minutes from now. But it won't keep you from getting alerts multiple times within that period.</p>
```<code>if (eventDT >= DateTime.Now && eventDT <= DateTime.Now.AddMinutes(15))
</code>```

Body:
     // Check for upcoming appointments
       ``` foreach (DataRow row in dtblAppointments.Rows)
        {
            DateTime eventDT =
    DateTime.Parse(row["Start"].ToString());

            if(eventDT > DateTime.Now && eventDT.AddMinutes(15)
    >= DateTime.Now)
            {
                MessageBox.Show("Alert - Appointment " +
    row["ID"].ToString() + " " + row["Title"].ToString() + "
    starts in 15 minutes or less.");
            }

        }```

Updated the code, i copied in the wrong lines. Can someone help me create an alert for a appointment that is occurring within 15 min. This just randomly alerts for the entire day

Body:
This will match only events occurring between now and 15 minutes from now. But it won't keep you from getting alerts multiple times within that period.

if (eventDT >= DateTime.Now && eventDT <= DateTime.Now.AddMinutes(15))