问:
Access denied for user 'root'@'192.168.128.3' in Laravel project in Docker
I try to set up Laravel project in Docker.
My docker-compose.yml:

```<code>version: "2"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MYSQL_DATABASE=identy
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_HOST=db
    ports:
      - "8080:80"
    volumes:
      - .:/var/www
    depends_on:
      - db
    networks:
      - identy-network

  db:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=654321
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_DATABASE=identy
    volumes:
      - "mysql_data:/var/lib/mysql"
      - ./data/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    networks:
      - identy-network

volumes:
  mysql_data:
    driver: local

networks:
  identy-network:
</code>```

My Dockerfile:

```<code>FROM php:7.4-apache

RUN apt-get update \
    && apt-get install -y vim git zlib1g-dev mariadb-client libzip-dev \
    && docker-php-ext-install zip mysqli pdo_mysql \
    && pecl install xdebug \
    && docker-php-ext-enable xdebug \
    && echo 'xdebug.remote_enable=on' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_host=host.docker.internal' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_port=9000' >>  /usr/local/etc/php/conf.d/xdebug.ini \
    && a2enmod rewrite \
    && sed -i 's!/var/www/html!/var/www/public!g' /etc/apache2/sites-available/000-default.conf \
    && mv /var/www/html /var/www/public \
    && curl -sS https://getcomposer.org/installer \
    | php -- --install-dir=/usr/local/bin --filename=composer \
    && echo "AllowEncodedSlashes On" >> /etc/apache2/apache2.conf

WORKDIR /var/www
</code>```

.env:

```<code>...
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=identy
DB_USERNAME=root
DB_PASSWORD=654321
...
</code>```

When I run
docker exec identy-api_web_1 php artisan migrate
I get error:
**  Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.144.3' (using password: YES) (SQL: select * from information_schema.tables where table_schema = identy and table_name = migrations and table_type = 'BASE TABLE')
**

I have no idea why it doesn't work.

答: I think you should remove the volumes data and try again.</p>

Body:
I try to set up Laravel project in Docker.
My docker-compose.yml:

version: "2"
services:
  web:
    build:
      context: .
      dockerfile: Dockerfile
    environment:
      - MYSQL_DATABASE=identy
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_HOST=db
    ports:
      - "8080:80"
    volumes:
      - .:/var/www
    depends_on:
      - db
    networks:
      - identy-network

  db:
    image: mysql:8.0
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=654321
      - MYSQL_USER=root
      - MYSQL_PASSWORD=654321
      - MYSQL_DATABASE=identy
    volumes:
      - "mysql_data:/var/lib/mysql"
      - ./data/schema.sql:/docker-entrypoint-initdb.d/schema.sql
    networks:
      - identy-network

volumes:
  mysql_data:
    driver: local

networks:
  identy-network:

My Dockerfile:

FROM php:7.4-apache

RUN apt-get update \
    && apt-get install -y vim git zlib1g-dev mariadb-client libzip-dev \
    && docker-php-ext-install zip mysqli pdo_mysql \
    && pecl install xdebug \
    && docker-php-ext-enable xdebug \
    && echo 'xdebug.remote_enable=on' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_host=host.docker.internal' >> /usr/local/etc/php/conf.d/xdebug.ini \
    && echo 'xdebug.remote_port=9000' >>  /usr/local/etc/php/conf.d/xdebug.ini \
    && a2enmod rewrite \
    && sed -i 's!/var/www/html!/var/www/public!g' /etc/apache2/sites-available/000-default.conf \
    && mv /var/www/html /var/www/public \
    && curl -sS https://getcomposer.org/installer \
    | php -- --install-dir=/usr/local/bin --filename=composer \
    && echo "AllowEncodedSlashes On" >> /etc/apache2/apache2.conf

WORKDIR /var/www

.env:

...
DB_CONNECTION=mysql
DB_HOST=db
DB_PORT=3306
DB_DATABASE=identy
DB_USERNAME=root
DB_PASSWORD=654321
...

When I run
docker exec identy-api_web_1 php artisan migrate
I get error:
**  Illuminate\Database\QueryException

SQLSTATE[HY000] [1045] Access denied for user 'root'@'192.168.144.3' (using password: YES) (SQL: select * from information_schema.tables where table_schema = identy and table_name = migrations and table_type = 'BASE TABLE')
**

I have no idea why it doesn't work.


来源: stackexchange

问:
What is difference: AttributeCollection.Contains(TKey) vs AttributeCollection.ContainsKey(TKey)?
What is difference for AttributeCollection.Contains(TKey) and AttributeCollection.ContainsKey(TKey)? I doesn't see any difference in the official manual.

```<code>var stuff = new Entity("abc_stuff");
stuff.Attributes.Add(new KeyValuePair<string, object>(
    "kvp", 12));
stuff.Attributes.Add("txt", "foo");
stuff.Attributes.Add("null", null);

var containsKvp = stuff.Attributes.Contains("kvp"); // true
var containsKvpKey = stuff.Attributes.ContainsKey("kvp"); // true

var containsTxt = stuff.Attributes.Contains("txt"); // true
var containsTxtKey = stuff.Attributes.ContainsKey("txt"); // true

var containsNull = stuff.Attributes.Contains("null"); // true
var containsNullKey = stuff.Attributes.ContainsKey("null"); // true

var containsFoo = stuff.Attributes.Contains("foo"); // false
var containsFooKey = stuff.Attributes.ContainsKey("foo"); // false
</code>```

答: The method Contains calls the ContainsKey method internally. You can see the generated IL code.

ContentLicense: CC BY-SA 4.0

Body:
What is difference for AttributeCollection.Contains(TKey) and AttributeCollection.ContainsKey(TKey)? I doesn't see any difference in the official manual.

var stuff = new Entity("abc_stuff");
stuff.Attributes.Add(new KeyValuePair<string, object>(
    "kvp", 12));
stuff.Attributes.Add("txt", "foo");
stuff.Attributes.Add("null", null);

var containsKvp = stuff.Attributes.Contains("kvp"); // true
var containsKvpKey = stuff.Attributes.ContainsKey("kvp"); // true

var containsTxt = stuff.Attributes.Contains("txt"); // true
var containsTxtKey = stuff.Attributes.ContainsKey("txt"); // true

var containsNull = stuff.Attributes.Contains("null"); // true
var containsNullKey = stuff.Attributes.ContainsKey("null"); // true

var containsFoo = stuff.Attributes.Contains("foo"); // false
var containsFooKey = stuff.Attributes.ContainsKey("foo"); // false


问:
A problem returning a SwiftUI (transformed) Path from a function
I am working on a custom SwiftUI button that has a special shape depending on configuration.

A utility function must return a Shape depending on configuration. Since the path/shape is complicated to programme, transformations are used to get variations depending on configuration.

For demonstration purpose, a simplified version of the utility function looks like this:

```<code>func shape(i: Int) -> some Shape {

        let path = Path()

        switch i {
        case 0:
            return path
        case 1:
            return path.transform(CGAffineTransform(translationX:0,y:0))
        default:
            break
        }

        return path
    }
</code>```

Unfortunately the compiler generate the well known error:

```<code>Function declares an opaque return type, but the return statements in its body do not have matching underlying types
</code>```

I am sure this happens due to the transformation, although it returns a struct

```<code>func transform(_ transform: CGAffineTransform) -> TransformedShape<Self>
</code>```

that conforms to Shape (like Path do):

```<code>struct TransformedShape<Content> where Content : Shape
</code>```

Documentation for Path states that Path conforms to Shape, and this makes me think that I am overlooking something or that this may be a bug in the compiler.

If someone knows a workaround or can see that I am doing something wrong - please let me known.

Thanks.

答: Inspired by the many useful answers, I decided to go for a solution that sets up the transforms entirely using CGAffineTransform. In that way to avoid nested calls of SwiftUI's TransformedShape, which will make it impossible to return the same type.</p>

Body:
I am working on a custom SwiftUI button that has a special shape depending on configuration.

A utility function must return a Shape depending on configuration. Since the path/shape is complicated to programme, transformations are used to get variations depending on configuration.

For demonstration purpose, a simplified version of the utility function looks like this:

func shape(i: Int) -> some Shape {

        let path = Path()

        switch i {
        case 0:
            return path
        case 1:
            return path.transform(CGAffineTransform(translationX:0,y:0))
        default:
            break
        }

        return path
    }

Unfortunately the compiler generate the well known error:

Function declares an opaque return type, but the return statements in its body do not have matching underlying types

I am sure this happens due to the transformation, although it returns a struct

func transform(_ transform: CGAffineTransform) -> TransformedShape<Self>

that conforms to Shape (like Path do):

struct TransformedShape<Content> where Content : Shape

Documentation for Path states that Path conforms to Shape, and this makes me think that I am overlooking something or that this may be a bug in the compiler.

If someone knows a workaround or can see that I am doing something wrong - please let me known.

Thanks.


问:
How to save TextField user inputs
When the user enter the text on my textfield, how can I use this user input to create an object?

I have class named Item:

```<code>class Item {
  final int id;
  final String name;
  final double price;

  Item(this.id, this.name, this.price);
}
</code>```

I have two textfields, one the name and price.
I have the following Strings before the build method:

```<code>String itemInput;
String priceInput;

Item currentItem;
</code>```

In my onChanged method, I save the input to them.

```<code>TextField(
  onChanged: (String input) => itemInput = input,
)

TextField(
  keyboardType: TextInputType.number,
  onChanged: (String price) => priceInput = price,
)
</code>```

How can I create the Item object, once I save the input to the variables?
Currently, the inputs stay uninitialized.

答: use a TextEditing Controller it can save values, after that you can do whatever you want. Just call the .text </p>

Title: How to save TextField user inputs

Body:
When the user enter the text on my textfield, how can I use this user input to create an object?

I have class named Item:

class Item {
  final int id;
  final String name;
  final double price;

  Item(this.id, this.name, this.price);
}

I have two textfields, one the name and price.
I have the following Strings before the build method:

String itemInput;
String priceInput;

Item currentItem;

In my onChanged method, I save the input to them.

TextField(
  onChanged: (String input) => itemInput = input,
)

TextField(
  keyboardType: TextInputType.number,
  onChanged: (String price) => priceInput = price,
)

How can I create the Item object, once I save the input to the variables?
Currently, the inputs stay uninitialized.


问:
Python Socket Server and parallel timed Tasks
I'm quite new to python and just hanging at the following problem.

