问:
Display result in graph based on combination of year and month selection in laravel
i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine

For date selection the query as

```<code>$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);
</code>```

For yearand month selection i need query
I tried like this

    $data=$req->all();

    $results = DB::table('orders')
                         ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
                         ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
                         ->groupBy('deliver_date')
                         ->get();
    $date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'
```

plz need query

答:
You can try this!</p>

```<code> $results = DB::table('orders')
       ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
      ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
     ->groupBy(function ($val) {
return Carbon::parse($val->start_time)->format('y');  });
</code>```

Body:
i am display graph of sum of qty datewise it works but now i want to display graph in which sum of qty of month and year combine selection. My date is stored in format 2020-02-14 and i want to display sum of qty of 2020-02 that is from 2019-02 to 2020-09. I tried lot of works. I am getting graph date wise but now i want to year and month combine

For date selection the query as

$get_details=DB::select('SELECT sum(orders_qty) as sum_of_qty,deliver_date FROM `orders` WHERE deliver_date between ? AND ? GROUP BY deliver_date',[$data['start_date'],$data['end_date']]);

For yearand month selection i need query
I tried like this

    $data=$req->all();

    $results = DB::table('orders')
                         ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
                         ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
                         ->groupBy('deliver_date')
                         ->get();
    $date[start_year_month]='2019-02' $date[end_year_month]='2019-05' and actual database date='2019-02-14'

plz need query

Body:
You can try this!

 $results = DB::table('orders')
       ->select(DB::raw('DATE_FORMAT(deliver_date,"%y-%m") as deliver_date'),DB::raw('SUM(orders_qty) as sum_of_qty'))
      ->whereBetween('deliver_date',[$data['start_year_month'],$data['end_year_month']])
     ->groupBy(function ($val) {
return Carbon::parse($val->start_time)->format('y');  });


来源: stackexchange

ContentLicense: CC BY-SA 4.0

Title: Scale SVG to reveal itself entire

Body:
I have an SVG here which I'm trying to reveal entirely, as you can see, it is cut on the top. I've tried adjusting the height and widths of the SVG but have not been successful.

<svg width="1200" height="500" viewBox="0 0 10 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M-693.966 132.361C-716.67 15.8345 -692.688 -100.024 -593.05 -159.076C-488.421 -221.102 -347.029 -75.6873 -242.4 -137.653C-134.362 -201.621 35.576 -268.927 178.186 -115.804C250.312 -38.3017 279.771 97.5851 296.266 199.546C309.839 283.299 305.457 383.742 252.503 456.086C174.777 562.355 67.8352 541.053 -35.6982 489.041C-105.329 454.083 -170.152 450.381 -246.904 461.548C-307.588 470.348 -369.915 482.365 -429.564 468.163C-554.583 438.425 -664.264 284.756 -693.966 132.361Z" fill="#3620BD"/>
</svg>

The original attributes were svg width="303" height="532" viewBox="0 0 303 532"

Body:
Adjust the second parameter of the viewBox.

<svg width="1200" height="500" viewBox="0 -300 10 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M-693.966 132.361C-716.67 15.8345 -692.688 -100.024 -593.05 -159.076C-488.421 -221.102 -347.029 -75.6873 -242.4 -137.653C-134.362 -201.621 35.576 -268.927 178.186 -115.804C250.312 -38.3017 279.771 97.5851 296.266 199.546C309.839 283.299 305.457 383.742 252.503 456.086C174.777 562.355 67.8352 541.053 -35.6982 489.041C-105.329 454.083 -170.152 450.381 -246.904 461.548C-307.588 470.348 -369.915 482.365 -429.564 468.163C-554.583 438.425 -664.264 284.756 -693.966 132.361Z" fill="#3620BD"/>
</svg>


问:
Multiple select tag under one id
I am appending multiple select element inside an id called append like the following.

```<code><div id="append">
    <select name="color[]" id="colorsData1" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

    <select name="color[]" id="colorsData2" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
    <select name="color[]" id="colorsData3" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
</div>
</code>```

Now, to prevent the data duplication, I want to use condition if the user selects color red and as the color red has already been selected before either in colorsData1 or colorsData2, I want to alert user. How do I check if the any of the selected options before matches the current selected option?

The reason for using multiple select rather than checkboxes is because I am making an e-commerce website, actually. And for the stock management I am cloning div  where vendor can upload images according to the colors they select. I am also appending upload field if there is no color duplication. If the selected option is not duplicate my whole div would look like this.

And, the reason for me to check the colour duplication is not to alert the vendor but for myself. Right after the vendor makes a color selection, if the colour has already been selected before I want to divert my code to else condition where there is not code to append the fileupload field. See, vendor can have shoes of Nike of different sizes with same colors. Sizes does not matter on online shopping as they cannot tell them if it fits to them by looking at the image. So, I am allowing vendor to upload products with same color but different sizes for stock management.
There is a button with id addnew and following is my jquery code after clicking on that button:

```<code>$('#addnew').on('click', function(){
        num = num+1;
        let html = '';
        html = '<div class="form-group row div"><div class="col-md-2 col-lg-2"><select name="color[]" id="colorsData'+num+'" class="form-control selectebox"><option>--Select any One--</option></select></div><div class="col-md-3 col-lg-3"><select class="select2 form-control" name="size[]" multiple="multiple" id="sizesData'+num+'"></select></div><div class="col-md-2 col-lg-2"><input type="number" placeholder="availability" name="stock" class="form-control h-100"></div><div class="col-md-2 col-lg-2"><input class="form-control h-100" value="" type="text" name="price[]" placeholder="price"></div><div class="col-md-3 col-lg-3"><input class="form-control h-100" value="" type="text" name="discount[]" placeholder="discount"></div></div>';
        $('#append').append(html);
        if(num == 1){
            html = '<div class="form-group row image"><div class="col-md-12 col-lg-12" style="display:inherit"><a href="/vendor/filemanager/dialog.php?type=4&field_id=thumbnail'+num+'&descending=1&sort_by=date&lang=undefined&akey=061e0de5b8d667cbb7548b551420eb821075e7a6" class="btn iframe-btn btn-primary" type="button"><i class="fa fa-picture-o"></i> Choose</a><input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]"></div></div>';
            $('#append').append(html);
            responsive_filemanager_callback('thumbnail'+num);
        } else {
            var selected_color = [];
                $(".selectebox").on('change',function(){  console.log(selected_color)
                if(jQuery.inArray( this.value, selected_color)){
                    alert('duplicate color')
                } else {
                    html = '<div class="form-group row image"><div class="col-md-12 col-lg-12" style="display:inherit"><a href="/vendor/filemanager/dialog.php?type=4&field_id=thumbnail'+num+'&descending=1&sort_by=date&lang=undefined&akey=061e0de5b8d667cbb7548b551420eb821075e7a6" class="btn iframe-btn btn-primary" type="button"><i class="fa fa-picture-o"></i> Choose</a><input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]"></div></div>';
                    $('#append').append(html);
                    responsive_filemanager_callback('thumbnail'+num);
                }
                selected_color.push($(this).val());
            });
        }

    })
</code>```

and following is my code on HTML

```<code><div class="page-body">
<form action="{{ route('products.store') }}" method="POST">
    @csrf
    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>What you're selling</h5>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="name" class="block">Product Name *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input name="name" type="text" class="required form-control" id="name">
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="slug" class="block">Product Slug *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input name="slug" type="text" class="required form-control" id="slug">
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="category-2" class="block">Category *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <select name="category_id" id="category_id" class="requires form-control">
                                        <option selected disabled>--Product Category--</option>
                                        <option value="">Hair</option>
                                        <option value="">Perfumes</option>
                                        <option value="">Shoes</option>
                                    </select>
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="brand-2" class="block">Brand *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <select name="brand_id" id="brand_id" class="requires form-control">
                                        <option selected disabled>--Product Brand--</option>
                                        <option value="">Nike</option>
                                        <option value="">Zivah</option>
                                        <option value="">Caliber</option>
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>General Information</h5>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="description-2" class="block">Product description *</label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <textarea name="description" id="description" rows="10" class="form-control editor"></textarea>
                                </div>
                            </div>
                            <div class="form-group row">
                                <div class="col-md-4 col-lg-2">
                                    <label for="description-2" class="block">Video URL </label>
                                </div>
                                <div class="col-md-8 col-lg-10">
                                    <input type="url" name="video" placeholder="video url" class="form-control">
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-sm-12">
            <div class="card">
                <div class="card-header">
                    <h5>SKU Information</h5>
                    <br>
                    <span class="hint">Click on the plus button to add the SKU of the product.</span>
                </div>
                <div class="card-block">
                    <div class="row">
                        <div class="col-12">
                            <div id="append"></div>
                            <div class="form-group text-center">
                                <button type="button" class="btn btn-primary" id="addnew"><span class="icofont icofont-ui-add"></span></button>
                                <button type="button" class="btn btn-danger" id="delete"><span class="icofont icofont-ui-delete"></span></button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-12">
            <input type="submit" name="submit" value="Save Changes" class="btn btn-success pull-right" id="submit">
        </div>
    </div>

