问:
Is it possible to use Single File Vue Components in premade html files
I'm trying to create a Flask project but I wanted to use Vue as well. I've done some reading about how I can use js files and combine them into my html files and make components like that, but I want to be able to create vue files and use them in my index.html without having to generate an app.html from webpack. I'd like to be able to use a component made in a vue file inside an index.html that I'm already using in flask. Is this possible?</p>

```<code>webapp
|-- static
  |-- css
  |-- vueComponents
    |--  Hello.vue
  |-- js
  |-- templates
    |-- index.html (not generated by webpack and vue)
</code>```

答:
Yep. https://v2.vuejs.org/v2/guide/installation.html#Direct-lt-script-gt-Include

```
<pre class="lang-js prettyprint-override"><code>new Vue({
    el: "#foo",
    template: `<span>Hello world!</span>`
})
</code>```

Body:
I'm trying to create a Flask project but I wanted to use Vue as well. I've done some reading about how I can use js files and combine them into my html files and make components like that, but I want to be able to create vue files and use them in my index.html without having to generate an app.html from webpack. I'd like to be able to use a component made in a vue file inside an index.html that I'm already using in flask. Is this possible?

webapp
|-- static
  |-- css
  |-- vueComponents
    |--  Hello.vue
  |-- js
  |-- templates
    |-- index.html (not generated by webpack and vue)

Body:
Yep. https://v2.vuejs.org/v2/guide/installation.html#Direct-lt-script-gt-Include

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="foo"></div>

new Vue({
    el: "#foo",
    template: `<span>Hello world!</span>`
})


来源: stackexchange