I'm trying to build a plant-watering-automation. As a base a use a tornado socket server which listen to client polls and deliveres the data for visualisation.

For the watering automation I created a ContinuousCallback (every 30 minutes) in which I want to check for humidity and control the pumps (GPIO out).

The task: if the Callback starts and it measures to low humidity, it should start to pump by switching the GPIO pins for a defined amount of time. (the time is defined in a SQLITE DB)

The problem: how can I do it, that I enter the Callback and start the pump action (I have 4 pumps) and make it end after the defined time? (Timer?, Timer Interrupt?) without influencing the Socket Server IOloop?

.

.

Thank you and best wishes

Sebastian

答:
Thanks to Joran I made it.

Here is my code.

```<code>GPIO_PUMP_1 = 17
GPIO_PUMP_2 = 27
GPIO_PUMP_3 = 22
GPIO_PUMP_4 = 10

#function which switches the relais off (low-active)
def setGPIO_HIGH(pin):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin,     GPIO.OUT)
    GPIO.output(pin,    GPIO.LOW)
    return True

#function which switches the relais on (low-active)
def setGPIO_LOW(pin):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin,     GPIO.OUT)
    GPIO.output(pin,    GPIO.HIGH)
    return True

#main function for controlling the watering logic
def doStuff():
    setGPIO_HIGH(GPIO_PUMP_1)
    setGPIO_HIGH(GPIO_PUMP_2)
    setGPIO_HIGH(GPIO_PUMP_3)
    setGPIO_HIGH(GPIO_PUMP_4)

    timer1 = threading.Timer(5.0, setGPIO_LOW, [GPIO_PUMP_1])
    timer1.start()
    timer2 = threading.Timer(6.0, setGPIO_LOW, [GPIO_PUMP_2])
    timer2.start()
    timer3 = threading.Timer(7.0, setGPIO_LOW, [GPIO_PUMP_3])
    timer3.start()
    timer4 = threading.Timer(8.0, setGPIO_LOW, [GPIO_PUMP_4])
    timer4.start()

    WebSocketHandler.broadcast("all done")
    return True
</code>```

Body:
Thanks to Joran I made it.

Here is my code.

GPIO_PUMP_1 = 17
GPIO_PUMP_2 = 27
GPIO_PUMP_3 = 22
GPIO_PUMP_4 = 10

#function which switches the relais off (low-active)
def setGPIO_HIGH(pin):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin,     GPIO.OUT)
    GPIO.output(pin,    GPIO.LOW)
    return True

#function which switches the relais on (low-active)
def setGPIO_LOW(pin):
    GPIO.setmode(GPIO.BCM)
    GPIO.setup(pin,     GPIO.OUT)
    GPIO.output(pin,    GPIO.HIGH)
    return True

#main function for controlling the watering logic
def doStuff():
    setGPIO_HIGH(GPIO_PUMP_1)
    setGPIO_HIGH(GPIO_PUMP_2)
    setGPIO_HIGH(GPIO_PUMP_3)
    setGPIO_HIGH(GPIO_PUMP_4)

    timer1 = threading.Timer(5.0, setGPIO_LOW, [GPIO_PUMP_1])
    timer1.start()
    timer2 = threading.Timer(6.0, setGPIO_LOW, [GPIO_PUMP_2])
    timer2.start()
    timer3 = threading.Timer(7.0, setGPIO_LOW, [GPIO_PUMP_3])
    timer3.start()
    timer4 = threading.Timer(8.0, setGPIO_LOW, [GPIO_PUMP_4])
    timer4.start()

    WebSocketHandler.broadcast("all done")
    return True


问:
Automapper to Map two List Classes of different structure and also Memberwise explicit Mapping
I have 4 classes namely ClassA, ClassADto,  ClassAA(inner class to ClassA) and the final Result class.

```<code>ClassAA
{
public int HouseNumber{get;set;}
public string StreetName{get;set;}
public string State{get;set;}
}

ClassA
{
public int Age{get;set;}
public string Name{get;set;}
public ClassAA AObj[get;set;}
}

ClassADto
{

 public int Age{get;set;}
 public string Name{get;set;}

}

class Result
{
public string StreetName{get;set;}
public int TotalCount{get;set;}
public int TodaysDate{get;set;}
public List<ClassADto> AObjectsList{get;set;}
}
</code>```

Now my aim is map the 'Result' class with the List of ClassA object to fill it the property 'AObjectsList'  as below:
    Result data= map mapper.map>(obj);

Also at the same time in automapper i want to use custom function either using 'Resolve' or 'AfterMap' to set properties like 'TodaysDate' to current datetime of system and property 'TotalCount' by counting the number of data.

I tried in many ways using 'CreateMap' and also used 'ForMembers' as from 'classAA' we only need the 'StreetName' but it didn't work. Need some help please.

答:
One time typing approach ;)

public static Result ToResult(this List<ClassA> users)
{
   return new Result
   {
       TotalCount = users.Count,
       TodaysDate = DateTime.Today,
       AObjectsList = users
           .Select(user => new ClassADto
           {
               Name = user.Name,
               Age = user.Age
           })
           .ToList()
   };
}

// Usage
var users = new List<ClassA> { new ClassA(), new ClassA() };

var result = users.ToResult();
```

Body:
I have 4 classes namely ClassA, ClassADto,  ClassAA(inner class to ClassA) and the final Result class.

ClassAA
{
public int HouseNumber{get;set;}
public string StreetName{get;set;}
public string State{get;set;}
}

ClassA
{
public int Age{get;set;}
public string Name{get;set;}
public ClassAA AObj[get;set;}
}

ClassADto
{

 public int Age{get;set;}
 public string Name{get;set;}

}

class Result
{
public string StreetName{get;set;}
public int TotalCount{get;set;}
public int TodaysDate{get;set;}
public List<ClassADto> AObjectsList{get;set;}
}

Now my aim is map the 'Result' class with the List of ClassA object to fill it the property 'AObjectsList'  as below:
    Result data= map mapper.map>(obj);

Also at the same time in automapper i want to use custom function either using 'Resolve' or 'AfterMap' to set properties like 'TodaysDate' to current datetime of system and property 'TotalCount' by counting the number of data.

I tried in many ways using 'CreateMap' and also used 'ForMembers' as from 'classAA' we only need the 'StreetName' but it didn't work. Need some help please.


问:
Scraping the entire website using beautiful soup. Any other better method is also appreciated
I am trying to scrape storytel.in. In the website after selecting any 1 of the categories we can see set of books. In that page you only have book name mentioned. I want to fetch author, narrator, rating, category, bookid from the website which can be inspected by opening the individual book in new tab. Below is my code

```<code>response = get('https://www.storytel.com/in/en/categories/8-History?pageNumber=1', headers = headers)
soup = BeautifulSoup(response.text,"html.parser")
books_div = soup.find_all('div', class_='gridItem')
for container in books_div:
    name = container.find('div',class_='gridBookTitle').a.text
    titles.append(name)

    b_id = container.div.find('a').get('href')
    b_id = b_id[-6:-1]
    book_id.append(b_id)

    for i,t in zip(book_id,titles):
        response1 = get('https://www.storytel.com/in/en/books/'+i+'-'+t, headers = headers)
        soup = BeautifulSoup(response1.text,"html.parser")
        tab_div = soup.find('div', class_='bookDetailDesc')
        a_name = tab_div.find('span', class_:'expandAuthorName').text
        author.append(a_name)
        b_rating = tab_div.find('span', id='dennisBookRating').text
        rating.append(b_rating)
</code>```

I am getting error while executing this.Any leads on how this can be done. Thanks in advance.

答:
This script will get from the link all book URLs and from each URL get information about Author, Detail, Rating and BookID:

```<code>import requests
from bs4 import BeautifulSoup

def get_book_info(url):
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')

    detail = soup.select_one('[itemprop="description"]').get_text(strip=True, separator='\n')
    name = soup.select_one('.expandAuthorName').get_text(strip=True)
    rating = soup.select_one('#dennisBookRating').get_text(strip=True)
    book_id = soup.select_one('div[bookid]')['bookid']

    return name, rating, book_id, detail

url = 'https://www.storytel.com/in/en/categories/8-History?pageNumber=1'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('.gridBookTitle a'):
    book_url = 'https://www.storytel.com' + a['href']
    print('Processing {}'.format(book_url))
    all_data.append( get_book_info(book_url) )

# print data to screen:
from textwrap import shorten
for name, rating, book_id, detail in all_data:
    print('{:<35}{:<10}{:<10}{:<150}'.format(name, rating, book_id, shorten(detail, 150)))