</form>
</code>```

答:
this will help you

var selected_color = [];
$(".selectebox").on('change',function(){
  if(selected_color.includes($(this).val())){
   alert("This color already selected");
   $(this).val("");
  }
selected_color.push($(this).val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="append">
<select name="color[]" id="colorsData1"  class="form-control selectebox">
   <option value = "">--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>

<select name="color[]" id="colorsData2" class="form-control selectebox">
   <option value = "" >--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>
<select name="color[]" id="colorsData3" class="form-control selectebox">
   <option value = "">--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>
</div></code>```

Title: Multiple select tag under one id

Body:
I am appending multiple select element inside an id called append like the following.

    <select name="color[]" id="colorsData1" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

    <select name="color[]" id="colorsData2" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>
    <select name="color[]" id="colorsData3" class="form-control">
        <option>--Select any One--</option>
        <option>Red</option>
        <option>Yellow</option>
        <option>Blue</option>
        <option>Black</option>
    </select>

Now, to prevent the data duplication, I want to use condition if the user selects color red and as the color red has already been selected before either in colorsData1 or colorsData2, I want to alert user. How do I check if the any of the selected options before matches the current selected option?

The reason for using multiple select rather than checkboxes is because I am making an e-commerce website, actually. And for the stock management I am cloning div  where vendor can upload images according to the colors they select. I am also appending upload field if there is no color duplication. If the selected option is not duplicate my whole div would look like this.

And, the reason for me to check the colour duplication is not to alert the vendor but for myself. Right after the vendor makes a color selection, if the colour has already been selected before I want to divert my code to else condition where there is not code to append the fileupload field. See, vendor can have shoes of Nike of different sizes with same colors. Sizes does not matter on online shopping as they cannot tell them if it fits to them by looking at the image. So, I am allowing vendor to upload products with same color but different sizes for stock management.
There is a button with id addnew and following is my jquery code after clicking on that button:

$('#addnew').on('click', function(){
        num = num+1;
        let html = '';
        html = '

<select name="color[]" id="colorsData'+num+'" class="form-control selectebox"><option>--Select any One--</option></select>

<select class="select2 form-control" name="size[]" multiple="multiple" id="sizesData'+num+'"></select>

<input type="number" placeholder="availability" name="stock" class="form-control h-100">

<input class="form-control h-100" value="" type="text" name="price[]" placeholder="price">

<input class="form-control h-100" value="" type="text" name="discount[]" placeholder="discount">

';
        $('#append').append(html);
        if(num == 1){
            html = '

 Choose<input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]">

';
            $('#append').append(html);
            responsive_filemanager_callback('thumbnail'+num);
        } else {
            var selected_color = [];
                $(".selectebox").on('change',function(){  console.log(selected_color)
                if(jQuery.inArray( this.value, selected_color)){
                    alert('duplicate color')
                } else {
                    html = '

 Choose<input id="thumbnail'+num+'" class="form-control h-100" value="" type="text" name="image[]">

';
                    $('#append').append(html);
                    responsive_filemanager_callback('thumbnail'+num);
                }
                selected_color.push($(this).val());
            });
        }

    })

and following is my code on HTML

<form action="{{ route('products.store') }}" method="POST">
    @csrf

What you're selling

                                    Product Name *

                                    <input name="name" type="text" class="required form-control" id="name">

                                    Product Slug *

                                    <input name="slug" type="text" class="required form-control" id="slug">

                                    Category *

                                    <select name="category_id" id="category_id" class="requires form-control">
                                        <option selected disabled>--Product Category--</option>
                                        <option value="">Hair</option>
                                        <option value="">Perfumes</option>
                                        <option value="">Shoes</option>
                                    </select>

                                    Brand *

                                    <select name="brand_id" id="brand_id" class="requires form-control">
                                        <option selected disabled>--Product Brand--</option>
                                        <option value="">Nike</option>
                                        <option value="">Zivah</option>
                                        <option value="">Caliber</option>
                                    </select>

General Information

                                    Product description *

                                    <textarea name="description" id="description" rows="10" class="form-control editor"></textarea>

                                    Video URL

                                    <input type="url" name="video" placeholder="video url" class="form-control">

SKU Information

                    Click on the plus button to add the SKU of the product.

                                <button type="button" class="btn btn-primary" id="addnew"></button>
                                <button type="button" class="btn btn-danger" id="delete"></button>

            <input type="submit" name="submit" value="Save Changes" class="btn btn-success pull-right" id="submit">

</form>

Body:
this will help you

