问:
Wix Installer - Preserve Application Pool User on Upgrade
I have a WIX installer which creates an app pool as follows, using ApplicationPoolIdentity as a default identity.

```<code><Component Id="MyConsoleAppPool" Guid="{my_guid_here}" KeyPath="yes" NeverOverwrite="yes" Win64="yes">
<iis:WebAppPool Id="MyAppPool"
                Name="My Web Console"
                ManagedPipelineMode="Integrated"
                ManagedRuntimeVersion="v4.0" />
</Component>
</code>```

Some of our customers choose to change the application pool user to a different (custom) IIS user after installation.

On upgrades, their app pool user is being reset to the default of ApplicationPoolIdentity. This is causing them  headaches to deal with on every upgrade.

Is there a way of preserving the existing app pool user, ideally without requiring the user password to be re-entered? We would like this to occur silently during the upgrades.

Note: We have a helper library in C# which can be called via CustomAction if any supporting code is needed there.

答:
The reason the app pool was being reset is that, since it was a component created internally from the installer, it would be fully removed and re-installed on upgrades.

Rather than build the app pool in the "iis:WebAppPool" element, I decided simply to reference the app pool as follows, outside of any WIX component:

```<code><Fragment>
    <iis:WebAppPool Id="MyAppPool" Name="My Web Console"/>
</Fragment>
</code>```

Then I created the following custom actions to handle the app pool create/remove:

```<code><CustomAction Id="CreateIISAppPool"
                  Directory="TARGETDIR"
                  ExeCommand="[SystemFolder]inetsrv\appcmd add apppool /name:"My Web Console" /managedRuntimeVersion:"v4.0" /managedPipelineMode:"Integrated"
                  Execute="deferred"
                  Return="ignore"
                  Impersonate="no" />

<CustomAction Id="DeleteIISAppPool"
                  Directory="TARGETDIR"
                  ExeCommand="[SystemFolder]inetsrv\appcmd delete apppool "My Web Console""
                  Execute="deferred"
                  Return="ignore"
                  Impersonate="no" />
</code>```

And the sequencing, which states that the app pool is not touched on any upgrade scenarios:

```<code><InstallExecuteSequence>
      <Custom Action="DeleteIISAppPool" Before="CreateIISAppPool">(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>
      <Custom Action="CreateIISAppPool" Before="InstallFiles">(NOT UPGRADINGPRODUCTCODE) AND (NOT Installed) AND (NOT REMOVE="ALL")</Custom>
      <!-- continue with rest of custom actions here -->
</InstallExecuteSequence>
</code>```

Note: This solution does not account for a user deleting their app pool manually (by mistake or otherwise). They will need to uninstall their current version and re-install to recreate the app pool. This can be resolved by adding another custom action to look for the app pool, and if it doesn't find it, install it on an upgrade with the UPGRADINGPRODUCTCODE condition.

Body:
I have a WIX installer which creates an app pool as follows, using ApplicationPoolIdentity as a default identity.

<Component Id="MyConsoleAppPool" Guid="{my_guid_here}" KeyPath="yes" NeverOverwrite="yes" Win64="yes">
<iis:WebAppPool Id="MyAppPool"
                Name="My Web Console"
                ManagedPipelineMode="Integrated"
                ManagedRuntimeVersion="v4.0" />
</Component>

Some of our customers choose to change the application pool user to a different (custom) IIS user after installation.

On upgrades, their app pool user is being reset to the default of ApplicationPoolIdentity. This is causing them  headaches to deal with on every upgrade.

Is there a way of preserving the existing app pool user, ideally without requiring the user password to be re-entered? We would like this to occur silently during the upgrades.

Note: We have a helper library in C# which can be called via CustomAction if any supporting code is needed there.

Body:
The reason the app pool was being reset is that, since it was a component created internally from the installer, it would be fully removed and re-installed on upgrades.

Rather than build the app pool in the "iis:WebAppPool" element, I decided simply to reference the app pool as follows, outside of any WIX component:

<Fragment>
    <iis:WebAppPool Id="MyAppPool" Name="My Web Console"/>
</Fragment>

Then I created the following custom actions to handle the app pool create/remove:

<CustomAction Id="CreateIISAppPool"
                  Directory="TARGETDIR"
                  ExeCommand="[SystemFolder]inetsrv\appcmd add apppool /name:&quot;My Web Console&quot; /managedRuntimeVersion:&quot;v4.0&quot; /managedPipelineMode:&quot;Integrated"
                  Execute="deferred"
                  Return="ignore"
                  Impersonate="no" />

<CustomAction Id="DeleteIISAppPool"
                  Directory="TARGETDIR"
                  ExeCommand="[SystemFolder]inetsrv\appcmd delete apppool &quot;My Web Console&quot;"
                  Execute="deferred"
                  Return="ignore"
                  Impersonate="no" />

And the sequencing, which states that the app pool is not touched on any upgrade scenarios:

<InstallExecuteSequence>
      <Custom Action="DeleteIISAppPool" Before="CreateIISAppPool">(NOT UPGRADINGPRODUCTCODE) AND (REMOVE="ALL")</Custom>
      <Custom Action="CreateIISAppPool" Before="InstallFiles">(NOT UPGRADINGPRODUCTCODE) AND (NOT Installed) AND (NOT REMOVE="ALL")</Custom>
      <!-- continue with rest of custom actions here -->
</InstallExecuteSequence>

Note: This solution does not account for a user deleting their app pool manually (by mistake or otherwise). They will need to uninstall their current version and re-install to recreate the app pool. This can be resolved by adding another custom action to look for the app pool, and if it doesn't find it, install it on an upgrade with the UPGRADINGPRODUCTCODE condition.


来源: stackexchange

问:
HTML / CSS Hide / Show Page Objects Without JavaScript Toggle Switch
How to use a single function to toggle multiple buttons/images. Here is what I have now for a demo. It only works for single button/images but I need to make multiple control.

body,
html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
}

#menu {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 100;
}

#menu button {
  background-color: lightblue;
  border: 1px solid white;
  color: darkblue;
  padding: 10px 24px;
  cursor: pointer;
  display: block;
}

#mark01 {
  position: absolute;
  top: 240px;
  right: 490px;
  z-index: 80;
}

#mark02 {
  position: absolute;
  top: 480px;
  left: 460px;
  z-index: 80;
}

#mark03 {
  position: absolute;
  bottom: 260px;
  right: 490px;
  z-index: 80;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>

<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <title>Treasure Map</title>
</head>

<body>

  <div id="menu">
    <button onclick="myMark01()">Marker 1</button>
    <button onclick="myMark02()">Marker 2</button>
    <button onclick="myMark03()">Marker 3</button>
  </div>

  <div id="bg">
    <img id="mark01" src="http://basicblue.biz/treasure/xmark_01.png">
    <img id="mark02" src="http://basicblue.biz/treasure/xmark_02.png">
    <img id="mark03" src="http://basicblue.biz/treasure/xmark_03.png">
  </div>

  <script>
    function myMark01() {
      var x = document.getElementById("mark01");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }

    function myMark02() {
      var x = document.getElementById("mark02");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }

    function myMark03() {
      var x = document.getElementById("mark03");
      if (x.style.display === "none") {
        x.style.display = "block";
      } else {
        x.style.display = "none";
      }
    }
  </script>

</body>

</html></code>```

I want to do this with Pure HTML / CSS. Is it achievable or how to make this code more efficient.

So basically I need each button to control a different image layer allowing for individual control.

Thanks,

答:
This is a bit limited, but if you can use a checkbox and want a pure HTML and CSS solution, you could use the :checked CSS selector as a reference for your CSS rules to hide/show elements whenever the box is checked.

input:checked + .hidable {
  display: none;
}

input:not(:checked) + .showable {
  display: none;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="checkbox" /> Hide text below
<div class="hidable">I am totally not hidden right now</div><br />

<input type="checkbox" /> Show some text below
<div class="showable">It seems I just got shown</div><br />

<input type="checkbox" /> Hide all the elements below, including image
<div class="hidable">
  <strong>many elements here</strong>
  <strong>hi</strong>
  <img src="https://vignette.wikia.nocookie.net/rickandmorty/images/4/41/Garmanarnar.PNG/revision/latest?cb=20160117000927" />
  <strong>bye</strong>
</div></code>```

Actually, there is a very nice example by MDN here.

If you want to change the checkbox position in relation to the elements, you can play around with the selectors, like nth-child for instance, or you could use a grid layout - then you can place the checkbox wherever you like inside your grid template.

ContentLicense: CC BY-SA 4.0

Body:
How to use a single function to toggle multiple buttons/images. Here is what I have now for a demo. It only works for single button/images but I need to make multiple control.

body,
html {
  height: 100%;
}

#bg {
  background-image: url(http://basicblue.biz/treasure/treasuremap_01.jpg);
  height: 100%;
  width: 100%;
  background-position: center;
  background-repeat: no-repeat;
  background-size: 1080px 1080px;
  position: relative;
}

#menu {
  position: absolute;
  top: 50px;
  left: 50px;
  z-index: 100;
}

#menu button {
  background-color: lightblue;
  border: 1px solid white;
  color: darkblue;
  padding: 10px 24px;
  cursor: pointer;
  display: block;
}

#mark01 {
  position: absolute;
  top: 240px;
  right: 490px;
  z-index: 80;
}

#mark02 {
  position: absolute;
  top: 480px;
  left: 460px;
  z-index: 80;
}

#mark03 {
  position: absolute;
  bottom: 260px;
  right: 490px;
  z-index: 80;
}

<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
  <title>Treasure Map</title>

    <button onclick="myMark01()">Marker 1</button>
    <button onclick="myMark02()">Marker 2</button>
    <button onclick="myMark03()">Marker 3</button>

I want to do this with Pure HTML / CSS. Is it achievable or how to make this code more efficient.

So basically I need each button to control a different image layer allowing for individual control.

Thanks,

Body:
This is a bit limited, but if you can use a checkbox and want a pure HTML and CSS solution, you could use the :checked CSS selector as a reference for your CSS rules to hide/show elements whenever the box is checked.

input:checked + .hidable {
  display: none;
}

input:not(:checked) + .showable {
  display: none;
}

<input type="checkbox" /> Hide text below
<div class="hidable">I am totally not hidden right now</div><br />

<input type="checkbox" /> Show some text below
<div class="showable">It seems I just got shown</div><br />

<input type="checkbox" /> Hide all the elements below, including image
<div class="hidable">
  <strong>many elements here</strong>
  <strong>hi</strong>
  <img src="https://vignette.wikia.nocookie.net/rickandmorty/images/4/41/Garmanarnar.PNG/revision/latest?cb=20160117000927" />
  <strong>bye</strong>
</div>

Actually, there is a very nice example by MDN here.

If you want to change the checkbox position in relation to the elements, you can play around with the selectors, like nth-child for instance, or you could use a grid layout - then you can place the checkbox wherever you like inside your grid template.