</code>```

Prints:

```<code>Yuval Noah Harari                  4.32      113557    New York Times Bestseller A Summer Reading Pick for President Barack Obama, Bill Gates, and Mark Zuckerberg From a renowned historian comes a [...]
Ranjeet Desai                      4.11      869277    छत्रपती शिवरायांना दिलेल्या वचनासाठी आपल्या प्राणांची बाजी लावून लढणा-या वीर बाजीप्रभू देशपांडे यांच्या बलिदानाने पावन झालेली पावनखिंड.... [...]
Kalki                              4.66      1280402   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.62      1280428   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.8       1280400   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.62      1280442   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.73      1280430   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.67      1414836   अविनाश धर्माधिकारी यांनी विलक्षण प्रेरणादायी पद्धतीने सांगितलेला आधुनिक भारताचा इतिहास.
Kuldeep Nayar                      4.25      1131017   ‘इन सबकी शुरुआत उड़ीसा में 1972 में हुए उप-चुनाव से हुई। लाखों रुपए खर्च कर नंदिनी को राज्य की विधानसभा के लिए चुना गया था। गांधीवादी जयप्रकाश [...]
Sandilyan                          4.86      1186090   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Avinash Dharmadhikari              4.39      1427231   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास, ब्रिटीशांनी भारत कसा जिंकला.
Hari Narayan Apte                  4.19      146917    'आधी लगीन कोंढाण्याचे मग लगीन रायबाचे', कोंढाणा किल्ला जिंकण्याची जबाबदारी शिवाजी महाराजानी तानाजी मालुसरेला दिली होती. जेव्हा तानाजीला ह्या [...]
Yuval Noah Harari                  4.44      89508     Yuval Noah Harari, author of the critically-acclaimed New York Times bestseller and international phenomenon Sapiens, returns with an equally [...]
Avinash Dharmadhikari              4.4       1427239   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Kalki                              4.5       1147877   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Manu S. Pillai                     4.13      1165903   മനു എസ് പിള്ള എഴുതിയ 'ഐവറി ത്രോൺ' എന്ന പുസ്തകത്തിന്റെ മലയാള വിവർത്തനമാണിത്. തിരുവിതാംകൂറിന്റെ രാജ്യഭരണ ചരിത്രത്തിലെ അവസാനത്തെ റാണിയും, [...]
Kalki                              4.61      1147825   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Kalki                              4.72      1147875   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Avinash Dharmadhikari              4.33      1427241   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Vinayak Damodar Savarkar           4.02      148453    1857 चे स्वातंत्र्य समर भाग १ हे हिंदुहृदयसम्राट स्वातंत्र्यवीर सावरकर यांचा तेजस्वी ग्रंथ
Shivajirao Bhosle                  4.29      130522    शिवाजीराव भोसले यांनी या ऑडीओबुक मध्ये 'महात्मा गांधी आणि त्यांचे विचार' याविषयीचे चिंतन केले आहे .
Rupert Colley                      4.13      3717      Love history? Know your stuff with History in an Hour. World War One brought with it the world’s first experience of Total War, involving all of [...]
Fanishwarnath Renu                 3.88      123133    ' कितने चोराहे ' एक उपन्यास हैं जिसके रचिता फनिश्वरनाथ रेणु हैं इस उपन्यासमे आज़ादी के ठीक पहलें तथा उसके अंत में आज़ादी के तुरंत बाद के ग्रामीण [...]
Sandilyan                          4.68      1186086   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Kalki                              4.66      1280416   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.71      1427245   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Kalki                              0.0       1328504   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Ra. Ki. Rangarajan                 4.86      1127892   ‘நான்’ என்று சொல்வது போலத் தமிழில் இதுவரை யாரும் சரித்திரக் கதை எழுதவில்லை என்பதால், அது மாதிரி ஒன்று நாமே எழுதினால் என்ன என்ற அசட்டுத் [...]
Sandilyan                          4.79      1186088   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Sun Tzu                            4.05      121435    The Art of War dates back to the 5th century BC, and is an ancient Chinese military handbook. Attributed to the intelligent military strategist [...]
B.R. Ambedkar                      4.83      1058502   The classic analysis of the caste system with an extensive introduction by Arundhati Roy. “What the Communist Manifesto is to the capitalist [...]
Readtrepreneur Publishing          4.68      961847    A Brief History of Time by Stephen Hawking, Book Summary, Readtrepreneur (Disclaimer: This is NOT the original book, but an unofficial summary.) [...]
Vishnubhat Godse                   3.7       628157    "माझा प्रवास - १८५७ च्या बंडाची हकीकत" हा विष्णूभट गोडसे यांनी लिहिलेला मराठी प्रवास आहे. जो पेणच्या जवळच्या वारसाई मधून गेला. त्याच्या [...]
B.D. Kher                          3.7       858251    दुसरं महायुध्द आणि युध्दापूर्वीची शांतता यामध्ये सामान्य जपानी माणसाला भोगाव्या लागलेल्या यातनांचं दिशादर्शन करणारी ही प्रत्ययकारी कादंबरी [...]
Bankim Chandra Chattopadhyay       3.97      146906    ‘आनंदमठ’ में 1770 ई. से 1774 ई. तक के बंगाल का चित्र खींचा गया है ! यह उपन्यास या ऐतिहासिक उपन्यास से बढ़कर है ! ऋषि बंकिम ने इसमें उस युग का [...]
Kalki                              5.0       1328499   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.62      1427243   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Sanjay Sonawani                    3.69      807007    खडकीच्या रानात मल्हारराव होळकर (दुसरे) यांचा तळ पडला होता. ऐन रात्री भर पावसाळ्यात दौलतराव शिंदेंच्या फौजेने मल्हारराव होळकरांच्या बेसावध [...]
M Mukundan                         4.29      904861    മയ്യഴിയുടെ ചരിത്രം സംസ്കാരം ഭൂമിശാസ്ത്രം തുടങ്ങിയ സർവ്വ ഘടകങ്ങളിലൂടെയും സഞ്ചരിച്ച് മയ്യഴിയുടെ സ്വത്വം തന്നെ തിരയുന്ന ഏകാഗ്രവും സമഗ്രവുമായ ഒരു [...]
Jemma J. Saunders                  4.16      11357     Love history? Know your stuff with History in an Hour. The Holocaust, in which 11 million people died, was the largest atrocity of the 20th [...]
Rabindranath Tagore                4.0       916767    গোরা, এই গল্পটির প্রধান চরিত্র, হিন্দু ধর্মে বিশেষ ভাবে বিশ্বাসী এবং এক বিদ্বেষহীন ভারতবর্ষের স্বপ্ন দেখে। সমস্যা বড়ো হয়ে দাঁড়ায়ে যখন [...]
Shashi Tharoor                     3.84      628264    इस धमाकेदार पुस्तक में लोकप्रिय लेखक शशि थरूर ने प्रामाणिक शोध एवं अपनी चिरपटुता से यह उजागर किया है कि भारत के लिए ब्रिटिश शासन कितना विनाशकरी [...]
Sandilyan                          0.0       1299380   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Vijay Trivedi                      4.47      905409    There is rarely a moment in history where all political parties give their consent to something without any debate or controversy. There is [...]
Kalki                              4.25      1299444   1942-ஆம் வருஷத்துப் புரட்சி வீரன் குமாரலிங்கம். போலீஸாரிடம் அகப்படாமலிருக்கும் பொருட்டு சோலைமலைக்குப் போகிறான். அங்கே இடிந்து பாழடைந்து கிடந்த [...]
Kalki                              4.77      1076726   1942-ஆம் வருஷத்துப் புரட்சி வீரன் குமாரலிங்கம். போலீஸாரிடம் அகப்படாமலிருக்கும் பொருட்டு சோலைமலைக்குப் போகிறான். அங்கே இடிந்து பாழடைந்து கிடந்த [...]
Kalki                              3.86      1328487   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Ra. Ki. Rangarajan                 4.75      1127744   ‘நான்’ என்று சொல்வது போலத் தமிழில் இதுவரை யாரும் சரித்திரக் கதை எழுதவில்லை என்பதால், அது மாதிரி ஒன்று நாமே எழுதினால் என்ன என்ற அசட்டுத் [...]
Rupert Colley                      4.09      13787     Love history? Know your stuff with History in an Hour. ‘Il Duce’, Benito Mussolini, was one of the key figures in the creation of fascism. Famed [...]
Rupert Colley                      3.92      3733      Love history? Know your stuff with History in an Hour. Listen to this bite size audiobook about Hitler's experience as a soldier during World [...]
</code>```

Body:
I am trying to scrape storytel.in. In the website after selecting any 1 of the categories we can see set of books. In that page you only have book name mentioned. I want to fetch author, narrator, rating, category, bookid from the website which can be inspected by opening the individual book in new tab. Below is my code

response = get('https://www.storytel.com/in/en/categories/8-History?pageNumber=1', headers = headers)
soup = BeautifulSoup(response.text,"html.parser")
books_div = soup.find_all('div', class_='gridItem')
for container in books_div:
    name = container.find('div',class_='gridBookTitle').a.text
    titles.append(name)

    b_id = container.div.find('a').get('href')
    b_id = b_id[-6:-1]
    book_id.append(b_id)

    for i,t in zip(book_id,titles):
        response1 = get('https://www.storytel.com/in/en/books/'+i+'-'+t, headers = headers)
        soup = BeautifulSoup(response1.text,"html.parser")
        tab_div = soup.find('div', class_='bookDetailDesc')
        a_name = tab_div.find('span', class_:'expandAuthorName').text
        author.append(a_name)
        b_rating = tab_div.find('span', id='dennisBookRating').text
        rating.append(b_rating)

I am getting error while executing this.Any leads on how this can be done. Thanks in advance.

Body:
This script will get from the link all book URLs and from each URL get information about Author, Detail, Rating and BookID:

import requests
from bs4 import BeautifulSoup

def get_book_info(url):
    soup = BeautifulSoup(requests.get(url).content, 'html.parser')

    detail = soup.select_one('[itemprop="description"]').get_text(strip=True, separator='\n')
    name = soup.select_one('.expandAuthorName').get_text(strip=True)
    rating = soup.select_one('#dennisBookRating').get_text(strip=True)
    book_id = soup.select_one('div[bookid]')['bookid']

    return name, rating, book_id, detail

url = 'https://www.storytel.com/in/en/categories/8-History?pageNumber=1'
soup = BeautifulSoup(requests.get(url).content, 'html.parser')

all_data = []
for a in soup.select('.gridBookTitle a'):
    book_url = 'https://www.storytel.com' + a['href']
    print('Processing {}'.format(book_url))
    all_data.append( get_book_info(book_url) )

# print data to screen:
from textwrap import shorten
for name, rating, book_id, detail in all_data:
    print('{:<35}{:<10}{:<10}{:<150}'.format(name, rating, book_id, shorten(detail, 150)))

Prints:

Yuval Noah Harari                  4.32      113557    New York Times Bestseller A Summer Reading Pick for President Barack Obama, Bill Gates, and Mark Zuckerberg From a renowned historian comes a [...]
Ranjeet Desai                      4.11      869277    छत्रपती शिवरायांना दिलेल्या वचनासाठी आपल्या प्राणांची बाजी लावून लढणा-या वीर बाजीप्रभू देशपांडे यांच्या बलिदानाने पावन झालेली पावनखिंड.... [...]
Kalki                              4.66      1280402   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.62      1280428   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.8       1280400   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.62      1280442   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Kalki                              4.73      1280430   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.67      1414836   अविनाश धर्माधिकारी यांनी विलक्षण प्रेरणादायी पद्धतीने सांगितलेला आधुनिक भारताचा इतिहास.
Kuldeep Nayar                      4.25      1131017   ‘इन सबकी शुरुआत उड़ीसा में 1972 में हुए उप-चुनाव से हुई। लाखों रुपए खर्च कर नंदिनी को राज्य की विधानसभा के लिए चुना गया था। गांधीवादी जयप्रकाश [...]
Sandilyan                          4.86      1186090   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Avinash Dharmadhikari              4.39      1427231   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास, ब्रिटीशांनी भारत कसा जिंकला.
Hari Narayan Apte                  4.19      146917    'आधी लगीन कोंढाण्याचे मग लगीन रायबाचे', कोंढाणा किल्ला जिंकण्याची जबाबदारी शिवाजी महाराजानी तानाजी मालुसरेला दिली होती. जेव्हा तानाजीला ह्या [...]
Yuval Noah Harari                  4.44      89508     Yuval Noah Harari, author of the critically-acclaimed New York Times bestseller and international phenomenon Sapiens, returns with an equally [...]
Avinash Dharmadhikari              4.4       1427239   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Kalki                              4.5       1147877   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Manu S. Pillai                     4.13      1165903   മനു എസ് പിള്ള എഴുതിയ 'ഐവറി ത്രോൺ' എന്ന പുസ്തകത്തിന്റെ മലയാള വിവർത്തനമാണിത്. തിരുവിതാംകൂറിന്റെ രാജ്യഭരണ ചരിത്രത്തിലെ അവസാനത്തെ റാണിയും, [...]
Kalki                              4.61      1147825   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Kalki                              4.72      1147875   A theatre actor writer director for 50 years in Tamil stage Having penned over 20 dramas for TV AIR and Stage He has also acted in over 3000 [...]
Avinash Dharmadhikari              4.33      1427241   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Vinayak Damodar Savarkar           4.02      148453    1857 चे स्वातंत्र्य समर भाग १ हे हिंदुहृदयसम्राट स्वातंत्र्यवीर सावरकर यांचा तेजस्वी ग्रंथ
Shivajirao Bhosle                  4.29      130522    शिवाजीराव भोसले यांनी या ऑडीओबुक मध्ये 'महात्मा गांधी आणि त्यांचे विचार' याविषयीचे चिंतन केले आहे .
Rupert Colley                      4.13      3717      Love history? Know your stuff with History in an Hour. World War One brought with it the world’s first experience of Total War, involving all of [...]
Fanishwarnath Renu                 3.88      123133    ' कितने चोराहे ' एक उपन्यास हैं जिसके रचिता फनिश्वरनाथ रेणु हैं इस उपन्यासमे आज़ादी के ठीक पहलें तथा उसके अंत में आज़ादी के तुरंत बाद के ग्रामीण [...]
Sandilyan                          4.68      1186086   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Kalki                              4.66      1280416   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.71      1427245   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Kalki                              0.0       1328504   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Ra. Ki. Rangarajan                 4.86      1127892   ‘நான்’ என்று சொல்வது போலத் தமிழில் இதுவரை யாரும் சரித்திரக் கதை எழுதவில்லை என்பதால், அது மாதிரி ஒன்று நாமே எழுதினால் என்ன என்ற அசட்டுத் [...]
Sandilyan                          4.79      1186088   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Sun Tzu                            4.05      121435    The Art of War dates back to the 5th century BC, and is an ancient Chinese military handbook. Attributed to the intelligent military strategist [...]
B.R. Ambedkar                      4.83      1058502   The classic analysis of the caste system with an extensive introduction by Arundhati Roy. “What the Communist Manifesto is to the capitalist [...]
Readtrepreneur Publishing          4.68      961847    A Brief History of Time by Stephen Hawking, Book Summary, Readtrepreneur (Disclaimer: This is NOT the original book, but an unofficial summary.) [...]
Vishnubhat Godse                   3.7       628157    "माझा प्रवास - १८५७ च्या बंडाची हकीकत" हा विष्णूभट गोडसे यांनी लिहिलेला मराठी प्रवास आहे. जो पेणच्या जवळच्या वारसाई मधून गेला. त्याच्या [...]
B.D. Kher                          3.7       858251    दुसरं महायुध्द आणि युध्दापूर्वीची शांतता यामध्ये सामान्य जपानी माणसाला भोगाव्या लागलेल्या यातनांचं दिशादर्शन करणारी ही प्रत्ययकारी कादंबरी [...]
Bankim Chandra Chattopadhyay       3.97      146906    ‘आनंदमठ’ में 1770 ई. से 1774 ई. तक के बंगाल का चित्र खींचा गया है ! यह उपन्यास या ऐतिहासिक उपन्यास से बढ़कर है ! ऋषि बंकिम ने इसमें उस युग का [...]
Kalki                              5.0       1328499   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Avinash Dharmadhikari              4.62      1427243   अविनाश धर्माधिकारी यांनी आपल्या रसाळ शैलीत सांगितलेला आधुनिक भारताचा इतिहास
Sanjay Sonawani                    3.69      807007    खडकीच्या रानात मल्हारराव होळकर (दुसरे) यांचा तळ पडला होता. ऐन रात्री भर पावसाळ्यात दौलतराव शिंदेंच्या फौजेने मल्हारराव होळकरांच्या बेसावध [...]
M Mukundan                         4.29      904861    മയ്യഴിയുടെ ചരിത്രം സംസ്കാരം ഭൂമിശാസ്ത്രം തുടങ്ങിയ സർവ്വ ഘടകങ്ങളിലൂടെയും സഞ്ചരിച്ച് മയ്യഴിയുടെ സ്വത്വം തന്നെ തിരയുന്ന ഏകാഗ്രവും സമഗ്രവുമായ ഒരു [...]
Jemma J. Saunders                  4.16      11357     Love history? Know your stuff with History in an Hour. The Holocaust, in which 11 million people died, was the largest atrocity of the 20th [...]
Rabindranath Tagore                4.0       916767    গোরা, এই গল্পটির প্রধান চরিত্র, হিন্দু ধর্মে বিশেষ ভাবে বিশ্বাসী এবং এক বিদ্বেষহীন ভারতবর্ষের স্বপ্ন দেখে। সমস্যা বড়ো হয়ে দাঁড়ায়ে যখন [...]
Shashi Tharoor                     3.84      628264    इस धमाकेदार पुस्तक में लोकप्रिय लेखक शशि थरूर ने प्रामाणिक शोध एवं अपनी चिरपटुता से यह उजागर किया है कि भारत के लिए ब्रिटिश शासन कितना विनाशकरी [...]
Sandilyan                          0.0       1299380   அமரர் சாண்டில்யனின் அற்புதமான புதினம் ஒலி வடிவில் 42 மணி நேரம் ஒலிக்கும் இந்த ஒலிப்புத்தகத்தில் 40க்கும் மேற்பட்ட சிறந்த கலைஞர்கள் [...]
Vijay Trivedi                      4.47      905409    There is rarely a moment in history where all political parties give their consent to something without any debate or controversy. There is [...]
Kalki                              4.25      1299444   1942-ஆம் வருஷத்துப் புரட்சி வீரன் குமாரலிங்கம். போலீஸாரிடம் அகப்படாமலிருக்கும் பொருட்டு சோலைமலைக்குப் போகிறான். அங்கே இடிந்து பாழடைந்து கிடந்த [...]
Kalki                              4.77      1076726   1942-ஆம் வருஷத்துப் புரட்சி வீரன் குமாரலிங்கம். போலீஸாரிடம் அகப்படாமலிருக்கும் பொருட்டு சோலைமலைக்குப் போகிறான். அங்கே இடிந்து பாழடைந்து கிடந்த [...]
Kalki                              3.86      1328487   பொன்னியின் செல்வன் அமரர் கல்கி (1899-1954) எழுதிய புகழ் பெற்ற தமிழ் வரலாற்றூப் புதினமாகும். 1950 - 1955 ஆண்டு வரை கல்கி வார இதழில் தொடர்கதையாக [...]
Ra. Ki. Rangarajan                 4.75      1127744   ‘நான்’ என்று சொல்வது போலத் தமிழில் இதுவரை யாரும் சரித்திரக் கதை எழுதவில்லை என்பதால், அது மாதிரி ஒன்று நாமே எழுதினால் என்ன என்ற அசட்டுத் [...]
Rupert Colley                      4.09      13787     Love history? Know your stuff with History in an Hour. ‘Il Duce’, Benito Mussolini, was one of the key figures in the creation of fascism. Famed [...]
Rupert Colley                      3.92      3733      Love history? Know your stuff with History in an Hour. Listen to this bite size audiobook about Hitler's experience as a soldier during World [...]


问:
How to properly host Allure reports
after reading answer to the question How to serve Allure Report without automatically starting the browser

I wonder how to use nginx to host allure reports properly?
I suppose it would be enough if you may give an example of command for nginx and allure in proper order.

PS: I am trying to create a shared Allure report as a hosted website across company without the necessity for each user of the report to have Allure installed on his local machine, without executing "allure serve" on each new test result.
Hosting is planned on AWS EC2, resolving domain and etc is planned to be done separetly with AWS ELBs.
Allure documentation does not cover this topic, as there are no other questions wth detailed specific answer on this topic on StackOverflow in regards to allure.

Thanks in advance.

答: You can host Allure Docker Service in any machine with docker. It's easy to use, you don't have to do a lot of configurations:https://github.com/fescobar/allure-docker-service</p>

ContentLicense: CC BY-SA 3.0

Title: How to properly host Allure reports


问:
How to drop temporary table in Stored Procedure
I am using SQL Server 2016 Service Pack 2 and use the following code. It executes correctly in SQL query statement:

```<code>SELECT 'a' AS one INTO #deleted;
DROP TABLE IF EXISTS #deleted;
GO