var selected_color = [];
$(".selectebox").on('change',function(){
  if(selected_color.includes($(this).val())){
   alert("This color already selected");
   $(this).val("");
  }
selected_color.push($(this).val());
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="append">
<select name="color[]" id="colorsData1"  class="form-control selectebox">
   <option value = "">--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>

<select name="color[]" id="colorsData2" class="form-control selectebox">
   <option value = "" >--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>
<select name="color[]" id="colorsData3" class="form-control selectebox">
   <option value = "">--Select any One--</option>
   <option value = "Red">Red</option>
   <option value = "Yellow">Yellow</option>
   <option value = "Blue">Blue</option>
   <option value = "Black"> Black</option>
</select>
</div>


问:
Unable to install/run docker with opencv
I'm using the code below in Dockerfile and it builds successfully but it does not run. How can I get it to work?

```<code>FROM python:3.5-slim
COPY . /app
WORKDIR /app

RUN apt-get update
RUN apt-get -y upgrade

RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]
</code>```

Error:

```<code>Traceback (most recent call last):
  File "app.py", line 7, in <module>
    from my_file.test import test
  File "/app/my_file/test.py", line 9, in <module>
    from imutils import contours
  File "/usr/local/lib/python3.5/site-packages/imutils/__init__.py", line 8, in <module>
    from .convenience import translate
  File "/usr/local/lib/python3.5/site-packages/imutils/convenience.py", line 6, in <module>
    import cv2
  File "/usr/local/lib/python3.5/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory
</code>```

Docker code used:

```<code>docker build -t flask-sample-one:latest .
</code>```

and

```<code>docker run -d -p 5000:5000 flask-sample-one
</code>```

Requirements File :

```<code>opencv-contrib-python-headless==3.4.3.18
Click==7.0
cloudpickle==0.6.1
cycler==0.10.0
dask==0.20.1
decorator==4.3.0
Flask==1.0.2
imutils==0.5.1
itsdangerous==1.1.0
Jinja2==2.10
kiwisolver==1.0.1
MarkupSafe==1.1.0
networkx==2.2
numpy==1.15.4
Pillow==5.3.0
pyparsing==2.3.0
python-dateutil==2.7.5
PyWavelets==1.0.1
scikit-image==0.14.1
scipy==1.1.0
six==1.11.0
toolz==0.9.0
Werkzeug==0.14.1
</code>```

答:
I had the same issue. It occurs due to run time dependencies. Add the following code snippet in your DockerFile to install run time dependencies.

Install OpenCV's runtime dependencies

```<code>RUN apt-get update
RUN apt-get -y install libglib2.0-0
RUN apt-get -y install libsm6 \
     libxrender-dev \
     libxext6
</code>```

Body:
I'm using the code below in Dockerfile and it builds successfully but it does not run. How can I get it to work?

FROM python:3.5-slim
COPY . /app
WORKDIR /app

RUN apt-get update
RUN apt-get -y upgrade

RUN pip install -r requirements.txt
ENTRYPOINT ["python"]
CMD ["app.py"]

Error:

Traceback (most recent call last):
  File "app.py", line 7, in <module>
    from my_file.test import test
  File "/app/my_file/test.py", line 9, in <module>
    from imutils import contours
  File "/usr/local/lib/python3.5/site-packages/imutils/__init__.py", line 8, in <module>
    from .convenience import translate
  File "/usr/local/lib/python3.5/site-packages/imutils/convenience.py", line 6, in <module>
    import cv2
  File "/usr/local/lib/python3.5/site-packages/cv2/__init__.py", line 3, in <module>
    from .cv2 import *
ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

Docker code used:

docker build -t flask-sample-one:latest .

and

docker run -d -p 5000:5000 flask-sample-one

Requirements File :

opencv-contrib-python-headless==3.4.3.18
Click==7.0
cloudpickle==0.6.1
cycler==0.10.0
dask==0.20.1
decorator==4.3.0
Flask==1.0.2
imutils==0.5.1
itsdangerous==1.1.0
Jinja2==2.10
kiwisolver==1.0.1
MarkupSafe==1.1.0
networkx==2.2
numpy==1.15.4
Pillow==5.3.0
pyparsing==2.3.0
python-dateutil==2.7.5
PyWavelets==1.0.1
scikit-image==0.14.1
scipy==1.1.0
six==1.11.0
toolz==0.9.0
Werkzeug==0.14.1

Body:
I had the same issue. It occurs due to run time dependencies. Add the following code snippet in your DockerFile to install run time dependencies.

Install OpenCV's runtime dependencies

RUN apt-get update
RUN apt-get -y install libglib2.0-0
RUN apt-get -y install libsm6 \
     libxrender-dev \
     libxext6


问:
Is it possible to insert a date without considering leap year day 29th Feb in leap year with pandas dataframe or any other means?
I have a time series of 65 year (1941-2005). I have inserted a date coloumn in the dataframe as shown below:

```<code>Dataset= pd.read_csv('city10.csv', header = None)
Dataset['Date'] = pd.date_range(start='1/1/1951', periods=len(Dataset), freq='D')
Dataset.set_index('Date', inplace=True)
</code>```

This generates the following dataframe

```<code>Date         0       1       2       3  ...       5       6        7         8
1941-01-01  0.0  17.844  155.33  426.53  ...  61.102  47.929 -4.58980 -4.597900
1941-01-02  0.0  18.582  124.23  425.69  ...  70.191  51.980 -3.00210 -3.793400
1941-01-03  0.0  19.464  111.64  425.03  ...  74.315  56.936 -1.63070 -2.724700
        ...     ...     ...     ...  ...     ...     ...      ...       ...
2005-11-23  0.0  17.832  140.09  439.76  ...  63.003  49.942 -0.79576 -5.252300
2005-11-24  0.0  17.904  149.54  439.58  ...  58.072  47.666 -4.88510 -5.032600
</code>```

The above-generated date generates 29th February in the leap year. I don't want to generate 29th Feb date i.e. for the series I want to considers 365 days in each year. It should not generate 29th Feb in a leap year.

答:
One idea is generate date_range with longer length, then remove 29.2. and assign to column by real length of DataFrame:

```<code>d = pd.date_range(start='1/1/1951', periods=len(Dataset) + int(len(Dataset) // 365), freq='D')
d = d[(d.month != 2) | (d.day != 29)]

Dataset['Date'] = d[:len(Dataset)]
</code>```

Body:
I have a time series of 65 year (1941-2005). I have inserted a date coloumn in the dataframe as shown below:

Dataset= pd.read_csv('city10.csv', header = None)
Dataset['Date'] = pd.date_range(start='1/1/1951', periods=len(Dataset), freq='D')
Dataset.set_index('Date', inplace=True)

This generates the following dataframe

Date         0       1       2       3  ...       5       6        7         8
1941-01-01  0.0  17.844  155.33  426.53  ...  61.102  47.929 -4.58980 -4.597900
1941-01-02  0.0  18.582  124.23  425.69  ...  70.191  51.980 -3.00210 -3.793400
1941-01-03  0.0  19.464  111.64  425.03  ...  74.315  56.936 -1.63070 -2.724700
        ...     ...     ...     ...  ...     ...     ...      ...       ...
2005-11-23  0.0  17.832  140.09  439.76  ...  63.003  49.942 -0.79576 -5.252300
2005-11-24  0.0  17.904  149.54  439.58  ...  58.072  47.666 -4.88510 -5.032600

The above-generated date generates 29th February in the leap year. I don't want to generate 29th Feb date i.e. for the series I want to considers 365 days in each year. It should not generate 29th Feb in a leap year.

Body:
One idea is generate date_range with longer length, then remove 29.2. and assign to column by real length of DataFrame:

d = pd.date_range(start='1/1/1951', periods=len(Dataset) + int(len(Dataset) // 365), freq='D')
d = d[(d.month != 2) | (d.day != 29)]

Dataset['Date'] = d[:len(Dataset)]


问:
How can I convert a class into Dictionary<string,string>?
Can I convert Class into Dictionary<string, string>?

In Dictionary I want my class properties as keys and value of particular a property as the value.

Suppose my class is

```<code>public class Location
{
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set;
}
</code>```

Now suppose my data is

```<code>city = Delhi
state = Delhi
country = India
</code>```

Now you can understand my point easily!

I want to make a Dictionary! That dictionary should be like:

```<code>Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");
</code>```

I can get the value! But how can I get property names (not value)?

What should I code to create it dynamic? That should work for every class which I want.

You can understand this question as:

How can I get a list of properties from particular class?

Now again I am explaining one of my eagernesses about Dictionary! This question popuped in my mind from answer of my previous question!!

答:
I hope this extension can be useful to someone.</p>

```<code>public static class Ext {
    public static Dictionary<string, object> ToDict<T>(this T target)
        => target is null
            ? new Dictionary<string, object>()
            : typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .ToDictionary(
                            x => x.Name,
                            x => x.GetValue(target)
                        );
}
</code>```

Body:
Can I convert Class into Dictionary<string, string>?

In Dictionary I want my class properties as keys and value of particular a property as the value.

Suppose my class is

public class Location
{
    public string city { get; set; }
    public string state { get; set; }
    public string country { get; set;
}

Now suppose my data is

city = Delhi
state = Delhi
country = India

Now you can understand my point easily!

I want to make a Dictionary! That dictionary should be like:

Dictionary<string,string> dix = new Dictionary<string,string> ();
dix.add("property_name", "property_value");

I can get the value! But how can I get property names (not value)?

What should I code to create it dynamic? That should work for every class which I want.

You can understand this question as:

How can I get a list of properties from particular class?

Now again I am explaining one of my eagernesses about Dictionary! This question popuped in my mind from answer of my previous question!!

Body:
I hope this extension can be useful to someone.

public static class Ext {
    public static Dictionary<string, object> ToDict<T>(this T target)
        => target is null
            ? new Dictionary<string, object>()
            : typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public)
                        .ToDictionary(
                            x => x.Name,
                            x => x.GetValue(target)
                        );
}


问:
Variable1 value exists in variable2 script
I have a table with sample1 and sample2 Columns. Some of the sample2 values exist in sample 1.
Now I want to extract a table where sample2 value is NOT available in sample1. Please see the tables below for clarification.
Thanks.

答:
You basically said the answer in you question. Make sure Sample2 is NOT IN Sample1

```<code>SELECT *
FROM Table
WHERE Sample2 NOT IN (SELECT Sample1 From Table)
</code>```

Body:
You basically said the answer in you question. Make sure Sample2 is NOT IN Sample1

SELECT *
FROM Table
WHERE Sample2 NOT IN (SELECT Sample1 From Table)


问:
IE overrides cursor when using contenteditable
I'm wanting a pointer cursor over an element until that element has focus, and then turn to the typical text caret. Easy enough in Chrome, but IE11 and Edge don't seem to let me change the cursor if the element has the contenteditable attribute.

```<code>#thing{cursor:pointer;}

<div id="thing" contenteditable="true"style="width:200px;border:1px solid black;cursor:pointer;"> this is a some random foo bar dog jumps over a stick test</div>
</code>```

The simple example shows the cursor only changing if contentedible is false. If true, it only does the text cursor. Rather annoying since MS is the one who supposedly created this attribute.  Is this just a bug? Intended by design?  Is there a workaround?

I came across this link but unfortunately I'm still not having any luck by changing the DTD.
How to change cursor style on element with 'contenteditable' attribute in IE?

答:
I have reproduced the problem on my side, it could be the default behavior of the IE browser, I will feedback this issue.

As a workaround, I suggest you could try to use the <textarea> tag, by using this tag, in IE browser it could use the pointer cursor, code as below:

```<code><textarea  id="thing" contenteditable="true" style="width:200px; height:100px; border :1px solid black; cursor:pointer">

    this is a some random foo bar jumps over a stick test

</textarea>
</code>```

Body:
I'm wanting a pointer cursor over an element until that element has focus, and then turn to the typical text caret. Easy enough in Chrome, but IE11 and Edge don't seem to let me change the cursor if the element has the contenteditable attribute.

#thing{cursor:pointer;}

 this is a some random foo bar dog jumps over a stick test

The simple example shows the cursor only changing if contentedible is false. If true, it only does the text cursor. Rather annoying since MS is the one who supposedly created this attribute.  Is this just a bug? Intended by design?  Is there a workaround?

I came across this link but unfortunately I'm still not having any luck by changing the DTD.
How to change cursor style on element with 'contenteditable' attribute in IE?

Body:
I have reproduced the problem on my side, it could be the default behavior of the IE browser, I will feedback this issue.

As a workaround, I suggest you could try to use the <textarea> tag, by using this tag, in IE browser it could use the pointer cursor, code as below:

<textarea  id="thing" contenteditable="true" style="width:200px; height:100px; border :1px solid black; cursor:pointer">

    this is a some random foo bar jumps over a stick test

</textarea>


问:
read JSON to PHP from javascript
I have an API that is available only in javascript (no PHP). It fetches some data of which I made a JSON string. What I need to know is how do I read this string in other page?

I tried using following :

```<code>$json = file_get_contents($url);
</code>```

but of course the string I get is not JSON but is actually the javascript code that will generate json in original page. Any suggestions ?
Thank you.

P.S. I also tried set cookie + redirect. Though that worked, I'd like to know a better solution.

Here is the javascript code

```<code>            function searchComplete() {

                 if (imageSearch.results && imageSearch.results.length > 0)
                 {
                    var contentDiv = document.getElementById('content');
                    contentDiv.innerHTML = '';
                    var results = imageSearch.results;

                    var data = "{['data' : [\n";

                    for (var i = 0; i < results.length; i++) {
                        //var result = results[i];
                        var result = results[i];

                        data += "{\n";
                        data += "'url' : '"+result.url+"'";
                        data += "\n},\n";

                   }
                   data += "]]}";
                   setCookie("datajson", data, 1); // This is how i set the cookie and redirected
                   window.location = "JSPHP.php?data="+data;

                document.getElementById('body').innerHTML = data;
                  }
            }
</code>```

答:
Ok, you said it is not JSON. Thus json_decode() function is useless here without additional things. If this happens on browser side, you should probably pass the data to the server using AJAX.

Alternatively you can take a look how this API works (maybe it connects with some server using JSONs to exchange data?) and do the same in PHP.

EDIT:

You do not need to create a string of JSON on JavaScript side. JSON is itself object notation in JavaScript.

If you need to pass the data, just do something similar to this:

```<code>var data = [];
for (var i=0; i<results.length; i++){
    data[] = {
        'url': result.url
    };
}
</code>```

Then you only need to pass this data to the server. You can use .get() function (if you need to pass it using GET) from jQuery like that:

```<code>jQuery.get('http://example.com/', data, function(){
    // something to do when successful
});
</code>```

It is pretty simple and the basic is: create data correctly and pass it to the server using AJAX call.

ContentLicense: CC BY-SA 3.0

Title: read JSON to PHP from javascript

Body:
I have an API that is available only in javascript (no PHP). It fetches some data of which I made a JSON string. What I need to know is how do I read this string in other page?

I tried using following :

$json = file_get_contents($url);

but of course the string I get is not JSON but is actually the javascript code that will generate json in original page. Any suggestions ?
Thank you.

P.S. I also tried set cookie + redirect. Though that worked, I'd like to know a better solution.

Here is the javascript code

            function searchComplete() {

                 if (imageSearch.results && imageSearch.results.length > 0)
                 {
                    var contentDiv = document.getElementById('content');
                    contentDiv.innerHTML = '';
                    var results = imageSearch.results;

                    var data = "{['data' : [\n";

                    for (var i = 0; i < results.length; i++) {
                        //var result = results[i];
                        var result = results[i];

                        data += "{\n";
                        data += "'url' : '"+result.url+"'";
                        data += "\n},\n";

                   }
                   data += "]]}";
                   setCookie("datajson", data, 1); // This is how i set the cookie and redirected
                   window.location = "JSPHP.php?data="+data;

                document.getElementById('body').innerHTML = data;
                  }
            }

Body:
Ok, you said it is not JSON. Thus json_decode() function is useless here without additional things. If this happens on browser side, you should probably pass the data to the server using AJAX.

Alternatively you can take a look how this API works (maybe it connects with some server using JSONs to exchange data?) and do the same in PHP.

EDIT:

You do not need to create a string of JSON on JavaScript side. JSON is itself object notation in JavaScript.

If you need to pass the data, just do something similar to this:

var data = [];
for (var i=0; i<results.length; i++){
    data[] = {
        'url': result.url
    };
}

Then you only need to pass this data to the server. You can use .get() function (if you need to pass it using GET) from jQuery like that:

jQuery.get('http://example.com/', data, function(){
    // something to do when successful
});

It is pretty simple and the basic is: create data correctly and pass it to the server using AJAX call.


问:
In BPMN - how to model interface with details (fields) between two components?
I've been wondering how to model interface between two components using it's rectangular representation (not lollipop) with all the details (attributes, operations).

I have two components and interface that lets them to "talk" to each other.

Using "lollipop" notation I would do this in this way:

But I didn't know how to attach my interface definition to this flow.
Is it correct to attach it to the line of Information Flow? What type of assotiation use to do this?

答:
I found in OMG specifiaction the following description.

The component providing the interface REALIZE it. The one that consume it - USES it.

Recreating the diagram gave me this state:


问:
How can i get properties and values from type object?
I have the following json:

```<code>{
        "Values":
         {
           "value1": "test1",
           "value2": "teste2"
         }
}
</code>```

And i have to get a specific property and value.This is my code:

```<code>   public MyMethod(object model)
   {
       var x = model.GetType().GetProperty("value1");
   }
</code>```

But this is always null. How can i get this?

答:
You could convert it to dynamic type and use

```<code>public string MyMethod(object model)
{
   var x = ((dynamic)model).Values["value1"].Value;
   return x;
}
</code>```

If you use asp.net core 3.0, you need to add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson and update Startup.ConfigureServices to call AddNewtonsoftJson.

```<code>services.AddControllers().AddNewtonsoftJson();
</code>```

I also find out another solution to use JObject, you need to add a reference  using Newtonsoft.Json.Linq; for you controller.

```<code>public string MyMethod(object model)
{
        var data = (JObject)model;
        //save all values in items
        var items = data.SelectToken("Values").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
        foreach (var item in items)
        {
            if (item.Key == "value1")
            {
                var x = (string)item.Value;
            }
        }
 }
</code>```

Body:
I have the following json:

{
        "Values":
         {
           "value1": "test1",
           "value2": "teste2"
         }
}

And i have to get a specific property and value.This is my code:

   public MyMethod(object model)
   {
       var x = model.GetType().GetProperty("value1");
   }

But this is always null. How can i get this?

Body:
You could convert it to dynamic type and use

public string MyMethod(object model)
{
   var x = ((dynamic)model).Values["value1"].Value;
   return x;
}

If you use asp.net core 3.0, you need to add a package reference to Microsoft.AspNetCore.Mvc.NewtonsoftJson and update Startup.ConfigureServices to call AddNewtonsoftJson.

services.AddControllers().AddNewtonsoftJson();

I also find out another solution to use JObject, you need to add a reference  using Newtonsoft.Json.Linq; for you controller.

public string MyMethod(object model)
{
        var data = (JObject)model;
        //save all values in items
        var items = data.SelectToken("Values").Children().OfType<JProperty>().ToDictionary(p => p.Name, p => p.Value);
        foreach (var item in items)
        {
            if (item.Key == "value1")
            {
                var x = (string)item.Value;
            }
        }
 }


问:
When to release a NSString in iPhone
I have the following method

```<code>   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }
</code>```

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

And if I don't have to release it, who is the responsible for releasing?

答: stringWithUTF8String: returns an autorelease string which will be released automatically by Cocoa in the next eventloop. But the string is also retained in the array when you do addObject:...so as long as it is in the array it will be retained.

OwnerDisplayName: Sacha Fuentes

ContentLicense: CC BY-SA 2.5

Title: When to release a NSString in iPhone

Body:
I have the following method

   -(NSMutableArray *) getPaises {
     NSMutableArray * paises;
     paises = [[NSMutableArray alloc] init];
     while( get new row ) {
      NSString *aPais =  [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
      [paises addObject:aPais];
     }
     return paises;
    }

I am not releasing the aPais, because if I do it the application crashes. I don't know when or if whether I should release it somewhere after using it and, if so, how do I do it. Just release the NSMutableArray is enough? Or do I have to traverse it and release each object?

And if I don't have to release it, who is the responsible for releasing?

LastEditorDisplayName: andynormancx

OwnerDisplayName: epatel


问:
How to toggle between Isotope's layout modes?
Two questions, everybody:

1) How do I toggle Isotope on and off?

2) How do I toggle layout modes? That is, how do I go from this:

```<code> $('.content').isotope({  itemSelector : '.hentry',
                          layoutMode : 'cellsByRow',
                          cellsByRow : { columnWidth : 240, rowHeight : 360 } });
</code>```

to this:

```<code> $('.content').isotope({  itemSelector : '.hentry',
                          layoutMode : 'masonry'});
</code>```

with a simple click switch? Any ideas?

Thanks!

答:
See http://jsfiddle.net/desandro/dbgFa/

1) To disable Isotope after initializing it, use the destroy method

```<code>$('.content').isotope('destroy')
</code>```

Then turn it back on by triggering Isotope again

```<code>$('.content').isotope( /* options */ )
</code>```

2) You would change layout modes just like your example code, by setting the layoutMode in the options. This will also trigger a re-layout and the layout will change.

Body:
Two questions, everybody:

1) How do I toggle Isotope on and off?

