问:
Separating the data from a string filled with multiple data types
I want to turn this string into a list of the dictionaries within it:

”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”

I have multiple columns in a pandas dataframe composed of similar strings to this. Some are only ”[]” or ”[{‘id’: ‘x’, ‘name’: ‘y’}]”, and others have many stringified dictionaries within them.

I have tried

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
list(json.loads(z[1:-1]))
```

<p>And this works fine for when there is only one stringified dictionary (<code>”[{‘id’: ‘x’, ‘name’: ‘y’}]”</code>) but because the dictionaries have shared keys, they cannot simply be  jsonified.</p>

<p>Once this is done, I’ll retrieve the value from <code>name</code> of each and create a list of those.</p>

<p><strong>ANSWERED</strong>
Thanks @Tenacious B</p>

<p>To turn the string into the list of the dicts:</p>

<pre class="lang-py prettyprint-override"><code>import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
data = json.loads(z.replace("'", ""))]) # this will be a list of dicts
</code>```

Output:

[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]
```

<hr>

<p><strong>And</strong> to apply to a pandas dataframe having a column with entries as the above, retrieving only the value from the desired key:</p>

<pre class="lang-py prettyprint-override"><code>import json
df['col'] = df['col'].apply(lambda x: [i['name'] for i in json.loads(x.replace("'", ""))])
</code>```

答:
After I searched up how to convert a string list to list object I came across this: How to convert string representation of list to a list?

using ast.literal_eval can solve you problem.

Body:
I want to turn this string into a list of the dictionaries within it:

”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”

I have multiple columns in a pandas dataframe composed of similar strings to this. Some are only ”[]” or ”[{‘id’: ‘x’, ‘name’: ‘y’}]”, and others have many stringified dictionaries within them.

I have tried

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
list(json.loads(z[1:-1]))

And this works fine for when there is only one stringified dictionary (”[{‘id’: ‘x’, ‘name’: ‘y’}]”) but because the dictionaries have shared keys, they cannot simply be  jsonified.

Once this is done, I’ll retrieve the value from name of each and create a list of those.

ANSWERED
Thanks @Tenacious B

To turn the string into the list of the dicts:

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
data = json.loads(z.replace("'", ""))]) # this will be a list of dicts

Output:

[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]

And to apply to a pandas dataframe having a column with entries as the above, retrieving only the value from the desired key:

import json
df['col'] = df['col'].apply(lambda x: [i['name'] for i in json.loads(x.replace("'", ""))])


来源: stackexchange

问:
Java Script Date Function
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.</p>

```<code>function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}
</code>```

答:
You're missing the () for your function.

```<code>
<div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>function abc(){
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

console.log(abc())</code>```

```

ContentLicense: CC BY-SA 4.0

Title: Java Script Date Function

Body:
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.

function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

Body:
You're missing the () for your function.

function abc(){
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

console.log(abc())


问:
URL Rewrite exceptions for Blazor WebAssembly Hosted deployment
During development, i have used Swagger on the server side of my Blazor WebAssembly App. Always launching (debug) using kestrel instead of IIS Express.
Routing worked as expected, all my component routed properly and if i manually typed /swagger, i got to the swagger page. All good.

We have deployed under IIS on our pre-prod servers, the Server side and Blazor WebAssembly App (client) work as expected and are usable, however, my /swagger url gets rewritten (I assume) to go somewhere in my App instead of letting it go to Swagger, obviously there isn't any component that answers to /swagger.

My only guess is that, when hosted on IIS, the aspnet core app takes care of telling IIS what to rewrite and how (similar to the configs that could be provided thru a web.config for a "Standalone" deployment.)

I can't find how to specify exceptions, I've been following the doc at
https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/blazor/webassembly?view=aspnetcore-3.1#iis

Any idea how i could add an exception for /swagger ?

EDIT:

Turns out it works without issues in Chrome, only Firefox has the unwanted behavior. If i clear my cache, or use Incognito mode, the issue does not happen in Firefox. So, it seems that Firefox caches some stuff and tries to send my URL input to the Blazor Wasm instead of going thru to the server. I will debug some more with the dev tools and fiddler open to try and figure it out, will report back.

答:
Turns out there this is part of the service-worker.js file that is published. It is different in dev than what gets published (which makes sense).

During my debugging i was able to reproduce the issue on all browsers (Edge, Chrome and Firefox), regardless of being in Incognito/Private mode or not.

Once the service-worker is running, it handles serving requests from cache/index.html of the Blazor WebAssembly app.

If you go into your Blazor WebAssembly Client "wwwroot" folder, you'll find a service-worker.js and a service-worker.published.js. In the service-worker.published.js, you will find a function that looks like this :

```<code>async function onFetch(event) {
    let cachedResponse = null;
    if (event.request.method === 'GET') {
        // For all navigation requests, try to serve index.html from cache
        // If you need some URLs to be server-rendered, edit the following check to exclude those URLs
        const shouldServeIndexHtml = event.request.mode === 'navigate'
            && !event.request.url.includes('/connect/')
            && !event.request.url.includes('/Identity/');

        const request = shouldServeIndexHtml ? 'index.html' : event.request;
        const cache = await caches.open(cacheName);
        cachedResponse = await cache.match(request);
    }

    return cachedResponse || fetch(event.request);
}
</code>```

Simply following the instructions found in the code comments is gonna fix the issue. So we ended up adding an exclusion for "/swagger" like so :

```<code>&& !event.request.url.includes('/swagger')
</code>```

Hopefully this post is useful for people who are gonna want to serve things outside of the service worker, not only Swagger.

Body:
Turns out there this is part of the service-worker.js file that is published. It is different in dev than what gets published (which makes sense).

During my debugging i was able to reproduce the issue on all browsers (Edge, Chrome and Firefox), regardless of being in Incognito/Private mode or not.

Once the service-worker is running, it handles serving requests from cache/index.html of the Blazor WebAssembly app.

If you go into your Blazor WebAssembly Client "wwwroot" folder, you'll find a service-worker.js and a service-worker.published.js. In the service-worker.published.js, you will find a function that looks like this :

async function onFetch(event) {
    let cachedResponse = null;
    if (event.request.method === 'GET') {
        // For all navigation requests, try to serve index.html from cache
        // If you need some URLs to be server-rendered, edit the following check to exclude those URLs
        const shouldServeIndexHtml = event.request.mode === 'navigate'
            && !event.request.url.includes('/connect/')
            && !event.request.url.includes('/Identity/');

        const request = shouldServeIndexHtml ? 'index.html' : event.request;
        const cache = await caches.open(cacheName);
        cachedResponse = await cache.match(request);
    }

    return cachedResponse || fetch(event.request);
}

Simply following the instructions found in the code comments is gonna fix the issue. So we ended up adding an exclusion for "/swagger" like so :

&& !event.request.url.includes('/swagger')

Hopefully this post is useful for people who are gonna want to serve things outside of the service worker, not only Swagger.


问:
Change number format of input field in Antd's table-row-edit mode?
I am using the Table Component of Ant Design v2.x and I cannot upgrade. I would like to change the formatting of numbers in row-edit mode, since currently it is inconsistent: In Display mode I have German formatting (as desired), but once I click edit, numbers are formatted with American decimal separators:

I understand that the table-component encapsulates an Input-Number component which has the parameter decimalSeparator which I have to adjust. It is not at all obvious to me how I can pass-through that parameter from my parent (table) component column property to the underlying input-number component.

As minimal code base to demonstrate that, let us consider the Typescript example code from https://ant.design/components/table/#components-table-demo-edit-row and focus on the column age. Assume that it is not an age, but rather a Value (e.g. of a trade).
The (correct) formatting in the 2nd row of my screenshot I obtain with a render-function like this:

x.toLocaleString("de-DE", { style: 'currency', currency: ccy, currencyDisplay: "code", maximumFractionDigits: 2 });
```

<p>where <code>x</code> is the value to be formatted and <code>ccy</code> is the currency-string to be displayed, in the screenshot it was just empty.</p>

<p>What I <em>am</em> able to do is to specify whether a column is a <code>number</code>, a <code>string</code>, or something else. In the example source code, the corresponding part is:</p>

