问:
node.js axios request with cookies
so i have browser(netscape?) cookie like that nscookie
or JSON cookie like jsoncookie

How should i pass this into request?

code source:

```<code>const
    fs = require('fs'),
    https = require('https'),
    axios = require('axios');

function reqTest()
{

    axios.default.request({
        'url': 'google.com',
        'method': 'post',
        'headers':
            {
                'Cookie': 'cookie1=?; cookie2=?;'
            }
    }
    ).then(res => {
        console.log(res);
    })
}
</code>```

答:
Having the withCredentials key enabled (set to 'true') should solve your issue.

Please try this:

```<code>const
    fs = require('fs'),
    https = require('https'),
    axios = require('axios');

function reqTest()
{

    axios.default.request({
        'url': 'google.com',
        'method': 'post',
        'headers':
            {
                'Cookie': 'cookie1=?; cookie2=?;'
            },
        'withCredentials': 'true' // ADD THIS LINE
    }
    ).then(res => {
        console.log(res);
    })
}
</code>```

You can also enable this property for all requests in this instance of axios, changing axios' defaults:

```<code>axios.defaults.withCredentials = true;

axios.post(url, body).then(...).catch(...); // withCredentials is automatically enabled
</code>```

Please report results.

Title: node.js axios request with cookies

Body:
so i have browser(netscape?) cookie like that nscookie
or JSON cookie like jsoncookie

How should i pass this into request?

code source:

const
    fs = require('fs'),
    https = require('https'),
    axios = require('axios');

function reqTest()
{

    axios.default.request({
        'url': 'google.com',
        'method': 'post',
        'headers':
            {
                'Cookie': 'cookie1=?; cookie2=?;'
            }
    }
    ).then(res => {
        console.log(res);
    })
}

Body:
Having the withCredentials key enabled (set to 'true') should solve your issue.

Please try this:

const
    fs = require('fs'),
    https = require('https'),
    axios = require('axios');

function reqTest()
{

    axios.default.request({
        'url': 'google.com',
        'method': 'post',
        'headers':
            {
                'Cookie': 'cookie1=?; cookie2=?;'
            },
        'withCredentials': 'true' // ADD THIS LINE
    }
    ).then(res => {
        console.log(res);
    })
}

You can also enable this property for all requests in this instance of axios, changing axios' defaults:

axios.defaults.withCredentials = true;

axios.post(url, body).then(...).catch(...); // withCredentials is automatically enabled

Please report results.


来源: stackexchange

问:
Share entered values while sharing a link
here is my problem: It would be great if users could not only share the link to my website, but also the values they entered there. So far, so good.

First try: simply submit values by GET.

Does not work because: if the URL is

```<code>domain.com?param1=a&param2=b
</code>```