2) How do I toggle layout modes? That is, how do I go from this:

 $('.content').isotope({  itemSelector : '.hentry',
                          layoutMode : 'cellsByRow',
                          cellsByRow : { columnWidth : 240, rowHeight : 360 } });

to this:

 $('.content').isotope({  itemSelector : '.hentry',
                          layoutMode : 'masonry'});

with a simple click switch? Any ideas?

Thanks!

Body:
See http://jsfiddle.net/desandro/dbgFa/

1) To disable Isotope after initializing it, use the destroy method

$('.content').isotope('destroy')

Then turn it back on by triggering Isotope again

$('.content').isotope( /* options */ )

2) You would change layout modes just like your example code, by setting the layoutMode in the options. This will also trigger a re-layout and the layout will change.


问:
Fragment Back Stack
I have 3 fragments like Fragment 1, Fragment 2, Fragment 3

These all are opened using replace transaction and api is implemented in OnViewCreated in each fragment.

Now when i move from 2nd fragment to 3rd, then 2nd fragment should be removed and there should only 1st fragment in stack.

The Problem occurs is that when i move from 2nd to 3rd, the api of 3rd should be called that is working fine but along with this, api of 1st fragment is also called.

I don't want 1st fragment to be called when calling 3rd.

答:
Sorry, but your 3rd Fragment will not call 1st Fragment's functionality unless you make it with viewPager or Tabs. If you do not want 2nd fragment to be in stack just remove .addToBackStack() function from your fragment attaching.</p>

```<code>getSupportFragmentManager().beginTransaction()
.replace(R.id.container, firstFragment)
.addToBackStack(null).commit();

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, secondFragment).commit();

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, thirdFragment)
.addToBackStack(null).commit();
</code>```

Title: Fragment Back Stack