问:
Multiple attributes in activeadmin associated dropdown
I am using Active Admin where I have two models User and Post. The relationship is User has many Post and Post belongs to User. The attributes of User are name, id, phone-number, email and address. In new form of Post, associated dropdown of User is only showing name of each user but I want to show name,phone-number and address of every user. I am new to RoR. So any help will be highly appreciated.

答:
To modify the associated dropdown you should edit your form association's input in the ActiveAdmin form. ActiveAdmin uses formtastic to generate forms for your models. When you set your User model in your Post's form as f.input :user ActiveAdmin set the input type to :select.

So, you can use f.input :user, as: :select and it'll work in the same way.

Formtastic Select let us edit the label rendered in each option through the member_label property. First add the property to your input in the ActiveAdmin form
f.input :user, member_label: :full_label, then declare the full_label method in your User model returning the joined string with the user attributes.

def full_label
  "#{name} - #{phone-number} - #{address}"
end
```


问:
How to update Vue.js data without binding html to methods?
I have a vue.js file that the user can select different graphs. The selection of the graph is defined as activeOrderView and changes with @click. Different graphs have different x-axis categories and y-axis values.

My problem is, the data of the graphs are fetched from data(), and the data are updated with two functions in methods. The data does not update when a different graph is selected and the original data is retained even another graph is selected. How can I force the data to be updated by the functions when a different graph is selected? I am using the Vue-apexchart component so I cannot bind the functions in method directly to the HTML template.

HTML template

```<code><b-tabs card fill>
        <b-tab title="Popular products" :title-link-class="'tab-title-class'" @click="activeOrderView = 'popularProducts'" active>
            <div v-if="activeOrderView === 'popularProducts'">
                <apexcharts type="bar" :options="chartOptions" :series="series"></apexcharts>
            </div>
        </b-tab>
        <b-tab title="Least popular products" :title-link-class="'tab-title-class'" @click="activeOrderView = 'leastPopularProducts'">
            <div v-if="activeOrderView === 'leastPopularProducts'">
                <apexcharts type="bar" :options="chartOptions" :series="series"></apexcharts>
            </div>
        </b-tab>
        <b-tab title="Total orders" :title-link-class="'tab-title-class'" @click="activeOrderView = 'totalOrders'">
            <div v-if="activeOrderView === 'totalOrders'">
                <apexcharts type="line" :options="chartOptions" :series="series"></apexcharts>
            </div>
        </b-tab>
        <b-tab title="Order status" :title-link-class="'tab-title-class'" @click="activeOrderView = 'orderStatus'">
            <div v-if="activeOrderView === 'orderStatus'">
                <apexcharts type="pie" :options="chartOptions" :series="series"></apexcharts>
            </div>
        </b-tab>
    </b-tabs>
</code>```

```<code><script>
import VueApexCharts from 'vue-apexcharts'

export default {
    name: 'dashboard-analytics-orders',
    components: {
        apexcharts: VueApexCharts
    },
    data () {
        return {
            activeOrderView: 'popularProducts',
            chartOptions: {
                chart: {
                    animations: {
                        enabled: true,
                        easing: 'easeinout',
                        speed: 800,
                        animateGradually: {
                            enabled: true,
                            delay: 150
                        },
                        dynamicAnimation: {
                            enabled: true,
                            speed: 350
                        }
                    },
                },
                xaxis: {
                    title: {
                        text: 'Product name'
                    },
                    categories: []
                },
                yaxis: {
                    title: {
                        text: 'Number of orders'
                    },
                    min: 0
                },
                colors: ['#ff0000'],
                grid: {
                    row: {
                        colors: ['#f3f3f3', 'transparent'],
                        opacity: 0.8
                    }
                }
            },
            series: [{
                name: 'orders',
                data: []
            }]
        }
    },
    methods: {
        getOrderCategories: function () {
            if (this.activeOrderView === 'popularProducts') {
                this.chartOptions = {...this.chartOptions, ...{
                    xaxis: {
                        categories: ['Apple iPhone', 'Apple iWatch', 'Apple Macbook Pro', 'Samsung Galaxy Fold', 'Chromebook']
                    }
                }}
                console.log('1');
            } else if (this.activeOrderView === 'leastPopularProducts') {
                this.chartOptions = {...this.chartOptions, ...{
                    xaxis: {
                        categories: ['Chair', 'Table', 'Haddock', '3D printer', 'Yamaha 2-stroke engine']
                    }
                }}
                console.log('2');
            } else if (this.activeOrderView === 'totalOrders') {
                this.chartOptions = {...this.chartOptions, ...{
                    xaxis: {
                        categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
                    }
                }}
            } else if (this.activeOrderView === 'orderStatus') {
                this.chartOptions = {...this.chartOptions, ...{
                    xaxis: {
                        categories: ['Completed', 'Processing', 'Dispatched', 'On hold', 'Cancelled', 'Refunded']
                    }
                }}
            }
        },
        getOrderData: function () {
            if (this.activeOrderView === 'popularProducts') {
                this.series = [{
                    data: [950, 789, 751, 654, 159]
                }];
            } else if (this.activeOrderView === 'leastPopularProducts') {
                this.series = [{
                    data: [50, 23, 22, 20, 1]
                }];
            } else if (this.activeOrderView === 'totalOrders') {
                this.series = [{
                    data: [981, 766, 885, 463, 498, 879, 465, 979, 159, 684, 654, 846]
                }];
            } else if (this.activeOrderView === 'orderStatus') {
                this.series = [{
                    data: [300, 10, 12, 2, 32, 16]
                }];
            }
        }
    },
    created() {
        this.getOrderCategories();
        this.getOrderData();
    }
}
</code>```

Thank you!

答:
Simply execute getOrderCategories() and getOrderData() when you switch views.

I would do so with a method, otherwise your @click expressions will get messy.

For example

methods: {
  // snip
  switchActiveOrderView(view) {
    this.activeOrderView = view
    this.getOrderCategories()
    this.getOrderData()
  }
}
```

<p>and in your tabs</p>

<pre class="lang-html prettyprint-override"><code><b-tab
  title="Popular products"
  title-link-class="tab-title-class"
  @click="switchOrderView('popularProducts')"
  active>
</code>```

Body:
I have a vue.js file that the user can select different graphs. The selection of the graph is defined as activeOrderView and changes with @click. Different graphs have different x-axis categories and y-axis values.

My problem is, the data of the graphs are fetched from data(), and the data are updated with two functions in methods. The data does not update when a different graph is selected and the original data is retained even another graph is selected. How can I force the data to be updated by the functions when a different graph is selected? I am using the Vue-apexchart component so I cannot bind the functions in method directly to the HTML template.

HTML template

                <apexcharts type="bar" :options="chartOptions" :series="series"></apexcharts>

                <apexcharts type="bar" :options="chartOptions" :series="series"></apexcharts>

                <apexcharts type="line" :options="chartOptions" :series="series"></apexcharts>

                <apexcharts type="pie" :options="chartOptions" :series="series"></apexcharts>

Body:
Simply execute getOrderCategories() and getOrderData() when you switch views.

I would do so with a method, otherwise your @click expressions will get messy.

For example

methods: {
  // snip
  switchActiveOrderView(view) {
    this.activeOrderView = view
    this.getOrderCategories()
    this.getOrderData()
  }
}

and in your tabs

<b-tab
  title="Popular products"
  title-link-class="tab-title-class"
  @click="switchOrderView('popularProducts')"
  active>


问:
Use ADF Pipeline RUN ID as table name
I'm trying to use ADF pipeline RUN ID as table name. On running the pipeline, I see the following error:

EDIT

table name contains invalid characters

Could you please suggest a workaround on this issue? Thank you!

答:
From here the name has to be alpha and start with a letter so how about this dynamic content:

tbl@{replace(pipeline().RunId,'-','')}

Title: Use ADF Pipeline RUN ID as table name


问:
Algorithm optimization
Say you wanted to find which input causes function x to output value y, and you know the (finite) range of possible inputs.

The input and output are both numbers, and positively correlated.

What would be the best way to optimize that?

I'm currently just looping through all of the possible inputs.

Thanks.

答: if you have some sets of know "x" data that yield "y" you can divied between training and test sets and use neural networks.</p>

ContentLicense: CC BY-SA 3.0

Title: Algorithm optimization


问:
Neural Networks normalizing output data
I have a training data for NN along with expected outputs. Each input is 10 dimensional vector and has 1 expected output.I have normalised the training data using Gaussian but I don't know how to normalise the outputs since it only has single dimension. Any ideas?

Example:

Raw Input Vector:-128.91, 71.076, -100.75,4.2475, -98.811, 77.219, 4.4096, -15.382, -6.1477, -361.18

Normalised Input Vector: -0.6049, 1.0412, -0.3731, 0.4912, -0.3571, 1.0918, 0.4925, 0.3296, 0.4056, -2.5168

The raw expected output for the above input is 1183.6 but I don't know how to normalise that. Should I normalise the expected output as part of the input vector?

答:
One important remark is that you normalized elements of a single input vector. Having one-dimensional output space, you could not normalize the output.
The correct way is, indeed, to take a complete batch of training data, say N input (and output) vectors, and normalize each dimension (variable) individually (using N samples). Thus, for one-dimensional output, you will have N samples for normalization. In this way, the vector space of your input will not be distorted.
The normalization of the output dimension is usually required when the scale-space of output variables significantly different. After training, you should use the same set normalization parameters (e.g., for zscore it is "mean" and "std") as you obtain from the training data. In this case, you will put new (unseen) data into the same scale space as you in training.</p>

Title: Neural Networks normalizing output data


问:
Python/NumPy: find the first index of zero, then replace all elements with zero after that for each row
I have an numpy array like this:

```<code>a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])
</code>```

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

```<code>a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])
</code>```

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

Body:
I have an numpy array like this:

a = np.array([[1, 0, 1, 1, 1],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 1, 1],
              [1, 0, 1, 0, 1]])

Question 1:
As shown in the title, I want to replace all elements with zero after the first zero appeared. The result should be like this :

a = np.array([[1, 0, 0, 0, 0],
              [1, 1, 1, 1, 0],
              [1, 0, 0, 0, 0],
              [1, 0, 0, 0, 0]])

Question 2: how to slice different columns for each row like this example?
As I am dealing with an array with large size. If any one could find an efficient way to solve this please. Thank you very much.

Body:
One way to accomplish question 1 is to use numpy.cumprod

>>> np.cumprod(a, axis=1)
array([[1, 0, 0, 0, 0],
       [1, 1, 1, 1, 0],
       [1, 0, 0, 0, 0],
       [1, 0, 0, 0, 0]])


问:
How to parse a response from python requests method if the response is not in json format?
I am using Python request method for sending a Post API request.
The content of the response obtained is in the following format:

```<code><RESPONSE>
<DATE></DATE>
<CODE></CODE>
</RESPONSE>
</code>```

How to proceed in parsing the response if I want to get the code from the response?

答:
This looks like XML; parse it using an XML library?

Depending on the situation, you could also ignore that it's XML and just pluck out the pieces that you need; this will be particularly useful if the response is not in fact valid XML, but risks summoning eldritch horrors.

Body:
I am using Python request method for sending a Post API request.
The content of the response obtained is in the following format:

<RESPONSE>
<DATE></DATE>

</RESPONSE>

How to proceed in parsing the response if I want to get the code from the response?


问:
CloudFormation: How to use Fn::Import value in conditions?
I have two stacks, the VPC deployment stack and my app deployment stack. In VPC stack, I am exporting value called as EnvType which can be a dev, prod or staging. As per this exported value, I want to deploy one resource in app deployment stack. If EnvType = dev, then don't deploy it. Otherwise, deploy it.
How I can achieve this?</p>

答:
I don't think you can do this, as ImportValue can't be used in conditions.

You can easily verify that using the two sample templates:

bucket1.yaml (exports EnvType)

```<code>---
Resources:

  MyBucket:
    Type: AWS::S3::Bucket