then simply the part before the ? will be shared (at least on iPhones, but that's bad.) So they just share

```<code>domain.com
</code>```

and no parameters are sent. (Google told me the same without giving me a proper workaround idea.)

Okay. Second try: Some workaround involving .htaccess and history.pushstate. It worked quite well, but history.pushstate does not seem to affect the shared URL on iPhones either.

That's bad so far. Does maybe anyone have an idea what to use to solve my problem? Thank you very much :)

答:
btW: I found a solution by myself:

The shared URL is the one set in the

```<code><link rel="canonical" href="domain.com?param1=a&param2=b">
</code>```

So if I share, the parameters are ignored if they are not found in the canonical link.

ContentLicense: CC BY-SA 4.0

Body:
here is my problem: It would be great if users could not only share the link to my website, but also the values they entered there. So far, so good.

First try: simply submit values by GET.

Does not work because: if the URL is

domain.com?param1=a&param2=b

then simply the part before the ? will be shared (at least on iPhones, but that's bad.) So they just share

domain.com

and no parameters are sent. (Google told me the same without giving me a proper workaround idea.)

Okay. Second try: Some workaround involving .htaccess and history.pushstate. It worked quite well, but history.pushstate does not seem to affect the shared URL on iPhones either.

That's bad so far. Does maybe anyone have an idea what to use to solve my problem? Thank you very much :)

Body:
btW: I found a solution by myself:

The shared URL is the one set in the

<link rel="canonical" href="domain.com?param1=a&param2=b">

So if I share, the parameters are ignored if they are not found in the canonical link.


问:
Javascript regular expression for search from starting letter?
I want add search functionality. I need to search any document by starting letter.

Suppose, we have to some document like-

```<code>Apple Industry
Samsung Industry
Xioami Industry
Ahua Industry
Sumatech Industry
</code>```

When user search a then it should give the result which one start with a like-

```<code>Ahua Industry
Apple Industry
</code>```

You can see the result show alphabetically

I already create a regex like this-

```<code>{ Industry: { '$regex': 'a', '$options': 'i' } }
</code>```

But it show all the content that contain a.

Like-

It show every content because all the content contain a.

How can I solve that. Can anyone help me.

答:
You need to add the startWith modifier to your regex. I'm not sure how this object gets converted to the regex, but here you go:

```<code>{ Industry: { '$regex': '^a.*', '$options': 'i' } }
</code>```

function matchText(query) {

  const text = ['Apple Industry',
  'Samsung Industry',
  'Xioami Industry',
  'Ahua Industry',
  'Sumatech Industry'
  ];

 const regex = new RegExp(`^${query}.*`, 'i');

 text.forEach((item) => console.log(item.match(regex)));
}

matchText('a');
matchText('ap');```

Body:
I want add search functionality. I need to search any document by starting letter.

Suppose, we have to some document like-

Apple Industry
Samsung Industry
Xioami Industry
Ahua Industry
Sumatech Industry

When user search a then it should give the result which one start with a like-

Ahua Industry
Apple Industry

You can see the result show alphabetically

I already create a regex like this-

{ Industry: { '$regex': 'a', '$options': 'i' } }

But it show all the content that contain a.

Like-

It show every content because all the content contain a.

How can I solve that. Can anyone help me.

Body:
You need to add the startWith modifier to your regex. I'm not sure how this object gets converted to the regex, but here you go:

{ Industry: { '$regex': '^a.*', '$options': 'i' } }

function matchText(query) {

  const text = ['Apple Industry',
  'Samsung Industry',
  'Xioami Industry',
  'Ahua Industry',
  'Sumatech Industry'
  ];

 const regex = new RegExp(`^${query}.*`, 'i');

 text.forEach((item) => console.log(item.match(regex)));
}

matchText('a');
matchText('ap');


问:
Compare Package Versions in Github Actions
I want to compare my current deployed version against the version mentioned in my 'package.json'. If the version number in the json is higher than the current one (mentioned in my pushed Tags (Release)) I want to deploy it with GitHub Actions.

Im not able to compare the two numbers/Integers in the Github Actions yaml file.

Currently I'm doing this:

```<code>- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if [ $(( ${{env.TAG_VERSION}} )) >> $(( ${{env.PACKAGE_VERSION}} )) ]; then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif [ ${{env.TAG_VERSION}} == ${{env.PACKAGE_VERSION_NUMBER}} ]; then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi
</code>```

Its not delivering the result I want:

Its looking good at first sight, but delivers:

```<code>PUSH: true
</code>```

Is there a nice and native way to compare those version numbers in the if condition?

Ive also tried it to convert the numbers like this, but same output:

```<code>- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name: Get Numbers
  run: |
    echo "TAG_NUMBER=$echo$((${{env.TAG_VERSION}} - 0 ))" >> $GITHUB_ENV
    echo "PACKAGE_NUMBER=$echo$((${{env.PACKAGE_VERSION}} - 0 ))" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if [ ${{env.TAG_NUMBER}} >>  ${{env.PACKAGE_NUMBER}} ]; then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif [ ${{env.TAG_NUMBER}} == ${{env.PACKAGE_NUMBER}} ]; then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi
</code>```

Output:

答:
Just changed the if bracktes from "[ ... ]" to "(( ... ))" and it worked perfect:</p>
```<code>- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name:
  run: |
    echo "TAG_NUMBER=$echo$((${{env.TAG_VERSION}} - 0 ))" >> $GITHUB_ENV
    echo "PACKAGE_NUMBER=$echo$((${{env.PACKAGE_VERSION}} - 0 ))" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if (( ${{env.PACKAGE_NUMBER}} > ${{env.TAG_NUMBER}} )); then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif (( ${{env.PACKAGE_NUMBER}} = ${{env.TAG_NUMBER}} )); then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi
</code>```

Body:
I want to compare my current deployed version against the version mentioned in my 'package.json'. If the version number in the json is higher than the current one (mentioned in my pushed Tags (Release)) I want to deploy it with GitHub Actions.

Im not able to compare the two numbers/Integers in the Github Actions yaml file.

Currently I'm doing this:

- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if [ $(( ${{env.TAG_VERSION}} )) >> $(( ${{env.PACKAGE_VERSION}} )) ]; then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif [ ${{env.TAG_VERSION}} == ${{env.PACKAGE_VERSION_NUMBER}} ]; then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi

Its not delivering the result I want:

Its looking good at first sight, but delivers:

PUSH: true

Is there a nice and native way to compare those version numbers in the if condition?

Ive also tried it to convert the numbers like this, but same output:

- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name: Get Numbers
  run: |
    echo "TAG_NUMBER=$echo$((${{env.TAG_VERSION}} - 0 ))" >> $GITHUB_ENV
    echo "PACKAGE_NUMBER=$echo$((${{env.PACKAGE_VERSION}} - 0 ))" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if [ ${{env.TAG_NUMBER}} >>  ${{env.PACKAGE_NUMBER}} ]; then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif [ ${{env.TAG_NUMBER}} == ${{env.PACKAGE_NUMBER}} ]; then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi

Output:

Body:
Just changed the if bracktes from "[ ... ]" to "(( ... ))" and it worked perfect:

- name: Clean Versions
  run: |
        echo "TAG_VERSION=$(echo ${{env.TAG}} | tr -dc '0-9')" >> $GITHUB_ENV
        echo "PACKAGE_VERSION=$(echo ${{env.PACKAGE}} | tr -dc '0-9')" >> $GITHUB_ENV

- name:
  run: |
    echo "TAG_NUMBER=$echo$((${{env.TAG_VERSION}} - 0 ))" >> $GITHUB_ENV
    echo "PACKAGE_NUMBER=$echo$((${{env.PACKAGE_VERSION}} - 0 ))" >> $GITHUB_ENV

- name: Compare Versions
  run: |
    if (( ${{env.PACKAGE_NUMBER}} > ${{env.TAG_NUMBER}} )); then
        echo "PUSH=true" >> "$GITHUB_ENV"

    elif (( ${{env.PACKAGE_NUMBER}} = ${{env.TAG_NUMBER}} )); then
        echo "PUSH=false" >> "$GITHUB_ENV"

    else
        echo "PUSH=false" >> "$GITHUB_ENV"
    fi


问:
Flutter detect triple tap
I would like to be able to detect a triple tap (or even more) in a Flutter widget, although GestureDetector only has detection for double-tap built in.

What is the easiest way for me to detect a triple tap on a widget?

(I want continually clicking on a part of the screen to unlock some developer options)

答:
I tried the method mentioned here, but it didn't work for me. GestureDetector onTap is called only once,
regardless of the number of taps. Probably something has changed in flutter (I'm on the beta channel).
However, I dug into the source code of flutter and come to the solution (https://api.flutter.dev/flutter/gestures/SerialTapGestureRecognizer-class.html):

import "package:flutter/gestures.dart";
import 'package:flutter/material.dart';

RawGestureDetector(
  gestures: {
    SerialTapGestureRecognizer:
        GestureRecognizerFactoryWithHandlers<SerialTapGestureRecognizer>(
            SerialTapGestureRecognizer.new,
            (SerialTapGestureRecognizer instance) {
      instance.onSerialTapDown = (SerialTapDownDetails details) {
         if (details.count == 3) print('Consecutive tap 3');
      };
    })
  },

  //  child: // your widget,
);

```

Title: Flutter detect triple tap


问:
Clean way to implement validation on non-crud routes in Rails?
How do you implement validation on NON-CRUD routes? For example, there is a route for browsing recipes. It accepts parameters term (for search), sort, page and so on.

What is the neatest way to do this in Rails?

The most straight-forward solution would be to validate all these things using the bunch of if-else expressions in the controller, but I'm looking for something more clean and easier for extension and maintinance.

I ended up with the following

```<code>class RequestValidation
  attr_reader :validators
  attr_reader :errors

  def initialize
    @validators = []
    @errors = []
  end

  def add_validator(validator)
    @validators << validator
  end

  def validate
    @validators.each do |validator|
      validator.validate
      @errors += validator.errors
    end
  end

  def valid?
    validate
    errors.empty?
  end

end
</code>```

Example of validator class

```<code>  class SortValidator < Validator

    VALID_SORT_FIELD = [:created_at, :rate, :total_time]
    VALID_SORT_DIRECTIONS = [:asc, :desc]

    def validate
      return unless param

      valid = true
      begin
        sort = param.to_unsafe_h

        if sort.size == 1
          k = sort.keys[0].to_sym
          v = sort.values[0].to_sym
          valid = VALID_SORT_FIELD.include?(k) && VALID_SORT_DIRECTIONS.include?(v)
        else
          valid = false
        end
      rescue => ex
        valid = false
      end

      @errors << "Sort parameter invalid" unless valid
    end

    def is_valid?
      !errors.empty?
    end
  end

</code>```

So, RequestValidation is like a builder / container class for all validators. And then, in the controller:

```<code>    validation = RequestValidation.new
    validation.add_validator(RecipesValidators::SortValidator.new(params[:sort]))

    validation.validate

    if validation.errors.empty?
</code>```

This way, when new validation is required, we just need to create a new Validator class and add it to request validation.

Given that I took a pause from Rails for several years, there are doubts if this code is clean and neat and in accordance with Ruby principles.

Or is there a better way?

Thanks in advance

答:
The solution here was never really a custom validator - instead you should create a class such as a model or form object to encapsulate the validations and data. Just because your action doesn't persist anything doesn't mean you can't use a model to represent data and buisness logic.

```<code>class RecipeSearch
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :query, :string
  attribute :sort_by, :string
  # ...

  validates :query, length: { minimum: 5 }
  validates :sort_by, in: ['newest', 'quickest', 'cheapest']
  # ...

  # @todo apply filters to Recipe and return collection
  def perform
     # ...
  end
end
</code>```

This lets you add validations and logic. And pass it to forms:

```<code><%= form_with(model: local_assigns(:recipe_seach) || RecipeSearch.new) do |f| %>
  # ...
<% end %>
</code>```

Its also a misconception that searching can't be a part of CRUD. It is after all just Read with filters applied. If you really need a separate view from your normal index then by all means create a separate search action but its not really a neccissity.

```<code>class RecipesController
  def index
    @recipe_search = RecipeSearch.new(search_params)
    @recipes = @recipe_search.perform
  end

  private

  def search_params
    params.fetch(:recipe_search, {})
          .permit(:query, :sort_by)
  end
end
</code>```

Body:
How do you implement validation on NON-CRUD routes? For example, there is a route for browsing recipes. It accepts parameters term (for search), sort, page and so on.

What is the neatest way to do this in Rails?

The most straight-forward solution would be to validate all these things using the bunch of if-else expressions in the controller, but I'm looking for something more clean and easier for extension and maintinance.

I ended up with the following

class RequestValidation
  attr_reader :validators
  attr_reader :errors

  def initialize
    @validators = []
    @errors = []
  end

  def add_validator(validator)
    @validators << validator
  end

  def validate
    @validators.each do |validator|
      validator.validate
      @errors += validator.errors
    end
  end

  def valid?
    validate
    errors.empty?
  end

end

Example of validator class

  class SortValidator < Validator

    VALID_SORT_FIELD = [:created_at, :rate, :total_time]
    VALID_SORT_DIRECTIONS = [:asc, :desc]

    def validate
      return unless param

      valid = true
      begin
        sort = param.to_unsafe_h

        if sort.size == 1
          k = sort.keys[0].to_sym
          v = sort.values[0].to_sym
          valid = VALID_SORT_FIELD.include?(k) && VALID_SORT_DIRECTIONS.include?(v)
        else
          valid = false
        end
      rescue => ex
        valid = false
      end

      @errors << "Sort parameter invalid" unless valid
    end

    def is_valid?
      !errors.empty?
    end
  end

So, RequestValidation is like a builder / container class for all validators. And then, in the controller:

    validation = RequestValidation.new
    validation.add_validator(RecipesValidators::SortValidator.new(params[:sort]))

    validation.validate

    if validation.errors.empty?

This way, when new validation is required, we just need to create a new Validator class and add it to request validation.

Given that I took a pause from Rails for several years, there are doubts if this code is clean and neat and in accordance with Ruby principles.

Or is there a better way?

Thanks in advance

Body:
The solution here was never really a custom validator - instead you should create a class such as a model or form object to encapsulate the validations and data. Just because your action doesn't persist anything doesn't mean you can't use a model to represent data and buisness logic.

class RecipeSearch
  include ActiveModel::Model
  include ActiveModel::Attributes

  attribute :query, :string
  attribute :sort_by, :string
  # ...

  validates :query, length: { minimum: 5 }
  validates :sort_by, in: ['newest', 'quickest', 'cheapest']
  # ...

  # @todo apply filters to Recipe and return collection
  def perform
     # ...
  end
end

This lets you add validations and logic. And pass it to forms:

<%= form_with(model: local_assigns(:recipe_seach) || RecipeSearch.new) do |f| %>
  # ...
<% end %>

Its also a misconception that searching can't be a part of CRUD. It is after all just Read with filters applied. If you really need a separate view from your normal index then by all means create a separate search action but its not really a neccissity.

class RecipesController
  def index
    @recipe_search = RecipeSearch.new(search_params)
    @recipes = @recipe_search.perform
  end

  private

  def search_params
    params.fetch(:recipe_search, {})
          .permit(:query, :sort_by)
  end
end


问:
vs2019 meet LNK2001 while using external static library yaml-cpp.lib
I built yaml-cpp staticly using vs2019 and got lib from path yaml-cpp-master\build\Release\yaml-cpp.lib, now I intend to add it to my own project, simple code follows:

#include <yaml-cpp/yaml.h>
#include <string>

using namespace std;

int main() {
    YAML::Node config = YAML::LoadFile("test.yaml");
    if (config["test1"]) {
        cout << config["test1"].as<string>() << endl;
    }
    return 0;
}
```
<p>I've set my project properties following How to add static libraries to a Visual studio project,
but I meet LNK2001 error and C4251 warning when building:</p>
```LNK2001 "__declspec(dllimport) public: __cdecl YAML::Node::Node(void)" (__imp_??0Node@YAML@@QEAA@XZ)
```

it seems the linker still wants dll...which is not my intention, is there any possible solutions?

答: You need to #define YAML_CPP_STATIC_DEFINE before you include any yaml-cpp files or in your project processor settings.

Body:
I built yaml-cpp staticly using vs2019 and got lib from path yaml-cpp-master\build\Release\yaml-cpp.lib, now I intend to add it to my own project, simple code follows:

#include <yaml-cpp/yaml.h>
#include <string>

using namespace std;

int main() {
    YAML::Node config = YAML::LoadFile("test.yaml");
    if (config["test1"]) {
        cout << config["test1"].as<string>() << endl;
    }
    return 0;
}

I've set my project properties following How to add static libraries to a Visual studio project,
but I meet LNK2001 error and C4251 warning when building:

LNK2001 "__declspec(dllimport) public: __cdecl YAML::Node::Node(void)" (__imp_??0Node@YAML@@QEAA@XZ)

it seems the linker still wants dll...which is not my intention, is there any possible solutions?


问:
Having issue with container class in bootstrap?
Here is the link https://vkacademy.in/newm.html

When I create a container for every section I am getting space in between for every container, how to avoid the space for each container.

When you see the output I am getting space for each container that I highlighted. how to avoid the space?

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">

Bootstrap Tutorial

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.

Bootstrap Tutorial

Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile-first projects on the web.

```

答:
Please use this code. Because this is the correct use of "p-0" and "m-0" classes in the "container".

Example: container p-0 m-0


问:
Possible to get MSIL of a C# Delegate?
Just out of curiosity ... is it possible to programmatically get the MSIL of a delegate?  I'm curious because I've been toying with the idea of a distributed computing system where you can simply write programs, and the program itself would be distributed to each disparate node where work would occur.  I know you could do it by copying the actual assembly over the network and loading that in an appdomain, but I think it would be really interesting to have a simpler model to work with.

thanks!

答:
What about the dependencies of the delegate code -- this might possibly work using CodeDom reflection emit, but if the delegate calls anything outside itself (even framework code), how are you going to ensure it exists on the target machine(s)? Lots of Assembly.Load() code? </p>

<p>By the way: if you build a dynamically changing distributed system along these lines, you ain't gonna get me to maintain or operate it! Imagine doing fault isolation or trying to do anything like comprehensive testing... </p>

OwnerDisplayName: Joel Martinez

ContentLicense: CC BY-SA 2.5

Title: Possible to get MSIL of a C# Delegate?

LastEditorDisplayName: Joel Martinez

Body:
What about the dependencies of the delegate code -- this might possibly work using CodeDom reflection emit, but if the delegate calls anything outside itself (even framework code), how are you going to ensure it exists on the target machine(s)? Lots of Assembly.Load() code?

By the way: if you build a dynamically changing distributed system along these lines, you ain't gonna get me to maintain or operate it! Imagine doing fault isolation or trying to do anything like comprehensive testing...

OwnerDisplayName: Pontus Gagge


问:
mysql_query return TRUE on empty table

$rs = mysql_query("SELECT user, userid FROM House WHERE
  userid='$userid'");

This return Resource id #37
The table House is empty, shouldn't it return FALSE?
According to the manual http://php.net/manual/en/function.mysql-query.php

I have always gotten FALSE on error, but not this time.
Can someone explain, thanks!

答:
If there is nothing wrong with your query, then mysql_query() will not return false. An empty result set is not an error.

Calling any of the fetch functions against that result will return false. mysql_num_rows() will return 0.

ContentLicense: CC BY-SA 3.0

Title: mysql_query return TRUE on empty table


问:
for a in b.layers: The object is not iterable
I am trying to list all the feature services using the below code,

```<code>from arcgis.gis import GIS
gis = GIS(url='https://pythonapi.playground.esri.com/portal', username='arcgis_python', password='amazing_arcgis_123')

items = gis.content.search(query="", item_type="Feature Service")

some_list = []

for b in items:
    print(b.layers)
    print(b)
    for a in b.layers:
         if a.properties['name'] == 'WETTBEWERBER':
              some_list.append(a)
</code>```

but I get this error, what am I doing wrong ?? Any insights will be helpful.

```<code>Traceback (most recent call last):

  File "C:/Users/PycharmProjects/untitled/Test/Test maps.py", line 14, in <module>

    for a in b.layers:

TypeError: 'NoneType' object is not iterable
</code>```

I get the printed results as follows, but if I take one of the printed result URLs and tried to get that layer by changing the name according to the printed URL, I do not get any results.

```<code>F:\ArcGISPro\bin\Python\envs\arcgispro-py3\python.exe "C:/Users/PycharmProjects/untitled/Test/Test maps.py"

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/sd/FeatureServer/0">]

<Item title:"sd" type:Feature Layer Collection owner:dafsa>

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/CC/FeatureServer/0">]

<Item title:"CC" type:Feature Layer Collection owner:sajd57d>

[<FeatureLayer url:"https://maps.com/server/rest/services/MD/FeatureServer/0">]

<Item title:"MD" type:Feature Layer Collection owner:dasjc6>

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/ring/FeatureServer/0">]

<Item title:"ring" type:Feature Layer Collection owner:dashk56>
</code>```

For example, if I take the first URL and open my portal I can see the Feature containing a layer with its name 'WETTBEWERBER' but if the results do not show anything.

答:
You could use

```<code>some_list = [[a for a in b.layers if a.properties['name'] == 'WETTBEWERBER'] \
for b in items if b.layers]
</code>```

Test using this logic:

```<code>from dataclasses import dataclass

@dataclass
class Item:
    st:str
    layers:list

prop1 = {"properties":{
    "name" : "l1"
}}

prop2 = {"properties":{
    "name" : "l1"
}}

prop3 = {"properties":{
    "name" : "l3"
}}

items = [Item('a', None),Item('b', [prop1]),Item('c',[prop2]),Item('d', None),Item('e', [prop3])]

lst = [[a for a in b.layers if a['properties']['name'] == 'l1'] \
for b in items if b.layers]
print(lst)
</code>```

Alternatively, you could just add -> if b.layers is Not None after for b in items

Body:
I am trying to list all the feature services using the below code,

from arcgis.gis import GIS
gis = GIS(url='https://pythonapi.playground.esri.com/portal', username='arcgis_python', password='amazing_arcgis_123')

items = gis.content.search(query="", item_type="Feature Service")

some_list = []

for b in items:
    print(b.layers)
    print(b)
    for a in b.layers:
         if a.properties['name'] == 'WETTBEWERBER':
              some_list.append(a)

but I get this error, what am I doing wrong ?? Any insights will be helpful.

Traceback (most recent call last):

  File "C:/Users/PycharmProjects/untitled/Test/Test maps.py", line 14, in <module>

    for a in b.layers:

TypeError: 'NoneType' object is not iterable

I get the printed results as follows, but if I take one of the printed result URLs and tried to get that layer by changing the name according to the printed URL, I do not get any results.

F:\ArcGISPro\bin\Python\envs\arcgispro-py3\python.exe "C:/Users/PycharmProjects/untitled/Test/Test maps.py"

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/sd/FeatureServer/0">]

<Item title:"sd" type:Feature Layer Collection owner:dafsa>

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/CC/FeatureServer/0">]

<Item title:"CC" type:Feature Layer Collection owner:sajd57d>

[<FeatureLayer url:"https://maps.com/server/rest/services/MD/FeatureServer/0">]

<Item title:"MD" type:Feature Layer Collection owner:dasjc6>

[<FeatureLayer url:"https://maps.com/server/rest/services/Hosted/ring/FeatureServer/0">]

<Item title:"ring" type:Feature Layer Collection owner:dashk56>

For example, if I take the first URL and open my portal I can see the Feature containing a layer with its name 'WETTBEWERBER' but if the results do not show anything.

Body:
You could use

some_list = [[a for a in b.layers if a.properties['name'] == 'WETTBEWERBER'] \
for b in items if b.layers]

Test using this logic:

from dataclasses import dataclass

@dataclass
class Item:
    st:str
    layers:list

prop1 = {"properties":{
    "name" : "l1"
}}

prop2 = {"properties":{
    "name" : "l1"
}}

prop3 = {"properties":{
    "name" : "l3"
}}

items = [Item('a', None),Item('b', [prop1]),Item('c',[prop2]),Item('d', None),Item('e', [prop3])]

lst = [[a for a in b.layers if a['properties']['name'] == 'l1'] \
for b in items if b.layers]
print(lst)

Alternatively, you could just add -> if b.layers is Not None after for b in items


问:
Eigen runtime assertion due to fixed size members
When running my program I am currently retrieving the following Eigen assertion:

test_engine: /usr/include/eigen3/Eigen/src/Core/DenseStorage.h:128: Eigen::internal::plain_array::plain_array() [with T = double; int Size = 16; int MatrixOrArrayOptions = 0]: Assertion `(reinterpret_cast(eigen_unaligned_array_assert_workaround_gcc47(array)) & (31)) == 0 && "this assertion is explained here: " "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" " **** READ THIS WEB PAGE !!! ****"' failed.

The exact line of code which causes this assertion is:

```<code>  std::shared_ptr<Reference> ptr_tmp = std::make_shared<ReferenceLinCart>(cart_traj);
</code>```

where Reference and ReferenceLinCart are defined in a common header file as:

```<code>  struct Reference {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    virtual ~Reference() {}
  }

  struct ReferenceLinCart : Reference {
    Eigen::Transform<double, 3, Eigen::Affine> T_start;
    Eigen::Transform<double, 3, Eigen::Affine> T_goal;
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  };
</code>```

The link in the description provided me with information concerning static size structure members, which is why I added the EIGEN_MAKE_ALIGNED_OPERATOR_NEW flag.

The g++ compile flags used are:  -march=native -funroll-loops -std=c++11 -Ofast -Wall

Unfortunately I am still retrieving the same runtime assertion. Any suggestion on how to get rid of this?

答: compile the code with c++17, the bug(memory allocator) is fixed</p>

Body:
When running my program I am currently retrieving the following Eigen assertion:

test_engine: /usr/include/eigen3/Eigen/src/Core/DenseStorage.h:128: Eigen::internal::plain_array::plain_array() [with T = double; int Size = 16; int MatrixOrArrayOptions = 0]: Assertion `(reinterpret_cast(eigen_unaligned_array_assert_workaround_gcc47(array)) & (31)) == 0 && "this assertion is explained here: " "http://eigen.tuxfamily.org/dox-devel/group__TopicUnalignedArrayAssert.html" " **** READ THIS WEB PAGE !!! ****"' failed.

The exact line of code which causes this assertion is:

  std::shared_ptr<Reference> ptr_tmp = std::make_shared<ReferenceLinCart>(cart_traj);

where Reference and ReferenceLinCart are defined in a common header file as:

  struct Reference {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    virtual ~Reference() {}
  }

  struct ReferenceLinCart : Reference {
    Eigen::Transform<double, 3, Eigen::Affine> T_start;
    Eigen::Transform<double, 3, Eigen::Affine> T_goal;
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  };

The link in the description provided me with information concerning static size structure members, which is why I added the EIGEN_MAKE_ALIGNED_OPERATOR_NEW flag.

The g++ compile flags used are:  -march=native -funroll-loops -std=c++11 -Ofast -Wall

Unfortunately I am still retrieving the same runtime assertion. Any suggestion on how to get rid of this?


问:
how to add a for loop data to form.serializer() - jquery
I'm trying to send dynamic two input field to backend via ajax, and i have main form, the main form works fine, dont know how to send two extra dynamic inputs to backend, here is my code

var extra_inputs = 2
var removed_extra_inputs = []
var formData = new FormData();

for(var i=0; i<extra_inputs; i++){
  try{
      formData.append("guestinfo-"+i, document.getElementById("guestinfo-"+i).value);
      formData.append("reason-"+i, document.getElementById("reason-"+i).value);
      }
  catch(err){
      console.log(err);
      }
  }

  const form = document.getElementById('post-form-add-booking')

  const url = window.location.href
  const room = parseInt(room_number)
  form.addEventListener("submit",submitHanler);
  function submitHanler(e){
      e.preventDefault();
      $.ajax({
           type:'POST',
           url:url,
           data:$("#post-form-add-booking").serialize() + "&extra_inputs="+extra_inputs + '&removed_extra_inputs='+removed_extra_inputs,
           dataType:'json',
           success:successFunction,
           error:errorFunction,

       })
     }```

but not sure is there a way to combine formData with form.serilaizer please , thank you for you your help ..

答:
Here is what I believe you mean</p>
```<code>$('#post-form-add-booking').on("submit",function(e) {
  e.preventDefault();
  const formData = new FormData(this); // adding the DOM form
  $("[id^=guestinfo], [id^=reason]").each(function() {
    formData.append(this.id, this.value)
  })
  $.ajax({
       type:'POST',
       url:url,
       data:formData,
       dataType:'json',
       success:successFunction,
       error:errorFunction,
   })
})
</code>```

Body:
I'm trying to send dynamic two input field to backend via ajax, and i have main form, the main form works fine, dont know how to send two extra dynamic inputs to backend, here is my code

var extra_inputs = 2
var removed_extra_inputs = []
var formData = new FormData();

for(var i=0; i<extra_inputs; i++){
  try{
      formData.append("guestinfo-"+i, document.getElementById("guestinfo-"+i).value);
      formData.append("reason-"+i, document.getElementById("reason-"+i).value);
      }
  catch(err){
      console.log(err);
      }
  }

  const form = document.getElementById('post-form-add-booking')

  const url = window.location.href
  const room = parseInt(room_number)
  form.addEventListener("submit",submitHanler);
  function submitHanler(e){
      e.preventDefault();
      $.ajax({
           type:'POST',
           url:url,
           data:$("#post-form-add-booking").serialize() + "&extra_inputs="+extra_inputs + '&removed_extra_inputs='+removed_extra_inputs,
           dataType:'json',
           success:successFunction,
           error:errorFunction,

       })
     }

but not sure is there a way to combine formData with form.serilaizer please , thank you for you your help ..

Body:
Here is what I believe you mean

$('#post-form-add-booking').on("submit",function(e) {
  e.preventDefault();
  const formData = new FormData(this); // adding the DOM form
  $("[id^=guestinfo], [id^=reason]").each(function() {
    formData.append(this.id, this.value)
  })
  $.ajax({
       type:'POST',
       url:url,
       data:formData,
       dataType:'json',
       success:successFunction,
       error:errorFunction,
   })
})


问:
How we can retrieve the data of the checkboxes in another activity in a text view
This is the activity where I defined the checkboxes and Array list.
I have save the result in the arraylist and want to display the same arraylist in another activity.

```<code>   public ArrayList<String> Result;

   Result = new ArrayList<>();

   public void statuscheck(){

    bcg.setOnClickListener(v -> {
        if(bcg.isChecked()){
            Result.add("BCG(Bacillus Calmette and Guérin)");
        }
        else {
            Result.remove("BCG(Bacillus Calmette and Guérin)");
        }
    });

    bopv0.setOnClickListener(v -> {
        if(bopv0.isChecked()){
            Result.add("b Oral Polio vaccine(bOPV)-0 ");
        }
        else {
            Result.remove("b Oral Polio vaccine(bOPV)-0 ");
        }
    });

    hepatitis0.setOnClickListener(v -> {
        if(hepatitis0.isChecked()){

            Result.add("Hepatitis B birth dose ");

        }

        else {

            Result.remove("Hepatitis B birth dose ");

        }

    });
}
</code>```

the activity where I want to show the arraylist in a text view

```<code>TextView vac_result;
ArrayList<String> vc_Res;

    vac_result = findViewById(R.id.vac_result);
    vac_result.setEnabled(false);

    vc_Res = vaccineone.Result;
    StringBuilder stringBuilder = new StringBuilder();
    for(String s : vc_Res)
        stringBuilder.append("\n");

    vac_result.setText(stringBuilder.toString());
    vac_result.setEnabled(true);
</code>```

答:
There are many ways to achieve what you want. You can either pass your data as a Bundle when you're trying to call startActivity() or use a static global variable across your application.

The snippet below will demonstrate how to use a static variable:

```<code>class Example {

   public static ArrayList<String> Result = new ArrayList<>();
}
</code>```

Fill the static arraylist with your data and simply get the data in the other activity.

Body:
This is the activity where I defined the checkboxes and Array list.
I have save the result in the arraylist and want to display the same arraylist in another activity.

   public ArrayList<String> Result;

   Result = new ArrayList<>();

   public void statuscheck(){

    bcg.setOnClickListener(v -> {
        if(bcg.isChecked()){
            Result.add("BCG(Bacillus Calmette and Guérin)");
        }
        else {
            Result.remove("BCG(Bacillus Calmette and Guérin)");
        }
    });

    bopv0.setOnClickListener(v -> {
        if(bopv0.isChecked()){
            Result.add("b Oral Polio vaccine(bOPV)-0 ");
        }
        else {
            Result.remove("b Oral Polio vaccine(bOPV)-0 ");
        }
    });

    hepatitis0.setOnClickListener(v -> {
        if(hepatitis0.isChecked()){

            Result.add("Hepatitis B birth dose ");

        }

        else {

            Result.remove("Hepatitis B birth dose ");

        }

    });
}

the activity where I want to show the arraylist in a text view

TextView vac_result;
ArrayList<String> vc_Res;

    vac_result = findViewById(R.id.vac_result);
    vac_result.setEnabled(false);

    vc_Res = vaccineone.Result;
    StringBuilder stringBuilder = new StringBuilder();
    for(String s : vc_Res)
        stringBuilder.append("\n");

    vac_result.setText(stringBuilder.toString());
    vac_result.setEnabled(true);

Body:
There are many ways to achieve what you want. You can either pass your data as a Bundle when you're trying to call startActivity() or use a static global variable across your application.

The snippet below will demonstrate how to use a static variable:

class Example {

   public static ArrayList<String> Result = new ArrayList<>();
}

Fill the static arraylist with your data and simply get the data in the other activity.


问:
Why is jest test not recognizing react native components?
I have a react native app that I am trying to run tests on, I have set up a basic greeting component as shown below called Greetings.js:

```<code>import React from 'react';
import {View, Text} from 'react-native';

const Greetings = ({hello}) => {
  return (
    <View>
      <Text>{hello}</Text>
    </View>
  );
};

export default Greetings;
</code>```

This is the test I am running called Greetings.test.js:

```<code>import React from 'react';
import {render, screen} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {
    render(<Greetings hello="Hello World!" />);

    const helloWorldElement = screen.getByText('Hello World!');
    expect(helloWorldElement).toBeInTheDocument();
  });
});
</code>```

For some reason it doesnt recognise the react native components, this is the error when running the test:

```<code> FAIL  app/__tests__/components/Account/Greetings.test.js
  ● Console

    console.error
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You li
forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

      Check the render method of `Greetings`.
          at Greetings (C:\Users\meeve\OneDrive\Desktop\Cozify\smartliving-app\app\__tests__\components\Account\Greetings.js:4:21)

       5 |   return (
       6 |     <View>
    >  7 |       <Text>{hello}</Text>
         |       ^
       8 |     </View>
       9 |   );
      10 | };

      at printWarning (node_modules/react/cjs/react.development.js:220:30)
      at error (node_modules/react/cjs/react.development.js:196:5)
      at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:2215:7)
      at Greetings (app/__tests__/components/Account/Greetings.js:7:7)
      at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6016:18)
      at mountIndeterminateComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8744:13)
      at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9966:16)
      at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13800:12)