SELECT 'b' AS two INTO #deleted;
DROP TABLE IF EXISTS #deleted;
GO
</code>```

But when I picking up GO I am faced with this error:

There is already an object named '#deleted' in the database.

If I want to create a SP with this syntax I can't use GO.

答:
Correct. You will have to give the 2 temp tables different names if you want to use them in the same batch using SELECT INTO statements with a DIE statement in between.

Alternatively, you can create the temp table first, with all the required columns for both SELECT statements, then adjust the SELECTs (or whatever statements you're running with the temp table data) accordingly.

E.g.

BEGIN
    DROP TABLE IF EXISTS #deleted ;
    CREATE TABLE #deleted ( [one] VARCHAR(5) NULL, [two] VARCHAR(5) NULL ) ;

    INSERT  INTO #deleted ( [one] )
    SELECT 'a' AS [one] ;

    INSERT  INTO #deleted ( [two] )
    SELECT  'b' AS [two] ;

    SELECT [one] FROM #deleted WHERE [two] IS NULL ;
    SELECT [two] FROM #deleted WHERE [one] IS NULL ;

    DROP TABLE IF EXISTS #deleted ;
END
GO
```

<p><strong>Update 1</strong><br>
As already mentioned, you could just give the temp tables different names.</p>

<p>E.g.</p>

<pre class="lang-sql prettyprint-override"><code>BEGIN
    SELECT  'a' AS [one]
    INTO    #deleted1 ;
    SELECT  * FROM #deleted1 ;  -- or whatever statements you need to execute
    DROP TABLE IF EXISTS #deleted1 ;

    SELECT  'b' AS [two]
    INTO    #deleted2 ;
    SELECT  * FROM #deleted2 ;  -- or whatever statements you need to execute
    DROP TABLE IF EXISTS #deleted2 ;