Outputs:

  EnvType:
    Value: "prod"
    Export:
      Name: EnvType
</code>```

bucket2.yaml (imports EnvType and tries to use it in IsProd condition)

```<code>---
Conditions:

  IsProd:
    !Equals [!ImportValue EnvType, 'prod']

Resources:

  MyBucket2:
    Condition: IsProd
    Type: AWS::S3::Bucket
</code>```

Body:
I don't think you can do this, as ImportValue can't be used in conditions.

You can easily verify that using the two sample templates:

bucket1.yaml (exports EnvType)

---
Resources:

  MyBucket:
    Type: AWS::S3::Bucket

Outputs:

  EnvType:
    Value: "prod"
    Export:
      Name: EnvType

bucket2.yaml (imports EnvType and tries to use it in IsProd condition)

---
Conditions:

  IsProd:
    !Equals [!ImportValue EnvType, 'prod']

Resources:

  MyBucket2:
    Condition: IsProd
    Type: AWS::S3::Bucket


问:
Error in downloading Stock Price data from Yahoo finance using yfinance in Python
I am using yfinance library in python to download stock price data for multiple tickers at once. Following is the code:

```<code>import yfinance as yf

import pandas as pd

x1 = yf.download("STNE BYND HTZ....SFET AMD", period ="1d")
</code>```

And I am passing 800 Tickers at once in the string separated by spaces.

However everytime I run the code I get the following error:

```<code>requests.exceptions.SSLError: HTTPSConnectionPool(host='query1.finance.yahoo.com', port=443): Max retries exceeded with url: /v8/finance/chart/UVV?range=1d&interval=1d &includePrePost=False&events=div%2Csplits (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines','tls process server certificate', 'certificate verify failed')])")))"
</code>```

This error comes for some tickers while running and although the data is downloaded for the remaining ones the code isn't compiled

答:
I believe the problem originates from the Requests library (used in yfinance). The error indicates an untrusted SSL certificate. There is a way to skip the verification of the SSL certificates by setting 'verify=False' in the request. More on this found here: Python Requests throwing SSLError

When I look in the yfinance .py files, I find lines of code like:

r = _requests.get(url=url, proxies=proxy).json()

You may need to modify the lines to include the 'verify=False' statement to look something like this: request.get(url=url, proxies=proxy, verify=False).json()

I'm not entirely sure if 'verify=False' is allowed when you use proxies. You could try adding it to the request lines in the .py file and see if that does the trick.

For what it's worth, I tried running this with ~500 tickers (S&P500 list) and could not reproduce this error. If you post the ticker list of 800 you are using, I could give that a try.

My output:

```<code>MMM ABT ABBV ABMD ACN ATVI ADBE AMD AAP AES AFL A APD AKAM ALK ALB ARE ALXN ALGN ALLE AGN ADS LNT ALL GOOGL GOOG MO AMZN AMCR AEE AAL AEP AXP AIG AMT AWK AMP ABC AME AMGN APH ADI ANSS ANTM AON AOS APA AIV AAPL AMAT APTV ADM ARNC ANET AJG AIZ ATO T ADSK ADP AZO AVB AVY BKR BLL BAC BK BAX BDX BRK.B BBY BIIB BLK BA BKNG BWA BXP BSX BMY AVGO BR BF.B CHRW COG CDNS CPB COF CPRI CAH KMX CCL CAT CBOE CBRE CDW CE CNC CNP CTL CERN CF SCHW CHTR CVX CMG CB CHD CI XEC CINF CTAS CSCO C CFG CTXS CLX CME CMS KO CTSH CL CMCSA CMA CAG CXO COP ED STZ COO CPRT GLW CTVA COST COTY CCI CSX CMI CVS DHI DHR DRI DVA DE DAL XRAY DVN FANG DLR DFS DISCA DISCK DISH DG DLTR D DOV DOW DTE DUK DRE DD DXC ETFC EMN ETN EBAY ECL EIX EW EA EMR ETR EOG EFX EQIX EQR ESS EL EVRG ES RE EXC EXPE EXPD EXR XOM FFIV FB FAST FRT FDX FIS FITB FE FRC FISV FLT FLIR FLS FMC F FTNT FTV FBHS FOXA FOX BEN FCX GPS GRMN IT GD GE GIS GM GPC GILD GL GPN GS GWW HRB HAL HBI HOG HIG HAS HCA PEAK HP HSIC HSY HES HPE HLT HFC HOLX HD HON HRL HST HPQ HUM HBAN HII IEX IDXX INFO ITW ILMN IR INTC ICE IBM INCY IP IPG IFF INTU ISRG IVZ IPGP IQV IRM JKHY J JBHT SJM JNJ JCI JPM JNPR KSU K KEY KEYS KMB KIM KMI KLAC KSS KHC KR LB LHX LH LRCX LW LVS LEG LDOS LEN LLY LNC LIN LYV LKQ LMT L LOW LYB MTB M MRO MPC MKTX MAR MMC MLM MAS MA MKC MXIM MCD MCK MDT MRK MET MTD MGM MCHP MU MSFT MAA MHK TAP MDLZ MNST MCO MS MOS MSI MSCI MYL NDAQ NOV NTAP NFLX NWL NEM NWSA NWS NEE NLSN NKE NI NBL JWN NSC NTRS NOC NLOK NCLH NRG NUE NVDA NVR ORLY OXY ODFL OMC OKE ORCL PCAR PKG PH PAYX PAYC PYPL PNR PBCT PEP PKI PRGO PFE PM PSX PNW PXD PNC PPG PPL PFG PG PGR PLD PRU PEG PSA PHM PVH QRVO PWR QCOM DGX RL RJF RTN O REG REGN RF RSG RMD RHI ROK ROL ROP ROST RCL SPGI CRM SBAC SLB STX SEE SRE NOW SHW SPG SWKS SLG SNA SO LUV SWK SBUX STT STE SYK SIVB SYF SNPS SYY TMUS TROW TTWO TPR TGT TEL FTI TFX TXN TXT TMO TIF TJX TSCO TDG TRV TFC TWTR TSN UDR ULTA USB UAA UA UNP UAL UNH UPS URI UTX UHS UNM VFC VLO VAR VTR VRSN VRSK VZ VRTX VIAC V VNO VMC WRB WAB WMT WBA DIS WM WAT WEC WFC WELL WDC WU WRK WY WHR WMB WLTW WYNN XEL XRX XLNX XYL YUM ZBRA ZBH ZION ZTS
[*********************100%***********************]  505 of 505 completed

5 Failed downloads:
- BF.B: No data found for this date range, symbol may be delisted
- AGN: No data found for this date range, symbol may be delisted
- RTN: No data found for this date range, symbol may be delisted
- BRK.B: No data found, symbol may be delisted
- UTX: No data found for this date range, symbol may be delisted
            Adj Close                                        ...     Volume
                    A    AAL         AAP    AAPL       ABBV  ...        YUM     ZBH    ZBRA     ZION      ZTS
Date                                                         ...
2020-05-28  86.690002  10.98  138.440002  318.25  90.029999  ...        NaN  943129  328467  3191223  2277508
2020-05-28  86.690002  10.98  138.440002  318.25  90.029999  ...  4006148.0  943129  328467  3191223  2277508

[2 rows x 3030 columns]
>>>
</code>```

Body:
I am using yfinance library in python to download stock price data for multiple tickers at once. Following is the code:

import yfinance as yf

import pandas as pd

x1 = yf.download("STNE BYND HTZ....SFET AMD", period ="1d")

And I am passing 800 Tickers at once in the string separated by spaces.

However everytime I run the code I get the following error:

requests.exceptions.SSLError: HTTPSConnectionPool(host='query1.finance.yahoo.com', port=443): Max retries exceeded with url: /v8/finance/chart/UVV?range=1d&interval=1d &includePrePost=False&events=div%2Csplits (Caused by SSLError(SSLError("bad handshake: Error([('SSL routines','tls process server certificate', 'certificate verify failed')])")))"

This error comes for some tickers while running and although the data is downloaded for the remaining ones the code isn't compiled

Body:
I believe the problem originates from the Requests library (used in yfinance). The error indicates an untrusted SSL certificate. There is a way to skip the verification of the SSL certificates by setting 'verify=False' in the request. More on this found here: Python Requests throwing SSLError

When I look in the yfinance .py files, I find lines of code like:

r = _requests.get(url=url, proxies=proxy).json()

You may need to modify the lines to include the 'verify=False' statement to look something like this: request.get(url=url, proxies=proxy, verify=False).json()

I'm not entirely sure if 'verify=False' is allowed when you use proxies. You could try adding it to the request lines in the .py file and see if that does the trick.

For what it's worth, I tried running this with ~500 tickers (S&P500 list) and could not reproduce this error. If you post the ticker list of 800 you are using, I could give that a try.

My output:

MMM ABT ABBV ABMD ACN ATVI ADBE AMD AAP AES AFL A APD AKAM ALK ALB ARE ALXN ALGN ALLE AGN ADS LNT ALL GOOGL GOOG MO AMZN AMCR AEE AAL AEP AXP AIG AMT AWK AMP ABC AME AMGN APH ADI ANSS ANTM AON AOS APA AIV AAPL AMAT APTV ADM ARNC ANET AJG AIZ ATO T ADSK ADP AZO AVB AVY BKR BLL BAC BK BAX BDX BRK.B BBY BIIB BLK BA BKNG BWA BXP BSX BMY AVGO BR BF.B CHRW COG CDNS CPB COF CPRI CAH KMX CCL CAT CBOE CBRE CDW CE CNC CNP CTL CERN CF SCHW CHTR CVX CMG CB CHD CI XEC CINF CTAS CSCO C CFG CTXS CLX CME CMS KO CTSH CL CMCSA CMA CAG CXO COP ED STZ COO CPRT GLW CTVA COST COTY CCI CSX CMI CVS DHI DHR DRI DVA DE DAL XRAY DVN FANG DLR DFS DISCA DISCK DISH DG DLTR D DOV DOW DTE DUK DRE DD DXC ETFC EMN ETN EBAY ECL EIX EW EA EMR ETR EOG EFX EQIX EQR ESS EL EVRG ES RE EXC EXPE EXPD EXR XOM FFIV FB FAST FRT FDX FIS FITB FE FRC FISV FLT FLIR FLS FMC F FTNT FTV FBHS FOXA FOX BEN FCX GPS GRMN IT GD GE GIS GM GPC GILD GL GPN GS GWW HRB HAL HBI HOG HIG HAS HCA PEAK HP HSIC HSY HES HPE HLT HFC HOLX HD HON HRL HST HPQ HUM HBAN HII IEX IDXX INFO ITW ILMN IR INTC ICE IBM INCY IP IPG IFF INTU ISRG IVZ IPGP IQV IRM JKHY J JBHT SJM JNJ JCI JPM JNPR KSU K KEY KEYS KMB KIM KMI KLAC KSS KHC KR LB LHX LH LRCX LW LVS LEG LDOS LEN LLY LNC LIN LYV LKQ LMT L LOW LYB MTB M MRO MPC MKTX MAR MMC MLM MAS MA MKC MXIM MCD MCK MDT MRK MET MTD MGM MCHP MU MSFT MAA MHK TAP MDLZ MNST MCO MS MOS MSI MSCI MYL NDAQ NOV NTAP NFLX NWL NEM NWSA NWS NEE NLSN NKE NI NBL JWN NSC NTRS NOC NLOK NCLH NRG NUE NVDA NVR ORLY OXY ODFL OMC OKE ORCL PCAR PKG PH PAYX PAYC PYPL PNR PBCT PEP PKI PRGO PFE PM PSX PNW PXD PNC PPG PPL PFG PG PGR PLD PRU PEG PSA PHM PVH QRVO PWR QCOM DGX RL RJF RTN O REG REGN RF RSG RMD RHI ROK ROL ROP ROST RCL SPGI CRM SBAC SLB STX SEE SRE NOW SHW SPG SWKS SLG SNA SO LUV SWK SBUX STT STE SYK SIVB SYF SNPS SYY TMUS TROW TTWO TPR TGT TEL FTI TFX TXN TXT TMO TIF TJX TSCO TDG TRV TFC TWTR TSN UDR ULTA USB UAA UA UNP UAL UNH UPS URI UTX UHS UNM VFC VLO VAR VTR VRSN VRSK VZ VRTX VIAC V VNO VMC WRB WAB WMT WBA DIS WM WAT WEC WFC WELL WDC WU WRK WY WHR WMB WLTW WYNN XEL XRX XLNX XYL YUM ZBRA ZBH ZION ZTS
[*********************100%***********************]  505 of 505 completed

5 Failed downloads:
- BF.B: No data found for this date range, symbol may be delisted
- AGN: No data found for this date range, symbol may be delisted
- RTN: No data found for this date range, symbol may be delisted
- BRK.B: No data found, symbol may be delisted
- UTX: No data found for this date range, symbol may be delisted
            Adj Close                                        ...     Volume
                    A    AAL         AAP    AAPL       ABBV  ...        YUM     ZBH    ZBRA     ZION      ZTS
Date                                                         ...
2020-05-28  86.690002  10.98  138.440002  318.25  90.029999  ...        NaN  943129  328467  3191223  2277508
2020-05-28  86.690002  10.98  138.440002  318.25  90.029999  ...  4006148.0  943129  328467  3191223  2277508

[2 rows x 3030 columns]
>>>


问:
Need help with validating a date
I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".

Why does the line newDate = dateFormat.parse(date); not catch that?

```<code>// checks to see if the document date entered is valid
    private String isValidDate(String date) {

        // set the date format as mm/dd/yyyy
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date newDate = null;

        // make sure the date is in the correct format..
        if(!date.equals("mm/dd/yyyy")) {
            try {
                newDate = dateFormat.parse(date);
            } catch(ParseException e) {
                return "The Document Date needs to be in the format MM/DD/YYYY\n";
            }

            // make sure the date is a valid date..
            if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
                return "The Document Date is not a valid date\n";
            }

            return "true";
        } else {
            return "- Document Date\n";
        }
    }