</code>```

It shows the same error for the View Component.
Should it not automatically recognize these components after initial setup?
I have installed the following:
yarn add install -dev react-test-renderer@17.0.1 @testing-library/react-native @testing-library/jest-native

The current Jest configuration in the package.json file:

```<code>  "jest": {
    "preset": "react-native",
    "coverageThreshold": {
      "app/**/selectors.{js,ts,tsx}": {
        "_comment": "Let's strive to increase coverage, instead of lowering it!",
        "lines": 57
      }
    },
    "coverageDirectory": ".coverage/",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "native"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache",
    "setupFiles": [
      "./jest.setup.js"
    ]
  }
</code>```

答: The application was set up a while back and it seems they had mocked out the react-native imports in the jest.setup.js file so that was causing the issue</p>

Body:
I have a react native app that I am trying to run tests on, I have set up a basic greeting component as shown below called Greetings.js:

import React from 'react';
import {View, Text} from 'react-native';

const Greetings = ({hello}) => {
  return (
    <View>
      <Text>{hello}</Text>
    </View>
  );
};

export default Greetings;

This is the test I am running called Greetings.test.js:

import React from 'react';
import {render, screen} from '@testing-library/react-native';
import Greetings from './Greetings';

describe('Greetings component', () => {
  it('renders hello world as a test', () => {
    render(<Greetings hello="Hello World!" />);

    const helloWorldElement = screen.getByText('Hello World!');
    expect(helloWorldElement).toBeInTheDocument();
  });
});

For some reason it doesnt recognise the react native components, this is the error when running the test:

 FAIL  app/__tests__/components/Account/Greetings.test.js
  ● Console

    console.error
      Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You li
forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.

      Check the render method of `Greetings`.
          at Greetings (C:\Users\meeve\OneDrive\Desktop\Cozify\smartliving-app\app\__tests__\components\Account\Greetings.js:4:21)

       5 |   return (
       6 |     <View>
    >  7 |       <Text>{hello}</Text>
         |       ^
       8 |     </View>
       9 |   );
      10 | };

      at printWarning (node_modules/react/cjs/react.development.js:220:30)
      at error (node_modules/react/cjs/react.development.js:196:5)
      at Object.createElementWithValidation [as createElement] (node_modules/react/cjs/react.development.js:2215:7)
      at Greetings (app/__tests__/components/Account/Greetings.js:7:7)
      at renderWithHooks (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:6016:18)
      at mountIndeterminateComponent (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:8744:13)
      at beginWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:9966:16)
      at performUnitOfWork (node_modules/react-test-renderer/cjs/react-test-renderer.development.js:13800:12)

It shows the same error for the View Component.
Should it not automatically recognize these components after initial setup?
I have installed the following:
yarn add install -dev react-test-renderer@17.0.1 @testing-library/react-native @testing-library/jest-native

The current Jest configuration in the package.json file:

  "jest": {
    "preset": "react-native",
    "coverageThreshold": {
      "app/**/selectors.{js,ts,tsx}": {
        "_comment": "Let's strive to increase coverage, instead of lowering it!",
        "lines": 57
      }
    },
    "coverageDirectory": ".coverage/",
    "moduleFileExtensions": [
      "ts",
      "tsx",
      "js",
      "jsx",
      "native"
    ],
    "testRegex": "(/__tests__/.*|\\.(test|spec))\\.(ts|tsx|js|jsx)$",
    "testPathIgnorePatterns": [
      "\\.snap$",
      "<rootDir>/node_modules/"
    ],
    "cacheDirectory": ".jest/cache",
    "setupFiles": [
      "./jest.setup.js"
    ]
  }


问:
How to trigger the simple "Add to home screen" feature (the one without service worker)
There are in fact two "Add to home screen" features on Android browsers:

The popup dialog that is automatically showed on the bottom of Chrome Android when specific conditions are met (manifest.json available, having a service worker as discussed here, website visited at least twice in > 5 minutes, etc.)

The Chrome menu item that we can trigger for any website, even if it does not have a service worker. This one simply creates a shortcut to the website on the home screen of the mobile device:

Question: How to add a button on a HTML page that triggers the creation of a home screen shortcut, like in the second bullet before? (i.e. for a very simple HTML website, without any service worker)

答:
What you need is BeforeInstallPrompt event.

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
    deferredPrompt = e;
});

const installApp = document.getElementById('installApp');

installApp.addEventListener('click', async () => {
    if (deferredPrompt !== null) {
        deferredPrompt.prompt();
        const { outcome } = await deferredPrompt.userChoice;
        if (outcome === 'accepted') {
            deferredPrompt = null;
        }
    }
});
```