<pre class="lang-js prettyprint-override"><code>interface Item {
  key: string;
  name: string;
  age: number;
  address: string;
}
</code>```

Looking forward to your help!

答:
By trial and error, I finally understood how the formatter and parser of the  InputNumber component works, there was close to no documentation at https://2x.ant.design/components/table/

I ended up doing the following, which is not exactly pretty, but works:

```<code><InputNumber
  defaultValue={this.props.value !== null ? parseFloat(this.props.value) : null}
  // This is what 2x.antd.design suggests to do it:
  // formatter={value => ` ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
  // parser={value => value.replace(/\$\s?|(,*)/g, "")}

  // This my solution for German numbers
  formatter={value => ` ${value}`.replace(/\./,',').replace(/\B(?=(\d{3})+(?!\d))/g, '.')}
  parser={x => parseFloat(`${x}`.replace(/,/, '#').replace(/\./g, '').replace(/#/,'.')) }

  onChange={this.handleChange}
/>
</code>```

The idea of the formatter is to first replace the decimal separator . with ,. The replace(/\B(?=(\d{3})+(?!\d))/g, ',') is to find globally all 3-digit groups \d{3}, and replace any kind of thousand-separator with ., the \B(?=(\d{3})+(?!\d)) finds all but the last ,.

Before writing things back into the state variable this.props.value, we have to undo that replacement, so we first replace the comma as decimal separator with some placeholder #, then delete all . in the string, and finally make revert the placeholder to the . as decimal separator which can be understood by parseFloat.

Body:
I am using the Table Component of Ant Design v2.x and I cannot upgrade. I would like to change the formatting of numbers in row-edit mode, since currently it is inconsistent: In Display mode I have German formatting (as desired), but once I click edit, numbers are formatted with American decimal separators:

I understand that the table-component encapsulates an Input-Number component which has the parameter decimalSeparator which I have to adjust. It is not at all obvious to me how I can pass-through that parameter from my parent (table) component column property to the underlying input-number component.

As minimal code base to demonstrate that, let us consider the Typescript example code from https://ant.design/components/table/#components-table-demo-edit-row and focus on the column age. Assume that it is not an age, but rather a Value (e.g. of a trade).
The (correct) formatting in the 2nd row of my screenshot I obtain with a render-function like this:

x.toLocaleString("de-DE", { style: 'currency', currency: ccy, currencyDisplay: "code", maximumFractionDigits: 2 });

where x is the value to be formatted and ccy is the currency-string to be displayed, in the screenshot it was just empty.

What I am able to do is to specify whether a column is a number, a string, or something else. In the example source code, the corresponding part is:

interface Item {
  key: string;
  name: string;
  age: number;
  address: string;
}

Looking forward to your help!

Body:
By trial and error, I finally understood how the formatter and parser of the  InputNumber component works, there was close to no documentation at https://2x.ant.design/components/table/

I ended up doing the following, which is not exactly pretty, but works:

<InputNumber
  defaultValue={this.props.value !== null ? parseFloat(this.props.value) : null}
  // This is what 2x.antd.design suggests to do it:
  // formatter={value => ` ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')}
  // parser={value => value.replace(/\$\s?|(,*)/g, "")}

  // This my solution for German numbers
  formatter={value => ` ${value}`.replace(/\./,',').replace(/\B(?=(\d{3})+(?!\d))/g, '.')}
  parser={x => parseFloat(`${x}`.replace(/,/, '#').replace(/\./g, '').replace(/#/,'.')) }

  onChange={this.handleChange}
/>

The idea of the formatter is to first replace the decimal separator . with ,. The replace(/\B(?=(\d{3})+(?!\d))/g, ',') is to find globally all 3-digit groups \d{3}, and replace any kind of thousand-separator with ., the \B(?=(\d{3})+(?!\d)) finds all but the last ,.

Before writing things back into the state variable this.props.value, we have to undo that replacement, so we first replace the comma as decimal separator with some placeholder #, then delete all . in the string, and finally make revert the placeholder to the . as decimal separator which can be understood by parseFloat.


问:
How do i concat an array only when it's not undefined
I need to add multiple arrays together depending on user's preference some array might appear empty, how do I make sure the array I'm about to concat is not empty

here is my failed code

```<code>const num1 = [12,67,100]
const num2 = []
const num3 = [23,191, 58]
const num4 = [23,30]

const numbers = num1.concat(`num${Math.random() * 10}`)
</code>```

答:
const num1 = [12, 67, 100]
const num2 = []
const num3 = [23, 191, 58]
const num4 = [23, 30]

const check = `num${Math.random() * 10}`
const numbers = num1.concat(check && check)

console.log(numbers);```

Body:
I need to add multiple arrays together depending on user's preference some array might appear empty, how do I make sure the array I'm about to concat is not empty

here is my failed code

const num1 = [12,67,100]
const num2 = []
const num3 = [23,191, 58]
const num4 = [23,30]

const numbers = num1.concat(`num${Math.random() * 10}`)


问:
How to pass value returned by a method of a class as a parameter for test case in PyTest?
I am trying to pass a value returned by a class method into a test method in the same class.

```<code>def SampleTest:

    # my dynamic value generation function
    def dynamicValue(self):
        result = 10
        return result

    # how to pass a value returned by dynamicValue method?
    @pytest.mark.parametrize('value', [1, 2, dynamicValue])
    def test_case(self, value):
        print(f'Testing for input value {value}')
        # testing functionality...
</code>```

By dynamic value I mean some numeric value fetched from operating system during collect phase of tests execution. How to do this correctly? Above example doesn't work.

答:
You can use a pytest fixture to pass a value as input for a test. This feature of pytest is really nice because you just need to use a decorator on your method, then you can pass the function to other tests!

Here is a complete example which passes when run with pytest:

```<code>import pytest

class TestClass:
    @pytest.fixture
    def dynamic_value(self):
        return 10

    def test_case(self, dynamic_value):
        # This assertion only passes if dynamic_value is passed properly
        assert dynamic_value == 10
</code>```

Body:
I am trying to pass a value returned by a class method into a test method in the same class.

def SampleTest:

    # my dynamic value generation function
    def dynamicValue(self):
        result = 10
        return result

    # how to pass a value returned by dynamicValue method?
    @pytest.mark.parametrize('value', [1, 2, dynamicValue])
    def test_case(self, value):
        print(f'Testing for input value {value}')
        # testing functionality...

By dynamic value I mean some numeric value fetched from operating system during collect phase of tests execution. How to do this correctly? Above example doesn't work.

Body:
You can use a pytest fixture to pass a value as input for a test. This feature of pytest is really nice because you just need to use a decorator on your method, then you can pass the function to other tests!

Here is a complete example which passes when run with pytest:

import pytest

class TestClass:
    @pytest.fixture
    def dynamic_value(self):
        return 10

    def test_case(self, dynamic_value):
        # This assertion only passes if dynamic_value is passed properly
        assert dynamic_value == 10


问:
Darkmode + Changing source of pictures
So I had implement dark mode to my website but there are pictures that I need to change for it to function properly. I have the light and dark versions of the images that I need but I would like to know if there's any way I can change the source of the image when I enable dark mode.

I got my code from this video: https://www.youtube.com/watch?v=wodWDIdV9BY

This is my button for darkmode and the image in HTML:

```<code><button onclick="changeImage();" id="dark-mode-toggle" class="dark-mode-toggle">Darkmode On/Off</button>
</code>```

The Javascript to enable darkmode (refer to youtube link above):

```<code>let darkMode = localStorage.getItem('darkMode');
const darkModeToggle = document.querySelector('#dark-mode-toggle');
const enableDarkMode = () => {
  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {
  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}
if (darkMode === 'enabled') {
  enableDarkMode();
}

darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  if (darkMode !== 'enabled') {
    enableDarkMode();
  } else {
    disableDarkMode();
  }
});
</code>```

This is what I had tried

```<code>let darkMode = localStorage.getItem('darkMode');

const darkModeToggle = document.querySelector('#dark-mode-toggle');

const enableDarkMode = () => {

    document.getElementById('icon').src="images/twar-white-icon.png"

  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {

    document.getElementById('icon').src="images/twar-black-icon.png"

  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}
if (darkMode === 'enabled') {
  enableDarkMode();
}

darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  if (darkMode !== 'enabled') {
    enableDarkMode();
  } else {
    disableDarkMode();
  }
});
</code>```

Basicly what I added was  document.getElementById('icon').src="images/twar-white-icon.png" and document.getElementById('icon').src="images/twar-black-icon.png"

But I kept getting an error of "Uncaught TypeError: Cannot set property 'src' of null"
at my console log. I need the source of image to change as darkmode in enabled and disable because the function was saved on localStorage which remembers the setting made on the previous visit. The source of the image has to be based on whether darkmode was enabled or not.

答: The Javascript written was correct, but I was receiving error messages that the id was null. This was because I had put the script tag above the image tag and once I shifted it down the body tag, it read the id and carried out the function. </p>

Title: Darkmode + Changing source of pictures

Body:
So I had implement dark mode to my website but there are pictures that I need to change for it to function properly. I have the light and dark versions of the images that I need but I would like to know if there's any way I can change the source of the image when I enable dark mode.

I got my code from this video: https://www.youtube.com/watch?v=wodWDIdV9BY

This is my button for darkmode and the image in HTML:

<button onclick="changeImage();" id="dark-mode-toggle" class="dark-mode-toggle">Darkmode On/Off</button>

The Javascript to enable darkmode (refer to youtube link above):

let darkMode = localStorage.getItem('darkMode');
const darkModeToggle = document.querySelector('#dark-mode-toggle');
const enableDarkMode = () => {
  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {
  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}
if (darkMode === 'enabled') {
  enableDarkMode();
}

darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  if (darkMode !== 'enabled') {
    enableDarkMode();
  } else {
    disableDarkMode();
  }
});

This is what I had tried

let darkMode = localStorage.getItem('darkMode');

const darkModeToggle = document.querySelector('#dark-mode-toggle');

const enableDarkMode = () => {

    document.getElementById('icon').src="images/twar-white-icon.png"

  document.body.classList.add('darkmode');
  localStorage.setItem('darkMode', 'enabled');
}

const disableDarkMode = () => {

    document.getElementById('icon').src="images/twar-black-icon.png"

  document.body.classList.remove('darkmode');
  localStorage.setItem('darkMode', null);
}
if (darkMode === 'enabled') {
  enableDarkMode();
}

darkModeToggle.addEventListener('click', () => {
  darkMode = localStorage.getItem('darkMode');
  if (darkMode !== 'enabled') {
    enableDarkMode();
  } else {
    disableDarkMode();
  }
});

Basicly what I added was  document.getElementById('icon').src="images/twar-white-icon.png" and document.getElementById('icon').src="images/twar-black-icon.png"

But I kept getting an error of "Uncaught TypeError: Cannot set property 'src' of null"
at my console log. I need the source of image to change as darkmode in enabled and disable because the function was saved on localStorage which remembers the setting made on the previous visit. The source of the image has to be based on whether darkmode was enabled or not.


问:
Why doesn't "case" with "when > 2" work?
Why is this not working?</p>

```<code>case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end
</code>```

答:
An if statement would probably be more fitting for your code, since you don't have a definitive range/value, but rather just a greater-than:

```<code>if ARGV.length == 0
  abort "Error 1"
elsif ARGV.length > 2
  abort "Error 2"
end
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Why is this not working?

case ARGV.length
  when 0
    abort "Error 1"
  when > 2
    abort "Error 2"
end

Body:
An if statement would probably be more fitting for your code, since you don't have a definitive range/value, but rather just a greater-than:

if ARGV.length == 0
  abort "Error 1"
elsif ARGV.length > 2
  abort "Error 2"
end


问:
Elegant way to refer to files in data science project
I have spent few recent days to learn how to structure data science project to keep it simple, reusable and pythonic. Sticking to this guideline I have created my_project. You can see it's structure below.

```<code>├── README.md
├── data
│   ├── processed          <-- data files
│   └── raw
├── notebooks
|   └── notebook_1
├── setup.py
|
├── settings.py            <-- settings file
└── src
    ├── __init__.py
    │
    └── data
        └── get_data.py    <-- script
</code>```

I defined a function that loads data from .data/processed. I want to use this function in other scripts and also in jupyter notebooks located in .notebooks.

```<code>def data_sample(code=None):
    df = pd.read_parquet('../../data/processed/my_data')
    if not code:
        code = random.choice(df.code.unique())
    df = df[df.code == code].sort_values('Date')
    return df
</code>```

Obviously this function won't work anywhere unless I run it directly in the script where it is defined.
My idea was to create settings.py where I'd declare:

```<code>from os.path import join, dirname

DATA_DIR = join(dirname(__file__), 'data', 'processed')
</code>```

So now I can write:

```<code>from my_project import settings
import os

def data_sample(code=None):
    file_path = os.path.join(settings.DATA_DIR, 'my_data')
    df = pd.read_parquet(file_path)
    if not code:
        code = random.choice(df.code.unique())
    df = df[df.code == code].sort_values('Date')
    return df
</code>```

Questions:

Is this common practice to refer to files in this way? settings.DATA_DIR looks kinda ugly.

Is this at all how settings.py should be used? And should it be placed in this directory? I have seen it in different spot in this repo under .samr/settings.py

I understand that there might not be 'one right answer', I just try to find logical, elegant way of handling these things.

答:
You can open a file by using open() and save it in a variable and keep using the variable wherever u wish to refer to the file.

```<code>with open('Test.txt','r') as f:
</code>```

or

```<code>f=open('Test.txt','r')
</code>```

and use f to refer to the file.
If you want the file to be both readable & writable, you can use r+ in place of r.

Body:
I have spent few recent days to learn how to structure data science project to keep it simple, reusable and pythonic. Sticking to this guideline I have created my_project. You can see it's structure below.

├── README.md
├── data
│   ├── processed          <-- data files
│   └── raw
├── notebooks
|   └── notebook_1
├── setup.py
|
├── settings.py            <-- settings file
└── src
    ├── __init__.py
    │
    └── data
        └── get_data.py    <-- script

I defined a function that loads data from .data/processed. I want to use this function in other scripts and also in jupyter notebooks located in .notebooks.

def data_sample(code=None):
    df = pd.read_parquet('../../data/processed/my_data')
    if not code:
        code = random.choice(df.code.unique())
    df = df[df.code == code].sort_values('Date')
    return df

Obviously this function won't work anywhere unless I run it directly in the script where it is defined.
My idea was to create settings.py where I'd declare:

from os.path import join, dirname

DATA_DIR = join(dirname(__file__), 'data', 'processed')

So now I can write:

from my_project import settings
import os

def data_sample(code=None):
    file_path = os.path.join(settings.DATA_DIR, 'my_data')
    df = pd.read_parquet(file_path)
    if not code:
        code = random.choice(df.code.unique())
    df = df[df.code == code].sort_values('Date')
    return df

Questions:

Is this common practice to refer to files in this way? settings.DATA_DIR looks kinda ugly.

Is this at all how settings.py should be used? And should it be placed in this directory? I have seen it in different spot in this repo under .samr/settings.py

I understand that there might not be 'one right answer', I just try to find logical, elegant way of handling these things.

Body:
You can open a file by using open() and save it in a variable and keep using the variable wherever u wish to refer to the file.

with open('Test.txt','r') as f:

or

f=open('Test.txt','r')

and use f to refer to the file.
If you want the file to be both readable & writable, you can use r+ in place of r.


答:
Function declaration is wrong. After the function name () should be used. Refer below code

```<code>function abc() {
var returnString = '';
var today = new Date();
var currentTime = today.getHours();
return currentTime;
}
</code>```

Title: Java Script Date Function

Body:
Function declaration is wrong. After the function name () should be used. Refer below code

function abc() {
var returnString = '';
var today = new Date();
var currentTime = today.getHours();
return currentTime;
}


问:
Produce two plots with the same plotOutput() in a shiny app
I have the shiny app below in which the user select which plots he wants to display. The issue is that if for example only mtcars is selected I want it to be displayed on top and if then iris is selected the mtcars plot will be displayed under iris plot. This is why Im trying to produse them using the same plotOutput(). Otherwise when mtcars would be the only selection ther would be an empty space over it.

```<code>library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotOutput("fn")
    )
)

server <- function(input, output, session) {

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("iris","mtcars"),
                        multiple = T,options = list(`actions-box` = TRUE),
                        selected = "iris")

    })
    output$fn<-renderPlot({
        if(input$DB=="iris"){
            plot(iris)
        }
        else if(input$DB=="mtcars"){
            plot(mtcars)
        }
        else if(input$DB==c("iris","mtcars")){
            plot(iris)
            plot(mtcars)
        }

    })

}

shinyApp(ui, server)
</code>```

答:
an approach</p>

```<code>library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotOutput("fn"),
        plotOutput("fn2")
    )
)

server <- function(input, output, session) {

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("iris","mtcars"),
                        multiple = T,options = list(`actions-box` = TRUE),
                        selected = "iris")

    })
    output$fn<-renderPlot({
        if("iris" %in% input$DB & "mtcars" %in% input$DB){
            plot(iris)

        }
        else if("iris" %in% input$DB){
            plot(iris)
        }
        else if("mtcars" %in% input$DB){
            plot(mtcars)
        }

    })
    output$fn2<-renderPlot({
        if("iris" %in% input$DB & "mtcars" %in% input$DB){
            plot(mtcars)

        }
        else if("iris" %in% input$DB){
            return(NULL)
        }
        else if("mtcars" %in% input$DB){
            return(NULL)
        }

    })
}

shinyApp(ui, server)
</code>```

Body:
I have the shiny app below in which the user select which plots he wants to display. The issue is that if for example only mtcars is selected I want it to be displayed on top and if then iris is selected the mtcars plot will be displayed under iris plot. This is why Im trying to produse them using the same plotOutput(). Otherwise when mtcars would be the only selection ther would be an empty space over it.

library(shiny)
library(shinydashboard)

ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotOutput("fn")
    )
)

server <- function(input, output, session) {

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("iris","mtcars"),
                        multiple = T,options = list(`actions-box` = TRUE),
                        selected = "iris")

    })
    output$fn<-renderPlot({
        if(input$DB=="iris"){
            plot(iris)
        }
        else if(input$DB=="mtcars"){
            plot(mtcars)
        }
        else if(input$DB==c("iris","mtcars")){
            plot(iris)
            plot(mtcars)
        }

    })

}