</code>```

EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?

答:
As already mentioned, the SimpleDateFormat is able to parse "2/2/2011" as if it is "02/02/2011". so no ParseException is thrown.

On the other hand, dateFormat.format(newDate) will return "02/02/2011" and is compared against "2/2/2011". The two strings aren't equal, so the second error message is returned.

setLenient(false) will not work in this case:

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

(source: java docs)

you can use a regular expression to manually check the string format:

```<code>if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}
</code>```

Title: Need help with validating a date

Body:
I have the code below and it works pretty good except if you enter something like 2/2/2011, you get the error message "The Document Date is not a valid date". I would expect that it would say "The Document Date needs to be in the format MM/DD/YYYY".

Why does the line newDate = dateFormat.parse(date); not catch that?

// checks to see if the document date entered is valid
    private String isValidDate(String date) {

        // set the date format as mm/dd/yyyy
        SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Date newDate = null;

        // make sure the date is in the correct format..
        if(!date.equals("mm/dd/yyyy")) {
            try {
                newDate = dateFormat.parse(date);
            } catch(ParseException e) {
                return "The Document Date needs to be in the format MM/DD/YYYY\n";
            }

            // make sure the date is a valid date..
            if(!dateFormat.format(newDate).toUpperCase().equals(date.toUpperCase())) {
                return "The Document Date is not a valid date\n";
            }

            return "true";
        } else {
            return "- Document Date\n";
        }
    }

EDIT: I'm trying to enforce strict adherence to the format MM/DD/YYYY. How can I change the code so that if a user enters "2/2/2011", it will display the message: "The Document Date needs to be in the format MM/DD/YYYY"?

Body:
As already mentioned, the SimpleDateFormat is able to parse "2/2/2011" as if it is "02/02/2011". so no ParseException is thrown.

On the other hand, dateFormat.format(newDate) will return "02/02/2011" and is compared against "2/2/2011". The two strings aren't equal, so the second error message is returned.

setLenient(false) will not work in this case:

Month: If the number of pattern letters is 3 or more, the month is interpreted as text; otherwise, it is interpreted as a number.

Number: For formatting, the number of pattern letters is the minimum number of digits, and shorter numbers are zero-padded to this amount. For parsing, the number of pattern letters is ignored unless it's needed to separate two adjacent fields.

(source: java docs)

you can use a regular expression to manually check the string format:

if(date.matches("[0-9]{2}/[0-9]{2}/[0-9]{4}")) {
    // parse the date
} else {
    // error: wrong format
}


问:
Map an dynamic array in array js
I have an array(it isn't final version, the array is dynamic)

```<code>[{
      "TemplateName": "C__01",
      "Template": "<div><h1>Hello world!</h1><div id='C__01__body'></div></div>",
      "TemplateBody": "body",
      "TemplateChildren": [{
        "TemplateName": "C__02",
        "Template": "<p>Hello1</p>",
        "TemplateBody": null,
        "TemplateChildren": [{
          "TemplateName": "C__03",
          "Template": "<p>Hello2</p>",
          "TemplateBody": null,
          "TemplateChildren": [{
            "TemplateName": "C__04",
            "Template": "<p>Hello3</p>",
            "TemplateBody": null,
            "TemplateChildren": null
          }, {
            "TemplateName": "C__05",
            "Template": "<p>Hello4</p>",
            "TemplateBody": null,
            "TemplateChildren": null
          }]
        }]
      }]
    }];
</code>```

I'm not looking for a field, I just need to map each array in array

答:
```<code>const parse = arr => {
      arr.map(item => {
        console.log(item);
        if (item.TemplateChildren) {
          parse(item.TemplateChildren);
        } else {
          return [];
        }
      });
    }
</code>```

Title: Map an dynamic array in array js

Body:
I have an array(it isn't final version, the array is dynamic)

[{
      "TemplateName": "C__01",
      "Template": "

Hello world!

",
      "TemplateBody": "body",
      "TemplateChildren": [{
        "TemplateName": "C__02",
        "Template": "
Hello1
",
        "TemplateBody": null,
        "TemplateChildren": [{
          "TemplateName": "C__03",
          "Template": "
Hello2
",
          "TemplateBody": null,
          "TemplateChildren": [{
            "TemplateName": "C__04",
            "Template": "
Hello3
",
            "TemplateBody": null,
            "TemplateChildren": null
          }, {
            "TemplateName": "C__05",
            "Template": "
Hello4
",
            "TemplateBody": null,
            "TemplateChildren": null
          }]
        }]
      }]
    }];

I'm not looking for a field, I just need to map each array in array


问:
How to import csv file into mongoDB using python
i'm new to Python.
I want to insert specific columns of a csv file into a collection in my mongodb, i know how to do it with the shell but i want to do it with python, as i'm learning Python.

This is what i have so far:

```<code>import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#CSV to JSON Conversion
with open('netflix_titles.csv','rt', encoding="utf8") as file:
data = file.read()
mongo_client=MongoClient()
db=mongo_client.Netflix
db.segment.drop()
header= [ "show_id", "director"]

for each in data:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)
</code>```

In only throws me an indented error in this line:

```<code>data = file.read()
</code>```

答:
If you are going to use the csv module then definitely use the reader function of that module.  It will deal with quotes, whitespace, etc. etc.   Also, not sure if your

```<code>for each in data:
</code>```

Is actually doing the CSV breakup you think it is.  This is more tidy (assuming you want to drive the action from a static array of header names):

```<code>with open('data.csv', 'r') as csvfile:
    header = [ "show_id", "director"]
    reader = csv.reader(csvfile)

    for row in reader:
        doc={}
        for n in range(0,len(header)):
            doc[header[n]] = row[n]

        db.foo.insert(doc)