Here is a article that might help you.

https://www.amitmerchant.com/adding-custom-install-button-in-progressive-web-apps/

Body:
What you need is BeforeInstallPrompt event.

let deferredPrompt;

window.addEventListener('beforeinstallprompt', (e) => {
    deferredPrompt = e;
});

const installApp = document.getElementById('installApp');

installApp.addEventListener('click', async () => {
    if (deferredPrompt !== null) {
        deferredPrompt.prompt();
        const { outcome } = await deferredPrompt.userChoice;
        if (outcome === 'accepted') {
            deferredPrompt = null;
        }
    }
});

Here is a article that might help you.

https://www.amitmerchant.com/adding-custom-install-button-in-progressive-web-apps/


问:
How to add Link/URL button into remirror toolbar?
I am using remirror to build WSYWIG editor.

The requirement is to have an "Link" icon in the toolbar, so that when a user selects text and clicks on that icon, then an options appears to add a hyperlink behind it.

I have found the LinkExtension in the docs, but I have difficulties figuring out how to add that to the toolbar.

答:
I have found out that I can add

```<code>{ type: ComponentItem.ToolbarButton, onClick: () => alert("figure out how to execute logic"), icon: 'link',  }
</code>```

but now I am struggling to figure out how to implement the logic

Body:
I have found out that I can add