shinyApp(ui, server)

Body:
an approach

library(shiny)
library(shinydashboard)
library(shinyWidgets)

ui <- dashboardPage(
    header = dashboardHeader(title = "My dashboard"),
    sidebar = dashboardSidebar(
        uiOutput("dbs")

    ),
    body = dashboardBody(
        plotOutput("fn"),
        plotOutput("fn2")
    )
)

server <- function(input, output, session) {

    output$dbs<-renderUI({

            pickerInput("DB", "Select Database/s",
                        choices = c("iris","mtcars"),
                        multiple = T,options = list(`actions-box` = TRUE),
                        selected = "iris")

    })
    output$fn<-renderPlot({
        if("iris" %in% input$DB & "mtcars" %in% input$DB){
            plot(iris)

        }
        else if("iris" %in% input$DB){
            plot(iris)
        }
        else if("mtcars" %in% input$DB){
            plot(mtcars)
        }

    })
    output$fn2<-renderPlot({
        if("iris" %in% input$DB & "mtcars" %in% input$DB){
            plot(mtcars)

        }
        else if("iris" %in% input$DB){
            return(NULL)
        }
        else if("mtcars" %in% input$DB){
            return(NULL)
        }

    })
}

shinyApp(ui, server)


问:
Regex - Match only two digitsafter substring
I'm trying to replace all elements like \u00XY in a string that can contain multiple entries like that.

```<code>'"\u00bfIdade del titular?"'
</code>```

This can be a short string or a string containing json objects inside... (I know... but... old code)
I tried normalize after the string but it didn't work, so I got instructed to replace all of those elements in unicode with a '?' char.

Any ideas on a simple way for this purpose? I'm not being able to find the right regex for this.

答:
I made a small function that replaces all the unicode.

```<code>function replace_unicode_escape_sequence($sting) {
    //replace all \uxxxx for correct html equvilant
    $decoded_string = mb_convert_encoding(pack('H*', $sting), 'UTF-8', 'UCS-2BE');
    return $decoded_string;
}
</code>```

Hope this wil help you!

Body:
I'm trying to replace all elements like \u00XY in a string that can contain multiple entries like that.

'"\u00bfIdade del titular?"'

This can be a short string or a string containing json objects inside... (I know... but... old code)
I tried normalize after the string but it didn't work, so I got instructed to replace all of those elements in unicode with a '?' char.

Any ideas on a simple way for this purpose? I'm not being able to find the right regex for this.

Body:
I made a small function that replaces all the unicode.

function replace_unicode_escape_sequence($sting) {
    //replace all \uxxxx for correct html equvilant
    $decoded_string = mb_convert_encoding(pack('H*', $sting), 'UTF-8', 'UCS-2BE');
    return $decoded_string;
}

Hope this wil help you!


问:
How to take down APK when serving both a bundle and an APK
I have the following scenario. There's an old APK of the app that's on production along with the most recent version of the app in a Android Bundle format. It looks like there are no active devices using the APK which is good, but how can I totally deactivate that APK ?

答: Next time you're publishing to Production, you should deactivate the APK. Not just publish the new version. The APK will still be served to users whose devices are compatible with the release.</p>


问:
Jenkins reports incorrect username and password for Github credentials
Problem Statement: I am getting error like "stderr: remote: Invalid username or password." for Jenkins build.

My Jenkinsfile is as follows:

node {

```<code>    stage('SCM Checkout') {
        git 'https://github.com/xxxxxxxxxxxx/java-app'
    }
        stage('Compile Package'){
        // Get path of Maven Home
        def MavenHome = tool name: 'MVN_HOME', type: 'maven'
        sh "${MavenHome}/bin/mvn package"
    }
}
</code>```

I have saved my credentials in Jenkins as below:

My Jenkins looks like below:

Unfortunately, I am getting error/log output as below:

```<code>Checking out git https://github.com/xxxxxxxxxxx/java-app into /var/lib/jenkins/workspace/My-app-Jenkinspipeline@script to read Jenkinsfile
using credential githubcredentials
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/xxxxxxxxxxx/java-app # timeout=10
Fetching upstream changes from https://github.com/xxxxxxxxxxx/java-app
 > git --version # timeout=10
using GIT_ASKPASS to set credentials Github Credentials
 > git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 691f79125928ce480176fd04e96c4f61297c8051 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 691f79125928ce480176fd04e96c4f61297c8051 # timeout=10
Commit message: "Added Checkout step"
 > git rev-list --no-walk 371a72a8024ce467f287f5297efaa5662c3c5181 # timeout=10
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/My-app-Jenkinspipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (SCM Checkout)
[Pipeline] git
No credentials specified
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/xxxxxxxxxxx/java-app # timeout=10
Fetching upstream changes from https://github.com/xxxxxxxxxxx/java-app
 > git --version # timeout=10
 > git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/* # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from https://github.com/xxxxxxxxxxx/java-app
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:909)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1131)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1167)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:125)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:93)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:80)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: hudson.plugins.git.GitException: Command "git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/xxxxxxxxxxx/java-app/'

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2430)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:2044)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:81)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:569)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:907)
    ... 11 more
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: Error fetching remote repo 'origin'
Finished: FAILURE
</code>```

Please assist as I want to understand why I am getting an incorrect username and password even though I can login with the same credentials to Github

答:
To get SCM Checkout working we need to add credentials. I did as below:</p>

```<code>git changelog: false, credentialsId: 'githubcredentials', poll: false, url: 'https://github.com/xxxxxxxxxxxx/java-app'
</code>```

Body:
Problem Statement: I am getting error like "stderr: remote: Invalid username or password." for Jenkins build.

My Jenkinsfile is as follows:

node {

    stage('SCM Checkout') {
        git 'https://github.com/xxxxxxxxxxxx/java-app'
    }
        stage('Compile Package'){
        // Get path of Maven Home
        def MavenHome = tool name: 'MVN_HOME', type: 'maven'
        sh "${MavenHome}/bin/mvn package"
    }
}

I have saved my credentials in Jenkins as below:

My Jenkins looks like below:

Unfortunately, I am getting error/log output as below:

Checking out git https://github.com/xxxxxxxxxxx/java-app into /var/lib/jenkins/workspace/My-app-Jenkinspipeline@script to read Jenkinsfile
using credential githubcredentials
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/xxxxxxxxxxx/java-app # timeout=10
Fetching upstream changes from https://github.com/xxxxxxxxxxx/java-app
 > git --version # timeout=10
using GIT_ASKPASS to set credentials Github Credentials
 > git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/* # timeout=10
 > git rev-parse refs/remotes/origin/master^{commit} # timeout=10
 > git rev-parse refs/remotes/origin/origin/master^{commit} # timeout=10
Checking out Revision 691f79125928ce480176fd04e96c4f61297c8051 (refs/remotes/origin/master)
 > git config core.sparsecheckout # timeout=10
 > git checkout -f 691f79125928ce480176fd04e96c4f61297c8051 # timeout=10
Commit message: "Added Checkout step"
 > git rev-list --no-walk 371a72a8024ce467f287f5297efaa5662c3c5181 # timeout=10
Running in Durability level: MAX_SURVIVABILITY
[Pipeline] Start of Pipeline
[Pipeline] node
Running on Jenkins in /var/lib/jenkins/workspace/My-app-Jenkinspipeline
[Pipeline] {
[Pipeline] stage
[Pipeline] { (SCM Checkout)
[Pipeline] git
No credentials specified
 > git rev-parse --is-inside-work-tree # timeout=10
Fetching changes from the remote Git repository
 > git config remote.origin.url https://github.com/xxxxxxxxxxx/java-app # timeout=10
Fetching upstream changes from https://github.com/xxxxxxxxxxx/java-app
 > git --version # timeout=10
 > git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/* # timeout=10
ERROR: Error fetching remote repo 'origin'
hudson.plugins.git.GitException: Failed to fetch from https://github.com/xxxxxxxxxxx/java-app
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:909)
    at hudson.plugins.git.GitSCM.retrieveChanges(GitSCM.java:1131)
    at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1167)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep.checkout(SCMStep.java:125)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:93)
    at org.jenkinsci.plugins.workflow.steps.scm.SCMStep$StepExecutionImpl.run(SCMStep.java:80)
    at org.jenkinsci.plugins.workflow.steps.SynchronousNonBlockingStepExecution.lambda$start$0(SynchronousNonBlockingStepExecution.java:47)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Caused by: hudson.plugins.git.GitException: Command "git fetch --tags --force --progress -- https://github.com/xxxxxxxxxxx/java-app +refs/heads/*:refs/remotes/origin/*" returned status code 128:
stdout:
stderr: remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/xxxxxxxxxxx/java-app/'

    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandIn(CliGitAPIImpl.java:2430)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.launchCommandWithCredentials(CliGitAPIImpl.java:2044)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl.access$500(CliGitAPIImpl.java:81)
    at org.jenkinsci.plugins.gitclient.CliGitAPIImpl$1.execute(CliGitAPIImpl.java:569)
    at hudson.plugins.git.GitSCM.fetchFrom(GitSCM.java:907)
    ... 11 more
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: Error fetching remote repo 'origin'
Finished: FAILURE

Please assist as I want to understand why I am getting an incorrect username and password even though I can login with the same credentials to Github

Body:
To get SCM Checkout working we need to add credentials. I did as below:

git changelog: false, credentialsId: 'githubcredentials', poll: false, url: 'https://github.com/xxxxxxxxxxxx/java-app'


问:
How to use a handler to loop an if statement every 20 seconds
Hi I have been having issues using the handler (I have used nearly every single example in any thread about looping stuff using handler)to loop a if statement that I need to rerun every 20 secs, I'm very new to java, and please ignore my stupid toast messages, could someone edit it so it will rerun the code every 20 seconds, Thanks in advance</p>

```<code>DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);

for (final Display display : dm.getDisplays()) {
    Toast.makeText(MainActivity.this, "for loop reached", Toast.LENGTH_LONG).show();

    int state = display.getState();
    String StateString = Integer.toString(state);
    Toast.makeText(MainActivity.this, StateString, Toast.LENGTH_LONG).show();

    if (display.getState() == 1) {
        String command = "dumpsys deviceidle force-idle deep";
        try {
            Process process = Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
        }

        //Toast.makeText(MainActivity.this, "not failed yayay", Toast.LENGTH_LONG).show();
        TextView tv9 = (TextView) findViewById(R.id.text_view_id);
        tv9.setText("The screen was turned off");
        Toast.makeText(MainActivity.this, "The screen is offfffffffff lolol", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(MainActivity.this, "The screen is on lolol", Toast.LENGTH_LONG).show();
    }
}
</code>```

答:
What you need is not entirely clear.  Here are some examples of running tasks at fixed delays in a separate thread.  There are a lot of different ways to code this sort of example; this example is just one of many.

Example 1 Output:

```<code>main: Starting emitter with a delay of 5s
main: Started emitter
main: Running emitter for 50s
emitter: Count [ 0 ]
emitter: Count [ 1 ]
emitter: Count [ 2 ]
emitter: Count [ 3 ]
emitter: Count [ 4 ]
emitter: Count [ 5 ]
emitter: Count [ 6 ]
emitter: Count [ 7 ]
emitter: Count [ 8 ]
emitter: Count [ 9 ]
main: Completed running emitter for 50s
main: Stopping emitter
emitter: Stopped at count [ 10 ]
main: Stopped emitter
</code>```

Example 1:

```<code>package samples;

public class Emitter1 {
    public static final int MS_IN_SEC = 1000;

    public static void main(String[] args) {
        Emitter emitter = newEmitter(MS_IN_SEC * 5);
        Thread emitterThread = new Thread(emitter);

        System.out.println("main: Starting emitter with a delay of 5s");
        emitterThread.start();
        System.out.println("main: Started emitter");

        System.out.println("main: Running emitter for 50s");
        sleep("main", MS_IN_SEC * 50);
        System.out.println("main: Completed running emitter for 50s");

        System.out.println("main: Stopping emitter");

        emitter.requestStop();
        try {
            emitterThread.join();
            System.out.println("main: Stopped emitter");
        } catch ( InterruptedException e ) {
            System.out.println("main: Interrupted waiting for emitter to finish");
        }

    }

    public static boolean sleep(String threadName, int mSec) {
        try {
            Thread.sleep(mSec);
        } catch ( InterruptedException e ) {
            System.out.println(threadName + ": Interrupted on delay of [ " + mSec + " ms ]!");
            return false;
        }
        return true;
    }

    public interface Emitter extends Runnable {
        void requestStop();
        boolean getStopped();
    }

    public static Emitter newEmitter(int delayMs) {
        return new Emitter() {
            private boolean stopped;

            public synchronized void requestStop() {
                stopped= true;
            }

            public synchronized boolean getStopped() {
                return stopped;
            }

            public void run() {
                int counter = 0;
                while ( !getStopped() ) {
                    System.out.println("emitter: Count [ " + counter + " ]");
                    counter++;

                    if ( !sleep("emitter", delayMs) ) {
                        break;
                    }
                }

                System.out.println("emitter: Stopped at count [ " + counter + " ]");
            }
        };
    }
}
</code>```

Body:
Hi I have been having issues using the handler (I have used nearly every single example in any thread about looping stuff using handler)to loop a if statement that I need to rerun every 20 secs, I'm very new to java, and please ignore my stupid toast messages, could someone edit it so it will rerun the code every 20 seconds, Thanks in advance

DisplayManager dm = (DisplayManager) getSystemService(Context.DISPLAY_SERVICE);

for (final Display display : dm.getDisplays()) {
    Toast.makeText(MainActivity.this, "for loop reached", Toast.LENGTH_LONG).show();

    int state = display.getState();
    String StateString = Integer.toString(state);
    Toast.makeText(MainActivity.this, StateString, Toast.LENGTH_LONG).show();

    if (display.getState() == 1) {
        String command = "dumpsys deviceidle force-idle deep";
        try {
            Process process = Runtime.getRuntime().exec(command);
        } catch (Exception e) {
            Toast.makeText(MainActivity.this, "failed", Toast.LENGTH_LONG).show();
        }

        //Toast.makeText(MainActivity.this, "not failed yayay", Toast.LENGTH_LONG).show();
        TextView tv9 = (TextView) findViewById(R.id.text_view_id);
        tv9.setText("The screen was turned off");
        Toast.makeText(MainActivity.this, "The screen is offfffffffff lolol", Toast.LENGTH_LONG).show();
    } else {
        Toast.makeText(MainActivity.this, "The screen is on lolol", Toast.LENGTH_LONG).show();
    }
}

Body:
What you need is not entirely clear.  Here are some examples of running tasks at fixed delays in a separate thread.  There are a lot of different ways to code this sort of example; this example is just one of many.

Example 1 Output:

main: Starting emitter with a delay of 5s
main: Started emitter
main: Running emitter for 50s
emitter: Count [ 0 ]
emitter: Count [ 1 ]
emitter: Count [ 2 ]
emitter: Count [ 3 ]
emitter: Count [ 4 ]
emitter: Count [ 5 ]
emitter: Count [ 6 ]
emitter: Count [ 7 ]
emitter: Count [ 8 ]
emitter: Count [ 9 ]
main: Completed running emitter for 50s
main: Stopping emitter
emitter: Stopped at count [ 10 ]
main: Stopped emitter

Example 1:

package samples;

public class Emitter1 {
    public static final int MS_IN_SEC = 1000;

    public static void main(String[] args) {
        Emitter emitter = newEmitter(MS_IN_SEC * 5);
        Thread emitterThread = new Thread(emitter);

        System.out.println("main: Starting emitter with a delay of 5s");
        emitterThread.start();
        System.out.println("main: Started emitter");

        System.out.println("main: Running emitter for 50s");
        sleep("main", MS_IN_SEC * 50);
        System.out.println("main: Completed running emitter for 50s");

        System.out.println("main: Stopping emitter");

        emitter.requestStop();
        try {
            emitterThread.join();
            System.out.println("main: Stopped emitter");
        } catch ( InterruptedException e ) {
            System.out.println("main: Interrupted waiting for emitter to finish");
        }

    }

    public static boolean sleep(String threadName, int mSec) {
        try {
            Thread.sleep(mSec);
        } catch ( InterruptedException e ) {
            System.out.println(threadName + ": Interrupted on delay of [ " + mSec + " ms ]!");
            return false;
        }
        return true;
    }

    public interface Emitter extends Runnable {
        void requestStop();
        boolean getStopped();
    }

    public static Emitter newEmitter(int delayMs) {
        return new Emitter() {
            private boolean stopped;

            public synchronized void requestStop() {
                stopped= true;
            }

            public synchronized boolean getStopped() {
                return stopped;
            }

            public void run() {
                int counter = 0;
                while ( !getStopped() ) {
                    System.out.println("emitter: Count [ " + counter + " ]");
                    counter++;

                    if ( !sleep("emitter", delayMs) ) {
                        break;
                    }
                }

                System.out.println("emitter: Stopped at count [ " + counter + " ]");
            }
        };
    }
}


问:
Select users who have not signed up for an interview
I have two tables, interviews and users.

inteviews looks like this:

users looks like this:

The id column in the user table will match the user column in the interviews table.  How can I select all users that have not signed up for an interview?

(E.g. something along the lines of "select * from interviews left join users on interviews.id <> users.id")

答:
You'd want all the users that does not have an entry in the interviews table:

```<code> SELECT users.* FROM users LEFT JOIN interviews
   ON users.id = interviews.id WHERE interviews.id IS NULL
</code>```

(from the looks of the tables, it sounds like it's users.id that should be joined on interviews.user though)

Body:
You'd want all the users that does not have an entry in the interviews table:

 SELECT users.* FROM users LEFT JOIN interviews
   ON users.id = interviews.id WHERE interviews.id IS NULL

(from the looks of the tables, it sounds like it's users.id that should be joined on interviews.user though)


问:
python regex if some words contain spaces
Problem example:

```<code>str1 = "ur a sh * tty comment ."
</code>```

I need each word from the sentence and wanted to replace sh * tty with sh***tty (replace those spaces inside word with *)

If I try:

```<code>for word in s.split():
    print(word)
</code>```

I get:

```<code>ur
a
sh
*
tty
comment
.
</code>```

sh * tty is now split into 3 words

sh

*

tty

But I need exactly this word sh * tty so then I can replace spaces with * and make it sh***tty finally.

I can't simply replace spaces with *. I just needed to replace a space with * if that space is inside any English word (typical mistake).

I also tried:

```<code>s = "ur a sh * tty comment ."
makeBad = s.translate ({ord(c): "*" for c in " "})
</code>```

But I wanted not to replace spaces that separate 2 words.

Body:
Problem example:

str1 = "ur a sh * tty comment ."

I need each word from the sentence and wanted to replace sh * tty with sh***tty (replace those spaces inside word with *)

If I try:

for word in s.split():
    print(word)

I get:

ur
a
sh
*
tty
comment
.

sh * tty is now split into 3 words

sh

*

tty

But I need exactly this word sh * tty so then I can replace spaces with * and make it sh***tty finally.

I can't simply replace spaces with *. I just needed to replace a space with * if that space is inside any English word (typical mistake).

I also tried:

s = "ur a sh * tty comment ."
makeBad = s.translate ({ord(c): "*" for c in " "})

But I wanted not to replace spaces that separate 2 words.

Body:
You may use

import re
str1 = "ur a sh * tty comment ."
nw = r"[]*!@#$%^&()[{};:,./<>?\\|`~=_+-]"
print( re.sub(rf'(\S) {nw} (\S)', r'\1***\2' , str1) )

See the Python demo.

Here, the pattern will look like

(\S) []*!@#$%^&()[{};:,./<>?\\|`~=_+-] (\S)

It matches

(\S) - Group 1 (\1): any non-whitespace char

  - a space

[]*!@#$%^&()[{};:,./<>?\\|`~=_+-]</code> - a char form the set: <code>]*!@#$%^&()[{};:,./<>?\|`~=_+-

  - a space

(\S) - Group 2 (\2): any non-whitespace char.


问:
May I store array inside a html element and than use it as an array again
I have to store array in html element, so I can use it later.

I want to get --> arrayFromHtml[0] as [0,1] -->  arrayFromHtml[1] as [1,2]

```

答:
You should store the stringified array, then parse the array to retrieved items. Also, instead of innerHTML I will suggest you to use innerText or textContent when get/set plain text (not htmlString):

```

Body:
You should store the stringified array, then parse the array to retrieved items. Also, instead of innerHTML I will suggest you to use innerText or textContent when get/set plain text (not htmlString):

<p id="demo"></p>

<script>
  var array = JSON.stringify([[0,1], [1,2], [1,2]]);
  document.getElementById("demo").textContent = array;

  var useStoredArray = function(arrayFromHtml){
    console.log(JSON.parse(arrayFromHtml)[0]);
  }
  useStoredArray(document.getElementById("demo").textContent);
</script>


问:
Separating the data from a string filled with multiple data types
I want to turn this string into a list of the dictionaries within it:

”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”

I have multiple columns in a pandas dataframe composed of similar strings to this. Some are only ”[]” or ”[{‘id’: ‘x’, ‘name’: ‘y’}]”, and others have many stringified dictionaries within them.

I have tried

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
list(json.loads(z[1:-1]))
```

<p>And this works fine for when there is only one stringified dictionary (<code>”[{‘id’: ‘x’, ‘name’: ‘y’}]”</code>) but because the dictionaries have shared keys, they cannot simply be  jsonified.</p>

<p>Once this is done, I’ll retrieve the value from <code>name</code> of each and create a list of those.</p>

<p><strong>ANSWERED</strong>
Thanks @Tenacious B</p>

<p>To turn the string into the list of the dicts:</p>

<pre class="lang-py prettyprint-override"><code>import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
data = json.loads(z.replace("'", ""))]) # this will be a list of dicts
</code>```

Output:

[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]
```

<hr>

<p><strong>And</strong> to apply to a pandas dataframe having a column with entries as the above, retrieving only the value from the desired key:</p>

<pre class="lang-py prettyprint-override"><code>import json
df['col'] = df['col'].apply(lambda x: [i['name'] for i in json.loads(x.replace("'", ""))])
</code>```

答:
You can have the same keys in different dicts/json objects, also to loads() you need to replace the ' with ":

import json
z = "[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]"
data = json.loads(z.replace("'", '"')) # this will be a list of dicts
print(data)
```

<p>Output:</p>

```[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]
```

Body:
I want to turn this string into a list of the dictionaries within it:

”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”

I have multiple columns in a pandas dataframe composed of similar strings to this. Some are only ”[]” or ”[{‘id’: ‘x’, ‘name’: ‘y’}]”, and others have many stringified dictionaries within them.

I have tried

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
list(json.loads(z[1:-1]))

And this works fine for when there is only one stringified dictionary (”[{‘id’: ‘x’, ‘name’: ‘y’}]”) but because the dictionaries have shared keys, they cannot simply be  jsonified.

Once this is done, I’ll retrieve the value from name of each and create a list of those.

ANSWERED
Thanks @Tenacious B

To turn the string into the list of the dicts:

import json
z = ”[{‘id’: ‘x’, ‘name’: ‘y’}, {‘id’: ‘p’, ‘name’: ‘q’}]”
data = json.loads(z.replace("'", ""))]) # this will be a list of dicts

Output:

[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]

And to apply to a pandas dataframe having a column with entries as the above, retrieving only the value from the desired key:

import json
df['col'] = df['col'].apply(lambda x: [i['name'] for i in json.loads(x.replace("'", ""))])

Body:
You can have the same keys in different dicts/json objects, also to loads() you need to replace the ' with ":

import json
z = "[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]"
data = json.loads(z.replace("'", '"')) # this will be a list of dicts
print(data)

Output:

[{'id': 'x', 'name': 'y'}, {'id': 'p', 'name': 'q'}]


问:
AWS Lambda not working when deployed with CDK
I am trying to deploy a lambda using AWS CDK and it seems not to be working/deployed properly.
The "box" in the pipeline is green, so no errors are returned.

Everything appears to be fine, but when I ran it manually to test, I receive the next message:

```<code>{
  "errorType": "LambdaException",
  "errorMessage": "Could not find the required 'QuickSight.Lambdas.SpiceRefresh.deps.json'.  This file should be present at the root of the deployment package."
}
</code>```

The issue is that if I download the artefact manually to my machine, and upload it with the Function package upload button, it is working properly.

I have one Stack which contains CfnParametersCode which is the stack I use to create the lambda.

```<code>public class LambdaStack : Stack
{

    public CfnParametersCode LambdaCode { get; set; }

    //code

    private Function BuildSpiceRefreshLambda()
    {
        LambdaCode = Code.FromCfnParameters();

        var func = new Function(this, Constants.Lambda.LambdaName, new FunctionProps
        {
            Code = LambdaCode,
            Handler = Constants.Lambda.LambdaHandler,
            FunctionName = Constants.Lambda.LambdaName,
            MemorySize = 1024,
            Tracing = Tracing.ACTIVE,
            Timeout = Duration.Seconds(480),
            Runtime = Runtime.DOTNET_CORE_2_1,
            Environment = new Dictionary<string, string>()
            {
                {"ENVIRONMENT", Fn.Ref(Constants.EnvironmentVariables.Environment)},
                {"APPLICATION_NAME", Constants.Lambda.ApplicationName},
                {"AWS_ACCOUNT_ID", Fn.Ref("AWS::AccountId")},
                {"LOG_GROUP_NAME", Constants.Lambda.LogGroupName}
            },
            ReservedConcurrentExecutions = 1,
            Role = SpiceRefreshLambdaRole,
            Vpc = this.GetProjectVpc(),
            SecurityGroups = new ISecurityGroup[]
            {
                securityGroup
            }
        });
        return func;
    }
}
</code>```

and then I have the pipeline which one of the steps is build the lambda:

```<code>var lambdaBuild = new PipelineProject(this, "appLambda", new PipelineProjectProps
{
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object>
    {
        ["version"] = "0.2",
        ["phases"] = new Dictionary<string, object>
        {
            ["install"] = new Dictionary<string, object>
            {
                ["commands"] = new string[]
                {
                    "echo \"Installing lambda tools for dotnet\"",
                    "dotnet tool install -g Amazon.Lambda.Tools",
                }
            },
            ["build"] = new Dictionary<string, object>
            {
                ["commands"] = new string[]
                {
                    "echo \"Packaging app lambda\"",
                    "(cd app/src/Lambdas/app.Lambdas.Action; dotnet lambda package)"
                }
            }
        },
        ["artifacts"] = new Dictionary<string, object>
        {
            ["files"] = new[]
            {
                "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/app.Lambdas.Action.zip",
            }
        }
    }),
    Environment = new BuildEnvironment
    {
        BuildImage = LinuxBuildImage.STANDARD_2_0
    }
});

var lambdaBuildOutput = new Artifact_("LambdaBuildOutput");

new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "appPipeline", new PipelineProps
{
    ArtifactBucket = Bucket.FromBucketAttributes(this, "artifact-bucket", new BucketAttributes
    {
        BucketArn = "bucket",
        EncryptionKey = "key"
    }),
    Role = "role",
    Stages = new[]
    {
        new StageProps
        {
            StageName = "Source",
            Actions = new[]
            {
                new CodeCommitSourceAction(new CodeCommitSourceActionProps
                {
                    ActionName = "Source",
                    Repository = code,
                    Output = sourceOutput,
                })
            }
        },
        new StageProps
        {
            StageName = "Build",
            Actions = new[]
            {
                new CodeBuildAction(new CodeBuildActionProps
                {
                    ActionName = "Lambda_Build",
                    Project = lambdaBuild,
                    Input = sourceOutput,
                    Outputs = new[] {lambdaBuildOutput},
                }),
            }
        },
        new StageProps
        {
            StageName = "Deploy",
            Actions = new[]
            {
                new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps
                {
                    ActionName = "DeployLambdaapp",
                    TemplatePath = props.appLambdaStack.StackTemplate,
                    StackName = "appLambdaDeploymentStack",
                    AdminPermissions = true,
                    ParameterOverrides = props.appLambdaStack.LambdaCode.Assign(lambdaBuildOutput.S3Location),
                    ExtraInputs = new[] {lambdaBuildOutput},
                    Role = "role",
                    DeploymentRole = "deployRole"
                }),
            }
        }
    }
});
</code>```

there is more steps but they are not relevant.

so as you can see I am applying the ParameterOverrides to props.appLambdaStack.LambdaCode.Assign(lambdaBuildOutput.S3Location) which seems to be fine, because When the lambda gets created, and it specifies the size, which is the same size as the lambda was supposed to be, but when I execute it I receive that "errorMessage": "Could not find the required 'QuickSight.Lambdas.SpiceRefresh.deps.json'.  This file should be present at the root of the deployment package."

On the result Cloudformation file seems to be fine too:

```<code> "appLambdaF0BB8286": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "Code": {
          "S3Bucket": {
            "Ref": "appLambdaSourceBucketNameParameter"
          },
          "S3Key": {
            "Ref": "appLambdaSourceObjectKeyParameter"
          }
        },
        "Handler": "Constants.Lambda.LambdaHandler",  //same as the constant in c#

        //Rest of the properties
    }
}
</code>```

I checked before creating the post and most of the people had a problem with the handler. Un fortunately if I download manually the object in appLambdaSourceBucketNameParameter, appLambdaSourceObjectKeyParameter and upload it to the lambda, it works perfectly. I think that will exclude my issue.

Any idea what can be wrong?

答:
Found the solution.

The issue is that in the artifact I am returning the lambda .zip

```<code>["files"] = new[]
{
    "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/app.Lambdas.Action.zip",
}
</code>```

But what I really need is to return the binaries of the lambda. (the publish folder)

```<code>["artifacts"] = new Dictionary<string, object>
{
    ["base-directory"] = "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/publish",
    ["files"] = new[] { "**.*" }
}
</code>```

nothing else changed, and it worked.

Cloudformation translation:

before I was exporting artifact::app.Lambdas.Action.zip
then AWS was trying to find the binaries.
Now it is exporting artifact::**.*, so all the files.

Body:
I am trying to deploy a lambda using AWS CDK and it seems not to be working/deployed properly.
The "box" in the pipeline is green, so no errors are returned.

Everything appears to be fine, but when I ran it manually to test, I receive the next message:

{
  "errorType": "LambdaException",
  "errorMessage": "Could not find the required 'QuickSight.Lambdas.SpiceRefresh.deps.json'.  This file should be present at the root of the deployment package."
}

The issue is that if I download the artefact manually to my machine, and upload it with the Function package upload button, it is working properly.

I have one Stack which contains CfnParametersCode which is the stack I use to create the lambda.

public class LambdaStack : Stack
{

    public CfnParametersCode LambdaCode { get; set; }

    //code

    private Function BuildSpiceRefreshLambda()
    {
        LambdaCode = Code.FromCfnParameters();

        var func = new Function(this, Constants.Lambda.LambdaName, new FunctionProps
        {
            Code = LambdaCode,
            Handler = Constants.Lambda.LambdaHandler,
            FunctionName = Constants.Lambda.LambdaName,
            MemorySize = 1024,
            Tracing = Tracing.ACTIVE,
            Timeout = Duration.Seconds(480),
            Runtime = Runtime.DOTNET_CORE_2_1,
            Environment = new Dictionary<string, string>()
            {
                {"ENVIRONMENT", Fn.Ref(Constants.EnvironmentVariables.Environment)},
                {"APPLICATION_NAME", Constants.Lambda.ApplicationName},
                {"AWS_ACCOUNT_ID", Fn.Ref("AWS::AccountId")},
                {"LOG_GROUP_NAME", Constants.Lambda.LogGroupName}
            },
            ReservedConcurrentExecutions = 1,
            Role = SpiceRefreshLambdaRole,
            Vpc = this.GetProjectVpc(),
            SecurityGroups = new ISecurityGroup[]
            {
                securityGroup
            }
        });
        return func;
    }
}

and then I have the pipeline which one of the steps is build the lambda:

var lambdaBuild = new PipelineProject(this, "appLambda", new PipelineProjectProps
{
    BuildSpec = BuildSpec.FromObject(new Dictionary<string, object>
    {
        ["version"] = "0.2",
        ["phases"] = new Dictionary<string, object>
        {
            ["install"] = new Dictionary<string, object>
            {
                ["commands"] = new string[]
                {
                    "echo \"Installing lambda tools for dotnet\"",
                    "dotnet tool install -g Amazon.Lambda.Tools",
                }
            },
            ["build"] = new Dictionary<string, object>
            {
                ["commands"] = new string[]
                {
                    "echo \"Packaging app lambda\"",
                    "(cd app/src/Lambdas/app.Lambdas.Action; dotnet lambda package)"
                }
            }
        },
        ["artifacts"] = new Dictionary<string, object>
        {
            ["files"] = new[]
            {
                "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/app.Lambdas.Action.zip",
            }
        }
    }),
    Environment = new BuildEnvironment
    {
        BuildImage = LinuxBuildImage.STANDARD_2_0
    }
});

var lambdaBuildOutput = new Artifact_("LambdaBuildOutput");

new Amazon.CDK.AWS.CodePipeline.Pipeline(this, "appPipeline", new PipelineProps
{
    ArtifactBucket = Bucket.FromBucketAttributes(this, "artifact-bucket", new BucketAttributes
    {
        BucketArn = "bucket",
        EncryptionKey = "key"
    }),
    Role = "role",
    Stages = new[]
    {
        new StageProps
        {
            StageName = "Source",
            Actions = new[]
            {
                new CodeCommitSourceAction(new CodeCommitSourceActionProps
                {
                    ActionName = "Source",
                    Repository = code,
                    Output = sourceOutput,
                })
            }
        },
        new StageProps
        {
            StageName = "Build",
            Actions = new[]
            {
                new CodeBuildAction(new CodeBuildActionProps
                {
                    ActionName = "Lambda_Build",
                    Project = lambdaBuild,
                    Input = sourceOutput,
                    Outputs = new[] {lambdaBuildOutput},
                }),
            }
        },
        new StageProps
        {
            StageName = "Deploy",
            Actions = new[]
            {
                new CloudFormationCreateUpdateStackAction(new CloudFormationCreateUpdateStackActionProps
                {
                    ActionName = "DeployLambdaapp",
                    TemplatePath = props.appLambdaStack.StackTemplate,
                    StackName = "appLambdaDeploymentStack",
                    AdminPermissions = true,
                    ParameterOverrides = props.appLambdaStack.LambdaCode.Assign(lambdaBuildOutput.S3Location),
                    ExtraInputs = new[] {lambdaBuildOutput},
                    Role = "role",
                    DeploymentRole = "deployRole"
                }),
            }
        }
    }
});

there is more steps but they are not relevant.

so as you can see I am applying the ParameterOverrides to props.appLambdaStack.LambdaCode.Assign(lambdaBuildOutput.S3Location) which seems to be fine, because When the lambda gets created, and it specifies the size, which is the same size as the lambda was supposed to be, but when I execute it I receive that "errorMessage": "Could not find the required 'QuickSight.Lambdas.SpiceRefresh.deps.json'.  This file should be present at the root of the deployment package."

On the result Cloudformation file seems to be fine too:

 "appLambdaF0BB8286": {
      "Type": "AWS::Lambda::Function",
      "Properties": {
        "Code": {
          "S3Bucket": {
            "Ref": "appLambdaSourceBucketNameParameter"
          },
          "S3Key": {
            "Ref": "appLambdaSourceObjectKeyParameter"
          }
        },
        "Handler": "Constants.Lambda.LambdaHandler",  //same as the constant in c#

        //Rest of the properties
    }
}

I checked before creating the post and most of the people had a problem with the handler. Un fortunately if I download manually the object in appLambdaSourceBucketNameParameter, appLambdaSourceObjectKeyParameter and upload it to the lambda, it works perfectly. I think that will exclude my issue.

Any idea what can be wrong?

Body:
Found the solution.

The issue is that in the artifact I am returning the lambda .zip

["files"] = new[]
{
    "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/app.Lambdas.Action.zip",
}

But what I really need is to return the binaries of the lambda. (the publish folder)

["artifacts"] = new Dictionary<string, object>
{
    ["base-directory"] = "app/src/Lambdas/app.Lambdas.Action/bin/Release/netcoreapp2.1/publish",
    ["files"] = new[] { "**.*" }
}

nothing else changed, and it worked.

Cloudformation translation:

before I was exporting artifact::app.Lambdas.Action.zip
then AWS was trying to find the binaries.
Now it is exporting artifact::**.*, so all the files.


问:
Java Script Date Function
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.</p>

```<code>function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}
</code>```

答:
Your function declaration is wrong.  Instead of

function abc {
```

<p>you need to list the parameters, even if it's an empty list, with something like this:</p>

<pre class="lang-js prettyprint-override"><code>function abc () {
</code>```

Title: Java Script Date Function

Body:
Below JS to get current time does not return any value. I am calling the ecmascript function from my jsp page.

function abc{
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

Body:
Your function declaration is wrong.  Instead of

function abc {

you need to list the parameters, even if it's an empty list, with something like this:

function abc () {


问:
Is it possible to create multi page apps in angular?
I am thinking of creating a clone of Food ordering applications like Zomato, and I found out that it uses Angular like routing on certain pages that are at the time of Ordering after selecting a Restaurant.
i.e. the page is not refreshed can be seen from the Reload button on the browser and it seems that the request doesn't go to the server.

While on other sections such as selecting a restaurant the request does seem to get routed by the server.

So my question is that Is it feasible to make a multi-page application in angular?

and if yes then how please provide some links of a demo or something on the Internet, and if no then what should be the architecture of such a Food ordering app?

The architecture I am thinking:

But I am stuck at the problem that how will the server be able to render or request angular to get the data, I know the way angular can request the server to fetch the data using Restful Services but I don't know how the server will be able to pass control to the angular app when user requests for a particular URL that is designed for the angular app such as the URL at the time of ordering.

答: If server wants to get some data from frontend without any request from frontend. then you can use server sent events. You can refer to Angular 2 spring boot server side events. This link have an example which shows that how spring boot can send an event to ui and how ui can get that event. After ui receives this event. You can trigger an http call from ui to backend send the data required by backend.</p>


问:
ASP.NET: how to validate
I have a simple ASP.NET (VB) page with a CompareValidator. I can check to ensure the value is numeric, but I have no idea how to check for the length (business rules require a 7 digit number). Existing code is below:

```<code><asp:TextBox ID="txtPolicyNo" runat="server"
                    BorderStyle="Ridge"></asp:TextBox>

<asp:CompareValidator ID="cvCheckPolicy" runat="server"
                    ErrorMessage="Must be a valid policy number" ControlToValidate="txtPolicyNo"
                    Type="Integer" Operator="DataTypeCheck">
</asp:CompareValidator>
</code>```

How can I accomplish this?

Thanks,

Jason

答:
Use a RangeValidator or RegularExpressionValidator</p>

```<code><asp:RangeValidator id="rvCheckPolicy"
   ControlToValidate="txtPolicyNo"
   MinimumValue="1000000"
   MaximumValue="9999999"
   Type="Integer"
   EnableClientScript="false"
   ErrorMessage="Must be a valid policy number"
   runat="server"/>

<asp:RegularExpressionValidator id="revCheckPolicy"
    ControlToValidate="txtPolicyNo"
    ValidationExpression="\d{7}"
    ErrorMessage="Must be a valid policy number"
    runat="server"/>
</code>```

Title: ASP.NET: how to validate

Body:
I have a simple ASP.NET (VB) page with a CompareValidator. I can check to ensure the value is numeric, but I have no idea how to check for the length (business rules require a 7 digit number). Existing code is below:

<asp:TextBox ID="txtPolicyNo" runat="server"
                    BorderStyle="Ridge"></asp:TextBox>

<asp:CompareValidator ID="cvCheckPolicy" runat="server"
                    ErrorMessage="Must be a valid policy number" ControlToValidate="txtPolicyNo"
                    Type="Integer" Operator="DataTypeCheck">
</asp:CompareValidator>

How can I accomplish this?

Thanks,

Jason

Body:
Use a RangeValidator or RegularExpressionValidator

<asp:RangeValidator id="rvCheckPolicy"
   ControlToValidate="txtPolicyNo"
   MinimumValue="1000000"
   MaximumValue="9999999"
   Type="Integer"
   EnableClientScript="false"
   ErrorMessage="Must be a valid policy number"
   runat="server"/>

<asp:RegularExpressionValidator id="revCheckPolicy"
    ControlToValidate="txtPolicyNo"
    ValidationExpression="\d{7}"
    ErrorMessage="Must be a valid policy number"
    runat="server"/>


答:
Two things.

You are missing () as others pointed out.

Second, I'm not sure what the purpose of the method is, but it can be shortened. See my abcd()

```<code>var a = abc();
var b = abcd();
console.log(a);
console.log(b);

function abc() {
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

function abcd() {
  return new Date().getHours();
}
</code>```

Title: Java Script Date Function

Body:
Two things.

You are missing () as others pointed out.

Second, I'm not sure what the purpose of the method is, but it can be shortened. See my abcd()

var a = abc();
var b = abcd();
console.log(a);
console.log(b);

function abc() {
    var returnString = '';
    var today = new Date();
    var currentTime = today.getHours();
    return currentTime;
}

function abcd() {
  return new Date().getHours();
}


答:
Not like that

You can use JSON.stringify and data attributes

That is assuming you WANT to show 0,1,1,2,1,2 but want to store
[[0,1],[1,2],[1,2]]

```

Title: May I store array inside a html element and than use it as an array again

Body:
I have to store array in html element, so I can use it later.

I want to get --> arrayFromHtml[0] as [0,1] -->  arrayFromHtml[1] as [1,2]

Body:
Not like that

You can use JSON.stringify and data attributes

That is assuming you WANT to show 0,1,1,2,1,2 but want to store
[[0,1],[1,2],[1,2]]

<p id="demo"></p>

<script>
  var array = [
    [0, 1],
    [1, 2],
    [1, 2]
  ];
  document.getElementById("demo").innerHTML = array;
  document.getElementById("demo").dataset.storedarr = JSON.stringify(array);
  // than in another code block, i want to use array as

  var useStoredArray = function(obj) {
    const arrayFromHTML = JSON.parse(obj.dataset.storedarr);
    console.log(arrayFromHTML[0]);
  }
  useStoredArray(document.getElementById("demo"));
</script>


问:
unlocking the system preferences is not working
System Preferences is trying to unlock users & Groups preferences
Unable to open System preferences for the my MacOs High Sierra.

sudo commands helps to provided the access to unlock the usergroups?

答: Only admins can change the settings for the Users&Groups. You need to type in your login (username and password) to be able to change the settings. If you are not an admin on this machine, you need to have somebody else who is type in their credentials.</p>


问:
Is there an easy way to disable linux logs on kubernetes pod containers?
I have a go based application deployed on a kubernetes cluster.

I am using   golang:1.13 as my base image

The /var/log folders on those containers keep filling up causing the pods to evict.

Is there a way where I could specify something in deployment.yaml or something like that where I disable system logs from being written to file system?

答:
There are a few ways to sort this out and solving this issue really depends on your application, environment and your creativity.

The Kubernetes documentation describes a few ways to achieve what you need and on all of them the use of logrotate is in place.

Suggestions are:

Basic logging in Kubernetes -    Example of basic logging in Kubernetes that outputs data to the standard output stream.

Logging at the node level - Describe how to deal with logs ans suggest the use of logrotate.

Cluster-level logging architectures - Describes the use of a node logging agent and the use of a sidecar container with the logging agent.

As an example on how you can use your creativity to sort this out, a simple solution would be to mount a volume on /var/log and save all your logs externally, this way you can have more space to store these logs and you can deal with them externally, cleaning or maintaining as you wish. In this example I'm using a CronJob to "delete" the files.

Example:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: logsvol
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: logsvol
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: counter
spec:
  containers:
  - name: count
    image: busybox
    args:
    - /bin/sh
    - -c
    - >
      i=0;
      while true;
      do
        echo "$i: $(date)" >> /var/log/1.log;
        i=$((i+1));
        sleep 1;
      done
    volumeMounts:
    - name: varlog
      mountPath: /var/log
  volumes:
  - name: varlog
    persistentVolumeClaim:
      claimName: logsvol
```

<p>You can create a CronJob to clean (in this example I'm just listing it) these logs for you: </p>

<pre class="lang-yaml prettyprint-override"><code>apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: logcleaner
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - ls -l /var/log
            volumeMounts:
            - name: varlog
              mountPath: /var/log
          volumes:
          - name: varlog
            persistentVolumeClaim:
              claimName: logsvol
          restartPolicy: OnFailure
</code>```

Body:
There are a few ways to sort this out and solving this issue really depends on your application, environment and your creativity.

The Kubernetes documentation describes a few ways to achieve what you need and on all of them the use of logrotate is in place.

Suggestions are:

Basic logging in Kubernetes -    Example of basic logging in Kubernetes that outputs data to the standard output stream.

Logging at the node level - Describe how to deal with logs ans suggest the use of logrotate.

Cluster-level logging architectures - Describes the use of a node logging agent and the use of a sidecar container with the logging agent.

As an example on how you can use your creativity to sort this out, a simple solution would be to mount a volume on /var/log and save all your logs externally, this way you can have more space to store these logs and you can deal with them externally, cleaning or maintaining as you wish. In this example I'm using a CronJob to "delete" the files.

Example:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: logsvol
spec:
  storageClassName: manual
  capacity:
    storage: 10Gi
  accessModes:
    - ReadWriteOnce
  hostPath:
    path: "/mnt/data"
---
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: logsvol
spec:
  storageClassName: manual
  accessModes:
    - ReadWriteOnce
  resources:
    requests:
      storage: 10Gi
---
apiVersion: v1
kind: Pod
metadata:
  name: counter
spec:
  containers:
  - name: count
    image: busybox
    args:
    - /bin/sh
    - -c
    - >
      i=0;
      while true;
      do
        echo "$i: $(date)" >> /var/log/1.log;
        i=$((i+1));
        sleep 1;
      done
    volumeMounts:
    - name: varlog
      mountPath: /var/log
  volumes:
  - name: varlog
    persistentVolumeClaim:
      claimName: logsvol

You can create a CronJob to clean (in this example I'm just listing it) these logs for you:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: logcleaner
spec:
  schedule: "*/1 * * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: hello
            image: busybox
            args:
            - /bin/sh
            - -c
            - ls -l /var/log
            volumeMounts:
            - name: varlog
              mountPath: /var/log
          volumes:
          - name: varlog
            persistentVolumeClaim:
              claimName: logsvol
          restartPolicy: OnFailure


问:
std::time_point from and to std::string
Am trying to replace some boost::gregorian code using c++20 std::chrono, hoping to remove the boost build depedency.  Code is reading and writing to json (using nlohmann) so ability to convert dates to and from std::string is critical.

Using g++ 9.3.0 on Ubuntu 20.04.  2 compile-time erorrs, one on std::chrono::parse() and the second on std::put_time()

For error A on std::chrono::parse(), I see here that calendar support (P0355R7), that includes chrono::parse, is not yet available in gcc libstdc++.  Anyone know if this is correct or have a link to an ETA for this? or is there something wrong with how I'm calling parse()?

For error B for std::put_time(): since std:put_time() is documented as c++11 feel like I'm missing something silly here.  Also find it strange needing to covert through c's time_t and tm.  Is there a better way to convert std::chrono::time_point directly to std::string without resorting to c?

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

int main(int argc, char *argv[]) {
    std::chrono::system_clock::time_point myDate;

    //Create time point from string
    //Ref: https://en.cppreference.com/w/cpp/chrono/parse
    std::stringstream ss;
    ss << "2020-05-24";
    ss >> std::chrono::parse("%Y-%m-%e", myDate);   //error A: ‘parse’ is not a member of ‘std::chrono’

    //Write time point to string
    //https://en.cppreference.com/w/cpp/io/manip/put_time
    //http://cgi.cse.unsw.edu.au/~cs6771/cppreference/en/cpp/chrono/time_point.html
    std::string dateString;
    std::time_t dateTime = std::chrono::system_clock::to_time_t(myDate);
    std::tm tm = *std::localtime(&dateTime);
    dateString = std::put_time(&tm, "%Y-%m-%e");    //error B: ‘put_time’ is not a member of ‘std’

    //Write out
    std::cout << "date: " << dateString << "\n";

    return 0;
}
</code>```

答:
C++20 <chrono> is still under construction for gcc.  I've seen no public ETA's for it.

Your syntax for std::chrono::parse looks correct.  If you're willing to use a free, open-source, header-only preview of C++20 <chrono> then you can get it to work by adding #include "date/date.h" and using date::parse instead.

Note that the resulting myDate will be 2020-05-24 00:00:00 UTC.

std::put_time lives in the header <iomanip> and is a manipulator.  After adding that header and <iostream> you would use it like this:

```<code>std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << '\n';
</code>```

If you need the output in a std::string, you will have to stream the manipulator to a std::stringstream first.

C++20 <chrono> will provide an alternative to the C API for formatting:

```<code>std::cout << "date: " << std::format("{%Y-%m-%e}", myDate) << '\n';
</code>```

The preview library also provides this with a slightly altered format string:

```<code>std::cout << "date: " << date::format("%Y-%m-%e", myDate) << '\n';
</code>```

Title: std::time_point from and to std::string

Body:
Am trying to replace some boost::gregorian code using c++20 std::chrono, hoping to remove the boost build depedency.  Code is reading and writing to json (using nlohmann) so ability to convert dates to and from std::string is critical.

Using g++ 9.3.0 on Ubuntu 20.04.  2 compile-time erorrs, one on std::chrono::parse() and the second on std::put_time()

For error A on std::chrono::parse(), I see here that calendar support (P0355R7), that includes chrono::parse, is not yet available in gcc libstdc++.  Anyone know if this is correct or have a link to an ETA for this? or is there something wrong with how I'm calling parse()?

For error B for std::put_time(): since std:put_time() is documented as c++11 feel like I'm missing something silly here.  Also find it strange needing to covert through c's time_t and tm.  Is there a better way to convert std::chrono::time_point directly to std::string without resorting to c?

#include <chrono>
#include <string>
#include <sstream>
#include <iostream>

int main(int argc, char *argv[]) {
    std::chrono::system_clock::time_point myDate;

    //Create time point from string
    //Ref: https://en.cppreference.com/w/cpp/chrono/parse
    std::stringstream ss;
    ss << "2020-05-24";
    ss >> std::chrono::parse("%Y-%m-%e", myDate);   //error A: ‘parse’ is not a member of ‘std::chrono’

    //Write time point to string
    //https://en.cppreference.com/w/cpp/io/manip/put_time
    //http://cgi.cse.unsw.edu.au/~cs6771/cppreference/en/cpp/chrono/time_point.html
    std::string dateString;
    std::time_t dateTime = std::chrono::system_clock::to_time_t(myDate);
    std::tm tm = *std::localtime(&dateTime);
    dateString = std::put_time(&tm, "%Y-%m-%e");    //error B: ‘put_time’ is not a member of ‘std’

    //Write out
    std::cout << "date: " << dateString << "\n";

    return 0;
}

Body:
C++20 <chrono> is still under construction for gcc.  I've seen no public ETA's for it.

Your syntax for std::chrono::parse looks correct.  If you're willing to use a free, open-source, header-only preview of C++20 <chrono> then you can get it to work by adding #include "date/date.h" and using date::parse instead.

Note that the resulting myDate will be 2020-05-24 00:00:00 UTC.

std::put_time lives in the header <iomanip> and is a manipulator.  After adding that header and <iostream> you would use it like this:

std::cout << "date: " << std::put_time(&tm, "%Y-%m-%e") << '\n';

If you need the output in a std::string, you will have to stream the manipulator to a std::stringstream first.

C++20 <chrono> will provide an alternative to the C API for formatting:

std::cout << "date: " << std::format("{%Y-%m-%e}", myDate) << '\n';

The preview library also provides this with a slightly altered format string:

std::cout << "date: " << date::format("%Y-%m-%e", myDate) << '\n';


问:
Looking for a way to wait for only all visible elements using Java Selenium WebDriver
I am looking to develop a generic method for my framework that will click a button with a given text. There are some pages in my working application that have hidden buttons with the same text as the target. I need there to be some manner of explicit wait, as some pages take a few seconds to load the elements in. The current implementation does not work because it is waiting for all elements to become visible, when some of them will never load a visible element.

I need a way to wait for some amount of time for the elements that will become visible, but not throw an exception when not all of them do.

```<code>public void clickButtonByText(String buttonText) {
    WebDriverWait wait = new WebDriverWait(driver, PAGE_COMPONENT_LOADING_AVERAGE_TIME);
    String xpath = "//button[normalize-space(text())='" + buttonText + "']";
    WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", button);}
</code>```

答:
Thank you all for the help. This is what I've come up with, and it seems to be working.</p>

```<code>public void clickButtonByText(String buttonText) {
    WebDriverWait wait = new WebDriverWait(driver, PAGE_COMPONENT_LOADING_AVERAGE_TIME);
    String xpath = "//button[normalize-space(text())='" + buttonText + "']";
    List<WebElement> elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xpath)));
    for (WebElement button : elements)  {
        if (button.isDisplayed())   {
            button = wait.until(ExpectedConditions.elementToBeClickable(button));
            clickWithJs(buttonText + " button clicked.", button, PAGE_COMPONENT_LOADING_MIN_TIME);
            break;
        }
    }
}
</code>```

Body:
I am looking to develop a generic method for my framework that will click a button with a given text. There are some pages in my working application that have hidden buttons with the same text as the target. I need there to be some manner of explicit wait, as some pages take a few seconds to load the elements in. The current implementation does not work because it is waiting for all elements to become visible, when some of them will never load a visible element.

I need a way to wait for some amount of time for the elements that will become visible, but not throw an exception when not all of them do.

public void clickButtonByText(String buttonText) {
    WebDriverWait wait = new WebDriverWait(driver, PAGE_COMPONENT_LOADING_AVERAGE_TIME);
    String xpath = "//button[normalize-space(text())='" + buttonText + "']";
    WebElement button = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpath)));
    JavascriptExecutor executor = (JavascriptExecutor) driver;
    executor.executeScript("arguments[0].click();", button);}

Body:
Thank you all for the help. This is what I've come up with, and it seems to be working.

public void clickButtonByText(String buttonText) {
    WebDriverWait wait = new WebDriverWait(driver, PAGE_COMPONENT_LOADING_AVERAGE_TIME);
    String xpath = "//button[normalize-space(text())='" + buttonText + "']";
    List<WebElement> elements = wait.until(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(xpath)));
    for (WebElement button : elements)  {
        if (button.isDisplayed())   {
            button = wait.until(ExpectedConditions.elementToBeClickable(button));
            clickWithJs(buttonText + " button clicked.", button, PAGE_COMPONENT_LOADING_MIN_TIME);
            break;
        }
    }
}


答:
```<code>SELECT u.*
FROM Users u
LEFT JOIN Interviews i ON u.id = i.user
WHERE i.id IS NULL
</code>```

Title: Select users who have not signed up for an interview

Body:
I have two tables, interviews and users.

inteviews looks like this:

users looks like this:

The id column in the user table will match the user column in the interviews table.  How can I select all users that have not signed up for an interview?

(E.g. something along the lines of "select * from interviews left join users on interviews.id <> users.id")