</code>```

Body:
i'm new to Python.
I want to insert specific columns of a csv file into a collection in my mongodb, i know how to do it with the shell but i want to do it with python, as i'm learning Python.

This is what i have so far:

import csv
import json
import pandas as pd
import sys, getopt, pprint
from pymongo import MongoClient
#CSV to JSON Conversion
with open('netflix_titles.csv','rt', encoding="utf8") as file:
data = file.read()
mongo_client=MongoClient()
db=mongo_client.Netflix
db.segment.drop()
header= [ "show_id", "director"]

for each in data:
    row={}
    for field in header:
        row[field]=each[field]

    db.segment.insert(row)

In only throws me an indented error in this line:

data = file.read()

Body:
If you are going to use the csv module then definitely use the reader function of that module.  It will deal with quotes, whitespace, etc. etc.   Also, not sure if your

for each in data:

Is actually doing the CSV breakup you think it is.  This is more tidy (assuming you want to drive the action from a static array of header names):

with open('data.csv', 'r') as csvfile:
    header = [ "show_id", "director"]
    reader = csv.reader(csvfile)

    for row in reader:
        doc={}
        for n in range(0,len(header)):
            doc[header[n]] = row[n]

        db.foo.insert(doc)


问:
Width of Chosen dropdowns near zero when starting in collapsed Bootstrap accordion
When a Chosen dropdown is inside a Bootstrap 3 accordion that's initially hidden, then the width of the dropdown is near zero. After expanding it looks like this:

Whereas I expect it to look like this:

The problem occurs when the panel-collapse collapse div does not have an in class,effectively indicating it's initially collapsed. Here's the code to reproduce this issue:

$(document).ready(function() {
    $('select').chosen();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.panel-heading { cursor: pointer; }
body { padding: 10px; }</code>```

<link href="http://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

          Expand me to show the issue!

This select has a near-width zero:

        <select class="form-control">
            <option>Short</option>
            <option>Longer option</option>
            <option>The longest option of them all</option>
        </select>

          Already expanded / how it should be

This panel is initially visible and does have correct width for the select box:

          <select class="form-control">
            <option>Short</option>
            <option>Longer option</option>
            <option>The longest option of them all</option>
        </select>

```

What can I do to prevent this from happening? Calling chosen as .chosen({width: '90%'});, i.e. with a hard-coded width works, but is not satisfactory (I want to style in my stylesheet or using Bootstrap). The only resolution left seems to be to hook into the expanding event and force a chosen update, but that also feels like a workaround.

Preferably I'd have a line of CSS to fix this, or know whether this might even be a bug in the (combination of) tool(s)?

答:
To avoid an inline width style being applied by chosen, pass an empty string as the width parameter when initializing your select.

```<code>$('#your-select-element').chosen({ width: '' });
</code>```

Behind the scenes, chosen just calls jQuery .width() to set the width on the element using the value you supply.

By passing an empty string, the chosen-container element won't have any width style applied to it at all. Then you don't need to mess with !important or other things that could conflict with your stylesheet.

Body:
When a Chosen dropdown is inside a Bootstrap 3 accordion that's initially hidden, then the width of the dropdown is near zero. After expanding it looks like this:

Whereas I expect it to look like this:

The problem occurs when the panel-collapse collapse div does not have an in class,effectively indicating it's initially collapsed. Here's the code to reproduce this issue:

$(document).ready(function() {
    $('select').chosen();
});

.panel-heading { cursor: pointer; }
body { padding: 10px; }

<link href="http://cdnjs.cloudflare.com/ajax/libs/chosen/1.1.0/chosen.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet"/>

          Expand me to show the issue!

This select has a near-width zero:

        <select class="form-control">
            <option>Short</option>
            <option>Longer option</option>
            <option>The longest option of them all</option>
        </select>

          Already expanded / how it should be

This panel is initially visible and does have correct width for the select box:

          <select class="form-control">
            <option>Short</option>
            <option>Longer option</option>
            <option>The longest option of them all</option>
        </select>

What can I do to prevent this from happening? Calling chosen as .chosen({width: '90%'});, i.e. with a hard-coded width works, but is not satisfactory (I want to style in my stylesheet or using Bootstrap). The only resolution left seems to be to hook into the expanding event and force a chosen update, but that also feels like a workaround.

Preferably I'd have a line of CSS to fix this, or know whether this might even be a bug in the (combination of) tool(s)?

Body:
To avoid an inline width style being applied by chosen, pass an empty string as the width parameter when initializing your select.

$('#your-select-element').chosen({ width: '' });

Behind the scenes, chosen just calls jQuery .width() to set the width on the element using the value you supply.

By passing an empty string, the chosen-container element won't have any width style applied to it at all. Then you don't need to mess with !important or other things that could conflict with your stylesheet.


问:
Using nodemon and --inspect with serverless
I am writing a lambda service and hate having to stop and start the server after every change.

I do have this running together with chrome --inspect working correctly:

```<code>    "start": "node --inspect-brk $(which serverless) invoke local -f getGoldenDeomondotcom"
</code>```

I then used:

```<code>    "start": "nodemon --exec \"node --inspect-brk $(which serverless) invoke local -f getGoldenDeomondotcom\""
</code>```

to allow me to use nodemon with --inspect, however the messages don't pipe through to chrome.

Any ideas how I could use them together?

答:
From github ... (https://github.com/akupila)
nodemon --exec "serverless serve start"

I'm using this in package.json during dev:

"scripts": {
  "start": "nodemon --exec \"serverless serve start\""
}

This allows me to just run npm start. Whenever any file in the project changes nodemon will restart serve.

Body:
I am writing a lambda service and hate having to stop and start the server after every change.

I do have this running together with chrome --inspect working correctly:

    "start": "node --inspect-brk $(which serverless) invoke local -f getGoldenDeomondotcom"

I then used:

    "start": "nodemon --exec \"node --inspect-brk $(which serverless) invoke local -f getGoldenDeomondotcom\""

to allow me to use nodemon with --inspect, however the messages don't pipe through to chrome.

Any ideas how I could use them together?


问:
cannot move Kaggle.json to /root/.kaggle in Colab
I am working on Colab.

To get the kaggle training data (https://www.kaggle.com/muerbingsha/pandatiledsingle/settings), I used kaggle API.

upload kaggle.json to Colab

move kaggle.json to /root/.kaggle

Theses steps work well in previous days. But today It gave me error of

```<code>mv: cannot move 'kaggle.json' to '/root/.kaggle/': Not a directory
</code>```

Error Screenshot (for better explanation)

This problem is really weird. How to deal with this, Thank you!

答:
Problem solved. I found asking on StackOverflow is really a good way to find solutions!!! Yeah, time saving!!!

When I was typing the question, I found that since it says !mv ... not a directory and !ls no such file or directory, maybe there is no folder of .kaggle.

I tried to create the folder and just follow the instructions if any error happens

```<code>!pip install kaggle -q      # At first, I suspect the kaggle API lose effect so it doesn't have .kaggle folder. (not working)
!rm -rf /root/.kaggle.      # when I created the folder, it says the file or dir already exits
!mkdir /root/.kaggle        # successful
!mv kaggle.json /root/.kaggle/kaggle.json    # not sure if I have to use full destination path, I previously only used /root/.kaggle and it failed. Don't have time to validate this thought.
!ls /root/.kaggle/kaggle.json
!kaggle datasets download muerbingsha/pandatiledsingle
</code>```

Conclusion:

The Colab environment changed that .kaggle is lost for unknown reasons.

Body:
I am working on Colab.

To get the kaggle training data (https://www.kaggle.com/muerbingsha/pandatiledsingle/settings), I used kaggle API.

upload kaggle.json to Colab

move kaggle.json to /root/.kaggle

Theses steps work well in previous days. But today It gave me error of

mv: cannot move 'kaggle.json' to '/root/.kaggle/': Not a directory

Error Screenshot (for better explanation)

This problem is really weird. How to deal with this, Thank you!

Body:
Problem solved. I found asking on StackOverflow is really a good way to find solutions!!! Yeah, time saving!!!

When I was typing the question, I found that since it says !mv ... not a directory and !ls no such file or directory, maybe there is no folder of .kaggle.

I tried to create the folder and just follow the instructions if any error happens

!pip install kaggle -q      # At first, I suspect the kaggle API lose effect so it doesn't have .kaggle folder. (not working)
!rm -rf /root/.kaggle.      # when I created the folder, it says the file or dir already exits
!mkdir /root/.kaggle        # successful
!mv kaggle.json /root/.kaggle/kaggle.json    # not sure if I have to use full destination path, I previously only used /root/.kaggle and it failed. Don't have time to validate this thought.
!ls /root/.kaggle/kaggle.json
!kaggle datasets download muerbingsha/pandatiledsingle

Conclusion:

The Colab environment changed that .kaggle is lost for unknown reasons.


问:
How can I combine these two async functions?
I'm looping thru a teams array getting team data and players for each team...

I have 2 async functions that pull the same data but I can't figure out how to combine them.

As it works currently, each loop adds the teamPlayers array to a players array in the first async function. On completion I have 1450 player objects in my players array. The second async function adds the team object to a teams array. On completion I have 32 team objects in my teams array.

I've tried changing the first async function to get data and then have the dispatch return a value of results.teamPlayers but I end up with a players array with 32 arrays each with x number of player objects.

```<code>async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.teamPlayers);
        } catch (e) {
            console.log(e);
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}

async function loadTeamData(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.team);
        } catch (e) {
            //
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_TEAM_LOGOS', value: results });

    return results;
}
</code>```

Here is the structure of the data I'm getting:

```<code>{
  "team": {
    "teamId": "string",
    "abbr": "string",
    "logo": "string"
  },
  "teamPlayers": [
    {
      "firstName": "string",
      "lastName": "string",
      "esbId": "string",
      "position": "string",
      "jerseyNumber": 0,
      "teamAbbr": "string",
      "headshot": "string"
    }
  ]
}
</code>```

It may be simpler if I get the team.logo and add it to each player in teamPlayers.

答:
To avoid fetching the same team multiple times, you could cache your results. For example, if this is a redux store, you could dispatch teams and place them in your redux state. To put it all together, you can write an async function that either retrieves teams from the store or fetches if it hasn't yet been fetched.

```<code>// Not sure how you are getting "dispatch" earlier, but assuming you've got a getState as well...

const inProgress = new Map();

async function loadTeam(endPoints, teamId, authKey) {
  const { teams } = getState();
  if (teamId in teams) {
    return teams[teamId];
  }

  let promise = inProgress.get(teamId);
  if (!promise) {
    axios.defaults.headers.common['Authorization'] = authKey;
    promise = axios.get(endPoints.roster + teamId);
    inProgress.set(teamId, promise);
  }

  const { data: team } = await promise;
  inProgress.delete(teamId);

  // TODO: add a reducer that puts this team in your state
  dispatch({ type: 'SET_TEAM', payload: { teamId, team } });
  return team;
}
</code>```

Now you don't have to worry about duplicate fetches if you use this loadTeam function:

```<code>async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => loadTeam(endPoints, teamId, authKey));

    const results = (await Promise.all(requests))
      .map(team => team.teamPlayers)
      .flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}