{ type: ComponentItem.ToolbarButton, onClick: () => alert("figure out how to execute logic"), icon: 'link',  }

but now I am struggling to figure out how to implement the logic


问:
Execution failed for task ':app:kaptDebugKotlin' - Error Occurs while using Hilt
Added hilt dependencies:

Build.gradle(project)

```<code>def hilt_version = "2.38.1"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"
</code>```

Build.gradle(app)

```<code>plugins {
 id 'dagger.hilt.android.plugin'
 ....
 }

....

dependencies {
implementation "com.google.dagger:hilt-android:2.38.1"
kapt "com.google.dagger:hilt-compiler:2.38.1"
 .......
 }
</code>```

I also have a global application class:

MyApplication.kt

```<code>@HiltAndroidApp
class MyApplication : Application()
</code>```

In my manifest:

Manifest.xml

```<code><application
    android:allowBackup="true"
    android:name=".global.MyApplication"/>
</code>```

Now, I create a module

NetworkModule.kt

```<code>@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

}
</code>```

I get error when I run my code:

**Execution failed for task ':app:kaptDebugKotlin'.

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
java.lang.reflect.InvocationTargetException (no error message)**

When I remove these:
@Module() and @InstallIn()

The error goes away...

what could be the problem? The error shown to me is not informative at all.

答:
Keeping latest updated dagger hilt dependencies solved my problem.</p>
```<code>plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}

 //dagger
    implementation 'com.google.dagger:dagger:2.40.5'
    kapt 'com.google.dagger:dagger-compiler:2.40.5'
</code>```

Body:
Added hilt dependencies:

Build.gradle(project)

def hilt_version = "2.38.1"
classpath "com.google.dagger:hilt-android-gradle-plugin:$hilt_version"

Build.gradle(app)

plugins {
 id 'dagger.hilt.android.plugin'
 ....
 }

....

dependencies {
implementation "com.google.dagger:hilt-android:2.38.1"
kapt "com.google.dagger:hilt-compiler:2.38.1"
 .......
 }

I also have a global application class:

MyApplication.kt

@HiltAndroidApp
class MyApplication : Application()

In my manifest:

Manifest.xml

<application
    android:allowBackup="true"
    android:name=".global.MyApplication"/>

Now, I create a module

NetworkModule.kt

@Module
@InstallIn(SingletonComponent::class)
class NetworkModule {

}

I get error when I run my code:

**Execution failed for task ':app:kaptDebugKotlin'.

A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptExecution
java.lang.reflect.InvocationTargetException (no error message)**

When I remove these:
@Module() and @InstallIn()

The error goes away...

what could be the problem? The error shown to me is not informative at all.

Body:
Keeping latest updated dagger hilt dependencies solved my problem.

plugins {
id 'com.android.application'
id 'org.jetbrains.kotlin.android'
id 'kotlin-kapt'
}

 //dagger
    implementation 'com.google.dagger:dagger:2.40.5'
    kapt 'com.google.dagger:dagger-compiler:2.40.5'


问:
Pattern attribute not working as expected?
So I'm trying to make a form for my assignment, and I am using the pattern attribute in html so only certain characters are required to be typed on the text box. But for some reason, the form is saying using that I'm using an incorrect format even though I made my pattern attribute that way.

Here's an example of the code and a picture of the problem.

<form>
  Mobile Number:
  <input type="text" required id="mnumber" pattern="[0-9]">

  <input type="submit" value="submit">
</form>```

答:
```<code>pattern="[0-9]"
</code>```

allows for only a single number character to validate (and be submitted). If you want to allow more than one character, here's your options:

One or more numbers:

```<code>pattern="[0-9]+"
</code>```

Zero or more numbers:

```<code>pattern="[0-9]*"
</code>```

One to three numbers:

```<code>pattern="[0-9]{1,3}"
</code>```

Body:
pattern="[0-9]"

allows for only a single number character to validate (and be submitted). If you want to allow more than one character, here's your options:

One or more numbers:

pattern="[0-9]+"

Zero or more numbers:

pattern="[0-9]*"

One to three numbers:

pattern="[0-9]{1,3}"


问:
Django filter OrderingFilter default choice
I have created an ordering filter with django filters and I have been wondering how I can set the default choice and remove the empty choice.

```<code>class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')

    o = django_filters.OrderingFilter(
        choices=(
            ("created", _("Created, old to new")),
            ("-created", _("Created, new to old"))
        ),
        fields = (
            "created", "created"
        )
    )
</code>```

When I render the filter form the empty choice "----" is being shown as default. I would like to set one the of filtering choices as default and remove the empty choice.

答:
The fix was to disable the empty option by setting the empty_label and null_label to None. This was the first option is the default option. Note, the first option should algin with the default ordering of your queryset so that it matches when loading the page without using a filter.</p>
```<code>class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')

    o = django_filters.OrderingFilter(
        choices=(
            ('created', _('Created, old to new')),
            ('-created', _('Created, new to old'))
        ),
        fields = (
            'created', 'created'
        ),
        empty_label = None,
        null_label = None
    )

</code>```

Body:
I have created an ordering filter with django filters and I have been wondering how I can set the default choice and remove the empty choice.

class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')

    o = django_filters.OrderingFilter(
        choices=(
            ("created", _("Created, old to new")),
            ("-created", _("Created, new to old"))
        ),
        fields = (
            "created", "created"
        )
    )

When I render the filter form the empty choice "----" is being shown as default. I would like to set one the of filtering choices as default and remove the empty choice.

Body:
The fix was to disable the empty option by setting the empty_label and null_label to None. This was the first option is the default option. Note, the first option should algin with the default ordering of your queryset so that it matches when loading the page without using a filter.

class MyFilter(django_filters.FilterSet):
    name = django_filters.CharFilter(lookup_expr='icontains')

    o = django_filters.OrderingFilter(
        choices=(
            ('created', _('Created, old to new')),
            ('-created', _('Created, new to old'))
        ),
        fields = (
            'created', 'created'
        ),
        empty_label = None,
        null_label = None
    )


问:
What is the usage of * as an argument in discord.py API functions?
I referenced the code in this answer about an avatar command for Discord Python bots:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)
```

What is the function of * as its own argument? I expect to see it as *args or **kwargs

答:
What Stanley Ulili said is correct when using basic python, but in the context of discord.py, the meaning of * is a bit different.

* basically means that variable alone will consume the rest of the command parameter. Or else each parameter is limited to only one word unless using quotes. Adding the * here would make !avatar Wasi Master possible for a member with the name Wasi Master. Otherwise it would raise a error saying member "Wasi" not found, since it only accepted the first word as the paremeter avamember and excluded the rest. Using * would make it accept the entire "Wasi Master" as the avamember variable

Body:
I referenced the code in this answer about an avatar command for Discord Python bots:

@commands.command()
async def avatar(self, ctx, *,  avamember : discord.Member=None):
    userAvatarUrl = avamember.avatar_url
    await ctx.send(userAvatarUrl)

What is the function of * as its own argument? I expect to see it as *args or **kwargs


问:
Nginx cache size not growing above 344GB
I have Nginx cache server built on Ubuntu 18 and with docker image nginx:1.19.10-alpine.

Ubuntu 18 disk usage details given below for reference