END
GO
</code>```

Body:
I am using SQL Server 2016 Service Pack 2 and use the following code. It executes correctly in SQL query statement:

SELECT 'a' AS one INTO #deleted;
DROP TABLE IF EXISTS #deleted;
GO

SELECT 'b' AS two INTO #deleted;
DROP TABLE IF EXISTS #deleted;
GO

But when I picking up GO I am faced with this error:

There is already an object named '#deleted' in the database.

If I want to create a SP with this syntax I can't use GO.

Body:
Correct. You will have to give the 2 temp tables different names if you want to use them in the same batch using SELECT INTO statements with a DIE statement in between.

Alternatively, you can create the temp table first, with all the required columns for both SELECT statements, then adjust the SELECTs (or whatever statements you're running with the temp table data) accordingly.

E.g.

BEGIN
    DROP TABLE IF EXISTS #deleted ;
    CREATE TABLE #deleted ( [one] VARCHAR(5) NULL, [two] VARCHAR(5) NULL ) ;

    INSERT  INTO #deleted ( [one] )
    SELECT 'a' AS [one] ;

    INSERT  INTO #deleted ( [two] )
    SELECT  'b' AS [two] ;

    SELECT [one] FROM #deleted WHERE [two] IS NULL ;
    SELECT [two] FROM #deleted WHERE [one] IS NULL ;

    DROP TABLE IF EXISTS #deleted ;
END
GO

Update 1

As already mentioned, you could just give the temp tables different names.

E.g.

BEGIN
    SELECT  'a' AS [one]
    INTO    #deleted1 ;
    SELECT  * FROM #deleted1 ;  -- or whatever statements you need to execute
    DROP TABLE IF EXISTS #deleted1 ;

    SELECT  'b' AS [two]
    INTO    #deleted2 ;
    SELECT  * FROM #deleted2 ;  -- or whatever statements you need to execute
    DROP TABLE IF EXISTS #deleted2 ;
END
GO


问:
How to prevent spring batch to start new instance of job?
Idea is not to start job if already same job is running.

JobExplorer is simple injected in class where is scheduled method for running

```<code>public class JobClass {

    private final Job job;
    private final JobExplorer jobExplorer;
    private final JobLauncher jobLauncher;

    public JobMain(Job job,
                   JobLauncher jobLauncher,
                   JobExplorer jobExplorer) {
        this.job = job;
        this.jobLauncher = jobLauncher;
        this.jobExplorer = jobExplorer;
    }
</code>```

and then it is executed

```<code>    @Scheduled("0 */5 * ? * *")
    public void startJob() {
        JobParameters jobParameters = new JobParametersBuilder()
                    .addString("jobName", String.valueOf(instant.toEpochMilli()))
                    .toJobParameters();
        jobLauncher.run(job, jobParameters);
    }
</code>```

This is not solution because if JVM stopped while job is running this will be same as current job running:

```<code>jobExplorer.findRunningJobExecutions("jobName")
</code>```

It will find all jobs with exitCode ExitStatus.UNKNOWN.

There is 3 solutions as I see it:

Solution 1:

stop previous running not finished jobs and run new job
PROS: everything is clean, just one property

CONT: loosing current execution of current job

```<code>@Scheduled("0 */5 * ? * *")
public void startJob() {
    (JobExecution jobExecution: jobExplorer.findRunningJobExecutions("jobName")) jobExecution.stop();
    ...
}
</code>```

Solution 2

Calculate time between latest running job like it is here described and if it is any do not start new job:
https://stackoverflow.com/a/23218986/1182625

PROS: everything is clean

CONT: have to have doubled property (5 *60*1000 and "0 */5 * ? * *")

```<code>Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("jobName");
        if(jobExecutions.size()>1){
            Long currentTime = (new Date()).getTime();
            for(JobExecution execution : jobExecutions) {
                if((currentTime - execution.getStartTime().getTime()) < 5*60*1000) {
                    return;
                } else {
                    execution.stop();
                }
            }

        }
</code>```

Solution 3

Idea is simple to add static (to share between instances of class) volatile (to share between threads) flag which will indicate is any job currently running
PROS: just one property

CONT: needs 2 listeners, and volatile static variable which i don't know how reacted in multi-nodes environment

```<code>    private static volatile boolean FINISHED = true;
</code>```

and then simple add listener and FINISHED modify method:

```<code>// reset FINISHED after job is done
     @AfterJob
     public void afterJob() {
         FINISHED = true;
     }

    public void setFinished() {
        this.FINISHED = true;
    }
</code>```

And simple add:

```<code>    @Scheduled("0 */5 * ? * *")
    public void startJob() {
    if(!FINISHED) return;
    FINISHED = false;
    ...
    }
</code>```

And finally add StepListener

```<code>public MyStepListener() {
...
    @AfterStep
    public ExitStatus afterStep(StepExecution stepExecution) {
    if(stepExecution.getExitStatus().getExitCode().equalsIgnoreCase(ExitStatus.FAILED.getExitCode()))  (new JobMain()).setFinished();
    return null;
    }
</code>```

答:
Idea is not to start job if already same job is running.

By design, Spring Batch will prevent that. If you try to start the same job instance while it has a running job execution, you will get a JobExecutionAlreadyRunningException.

Body:
Idea is not to start job if already same job is running.

JobExplorer is simple injected in class where is scheduled method for running

public class JobClass {

    private final Job job;
    private final JobExplorer jobExplorer;
    private final JobLauncher jobLauncher;

    public JobMain(Job job,
                   JobLauncher jobLauncher,
                   JobExplorer jobExplorer) {
        this.job = job;
        this.jobLauncher = jobLauncher;
        this.jobExplorer = jobExplorer;
    }

and then it is executed

    @Scheduled("0 */5 * ? * *")
    public void startJob() {
        JobParameters jobParameters = new JobParametersBuilder()
                    .addString("jobName", String.valueOf(instant.toEpochMilli()))
                    .toJobParameters();
        jobLauncher.run(job, jobParameters);
    }

This is not solution because if JVM stopped while job is running this will be same as current job running:

jobExplorer.findRunningJobExecutions("jobName")

It will find all jobs with exitCode ExitStatus.UNKNOWN.

There is 3 solutions as I see it:

Solution 1:

stop previous running not finished jobs and run new job
PROS: everything is clean, just one property

CONT: loosing current execution of current job

@Scheduled("0 */5 * ? * *")
public void startJob() {
    (JobExecution jobExecution: jobExplorer.findRunningJobExecutions("jobName")) jobExecution.stop();
    ...
}

Solution 2

Calculate time between latest running job like it is here described and if it is any do not start new job:
https://stackoverflow.com/a/23218986/1182625

PROS: everything is clean

CONT: have to have doubled property (5 *60*1000 and "0 */5 * ? * *")

Set<JobExecution> jobExecutions = jobExplorer.findRunningJobExecutions("jobName");
        if(jobExecutions.size()>1){
            Long currentTime = (new Date()).getTime();
            for(JobExecution execution : jobExecutions) {
                if((currentTime - execution.getStartTime().getTime()) < 5*60*1000) {
                    return;
                } else {
                    execution.stop();
                }
            }

        }

Solution 3

Idea is simple to add static (to share between instances of class) volatile (to share between threads) flag which will indicate is any job currently running
PROS: just one property

CONT: needs 2 listeners, and volatile static variable which i don't know how reacted in multi-nodes environment

    private static volatile boolean FINISHED = true;

and then simple add listener and FINISHED modify method:

// reset FINISHED after job is done
     @AfterJob
     public void afterJob() {
         FINISHED = true;
     }

    public void setFinished() {
        this.FINISHED = true;
    }

And simple add:

    @Scheduled("0 */5 * ? * *")
    public void startJob() {
    if(!FINISHED) return;
    FINISHED = false;
    ...
    }

And finally add StepListener

public MyStepListener() {
...
    @AfterStep
    public ExitStatus afterStep(StepExecution stepExecution) {
    if(stepExecution.getExitStatus().getExitCode().equalsIgnoreCase(ExitStatus.FAILED.getExitCode()))  (new JobMain()).setFinished();
    return null;
    }


问:
C# binary data from port convert to hex string
I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. Now I want to convert it to a hex string. If it's a hex string we can cut parts of the string and decode them seperately. how can i do this?

The following is the code:

```<code>using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);

            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}
</code>```

答: Look at the BitConverter.ToString() method

Body:
I found a source code and changed it a little bit so i can retrieve data from a receiver that is on com6. The data i am receiving is binary. Now I want to convert it to a hex string. If it's a hex string we can cut parts of the string and decode them seperately. how can i do this?

The following is the code:

using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
    static bool _continue;
    static SerialPort _serialPort;
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 1000;
        _serialPort.WriteTimeout = 1000;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }

    public static void Read()
    {
        while (_continue)
        {

            try
            {

                string message = _serialPort.ReadLine();
                Console.WriteLine(message);

            catch (TimeoutException) { }
        }
    }

    public static string SetPortName(string defaultPortName)
    {
        string portName;

            portName = "COM6";

        return portName;
    }

    public static int SetPortBaudRate(int defaultPortBaudRate)
    {
        string baudRate;

        baudRate = "9600";

        return int.Parse(baudRate);
    }

    public static Parity SetPortParity(Parity defaultPortParity)
    {
        string parity;

        parity = "None";

        return (Parity)Enum.Parse(typeof(Parity), parity);
    }

    public static int SetPortDataBits(int defaultPortDataBits)
    {
        string dataBits;

        dataBits = "8";

        return int.Parse(dataBits);
    }

    public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
    {
        string stopBits;

        stopBits = "One";

        return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
    }

    public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
    {
        string handshake;

        handshake = "None";

        return (Handshake)Enum.Parse(typeof(Handshake), handshake);
    }
}


问:
Can obtain the condition applied in my if conditional in Python?
I would like to keep in a variable the condition applied, for example:

l = "test.log"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)
```

<blockquote>
  <p>.log</p>
</blockquote>

<pre class="lang-py prettyprint-override"><code>l = "test.csv"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)
</code>```

.csv

How can I perform that without a switch case? I just wanna know which condition was performed.

答:
this is a variant:

```<code>from pathlib import Path

def log_action():
    print("log")

def csv_action():
    print("csv")