</code>```

Body:
I'm looping thru a teams array getting team data and players for each team...

I have 2 async functions that pull the same data but I can't figure out how to combine them.

As it works currently, each loop adds the teamPlayers array to a players array in the first async function. On completion I have 1450 player objects in my players array. The second async function adds the team object to a teams array. On completion I have 32 team objects in my teams array.

I've tried changing the first async function to get data and then have the dispatch return a value of results.teamPlayers but I end up with a players array with 32 arrays each with x number of player objects.

async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.teamPlayers);
        } catch (e) {
            console.log(e);
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}

async function loadTeamData(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => {
        try {
            return axios.get(endPoints.roster + teamId).then(r => r.data.team);
        } catch (e) {
            //
        }
        return [];
    });

    const results = (await Promise.all(requests)).flat();
    dispatch({ type: 'SET_TEAM_LOGOS', value: results });

    return results;
}

Here is the structure of the data I'm getting:

{
  "team": {
    "teamId": "string",
    "abbr": "string",
    "logo": "string"
  },
  "teamPlayers": [
    {
      "firstName": "string",
      "lastName": "string",
      "esbId": "string",
      "position": "string",
      "jerseyNumber": 0,
      "teamAbbr": "string",
      "headshot": "string"
    }
  ]
}

It may be simpler if I get the team.logo and add it to each player in teamPlayers.

Body:
To avoid fetching the same team multiple times, you could cache your results. For example, if this is a redux store, you could dispatch teams and place them in your redux state. To put it all together, you can write an async function that either retrieves teams from the store or fetches if it hasn't yet been fetched.

// Not sure how you are getting "dispatch" earlier, but assuming you've got a getState as well...

const inProgress = new Map();

async function loadTeam(endPoints, teamId, authKey) {
  const { teams } = getState();
  if (teamId in teams) {
    return teams[teamId];
  }

  let promise = inProgress.get(teamId);
  if (!promise) {
    axios.defaults.headers.common['Authorization'] = authKey;
    promise = axios.get(endPoints.roster + teamId);
    inProgress.set(teamId, promise);
  }

  const { data: team } = await promise;
  inProgress.delete(teamId);

  // TODO: add a reducer that puts this team in your state
  dispatch({ type: 'SET_TEAM', payload: { teamId, team } });
  return team;
}

Now you don't have to worry about duplicate fetches if you use this loadTeam function:

async function loadRosters(endPoints, teams, authKey) {
    axios.defaults.headers.common['Authorization'] = authKey;

    const requests = teams.map(teamId => loadTeam(endPoints, teamId, authKey));

    const results = (await Promise.all(requests))
      .map(team => team.teamPlayers)
      .flat();
    dispatch({ type: 'SET_PLAYERS', value: results });

    return results;
}


问:
Can I get the path of the currently running java executable?
Suppose I want to run a java program from the command line and I use this command:

```<code>myExes\java\java.exe AJavaProgram
</code>```

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.

答: When you do myExes\java\java.exe AJavaProgram AJavaProgram is the arg to java.exe and not the reverse. Its the same when you do java AJavaProgram, AJavaProgram is the arg to java.

Body:
Suppose I want to run a java program from the command line and I use this command:

myExes\java\java.exe AJavaProgram

As you can see, java.exe is not in my path, so I am running it manually rather than simply using the command java AJavaProgram.

I would like the program to return/print the first entry in the command, in this case, that entry is myExes\java. (Including java.exe at the end of this is also fine).

Is there a way to do this?

Initially, I thought it would be simple. args[0] would return the path, but that is not the case.


问:
How to bulk update sequence ID postgreSQL for all tables
I imported the Postgres SQL file to my server using TablePlus(SQL client), but after I insert new row I got error like this:

SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"users_pkey\"
  DETAIL:  Key (id)=(1) already exists

I know it caused by sequence value is 0 and need to be updated by code below:

```<code>SELECT setval(_sequence_name_, max(id)) FROM _table_name_;
</code>```

But it needs so much time if I must write to all table sequences(maybe hundreds of sequences) one by one. So how to update all sequences at once?

答:
as @a_horse_with_no_name answer doesn't work in my case (maybe something is wrong with the SQL file), I modified the query like below that works in my case.

```<code>with sequences as (
  select *
  from (
    select table_schema,
           table_name,
           column_name,
           replace(replace(replace(column_default, '::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence
    from information_schema.columns
    where table_schema not in ('pg_catalog', 'information_schema') and column_default ILIKE 'nextval(%'
  ) t
  where col_sequence is not null
), maxvals as (
  select table_schema, table_name, column_name, col_sequence,
          (xpath('/row/max/text()',
             query_to_xml(format('select max(%I) from %I.%I', column_name, table_schema, table_name), true, true, ''))
          )[1]::text::bigint as max_val
  from sequences
)
select table_schema,
       table_name,
       column_name,
       col_sequence,
       coalesce(max_val, 0) as max_val,
       setval(col_sequence, coalesce(max_val, 1)) --<< this will change the sequence
from maxvals;
</code>```

I just change  pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence to replace(replace(replace(column_default, '::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence .

Maybe my query is not too good, I should use regex instead of multiple replace. but it's work 100% in my case.

Body:
I imported the Postgres SQL file to my server using TablePlus(SQL client), but after I insert new row I got error like this:

SQLSTATE[23505]: Unique violation: 7 ERROR:  duplicate key value violates unique constraint \"users_pkey\"
  DETAIL:  Key (id)=(1) already exists

I know it caused by sequence value is 0 and need to be updated by code below:

SELECT setval(_sequence_name_, max(id)) FROM _table_name_;

But it needs so much time if I must write to all table sequences(maybe hundreds of sequences) one by one. So how to update all sequences at once?

Body:
as @a_horse_with_no_name answer doesn't work in my case (maybe something is wrong with the SQL file), I modified the query like below that works in my case.

with sequences as (
  select *
  from (
    select table_schema,
           table_name,
           column_name,
           replace(replace(replace(column_default, '::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence
    from information_schema.columns
    where table_schema not in ('pg_catalog', 'information_schema') and column_default ILIKE 'nextval(%'
  ) t
  where col_sequence is not null
), maxvals as (
  select table_schema, table_name, column_name, col_sequence,
          (xpath('/row/max/text()',
             query_to_xml(format('select max(%I) from %I.%I', column_name, table_schema, table_name), true, true, ''))
          )[1]::text::bigint as max_val
  from sequences
)
select table_schema,
       table_name,
       column_name,
       col_sequence,
       coalesce(max_val, 0) as max_val,
       setval(col_sequence, coalesce(max_val, 1)) --<< this will change the sequence
from maxvals;

I just change  pg_get_serial_sequence(format('%I.%I', table_schema, table_name), column_name) as col_sequence to replace(replace(replace(column_default, '::regclass)', ''), '''', ''), 'nextval(', 'public.') as col_sequence .

Maybe my query is not too good, I should use regex instead of multiple replace. but it's work 100% in my case.


问:
Iterate over two list and set element from first list
I have two ArrayList as below -

```<code>certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]
</code>```

promotions list size is not confirm but certificates list size is confirmed. So consider first list size is 2 and second list size is 3

I want to set promotionCode in second list from certificates but in second list some time promotionCode is not present.

```<code>for (int i = 0; i < getCertificateNumber().size(); i++) {
   if (!promotions().isEmpty()) {
       promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
   }
}
</code>```

as in above for loop it set only first two promotions in promotion list because certificate list size two

How can I avoid any element from second list which don't have promotionCode and set CERT to element which has promotionCode

答:
This code will filter out promotions without codes and limit it to the number of certs we have. Then you can run your for loop to map the codes to valid promotions. Also, in this case I would run the for loop over validPromotions, not certificates, because we might not have any valid promotions.

```<code>    List<Promotion> validPromotions = promotions.stream()
            .filter(x -> x.promotionCode != null) // only keep promotions that have valid promotion codes
            .limit(certificates.length) // only keep as many promotions as we have certificates for
            .collect(Collectors.toList());
</code>```

Body:
I have two ArrayList as below -

certificates=[CERT1, CERT2]
promotions=[{type}, {type, promotionCode}, {type, promotionCode}]

promotions list size is not confirm but certificates list size is confirmed. So consider first list size is 2 and second list size is 3

I want to set promotionCode in second list from certificates but in second list some time promotionCode is not present.

for (int i = 0; i < getCertificateNumber().size(); i++) {
   if (!promotions().isEmpty()) {
       promotions().get(i).setPromotionCode(getCertificateNumber().get(i));
   }
}

as in above for loop it set only first two promotions in promotion list because certificate list size two

How can I avoid any element from second list which don't have promotionCode and set CERT to element which has promotionCode

Body:
This code will filter out promotions without codes and limit it to the number of certs we have. Then you can run your for loop to map the codes to valid promotions. Also, in this case I would run the for loop over validPromotions, not certificates, because we might not have any valid promotions.

    List<Promotion> validPromotions = promotions.stream()
            .filter(x -> x.promotionCode != null) // only keep promotions that have valid promotion codes
            .limit(certificates.length) // only keep as many promotions as we have certificates for
            .collect(Collectors.toList());


问:
What does a C++ preprocessor do when there's just a single `#` in a line - and nothing else?
Is this a valid line of C++? What is it supposed to mean?

```<code>#
</code>```

What about this one:

```<code># // a comment
</code>```

Recent compilers seem to ignore it without errors nor warnings.

Does it "do nothing"? I have a header file where a "compatibility" section bombs out when compiled with g++ 7.4.0 in presence of such lines. It doesn't seem to trip up compilers that see this line excluded in an inactive #if branch.

Note: gcc 7.4.0 on Debian Bionic (as of this writing) on Travis CI is tripped by such lines.

答:
Both examples are valid, and they do nothing.

For the second example, first the comments are removed in translation phase 3:

... Each comment is replaced by one space character. New-line characters are retained. ...

which results in the first case, which is a preprocessor directive that is expanded in translation phase 4:

Preprocessing directives are executed, ...

This preprocessor directive is valid, and is called a Null directive, and has no effect, as stated here:

A preprocessing directive of the form

# new-line

has no effect.

where new-line is literally the new-line character.

So the code you have shown is valid, and should be accepted by a conforming implementation.

Body:
Is this a valid line of C++? What is it supposed to mean?

#

What about this one:

# // a comment

Recent compilers seem to ignore it without errors nor warnings.

Does it "do nothing"? I have a header file where a "compatibility" section bombs out when compiled with g++ 7.4.0 in presence of such lines. It doesn't seem to trip up compilers that see this line excluded in an inactive #if branch.

Note: gcc 7.4.0 on Debian Bionic (as of this writing) on Travis CI is tripped by such lines.


问:
Extract string between two characters in a string
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

```<code>CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;
</code>```

Expected Results:

```<code>20200528102030
20190528102030
20200528102030
</code>```

答:
If interested in a helper function...  I created this TVF because I was tiered of extracting portions of strings (left, right, charindex, reverse, substing, etc)

Example

```<code>Select *
 From  #Temp A
 Cross Apply [dbo].[tvf-Str-Extract](Blob_NM,'_','.') B
</code>```

Returns

```<code>BLOB_NM                                         RetSeq  RetVal
products_country_20200528102030.txt             1       20200528102030
products_territory_20190528102030.txt           1       20190528102030
products_country_2020-05-20_20200528102030.txt  1       20200528102030
</code>```

The Function if Interested

```<code>CREATE FUNCTION [dbo].[tvf-Str-Extract] (@String varchar(max),@Delim1 varchar(100),@Delim2 varchar(100))
Returns Table
As
Return (

    Select RetSeq = row_number() over (order by RetSeq)
          ,RetVal = left(RetVal,charindex(@Delim2,RetVal)-1)
    From  (
            Select RetSeq = row_number() over (order by 1/0)
                  ,RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(max)')))
            From  ( values (convert(xml,'<x>' + replace((Select replace(@String,@Delim1,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>').query('.'))) as A(XMLData)
            Cross Apply XMLData.nodes('x') AS B(i)
          ) C1
    Where charindex(@Delim2,RetVal)>1

)
</code>```

Body:
I have a set of strings that has datetime values and I would like to extract them. I am not sure if this is even possible using T-SQL.

CREATE TABLE #Temp (
BLOB_NM VARCHAR(100)
);

INSERT INTO #Temp
SELECT 'products_country_20200528102030.txt'
UNION ALL
SELECT 'products_territory_20190528102030.txt'
UNION ALL
SELECT 'products_country_2020-05-20_20200528102030.txt'
;

Expected Results:

20200528102030
20190528102030
20200528102030

Body:
If interested in a helper function...  I created this TVF because I was tiered of extracting portions of strings (left, right, charindex, reverse, substing, etc)

Example

Select *
 From  #Temp A
 Cross Apply [dbo].[tvf-Str-Extract](Blob_NM,'_','.') B

Returns

BLOB_NM                                         RetSeq  RetVal
products_country_20200528102030.txt             1       20200528102030
products_territory_20190528102030.txt           1       20190528102030
products_country_2020-05-20_20200528102030.txt  1       20200528102030

The Function if Interested

CREATE FUNCTION [dbo].[tvf-Str-Extract] (@String varchar(max),@Delim1 varchar(100),@Delim2 varchar(100))
Returns Table
As
Return (

    Select RetSeq = row_number() over (order by RetSeq)
          ,RetVal = left(RetVal,charindex(@Delim2,RetVal)-1)
    From  (
            Select RetSeq = row_number() over (order by 1/0)
                  ,RetVal = ltrim(rtrim(B.i.value('(./text())[1]', 'varchar(max)')))
            From  ( values (convert(xml,'<x>' + replace((Select replace(@String,@Delim1,'§§Split§§') as [*] For XML Path('')),'§§Split§§','</x><x>')+'</x>').query('.'))) as A(XMLData)
            Cross Apply XMLData.nodes('x') AS B(i)
          ) C1
    Where charindex(@Delim2,RetVal)>1

)


问:
Exclude column from resultset in controller | Spring data jpa
I have a Users Entity:

```<code>public class SpringUsers implements Serializable {
    private String password;
    // other fields omitted
    @Basic
    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
</code>```

And its repository:

```<code>public interface SpringUsersRepository extends CrudRepository<SpringUsers, Integer> {
    SpringUsers findByUsername(String username);
    List<SpringUsers> findByUserId(Integer userId);
}
</code>```

And I have a controller method that should get a list of all registered users with the same userId (is internally used) as the currently authenticated user:

```<code>public List<SpringUsers> getRegisteredUsers() {
    CustomUserDetails authenticatedUserDetails = getCustomUserDetails();
    List<SpringUsers> registered = springUsersRepository.findByUserId(
        authenticatedUserDetails.getUserMyId());
    return registered.stream().map(v -> {
        v.setPassword(null);
        return v;
    }).collect(Collectors.toList());
}
</code>```

I don't want to pass the password (even though it's encrypted) to the frontend - so I stream through the users and set the password to null, as you can see above.