```<code>ubuntu@host_name:~$ df -h
Filesystem                  Size  Used Avail Use% Mounted on
udev                        126G     0  126G   0% /dev
tmpfs                        26G  1.4M   26G   1% /run
/dev/mapper/vg_system-root  193G  8.9G  176G   5% /
tmpfs                       126G     0  126G   0% /dev/shm
tmpfs                       5.0M     0  5.0M   0% /run/lock
tmpfs                       126G     0  126G   0% /sys/fs/cgroup
/dev/mapper/vg_data-srv      24T  369G   24T   2% /srv
/dev/sda1                   453M  364M   62M  86% /boot
overlay                     193G  8.9G  176G   5% /var/lib/docker/overlay2/64_characters_random/merged
tmpfs                        26G     0   26G   0% /run/user/1646269961
</code>```

Docker container details

```<code>ubuntu@host_name:~$ sudo docker ps
CONTAINER ID   IMAGE                  COMMAND                  CREATED      STATUS       PORTS     NAMES
contnr_idxyz   nginx:1.19.10-alpine   "/docker-entrypoint.…"   5 days ago   Up 9 hours             contnr_name
</code>```

Nginx Configuration for reference

```<code>user@host-name:/srv/mytool/nginx/config$ cat proxy.conf
access_log          off;
root                /var/log/nginx;
open_log_file_cache max=100;

log_format mytoollogformat
    '$time_iso8601 $remote_addr $status $request_time $body_bytes_sent '
    '$upstream_cache_status "$request" "$http_user_agent"';

proxy_http_version 1.1;
client_max_body_size 10g;

# R/W timeout for origin server
proxy_read_timeout 15m;
proxy_send_timeout 15m;

# R/W timeout for clients
client_body_timeout   15m;
client_header_timeout 15m;
send_timeout          15m;

# TODO: ssl_stapling and ssl_ciphers
ssl_prefer_server_ciphers on;
ssl_session_cache         shared:SSL:10m;

proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-mytool-Cache-Host $scheme://$host;

proxy_redirect         off;

proxy_cache_path       /var/cache/nginx levels=1:2 keys_zone=mytool:10m max_size=22000g inactive=180d;
proxy_cache_key        $host$uri$is_args$args$slice_range;
proxy_set_header       Range $slice_range;
proxy_cache_valid      200 206 2y;
proxy_cache_revalidate on;

add_header X-Cache-Status $upstream_cache_status;

proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_429;
</code>```

Removed server block as it comes out of context for the current issue and also due to security reason.

Let me explain my issue in detail. We have main server(proxy_passed server) which has hundreds of TBs of file which are static resources. When we set up cache server it was filling cache and serving files from cache well. But over time noticed that cache size is not increasing above 344GB

```<code>user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
344G    ./cache
52K     ./config
1004K   ./log
user@host_name:/srv/mytool/nginx$
</code>```

I have wrote a script to download about 500GB's of files. But It never increased the size of cache above 344GB.

Experiments done so far

Added max_size=100000g (along with old value min_free=1000g)

Modified max_size=22000g (set less value than /srv size which is 24TB)

removed min_free=1000g (Assuming min_free is somehow clearing cache)

Modified

proxy_cache_valid 200 206 1h;  to  proxy_cache_valid 200 206 2y;

For all above experiments, after configuration change i have restarted docker container and ran script of downloading 500GB of files through the cache server. But even though cache size was reaching 380 to 400 GB, but within an hour it was suddenly dropping to 344GB.

I left with no clue, why cache is not filling up completely even though i have allocated 24TB for /srv

Is it issue with Nginx? I mean for free version of Nginx there might be any limitations.. Should i go with Nginx plus. Or there might be configuration mistake.

Any guess would help me. Thanks in advance

Update

What are the soft and hard limits for max open files on the cache server?

```<code>$ cat /proc/sys/fs/file-max
26375980
$ ulimit -Hn
1048576
$ ulimit -Sn
1024
</code>```

have you set limits in your nginx conf using worker_rlimit_nofile?

Currently no settings of worker_rlimit_nofile

```<code>/ # cat /etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}
</code>```

Do you have anything in the error logs?

Below given filtered/distinct logs

```<code>$ cat /srv/mytool/nginx/log/error.log
2022/01/09 05:56:35 [warn] 22#22: *10 an upstream response is buffered to a temporary file /var/cache/nginx/proxy_temp/1/00/0000000001 while reading upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /dists/58.2.A.0.409/semc/binary-arm/Packages HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/Packages", host: "dev.mytool-region.mycompany.com"
2022/01/09 06:09:21 [warn] 22#22: *35 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000006, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "POST /masked_path/all HTTP/1.1", host: "dev.mytool-region.mycompany.com"
2022/01/09 08:19:01 [error] 22#22: *120 etag mismatch in slice response while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", subrequest: "/masked_path/xyz.zip", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/09 18:19:12 [warn] 22#22: *1566 upstream server temporarily disabled while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[masked_IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/10 01:23:20 [error] 22#22: *2920 etag mismatch in slice response while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", subrequest: "/masked_path/xyz.zip", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/21 07:43:47 [error] 36#36: *441913 upstream timed out (110: Operation timed out) while SSL handshaking to upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/21 07:46:17 [warn] 37#37: *442070 upstream server temporarily disabled while SSL handshaking to upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"

Total 25k rows same as below within 10 days of logs
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry 55a25a5037f198bbec6cd49100bb1b76, count:1
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry e996d5e104f405444a579cd491faf3a8, count:1
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry 394517a8ed8e43949003b3f7538dc471, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 4f92d3a72f64b7bafdbb3f0b66d8e638, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry be41b259a3e8f9698e0976639883a423, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 1da19b571ea4bce1428251689f0a7c69, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 2a4cac0c28ea430e7eef3f808cf1e06f, count:1
2022/01/11 05:37:18 [alert] 70#70: ignore long locked inactive cache entry 53a826f6931cf0f16020bcae100af347, count:1
</code>```

Update 2:
Tried the same with nginx:perl docker container. It also didn't work and cache size observed that even though it grows beyond 392GB but within couple hours suddenly dropped to 344GB. Command used to start container given below

```<code>sudo docker run \
--detach \
--restart unless-stopped \
--volume /srv/mytool/nginx/config:/etc/nginx/conf.d:ro \
--volume /srv/mytool/nginx/cache:/var/cache/nginx \
--volume /srv/mytool/nginx/log:/var/log/nginx \
nginx:perl
</code>```

Update Again

Avoided docker container nginx:1.19.10-alpine
And did simple Nginx configuration as given below

```<code>sudo apt install nginx
systemctl status nginx

$ sudo ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
$ sudo ufw allow 'Nginx Full'
Rules updated
Rules updated (v6)
</code>```

Modify default.conf in /etc/nginx/sites-available

```<code>proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=custom_cache:10m inactive=180d;

upstream origin_server {
    server dev.mytool-region.mycompany.com;
}
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name _;

        location / {
            include proxy_params;
            proxy_pass http://origin_server;
        }

        location ~ ^/(path1|path2|path3|path4)/ {
            slice       5m;
            proxy_cache custom_cache;

            proxy_pass http://origin_server;
            proxy_cache_valid 200 206 2y;
            add_header X-Proxy-Cache $upstream_cache_status;
        }
}
</code>```

Downloaded about ~500GB. It worked and cache filled as expected

```<code>ubuntu@host_name:/var/cache$ sudo du -sh ./*
128K    ./apparmor
82M     ./apt
4.8M    ./debconf
20K     ./ldconfig
1.2M    ./man
0       ./motd-news
518G    ./nginx
4.0K    ./pollinate
20K     ./snapd
ubuntu@host_name:/var/cache$
</code>```

But still don't know the exact reason or what is wrong with my configuration. Still trial is going on.

One more trial

Used old configuration(docker nginx:1.19.10-alpine
And moved proxy_cache_valid      200 206 2y; inside

```<code>location ~ ^/(path1|path2|path3|path4)/ {
</code>```

But this also not worked.

答:
Problem with nginx cache slicing is when you configure cache slicing of say 5 MB.
It will end up in creating sliced cache files in cache directory.
Number of files that can be cached up is directly propotional to keys_zone size
keys_zone=mytool:10m

Since i had 10m(10 mega byte) for cache keys it was allowing maximum 71203 files.
Document says

In addition, all active keys and information about data are stored in
a shared memory zone, whose name and size are configured by the
keys_zone parameter. One megabyte zone can store about 8 thousand
keys.

As part of commercial subscription, the shared memory zone also stores
extended cache information, thus, it is required to specify a larger
zone size for the same number of keys. For example, one megabyte zone
can store about 4 thousand keys.

So modifying keys_zone to larger value keys_zone=mytool:1000m Fixed issue.

You can observe cache file count was not growing after 71203 for keys_zone=mytool:10m

```<code>user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
326G    ./cache
52K     ./config
406M    ./log
user@host_name:/srv/mytool/nginx$ sudo find cache/ -type f | wc -l
71203
</code>```

But it started growing in size by allowing cached file count seamlessly for keys_zone=mytool:1000m

```<code>user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
518G    ./cache
52K     ./config
4.6M    ./log
user@host_name:/srv/mytool/nginx$ sudo find cache/ -type f | wc -l
107243
</code>```

Body:
I have Nginx cache server built on Ubuntu 18 and with docker image nginx:1.19.10-alpine.

Ubuntu 18 disk usage details given below for reference

ubuntu@host_name:~$ df -h
Filesystem                  Size  Used Avail Use% Mounted on
udev                        126G     0  126G   0% /dev
tmpfs                        26G  1.4M   26G   1% /run
/dev/mapper/vg_system-root  193G  8.9G  176G   5% /
tmpfs                       126G     0  126G   0% /dev/shm
tmpfs                       5.0M     0  5.0M   0% /run/lock
tmpfs                       126G     0  126G   0% /sys/fs/cgroup
/dev/mapper/vg_data-srv      24T  369G   24T   2% /srv
/dev/sda1                   453M  364M   62M  86% /boot
overlay                     193G  8.9G  176G   5% /var/lib/docker/overlay2/64_characters_random/merged
tmpfs                        26G     0   26G   0% /run/user/1646269961

Docker container details

ubuntu@host_name:~$ sudo docker ps
CONTAINER ID   IMAGE                  COMMAND                  CREATED      STATUS       PORTS     NAMES
contnr_idxyz   nginx:1.19.10-alpine   "/docker-entrypoint.…"   5 days ago   Up 9 hours             contnr_name

Nginx Configuration for reference

user@host-name:/srv/mytool/nginx/config$ cat proxy.conf
access_log          off;
root                /var/log/nginx;
open_log_file_cache max=100;

log_format mytoollogformat
    '$time_iso8601 $remote_addr $status $request_time $body_bytes_sent '
    '$upstream_cache_status "$request" "$http_user_agent"';

proxy_http_version 1.1;
client_max_body_size 10g;

# R/W timeout for origin server
proxy_read_timeout 15m;
proxy_send_timeout 15m;

# R/W timeout for clients
client_body_timeout   15m;
client_header_timeout 15m;
send_timeout          15m;

# TODO: ssl_stapling and ssl_ciphers
ssl_prefer_server_ciphers on;
ssl_session_cache         shared:SSL:10m;

proxy_set_header Connection "";
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-mytool-Cache-Host $scheme://$host;

proxy_redirect         off;

proxy_cache_path       /var/cache/nginx levels=1:2 keys_zone=mytool:10m max_size=22000g inactive=180d;
proxy_cache_key        $host$uri$is_args$args$slice_range;
proxy_set_header       Range $slice_range;
proxy_cache_valid      200 206 2y;
proxy_cache_revalidate on;

add_header X-Cache-Status $upstream_cache_status;

proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504 http_429;

Removed server block as it comes out of context for the current issue and also due to security reason.

Let me explain my issue in detail. We have main server(proxy_passed server) which has hundreds of TBs of file which are static resources. When we set up cache server it was filling cache and serving files from cache well. But over time noticed that cache size is not increasing above 344GB

user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
344G    ./cache
52K     ./config
1004K   ./log
user@host_name:/srv/mytool/nginx$

I have wrote a script to download about 500GB's of files. But It never increased the size of cache above 344GB.

Experiments done so far

Added max_size=100000g (along with old value min_free=1000g)

Modified max_size=22000g (set less value than /srv size which is 24TB)

removed min_free=1000g (Assuming min_free is somehow clearing cache)

Modified

proxy_cache_valid 200 206 1h;  to  proxy_cache_valid 200 206 2y;

For all above experiments, after configuration change i have restarted docker container and ran script of downloading 500GB of files through the cache server. But even though cache size was reaching 380 to 400 GB, but within an hour it was suddenly dropping to 344GB.

I left with no clue, why cache is not filling up completely even though i have allocated 24TB for /srv

Is it issue with Nginx? I mean for free version of Nginx there might be any limitations.. Should i go with Nginx plus. Or there might be configuration mistake.

Any guess would help me. Thanks in advance

Update

What are the soft and hard limits for max open files on the cache server?

$ cat /proc/sys/fs/file-max
26375980
$ ulimit -Hn
1048576
$ ulimit -Sn
1024

have you set limits in your nginx conf using worker_rlimit_nofile?

Currently no settings of worker_rlimit_nofile

/ # cat /etc/nginx/nginx.conf

user  nginx;
worker_processes  auto;

error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
}