Body:
Sorry, but your 3rd Fragment will not call 1st Fragment's functionality unless you make it with viewPager or Tabs. If you do not want 2nd fragment to be in stack just remove .addToBackStack() function from your fragment attaching.

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, firstFragment)
.addToBackStack(null).commit();

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, secondFragment).commit();

getSupportFragmentManager().beginTransaction()
.replace(R.id.container, thirdFragment)
.addToBackStack(null).commit();


问:
How to mount same volume on to all pods in a kubernetes namespace
We have a namespace in kubernetes where I would like some secrets (files like jks,properties,ts,etc.) to be made available to all the containers in all the pods (we have one JVM per container & one container per pod kind of Deployment).

I have created secrets using kustomization and plan to use it as a volume for spec of each Deployment & then volumeMount it for the container of this Deployment. I would like to have this volume to be mounted on each of the containers deployed in our namespace.

I want to know if kustomize (or anything else) can help me to mount this volume on all the deployments in this namespace?

I have tried the following patchesStrategicMerge

```<code>---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: myNamespace
spec:
  template:
    spec:
      imagePullSecrets:
        - name: pull-secret
      containers:
        - volumeMounts:
          - name: secret-files
            mountPath: "/secrets"
            readOnly: true
      volumes:
      - name: secret-files
        secret:
          secretName: mySecrets
          items:
          - key: key1
            path: ...somePath
          - key: key2
            path: ...somePath
</code>```

It requires name in metadata section which does not help me as all my Deployments have different names.

答:
Inject Information into Pods Using a PodPreset

You can use a PodPreset object to inject information like secrets, volume mounts, and environment variables etc into pods at creation time.

Update: Feb 2021. The PodPreset feature only made it to alpha. It was removed in v1.20 of kubernetes. See release note https://kubernetes.io/docs/setup/release/notes/

The v1alpha1 PodPreset API and admission plugin has been removed with
no built-in replacement. Admission webhooks can be used to modify pods
on creation. (#94090, @deads2k) [SIG API Machinery, Apps, CLI, Cloud
Provider, Scalability and Testing]

Body:
We have a namespace in kubernetes where I would like some secrets (files like jks,properties,ts,etc.) to be made available to all the containers in all the pods (we have one JVM per container & one container per pod kind of Deployment).

I have created secrets using kustomization and plan to use it as a volume for spec of each Deployment & then volumeMount it for the container of this Deployment. I would like to have this volume to be mounted on each of the containers deployed in our namespace.

I want to know if kustomize (or anything else) can help me to mount this volume on all the deployments in this namespace?

I have tried the following patchesStrategicMerge

---
apiVersion: apps/v1
kind: Deployment
metadata:
  namespace: myNamespace
spec:
  template:
    spec:
      imagePullSecrets:
        - name: pull-secret
      containers:
        - volumeMounts:
          - name: secret-files
            mountPath: "/secrets"
            readOnly: true
      volumes:
      - name: secret-files
        secret:
          secretName: mySecrets
          items:
          - key: key1
            path: ...somePath
          - key: key2
            path: ...somePath

It requires name in metadata section which does not help me as all my Deployments have different names.


问:
Embed font-awesome icon in Rails button_to
I would like to have a button as follow:

```<code>[ Sign in with FB]
</code>```

where FB is a font-awesome icon. I tried the following, but couldn't figure out how to embed the icon to the button:

```<code>= button_to "Login with", user_omniauth_authorize_path(:facebook)
</code>```

Here is how font-awesome is normally invoked (in haml):

```<code>%i.icon-facebook-sign
</code>```

How do I achieve the effect I want?

Thank you.

答:
try this code, it runs for me

<%= button_to line_items_path(product_id: produit.id),class:"btn btn-outline-primary" do %>

                <% end %>

just change the icon

Body:
I would like to have a button as follow:

[ Sign in with FB]

where FB is a font-awesome icon. I tried the following, but couldn't figure out how to embed the icon to the button:

= button_to "Login with", user_omniauth_authorize_path(:facebook)

Here is how font-awesome is normally invoked (in haml):

%i.icon-facebook-sign

How do I achieve the effect I want?

Thank you.

Body:
try this code, it runs for me

<%= button_to line_items_path(product_id: produit.id),class:"btn btn-outline-primary" do %>
                <i class="fas fa-shopping-basket"></i>
                <% end %>

just change the icon


问:
Can't use dict.values() with min func's key
I created a dict:

```<code>scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598}
</code>```

I can use min function with it using:

```<code>min(scores.keys(),key = lambda x: scores[x])
min(scores, key=scores.get)
</code>```

but when I try to use:

```<code>min(scores.keys(),key = scores.values())
</code>```

I get an error :

'dict_values' object is not callable

Could someone please explain why?

答:
key must be a function callable with one parameter. values() is not a function, it's a view, a sequence of all values in the dict. And while scores.values is a function it's not callable with a parameter.

It's also unclear as to what you think your snippet would actually do even if it worked. What would looking for a key in the set of values do exactly?

Body:
I created a dict:

scores = {5: 35044.51299744237, 25: 29016.41319191076, 50: 27405.930473214907, 100: 27282.50803885739, 250: 27893.822225701646, 500: 29454.18598068598}

I can use min function with it using:

min(scores.keys(),key = lambda x: scores[x])
min(scores, key=scores.get)

but when I try to use:

min(scores.keys(),key = scores.values())

I get an error :

'dict_values' object is not callable

Could someone please explain why?


问:
Getting error in mongodb connection during test case?
I am getting the following error during test condition. I did not understand where i am doing mistake.</p>

```<code>    client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT)

    raise TypeError("port must be an instance of int")
    TypeError: port must be an instance of int
</code>```

答:
Your settings.MONGO_PORT value is most likely a string, while it should be an integer.

You can either change it at the source, or cast it here at the call site:

```<code>client = MongoClient(settings.MONGO_HOST, int(settings.MONGO_PORT))
</code>```

Body:
I am getting the following error during test condition. I did not understand where i am doing mistake.

    client = MongoClient(settings.MONGO_HOST, settings.MONGO_PORT)

    raise TypeError("port must be an instance of int")
    TypeError: port must be an instance of int

Body:
Your settings.MONGO_PORT value is most likely a string, while it should be an integer.

You can either change it at the source, or cast it here at the call site:

client = MongoClient(settings.MONGO_HOST, int(settings.MONGO_PORT))


问:
Can someone explain the output of following code?

var employeeId = 'abc123';
function foo() {
 employeeId = '123bcd';
 return;

 function employeeId() {
  var x = 0;
 }
}
foo();
console.log(employeeId); //abc123```

The question is based on hoisting. We are printing employeeId in console.log here. Can someone explain the output of above code ?

答:
By the rule of hoisting, in the same closure, the function declaration is almost equivalent to:

var employeeId = 'abc123';

function foo() {
 var employeeId = function () { // hoisted from the function below
  var x = 0;
 }

 employeeId = '123bcd';
 return;

 // function employeeId() {
 //  var x = 0;
 // }
}

foo();
console.log(employeeId); //abc123```

So the outer scope employeeId hasn't been altered since it got obscured in the foo
function scope.

Body:
var employeeId = 'abc123';
function foo() {
 employeeId = '123bcd';
 return;

 function employeeId() {
  var x = 0;
 }
}
foo();
console.log(employeeId); //abc123

The question is based on hoisting. We are printing employeeId in console.log here. Can someone explain the output of above code ?

Body:
By the rule of hoisting, in the same closure, the function declaration is almost equivalent to:

var employeeId = 'abc123';

function foo() {
 var employeeId = function () { // hoisted from the function below
  var x = 0;
 }

 employeeId = '123bcd';
 return;

 // function employeeId() {
 //  var x = 0;
 // }
}

foo();
console.log(employeeId); //abc123

So the outer scope employeeId hasn't been altered since it got obscured in the foo
function scope.


问:
Display array items on a div element on click of button using vanilla javascript
Can any one please tell me how can print the elements array on a div element</p>

```<code>var myArray=["stone","paper","scissors"]

<button onclick="printnumbers()"></button>
<div id="result">

</div>
</code>```

答:
With Vanilla.js only, this should help you :)

const myArray = ["stone", "paper", "scissors"];

const el = document.getElementById('myButton');

el.addEventListener('click', function() {
  const div = document.getElementById("result");
  myArray.forEach((currentValue, index, array) => {
    let text = index == (array.length - 1) ? `${currentValue}` : `${currentValue}, `;
    let content = document.createTextNode(text);
    div.appendChild(content)
  });
}, false);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#result{
  width: 20rem;
  height: 1rem;
  margin-top: 2rem;
  border-width:3px;
  border-style:dashed;
  border-color:#FFAC55;
  padding: 15px 20px;
}</code>```

<!DOCTYPE html>

    <button id="myButton">Try it</button>

```

Body:
Can any one please tell me how can print the elements array on a div element

var myArray=["stone","paper","scissors"]

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

Body:
With Vanilla.js only, this should help you :)

const myArray = ["stone", "paper", "scissors"];

const el = document.getElementById('myButton');

el.addEventListener('click', function() {
  const div = document.getElementById("result");
  myArray.forEach((currentValue, index, array) => {
    let text = index == (array.length - 1) ? `${currentValue}` : `${currentValue}, `;
    let content = document.createTextNode(text);
    div.appendChild(content)
  });
}, false);