However, I'm wondering if there isn't a possibility to just not include the users' password in the query result in the first place?

Version Info:

Spring boot 1.4.0 &
Hibernate 5.0.9.Final

答:
Use @JsonIgnore, this will make it available in the back but will not return when transforming to json</p>

```<code>@Size(min = 8)
@JsonIgnore
private String password;
</code>```

Body:
I have a Users Entity:

public class SpringUsers implements Serializable {
    private String password;
    // other fields omitted
    @Basic
    @Column(name = "password")
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

And its repository:

public interface SpringUsersRepository extends CrudRepository<SpringUsers, Integer> {
    SpringUsers findByUsername(String username);
    List<SpringUsers> findByUserId(Integer userId);
}

And I have a controller method that should get a list of all registered users with the same userId (is internally used) as the currently authenticated user:

public List<SpringUsers> getRegisteredUsers() {
    CustomUserDetails authenticatedUserDetails = getCustomUserDetails();
    List<SpringUsers> registered = springUsersRepository.findByUserId(
        authenticatedUserDetails.getUserMyId());
    return registered.stream().map(v -> {
        v.setPassword(null);
        return v;
    }).collect(Collectors.toList());
}

I don't want to pass the password (even though it's encrypted) to the frontend - so I stream through the users and set the password to null, as you can see above.

However, I'm wondering if there isn't a possibility to just not include the users' password in the query result in the first place?

Version Info:

Spring boot 1.4.0 &
Hibernate 5.0.9.Final

Body:
Use @JsonIgnore, this will make it available in the back but will not return when transforming to json

@Size(min = 8)
@JsonIgnore
private String password;


问:
Why error in phpmyadmin connecting to mysql?
Running phpmyadmin on my local ubuntu 18
I got error

```<code>#1698 - Access denied for user 'root'@'localhost'
</code>```

But in file /etc/phpmyadmin/config.inc.php
I changed connection parameters to escape default user as :

```<code>$dbuser='MYUSER';
$dbpass='MYPASSWORD';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='3306';
$dbtype='mysql';
</code>```

Under MYUSER/MYPASSWORD I connect to my sql from my php apps.
In information_schema I run

```<code>GRANT ALL PRIVILEGES ON * . * TO 'lardev'@'localhost'
</code>```

with output :

```<code>Query executed OK, 0 rows affected.
</code>```

Why root user is refrerence in error message and how to fix the error ?

Thanks!

答:
The variables you have put in to config.inc.php aren't the correct variables for phpMyAdmin. You can refer to the sample configuration files, documentation on all configuration directives, or the file config.sample.inc.php that should be included with your download (or can be viewed at Github) for details on the correct syntax.

The official default is to use an authentication type called cookie, where you are prompted for the username and password when attempting to log in (you can see this in action on the demo server). Your description sounds like you aren't prompted for a username, which means someone has changed to the 'config' authentication type, with a directive like $cfg['Servers'][$i]['auth_type'] = 'config'; The relevant difference (aside from security and how you go about logging in) is that with auth_type config, you also need to set the username and password in the configuration file. With the auth_type cookie or http, those values aren't used.

With that being said, here's a corrected version of config.inc.php using the configuration you've listed, using the phpMyAdmin variable names:

```<code><?php

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'MYUSER';
$cfg['Servers'][$i]['password'] = 'MYPASSWORD';
</code>```

'localhost' is the default hostname, which forces the connection to use sockets rather than TCP/IP networking, so the port is ignored. To use a TCP/IP connection, set $cfg['Servers'][$i]['host'] = '127.0.0.1';

The other variables, $basepath, $dbname, and $dbtype, have no direct equivalent to phpMyAdmin.

Also, note that I suggest using auth_type cookie rather than config in any situation where your web server would serve phpMyAdmin to connections not coming from localhost (as a security measure, otherwise anyone with the URL has direct access to your database).

Body:
Running phpmyadmin on my local ubuntu 18
I got error

#1698 - Access denied for user 'root'@'localhost'

But in file /etc/phpmyadmin/config.inc.php
I changed connection parameters to escape default user as :

$dbuser='MYUSER';
$dbpass='MYPASSWORD';
$basepath='';
$dbname='phpmyadmin';
$dbserver='localhost';
$dbport='3306';
$dbtype='mysql';

Under MYUSER/MYPASSWORD I connect to my sql from my php apps.
In information_schema I run

GRANT ALL PRIVILEGES ON * . * TO 'lardev'@'localhost'

with output :

Query executed OK, 0 rows affected.

Why root user is refrerence in error message and how to fix the error ?

Thanks!

Body:
The variables you have put in to config.inc.php aren't the correct variables for phpMyAdmin. You can refer to the sample configuration files, documentation on all configuration directives, or the file config.sample.inc.php that should be included with your download (or can be viewed at Github) for details on the correct syntax.

The official default is to use an authentication type called cookie, where you are prompted for the username and password when attempting to log in (you can see this in action on the demo server). Your description sounds like you aren't prompted for a username, which means someone has changed to the 'config' authentication type, with a directive like $cfg['Servers'][$i]['auth_type'] = 'config'; The relevant difference (aside from security and how you go about logging in) is that with auth_type config, you also need to set the username and password in the configuration file. With the auth_type cookie or http, those values aren't used.

With that being said, here's a corrected version of config.inc.php using the configuration you've listed, using the phpMyAdmin variable names:

<?php

$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'MYUSER';
$cfg['Servers'][$i]['password'] = 'MYPASSWORD';

'localhost' is the default hostname, which forces the connection to use sockets rather than TCP/IP networking, so the port is ignored. To use a TCP/IP connection, set $cfg['Servers'][$i]['host'] = '127.0.0.1';

The other variables, $basepath, $dbname, and $dbtype, have no direct equivalent to phpMyAdmin.

Also, note that I suggest using auth_type cookie rather than config in any situation where your web server would serve phpMyAdmin to connections not coming from localhost (as a security measure, otherwise anyone with the URL has direct access to your database).


问:
How does Perl handle password prompts?
I'd like to pass a password through Perl. In my Perl script, it invokes SSH but gets stuck when the terminal is promoted for a password.

I've looked into using NET::SSH::Perl and other libraries but as of now they are not viable options. I just need to SSH into the machine, retrieve a file and leave.

答:
Use Term::ReadPassword to get the user's password, then use that as an option to your SSH module of choice.

Since you only need to get a file and leave, you might try an SFTP module like LWP+LWP::Protocol::sftp or Net::SFTP::Foriegn.

Here is an example using Net::SFTP::Foreign (which also has few dependencies):

```<code>#!/usr/bin/perl
use strict;
use warnings;

use Term::ReadPassword;
use Net::SFTP::Foreign;

my $pass = read_password("Enter Password: ");
my %opts = (
  host => "my.host.com",
  user => "me",
  password => $pass,
);

my $sftp = Net::SFTP::Foreign->new(%opts);

$sftp->get('/home/me/path/to/file', 'local_file');
</code>```

Title: How does Perl handle password prompts?

Body:
Use Term::ReadPassword to get the user's password, then use that as an option to your SSH module of choice.