http {
    include       /etc/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include /etc/nginx/conf.d/*.conf;
}

Do you have anything in the error logs?

Below given filtered/distinct logs

$ cat /srv/mytool/nginx/log/error.log
2022/01/09 05:56:35 [warn] 22#22: *10 an upstream response is buffered to a temporary file /var/cache/nginx/proxy_temp/1/00/0000000001 while reading upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /dists/58.2.A.0.409/semc/binary-arm/Packages HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/Packages", host: "dev.mytool-region.mycompany.com"
2022/01/09 06:09:21 [warn] 22#22: *35 a client request body is buffered to a temporary file /var/cache/nginx/client_temp/0000000006, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "POST /masked_path/all HTTP/1.1", host: "dev.mytool-region.mycompany.com"
2022/01/09 08:19:01 [error] 22#22: *120 etag mismatch in slice response while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", subrequest: "/masked_path/xyz.zip", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/09 18:19:12 [warn] 22#22: *1566 upstream server temporarily disabled while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[masked_IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/10 01:23:20 [error] 22#22: *2920 etag mismatch in slice response while reading response header from upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", subrequest: "/masked_path/xyz.zip", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/21 07:43:47 [error] 36#36: *441913 upstream timed out (110: Operation timed out) while SSL handshaking to upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"
2022/01/21 07:46:17 [warn] 37#37: *442070 upstream server temporarily disabled while SSL handshaking to upstream, client: masked_IPv6_address, server: dev.mytool-region.mycompany.com, request: "GET /masked_path/xyz.zip HTTP/1.1", upstream: "https://[IPv6_address]:443/masked_path/xyz.zip", host: "dev.mytool-region.mycompany.com"

Total 25k rows same as below within 10 days of logs
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry 55a25a5037f198bbec6cd49100bb1b76, count:1
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry e996d5e104f405444a579cd491faf3a8, count:1
2022/01/11 05:36:58 [alert] 70#70: ignore long locked inactive cache entry 394517a8ed8e43949003b3f7538dc471, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 4f92d3a72f64b7bafdbb3f0b66d8e638, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry be41b259a3e8f9698e0976639883a423, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 1da19b571ea4bce1428251689f0a7c69, count:1
2022/01/11 05:37:08 [alert] 70#70: ignore long locked inactive cache entry 2a4cac0c28ea430e7eef3f808cf1e06f, count:1
2022/01/11 05:37:18 [alert] 70#70: ignore long locked inactive cache entry 53a826f6931cf0f16020bcae100af347, count:1

Update 2:
Tried the same with nginx:perl docker container. It also didn't work and cache size observed that even though it grows beyond 392GB but within couple hours suddenly dropped to 344GB. Command used to start container given below

sudo docker run \
--detach \
--restart unless-stopped \
--volume /srv/mytool/nginx/config:/etc/nginx/conf.d:ro \
--volume /srv/mytool/nginx/cache:/var/cache/nginx \
--volume /srv/mytool/nginx/log:/var/log/nginx \
nginx:perl

Update Again

Avoided docker container nginx:1.19.10-alpine
And did simple Nginx configuration as given below

sudo apt install nginx
systemctl status nginx

$ sudo ufw app list
Available applications:
  Nginx Full
  Nginx HTTP
  Nginx HTTPS
  OpenSSH
$ sudo ufw allow 'Nginx Full'
Rules updated
Rules updated (v6)

Modify default.conf in /etc/nginx/sites-available

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=custom_cache:10m inactive=180d;

upstream origin_server {
    server dev.mytool-region.mycompany.com;
}
server {
        listen 80 default_server;
        listen [::]:80 default_server;

        server_name _;

        location / {
            include proxy_params;
            proxy_pass http://origin_server;
        }

        location ~ ^/(path1|path2|path3|path4)/ {
            slice       5m;
            proxy_cache custom_cache;

            proxy_pass http://origin_server;
            proxy_cache_valid 200 206 2y;
            add_header X-Proxy-Cache $upstream_cache_status;
        }
}

Downloaded about ~500GB. It worked and cache filled as expected

ubuntu@host_name:/var/cache$ sudo du -sh ./*
128K    ./apparmor
82M     ./apt
4.8M    ./debconf
20K     ./ldconfig
1.2M    ./man
0       ./motd-news
518G    ./nginx
4.0K    ./pollinate
20K     ./snapd
ubuntu@host_name:/var/cache$

But still don't know the exact reason or what is wrong with my configuration. Still trial is going on.

One more trial

Used old configuration(docker nginx:1.19.10-alpine
And moved proxy_cache_valid      200 206 2y; inside

location ~ ^/(path1|path2|path3|path4)/ {

But this also not worked.

Body:
Problem with nginx cache slicing is when you configure cache slicing of say 5 MB.
It will end up in creating sliced cache files in cache directory.
Number of files that can be cached up is directly propotional to keys_zone size
keys_zone=mytool:10m

Since i had 10m(10 mega byte) for cache keys it was allowing maximum 71203 files.
Document says

In addition, all active keys and information about data are stored in
a shared memory zone, whose name and size are configured by the
keys_zone parameter. One megabyte zone can store about 8 thousand
keys.

As part of commercial subscription, the shared memory zone also stores
extended cache information, thus, it is required to specify a larger
zone size for the same number of keys. For example, one megabyte zone
can store about 4 thousand keys.

So modifying keys_zone to larger value keys_zone=mytool:1000m Fixed issue.

You can observe cache file count was not growing after 71203 for keys_zone=mytool:10m

user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
326G    ./cache
52K     ./config
406M    ./log
user@host_name:/srv/mytool/nginx$ sudo find cache/ -type f | wc -l
71203

But it started growing in size by allowing cached file count seamlessly for keys_zone=mytool:1000m

user@host_name:/srv/mytool/nginx$ sudo du -sh ./*
518G    ./cache
52K     ./config
4.6M    ./log
user@host_name:/srv/mytool/nginx$ sudo find cache/ -type f | wc -l
107243


问:
withAuth module not exported in next-auth in Next.js
I am trying to add a middleware in the route /admin at next.js, and in the file " _middleware.js" it is like this:

```<code>    import { withAuth } from "next-auth/middleware";

export default withAuth({
  callbacks: {
    authorized({ req, token }) {
      if (token) return true; // If there is a token, the user is authenticated
    },
  },
});
</code>```

Error:

```<code>./pages/admin/_middleware.js:1:0
Module not found: Package path ./middleware is not exported from package
</code>```

Path:

```<code>    pages
    |-------admin
    |--------------_middleware.js
    |--------------index.js
</code>```

答:
The solution, update your nextAuth dependence.
withAuth was an update at 4.2.0.
https://github.com/nextauthjs/next-auth/releases/tag/v4.2.0
Special thanks to juliomalves</p>

Body:
I am trying to add a middleware in the route /admin at next.js, and in the file " _middleware.js" it is like this:

    import { withAuth } from "next-auth/middleware";

export default withAuth({
  callbacks: {
    authorized({ req, token }) {
      if (token) return true; // If there is a token, the user is authenticated
    },
  },
});

Error:

./pages/admin/_middleware.js:1:0
Module not found: Package path ./middleware is not exported from package

Path:

    pages
    |-------admin
    |--------------_middleware.js
    |--------------index.js


问:
SQL UNION failed
This is my query:

```<code>select dept_name, count(*)  as student_number
from Student s join Department d
on s.dept_id=d.dept_id
group by dept_name
order by student_number desc, dept_name asc
UNION
select d.dept_name, 0 as student_number
from Department d left join Student s
on s.dept_id=d.dept_id
where student_id  is NULL
</code>```

Error:

You have an error in your SQL syntax; check the manual that corespond to your mysql server version for the right syntax to use near 'UNION'
select d.dept_name, 0 as student_number
from Department d left join Student s

I have 2 tables
the first:

Column Name
Type

student_id
int

student_name
varchar

gender
varchar

dept_id
int

the second

Column Name
Type

dept_id
int

dept_name
varchar

答:
The problem with your query is the ORDER BY clause, which is not allowed in the first of the unioned queries.

It should be placed last to the final result of the union.

But, you don't need UNION.

You can do it with a LEFT join of Department to Student:

```<code>SELECT d.dept_name, count(s.student_id) AS student_number
FROM Department d LEFT JOIN Student s
ON s.dept_id = d.dept_id
GROUP BY d.dept_name
ORDER BY student_number DESC, dept_name ASC;
</code>```

Title: SQL UNION failed

Body:
This is my query:

select dept_name, count(*)  as student_number
from Student s join Department d
on s.dept_id=d.dept_id
group by dept_name
order by student_number desc, dept_name asc
UNION
select d.dept_name, 0 as student_number
from Department d left join Student s
on s.dept_id=d.dept_id
where student_id  is NULL

Error:

You have an error in your SQL syntax; check the manual that corespond to your mysql server version for the right syntax to use near 'UNION'
select d.dept_name, 0 as student_number
from Department d left join Student s

I have 2 tables
the first:

Column Name
Type

student_id
int

student_name
varchar

gender
varchar

dept_id
int

the second

Column Name
Type

dept_id
int

dept_name
varchar

Body:
The problem with your query is the ORDER BY clause, which is not allowed in the first of the unioned queries.

It should be placed last to the final result of the union.

But, you don't need UNION.

You can do it with a LEFT join of Department to Student:

SELECT d.dept_name, count(s.student_id) AS student_number
FROM Department d LEFT JOIN Student s
ON s.dept_id = d.dept_id
GROUP BY d.dept_name
ORDER BY student_number DESC, dept_name ASC;


问:
Learning to use Tweepy and Twitter API
I'm currently trying to learn the Twitter API within Python. My code is this:

```<code>import tweepy

consumer_key = "Consumer Key"
consumer_secret = "Consumer Secret"
access_token = "Access Token"
access_token_secret = "Access Token Secret"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_acess_token(access_token, access_token_secret)
auth.secure = True
api = tweepy.API(auth)

tweet = "This tweet was made from a program"
api.update_status(status=tweet)
</code>```

However this is the error that the code is giving me:

```<code>Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

Process finished with exit code 1
</code>```

Do I really need to apply for further access just to tweet one thing? Thanks

答: Twitter has a newer (v2) API. You should use tweepy.Client to be able to use the new endpoints without signing up.</p>

Title: Learning to use Tweepy and Twitter API

Body:
I'm currently trying to learn the Twitter API within Python. My code is this:

import tweepy

consumer_key = "Consumer Key"
consumer_secret = "Consumer Secret"
access_token = "Access Token"
access_token_secret = "Access Token Secret"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_acess_token(access_token, access_token_secret)
auth.secure = True
api = tweepy.API(auth)

tweet = "This tweet was made from a program"
api.update_status(status=tweet)

However this is the error that the code is giving me:

Forbidden: 403 Forbidden
453 - You currently have Essential access which includes access to Twitter API v2 endpoints only. If you need access to this endpoint, you’ll need to apply for Elevated access via the Developer Portal. You can learn more here: https://developer.twitter.com/en/docs/twitter-api/getting-started/about-twitter-api#v2-access-leve

Process finished with exit code 1

Do I really need to apply for further access just to tweet one thing? Thanks


问:
The command dal:create:schema does not create foreign keys
Given the following example for an Entity-Definition, there is a foreign key defined. As a developer and database engineer i would expect that the command dal:create:schema would also create the expected foreign keys. But this is not the case.

```<code> return new FieldCollection([
    (new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),

    (new LongTextField('comment', 'name'))->addFlags(new Required()),

    (new FkField('order_id', 'orderId', OrderDefinition::class))->addFlags(new Required()),
    new OneToOneAssociationField('order', 'order_id', 'id', OrderDefinition::class, false),

            new CreatedAtField(),
            new UpdatedAtField()
        ]);
</code>```

Instead this is the result:

```<code>CREATE TABLE `order_refund` (
    `id` BINARY(16) NOT NULL,
    `comment` LONGTEXT NOT NULL,
    `order_id` BINARY(16) NOT NULL,
    `created_at` DATETIME(3) NOT NULL,
    `updated_at` DATETIME(3) NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
</code>```

However, it seems like that ManyToOneAssociations will add foreign keys. Is there something missing in the entity definition?

答:
The command you mentioned is using the SchemaGenerator which has a method to generate Foreign keys:

\Shopware\Core\Framework\DataAbstractionLayer\SchemaGenerator::generateForeignKeys

Looking at this method it seems to work only fields of the type ManyToOneAssociationField

```<code>private function generateForeignKeys(EntityDefinition $definition): string
{
    $fields = $definition->getFields()->filter(
        function (Field $field) {
            if (!$field instanceof ManyToOneAssociationField) {
                return false;
            }

            return true;
        }
    );
</code>```

I also think it is a shortcoming of this function that it does not generate foreign keys for fields of the type OneToOneAssociationField. Maybe you can try to adjust this filtering and see if it works and make a pull request on GitHub for the benefit of yourself and other developers?

Body:
Given the following example for an Entity-Definition, there is a foreign key defined. As a developer and database engineer i would expect that the command dal:create:schema would also create the expected foreign keys. But this is not the case.

 return new FieldCollection([
    (new IdField('id', 'id'))->addFlags(new PrimaryKey(), new Required()),

    (new LongTextField('comment', 'name'))->addFlags(new Required()),

    (new FkField('order_id', 'orderId', OrderDefinition::class))->addFlags(new Required()),
    new OneToOneAssociationField('order', 'order_id', 'id', OrderDefinition::class, false),

            new CreatedAtField(),
            new UpdatedAtField()
        ]);

Instead this is the result:

CREATE TABLE `order_refund` (
    `id` BINARY(16) NOT NULL,
    `comment` LONGTEXT NOT NULL,
    `order_id` BINARY(16) NOT NULL,
    `created_at` DATETIME(3) NOT NULL,
    `updated_at` DATETIME(3) NULL,
    PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

However, it seems like that ManyToOneAssociations will add foreign keys. Is there something missing in the entity definition?

Body:
The command you mentioned is using the SchemaGenerator which has a method to generate Foreign keys:

\Shopware\Core\Framework\DataAbstractionLayer\SchemaGenerator::generateForeignKeys

Looking at this method it seems to work only fields of the type ManyToOneAssociationField

private function generateForeignKeys(EntityDefinition $definition): string
{
    $fields = $definition->getFields()->filter(
        function (Field $field) {
            if (!$field instanceof ManyToOneAssociationField) {
                return false;
            }

            return true;
        }
    );

I also think it is a shortcoming of this function that it does not generate foreign keys for fields of the type OneToOneAssociationField. Maybe you can try to adjust this filtering and see if it works and make a pull request on GitHub for the benefit of yourself and other developers?


问:
Array with only even number
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

```<code>#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done
</code>```

but got errors like:
line 15: syntax error near unexpected token `do'

答:
There are a couple things you can do:

use the modulus function for your language:

for x in {18..2500} {

if (x mod 2=0) {

do something;}

step through your For loop 2 at a time:

for x in {18..2500} step 2 {

do something;}

Title: Array with only even number

Body:
for X in {18..2500} ; is one line of my script, which means to pick number one by one like: 18,19,20,21,22,23....till 2500

However I find I only need even number right now: 18,20,22,24.....2500

Then what should I do by a slight modify of the line?

Thanks

edit:
It's bash...

My script is now changed to:

#!/bin/bash

TASK=1101;

NUM=9;

TEND=1100;

for X in {18..2500};{

   if (X % 2 == 0);

   do

     echo "$X      echo \"Wait until $NUM job is done\" $NUM" ;

     NUM=$((NUM+2)) ;

     X=$((X+1)) ;

     TEND=$((TEND+100)) ;

     echo "$X      -t $TASK-$TEND jobs.sh" ;

     TASK=$((TASK+100)) ;}

done

but got errors like:
line 15: syntax error near unexpected token `do'


问:
How to remove wrapping p tags from acf wysiwyg field string for later custom excerpt processing
I have a WYSIWG field with the advanced custom fields plugin. When i query it with :

```<code><p class="bran-hn news-excerpt"><?php echo custom_field_excerpt('news_post'); ?></p>
</code>```

the output looks like that:

```<code><p class="bran-hn news-excerpt"></p>
<p>Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]</p>
<p></p>
</code>```

But i would have expected and want something like:

```<code><p class="bran-hn news-excerpt">Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]</p>
</code>```

i tried to add

```<code>$text = strip_tags ($text);
</code>```

right before the strip_shortcodes call into the function querying the wysiwyg custom field:

```<code>function custom_field_excerpt($title) {
    global $post;
    $text = get_field($title);
    if ( '' != $text ) {
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = 35; // 20 words
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('the_excerpt', $text);
}
</code>```

but also no effect. so is there a way to strip the wrapping p tags while keeping possible tags inside the strings text body like e.g. a tags for links. Best regards Ralf

答:
```<code>remove_filter ('acf_the_content', 'wpautop');
</code>```

Body:
I have a WYSIWG field with the advanced custom fields plugin. When i query it with :

<?php echo custom_field_excerpt('news_post'); ?>

the output looks like that:

Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]

But i would have expected and want something like:

Worf, It's better than music. It's jazz. Mr. Crusher, ready a collision course with the Borg ship. This is not about revenge. This is about justice. The Federation's gone; the Borg is everywhere! In all trust, [...]

i tried to add

$text = strip_tags ($text);

right before the strip_shortcodes call into the function querying the wysiwyg custom field:

function custom_field_excerpt($title) {
    global $post;
    $text = get_field($title);
    if ( '' != $text ) {
        $text = strip_shortcodes( $text );
        $text = apply_filters('the_content', $text);
        $text = str_replace(']]>', ']]>', $text);
        $excerpt_length = 35; // 20 words
        $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]');
        $text = wp_trim_words( $text, $excerpt_length, $excerpt_more );
    }
    return apply_filters('the_excerpt', $text);
}

but also no effect. so is there a way to strip the wrapping p tags while keeping possible tags inside the strings text body like e.g. a tags for links. Best regards Ralf