#result{
  width: 20rem;
  height: 1rem;
  margin-top: 2rem;
  border-width:3px;
  border-style:dashed;
  border-color:#FFAC55;
  padding: 15px 20px;
}

<!DOCTYPE html>
<html>

<body>

    <button id="myButton">Try it</button>
    <div id="result"></div>

</body>

</html>


问:
PHP form not writing to mySQL database
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

```<code><form method="post" action="post_metrics_stack.php" >
<p>Date<br />
<input name="date" type="text" /></p>

<p>Metric1<br />
<input name="metric1" type="text" /></p>

<p>Metric2<br />
<input name="metric2" type="text" /></p>

<input type="submit" name="submit" value="Submit" />
</form>
</code>```

* Processor File *

```<code><?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>
</code>```

答:
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.

When connecting to the database, you write

```<code>$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}
</code>```

You can simplify this, and making this more readable by writing

```<code>mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());
</code>```

For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:

```<code>"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"
</code>```

And finally, here's a speed concideration.

There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code

```<code>$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'

echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'

echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.
</code>```

As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although

```<code>echo "the cat is $age years old"
</code>```

is shorter to type than

echo 'the cat is '.$age.' years old';

it will boost your page loading when you write larger applications.

Title: PHP form not writing to mySQL database

Body:
I'm just learning PHP and am trying the most basic thing: capturing info from a form and sticking it into a table in a mySQL database.  I'm embarrassed to ask such a stupid newbie question, but after reviewing two books, several Stack Overflow posts, and 7 different tutorials, I still can't get my pathetic code to write a few lousy metrics to my database.

Here's the latest version of the code.  Could someone please tell me what I am doing wrong?

* Basic HTML Form *

<form method="post" action="post_metrics_stack.php" >

Date

<input name="date" type="text" />

Metric1

<input name="metric1" type="text" />

Metric2

<input name="metric2" type="text" />

<input type="submit" name="submit" value="Submit" />
</form>

* Processor File *

<?php

$date=$_POST['date'];
$metric1=$_POST['metric1'];
$metric2=$_POST['metric2'];

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

$mydb = mysql_select_db("mydatabasename");
if (!$mydb)
  {die('Could not connect to database: ' . mysql_error());}

mysql_query("INSERT INTO my_metrics VALUES ('$date', '$metric1', '$metric2')");
 Print "Your metrics have been successfully added to the database.";

mysql_close($con);
?>

Body:
As far as the vulnerability to SQL injection, you should feed your input strings to mysql_real_escape_string();. This will escape any unwanted characters.

When connecting to the database, you write

$con = mysql_connect("localhost", "root", "mypassword");
if (!$con)
  {die('Could not connect to mysql: ' . mysql_error());}

You can simplify this, and making this more readable by writing

mysql_connect('localhost','root','mypassword') or die('Could not connect to mysql:<hr>'.mysql_error());

For solving your problem, see if specifieng column names helps. If you don't, mysql will assume you enter values in the order of the columns, you might get some trouble with an ID field, or something like that. Your query could look like this:

"INSERT INTO my metrics (date,metric1,metric2) VALUES ('$data','$metric1','$metric2'))"

And finally, here's a speed concideration.

There are two ways to write strings: using single quotes ('string'), and using double quotes ("string"). in the case of 'string' and "string", they will work exactly the same, but there is a difference. Look at the following code

$age=3
echo 'the cat is $age years old.';
//prints out 'the cat is $age years old.'

echo "the cat is $age years old.";
//prints out 'the cat is 3 years old'

echo 'the cat is '.$age.' years old';
//prints out 'the cat is 3 years old'.

As you can see from this example, when you use single quotes, PHP doesn't check the string for variables and other things to parse inside the string. Doing that takes PHP longer than concatinating the variable to the string. so although

echo "the cat is $age years old"

is shorter to type than

echo 'the cat is '.$age.' years old';

it will boost your page loading when you write larger applications.


问:
How do you center an error message created with BootstrapValidate?
First time using bootstrap and first time asking a question on stackoverflow! I am creating this mockup with forms for email, subject and message. I am also using bootstrap validator to get error messages to pop-up (like ""). but they appear all the way to the left of the window. Anyone know of a way to get the below the input box? Or even above the input box? Like if where says "Email" I would like the error message that says "Please enter a valid email" to pop up right next to it. I've included the html and css. Hopefully I did it right. Thanks!</p>

```<code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="form-issue.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://cdn.rawgit.com/PascaleBeier/bootstrap-validate/v2.2.0/dist/bootstrap-validate.js"></script>
</head>

<body>
    <div class="contact">
        <h2>CONTACT</h2>
        <form action="" method="POST">
            <div class="form-group">
                <label class="label" for="email">Email</label>
                <input id="email" class="form-control" type="text" name="email">
            </div>
            <div class="form-group">
                <label class="label" for="subject"> Subject </label>
                <input id="subject" class="form-control" type="text" name="subject">
            </div>
            <div class="form-group">
                <label class="label" for="message">Message</label>
                <textarea id="message" class="form-control" name="message" rows="10"></textarea>
                <input class="button" type="submit" value="Submit">
            </div>
        </form>
    </div>

    <script>
        bootstrapValidate('#email', 'email:Please enter a valid email');
        bootstrapValidate('#subject', 'required:Subject is required');
        bootstrapValidate('#message', 'required:Message is required');
    </script>
</body>

</html>
</code>```

```<code>.contact {
    color: white;
    background-color: #c0c0c0;
    padding-top: 2%;
    padding-bottom: 4%;
    width: 100%;
}

.contact h2 {
    text-align: center;
}

.form-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 25px;
}

#email,
#subject,
#message {
    width: 30%;
}

.label {
    width: 30%;
    text-align: left;
}

.button {
    background-color: #000000;
    color: white;
    text-align: center;
    width: fit-content;
    min-height: inherit;
    border-color: #000000;
    border-width: 10px;
    margin-top: 20px;
    margin-bottom: 5px;
}
</code>```

答: Use Bootstrap class "text-center" in class attribute of an element.</p>

Body:
First time using bootstrap and first time asking a question on stackoverflow! I am creating this mockup with forms for email, subject and message. I am also using bootstrap validator to get error messages to pop-up (like ""). but they appear all the way to the left of the window. Anyone know of a way to get the below the input box? Or even above the input box? Like if where says "Email" I would like the error message that says "Please enter a valid email" to pop up right next to it. I've included the html and css. Hopefully I did it right. Thanks!

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="form-issue.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

CONTACT

        <form action="" method="POST">

                Email
                <input id="email" class="form-control" type="text" name="email">

                 Subject
                <input id="subject" class="form-control" type="text" name="subject">

                Message
                <textarea id="message" class="form-control" name="message" rows="10"></textarea>
                <input class="button" type="submit" value="Submit">

        </form>

.contact {
    color: white;
    background-color: #c0c0c0;
    padding-top: 2%;
    padding-bottom: 4%;
    width: 100%;
}

.contact h2 {
    text-align: center;
}

.form-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 25px;
}

#email,
#subject,
#message {
    width: 30%;
}

.label {
    width: 30%;
    text-align: left;
}

.button {
    background-color: #000000;
    color: white;
    text-align: center;
    width: fit-content;
    min-height: inherit;
    border-color: #000000;
    border-width: 10px;
    margin-top: 20px;
    margin-bottom: 5px;
}


问:
I'm unable to install opencv-contrib-python in docker
I tried installing opencv-contrib-python but I'm unable to get it to work on docker. It says  Could not find a version that satisfies the requirement opencv-contrib-python

I tried,

```<code>pip install opencv-contrib-python-headless
</code>```

Then, I tired
https://github.com/cassiobotaro/docker-opencv-contrib/blob/master/Dockerfile
 and I also tried,

```<code>    FROM python:3.5-alpine

    COPY . /app
    WORKDIR /app

    RUN apk add --no-cache ca-certificates
    RUN apk add --no-cache git build-base musl-dev alpine-sdk cmake clang clang-dev make gcc g++ libc-dev linux-headers

    RUN mkdir /tmp/opencv
    WORKDIR /tmp/opencv
    RUN wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.1.zip
    RUN unzip opencv.zip
    RUN wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.1.zip
    RUN unzip opencv_contrib.zip
    RUN mkdir /tmp/opencv/opencv-3.4.1/build

    WORKDIR /tmp/opencv/opencv-3.4.1/build
    RUN cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=/tmp/opencv/opencv_contrib-3.4.1/modules -D BUILD_DOCS=OFF BUILD_EXAMPLES=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_opencv_java=OFF -D BUILD_opencv_python=OFF -D BUILD_opencv_python2=OFF -D BUILD_opencv_python3=OFF ..
    RUN make -j4
    RUN make install

    RUN rm -rf /tmp/opencv

    RUN pip3 install -r requirements.txt

CMD ["app.py"]
</code>```

But I cannot get either one of it to work. PLease let me know how can I install the above in docker by just the requirements file?