问:
Joomla, Multiple layouts in a single template
I tired the joomla IRC but no one ever talks in there :(, heres the issue i have.

i have a site that have 3 diff types of layouts.

home page

all the other pages

portfolio page

im using joomla 1.6

all i can see is the index.php file on the root of my template folder.
hwo can i create 3 diff layouts in side a single template folder and assign these to diff pages (menu itmes).

答: You can assign different templates to different menu items using the admin backend of Joomla.</p>

ContentLicense: CC BY-SA 3.0


问:
How to perform >= or <= conditions with date in python pandas dataframe
I have a dataframe named df1 and one variable named start date and I have given the dt for both the dataframe and Date variable. the important thing to check out here is both the length of dataframe and date variable are different

```<code>df1
</code>```

Date Variable

we need to filter the data in dataframe df1 based dates for df1 greater than or equal to dates in Date variable.

simply df['Date'] >= Date variable

答:
You can compare dates, but you have to be sure they are the proper type first.
With Pandas you can enforce the datetime type by doing:

```<code>df['Date'] = pd.to_datetime(df['Date'])
</code>```

Once both your df and the date_variable are ok, then you can filter by:

```<code>filtered = df[df['Date'] >= date_variable['Date']]
</code>```

Here I am assuming that "Date variable" is a dataframe called date_variable with a columns Date.

ContentLicense: CC BY-SA 4.0

Body:
I have a dataframe named df1 and one variable named start date and I have given the dt for both the dataframe and Date variable. the important thing to check out here is both the length of dataframe and date variable are different

df1

Date Variable

we need to filter the data in dataframe df1 based dates for df1 greater than or equal to dates in Date variable.

simply df['Date'] >= Date variable

Body:
You can compare dates, but you have to be sure they are the proper type first.
With Pandas you can enforce the datetime type by doing:

df['Date'] = pd.to_datetime(df['Date'])

Once both your df and the date_variable are ok, then you can filter by:

filtered = df[df['Date'] >= date_variable['Date']]

Here I am assuming that "Date variable" is a dataframe called date_variable with a columns Date.


问:
Facing a difficulty in a bubble sort algorithm in C
First of all I am beginner in C, so I am sorry if my question seems stupid.
I was learning how to use the bubble sort algorithm in C, and I came through this code :

```<code>#include <stdio.h>

int main() {
    int ctr, inner, outer, didSwap, temp;
    int nums[10] = {
        78,
        16,
        21,
        7,
        13,
        9,
        22,
        52,
        67,
        19
    };

    //Listing the array before sorting

    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    //Sorting the arrays

    for (outer = 0; outer < 9; outer++) {
        didSwap = 0;
        for (inner = outer; inner < 10; inner++) {
            if (nums[inner] < nums[outer]) {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }
        if (didSwap == 0) {
            break;
        }
    }

    //Listing the array after sorting

    printf("\n\nThis is the sorted array\n");
    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    return 0;
}
</code>```

The code works fine, but what I want to understand is how in the second for loop it is written inner = outer, and in the next if statement it is comparing the elements of the array were one of them has the same number as inner and the other has the same number as outer.
And since we said that inner = outer, that means that we are comparing the same element.
The way I think about it is, if outer = 0, and since inner = outer, then inner will be 0 too, so the next if statement will be if (nums[0] < nums[0]) and that doesn't make any sense.

I know that I am probably wrong about it because the code works fine, but what did I think wrong?

Thanks in advance.

答: It is not stupid question. You successfully spotted an inefficiency. The inner loop first iteration is indeed pointless, but it won't cause any trouble. The right way would be to start it from outer + 1 instead of outer.

Body:
First of all I am beginner in C, so I am sorry if my question seems stupid.
I was learning how to use the bubble sort algorithm in C, and I came through this code :

#include <stdio.h>

int main() {
    int ctr, inner, outer, didSwap, temp;
    int nums[10] = {
        78,
        16,
        21,
        7,
        13,
        9,
        22,
        52,
        67,
        19
    };

    //Listing the array before sorting

    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    //Sorting the arrays

    for (outer = 0; outer < 9; outer++) {
        didSwap = 0;
        for (inner = outer; inner < 10; inner++) {
            if (nums[inner] < nums[outer]) {
                temp = nums[inner];
                nums[inner] = nums[outer];
                nums[outer] = temp;
                didSwap = 1;
            }
        }
        if (didSwap == 0) {
            break;
        }
    }

    //Listing the array after sorting

    printf("\n\nThis is the sorted array\n");
    for (ctr = 0; ctr < 10; ctr++) {
        printf("%d\n", nums[ctr]);
    }

    return 0;
}

The code works fine, but what I want to understand is how in the second for loop it is written inner = outer, and in the next if statement it is comparing the elements of the array were one of them has the same number as inner and the other has the same number as outer.
And since we said that inner = outer, that means that we are comparing the same element.
The way I think about it is, if outer = 0, and since inner = outer, then inner will be 0 too, so the next if statement will be if (nums[0] < nums[0]) and that doesn't make any sense.

I know that I am probably wrong about it because the code works fine, but what did I think wrong?

Thanks in advance.


问:
Getting "Failed to load resource" error on Dash load on IIS with Flask on Anaconda
I am trying to setup a Dash App on Flask with the IIS server and WFastCGI on Anaconda. What I could be missing so that it cannot find the required JS? I've tested plain Flask apps on the server and it works okay.

IIS server version: 8.0

Flask=1.1.1

Dash=1.8.0

python 3.6.8

I have also tried with app.css.config.serve_locally = False and app.scripts.config.serve_locally = False But it doesn't work whether both are true/false.

I've tried below variant too for creating server and the app object.

```<code>server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)
</code>```

Below is my code.

```<code>import dash
import dash_core_components as dcc
import dash_html_components as html

# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__)#, external_stylesheets=external_stylesheets)
server = app.server
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)
</code>```

The errors are as below on chrome console.

```<code>GET http://127.0.0.1/_dash-component-suites/dash_renderer/polyfill@7.v1_2_3m1580483115.7.0.min.js net::ERR_ABORTED 404 (Not Found)
flask:22 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react-dom@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:21 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:23 GET http://127.0.0.1/_dash-component-suites/dash_renderer/prop-types@15.v1_2_3m1580483115.7.2.min.js net::ERR_ABORTED 404 (Not Found)
flask:24 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components.v1_7_0m1580483133.min.js net::ERR_ABORTED 404 (Not Found)
flask:25 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components-shared.v1_7_0m1580483133.js net::ERR_ABORTED 404 (Not Found)
flask:26 GET http://127.0.0.1/_dash-component-suites/dash_html_components/dash_html_components.v1_0_2m1573845875.min.js net::ERR_ABORTED 404 (Not Found)
flask:27 GET http://127.0.0.1/_dash-component-suites/dash_renderer/dash_renderer.v1_2_3m1580483115.min.js net::ERR_ABORTED 404 (Not Found)
flask:22 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react-dom@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:23 GET http://127.0.0.1/_dash-component-suites/dash_renderer/prop-types@15.v1_2_3m1580483115.7.2.min.js net::ERR_ABORTED 404 (Not Found)
flask:24 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components.v1_7_0m1580483133.min.js net::ERR_ABORTED 404 (Not Found)
flask:25 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components-shared.v1_7_0m1580483133.js net::ERR_ABORTED 404 (Not Found)
flask:26 GET http://127.0.0.1/_dash-component-suites/dash_html_components/dash_html_components.v1_0_2m1573845875.min.js net::ERR_ABORTED 404 (Not Found)
flask:27 GET http://127.0.0.1/_dash-component-suites/dash_renderer/dash_renderer.v1_2_3m1580483115.min.js net::ERR_ABORTED 404 (Not Found)
flask:28 Uncaught ReferenceError: DashRenderer is not defined
    at flask:28
</code>```

The generated webpage code as below:

```<code><html>
    <head>
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta charset="UTF-8">
        <title>Dash</title>
        <link rel="icon" type="image/x-icon" href="/_favicon.ico?v=1.8.0">

    </head>
    <body>

<div id="react-entry-point">
    <div class="_dash-loading">
        Loading...
    </div>
</div>

        <footer>
            <script id="_dash-config" type="application/json">{"url_base_pathname": null, "requests_pathname_prefix": "/", "ui": false, "props_check": false, "show_undo_redo": false}</script>
            <script src="/_dash-component-suites/dash_renderer/polyfill@7.v1_2_3m1580483115.7.0.min.js"></script>
<script src="/_dash-component-suites/dash_renderer/react@16.v1_2_3m1580483115.8.6.min.js"></script>
<script src="/_dash-component-suites/dash_renderer/react-dom@16.v1_2_3m1580483115.8.6.min.js"></script>
<script src="/_dash-component-suites/dash_renderer/prop-types@15.v1_2_3m1580483115.7.2.min.js"></script>
<script src="/_dash-component-suites/dash_core_components/dash_core_components.v1_7_0m1580483133.min.js"></script>
<script src="/_dash-component-suites/dash_core_components/dash_core_components-shared.v1_7_0m1580483133.js"></script>
<script src="/_dash-component-suites/dash_html_components/dash_html_components.v1_0_2m1573845875.min.js"></script>
<script src="/_dash-component-suites/dash_renderer/dash_renderer.v1_2_3m1580483115.min.js"></script>
            <script id="_dash-renderer" type="application/javascript">var renderer = new DashRenderer();</script>
        </footer>
    </body>
</html>
</code>```

答: I found the fix. When I did closer look to the IIS settings, I've find out that the it was running as an application of the main website rather then as a main website of IIS. When I switched it to the main website it could find the paths to the required *.js and it can run the webpage without any issue.</p>

Body:
I am trying to setup a Dash App on Flask with the IIS server and WFastCGI on Anaconda. What I could be missing so that it cannot find the required JS? I've tested plain Flask apps on the server and it works okay.

IIS server version: 8.0

Flask=1.1.1

Dash=1.8.0

python 3.6.8

I have also tried with app.css.config.serve_locally = False and app.scripts.config.serve_locally = False But it doesn't work whether both are true/false.

I've tried below variant too for creating server and the app object.

server = flask.Flask(__name__)
app = dash.Dash(__name__, server=server)

Below is my code.

import dash
import dash_core_components as dcc
import dash_html_components as html

# external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__)#, external_stylesheets=external_stylesheets)
server = app.server
app.css.config.serve_locally = True
app.scripts.config.serve_locally = True

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for Python.
    '''),

    dcc.Graph(
        id='example-graph',
        figure={
            'data': [
                {'x': [1, 2, 3], 'y': [4, 1, 2], 'type': 'bar', 'name': 'SF'},
                {'x': [1, 2, 3], 'y': [2, 4, 5], 'type': 'bar', 'name': u'Montréal'},
            ],
            'layout': {
                'title': 'Dash Data Visualization'
            }
        }
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

The errors are as below on chrome console.

GET http://127.0.0.1/_dash-component-suites/dash_renderer/polyfill@7.v1_2_3m1580483115.7.0.min.js net::ERR_ABORTED 404 (Not Found)
flask:22 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react-dom@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:21 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:23 GET http://127.0.0.1/_dash-component-suites/dash_renderer/prop-types@15.v1_2_3m1580483115.7.2.min.js net::ERR_ABORTED 404 (Not Found)
flask:24 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components.v1_7_0m1580483133.min.js net::ERR_ABORTED 404 (Not Found)
flask:25 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components-shared.v1_7_0m1580483133.js net::ERR_ABORTED 404 (Not Found)
flask:26 GET http://127.0.0.1/_dash-component-suites/dash_html_components/dash_html_components.v1_0_2m1573845875.min.js net::ERR_ABORTED 404 (Not Found)
flask:27 GET http://127.0.0.1/_dash-component-suites/dash_renderer/dash_renderer.v1_2_3m1580483115.min.js net::ERR_ABORTED 404 (Not Found)
flask:22 GET http://127.0.0.1/_dash-component-suites/dash_renderer/react-dom@16.v1_2_3m1580483115.8.6.min.js net::ERR_ABORTED 404 (Not Found)
flask:23 GET http://127.0.0.1/_dash-component-suites/dash_renderer/prop-types@15.v1_2_3m1580483115.7.2.min.js net::ERR_ABORTED 404 (Not Found)
flask:24 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components.v1_7_0m1580483133.min.js net::ERR_ABORTED 404 (Not Found)
flask:25 GET http://127.0.0.1/_dash-component-suites/dash_core_components/dash_core_components-shared.v1_7_0m1580483133.js net::ERR_ABORTED 404 (Not Found)
flask:26 GET http://127.0.0.1/_dash-component-suites/dash_html_components/dash_html_components.v1_0_2m1573845875.min.js net::ERR_ABORTED 404 (Not Found)
flask:27 GET http://127.0.0.1/_dash-component-suites/dash_renderer/dash_renderer.v1_2_3m1580483115.min.js net::ERR_ABORTED 404 (Not Found)
flask:28 Uncaught ReferenceError: DashRenderer is not defined
    at flask:28

The generated webpage code as below:

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta charset="UTF-8">
        <title>Dash</title>
        <link rel="icon" type="image/x-icon" href="/_favicon.ico?v=1.8.0">

        Loading...


问:
Make array consecutive
i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

```<code>Example

For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

Input/Output

[time limit] 4000ms (js)
[input] array.integer statues

An array of distinct non-negative integers.

Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.

[output] integer
</code>```

The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

and here is my code :

```<code>function makeArrayConsecutive2(statues) {
 //range the table from min to max
 var rang=statues.sort();
 var some=0;
 //if the table is one element
 if(rang.length-1==0){
  return 0;

 }else{
  //if the table contain more then one element
  for(i=0;i<=rang.length-2;i++){
   //add the deference of two consecutive position -1
   //to find the number of missing numbers
   some+=(rang[i+1]-rang[i]-1);
 }
  return some;
 }
}
</code>```

答:
Best solution goes here in just O(1) complexity: </p>

```<code>let n = statues.length;
let max = Math.max.apply(null, statues);
let min = Math.min.apply(null, statues);
return max - min - n + 1;
</code>```

Title: Make array consecutive

Body:
i got stucked in a chalenge in codeFights.my code pass the simple test and fail in just 2 from five of hidden tests her is the chalenge instruction:

Ratiorg got statues of different sizes as a present from CodeMaster for his birthday, each statue having an non-negative integer size. Since he likes to make things perfect, he wants to arrange them from smallest to largest so that each statue will be bigger than the previous one exactly by 1. He may need some additional statues to be able to accomplish that. Help him figure out the minimum number of additional statues needed.

Example

For statues = [6, 2, 3, 8], the output should be
makeArrayConsecutive2(statues) = 3.

Ratiorg needs statues of sizes 4, 5 and 7.

Input/Output

[time limit] 4000ms (js)
[input] array.integer statues

An array of distinct non-negative integers.

Constraints:
1 ≤ statues.length ≤ 10,
0 ≤ statues[i] ≤ 20.

[output] integer

The minimal number of statues that need to be added to existing statues such that it contains every integer size from an interval [L, R] (for some L, R) and no other sizes.

and here is my code :

function makeArrayConsecutive2(statues) {
 //range the table from min to max
 var rang=statues.sort();
 var some=0;
 //if the table is one element
 if(rang.length-1==0){
  return 0;

 }else{
  //if the table contain more then one element
  for(i=0;i<=rang.length-2;i++){
   //add the deference of two consecutive position -1
   //to find the number of missing numbers
   some+=(rang[i+1]-rang[i]-1);
 }
  return some;
 }
}

Body:
Best solution goes here in just O(1) complexity:

let n = statues.length;
let max = Math.max.apply(null, statues);
let min = Math.min.apply(null, statues);
return max - min - n + 1;


问:
Some troubles with deploying vue.js to heroku
I tried to deploy spring-boot web-application and vue-cli as frontend.
Spring hasn't problems.

There is problem with node build/build.js.

link on github - https://github.com/stepan09/courseworkSV

There is my build log.

```<code>[INFO] Running 'npm install' in /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [WARNING] npm WARN bootstrap@4.1.1 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
   [ERROR]
   [INFO] up to date in 2.729s
   [INFO]
   [INFO] --- frontend-maven-plugin:1.6:npm (npm run build) @ sport-app ---
   [INFO] Running 'npm run build' in /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [INFO]
   [INFO] > sport-app@1.0.0 build /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [INFO] > node build/build.js
   [INFO]
   [ERROR] internal/modules/cjs/loader.js:550
   [ERROR]     throw err;
   [ERROR]     ^
   [ERROR]
   [ERROR] Error: Cannot find module 'chalk'
   [ERROR]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
   [ERROR]     at Function.Module._load (internal/modules/cjs/loader.js:475:25)
   [ERROR]     at Module.require (internal/modules/cjs/loader.js:598:17)
   [ERROR]     at require (internal/modules/cjs/helpers.js:11:18)
   [ERROR]     at Object.<anonymous> (/tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app/build/check-versions.js:2:15)
   [ERROR]     at Module._compile (internal/modules/cjs/loader.js:654:30)
   [ERROR]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
   [ERROR]     at Module.load (internal/modules/cjs/loader.js:566:32)
   [ERROR]     at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
   [ERROR]     at Function.Module._load (internal/modules/cjs/loader.js:498:3)
   [ERROR] npm ERR! code ELIFECYCLE
   [ERROR] npm ERR! errno 1
   [ERROR] npm ERR! sport-app@1.0.0 build: `node build/build.js`
   [ERROR] npm ERR! Exit status 1
   [ERROR] npm ERR!
   [ERROR] npm ERR! Failed at the sport-app@1.0.0 build script.
   [ERROR] npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
   [ERROR]
   [ERROR] npm ERR! A complete log of this run can be found in:
   [ERROR] npm ERR!     /app/.npm/_logs/2018-05-30T18_07_35_898Z-debug.log
   [INFO] ------------------------------------------------------------------------
   [INFO] Reactor Summary:
   [INFO]
   [INFO] coursework ......................................... SUCCESS [  2.843 s]
   [INFO] sport-app .......................................... FAILURE [ 15.478 s]
   [INFO] sport .............................................. SKIPPED
   [INFO] ------------------------------------------------------------------------
   [INFO] BUILD FAILURE
   [INFO] ------------------------------------------------------------------------
   [INFO] Total time: 20.496 s
   [INFO] Finished at: 2018-05-30T18:07:35+00:00
   [INFO] Final Memory: 34M/269M
   [INFO] ------------------------------------------------------------------------
   [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:npm (npm run build) on project sport-app: Failed to run task: 'npm run build' failed. org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
   [ERROR]
   [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
   [ERROR] Re-run Maven using the -X switch to enable full debug logging.
   [ERROR]
   [ERROR] For more information about the errors and possible solutions, please read the following articles:
   [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
   [ERROR]
   [ERROR] After correcting the problems, you can resume the build with the command
   [ERROR]   mvn <goals> -rf :sport-app
</code>```

!     ERROR: Failed to build app with Maven
       We're sorry this build is failing! If you can't find the issue in application code,
       please submit a ticket so we can help: https://help.heroku.com/
 !     Push rejected, failed to compile Java app.
 !     Push failed

答: Deleting 'yarn.lock' worked for me</p>

Body:
I tried to deploy spring-boot web-application and vue-cli as frontend.
Spring hasn't problems.

There is problem with node build/build.js.

link on github - https://github.com/stepan09/courseworkSV

There is my build log.

[INFO] Running 'npm install' in /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [WARNING] npm WARN bootstrap@4.1.1 requires a peer of jquery@1.9.1 - 3 but none is installed. You must install peer dependencies yourself.
   [ERROR]
   [INFO] up to date in 2.729s
   [INFO]
   [INFO] --- frontend-maven-plugin:1.6:npm (npm run build) @ sport-app ---
   [INFO] Running 'npm run build' in /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [INFO]
   [INFO] > sport-app@1.0.0 build /tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app
   [INFO] > node build/build.js
   [INFO]
   [ERROR] internal/modules/cjs/loader.js:550
   [ERROR]     throw err;
   [ERROR]     ^
   [ERROR]
   [ERROR] Error: Cannot find module 'chalk'
   [ERROR]     at Function.Module._resolveFilename (internal/modules/cjs/loader.js:548:15)
   [ERROR]     at Function.Module._load (internal/modules/cjs/loader.js:475:25)
   [ERROR]     at Module.require (internal/modules/cjs/loader.js:598:17)
   [ERROR]     at require (internal/modules/cjs/helpers.js:11:18)
   [ERROR]     at Object.<anonymous> (/tmp/build_31b7d0935e35bcd3ec6a6bff51ee1bad/sport-app/build/check-versions.js:2:15)
   [ERROR]     at Module._compile (internal/modules/cjs/loader.js:654:30)
   [ERROR]     at Object.Module._extensions..js (internal/modules/cjs/loader.js:665:10)
   [ERROR]     at Module.load (internal/modules/cjs/loader.js:566:32)
   [ERROR]     at tryModuleLoad (internal/modules/cjs/loader.js:506:12)
   [ERROR]     at Function.Module._load (internal/modules/cjs/loader.js:498:3)
   [ERROR] npm ERR! code ELIFECYCLE
   [ERROR] npm ERR! errno 1
   [ERROR] npm ERR! sport-app@1.0.0 build: `node build/build.js`
   [ERROR] npm ERR! Exit status 1
   [ERROR] npm ERR!
   [ERROR] npm ERR! Failed at the sport-app@1.0.0 build script.
   [ERROR] npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
   [ERROR]
   [ERROR] npm ERR! A complete log of this run can be found in:
   [ERROR] npm ERR!     /app/.npm/_logs/2018-05-30T18_07_35_898Z-debug.log
   [INFO] ------------------------------------------------------------------------
   [INFO] Reactor Summary:
   [INFO]
   [INFO] coursework ......................................... SUCCESS [  2.843 s]
   [INFO] sport-app .......................................... FAILURE [ 15.478 s]
   [INFO] sport .............................................. SKIPPED
   [INFO] ------------------------------------------------------------------------
   [INFO] BUILD FAILURE
   [INFO] ------------------------------------------------------------------------
   [INFO] Total time: 20.496 s
   [INFO] Finished at: 2018-05-30T18:07:35+00:00
   [INFO] Final Memory: 34M/269M
   [INFO] ------------------------------------------------------------------------
   [ERROR] Failed to execute goal com.github.eirslett:frontend-maven-plugin:1.6:npm (npm run build) on project sport-app: Failed to run task: 'npm run build' failed. org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1) -> [Help 1]
   [ERROR]
   [ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
   [ERROR] Re-run Maven using the -X switch to enable full debug logging.
   [ERROR]
   [ERROR] For more information about the errors and possible solutions, please read the following articles:
   [ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoFailureException
   [ERROR]
   [ERROR] After correcting the problems, you can resume the build with the command
   [ERROR]   mvn <goals> -rf :sport-app

!     ERROR: Failed to build app with Maven
       We're sorry this build is failing! If you can't find the issue in application code,
       please submit a ticket so we can help: https://help.heroku.com/
 !     Push rejected, failed to compile Java app.
 !     Push failed

Body: Deleting 'yarn.lock' worked for me


问:
Docker: disable caching for a specific stage
I have a multi-stage Dockerfile. In stage one, I git clone from a github repo. In later stage, I do other stuff like pip etc and use a file from stage 1. I'd like to only disable caching for the first stage.

It looks like docker build --target stage1 --no-cache doesn't do what I want.

Is there a way to disable only a certain stage?

My Dockerfile looks like this:

```<code>FROM yijian/git-alpine
WORKDIR /tmp
RUN git clone https://github.com/abc/abc.git

FROM python:3.5.3-slim

RUN mkdir /app
ADD requirements.txt /app
ADD pip/pip.conf /root/.pip/pip.conf
WORKDIR /app
RUN pip3 install --upgrade pip && \
    pip3 install pbr && \
    pip3 install -r requirements.txt
ADD server.py /app
ADD docker/start.sh /app
RUN chmod a+x /app/start.sh
COPY --from=0 /tmp/abc/directory /usr/local/lib/python3.5/site-packages/abc/directory

EXPOSE 9092
ENTRYPOINT ["./start.sh"]
</code>```

答:
If your earlier stages change more often than the later ones you might want to consider reversing the order of the stages.

Stage 1. Setup your environment with pip (possibly in an virtual env).

Stage 2. copy environment files for virtual env from previous stage & then do git clone.

As long as your stage 1 doesn't need to change the cache can be used there and only the git clone part will be updated.

Body:
I have a multi-stage Dockerfile. In stage one, I git clone from a github repo. In later stage, I do other stuff like pip etc and use a file from stage 1. I'd like to only disable caching for the first stage.

It looks like docker build --target stage1 --no-cache doesn't do what I want.

Is there a way to disable only a certain stage?

My Dockerfile looks like this:

FROM yijian/git-alpine
WORKDIR /tmp
RUN git clone https://github.com/abc/abc.git

FROM python:3.5.3-slim

RUN mkdir /app
ADD requirements.txt /app
ADD pip/pip.conf /root/.pip/pip.conf
WORKDIR /app
RUN pip3 install --upgrade pip && \
    pip3 install pbr && \
    pip3 install -r requirements.txt
ADD server.py /app
ADD docker/start.sh /app
RUN chmod a+x /app/start.sh
COPY --from=0 /tmp/abc/directory /usr/local/lib/python3.5/site-packages/abc/directory

EXPOSE 9092
ENTRYPOINT ["./start.sh"]


问:
Variables within app.config/web.config
Is it is possible to do something like the following in the app.config or web.config files?

```<code><appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>
</code>```

I then want to access Dir2 in my code by simply saying:

```<code> ConfigurationManager.AppSettings["Dir2"]
</code>```

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

答:
I thought I just saw this question.

In short, no, there's no variable interpolation within an application configuration.

You have two options

You could roll your own to substitute variables at runtime

At build time, massage the application configuration to the particular specifics of the target deployment environment. Some details on this at dealing with the configuration-nightmare

OwnerDisplayName: DeeStackOverflow

ContentLicense: CC BY-SA 2.5

Title: Variables within app.config/web.config

Body:
Is it is possible to do something like the following in the app.config or web.config files?

<appSettings>
 <add key="MyBaseDir" value="C:\MyBase" />
 <add key="Dir1" value="[MyBaseDir]\Dir1"/>
 <add key="Dir2" value="[MyBaseDir]\Dir2"/>
</appSettings>

I then want to access Dir2 in my code by simply saying:

 ConfigurationManager.AppSettings["Dir2"]

This will help me when I install my application in different servers and locations wherein I will only have to change ONE entry in my entire app.config.
(I know I can manage all the concatenation in code, but I prefer it this way).

LastEditorDisplayName: LFSR Consulting

OwnerDisplayName: Scott Weinstein


问:
How to wait until a job is done or a file is updated in airflow
I am trying to use apache-airflow, with google cloud-composer, to shedule batch processing that result in the training of a model with google ai platform. I failed to use airflow operators as I explain in this question unable to specify master_type in MLEngineTrainingOperator

Using the command line I managed to launch a job successfully.
So now my issue is to integrate this command in airflow.

Using BashOperator I can train the model but I need to wait for the job to be completed before creating a version and setting it as the default. This DAG create a version before the job is done

    bash_command_train = "gcloud ai-platform jobs submit training training_job_name " \
                         "--packages=gs://path/to/the/package.tar.gz " \
                         "--python-version=3.5 --region=europe-west1 --runtime-version=1.14" \
                         " --module-name=trainer.train --scale-tier=CUSTOM --master-machine-type=n1-highmem-16"
    bash_train_operator = BashOperator(task_id='train_with_bash_command',
                                       bash_command=bash_command_train,
                                       dag=dag,)

    ...
    create_version_op = MLEngineVersionOperator(
        task_id='create_version',
        project_id=PROJECT,
        model_name=MODEL_NAME,
        version={
            'name': version_name,
            'deploymentUri': export_uri,
            'runtimeVersion': RUNTIME_VERSION,
            'pythonVersion': '3.5',
            'framework': 'SCIKIT_LEARN',
        },
        operation='create')

    set_version_default_op = MLEngineVersionOperator(
        task_id='set_version_as_default',
        project_id=PROJECT,
        model_name=MODEL_NAME,
        version={'name': version_name},
        operation='set_default')

    # Ordering the tasks
    bash_train_operator >> create_version_op >> set_version_default_op
```

The training result in updating of a file in Gcloud storage. So I am looking for an operator or a sensor that will wait until this file is updated, I noticed GoogleCloudStorageObjectUpdatedSensor, but I dont know how to make it retry until this file is updated.
An other solution would be to check for the job to be completed, but I can't find how too.

Any help would be greatly appreciated.

答:
The Google Cloud documentation for the --stream-logs flag:

"Block until job completion and stream the logs while the job runs."

Add this flag to bash_command_train and I think it should solve your problem. The command should only release once the job is finished, then Airflow will mark it as success. It will also let you monitor your training job's logs in Airflow.

Body:
I am trying to use apache-airflow, with google cloud-composer, to shedule batch processing that result in the training of a model with google ai platform. I failed to use airflow operators as I explain in this question unable to specify master_type in MLEngineTrainingOperator

Using the command line I managed to launch a job successfully.
So now my issue is to integrate this command in airflow.

Using BashOperator I can train the model but I need to wait for the job to be completed before creating a version and setting it as the default. This DAG create a version before the job is done

    bash_command_train = "gcloud ai-platform jobs submit training training_job_name " \
                         "--packages=gs://path/to/the/package.tar.gz " \
                         "--python-version=3.5 --region=europe-west1 --runtime-version=1.14" \
                         " --module-name=trainer.train --scale-tier=CUSTOM --master-machine-type=n1-highmem-16"
    bash_train_operator = BashOperator(task_id='train_with_bash_command',
                                       bash_command=bash_command_train,
                                       dag=dag,)

    ...
    create_version_op = MLEngineVersionOperator(
        task_id='create_version',
        project_id=PROJECT,
        model_name=MODEL_NAME,
        version={
            'name': version_name,
            'deploymentUri': export_uri,
            'runtimeVersion': RUNTIME_VERSION,
            'pythonVersion': '3.5',
            'framework': 'SCIKIT_LEARN',
        },
        operation='create')

    set_version_default_op = MLEngineVersionOperator(
        task_id='set_version_as_default',
        project_id=PROJECT,
        model_name=MODEL_NAME,
        version={'name': version_name},
        operation='set_default')

    # Ordering the tasks
    bash_train_operator >> create_version_op >> set_version_default_op

The training result in updating of a file in Gcloud storage. So I am looking for an operator or a sensor that will wait until this file is updated, I noticed GoogleCloudStorageObjectUpdatedSensor, but I dont know how to make it retry until this file is updated.
An other solution would be to check for the job to be completed, but I can't find how too.

Any help would be greatly appreciated.


问:
VLookup between dates, in combination with sumproduct
This is the spreadsheet in question.

I need to calculate the FTEs (employee full time equivalents) for multiple projects, over time. Employees keep changing number of week-hours over time (sheet "Employees Import"), with maximum week hours is 40. So someone working 40 hrs a week has a FTE of 1.

I'm trying to write a formula that would fill the yellow cells. I don't think it's possible to be achieved using array formulas, so I don't have a problem with copying the formula for each week and each project. But the challenge for me is to do the sumproduct operation that includes a VLOOKUP with Employee match AND date between match at the same time. Maybe someone can help out.

EDIT: I've had a bit success with this formula:

```<code>=SUMPRODUCT({K19:K21}; ARRAYFORMULA(VLOOKUP($F19:$F21;    SORT(   FILTER({'Employees Import'!$A$1:$A\'Employees Import'!$E$1:$E\'Employees Import'!$F$1:$F\'Employees Import'!$G$1:$G}; ('Employees Import'!$F$1:$F<K$4)*(  IF('Employees Import'!$G$1:$G=""; DATE(2030;12;31); 'Employees Import'!$G$1:$G)    >K$4) ) )     ; 2)))/40
</code>```

答:
This formula seems to be working:

=SUMPRODUCT({K19:K21}; ARRAYFORMULA(VLOOKUP($F19:$F21;    SORT(   FILTER({'Employees Import'!$A$1:$A\'Employees Import'!$E$1:$E\'Employees Import'!$F$1:$F\'Employees Import'!$G$1:$G}; ('Employees Import'!$F$1:$F<K$4)*(  IF('Employees Import'!$G$1:$G=""; DATE(2030;12;31); 'Employees Import'!$G$1:$G)    >K$4) ) )     ; 2)))/40

Body:
This is the spreadsheet in question.

I need to calculate the FTEs (employee full time equivalents) for multiple projects, over time. Employees keep changing number of week-hours over time (sheet "Employees Import"), with maximum week hours is 40. So someone working 40 hrs a week has a FTE of 1.

I'm trying to write a formula that would fill the yellow cells. I don't think it's possible to be achieved using array formulas, so I don't have a problem with copying the formula for each week and each project. But the challenge for me is to do the sumproduct operation that includes a VLOOKUP with Employee match AND date between match at the same time. Maybe someone can help out.

EDIT: I've had a bit success with this formula:

=SUMPRODUCT({K19:K21}; ARRAYFORMULA(VLOOKUP($F19:$F21;    SORT(   FILTER({'Employees Import'!$A$1:$A\'Employees Import'!$E$1:$E\'Employees Import'!$F$1:$F\'Employees Import'!$G$1:$G}; ('Employees Import'!$F$1:$F<K$4)*(  IF('Employees Import'!$G$1:$G=""; DATE(2030;12;31); 'Employees Import'!$G$1:$G)    >K$4) ) )     ; 2)))/40


问:
Parameter set cannot be resolved using the specified named parameters
In the below script either the -live or -test parameters should be required. However, the script will run without either switch. If I use one of those parameters I get the below error. Why is it not requiring either -live or -test and why is it failing if I use one of them?

C:\Users\Administrator\Documents\Disable-ADAccounts.ps1 : Parameter set cannot be resolved using the specified named parameters.
  At line:1 char:1
  + . .\Disable-ADAccounts.ps1 -days 7 -all -live
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (:) [Disable-ADAccounts.ps1], ParameterBindingException
      + FullyQualifiedErrorId : AmbiguousParameterSet,Disable-ADAccounts.ps1

```<code>    [CmdletBinding()]
    param (
    [Parameter(Mandatory = $true, ParameterSetName = 'UsersOnly')]
    [Switch]
    $usersOnly,

    [Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnly')]
    [Switch]
    $computersOnly,

    [Parameter(Mandatory = $true, ParameterSetName = 'All')]
    [Switch]
    $all,

    [Parameter(Mandatory=$true)]
    [string]
    $days,

    [switch]
    $console,

    [Parameter(Mandatory = $true, ParameterSetName = 'Test')]
    [switch]
    $test,

    [Parameter(Mandatory = $true, ParameterSetName = 'Live')]
    [switch]
    $live
)

Process {
    $DC = Get-ADDomainController
    $OUs = Get-ADOrganizationalUnit -Filter * # Uncomment this line to search ALL OUs.  Comment Next Variable.
    #$OUs = Get-ADOrganizationalUnit -Filter 'Name -eq "test"' # Use this line to test on a single OU
    $TimeStamp = get-date -format D
    $description = "Disabled on " + $TimeStamp
    $noDisableComputer =  Get-ADGroupMember -Identity DoNotDisableComputers -Recursive | Select -ExpandProperty Name
    $noDisableUser =  Get-ADGroupMember -Identity DoNotDisableUsers -Recursive | Select -ExpandProperty Name
    $noDisable = $noDisableComputer+$noDisableUser
    $CurrentDate = Get-Date
    $CurrentDate = $CurrentDate.ToString('yyMMdd_hhmmss')
    $tempDir = [System.Environment]::GetEnvironmentVariable('TEMP','Machine')
    $logFile = $tempDir + "\DisabledAccounts_$CurrentDate.csv"

    # If -test switch is used enable -WhatIf parameter.
    If($test) { $whatIf = @{ WhatIf = $true } }
    ElseIf($live) { $whatIf = @{ WhatIf = $false } }

    # Set parameter to UsersOnly, ComputersOnly, or do not use a perameter
    If($usersOnly) { $scope = @{ UsersOnly = $true } }
    ElseIf($computersOnly) { $scope = @{ ComputersOnly =$true } }
    ElseIf($all) { $scope = @{} }

    # Disable User and/or Computer Objects inactive for XX days.

    # Iterate through Organizational Units
    foreach ($OU in $OUs) {

        # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
        $days = $days + "D"
        $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope
        foreach($account in $accounts){
            If ($noDisable -notcontains $account.Name) {
                Write-Host $account
        #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
           }
        }
    }
}

        # Move Disabled Users to Disabled Users OU & Add Timestamp to Description
        #Search-ADAccount –AccountDisabled –ComputersOnly –SearchBase $OU.DistinguishedName | Foreach-object {
            #Set-ADComputer $_ -Description $description -Verbose -WhatIf
            #Move-ADObject $_ –TargetPath “OU=Disabled Computers, DC=COH,DC=net” -Verbose -WhatIf
        #}
    #}
</code>```

答:
I think you have confused yourself about parameter sets.  What you have done is created five distinct parameter sets, and only one of those five can be active at any time.  If I read your intent correctly, what you need is the ability to do any of the following:

```<code> \Disable-ADAccounts.ps1 -days 7 -all -live
 \Disable-ADAccounts.ps1 -days 7 -UsersOnly -live
 \Disable-ADAccounts.ps1 -days 7 -ComputersOnly -live
 \Disable-ADAccounts.ps1 -days 7 -all -test
 \Disable-ADAccounts.ps1 -days 7 -UsersOnly -test
 \Disable-ADAccounts.ps1 -days 7 -ComputersOnly -test
</code>```

If that is the case, you need six different parameter groups, not five.  Each of your parameters should be a member of the groups it is needed in, so something like this:

```<code>[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyTest')]
[Switch]
$usersOnly,

[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyTest')]
[Switch]
$computersOnly,

[Parameter(Mandatory = $true, ParameterSetName = 'AllLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'AllTest')]
[Switch]
$all,

[Parameter(Mandatory=$true)]
[string]
$days,

[switch]
$console,

[Parameter(Mandatory = $true, ParameterSetName = 'AllTest')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyTest')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyTest')]
[switch]
$test,

[Parameter(Mandatory = $true, ParameterSetName = 'AllLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyLive')]
[switch]
$live
</code>```

See this Microsoft article for more information about Parameter Sets.

I hope this helps.

Body:
In the below script either the -live or -test parameters should be required. However, the script will run without either switch. If I use one of those parameters I get the below error. Why is it not requiring either -live or -test and why is it failing if I use one of them?

C:\Users\Administrator\Documents\Disable-ADAccounts.ps1 : Parameter set cannot be resolved using the specified named parameters.
  At line:1 char:1
  + . .\Disable-ADAccounts.ps1 -days 7 -all -live
  + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
      + CategoryInfo          : InvalidArgument: (:) [Disable-ADAccounts.ps1], ParameterBindingException
      + FullyQualifiedErrorId : AmbiguousParameterSet,Disable-ADAccounts.ps1

    [CmdletBinding()]
    param (
    [Parameter(Mandatory = $true, ParameterSetName = 'UsersOnly')]
    [Switch]
    $usersOnly,

    [Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnly')]
    [Switch]
    $computersOnly,

    [Parameter(Mandatory = $true, ParameterSetName = 'All')]
    [Switch]
    $all,

    [Parameter(Mandatory=$true)]
    [string]
    $days,

    [switch]
    $console,

    [Parameter(Mandatory = $true, ParameterSetName = 'Test')]
    [switch]
    $test,

    [Parameter(Mandatory = $true, ParameterSetName = 'Live')]
    [switch]
    $live
)

Process {
    $DC = Get-ADDomainController
    $OUs = Get-ADOrganizationalUnit -Filter * # Uncomment this line to search ALL OUs.  Comment Next Variable.
    #$OUs = Get-ADOrganizationalUnit -Filter 'Name -eq "test"' # Use this line to test on a single OU
    $TimeStamp = get-date -format D
    $description = "Disabled on " + $TimeStamp
    $noDisableComputer =  Get-ADGroupMember -Identity DoNotDisableComputers -Recursive | Select -ExpandProperty Name
    $noDisableUser =  Get-ADGroupMember -Identity DoNotDisableUsers -Recursive | Select -ExpandProperty Name
    $noDisable = $noDisableComputer+$noDisableUser
    $CurrentDate = Get-Date
    $CurrentDate = $CurrentDate.ToString('yyMMdd_hhmmss')
    $tempDir = [System.Environment]::GetEnvironmentVariable('TEMP','Machine')
    $logFile = $tempDir + "\DisabledAccounts_$CurrentDate.csv"

    # If -test switch is used enable -WhatIf parameter.
    If($test) { $whatIf = @{ WhatIf = $true } }
    ElseIf($live) { $whatIf = @{ WhatIf = $false } }

    # Set parameter to UsersOnly, ComputersOnly, or do not use a perameter
    If($usersOnly) { $scope = @{ UsersOnly = $true } }
    ElseIf($computersOnly) { $scope = @{ ComputersOnly =$true } }
    ElseIf($all) { $scope = @{} }

    # Disable User and/or Computer Objects inactive for XX days.

    # Iterate through Organizational Units
    foreach ($OU in $OUs) {

        # Search for User and/or Computer Objects inactive for XX days.  Disable object if not in DoNotDisable Security Groups
        $days = $days + "D"
        $accounts = Search-ADAccount -SearchBase $OU.DistinguishedName -SearchScope OneLevel -AccountInactive -TimeSpan ([timespan]7D) @scope
        foreach($account in $accounts){
            If ($noDisable -notcontains $account.Name) {
                Write-Host $account
        #        #Disable-ADAccount -Identity $account.DistinguishedName -Verbose $whatIf | Export-Csv $logFile
           }
        }
    }
}

        # Move Disabled Users to Disabled Users OU & Add Timestamp to Description
        #Search-ADAccount –AccountDisabled –ComputersOnly –SearchBase $OU.DistinguishedName | Foreach-object {
            #Set-ADComputer $_ -Description $description -Verbose -WhatIf
            #Move-ADObject $_ –TargetPath “OU=Disabled Computers, DC=COH,DC=net” -Verbose -WhatIf
        #}
    #}

Body:
I think you have confused yourself about parameter sets.  What you have done is created five distinct parameter sets, and only one of those five can be active at any time.  If I read your intent correctly, what you need is the ability to do any of the following:

 \Disable-ADAccounts.ps1 -days 7 -all -live
 \Disable-ADAccounts.ps1 -days 7 -UsersOnly -live
 \Disable-ADAccounts.ps1 -days 7 -ComputersOnly -live
 \Disable-ADAccounts.ps1 -days 7 -all -test
 \Disable-ADAccounts.ps1 -days 7 -UsersOnly -test
 \Disable-ADAccounts.ps1 -days 7 -ComputersOnly -test

If that is the case, you need six different parameter groups, not five.  Each of your parameters should be a member of the groups it is needed in, so something like this:

[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyTest')]
[Switch]
$usersOnly,

[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyTest')]
[Switch]
$computersOnly,

[Parameter(Mandatory = $true, ParameterSetName = 'AllLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'AllTest')]
[Switch]
$all,

[Parameter(Mandatory=$true)]
[string]
$days,

[switch]
$console,

[Parameter(Mandatory = $true, ParameterSetName = 'AllTest')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyTest')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyTest')]
[switch]
$test,

[Parameter(Mandatory = $true, ParameterSetName = 'AllLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'UsersOnlyLive')]
[Parameter(Mandatory = $true, ParameterSetName = 'ComputersOnlyLive')]
[switch]
$live

See this Microsoft article for more information about Parameter Sets.

I hope this helps.


问:
Unable to run python code from Linux command line
I have gone through the explanations given in this forum and have tried them in my program. However, none of the suggestions worked. That's why I am opening this thread.

Below is the tree for my project. There are 2 packages: com and main.

When I try to run the code for ProcessRiskModelbyRecordID.py from command line, I am getting below error message:

$ python3 /AppDev/XXXX/py/riskScore/main/ProcessRiskModelbyRecordID.py

Traceback (most recent call last):
File "/AppDev/XXXX/py/riskScore/main/ProcessRiskModelbyRecordID.py", line 6, in
    from main.ConnectAPI import *
ModuleNotFoundError: No module named 'main'

When I run the same code from PyDev, I am able to execute it.

Below is the import code from ProcessRiskModelbyRecordID.py:

from main.ConnectAPI import *
from com import DBOperations as DBO,SourceProfile,TargetProfile

Can you please help so that I can run this code from command line?

答:
PyDev is probably setting PYTHONPATH for you. On the command line you would need to set it yourself:

```<code>cd riskScore
export PYTHONPATH=`pwd`
python3 main/ProcessRiskModelbyRecordID.py
</code>```

Body:
PyDev is probably setting PYTHONPATH for you. On the command line you would need to set it yourself:

cd riskScore
export PYTHONPATH=`pwd`
python3 main/ProcessRiskModelbyRecordID.py


问:
How to extract substring from directory name using bash
I have a group of directories with the following name template:

[random combination of numbers and/or characters and/or symbols(including blank space)]+[single space]+[(]+[number]+[)].

E.g.
asdf%k123 test1 (12345)
foo(123)??bar (456)
324(asd)! (456)
random()123 (456)

How do I go about extracting only the number within parenthesis using bash commands (without '()')? Keep in mind that number within parenthesis might occur in the random part of name, but I only need the on at the end. In any case every name will end with [space][(][number][)].

答:
Get the number

You can get the last number with sed:

sed 's/.*(\([0-9]*\))$/\1/' <<< "asdf%k123 test1 (12345)"

12345

The sed script is written like this:

the beginning s means this performs a substitution, which uses the following syntax s/pattern/replacement/

the / character defines the separator for substitution, you can use any character but / is a very common one

.*(\([0-9]*\))$ is the pattern (I will get back to it later)

\1 is the replacement, in this case it replaces the first string captured by the pattern, which is the number (see below)

The key element is the pattern. In this case .*(\([0-9]*\))$ could be split as:

.* which matches any character any number of times

( which matches the opening brace character

\([0-9]*\) which captures any string composed by digits, a.k.a. a number

) which matches the closing brace character

$ which matches the end of the line

In the capture pattern, i.e. (\([0-9]*\), it should be noted that \( and \) are the delimiters for capturing and should not be mistaken with ( and ) which are regular parentheses characters.

TL;DR: this pattern says “I want to capture a number surrounded by parentheses just before the end of the line”. And the sed script says “I want to print exclusively the number that was captured”.

List directories

You can parse the directories using find. If you just want the first level subfolders:

find /path/to/dir -mindepth 1 -maxdepth 1 -type d

The -mindepth 1 -maxdepth 1 options ensures that you only get children of 1 depth, while the -type d option lists only the directories (not files, not symbolic links, etc.).

You can get more depths by replacing -maxdepth 1 with the number of your choice, or simply omit this option to get all subfolders recursively.

Since your directories seem to have all sort of special characters, I would also suggest to get them with the -print0 option which separate the result with a null character \0 instead of a newline.

Solution

All in all it would look like this:

```<code>find /path/to/dir -mindepth 1 -maxdepth 1 -type d -print0 |
  while IFS= read -r -d '' dirname
  do
    sed 's/.*(\([0-9]*\))$/\1/' <<< $dirname
  done
</code>```

If you want to filter out the directories that do not match your pattern, you may change sed to use the -n option and then print with the p command:

```<code>find /path/to/dir -mindepth 1 -maxdepth 1 -type d -print0 |
  while IFS= read -r -d '' dirname
  do
    sed -n 's/.*(\([0-9]*\))$/\1/p' <<< $dirname
  done
</code>```

Body:
Get the number

You can get the last number with sed:

sed 's/.*(\([0-9]*\))$/\1/' <<< "asdf%k123 test1 (12345)"

12345

The sed script is written like this:

the beginning s means this performs a substitution, which uses the following syntax s/pattern/replacement/

the / character defines the separator for substitution, you can use any character but / is a very common one

.*(\([0-9]*\))$ is the pattern (I will get back to it later)

\1 is the replacement, in this case it replaces the first string captured by the pattern, which is the number (see below)

The key element is the pattern. In this case .*(\([0-9]*\))$ could be split as:

.* which matches any character any number of times

( which matches the opening brace character

\([0-9]*\) which captures any string composed by digits, a.k.a. a number

) which matches the closing brace character

$ which matches the end of the line

In the capture pattern, i.e. (\([0-9]*\), it should be noted that \( and \) are the delimiters for capturing and should not be mistaken with ( and ) which are regular parentheses characters.

TL;DR: this pattern says “I want to capture a number surrounded by parentheses just before the end of the line”. And the sed script says “I want to print exclusively the number that was captured”.

List directories

You can parse the directories using find. If you just want the first level subfolders:

find /path/to/dir -mindepth 1 -maxdepth 1 -type d

The -mindepth 1 -maxdepth 1 options ensures that you only get children of 1 depth, while the -type d option lists only the directories (not files, not symbolic links, etc.).

You can get more depths by replacing -maxdepth 1 with the number of your choice, or simply omit this option to get all subfolders recursively.

Since your directories seem to have all sort of special characters, I would also suggest to get them with the -print0 option which separate the result with a null character \0 instead of a newline.

Solution

All in all it would look like this:

find /path/to/dir -mindepth 1 -maxdepth 1 -type d -print0 |
  while IFS= read -r -d '' dirname
  do
    sed 's/.*(\([0-9]*\))$/\1/' <<< $dirname
  done

If you want to filter out the directories that do not match your pattern, you may change sed to use the -n option and then print with the p command:

find /path/to/dir -mindepth 1 -maxdepth 1 -type d -print0 |
  while IFS= read -r -d '' dirname
  do
    sed -n 's/.*(\([0-9]*\))$/\1/p' <<< $dirname
  done


问:
How to set android wallpaper
I am wondering if someone can help. I would like to create a simple wallpaper test app. I have tried a few things with no success. Eventually, I started playing with gallery codes and have a few achievements. But ... I am not sure how to attach a wallpaper function to the gallery. I am new to all this (I am only a few months into learning Droid apps with eclipse) is there someplace where I can find complete Java coding and possibly the XML files for a working wallpaper? I cannot build from scratch but I am getting better reading the source code creating buttons etc.

Another option is how can I insert a save as wallpaper function to the working gallery I have? I am assuming I can set a long press function but I am not sure how to go about that either. I do have a tutorial for creating long presses but I am not sure about the proper Java setup to accompany this.

Any help will be appreciated. Keep in mind I am new to both Java and Android coding. In other words keep it as simple as possible please. Or if someone has a simple wallpaper app and they don't mind sharing the source code ... that would help immensely.

答:
```<code>is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(
    bitmap, parent.getWidth(), parent.getHeight(), true);
bitmap.recycle();
if(imagePath!=null){
    System.out.println("Hi I am try to open Bit map");
    wallpaperManager = WallpaperManager.getInstance(this);
    wallpaperDrawable = wallpaperManager.getDrawable();
    wallpaperManager.setBitmap(useThisBitmap);
</code>```

................................................. if you have image URI then use this

```<code>wallpaperManager = WallpaperManager.getInstance(this);
wallpaperDrawable = wallpaperManager.getDrawable();
mImageView.setImageURI(imagepath);
</code>```

.............. Let me know if there is any issue .

OwnerDisplayName: Will

Title: How to set android wallpaper

Body:
is = new FileInputStream(new File(imagePath));
bis = new BufferedInputStream(is);
Bitmap bitmap = BitmapFactory.decodeStream(bis);
Bitmap useThisBitmap = Bitmap.createScaledBitmap(
    bitmap, parent.getWidth(), parent.getHeight(), true);
bitmap.recycle();
if(imagePath!=null){
    System.out.println("Hi I am try to open Bit map");
    wallpaperManager = WallpaperManager.getInstance(this);
    wallpaperDrawable = wallpaperManager.getDrawable();
    wallpaperManager.setBitmap(useThisBitmap);

................................................. if you have image URI then use this

wallpaperManager = WallpaperManager.getInstance(this);
wallpaperDrawable = wallpaperManager.getDrawable();
mImageView.setImageURI(imagepath);

.............. Let me know if there is any issue .


问:
The name 'InitializeComponent' does not exist in the current context
If I create a new project in Visual Studio 2010 SP1 and select "WPF Application" and tries to build the generated application, I get the error

The name 'InitializeComponent' does not exist in the current context.

I got a similar error this morning when I tried to build my current project. Yesterday, I had no problem compiling and running it.

I created a new project and got the error whenever I compiled the project. I have just sent the project to a colleague, and he has just compiled without any errors.

What is wrong?

答:
What helped me - is to change first line in .csproj to</p>

```<code><Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">
</code>```

Body:
What helped me - is to change first line in .csproj to

<Project Sdk="Microsoft.NET.Sdk.WindowsDesktop">


问:
MS chart candlestick How to set tail colors
I am currently developing a candlestick chart with mschart in visual C#.
I have now created two charts and created the charts as follows

Question 1. View the Candlestick Chart at the top. I would like to apply the tail color of each rod as red or blue.

Question 2. View the bar chart at the bottom. I would like to apply Red or Blue color to this chart. I want to apply the same color to the top of the Candlestick chart. How can I do it ?

[source]

```<code>DataTable table_ChartData = new DataTable();
table_ChartData.Columns.Add("Id");
table_ChartData.Columns.Add("Open");
table_ChartData.Columns.Add("Close");
table_ChartData.Columns.Add("High");
table_ChartData.Columns.Add("Low");
table_ChartData.Columns.Add("Day");
dataGridView1.DataSource = table_ChartData;

chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = max;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = min;

chart1.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart1.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;

chart1.Series["Candle"].XValueMember = "Day";
chart1.Series["Candle"].YValueMembers = "High,Low,Open,Close,Volume";
chart1.Series["Candle"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart1.Series["Candle"].CustomProperties = "PriceDownColor=Blue,PriceUpColor=Red";
chart1.Series["Candle"]["OpenCloseStyle"] = "Triangle";
chart1.Series["Candle"]["ShowOpenClose"] = "Both";
chart1.DataSource = table_ChartData;
chart1.DataBind();

////////////////////////////////////////////////////////////

chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.Maximum = v_max + (v_max / 10);
chart2.ChartAreas["ChartArea1"].AxisY.Minimum = v_min / 2;

chart2.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart2.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart2.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;

chart2.Series["Bar"].XValueMember = "Day";
chart2.Series["Bar"].YValueMembers = "Volume";
chart2.Series["Bar"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart2.Series["Bar"].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
chart2.DataSource = table_ChartData;
chart2.DataBind();
</code>```

答:
Simple way:</p>

```<code>priceSerie.Points[index].Color = Color.Blue;
// priceSerie.Points[index].BorderColor = Color.Magenta;
</code>```

Body:
I am currently developing a candlestick chart with mschart in visual C#.
I have now created two charts and created the charts as follows

Question 1. View the Candlestick Chart at the top. I would like to apply the tail color of each rod as red or blue.

Question 2. View the bar chart at the bottom. I would like to apply Red or Blue color to this chart. I want to apply the same color to the top of the Candlestick chart. How can I do it ?

[source]

DataTable table_ChartData = new DataTable();
table_ChartData.Columns.Add("Id");
table_ChartData.Columns.Add("Open");
table_ChartData.Columns.Add("Close");
table_ChartData.Columns.Add("High");
table_ChartData.Columns.Add("Low");
table_ChartData.Columns.Add("Day");
dataGridView1.DataSource = table_ChartData;

chart1.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart1.ChartAreas["ChartArea1"].AxisY.Maximum = max;
chart1.ChartAreas["ChartArea1"].AxisY.Minimum = min;

chart1.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart1.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart1.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;

chart1.Series["Candle"].XValueMember = "Day";
chart1.Series["Candle"].YValueMembers = "High,Low,Open,Close,Volume";
chart1.Series["Candle"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart1.Series["Candle"].CustomProperties = "PriceDownColor=Blue,PriceUpColor=Red";
chart1.Series["Candle"]["OpenCloseStyle"] = "Triangle";
chart1.Series["Candle"]["ShowOpenClose"] = "Both";
chart1.DataSource = table_ChartData;
chart1.DataBind();

////////////////////////////////////////////////////////////

chart2.ChartAreas["ChartArea1"].AxisX.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.MajorGrid.LineWidth = 1;
chart2.ChartAreas["ChartArea1"].AxisY.Maximum = v_max + (v_max / 10);
chart2.ChartAreas["ChartArea1"].AxisY.Minimum = v_min / 2;

chart2.ChartAreas["ChartArea1"].AxisX.LabelAutoFitStyle = LabelAutoFitStyles.WordWrap;
chart2.ChartAreas["ChartArea1"].AxisX.IsLabelAutoFit = true;
chart2.ChartAreas["ChartArea1"].AxisX.LabelStyle.Enabled = true;

chart2.Series["Bar"].XValueMember = "Day";
chart2.Series["Bar"].YValueMembers = "Volume";
chart2.Series["Bar"].XValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Date;
chart2.Series["Bar"].YValueType = System.Windows.Forms.DataVisualization.Charting.ChartValueType.Int32;
chart2.DataSource = table_ChartData;
chart2.DataBind();

Body:
Simple way:

priceSerie.Points[index].Color = Color.Blue;
// priceSerie.Points[index].BorderColor = Color.Magenta;


问:
Migrating working sets from old to new Domino Designer installation
I am trying to migrate my working sets to a new installation. While searching the web I found this link which says that by copying the file <DATA FOLDER>\workspace\.metadata\.plugins\org.eclipse.ui.workbench\workingsets.xml we can get our original working sets back. I tried it, but it only restores my working sets and they are empty with no database inside them.

What am I missing here? Does any one know how to get all the working sets from old installation and put it into new installation of Domino Designer?

答:
http://www.lotusguru.com/lotusguru/LGBlog.nsf/d6plinks/20100310-83ESQC

The Notes client being totally closed, backup or restore the following directories :

..data/workspace/.metadata/.plugins/..

com.ibm.designer.domino.ide.resources

org.eclipse.core.resources/.projects

org.eclipse.core.resources/.root

org.eclipse.core.resources/.safetable

org.eclipse.ui.workbench


问:
Elasticsearch - how to search for part of word across all indices and documents
I want to make a search that works like this:

when I enter "Desc" for example, I want to get everything that contains "Desc", and not to be case sensitive. I don't want to include index name, or document, I want it to search across everything.

I tried this but it doesn't work very well.

GET /_search
{
  "query":
      { "query_string":
          {
            "query": "Test*"
          }
      }
}```

答:
Try using wild card search. Make sure the field you are searching is text field.

```<code>{
    "query": {
        "query_string" : {
            "query" : "*desc*"
        }
    }
}
</code>```

If you want to use all index you can query like this

```<code>curl -XGET 'http://localhost:9200/index1,index2/_search
</code>```

PS: Performance wise this is a bad idea since this searches all fields in index. Alternatively you can use use default_field in the query string and specidy the field.

Body:
Try using wild card search. Make sure the field you are searching is text field.

{
    "query": {
        "query_string" : {
            "query" : "*desc*"
        }
    }
}

If you want to use all index you can query like this

curl -XGET 'http://localhost:9200/index1,index2/_search

PS: Performance wise this is a bad idea since this searches all fields in index. Alternatively you can use use default_field in the query string and specidy the field.


问:
SSRS DateTime Parameter Format
I need to create an SSRS (2017) report with date range parameters, BeginDate and EndDate.

Context: this is a report to pull names, birthdates, and deceased dates, based on the deceased date occurring between BeginDate and EndDate.

The table I am working with stores dates in a YYYYMMDD format.

Initially I tried the simple solution of setting the parameter to DateTime format. This did not work. I am assuming it is because the local language settings put the parameter format in MMDDYYYY so selecting 02172018 to 10172019 would not produce results if all the dates in the table start with 2019(mmdd).

I don't believe adjusting the language settings would not be beneficial in this instance in the long term as there will be multiple users in multiple locations running this report so I'm guessing it wouldn't work for everyone. I'm not authorized to change the language settings on my local server for this purpose either, so that's out.

If those assumptions not correct, please advise.

So then I thought maybe if I converted the dates within the report's main dataset that it might still read it, but that didn't work either:

```<code>CASE WHEN A.birthdate = '00000000'
              THEN ''
            ELSE CASE LEN(A.birthdate)
                 WHEN 8
                  THEN CONVERT(varchar(10), CAST(A.birthdate AS datetime),21)
                 WHEN 6
                  THEN CONVERT(varchar(10), SUBSTRING(A.birthdate,1,4)+'/'+SUBSTRING(A.birthdate,5,2),21)
                 WHEN 4
                  THEN CONVERT(varchar(10), A.birthdate,21)
                 ELSE NULL
                  END
        END AS BirthDate
,CASE WHEN D.DECEASEDDATE = '00000000'
              THEN ''
            ELSE CASE LEN(D.DECEASEDDATE)
                 WHEN 8
                  THEN CONVERT(varchar(10), CAST(D.DECEASEDDATE AS datetime),21)
                 WHEN 6
                  THEN CONVERT(varchar(10), SUBSTRING(D.DECEASEDDATE,1,4)+'/'+SUBSTRING(D.DECEASEDDATE,5,2),21)
                 WHEN 4
                  THEN CONVERT(varchar(10), D.DECEASEDDATE,21)
                 ELSE NULL
                  END
        END AS DeceasedDate
</code>```

I got the following error:

"An error has occurred during report processing. Cannot read the next data row for the dataset. The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."

What else can I try to get the date parameters to work?

答:
What datatype are the birth and deceased dates in the database?

If they are date or datetime and you use a date picker for your report parameters you can compare them, the format they get displayed in should not matter as internally they are stored correctly.

As a test, create a new report, add a date parameter so the datepicker is shown. Then add a textbox to show the formatted parameter value. Use a format that uses words such as "19 February 2020" so there is not ambiguity. If this works then you should have no problems

You WHERE CLAUSE would just be something like

```<code>WHERE DeceasedDate BETWEEN @BeginDate AND @EndDate
</code>```

EDIT
Based on OP's response..

Please try the following tests and see what results you get. Assuming you get a sensible date returned, I would create a view with an additional column that converts the char(8) format dates to real date data types the based you report on that view.

```<code>DECLARE @dt char(8) = '20200201'
SELECT CAST(@dt as date)
SELECT DATEFROMPARTS(LEFT(@dt,4),SUBSTRING(@dt, 5,2),RIGHT(@dt,2))

SELECT FORMAT(CAST(@dt as date), 'dd MMMM yyyy')
</code>```

The last one is there to make sure that the days and months are being correctly interpreted.

DATEFROMPARTS should always work as you are telling it which parts of the string represent each part of the date but this is slower that the first option.

Assuming DATEFROMPARTS works, your view could just be something like

```<code>SELECT *
    , DATEFROMPARTS(LEFT(Deceased,4),SUBSTRING(Deceased, 5,2),RIGHT(Deceased,2)) as DeceasedDateNew
    FROM myTable
</code>```

Title: SSRS DateTime Parameter Format

Body:
I need to create an SSRS (2017) report with date range parameters, BeginDate and EndDate.

Context: this is a report to pull names, birthdates, and deceased dates, based on the deceased date occurring between BeginDate and EndDate.

The table I am working with stores dates in a YYYYMMDD format.

Initially I tried the simple solution of setting the parameter to DateTime format. This did not work. I am assuming it is because the local language settings put the parameter format in MMDDYYYY so selecting 02172018 to 10172019 would not produce results if all the dates in the table start with 2019(mmdd).

I don't believe adjusting the language settings would not be beneficial in this instance in the long term as there will be multiple users in multiple locations running this report so I'm guessing it wouldn't work for everyone. I'm not authorized to change the language settings on my local server for this purpose either, so that's out.

If those assumptions not correct, please advise.

So then I thought maybe if I converted the dates within the report's main dataset that it might still read it, but that didn't work either:

CASE WHEN A.birthdate = '00000000'
              THEN ''
            ELSE CASE LEN(A.birthdate)
                 WHEN 8
                  THEN CONVERT(varchar(10), CAST(A.birthdate AS datetime),21)
                 WHEN 6
                  THEN CONVERT(varchar(10), SUBSTRING(A.birthdate,1,4)+'/'+SUBSTRING(A.birthdate,5,2),21)
                 WHEN 4
                  THEN CONVERT(varchar(10), A.birthdate,21)
                 ELSE NULL
                  END
        END AS BirthDate
,CASE WHEN D.DECEASEDDATE = '00000000'
              THEN ''
            ELSE CASE LEN(D.DECEASEDDATE)
                 WHEN 8
                  THEN CONVERT(varchar(10), CAST(D.DECEASEDDATE AS datetime),21)
                 WHEN 6
                  THEN CONVERT(varchar(10), SUBSTRING(D.DECEASEDDATE,1,4)+'/'+SUBSTRING(D.DECEASEDDATE,5,2),21)
                 WHEN 4
                  THEN CONVERT(varchar(10), D.DECEASEDDATE,21)
                 ELSE NULL
                  END
        END AS DeceasedDate

I got the following error:

"An error has occurred during report processing. Cannot read the next data row for the dataset. The conversion of a varchar data type to a datetime data type resulted in an out-of-range value."

What else can I try to get the date parameters to work?

Body:
What datatype are the birth and deceased dates in the database?

If they are date or datetime and you use a date picker for your report parameters you can compare them, the format they get displayed in should not matter as internally they are stored correctly.

As a test, create a new report, add a date parameter so the datepicker is shown. Then add a textbox to show the formatted parameter value. Use a format that uses words such as "19 February 2020" so there is not ambiguity. If this works then you should have no problems

You WHERE CLAUSE would just be something like

WHERE DeceasedDate BETWEEN @BeginDate AND @EndDate

EDIT
Based on OP's response..

Please try the following tests and see what results you get. Assuming you get a sensible date returned, I would create a view with an additional column that converts the char(8) format dates to real date data types the based you report on that view.

DECLARE @dt char(8) = '20200201'
SELECT CAST(@dt as date)
SELECT DATEFROMPARTS(LEFT(@dt,4),SUBSTRING(@dt, 5,2),RIGHT(@dt,2))

SELECT FORMAT(CAST(@dt as date), 'dd MMMM yyyy')

The last one is there to make sure that the days and months are being correctly interpreted.

DATEFROMPARTS should always work as you are telling it which parts of the string represent each part of the date but this is slower that the first option.

Assuming DATEFROMPARTS works, your view could just be something like

SELECT *
    , DATEFROMPARTS(LEFT(Deceased,4),SUBSTRING(Deceased, 5,2),RIGHT(Deceased,2)) as DeceasedDateNew
    FROM myTable


问:
Randomly show image + link in html newsletter template
Let's say i have a list of 4 images and i'm trying to randomly show 2 of them each time the newsletter is loaded.

I have a file show_image.php with the following code:

```<code>
$images = array(
  0 => array(
    'image' => 'http://example.com/img/partner1.jpg',
    'link' => 'http://www.example1.com'
  ),
  1 => array(
    'image' => 'http://example.com/img/partner2.jpg',
    'link' => 'http://www.example2.com'
  ),
  2 => array(
    'image' => 'http://example.com/img/partner3.jpg',
    'link' => 'http://www.example3.com'
  ),
  3 => array(
    'image' => 'http://example.com/img/partner4.jpg',
    'link' => 'http://www.example4.com'
  )
);

$i = 0
foreach($images as $image)
{
  $i++;
  $zones[$i][] = $image;
  if($i == 2)
    $i = 0;
}

if(!empty($zones[$_GET['zone']]))
{
    $zone = $zones[$_GET['zone']];
    $random_index = array_rand($zone);
    $partner = $zone[$random_index];

    if($_GET['field'] == 'image')
    {
        $file = getFullPath($partner['image']);

        $type = 'image/jpeg';
        header('Content-Type:'.$type);
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    elseif($_GET['field'] == 'link')
    {
        wp_redirect( $partner['link'], 301);
        exit();
    }
}

</code>```

In my current situation, the images in the (html) newsletter template look like this:

```<code><a href="http://example.com/show_image.php?zone=1&field=link">
  <img src="http://example.com/show_image.php?zone=1&field=image">
</a>
<a href="http://example.com/show_image.php?zone=2&field=link">
  <img src="http://example.com/show_image.php?zone=2&field=image">
</a>
</code>```

As you can see, the call for a random image and link are separate, causing the php script to respond with a random link that doesn't match the random image.

Can anyone point me in the right direction how to randomly show an image with the right corresponding link?

答:
First, there is a syntax error in your code. All your child arrays are missing a comma:

```<code>0 => array(
    'image' => 'http://example.com/img/partner1.jpg' // <-- Error
    'link' => 'http://www.example1.com'
  )
</code>```

Should be:

```<code>0 => array(
    'image' => 'http://example.com/img/partner1.jpg', // <-- Fixed
    'link' => 'http://www.example1.com'
  )
</code>```

You should use rand() to get an image randomly:

```<code>$images = array(
    0 => array(
      'image' => 'http://example.com/img/partner1.jpg',
      'link' => 'http://www.example1.com'
    ),
    1 => array(
      'image' => 'http://example.com/img/partner2.jpg',
      'link' => 'http://www.example2.com'
    ),
    2 => array(
      'image' => 'http://example.com/img/partner3.jpg',
      'link' => 'http://www.example3.com'
    ),
    3 => array(
      'image' => 'http://example.com/img/partner4.jpg',
      'link' => 'http://www.example4.com'
    )
  );

$total_images = count($images) - 1; // Get total number of images. Deducted one because arrays are zero-based

$random_img = rand(0, $total_images); // Get a random number between 0 and $total_images

echo $images[$random_img]['image'] . '<br />';
echo $images[$random_img]['link'] . '<br />';
</code>```

Body:
Let's say i have a list of 4 images and i'm trying to randomly show 2 of them each time the newsletter is loaded.

I have a file show_image.php with the following code:

$images = array(
  0 => array(
    'image' => 'http://example.com/img/partner1.jpg',
    'link' => 'http://www.example1.com'
  ),
  1 => array(
    'image' => 'http://example.com/img/partner2.jpg',
    'link' => 'http://www.example2.com'
  ),
  2 => array(
    'image' => 'http://example.com/img/partner3.jpg',
    'link' => 'http://www.example3.com'
  ),
  3 => array(
    'image' => 'http://example.com/img/partner4.jpg',
    'link' => 'http://www.example4.com'
  )
);

$i = 0
foreach($images as $image)
{
  $i++;
  $zones[$i][] = $image;
  if($i == 2)
    $i = 0;
}

if(!empty($zones[$_GET['zone']]))
{
    $zone = $zones[$_GET['zone']];
    $random_index = array_rand($zone);
    $partner = $zone[$random_index];

    if($_GET['field'] == 'image')
    {
        $file = getFullPath($partner['image']);

        $type = 'image/jpeg';
        header('Content-Type:'.$type);
        header('Content-Length: ' . filesize($file));
        readfile($file);
    }
    elseif($_GET['field'] == 'link')
    {
        wp_redirect( $partner['link'], 301);
        exit();
    }
}

In my current situation, the images in the (html) newsletter template look like this:

As you can see, the call for a random image and link are separate, causing the php script to respond with a random link that doesn't match the random image.

Can anyone point me in the right direction how to randomly show an image with the right corresponding link?

Body:
First, there is a syntax error in your code. All your child arrays are missing a comma:

0 => array(
    'image' => 'http://example.com/img/partner1.jpg' // <-- Error
    'link' => 'http://www.example1.com'
  )

Should be:

0 => array(
    'image' => 'http://example.com/img/partner1.jpg', // <-- Fixed
    'link' => 'http://www.example1.com'
  )

You should use rand() to get an image randomly:

$images = array(
    0 => array(
      'image' => 'http://example.com/img/partner1.jpg',
      'link' => 'http://www.example1.com'
    ),
    1 => array(
      'image' => 'http://example.com/img/partner2.jpg',
      'link' => 'http://www.example2.com'
    ),
    2 => array(
      'image' => 'http://example.com/img/partner3.jpg',
      'link' => 'http://www.example3.com'
    ),
    3 => array(
      'image' => 'http://example.com/img/partner4.jpg',
      'link' => 'http://www.example4.com'
    )
  );

$total_images = count($images) - 1; // Get total number of images. Deducted one because arrays are zero-based

$random_img = rand(0, $total_images); // Get a random number between 0 and $total_images

echo $images[$random_img]['image'] . '<br />';
echo $images[$random_img]['link'] . '<br />';


问:
hiding overlay after some time just like standard video player
i am making a custom video player in which there is an overlay containing the controls of the video player

my player starts to work in full length and height.

now i want to hide the overlay after 5 seconds i stop the mouse over.

now the problem is that when the below function mouse over in .ts file is called the synchronization of the timer is harmed.

so if i move my mouse continuously the overlay starts to flicker.

please provide me the solution to the problem.

following is my html code

```<code><div class="video-container" #videoFullscreen>
    <div class="video-wrapper" mouse-move>
      <video class="video video-js" data-dashjs-player  id="myVideo"  autoplay #videoPlayer>
        <source src="{{ videoSource }}" type="video/mp4" />
      </video>

      <!-- overlay -->
      <div class="overlay" [class.hideOverlay]="hideTop">
        <!-- top controls  -->
          .
          .
          <!-- lower controls  -->

        </div>
      </div>
</code>```

this is my type script code

```<code>@HostListener('document:mousemove', [ '$event' ]) //fuction to display and hide element sue to mouseover
    onMouseMove($event) {
            this.hideTop = false;
            setTimeout(() => {
                this.hideTop = true;
            }, 5000);
    }
</code>```

this is my css code :

```<code>.overlay {
    display: flex;
}
.hideOverlay {
    display:none;
}
</code>```

please help me to solve this problem.

答:
A neat solution would be to use rxjs to solve this like shown below:

```<code>ngOnInit(): void {
    fromEvent<MouseEvent>(document, 'mousemove').pipe(tap(() => {
      console.log("show it!");
      this.hideTop = false
    }), switchMap((event) =>
      timer(5000).pipe(tap(() => {
        console.log("hideit");
        this.hideTop = true;
      }))
    )).subscribe();
  }
</code>```

Don't forget to unsubscribe if your component gets destroyed to prevent memory leaks!

First we make an Observable from the documents mousemove event.
Now if the event triggers we set hideTop to true.
And here comes the interesting part: we use switchMap with a timer Observable. switchMap automatically unsubscribes from the inner Observable if the outer one emits a new value. Therefore the inner Observable only emits after the user actually stopped moving the mouse for 5 seconds.

Body:
i am making a custom video player in which there is an overlay containing the controls of the video player

my player starts to work in full length and height.

now i want to hide the overlay after 5 seconds i stop the mouse over.

now the problem is that when the below function mouse over in .ts file is called the synchronization of the timer is harmed.

so if i move my mouse continuously the overlay starts to flicker.

please provide me the solution to the problem.

following is my html code

      <video class="video video-js" data-dashjs-player  id="myVideo"  autoplay #videoPlayer>
        <source src="{{ videoSource }}" type="video/mp4" />
      </video>

          .
          .

this is my type script code

@HostListener('document:mousemove', [ '$event' ]) //fuction to display and hide element sue to mouseover
    onMouseMove($event) {
            this.hideTop = false;
            setTimeout(() => {
                this.hideTop = true;
            }, 5000);
    }

this is my css code :

.overlay {
    display: flex;
}
.hideOverlay {
    display:none;
}

please help me to solve this problem.

Body:
A neat solution would be to use rxjs to solve this like shown below:

ngOnInit(): void {
    fromEvent<MouseEvent>(document, 'mousemove').pipe(tap(() => {
      console.log("show it!");
      this.hideTop = false
    }), switchMap((event) =>
      timer(5000).pipe(tap(() => {
        console.log("hideit");
        this.hideTop = true;
      }))
    )).subscribe();
  }

Don't forget to unsubscribe if your component gets destroyed to prevent memory leaks!

First we make an Observable from the documents mousemove event.
Now if the event triggers we set hideTop to true.
And here comes the interesting part: we use switchMap with a timer Observable. switchMap automatically unsubscribes from the inner Observable if the outer one emits a new value. Therefore the inner Observable only emits after the user actually stopped moving the mouse for 5 seconds.


问:
I have problem when deploy my laravel on herkou (Mixed Content)
Hello …  l am finish Building website using Laravel and jQuery and bootstrap it's working good in local but when I upload to Heroku  the file jQuery and bootstrap not working … it's work in local using http but in Heroku its need https its not working but when write http substitute of https it's working good like local and display Not Secure .. now any body know how can i allow website using https in Heroku or How can selection this problem

答:
You should closely read all of Heroku's guide to getting started with Laravel.

The section titled "Trusting the Load Balancer" will resolve your issues.

Because of this:

This means that requests received by a dyno will have the last router’s IP address in the REMOTE_ADDR environment variable, and the internal request will always be made using the HTTP protocol, even if the original request was made over HTTPS.

Laravel sees HTTP requests coming in to the application, so it serves HTTP URLs for your various routes and asset URLs. As far as it knows, you're browsing via HTTP. The fix is to trust Heroku's "forwarded for" headers in your app's App\Http\Middleware\TrustProxies middleware:

```<code><?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
    protected $proxies = '*';
    protected $headers = Request:: HEADER_X_FORWARDED_AWS_ELB;
}
</code>```

Body:
You should closely read all of Heroku's guide to getting started with Laravel.

The section titled "Trusting the Load Balancer" will resolve your issues.

Because of this:

This means that requests received by a dyno will have the last router’s IP address in the REMOTE_ADDR environment variable, and the internal request will always be made using the HTTP protocol, even if the original request was made over HTTPS.

Laravel sees HTTP requests coming in to the application, so it serves HTTP URLs for your various routes and asset URLs. As far as it knows, you're browsing via HTTP. The fix is to trust Heroku's "forwarded for" headers in your app's App\Http\Middleware\TrustProxies middleware:

<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
use Fideloper\Proxy\TrustProxies as Middleware;
class TrustProxies extends Middleware
{
    protected $proxies = '*';
    protected $headers = Request:: HEADER_X_FORWARDED_AWS_ELB;
}


问:
How to search a partial text in dict?
I have a dictionary and would like to be able to search with a partial variable and return a text.

```<code>df = pd.read_csv('MY_PATH')
d = defaultdict(lambda: 'Error, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())
d[last_msg()]
</code>```

last_msg() should be my partial variable, and d is my dictionary.

The index on my dictionary is column msg from df.

In column msg i have a sample like Jeff Bezos.

In column reply i have a matching reply Jeff Bezos is the CEO of Amazon

How can I search a partial value in column msg and return matching value from column reply?

I want to search just Jeff or just Bezos and get the matching reply Jeff Bezos is the CEO of Amazon

PS. Alternatives to defaultdict may also help improve the code.

EDIT: last_msg() code extracts a text from selenium element.

```<code>def last_msg():
try:
    post = driver.find_elements_by_class_name("_12pGw")
    ultimo = len(post) - 1
    texto = post[ultimo].find_element_by_css_selector(
        "span.selectable-text").text
    return texto
except Exception as e:
    print("Error, input not valid")
</code>```

When I print(d):

```<code>defaultdict(<function <lambda> at 0x0000021F959D37B8>, {'Jeff Bezos': 'Jeff Bezos is the CEO of Amazon', 'Serguey Brin': 'Serguey Brin co-founded Google', nan: nan})
</code>```

When I print(df)

```<code>   Unnamed: 0           msg                            reply
0           0    Jeff Bezos  Jeff Bezos is the CEO of Amazon
1           1  Serguey Brin   Serguey Brin co-founded Google
2           2           NaN                              NaN
3           3           NaN                              NaN
</code>```

答:
I found a way arround my own question using:</p>

```<code>d = df.set_index('msg')['reply'].to_dict()
...
        try:
        x = next(v for k, v in d.items() if last_msg() in k)
    except StopIteration:
        x = 'Error, input not listed'
</code>```

Title: How to search a partial text in dict?

Body:
I have a dictionary and would like to be able to search with a partial variable and return a text.

df = pd.read_csv('MY_PATH')
d = defaultdict(lambda: 'Error, input not listed')
d.update(df.set_index('msg')['reply'].to_dict())
d[last_msg()]

last_msg() should be my partial variable, and d is my dictionary.

The index on my dictionary is column msg from df.

In column msg i have a sample like Jeff Bezos.

In column reply i have a matching reply Jeff Bezos is the CEO of Amazon

How can I search a partial value in column msg and return matching value from column reply?

I want to search just Jeff or just Bezos and get the matching reply Jeff Bezos is the CEO of Amazon

PS. Alternatives to defaultdict may also help improve the code.

EDIT: last_msg() code extracts a text from selenium element.

def last_msg():
try:
    post = driver.find_elements_by_class_name("_12pGw")
    ultimo = len(post) - 1
    texto = post[ultimo].find_element_by_css_selector(
        "span.selectable-text").text
    return texto
except Exception as e:
    print("Error, input not valid")

When I print(d):

defaultdict(<function <lambda> at 0x0000021F959D37B8>, {'Jeff Bezos': 'Jeff Bezos is the CEO of Amazon', 'Serguey Brin': 'Serguey Brin co-founded Google', nan: nan})

When I print(df)

   Unnamed: 0           msg                            reply
0           0    Jeff Bezos  Jeff Bezos is the CEO of Amazon
1           1  Serguey Brin   Serguey Brin co-founded Google
2           2           NaN                              NaN
3           3           NaN                              NaN

Body:
I found a way arround my own question using:

d = df.set_index('msg')['reply'].to_dict()
...
        try:
        x = next(v for k, v in d.items() if last_msg() in k)
    except StopIteration:
        x = 'Error, input not listed'