suffix_action = {".log": log_action, ".csv": csv_action}

action = suffix_action[Path("file.log").suffix]
action()
</code>```

this way you have a lot of flexibility to do what you want in the respective functions.

Body:
I would like to keep in a variable the condition applied, for example:

l = "test.log"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.log

l = "test.csv"
if l.endswith('.csv') or l.endswith('.log') or l.endswith('.xlsx'):
    print(someVariable)

.csv

How can I perform that without a switch case? I just wanna know which condition was performed.

Body:
this is a variant:

from pathlib import Path

def log_action():
    print("log")

def csv_action():
    print("csv")

suffix_action = {".log": log_action, ".csv": csv_action}

action = suffix_action[Path("file.log").suffix]
action()

this way you have a lot of flexibility to do what you want in the respective functions.


问:
Making a
 element without a newline before it?
Here's my code:

```<code>Your rating: <div>4</div>
</code>```

It looks like:

```<code>Your rating:
     4
</code>```

How can I make a div not make a newline before it?

答:
you can use span

Your rating: 4</span```

OP: Your rating: 4

ContentLicense: CC BY-SA 2.5

Title: Making a <div> element without a newline before it?

Body:
Here's my code:

Your rating:
4

It looks like:

Your rating:
     4

How can I make a div not make a newline before it?

Body:
you can use span

Your rating: <span>4</span

OP: Your rating: 4


问:
Closing ZipOutputStream
I'm a bit confused. I know that an empty zip is not legal. But what about this sample snippet:

```<code>ZipOutputStream zos = null;
try
{
    zos = new ZipOutputStream(new FileOutputStream("..."));
    //
    //..
    //
}
finally
{
    zos.close();
}
</code>```

If no zip entries had been added for some reason (possibly exceptional situation) then the following exception will be thrown on close attempt:

```<code>Exception in thread "main" java.util.zip.ZipException: ZIP file must have at least one entry
    at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:304)
    at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:146)
    at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:321)
</code>```

In this situation what would be the cleanest way to close the stream?

Thanks...

答:
If you use Java 7 or above, you can use try-with-resources for better readability

For example:

```<code>try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("..."))) {
    // do something with zos
}
</code>```

Title: Closing ZipOutputStream

Body:
I'm a bit confused. I know that an empty zip is not legal. But what about this sample snippet:

ZipOutputStream zos = null;
try
{
    zos = new ZipOutputStream(new FileOutputStream("..."));
    //
    //..
    //
}
finally
{
    zos.close();
}

If no zip entries had been added for some reason (possibly exceptional situation) then the following exception will be thrown on close attempt:

Exception in thread "main" java.util.zip.ZipException: ZIP file must have at least one entry
    at java.util.zip.ZipOutputStream.finish(ZipOutputStream.java:304)
    at java.util.zip.DeflaterOutputStream.close(DeflaterOutputStream.java:146)
    at java.util.zip.ZipOutputStream.close(ZipOutputStream.java:321)

In this situation what would be the cleanest way to close the stream?

Thanks...

Body:
If you use Java 7 or above, you can use try-with-resources for better readability

For example:

try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream("..."))) {
    // do something with zos
}


问:
How to implement unit testing within the strapi framework
I'm experimenting with Strapi and would like to create a controller verified by unit tests.

How do I setup Unit tests within Strapi?

I have written the following test

```<code>test('checks entity inside boundary',async ()=> {
    ctx={};
    var result = await controller.findnearby(ctx);
    result = {};
    expect(result).anyting();
});
</code>```

however, inside my Controller I have code that accesses a global strapi object, which causes this error ReferenceError: strapi is not defined

```<code>   strapi.log.info('findNearby');
   strapi.log.info(ctx.request.query.lat);
   strapi.log.info(ctx.request.query.long);
</code>```

What is the best practice with Strapi and testing?

答:
There were some changes, regarding the version upgrade.

I recommend to switch to stable 3.0.0 and use the following snippet

const Strapi = require("strapi");
const http = require("http");

let instance;

async function setupStrapi() {
  if (!instance) {
    /** the follwing code in copied from `./node_modules/strapi/lib/Strapi.js` */
    await Strapi().load();
    instance = strapi; // strapi is global now
    await instance.app
      .use(instance.router.routes()) // populate KOA routes
      .use(instance.router.allowedMethods()); // populate KOA methods

    instance.server = http.createServer(instance.app.callback());
  }
  return instance;
}
module.exports = { setupStrapi };
```

Here is my example project.

Guide for this is hopefully coming to Strapi documentation sooner then later.

Body:
I'm experimenting with Strapi and would like to create a controller verified by unit tests.

How do I setup Unit tests within Strapi?

I have written the following test

test('checks entity inside boundary',async ()=> {
    ctx={};
    var result = await controller.findnearby(ctx);
    result = {};
    expect(result).anyting();
});

however, inside my Controller I have code that accesses a global strapi object, which causes this error ReferenceError: strapi is not defined

   strapi.log.info('findNearby');
   strapi.log.info(ctx.request.query.lat);
   strapi.log.info(ctx.request.query.long);

What is the best practice with Strapi and testing?

Body:
There were some changes, regarding the version upgrade.

I recommend to switch to stable 3.0.0 and use the following snippet

const Strapi = require("strapi");
const http = require("http");

let instance;

async function setupStrapi() {
  if (!instance) {
    /** the follwing code in copied from `./node_modules/strapi/lib/Strapi.js` */
    await Strapi().load();
    instance = strapi; // strapi is global now
    await instance.app
      .use(instance.router.routes()) // populate KOA routes
      .use(instance.router.allowedMethods()); // populate KOA methods

    instance.server = http.createServer(instance.app.callback());
  }
  return instance;
}
module.exports = { setupStrapi };

Here is my example project.

Guide for this is hopefully coming to Strapi documentation sooner then later.


问:
How to dynamically call accessor methods in Ruby
Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

```<code>class Test_Class
  attr_accessor :a, :b
end
</code>```

I can use the Object.send method to read the variable...

```<code>instance.a = "value"
puts( instance.send( "a" ) )
# => value
</code>```

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

```<code>instance.send("a", "value")
</code>```

and

```<code>instance.method("a").call("value")
</code>```

Please help me StackOverflow!

答:
You can also directly access instance variables of an object using instance_variable_* functions:

```<code>instance = Test_Class.new                 # => #<Test_Class:0x12b3b84>

# instance variables are lazily created after first use of setter,
# so for now instance variables list is empty:
instance.instance_variables                # => []

instance.instance_variable_set(:@a, 123)   # => 123
instance.a                                 # => 123
instance.instance_variables                # => ["@a"]
instance.instance_variable_get("@a")       # => 123
</code>```

OwnerDisplayName: THE Joe Zack

Body:
Regardless of whether it's good practice or not, how can I dynamically call accessor methods in Ruby?

Here's an example class:

class Test_Class
  attr_accessor :a, :b
end

I can use the Object.send method to read the variable...

instance.a = "value"
puts( instance.send( "a" ) )
# => value

But I'm having a hard time trying to write to it. These throw "wrong number of arguments (1 for 0) (ArgumentError)"

instance.send("a", "value")

and

instance.method("a").call("value")

Please help me StackOverflow!

Body:
You can also directly access instance variables of an object using instance_variable_* functions:

instance = Test_Class.new                 # => #<Test_Class:0x12b3b84>

# instance variables are lazily created after first use of setter,
# so for now instance variables list is empty:
instance.instance_variables                # => []

instance.instance_variable_set(:@a, 123)   # => 123
instance.a                                 # => 123
instance.instance_variables                # => ["@a"]
instance.instance_variable_get("@a")       # => 123

OwnerDisplayName: Marcin Urbanski


问:
WCF RESTful API
I created a WCF project with one simple method that returns a pdf in a byte[] and a int (id #) and has username+password with a custom validator for message security and a SSL for transport security. Now the client tells me that he was assuming I was going to create a RESTful API instead. I don't have any experience with REST, but I've seen that you can create a REST project in WCF (which is what I'd prefer for interaction with the rest of my solution).

First, can you deliver a pdf the same way in a RESTful API? I set the int as an out parameter in order to return it to the client, can I assume an out parameter will function the same as well?

Second, can I use the same kind of security setup? I'm assuming the SSL will still protect the transport, but I cannot seem to find a good example or tutorial on basic security. I can use a different method of security if needed.

答:
REST is different than SOAP or even WCF in that you aren't using cumbersome "envelopes" unfortunately those envelopes provide you with functionality like the authentication scheme you're using (and out params, etc.)

See Best Practices for securing a REST API / web service

You can go /w basic authentication + SSL for authentication.  You must encrypt basic authentication though or else it is insecure.  As for the out parameter, it seems that a composite XML based result like the following is one way to go:

GET

could return XML like:

```<code><result>
  <intValue>4</intValue>
  <pdfByteString><![CDATA[bytestring...etc.]]></pdfByteString>