Since you only need to get a file and leave, you might try an SFTP module like LWP+LWP::Protocol::sftp or Net::SFTP::Foriegn.

Here is an example using Net::SFTP::Foreign (which also has few dependencies):

#!/usr/bin/perl
use strict;
use warnings;

use Term::ReadPassword;
use Net::SFTP::Foreign;

my $pass = read_password("Enter Password: ");
my %opts = (
  host => "my.host.com",
  user => "me",
  password => $pass,
);

my $sftp = Net::SFTP::Foreign->new(%opts);

$sftp->get('/home/me/path/to/file', 'local_file');


问:
Problem with Scala Function and Call-by-Name
I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks</p>

```<code>def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
  if(f(ival)==false)
    return
  else {
    println(exp)
    forLoop(g(ival),f,g)(exp)
  }
}

def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")
</code>```

答:
The value "Hello World" is of type String however you are assigning it to Unit

```<code>val exp: Unit = "Hello World"
</code>```

which compiler expands to

```<code>val exp: Unit = {
  "Hello World";
  ()
}
</code>```

Note how () becomes the value of exp. Try changing the definition of exp to

```<code>val exp: String = "Hello World"
</code>```

and second parameter list to

```<code>(exp: => String)
</code>```

If you compile with compiler flag -Wvalue-discard, for example,

```<code>scala -Wvalue-discard -e 'val exp: Unit = "Hello World"'
</code>```

you will get a warning

```<code>warning: discarded non-Unit value
val exp: Unit = "Hello World"
                ^
</code>```

Body:
I am trying to loop a the second parameter (exp) in this function that uses call by name parameters. The first 3 parameters are the index, boolean to stop loop, and increment function. I am getting an output with 10 '()'s when I am trying to loop "hello world" 10 times as seen in the test code. May I get some help with what is wrong here? Thanks

def forLoop(ival: => Int, f: (Int) => Boolean, g: (Int)=>Int)(exp: => Unit): Unit = {
  if(f(ival)==false)
    return
  else {
    println(exp)
    forLoop(g(ival),f,g)(exp)
  }
}

def f(x: Int): Boolean = { x<10 }
def g(y: Int): Int = { y+1 }
val exp: Unit = "Hello World"
forLoop(0,f,g)("Hello World")

Body:
The value "Hello World" is of type String however you are assigning it to Unit

val exp: Unit = "Hello World"

which compiler expands to

val exp: Unit = {
  "Hello World";
  ()
}

Note how () becomes the value of exp. Try changing the definition of exp to

val exp: String = "Hello World"

and second parameter list to

(exp: => String)

If you compile with compiler flag -Wvalue-discard, for example,

scala -Wvalue-discard -e 'val exp: Unit = "Hello World"'

you will get a warning

warning: discarded non-Unit value
val exp: Unit = "Hello World"
                ^


问:
Conditional missing arguments in R function?
I'm trying to work with a function in R that allows for only one of two arguments to be passed, through a series of missing(arg) calls. I cannot easily modify the function.  My data is such that sometimes I supply one argument and other times the other.  Is it possible to have some variant of:

```<code>myFunction(arg1 = switch(condition == T, arg1, NULL),
           arg2 = switch(condition == F, arg2, NULL))
</code>```

When I run the function like that, it counts the switch function as an argument and not a NULL object.  Wrapping each switch in eval doesn't help either.

Thanks for the help!

Post script: I know this is bad practice, and I should have the call the function specified by the condition.  But this is part of a magrittr-style pipeline that I'd rather not disturb.

答:
You're probably much better off using @user2554330 's solution, or, as it seems from comments that you're fine with considering NULL and missing to be equivalent, use missing(arg1) || is.null(arg1) in your code.

Nevertheless If we really want to type myFunction once only and keep it as is we could do the following :

myFunction <- function(arg1, arg2) {
  if(missing(arg2))
    paste(arg1, "apples")
  else
    paste(arg2, "pears")
}

arg1 <- 2
arg2 <- 3

# SOLUTION 1

# similar to what you've tried, but we build the expression first, then eval
# `substitute()` will become your missing argument here

condition <- TRUE
eval(bquote(myFunction(
  .(if(condition) arg1 else substitute()),
  .(if(!condition) arg2 else substitute())
)))
#> [1] "2 apples"

condition <- FALSE
eval(bquote(myFunction(
  .(if(condition) arg1 else substitute()),
  .(if(!condition) arg2 else substitute())
)))
#> [1] "3 pears"

# SOLUTION 2

# feed to the function the right list of arguments depending on condition

condition <- TRUE
do.call(myFunction, list(arg1 = arg1, arg2 = arg2)[xor(condition,c(FALSE, TRUE))])
#> [1] "2 apples"
condition <- FALSE
do.call(myFunction, list(arg1 = arg1, arg2 = arg2)[xor(condition,c(FALSE, TRUE))])
#> [1] "3 pears"
```

Body:
I'm trying to work with a function in R that allows for only one of two arguments to be passed, through a series of missing(arg) calls. I cannot easily modify the function.  My data is such that sometimes I supply one argument and other times the other.  Is it possible to have some variant of:

myFunction(arg1 = switch(condition == T, arg1, NULL),
           arg2 = switch(condition == F, arg2, NULL))

When I run the function like that, it counts the switch function as an argument and not a NULL object.  Wrapping each switch in eval doesn't help either.

Thanks for the help!

Post script: I know this is bad practice, and I should have the call the function specified by the condition.  But this is part of a magrittr-style pipeline that I'd rather not disturb.


问:
Many similar activities in Android App against DRY principle
I'm new to Android App Development and to Kotlin. So, now I have an app (written with Kotlin) with 20 activities one go after another: Activity1 -> Activity2 -> ... -> Activity20.

They all have the same structure of XML files which differ only in image presented. They also have similar code. As there are 2 buttons in each activity (NEXT and BACK) they only differ in "nextActivity" and "previousActivity" (for example, NEXT button for Activity3 intents Activity4 and NEXT button for Activity5 intents Activity6 and so on).

At some point, it started to worry me, so I tried to write an open class:

```<code>open class everyActivity(pic: Int, nextActivity: Activity, prevActivity: Activity): AppCompatActivity() {

val pic = pic
val nextActivity = nextActivity
val prevActivity = prevActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(pic)
}

fun nextClick(view: View) {
    val nextIntent = Intent(this, nextActivity::class.java)
    startActivity(nextIntent)
    this.finish()
}

fun backClick(view: View){
    val prevIntent = Intent(this, prevActivity::class.java)
    startActivity(prevIntent)
    this.finish()
}
}
</code>```

Then I tried to inherit these similar activities, but I cannot pass Activity as an Argument for class (due to "Classifier 'Activity2' does not have companion object and so on"):

```<code>class Activity2 : everyActivity(R.layout.activity_02, Activity3, Activity1) {}
</code>```

And, overall, such construction looks pretty strange. That's when I thought that I may not have to do it at all.

So, final question:

There's is DRY principle considering most programming. However, I want to know: is it actually convenient to have similar codes for activities in Android?

答:
There are multiple things possible to achieve the DRY principle.
To achieve DRY principles you should ask yourself that I am breaking another Android rule such as Single Activity Architecture which is the more android specific rule.

It is a good thing you are taking care of such a principle but as per Single Activity Architecture, You have to try to keep minimal Activity in the android app.

In this situation, you can create function to change the image and can call that function in nextClick() and backClick(). This solution will help you to achieve the DRY principle as well Single Activity Architecture.Also, you will get better user experience.

So, you don't need to create 10 Activities to show 10 images but you can create functions like this:

```<code>nextClickFunction():

var currentNumber = 1
var iamge = R.drawable.image1
var listOfImages = mutableListOf(
        R.drawable.image1,
        R.drawable.image2,
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    }

fun nextClick(){
    image = listOfImages[currentNumber]
    setImageIntoImageView(image)
}

fun backClick(){
    image = listOfImages[currentNumber - 1]
    setImageIntoImageView(image)
}

fun setImageIntoImageView(int image){
   // Set image into ImageView here
}
</code>```

Let me know if it can help you.
Thanks & Happy coding..!

Body:
I'm new to Android App Development and to Kotlin. So, now I have an app (written with Kotlin) with 20 activities one go after another: Activity1 -> Activity2 -> ... -> Activity20.

They all have the same structure of XML files which differ only in image presented. They also have similar code. As there are 2 buttons in each activity (NEXT and BACK) they only differ in "nextActivity" and "previousActivity" (for example, NEXT button for Activity3 intents Activity4 and NEXT button for Activity5 intents Activity6 and so on).

At some point, it started to worry me, so I tried to write an open class:

open class everyActivity(pic: Int, nextActivity: Activity, prevActivity: Activity): AppCompatActivity() {

val pic = pic
val nextActivity = nextActivity
val prevActivity = prevActivity

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(pic)
}

fun nextClick(view: View) {
    val nextIntent = Intent(this, nextActivity::class.java)
    startActivity(nextIntent)
    this.finish()
}

fun backClick(view: View){
    val prevIntent = Intent(this, prevActivity::class.java)
    startActivity(prevIntent)
    this.finish()
}
}

Then I tried to inherit these similar activities, but I cannot pass Activity as an Argument for class (due to "Classifier 'Activity2' does not have companion object and so on"):

class Activity2 : everyActivity(R.layout.activity_02, Activity3, Activity1) {}

And, overall, such construction looks pretty strange. That's when I thought that I may not have to do it at all.

So, final question:

There's is DRY principle considering most programming. However, I want to know: is it actually convenient to have similar codes for activities in Android?

Body:
There are multiple things possible to achieve the DRY principle.
To achieve DRY principles you should ask yourself that I am breaking another Android rule such as Single Activity Architecture which is the more android specific rule.

It is a good thing you are taking care of such a principle but as per Single Activity Architecture, You have to try to keep minimal Activity in the android app.

In this situation, you can create function to change the image and can call that function in nextClick() and backClick(). This solution will help you to achieve the DRY principle as well Single Activity Architecture.Also, you will get better user experience.

So, you don't need to create 10 Activities to show 10 images but you can create functions like this:

nextClickFunction():

var currentNumber = 1
var iamge = R.drawable.image1
var listOfImages = mutableListOf(
        R.drawable.image1,
        R.drawable.image2,
        R.drawable.image3,
        R.drawable.image4,
        R.drawable.image5,
        R.drawable.image6,
        R.drawable.image7,
        R.drawable.image8,
        R.drawable.image9,
        R.drawable.image10,
    }

fun nextClick(){
    image = listOfImages[currentNumber]
    setImageIntoImageView(image)
}

fun backClick(){
    image = listOfImages[currentNumber - 1]
    setImageIntoImageView(image)
}

fun setImageIntoImageView(int image){
   // Set image into ImageView here
}

Let me know if it can help you.
Thanks & Happy coding..!