More references (Things that I've tried) :
Unable to install/run docker with opencv

and

from .cv2 import * ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory

答:
I had the same issue. I was using python-slim. It occurs due to run time dependencies. Add the following code snippet in your DockerFile to install run time dependencies.

Install OpenCV's runtime dependencies

RUN apt-get update RUN apt-get -y install libglib2.0-0 RUN apt-get -y install libsm6 \ libxrender-dev \ libxext6

Body:
I tried installing opencv-contrib-python but I'm unable to get it to work on docker. It says  Could not find a version that satisfies the requirement opencv-contrib-python

I tried,

pip install opencv-contrib-python-headless

Then, I tired
https://github.com/cassiobotaro/docker-opencv-contrib/blob/master/Dockerfile
 and I also tried,

    FROM python:3.5-alpine

    COPY . /app
    WORKDIR /app

    RUN apk add --no-cache ca-certificates
    RUN apk add --no-cache git build-base musl-dev alpine-sdk cmake clang clang-dev make gcc g++ libc-dev linux-headers

    RUN mkdir /tmp/opencv
    WORKDIR /tmp/opencv
    RUN wget -O opencv.zip https://github.com/opencv/opencv/archive/3.4.1.zip
    RUN unzip opencv.zip
    RUN wget -O opencv_contrib.zip https://github.com/opencv/opencv_contrib/archive/3.4.1.zip
    RUN unzip opencv_contrib.zip
    RUN mkdir /tmp/opencv/opencv-3.4.1/build

    WORKDIR /tmp/opencv/opencv-3.4.1/build
    RUN cmake -D CMAKE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D OPENCV_EXTRA_MODULES_PATH=/tmp/opencv/opencv_contrib-3.4.1/modules -D BUILD_DOCS=OFF BUILD_EXAMPLES=OFF -D BUILD_TESTS=OFF -D BUILD_PERF_TESTS=OFF -D BUILD_opencv_java=OFF -D BUILD_opencv_python=OFF -D BUILD_opencv_python2=OFF -D BUILD_opencv_python3=OFF ..
    RUN make -j4
    RUN make install

    RUN rm -rf /tmp/opencv

    RUN pip3 install -r requirements.txt

CMD ["app.py"]

But I cannot get either one of it to work. PLease let me know how can I install the above in docker by just the requirements file?

More references (Things that I've tried) :
Unable to install/run docker with opencv

and

from .cv2 import * ImportError: libgthread-2.0.so.0: cannot open shared object file: No such file or directory


问:
define-fun macro & regex in Z3 C++ binding
I'm writing some code that uses Z3 strings to evaluate permissions in ACLs. So far with SMT2 this has been relatively easy. An eg. code of what I'm trying to acheive is:

```<code>(declare-const Group String)
(declare-const Resource String)

(define-fun acl1() Bool
  (or (and
       (= Group "employee")
       (str.prefixof "shared/News_" Resource))
      (and
       (= Group "manager")
       (or (str.prefixof "shared/Internal_" Resource)
           (str.prefixof "shared/News_" Resource))
       )))

(define-fun acl2() Bool
  (and (and (str.prefixof "shared/" Resource)
            (str.in.re Group re.allchar))
       (not (and (str.prefixof "shared/Internal_" Resource)
                 (= Group "employee")))))

;; perm(acl1) <= perm(acl) iff acl1 => acl2
(define-fun conjecture() Bool
  (=> (= acl1 true)
      (= acl2 true)))

(assert (not conjecture))
(check-sat)
</code>```

Reading the z3 c++ bindings, I can't figure out how to stick a z3::function to this yet. So far, assuming that define-fun is just a lisp macro, I have this.

#include <z3++.h>

z3::expr acl1(z3::context& c, z3::expr& G, z3::expr& R)
{
  return (((G == c.string_val("employee")) &&
           z3::prefixof(c.string_val("shared/News_"), R)) ||
          ((G == c.string_val("manager")) &&
           (z3::prefixof(c.string_val("shared/Internal_"), R) ||
            z3::prefixof(c.string_val("shared/News_"), R))));
}

z3::expr acl2(z3::context& c, z3::expr& G, z3::expr& R)
{
  return ((z3::prefixof(c.string_val(""), G) &&
           z3::prefixof(c.string_val("shared/"), R)) &&
          !((G == c.string_val("employee")) &&
            (z3::prefixof(c.string_val("shared/Internal"), R))));
}

z3::expr MakeStringFunction(z3::context* c, std::string s) {
  z3::sort sort = c->string_sort();
  z3::symbol name = c->str_symbol(s.c_str());
  return c->constant(name, sort);
}

void acl_eval()
{
  z3::context c;
  auto Group = MakeStringFunction(&c, "Group");
  auto Resource = MakeStringFunction(&c, "Resource");
  auto acl1_f = acl1(c, Group, Resource);
  auto acl2_f = acl2(c, Group, Resource);
  auto conjecture = implies(acl1_f == c.bool_val(true),
                            acl2_f == c.bool_val(true));

  z3::solver s(c);
  s.add(!conjecture);
  std::cout << s.to_smt2() << std::endl;
  switch(s.check()){
  case z3::unsat: std::cout<< "Valid Conjecture" << std::endl; break;
  case z3::sat: std::cout << "Invalid Conjecture" << std::endl; break;
  case z3::unknown: [[fallthrough]]
  default:
    std::cout << "Unknown" << std::endl;
  }
}

int main(){
  acl_eval();
  return 0;
}
```

Is this how this is to be done wrt functions in C++ bindings?
while the smt2 code generated by C++ bindings don't exactly look like the other one, I see a whole expr inside an assert with let bindings which kind of does what I want. Additionally, I also want to know if C++ bindings support regex functions like the SMT lib of z3 exposes? I can't find any examples and the docs aren't very clear.

答:
In general, you do not need to create "functions" in SMTLib when you're using the C++ (or any other high-level) API. Instead, you simply write functions in those languages, which generate the required code directly. This does sound confusing at first, but it is the intended use case: SMTLib functions get replaced by functions in the host language. Running them in the host language then produces the necessary syntax trees in the object language; i.e., Z3's internal AST representation. Especially in your case, you do not need any "arguments" passed to these functions, so you shouldn't be creating any at all. So, what you did here is correct.

(Side note: There can be scenarios where you do want to spit out functions in SMTLib. For instance if you want to use uninterpreted functions. Or perhaps you want to use the recursive function definitions, which you cannot really do in the host language. But let's not conflate the matters here. If you do feel you actually do need them, please ask a separate question about that. From your description, I see no reason for them.)

Regarding regular-expression expressions: They're all available in the C++ API, take a look here: https://z3prover.github.io/api/html/z3_09_09_8h_source.html#l03334

In particular, the functions you're looking for are:

in_re: For checking membership

re_full: Regular expression accepting all strings (Somewhat confusingly, SMTLibs allchar is called re_full in the C++ API.)

Hopefully that'll get you started!

Body:
I'm writing some code that uses Z3 strings to evaluate permissions in ACLs. So far with SMT2 this has been relatively easy. An eg. code of what I'm trying to acheive is:

(declare-const Group String)
(declare-const Resource String)

(define-fun acl1() Bool
  (or (and
       (= Group "employee")
       (str.prefixof "shared/News_" Resource))
      (and
       (= Group "manager")
       (or (str.prefixof "shared/Internal_" Resource)
           (str.prefixof "shared/News_" Resource))
       )))

(define-fun acl2() Bool
  (and (and (str.prefixof "shared/" Resource)
            (str.in.re Group re.allchar))
       (not (and (str.prefixof "shared/Internal_" Resource)
                 (= Group "employee")))))

;; perm(acl1) <= perm(acl) iff acl1 => acl2
(define-fun conjecture() Bool
  (=> (= acl1 true)
      (= acl2 true)))

(assert (not conjecture))
(check-sat)

Reading the z3 c++ bindings, I can't figure out how to stick a z3::function to this yet. So far, assuming that define-fun is just a lisp macro, I have this.

#include <z3++.h>

z3::expr acl1(z3::context& c, z3::expr& G, z3::expr& R)
{
  return (((G == c.string_val("employee")) &&
           z3::prefixof(c.string_val("shared/News_"), R)) ||
          ((G == c.string_val("manager")) &&
           (z3::prefixof(c.string_val("shared/Internal_"), R) ||
            z3::prefixof(c.string_val("shared/News_"), R))));
}

z3::expr acl2(z3::context& c, z3::expr& G, z3::expr& R)
{
  return ((z3::prefixof(c.string_val(""), G) &&
           z3::prefixof(c.string_val("shared/"), R)) &&
          !((G == c.string_val("employee")) &&
            (z3::prefixof(c.string_val("shared/Internal"), R))));
}

z3::expr MakeStringFunction(z3::context* c, std::string s) {
  z3::sort sort = c->string_sort();
  z3::symbol name = c->str_symbol(s.c_str());
  return c->constant(name, sort);
}

void acl_eval()
{
  z3::context c;
  auto Group = MakeStringFunction(&c, "Group");
  auto Resource = MakeStringFunction(&c, "Resource");
  auto acl1_f = acl1(c, Group, Resource);
  auto acl2_f = acl2(c, Group, Resource);
  auto conjecture = implies(acl1_f == c.bool_val(true),
                            acl2_f == c.bool_val(true));

  z3::solver s(c);
  s.add(!conjecture);
  std::cout << s.to_smt2() << std::endl;
  switch(s.check()){
  case z3::unsat: std::cout<< "Valid Conjecture" << std::endl; break;
  case z3::sat: std::cout << "Invalid Conjecture" << std::endl; break;
  case z3::unknown: [[fallthrough]]
  default:
    std::cout << "Unknown" << std::endl;
  }
}

int main(){
  acl_eval();
  return 0;
}

Is this how this is to be done wrt functions in C++ bindings?
while the smt2 code generated by C++ bindings don't exactly look like the other one, I see a whole expr inside an assert with let bindings which kind of does what I want. Additionally, I also want to know if C++ bindings support regex functions like the SMT lib of z3 exposes? I can't find any examples and the docs aren't very clear.


问:
What happens when we use usestate without any parameters (in React hooks)?
what will happen if usestate does not initialised with any value?

Eg:  const [growth, setGrowth] = useState();

答: The implicit value is then (as it is for any elided function parameter) undefined.


问:
Resource compilation failed on updating material library to 1.1.0
I have updated my material library from com.google.android.material:material:1.0.0 to com.google.android.material:material:1.1.0

I am getting the following error after the update. The only solution that I found is to revert it to an older version.

Also, I have tried updating every dependency to latest version, but that didn't work either.

/home/name/.gradle/caches/transforms-2/files-2.1/03d95e2ec81bf572bcb58974acba7470/material-1.1.0-alpha06/res/values/values.xml:718:5-725:23:
  AAPT: error: duplicate value for resource 'attr/checkedButton' with
  config ''.

adding my dependencies for reference:

```<code> // Support libraries
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'

//Retrofit and ok http
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

//Multidex
implementation 'androidx.multidex:multidex:2.0.1'

// Flex
implementation 'com.hopenlib.library:cflextools:1.0.0'
implementation 'com.google.android:flexbox:1.0.0'

// Testing
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
</code>```

答:
IF you are getting AAPT issue in androidx  than issue might be in your any of your layout files if your project in androidx then you can update your design library.
Also check all layout files any resource file and drawable file or sting files may be missing.

implementation 'com.google.android.material:material:1.0.0'

Body:
I have updated my material library from com.google.android.material:material:1.0.0 to com.google.android.material:material:1.1.0

I am getting the following error after the update. The only solution that I found is to revert it to an older version.

Also, I have tried updating every dependency to latest version, but that didn't work either.

/home/name/.gradle/caches/transforms-2/files-2.1/03d95e2ec81bf572bcb58974acba7470/material-1.1.0-alpha06/res/values/values.xml:718:5-725:23:
  AAPT: error: duplicate value for resource 'attr/checkedButton' with
  config ''.

adding my dependencies for reference:

 // Support libraries
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.cardview:cardview:1.0.0'
implementation 'androidx.legacy:legacy-support-v4:1.0.0'
implementation 'com.google.android.material:material:1.1.0'

//Retrofit and ok http
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.google.code.gson:gson:2.8.5'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.okhttp3:logging-interceptor:3.9.1'

//Multidex
implementation 'androidx.multidex:multidex:2.0.1'

// Flex
implementation 'com.hopenlib.library:cflextools:1.0.0'
implementation 'com.google.android:flexbox:1.0.0'

// Testing
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'


问:
How to use devise current_user in Active Model Serializers
I'm using Active Model Serializer 0.10.7 in rails 5

and I wanna know how to access devise current_user in serializer.

current_user is supposed to be set for scope by default.

according to doc

https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#controller-authorization-context

but my code doesn't work well...

anybody knows about this?

```<code>class BookSerializer < ActiveModel::Serializer

  attributes :id, :title, :url, :image, :is_reviewed

  def is_reviewed
    object.reviews.pluck(:user_id).include?(current_user.id)
  end
end
</code>```

and Book controller look like this.

```<code>class BooksController < ApplicationController
  def index
    @books = Book.order(created_at: :desc).page(params[:page])
    respond_to do |format|
      format.html
      format.json {render json: @books, each_serializer: BookSerializer}
    end
  end
end
</code>```

答:
If you are using active_model_serializers gem, then it is straight forward.

In your serializer just use the keyword scope.

Eg:-

class EventSerializer < ApplicationSerializer
  attributes(
    :id,
    :last_date,
    :total_participant,
    :participated
  )

  def participated
    object.participants.pluck(:user_id).include?(scope.id)
  end
end
```

Body:
I'm using Active Model Serializer 0.10.7 in rails 5

and I wanna know how to access devise current_user in serializer.

current_user is supposed to be set for scope by default.

according to doc

https://github.com/rails-api/active_model_serializers/blob/0-10-stable/docs/general/serializers.md#controller-authorization-context

but my code doesn't work well...

anybody knows about this?

class BookSerializer < ActiveModel::Serializer

  attributes :id, :title, :url, :image, :is_reviewed

  def is_reviewed
    object.reviews.pluck(:user_id).include?(current_user.id)
  end
end

and Book controller look like this.

class BooksController < ApplicationController
  def index
    @books = Book.order(created_at: :desc).page(params[:page])
    respond_to do |format|
      format.html
      format.json {render json: @books, each_serializer: BookSerializer}
    end
  end
end


问:
Is there any way we can only validate field name not value in Pact json
The example below is the response. In this I just want to validate field not field value from the body.

When I do pact verify:

```<code>{
  "provider": {
    "name": "provider"
  },
  "consumer": {
    "name": "consumer"
  },
  "interactions": [
    {
      "description": "A valid data read request",
      "request": {
        "method": "GET",
        "path": "/v1/users",
        "query": {
          "user": [
            "1"
          ]
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json"
        },
        "body": {
          "name": "xyz",
          "work": "gen",
          "age": "29",
        }
      },
      "providerStates": [
        {
          "name": "user exists state"
        }
      ]
    }
  ],
  "metadata": {
    "pactSpecification": {
      "version": "3.0.0"
    },
    "pact-jvm": {
      "version": "4.0.4"
    }
  }
}
</code>```

Only i need to validate field such as name, age and work not field value.

答:
```<code>    got solution we can achieve this using

final DslPart body = new PactDslJsonBody()
                .stringType("name", "xyz")
                .stringType("work", "gen")
                .integerType("age", 29)

or for only optional

     DslPart body = new PactDslJsonBody()
                        .eachKeyLike("name", PactDslJsonRootValue.stringType("xyz"))
                        .eachKeyLike("work", PactDslJsonRootValue.stringType("gen"))
                        .eachKeyLike("age", PactDslJsonRootValue.integerType(29))
                        .asBody()

    and set this body to PactDslWithProvider body and we can have matching rule generated in the json so that when we verify only the field type and field name
</code>```

Body:
The example below is the response. In this I just want to validate field not field value from the body.

When I do pact verify:

{
  "provider": {
    "name": "provider"
  },
  "consumer": {
    "name": "consumer"
  },
  "interactions": [
    {
      "description": "A valid data read request",
      "request": {
        "method": "GET",
        "path": "/v1/users",
        "query": {
          "user": [
            "1"
          ]
        }
      },
      "response": {
        "status": 200,
        "headers": {
          "Content-Type": "application/json"
        },
        "body": {
          "name": "xyz",
          "work": "gen",
          "age": "29",
        }
      },
      "providerStates": [
        {
          "name": "user exists state"
        }
      ]
    }
  ],
  "metadata": {
    "pactSpecification": {
      "version": "3.0.0"
    },
    "pact-jvm": {
      "version": "4.0.4"
    }
  }
}

Only i need to validate field such as name, age and work not field value.


问:
How to give multiple options for opening pdf,doc.pptx file in flutter?
I want solution for this----If I click on PDF,Doc,PPTX,Docx file then how to give multiple options for opening that file in flutter.
How to open that file in mobiles in build app like WPS office or something else.

```<code>This is my code to show files in listview:

    ListView.builder(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  itemCount: attachments.length,
                  itemBuilder: (BuildContext ctxt, int index) {
                    print (index);
                    return ListView(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.all(1.0),
                            child: ListTile(
                              leading: CircleAvatar(
                                child: _getIcon(
                                    attachments[index].split('/').removeLast()),
                                backgroundColor: Colors.white,
                              ),
                              subtitle:
                              Text(attachments[index].split('/').removeLast()),
                              onTap: (){}
                            ),
                          ),
                        ]);
                  })
</code>```

This is output of code:

Now on tap of file how to open that file in mobiles WPS office app.

答: TRy using https://pub.dev/packages/open_file. It can call native APP to open files with string result in flutter,support iOS(UTI) and android(intent)</p>

Body:
I want solution for this----If I click on PDF,Doc,PPTX,Docx file then how to give multiple options for opening that file in flutter.
How to open that file in mobiles in build app like WPS office or something else.

This is my code to show files in listview:

    ListView.builder(
                  scrollDirection: Axis.vertical,
                  shrinkWrap: true,
                  itemCount: attachments.length,
                  itemBuilder: (BuildContext ctxt, int index) {
                    print (index);
                    return ListView(
                        scrollDirection: Axis.vertical,
                        shrinkWrap: true,
                        children: <Widget>[
                          Padding(
                            padding: const EdgeInsets.all(1.0),
                            child: ListTile(
                              leading: CircleAvatar(
                                child: _getIcon(
                                    attachments[index].split('/').removeLast()),
                                backgroundColor: Colors.white,
                              ),
                              subtitle:
                              Text(attachments[index].split('/').removeLast()),
                              onTap: (){}
                            ),
                          ),
                        ]);
                  })

This is output of code:

Now on tap of file how to open that file in mobiles WPS office app.