</result>
</code>```

It actually does look like WCF does have some built-in functionality to help you out, this white paper should provide a decent intro:

http://msdn.microsoft.com/en-us/library/ee391967.aspx#Y1720

Title: WCF RESTful API

Body:
REST is different than SOAP or even WCF in that you aren't using cumbersome "envelopes" unfortunately those envelopes provide you with functionality like the authentication scheme you're using (and out params, etc.)

See Best Practices for securing a REST API / web service

You can go /w basic authentication + SSL for authentication.  You must encrypt basic authentication though or else it is insecure.  As for the out parameter, it seems that a composite XML based result like the following is one way to go:

GET

could return XML like:

<result>
  <intValue>4</intValue>
  <pdfByteString><![CDATA[bytestring...etc.]]></pdfByteString>
</result>

It actually does look like WCF does have some built-in functionality to help you out, this white paper should provide a decent intro:

http://msdn.microsoft.com/en-us/library/ee391967.aspx#Y1720


问:
Is there a way to get the height of the ScrollView that contains the content in SwiftUI?
I want to calculate how much I can scroll from the height of the entire ScrollView to the bottom of the ScrollView, but I can't get the height of the entire ScrollView.
If there is any way to do this, please let me know.

scrollView.contentSize.height
scrollView.frame.height

The top two are the values you want to get

```<code>var body: some View {
    ScrollView {
        ForEach(0..<100, id: \.self) { number in
            Text("\(number)")
        }
    }
}
</code>```

答:
Here is a solution based on ViewHeightKey preference key from my answer in How to make a SwiftUI List scroll automatically?

```<code>var body: some View {
    ScrollView {
        VStack {
            ForEach(0..<100, id: \.self) { number in
                Text("\(number)")
            }
        }
        .modifier(ViewHeightKey())   // calculate here !!
    }
    .onPreferenceChange(ViewHeightKey.self) { // read here !!
        print("Content height: \($0)")
    }
    .background(GeometryReader { gp -> Color in
        let frame = gp.frame(in: .local)
        print("ScrollView height: \(frame.size.height)")
        return Color.clear
    })
}
</code>```

Body:
I want to calculate how much I can scroll from the height of the entire ScrollView to the bottom of the ScrollView, but I can't get the height of the entire ScrollView.
If there is any way to do this, please let me know.

scrollView.contentSize.height
scrollView.frame.height

The top two are the values you want to get

var body: some View {
    ScrollView {
        ForEach(0..<100, id: \.self) { number in
            Text("\(number)")
        }
    }
}

Body:
Here is a solution based on ViewHeightKey preference key from my answer in How to make a SwiftUI List scroll automatically?

var body: some View {
    ScrollView {
        VStack {
            ForEach(0..<100, id: \.self) { number in
                Text("\(number)")
            }
        }
        .modifier(ViewHeightKey())   // calculate here !!
    }
    .onPreferenceChange(ViewHeightKey.self) { // read here !!
        print("Content height: \($0)")
    }
    .background(GeometryReader { gp -> Color in
        let frame = gp.frame(in: .local)
        print("ScrollView height: \(frame.size.height)")
        return Color.clear
    })
}


问:
How to hide the highlighted lines when the ".sql" file are opened in VSCode
Below is what it looks like when opened the ".sql" file, I want to hide those highlighted lines

答:
I have found out that it comes with the SQL Tools extension

You could either uninstall it or revert back to 0.21.9 version. Not sure where the root cause for highlighting is.


答:
You can use if ... elif ... like this

l = "test.csv"
if l.endswith('.csv'):
    someVariable = '.csv'
elif l.endswith('.log'):
    someVariable = '.log'
elif l.endswith('.xlsx'):
    someVariable = '.xlsx'

print(someVariable)
```

<p>Another solution might use <code>split</code></p>

<pre class="lang-py prettyprint-override"><code>someVariable = '.' + l.split('.')[-1]

if someVariable in ('.csv', '.log', '.xlsx'):
    print(someVariable)
</code>```

Title: Can obtain the condition applied in my if conditional in Python?

Body:
You can use if ... elif ... like this

l = "test.csv"
if l.endswith('.csv'):
    someVariable = '.csv'
elif l.endswith('.log'):
    someVariable = '.log'
elif l.endswith('.xlsx'):
    someVariable = '.xlsx'

print(someVariable)

Another solution might use split

someVariable = '.' + l.split('.')[-1]

if someVariable in ('.csv', '.log', '.xlsx'):
    print(someVariable)


问:
C++ Cypher issue
I am new to the world of coding and been experimenting on making a cypher with c++ but it is throwing an error and I don't know how to fix it. Help would be appreciated, Here is the code

```<code>#include <iostream>
#include <string>

using namespace std;

int main(){

/* Variables Declaration! */

string alphabets{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};

string key{"XWZYLMNOPQRSTUVABCDEFGHIJKuvwxyzabcdefghijklmnopqrst"};

string input{};

string encrypted_message{};

string decrypted_message{};

/*----------------------------------------------------------------------------------------------*/

cout << "Welcome To the Cypher!" << endl;
cout << "-------------------------------------------------------------" << endl;

cout << "Enter the code: " << endl;
getline(cin,input);

/*Encryption Part Code*/

cout << "Encrypting!"<< endl;
cout << endl ;

for (char c:input) {

    size_t postition = alphabets.find(c);
    if (postition != string::npos){
        encrypted_message += key.at(postition);
    }
    else
        encrypted_message += c;
}
cout << endl ;
cout << encrypted_message << endl;

/* Decryption Part Code */

cout << "Decrypting!" << endl;
cout << endl ;

for (char c : encrypted_message) {

    size_t position = key.find(c);

    if (position != string::npos){
        decrypted_message += alphabets.at(c);
    }

    else
        decrypted_message += c;

}
/* --------------------------------------------------------------------------------------*/

cout << endl;
cout << "-----------------------------------------------------------------------------" ;
cout << endl ;

return 0;
}
</code>```

The error I'm getting -

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::at: __n (which is 88) >= this->size() (which is
  52)

答:
printing the backtrace of the process dump using gdb,

```<code>    (gdb) bt
    #0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
    #1  0x00007ffff7aed535 in __GI_abort () at abort.c:79
    #2  0x00007ffff7eb5943 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #3  0x00007ffff7ebb8a6 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #4  0x00007ffff7ebb8e1 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #5  0x00007ffff7ebbb14 in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #6  0x00007ffff7eb7851 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #7  0x00007ffff7f4779f in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::at(unsigned long) () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #8  0x000055555555559b in main () at cypher.cc:61
</code>```

According to #8, there was a problem at line 61.

```<code>decrypted_message += alphabets.at(c);
</code>```

According to #7, there was a problem when you attempted "at" function.

Your error reads,

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 88) >= this->size() (which is 52)

That means you are trying to access at n (88) which exceeds the size of alphabets (52).

What you need to do is change "c" to "position".

Title: C++ Cypher issue

Body:
I am new to the world of coding and been experimenting on making a cypher with c++ but it is throwing an error and I don't know how to fix it. Help would be appreciated, Here is the code

#include <iostream>
#include <string>

using namespace std;

int main(){

/* Variables Declaration! */

string alphabets{"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"};

string key{"XWZYLMNOPQRSTUVABCDEFGHIJKuvwxyzabcdefghijklmnopqrst"};

string input{};

string encrypted_message{};

string decrypted_message{};

/*----------------------------------------------------------------------------------------------*/

cout << "Welcome To the Cypher!" << endl;
cout << "-------------------------------------------------------------" << endl;

cout << "Enter the code: " << endl;
getline(cin,input);

/*Encryption Part Code*/

cout << "Encrypting!"<< endl;
cout << endl ;

for (char c:input) {

    size_t postition = alphabets.find(c);
    if (postition != string::npos){
        encrypted_message += key.at(postition);
    }
    else
        encrypted_message += c;
}
cout << endl ;
cout << encrypted_message << endl;

/* Decryption Part Code */

cout << "Decrypting!" << endl;
cout << endl ;

for (char c : encrypted_message) {

    size_t position = key.find(c);

    if (position != string::npos){
        decrypted_message += alphabets.at(c);
    }

    else
        decrypted_message += c;

}
/* --------------------------------------------------------------------------------------*/

cout << endl;
cout << "-----------------------------------------------------------------------------" ;
cout << endl ;

return 0;
}

The error I'm getting -

terminate called after throwing an instance of 'std::out_of_range'

  what():  basic_string::at: __n (which is 88) >= this->size() (which is
  52)

Body:
printing the backtrace of the process dump using gdb,

    (gdb) bt
    #0  __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:50
    #1  0x00007ffff7aed535 in __GI_abort () at abort.c:79
    #2  0x00007ffff7eb5943 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #3  0x00007ffff7ebb8a6 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #4  0x00007ffff7ebb8e1 in std::terminate() () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #5  0x00007ffff7ebbb14 in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #6  0x00007ffff7eb7851 in ?? () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #7  0x00007ffff7f4779f in std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >::at(unsigned long) () from /lib/x86_64-linux-gnu/libstdc++.so.6
    #8  0x000055555555559b in main () at cypher.cc:61

According to #8, there was a problem at line 61.

decrypted_message += alphabets.at(c);

According to #7, there was a problem when you attempted "at" function.

Your error reads,

terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::at: __n (which is 88) >= this->size() (which is 52)

That means you are trying to access at n (88) which exceeds the size of alphabets (52).

What you need to do is change "c" to "position".


答:
If you only deal with file extensions, you can use pathlib to get the extension, and compare against a predefined set, like this:

from pathlib import Path

approved_extensions = {'.csv', '.log', '.xlsx'}

l = "test.log"
ext = Path(l).suffix
if ext in approved_extensions:
    print(ext)
```


问:
How to call function if condition is true kotlin?
Right now in my project I have such functions calls:

```<code>if (theme.isNotEmpty() && body.isNotEmpty()) {
   sendToCons()
}
if (theme.isEmpty() && body.isEmpty()) {
   alertDialog(getString(R.string.alert_1), 0)
}
if (theme.isNotEmpty() && body.isEmpty()) {
   alertDialog(getString(R.string.alert_2), 0)
}
if (theme.isEmpty() && body.isNotEmpty()) {
   alertDialog(getString(R.string.alert_3), 0)
}
</code>```

this code scope I changed to this one:

```<code>when {
      theme.isNotEmpty() && body.isNotEmpty() -> sendToCons()
      theme.isEmpty() && body.isEmpty() -> alertDialog(getString(R.string.alert_1), 0)
      theme.isNotEmpty() && body.isEmpty() -> alertDialog(getString(R.string.alert_2), 0)
      theme.isEmpty() && body.isNotEmpty() -> alertDialog(getString(R.string.alert_3), 0)
}
</code>```

And maybe kotlin has some methods for calling functions if condition is true? I thought that I will solve this problem with .run{condition} but when I do it:

```<code>alertDialog(getString(R.string.alert_1), 0).run{theme.isEmpty() && body.isEmpty()}
</code>```

my alerDialog function was called two times. Maybe I did smth wrong or kotlin has another mechanism for it?

答:
The variant using when is different from the sequence of ifs in that exactly one branch is executed. With the ifs multiple branches can be executed if their respective conditions evaluate to true.
Depending on if you want just 1 branch executed or allow multiple ones, I would keep the code using ifs or when.
run does not serve for branching at all. It allows you to call some functions on an object without assigning it to a variable because the object becomes the implicit this variable.

Body:
Right now in my project I have such functions calls:

if (theme.isNotEmpty() && body.isNotEmpty()) {
   sendToCons()
}
if (theme.isEmpty() && body.isEmpty()) {
   alertDialog(getString(R.string.alert_1), 0)
}
if (theme.isNotEmpty() && body.isEmpty()) {
   alertDialog(getString(R.string.alert_2), 0)
}
if (theme.isEmpty() && body.isNotEmpty()) {
   alertDialog(getString(R.string.alert_3), 0)
}

this code scope I changed to this one:

when {
      theme.isNotEmpty() && body.isNotEmpty() -> sendToCons()
      theme.isEmpty() && body.isEmpty() -> alertDialog(getString(R.string.alert_1), 0)
      theme.isNotEmpty() && body.isEmpty() -> alertDialog(getString(R.string.alert_2), 0)
      theme.isEmpty() && body.isNotEmpty() -> alertDialog(getString(R.string.alert_3), 0)
}

And maybe kotlin has some methods for calling functions if condition is true? I thought that I will solve this problem with .run{condition} but when I do it:

alertDialog(getString(R.string.alert_1), 0).run{theme.isEmpty() && body.isEmpty()}

my alerDialog function was called two times. Maybe I did smth wrong or kotlin has another mechanism for it?


问:
Fill a stacked boxplot of a dataframe by a column of another dataframe
I would like to get a figure of boxplots for each of the columns of my dataframe:

```<code>sampleA    sampleB    sampleC    sampleD
  1          2           3          4
  3          2           8          9.5
  2.3        4           5.6        7
  9          2.1         6          15.7
  18.1       4.8         10         22.2

</code>```

Then, I have another dataframe where I specify some features of this samples:

```<code>sampleID    FeatureA    FeatureB    FeatureC
sampleA       C            B          D
sampleB       C            A          R
sampleC       D            E          V
sampleD       M            B          T
</code>```

How can I get a boxplot for each column of the first dataframe in the same picture, coloured by FeatureA (both the boxplot and its corresponding  x axis tick) of the second dataframe?

I have been trying:

```<code>ggplot(stack(df1), aes(x = ind, y = values)) +
  geom_boxplot(fill=df2$FeatureA)+
  theme_bw()+
  theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA))
</code>```

But, this is not colouring my boxplots

This part geom_boxplot(fill=df2$FeatureA) just works if instead of FeatureA, I use a vector with colour names substituting the values of thIs factor.

This part theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA)) is not colouring the x ticks in the right order

I have also tried:

```<code>ggplot(stack(df1), aes(x = ind, y = values), fill=df2$FeatureA) +
  geom_boxplot()+
  theme_bw()+
  theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA))
</code>```

but the fill argument is not colouring at all.

Moreover, I don't get a legend with none of this commands:

答:
Like this?

```<code>library(tidyverse)
df1 <- tibble::tribble(
         ~sampleA, ~sampleB, ~sampleC, ~sampleD,
                1,        2,        3,        4,
                3,        2,        8,      9.5,
              2.3,        4,      5.6,        7,
                9,      2.1,        6,     15.7,
             18.1,      4.8,       10,     22.2
         )

df2 <- tibble::tribble(
  ~sampleID, ~FeatureA, ~FeatureB, ~FeatureC,
  "sampleA",       "C",       "B",       "D",
  "sampleB",       "C",       "A",       "R",
  "sampleC",       "D",       "E",       "V",
  "sampleD",       "M",       "B",       "T"
  )

df1 %>%
  pivot_longer(1:4,names_to = "sample", values_to = "values") %>%
  left_join(df2, by = c("sample" = "sampleID")) %>%
  ggplot(aes(x = sample, y = values, fill = FeatureA)) +
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = c("red","red","green","blue")))
</code>```

Body:
I would like to get a figure of boxplots for each of the columns of my dataframe:

sampleA    sampleB    sampleC    sampleD
  1          2           3          4
  3          2           8          9.5
  2.3        4           5.6        7
  9          2.1         6          15.7
  18.1       4.8         10         22.2

Then, I have another dataframe where I specify some features of this samples:

sampleID    FeatureA    FeatureB    FeatureC
sampleA       C            B          D
sampleB       C            A          R
sampleC       D            E          V
sampleD       M            B          T

How can I get a boxplot for each column of the first dataframe in the same picture, coloured by FeatureA (both the boxplot and its corresponding  x axis tick) of the second dataframe?

I have been trying:

ggplot(stack(df1), aes(x = ind, y = values)) +
  geom_boxplot(fill=df2$FeatureA)+
  theme_bw()+
  theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA))

But, this is not colouring my boxplots

This part geom_boxplot(fill=df2$FeatureA) just works if instead of FeatureA, I use a vector with colour names substituting the values of thIs factor.

This part theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA)) is not colouring the x ticks in the right order

I have also tried:

ggplot(stack(df1), aes(x = ind, y = values), fill=df2$FeatureA) +
  geom_boxplot()+
  theme_bw()+
  theme(axis.text.x=element_text(angle = 90, colour=df2$FeatureA))

but the fill argument is not colouring at all.

Moreover, I don't get a legend with none of this commands:

Body:
Like this?

library(tidyverse)
df1 <- tibble::tribble(
         ~sampleA, ~sampleB, ~sampleC, ~sampleD,
                1,        2,        3,        4,
                3,        2,        8,      9.5,
              2.3,        4,      5.6,        7,
                9,      2.1,        6,     15.7,
             18.1,      4.8,       10,     22.2
         )

df2 <- tibble::tribble(
  ~sampleID, ~FeatureA, ~FeatureB, ~FeatureC,
  "sampleA",       "C",       "B",       "D",
  "sampleB",       "C",       "A",       "R",
  "sampleC",       "D",       "E",       "V",
  "sampleD",       "M",       "B",       "T"
  )

df1 %>%
  pivot_longer(1:4,names_to = "sample", values_to = "values") %>%
  left_join(df2, by = c("sample" = "sampleID")) %>%
  ggplot(aes(x = sample, y = values, fill = FeatureA)) +
  geom_boxplot() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, colour = c("red","red","green","blue")))


问:
Skip Parent Background in Child class while inherit other properties
I don't want child class to inherit the immediate parent class background color which has background color as white. Instead it should skip and take background color from parent component which is bluebackground. When I use the transparent background in child class it should show blue color not white. Rest of the property of parent (whitebackground class) should be inherited just not the white background in child class.

I cannot do any changes on Parent component just I can do changes using css.

app component :

```<code><div class="bluebackground">
<app-test>
</app-test>
</div>
</code>```

Component: test

```<code>BlueBackGround Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="child">
          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class <br />
      </div>
  </div>
BlueBackGround End
</code>```

Here is the Css

```<code>.child {
    font-size: 2rem;
    text-align: center;
    color: green;
    background:transparent;
  }
  .bluebackground{
    background: blue;
     font-size: 3rem;
  }

  .whitebackground {
    background:white;
  }
</code>```

StackBlitz

https://stackblitz.com/edit/angular-ivy-hbfvjs

答:
You could try to change the CSS to the following

.child {
  font-size: 2rem;
  text-align: center;
}

.bluebackground {
  font-size: 3rem;
}

.whitebackground {
  background:white;
  color:yellow;
}

.bluebackground, .child {
  background-color: blue;
}
```
<p>Working example: Stackblitz</p>
<h3>Update</h3>
<p>There is a dirty way to include the CSS selectors from the app component to the child component.</p>
<p>test.component.ts</p>
<pre class="lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css', '../app.component.css']   // <-- include `app.component.css` here
})
export class TestComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
</code>```

Now you could use the bluebackground selector in the test component.

test.component.html

BlueBackGround Start

      Some White Background Stuff that I need

          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class

BlueBackGround End
```
<p>I've modified your Stackblitz</p>
<h3>Update: <code>encapsulation</code></h3>
<p>You could set the <code>encapsulation</code> to <code>ViewEncapsulation.None</code> in the app.component and rename the <code>child</code> selector to <code>bluebackground</code> in the child as well. Try the following</p>
<p>app.component.ts</p>
<pre class="lang-js prettyprint-override"><code>import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None     // <-- set `ViewEncapsulation.None` here
})
export class AppComponent  {
  ...
}
</code>```

test.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}
```
<p>test.component.css</p>
<pre class="lang-css prettyprint-override"><code>/* overwrite/introduce values to the `bluebackground` specific to test component */
.bluebackground {
  font-size: 2rem;
  text-align: center;
}

.whitebackground {
  background:white;
  color:yellow;
}
</code>```

test.component.html

BlueBackGround Start

      Some White Background Stuff that I need

          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class

BlueBackGround End
```

Working example: Stackblitz

Body:
I don't want child class to inherit the immediate parent class background color which has background color as white. Instead it should skip and take background color from parent component which is bluebackground. When I use the transparent background in child class it should show blue color not white. Rest of the property of parent (whitebackground class) should be inherited just not the white background in child class.

I cannot do any changes on Parent component just I can do changes using css.

app component :

<app-test>
</app-test>

Component: test

BlueBackGround Start

      Some White Background Stuff that I need

          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class

BlueBackGround End

Here is the Css

.child {
    font-size: 2rem;
    text-align: center;
    color: green;
    background:transparent;
  }
  .bluebackground{
    background: blue;
     font-size: 3rem;
  }

  .whitebackground {
    background:white;
  }

StackBlitz

https://stackblitz.com/edit/angular-ivy-hbfvjs

Body:
You could try to change the CSS to the following

.child {
  font-size: 2rem;
  text-align: center;
}

.bluebackground {
  font-size: 3rem;
}

.whitebackground {
  background:white;
  color:yellow;
}

.bluebackground, .child {
  background-color: blue;
}

Working example: Stackblitz

Update

There is a dirty way to include the CSS selectors from the app component to the child component.

test.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css', '../app.component.css']   // <-- include `app.component.css` here
})
export class TestComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

Now you could use the bluebackground selector in the test component.

test.component.html

BlueBackGround Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="child bluebackground">     <!-- include `bluebackground` here -->
          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class <br />
      </div>
  </div>
BlueBackGround End

I've modified your Stackblitz

Update: encapsulation

You could set the encapsulation to ViewEncapsulation.None in the app.component and rename the child selector to bluebackground in the child as well. Try the following

app.component.ts

import { Component, ViewEncapsulation } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ],
  encapsulation: ViewEncapsulation.None     // <-- set `ViewEncapsulation.None` here
})
export class AppComponent  {
  ...
}

test.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-test',
  templateUrl: './test.component.html',
  styleUrls: ['./test.component.css']
})
export class TestComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}

test.component.css

/* overwrite/introduce values to the `bluebackground` specific to test component */
.bluebackground {
  font-size: 2rem;
  text-align: center;
}

.whitebackground {
  background:white;
  color:yellow;
}

test.component.html

BlueBackGround Start
  <div class="whitebackground">
      Some White Background Stuff that I need
      <div class="bluebackground">
          Here i want background which should skip the parent whitebackground and show blue color same as bluebackground class <br />
      </div>
  </div>
BlueBackGround End

Working example: Stackblitz