问:
Requests-html can I get status codes of all requests (or selenium alternative)
I have the following code:

```<code>from requests_html import HTMLSession

ses = HTMLSession()
r = ses.get(MYURL)  # start a headless chrome browser and load MYURL
r.render(keep_page=True)  # This will now 'render' the html page
                          # which means like in a real browser trigger
                          # all requests for dependent links.
                          # like .css, .js, .jpg, .gif

</code>```

Calling render() triggers a load of requests for Javascript, bitmaps, etc.
Is there any way I can get a trace of status codes for each requests.
I'm mostly interested in 404, but 403 and 5xx errors might be interesting as well.

One use case would for example be:

• Go to a page or a sequence of pages

• Then report how many requests failed and which urls were accessed.

If this is not possible with requests-html but reasonably simple with selenium I can switch to selenium

Addendum: ugly work around 1:

I can setup logging to log into a file and set log level to debug.
Then I can try to parse logs of websockets.protocol: which contains strings like
{\\"url\\":\\"https://my.server/example.gif\\",\\"status\\":404,\\"statusText\\":\\"...

Issues:

Activating log level DEBUG into a file seems to activate something else, because suddenly loads of debug info is also logged into stdout.

For example:

```<code>[I:pyppeteer.launcher] Browser listening on: ws://127.0.0.1:45945/devtools/browser/bc5ce097-e67d-455e-8a59-9a4c213263c1
[D:pyppeteer.connection.Connection] SEND: {"id": 1, "method": "Target.setDiscoverTargets", "params": {"discover": true}}
</code>```

Also it's not really fun to parse this in real time and to correlate it with the url I used in my code.

Addendum: ugly work around 2:

Even worse for correlating but nicer for parsing and just identifying 404s and works just if in control of the http server.

Parsing the logs of the log http server with nginx I can even setup a custom logger in csv format with just the data I'm interested in.

Addendum: ugly work around 3:

Using python logging (a dedicated handler and filter for pyppeteer) I can intercept a json string describing the responses from the pyppeteer.connection.CDPSession logger without having stderr become polluted.

The filter allows me to retrieve the data in real time.

This is still quite hackish. So looking for a better solution.

答:
Give the following a try and see if it's what you're after.  It's strictly a pyppeteer version (rather than requests_html) and relies on unexposed private variables so is fairly susceptible to breakage with version updates.

```<code>import asyncio
from pyppeteer import launch
from pyppeteer.network_manager import NetworkManager

def logit(event):
    req = event._request
    print("{0} - {1}".format(req.url, event._status))

async def main():
    browser = await launch({"headless": False})
    page = await browser.newPage()
    page._networkManager.on(NetworkManager.Events.Response, logit)
    await page.goto('https://www.google.com')
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())
</code>```

Checking the source of requests_html the browser page object seems to be buried pretty deep-- so getting at the NetworkManager isn't exactly straightforward.  If you really want it working from within requests_html it's probably easiest to monkeypatch.  Here's an example:

```<code>import asyncio
from requests_html import HTMLSession, TimeoutError, HTML
from pyppeteer.network_manager import NetworkManager
from typing import Optional, Union

def logit(event):
    req = event._request
    print("{0} - {1}".format(req.url, event._status))

async def _async_render(self, *, url: str, script: str = None, scrolldown, sleep: int, wait: float, reload, content: Optional[str], timeout: Union[float, int], keep_page: bool, cookies: list = [{}]):
    """ Handle page creation and js rendering. Internal use for render/arender methods. """
    try:
        page = await self.browser.newPage()
        page._networkManager.on(NetworkManager.Events.Response, logit)

        # Wait before rendering the page, to prevent timeouts.
        await asyncio.sleep(wait)

        if cookies:
            for cookie in cookies:
                if cookie:
                    await page.setCookie(cookie)

        # Load the given page (GET request, obviously.)
        if reload:
            await page.goto(url, options={'timeout': int(timeout * 1000)})
        else:
            await page.goto(f'data:text/html,{self.html}', options={'timeout': int(timeout * 1000)})

        result = None
        if script:
            result = await page.evaluate(script)

        if scrolldown:
            for _ in range(scrolldown):
                await page._keyboard.down('PageDown')
                await asyncio.sleep(sleep)
        else:
            await asyncio.sleep(sleep)

        if scrolldown:
            await page._keyboard.up('PageDown')

        # Return the content of the page, JavaScript evaluated.
        content = await page.content()
        if not keep_page:
            await page.close()
            page = None
        return content, result, page
    except TimeoutError:
        await page.close()
        page = None
        return None

ses = HTMLSession()
r = ses.get('https://www.google.com')  # start a headless chrome browser and load MYURL
html =  r.html
html._async_render = _async_render.__get__(html, HTML)
html.render()
</code>```

Body:
I have the following code:

from requests_html import HTMLSession

ses = HTMLSession()
r = ses.get(MYURL)  # start a headless chrome browser and load MYURL
r.render(keep_page=True)  # This will now 'render' the html page
                          # which means like in a real browser trigger
                          # all requests for dependent links.
                          # like .css, .js, .jpg, .gif

Calling render() triggers a load of requests for Javascript, bitmaps, etc.
Is there any way I can get a trace of status codes for each requests.
I'm mostly interested in 404, but 403 and 5xx errors might be interesting as well.

One use case would for example be:

• Go to a page or a sequence of pages

• Then report how many requests failed and which urls were accessed.

If this is not possible with requests-html but reasonably simple with selenium I can switch to selenium

Addendum: ugly work around 1:

I can setup logging to log into a file and set log level to debug.
Then I can try to parse logs of websockets.protocol: which contains strings like
{\\"url\\":\\"https://my.server/example.gif\\",\\"status\\":404,\\"statusText\\":\\"...

Issues:

Activating log level DEBUG into a file seems to activate something else, because suddenly loads of debug info is also logged into stdout.

For example:

[I:pyppeteer.launcher] Browser listening on: ws://127.0.0.1:45945/devtools/browser/bc5ce097-e67d-455e-8a59-9a4c213263c1
[D:pyppeteer.connection.Connection] SEND: {"id": 1, "method": "Target.setDiscoverTargets", "params": {"discover": true}}

Also it's not really fun to parse this in real time and to correlate it with the url I used in my code.

Addendum: ugly work around 2:

Even worse for correlating but nicer for parsing and just identifying 404s and works just if in control of the http server.

Parsing the logs of the log http server with nginx I can even setup a custom logger in csv format with just the data I'm interested in.

Addendum: ugly work around 3:

Using python logging (a dedicated handler and filter for pyppeteer) I can intercept a json string describing the responses from the pyppeteer.connection.CDPSession logger without having stderr become polluted.

The filter allows me to retrieve the data in real time.

This is still quite hackish. So looking for a better solution.

Body:
Give the following a try and see if it's what you're after.  It's strictly a pyppeteer version (rather than requests_html) and relies on unexposed private variables so is fairly susceptible to breakage with version updates.

import asyncio
from pyppeteer import launch
from pyppeteer.network_manager import NetworkManager

def logit(event):
    req = event._request
    print("{0} - {1}".format(req.url, event._status))

async def main():
    browser = await launch({"headless": False})
    page = await browser.newPage()
    page._networkManager.on(NetworkManager.Events.Response, logit)
    await page.goto('https://www.google.com')
    await browser.close()

asyncio.get_event_loop().run_until_complete(main())

Checking the source of requests_html the browser page object seems to be buried pretty deep-- so getting at the NetworkManager isn't exactly straightforward.  If you really want it working from within requests_html it's probably easiest to monkeypatch.  Here's an example:

import asyncio
from requests_html import HTMLSession, TimeoutError, HTML
from pyppeteer.network_manager import NetworkManager
from typing import Optional, Union

def logit(event):
    req = event._request
    print("{0} - {1}".format(req.url, event._status))

async def _async_render(self, *, url: str, script: str = None, scrolldown, sleep: int, wait: float, reload, content: Optional[str], timeout: Union[float, int], keep_page: bool, cookies: list = [{}]):
    """ Handle page creation and js rendering. Internal use for render/arender methods. """
    try:
        page = await self.browser.newPage()
        page._networkManager.on(NetworkManager.Events.Response, logit)

        # Wait before rendering the page, to prevent timeouts.
        await asyncio.sleep(wait)

        if cookies:
            for cookie in cookies:
                if cookie:
                    await page.setCookie(cookie)

        # Load the given page (GET request, obviously.)
        if reload:
            await page.goto(url, options={'timeout': int(timeout * 1000)})
        else:
            await page.goto(f'data:text/html,{self.html}', options={'timeout': int(timeout * 1000)})

        result = None
        if script:
            result = await page.evaluate(script)

        if scrolldown:
            for _ in range(scrolldown):
                await page._keyboard.down('PageDown')
                await asyncio.sleep(sleep)
        else:
            await asyncio.sleep(sleep)

        if scrolldown:
            await page._keyboard.up('PageDown')

        # Return the content of the page, JavaScript evaluated.
        content = await page.content()
        if not keep_page:
            await page.close()
            page = None
        return content, result, page
    except TimeoutError:
        await page.close()
        page = None
        return None

ses = HTMLSession()
r = ses.get('https://www.google.com')  # start a headless chrome browser and load MYURL
html =  r.html
html._async_render = _async_render.__get__(html, HTML)
html.render()


来源: stackexchange

问:
Running multiple copies of Nodejs corrupting my object data
I have a service which holds a javascript object, lets say obj. Initially when the server starts, the object is empty.
I receive pub sub messages. Each message has two attributes, the type of the message and the data. Based on the type of message, I modify the object.

For example, if I receive a message msg-0 of type start and receive some data abc-0. I add the data to my main object and now my object obj becomes {abc-0}.

Similarly, if I receive another message msg-1 of type start and receive some data abc-1. I add the data to my main object and now my object obj becomes {abc-0, abc-1}.

So imagine I receive 10 such messages then my object obj should look like {abc-0, abc-1, abc-2, abc-3, abc-4, abc-5, abc-6, abc-7, abc-8, abc-9, abc-10},

If I were to run just a single copy of this program, then, everything works fine.

But when I run 3 copies of this program, what I end up with is different. It creates 3 different objects, and  each object holds {abc-0, abc-1, abc-2, abc-3}, {abc-4, abc-5, abc-6} and {abc-7, abc-8, abc-9, abc-10}.

I'm running 3 pods on kubernetes and this problem became evident. And, when I run just one pod, the problem goes away.

What could I be doing wrong? Is it some sort of a common error?

答:
The issue here is that when running separate NodeJS instances, they are separate. They don't share memory. Objects declared in one are completely separate from the others. In order to get this working correctly, the processes need to communicate with each other. I'm not entirely familiar with Kubernetes, but I'm assuming a pod is the equivalent of a process on a Linux system. Please correct me if I'm wrong, but if this is the case, then that will be the source of the issue.

I would approach this issue by requiring timestamps on each chunk of incoming data, then keep a complete copy of the object in each process. When a new chunk comes in, place it in the correct position based on its timestamp and alert all other processes of an update and optionally share the new chunk or the complete object.

If the different processes (pods) are running synchronously (one after each other) then you'll need to inform the next process of the object at that point in time, so it can continue building the object as time goes on.

TL:DR This issue comes from NodeJS processes not sharing memory. In order to fix this, if the processes run concurrently, keep a running log of the object in all instances and alert all others, should new information be received. If not, inform next process of object at the time of process instantiation.

Hope I understood the question correctly, let me know if not.

ContentLicense: CC BY-SA 4.0


问:
Pandas groupby and custom agg lambda function
I have a data frame and I want to aggregate a custom aggregation function.

Right now I have it like a predefined function, but I want to call it as a lambda function. Notice that the predefined function has a parameter that can be change.

from sklearn.datasets import load_boston
import pandas as pd
import numpy as np
bunch = load_boston()

y = bunch.target
X = pd.DataFrame(bunch.data, columns=bunch.feature_names)

def percentile_func(y,PERCENTILE=50):
    return np.percentile(y,PERCENTILE)

X.groupby('CHAS')['CRIM'].agg([percentile_func,'sum', 'count'])
```

答:
Try this:</p>

```<code>X.groupby('CHAS')['CRIM'].agg([lambda x: np.percentile(x, 50),'sum', 'count'])
</code>```

Body:
Try this:

X.groupby('CHAS')['CRIM'].agg([lambda x: np.percentile(x, 50),'sum', 'count'])


问:
Show dynamic content based on clicked tab
I am trying to display content for a particular tab dynamically.

If a particular navigation tab is clicked it has to show the respective contents on the right.

Currently, it's showing all the tab information together. Is there a way this can be handled using jquery/js.

Tab:

```<code><div class="ibm-tab-section">
            <ul class="ibm-tabs" role="tablist">
                <li><a aria-selected="true" role="tab" href="#example2b-tab1">Example 2b Tab 1</a></li>
                <li><a role="tab" href="#example2b-tab2">Example 2b Tab 2</a></li>
                <li><a role="tab" href="#example2b-tab3">Example 2b Tab 3</a></li>
                <li><a role="tab" href="#example2b-tab4">Example 2b Tab 4</a></li>
            </ul>
        </div>
</code>```

Tab 1 content:

```<code>    <div id="example2b-tab1" class="ibm-tabs-content">
            <p>Example 2b Tab 1 contents</p>
        </div>
</code>```

Tab 2 content :

```<code><div id="example2b-tab2" class="ibm-tabs-content">
            <p>Example 2b Tab 2 contents</p>
            <form>
                <p>
                    <select>
                        <option value="">Select one</option>
                        <option value="1">Mr.</option>
                        <option value="1">Mrs.</option>
                        <option value="1">Dude</option>
                    </select>
                </p>
            </form>
        </div>
</code>```

答: You can hide and show the content of different tabs on click on the tabs using jquery and javascript by using the style property of display and making it as none.</p>

Body:
I am trying to display content for a particular tab dynamically.

If a particular navigation tab is clicked it has to show the respective contents on the right.

Currently, it's showing all the tab information together. Is there a way this can be handled using jquery/js.

Tab:

Example 2b Tab 1

Example 2b Tab 2

Example 2b Tab 3

Example 2b Tab 4

Tab 1 content:

Example 2b Tab 1 contents

Tab 2 content :

Example 2b Tab 2 contents

            <form>

                    <select>
                        <option value="">Select one</option>
                        <option value="1">Mr.</option>
                        <option value="1">Mrs.</option>
                        <option value="1">Dude</option>
                    </select>

            </form>


问:
why doesn't my javascript function display my message?
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div></code>```

答:
Firstly you are targeting an input element. Input elements don't have the property innerHTML, they have a value, which represents the text.
See snippet

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name");
  var usrname_value = usname.value;
  var message = greeting + usrname_value;
  //Uncomment to save value
  //usname.value = message;

  //change result
  document.querySelector(".result p").innerHTML = message;
  }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div></code>```

Body:
So i connected a javascript file to my html file. When a button is clicked, it's supposed to display a message but for some reason it doesn't display anything. What am i doing wrong?
(p.s. i know very little about js)

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name").innerHTML = greeting;
}

 BMI Calculator

    <form>

 Fill in the form below

      Name:

      <input type="text" name="name" id="name">
 Weight:

      <input type="number" name="weight">
 Height:

      <input type="number" name="height">

      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other

<input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>

 Your Results

Body:
Firstly you are targeting an input element. Input elements don't have the property innerHTML, they have a value, which represents the text.
See snippet

function calc() {
  greeting = "hello"
  var usname = document.getElementById("name");
  var usrname_value = usname.value;
  var message = greeting + usrname_value;
  //Uncomment to save value
  //usname.value = message;

  //change result
  document.querySelector(".result p").innerHTML = message;
  }

<header>
  <p> BMI Calculator</p>
</header>
<div class="grid">
  <div class=input>
    <form>
      <p> Fill in the form below</p>
      Name: <br>
      <input type="text" name="name" id="name"><br> Weight: <br>
      <input type="number" name="weight"><br> Height: <br>
      <input type="number" name="height"><br>
      <input type="radio" name="gender" value="female">Female
      <input type="radio" name="gender" value="male">Male
      <input type="radio" name="gender" value="other">Other<br>
      <br><input type="button" onclick="calc()" name="calculate" value="calculate">
    </form>
  </div>
  <div class="result">
    <p> Your Results</p>
  </div>
</div>


问:
How to restore jQuery-animated page to initial state when visited via browser's back button?
The website I'm making has a few basic jQuery-animated effects, including the animation that slides the main content from below the lower edge of the browser window when every new page opens, and slides the same content up and out of the browser window when any menu link is clicked, before opening the new page.

When I go back to the previous page using the browser's "back" button, the main content remains hidden (because the last thing that happen to the page was the animation that removed the content out of the browser window).

Question: how can I refresh / reset the page to its initial state when it's visited by clicking the browser's back button?

I assume this can be achieved by forcing a page refresh when it's visited via browser back button - even though I may be wrong. I would greatly appreciate advice on this!

(This topic has been brought up before but somehow none of the answers I found on this website quite solves the issue.)

答:
For starters, your site seems to work fine in Chrome (no hidden content).  However, I see the behavior you describe when I load the page in Firefox.

However, to force your page to 'refresh', you can prevent it from caching in the first place.  Try adding something like this to the  section.

```<code><meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
</code>```

Really, these headers should be pushed from the server.  See this question or this question.

Alternatively, you can check the position of the hidden div when the page loads (in the $(document).ready() section).  If it's not where it's supposed to be, reload the page using location.reload();

For your site, something like this should work.

```<code>window.onload = function() {
  if (document.getElementById("content").offsetParent.offsetTop < 0) {
      location.reload(); }
  }
</code>```

Please note that you should only have ONE window.onload or $(document).ready on your page.  So if you already have one, simply place the if statement in there.

ContentLicense: CC BY-SA 3.0

Body:
For starters, your site seems to work fine in Chrome (no hidden content).  However, I see the behavior you describe when I load the page in Firefox.

However, to force your page to 'refresh', you can prevent it from caching in the first place.  Try adding something like this to the <head> section.

<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">

Really, these headers should be pushed from the server.  See this question or this question.

Alternatively, you can check the position of the hidden div when the page loads (in the $(document).ready() section).  If it's not where it's supposed to be, reload the page using location.reload();

For your site, something like this should work.

window.onload = function() {
  if (document.getElementById("content").offsetParent.offsetTop < 0) {
      location.reload(); }
  }

Please note that you should only have ONE window.onload or $(document).ready on your page.  So if you already have one, simply place the if statement in there.


问:
How to remove elements in ArrayList?
Below is sample code.

How to remove a specific element in ArrayList?

```<code>
import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList <A> valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}
</code>```

Element as still not been removed. What is the solution for this?

答:
In Java every Class is extending Object at some point. Object got a method equals() which every class inherits. You should overwrite it to check if the passed object is equal to the current one.

It would solve your problem with the List. Lets take a look at the ArrayList.remove() JavaDoc - It says:

removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).

ArrayList goes through every entry in the List and calls the equals() method of it to compare it to the passed Object.
So you could append your Class A by overriding the equals method and let it check on some kind of attribute to make sure it's the same Object. You could also implement some other way to make sure the Objects are equal, like generating a hashcode and compare those or the actual object ID.

An example on how you could implement such a way on your Class A:

```<code>Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    @Override
    public boolean equals(Object obj)
    {
        if(obj != null && obj instanceof A)
        {
            A tmp = (A)obj;
            if(tmp.getValue() == this.value) return true;
            else return false;
        }

        return false;
    }
}
</code>```

Title: How to remove elements in ArrayList?

Body:
Below is sample code.

How to remove a specific element in ArrayList?

import java.util.ArrayList;

class A {
    int value;

    public A(int newValue) {
        setValue(newValue);
    }

    public int getValue() {
        return value;
    }

    public void setValue(int newValue) {
        value = newValue;
    }
}

class B {

    ArrayList  valuesOfA = new ArrayList<>();
    valuesOfA.add(new A(5));
    System.out.println("Adding...");
    for (A value: valueOfA) {
        System.out.println(value); //prints the values added.
    }
    valuesOfA.remove(new A(5));
    System.out.println("Removed");
    for (A value: valueOfA) {
        System.out.println(value);
    }
}

Element as still not been removed. What is the solution for this?

Body:
In Java every Class is extending Object at some point. Object got a method equals() which every class inherits. You should overwrite it to check if the passed object is equal to the current one.

It would solve your problem with the List. Lets take a look at the ArrayList.remove() JavaDoc - It says:

removes the element with the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))) (if such an element exists).

ArrayList goes through every entry in the List and calls the equals() method of it to compare it to the passed Object.
So you could append your Class A by overriding the equals method and let it check on some kind of attribute to make sure it's the same Object. You could also implement some other way to make sure the Objects are equal, like generating a hashcode and compare those or the actual object ID.

An example on how you could implement such a way on your Class A:

Class A
{
    int value;
    public A(int newValue)
    {
        setValue(newValue);
    }
    public int getValue()
    {
         return value;
    }
    public void setValue(int newValue)
    {
         value = newValue;
    }
    @Override
    public boolean equals(Object obj)
    {
        if(obj != null && obj instanceof A)
        {
            A tmp = (A)obj;
            if(tmp.getValue() == this.value) return true;
            else return false;
        }

        return false;
    }
}


问:
How to share code between Netlify lambda functions
I have 3 separate functions each in their own folders. All of them make use of a Twilio client and Apollo Client for dealing with SMS and GraphQL server respectively.

Rather than having all the code to instantiate each client (get keys from env etc.) in each file, can it be put somewhere and required in?

I've tried putting the code into a .js file in the top level functions/ folder and requiring it in the function code as below and this works fine locally on netlify dev but errors with Module not found '../twilioClient' when the function is called in live environment.

```<code>/functions
  apolloClient.js
  twilioClient.js
  package.json - specifying deps used by above files
  /auth
    auth.js - require('../apolloClient')
    ...
  /trails
    trails.js - require('../twilioClient') etc.
    ...
</code>```

答:
Posting my interim solution in case it helps before I get a chance to try out @nomadoda's answer.

My functions folder looks like this

```<code>/functions
  /utils
    apolloClient.js
    twilioClient.js
  /receive-sms
  /auth
  /stripe
  /scripts
</code>```

Where auth, scripts, receive-sms and stripe are my lambda functions.

I have "prebuild": "sh scripts/prebuild.sh" in my root package.json which looks like this:

```<code>cp -rf functions/utils functions/receive-sms
cp -rf functions/utils functions/auth
cp -rf functions/utils functions/scripts
cp -rf functions/utils functions/stripe
</code>```

This is also where I cd into each lambda function folder and run yarn to install their dependencies.

Then in my function folders I can make use of the utils code by simply importing from the local /utils folder i.e. const apolloClient = require('./utils/apolloClient');

I also gitignore the copied /utils folders so only the master version of utils is tracked by git.

As I said, it's less than ideal but does work though I hope above answer works for me instead.

Body:
I have 3 separate functions each in their own folders. All of them make use of a Twilio client and Apollo Client for dealing with SMS and GraphQL server respectively.

Rather than having all the code to instantiate each client (get keys from env etc.) in each file, can it be put somewhere and required in?

I've tried putting the code into a .js file in the top level functions/ folder and requiring it in the function code as below and this works fine locally on netlify dev but errors with Module not found '../twilioClient' when the function is called in live environment.

/functions
  apolloClient.js
  twilioClient.js
  package.json - specifying deps used by above files
  /auth
    auth.js - require('../apolloClient')
    ...
  /trails
    trails.js - require('../twilioClient') etc.
    ...

Body:
Posting my interim solution in case it helps before I get a chance to try out @nomadoda's answer.

My functions folder looks like this

/functions
  /utils
    apolloClient.js
    twilioClient.js
  /receive-sms
  /auth
  /stripe
  /scripts

Where auth, scripts, receive-sms and stripe are my lambda functions.

I have "prebuild": "sh scripts/prebuild.sh" in my root package.json which looks like this:

cp -rf functions/utils functions/receive-sms
cp -rf functions/utils functions/auth
cp -rf functions/utils functions/scripts
cp -rf functions/utils functions/stripe

This is also where I cd into each lambda function folder and run yarn to install their dependencies.

Then in my function folders I can make use of the utils code by simply importing from the local /utils folder i.e. const apolloClient = require('./utils/apolloClient');

I also gitignore the copied /utils folders so only the master version of utils is tracked by git.

As I said, it's less than ideal but does work though I hope above answer works for me instead.


问:
efficient way of making a library for different languages and platforms
Hello i need to write 4 libraries in 3 different languages for 2 platforms  for my PCB module to work on the raspberry pi and arduino. Most of the library just contain functions of bit manipulation which will then be passed to a function that will be unique to each language and platform combination.

So basically the 4 libraries will be 90-95% identical. Now i find it very inefficient that i will have to code for all 4 libraries, where all i do is just adjust the syntaxes. This can also be a pain when there is an update that has to be done on the library because you have to update all 4 of them. There has to be a better way of doing this

My idea is to have a core library where it will be written in one language that can be loaded by a some sort of Hardware Abstraction Layer (HAL) written using the three different languages it is needed python, javascript, and c++. My problem is what will that language be. And what will i use to load it into the other languages. Would C be my best option?

答: Probably the simplest option would be to write your library in C++ and to add bindings for that library. That way you will have your "master" library and also you will be able to use the library in other languages. Proposed diagram would look something like this:


问:
Django Logbook Timefield() subtraction for total time
i have been trying to figure how how do I do a simple subtraction between two time fields and show the total time on the admin page as well for confirmation before saving. example would be actual time of arrival - actual time of departure = total flight time

atd = models.TimeField(null=True, default='00:00:00')
ata = models.TimeField(null=True, default='00:00:00')

trying to get atd - ata to get the total flight time, how do i  do this in django.

thanks for your help!

答:
You can try the following</p>

```<code>import datetime
time1 = datetime.datetime.strptime(atd,'%H:%M:%S')
time2 = datetime.datetime.strptime(ata,'%H:%M:%S')
difference = time2-time1
</code>```

Body:
You can try the following

import datetime
time1 = datetime.datetime.strptime(atd,'%H:%M:%S')
time2 = datetime.datetime.strptime(ata,'%H:%M:%S')
difference = time2-time1


问:
How to import stylesheet in angular with id attribute?
I'm trying to integrate a bootstrap dashboard template into an Angular8 project. but I'm getting the resource not found error when I link the css file in index.html,

```<code>  <link rel="stylesheet" href="./src/assets/css/theme.min.css" id="stylesheetLight">
  <link rel="stylesheet" href="./src/assets/css/theme-dark.min.css" id="stylesheetDark">
</code>```

In my template they used an id attribute in each stylesheet. Because of this id attribute (id="stylesheetLight"), I'm not able to import it into; neither style.css nor angular.json. And without specifying the id, the design will be broken.

The error I'm getting when I import in index.html:

How can solve the resource not found error? Or is there any way that I can specify the id in style.css as @import ?

答:
I have the same problem, reason why I want to add id is because i want to do this from https://material.angular.io/guide/theming

```<code><link id="themeAsset" rel="stylesheet" href="/path/to/my/theme-name.css">

function changeTheme(themeName) {
  document.getElementById('themeAsset').href = `/path/to/my/${themeName}.css`;
}
</code>```

so i could change style for whole app styles by click instead of adding classes to every component

Body:
I'm trying to integrate a bootstrap dashboard template into an Angular8 project. but I'm getting the resource not found error when I link the css file in index.html,

  <link rel="stylesheet" href="./src/assets/css/theme.min.css" id="stylesheetLight">
  <link rel="stylesheet" href="./src/assets/css/theme-dark.min.css" id="stylesheetDark">

In my template they used an id attribute in each stylesheet. Because of this id attribute (id="stylesheetLight"), I'm not able to import it into; neither style.css nor angular.json. And without specifying the id, the design will be broken.

The error I'm getting when I import in index.html:

How can solve the resource not found error? Or is there any way that I can specify the id in style.css as @import ?

Body:
I have the same problem, reason why I want to add id is because i want to do this from https://material.angular.io/guide/theming

<link id="themeAsset" rel="stylesheet" href="/path/to/my/theme-name.css">

function changeTheme(themeName) {
  document.getElementById('themeAsset').href = `/path/to/my/${themeName}.css`;
}

so i could change style for whole app styles by click instead of adding classes to every component


问:
RTL issue in string containing English, Hebrew and digits in Android (Java)
I have an issue when mixing in one string English, Hebrew and digits.
The order of digits next to Hebrew is getting reversed, no matter what order I make - fist digit and then text, of first text and then Hebrew - it's getting reversed to: on the left digit, on the right text.
My text example is:

```<code>String leftPart = "10 gr";
int numder = 8;
String hebrewText = "כפות";
String rightPart = hebrewText + " " + number;
String finalString = leftPart + " · " + rightPart; //10 gr · כפות 8
</code>```

I want to display the digit 8 in the end of this string, after the Hebrew word, not before it, but I'm unable to do it even here...it's getting reversed because of the English text in the begging.

Even if I change the order to:

```<code>String rightPart = number + " " + hebrewText ;
</code>```

the result is the same...

Any ideas? It's looks like something simple that I'm missing

答:
A tip for forcing English to be shown nicely when mixed with Hebrew:

Wrap the English (or numbers) words with LRI and PDI (check here: https://unicode.org/reports/tr9/ ) .

For example, instead of these (first word is in English) :

```<code>    <string name="test">ABC היא האפליקציה הכי טובה</string>
    <string name="test2">%1$s היא האפליקציה הכי טובה</string>
</code>```

Use these:

```<code>    <string name="test">\u2066ABC\u2069 היא האפליקציה הכי טובה</string>
    <string name="test2">\u2066%1$s\u2069 היא האפליקציה הכי טובה</string>
</code>```

Other useful ones can be found here:

https://stackoverflow.com/a/10989502/878126

Body:
I have an issue when mixing in one string English, Hebrew and digits.
The order of digits next to Hebrew is getting reversed, no matter what order I make - fist digit and then text, of first text and then Hebrew - it's getting reversed to: on the left digit, on the right text.
My text example is:

String leftPart = "10 gr";
int numder = 8;
String hebrewText = "כפות";
String rightPart = hebrewText + " " + number;
String finalString = leftPart + " · " + rightPart; //10 gr · כפות 8

I want to display the digit 8 in the end of this string, after the Hebrew word, not before it, but I'm unable to do it even here...it's getting reversed because of the English text in the begging.

Even if I change the order to:

String rightPart = number + " " + hebrewText ;

the result is the same...

Any ideas? It's looks like something simple that I'm missing

Body:
A tip for forcing English to be shown nicely when mixed with Hebrew:

Wrap the English (or numbers) words with LRI and PDI (check here: https://unicode.org/reports/tr9/ ) .

For example, instead of these (first word is in English) :

    <string name="test">ABC היא האפליקציה הכי טובה</string>
    <string name="test2">%1$s היא האפליקציה הכי טובה</string>

Use these:

    <string name="test">\u2066ABC\u2069 היא האפליקציה הכי טובה</string>
    <string name="test2">\u2066%1$s\u2069 היא האפליקציה הכי טובה</string>

Other useful ones can be found here:

https://stackoverflow.com/a/10989502/878126


问:
React API fetch returning an empty object
I am having problems of receiving the data from a api fetch,
I am guessing data might received after the console.log()?

How can I fix this?

```<code>fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        console.log(data[0])
      })
</code>```

This code return a object data straight away

```<code>fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false})
      })
      console.log(this.state.api)
</code>```

However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.

Help....

答:
you are trying to resolve a promise and the console log is likely to be executed before the promise returns, try to following code to fetch your data:

```<code>fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false},() => console.log(this.state.api))
      });
</code>```

This always executes the log line after setting the state.

Body:
I am having problems of receiving the data from a api fetch,
I am guessing data might received after the console.log()?

How can I fix this?

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        console.log(data[0])
      })

This code return a object data straight away

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false})
      })
      console.log(this.state.api)

However, I'll need to save the fetched data into the state, but when I call it after saving it, it returns a empty object, that influences me to print the data to UI.

Help....

Body:
you are trying to resolve a promise and the console log is likely to be executed before the promise returns, try to following code to fetch your data:

fetch("https://www.cheapshark.com/api/1.0/games?title=batman")
      .then(response => response.json())
      .then(data => {
        this.setState({api: data[0] ,loading:false},() => console.log(this.state.api))
      });

This always executes the log line after setting the state.


问:
How to covert a Dataframe to a Dataset,having a object reference of the parent class as a composition inside another class?
I am trying to convert a Dataframe to a Dataset, and the java classes structure is as follows:

class A:

public class A {

    private int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}
```

<p>class B:</p>

<pre class="lang-java prettyprint-override"><code>public class B extends A {

    private int b;

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }
}
</code>```

and class C

public class C {

    private A a;

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }
}
```

<p>and the data in the dataframe is as follows :</p>

```+-----+
|  a  |
+-----+
|[1,2]|
+-----+
```

<p>When I am trying to apply Encoders.bean[C](classOf[C]) to the dataframe. The object reference <code>A</code> which is a instance of <code>B</code> in class <code>C</code> is not returning true when I am checking for .isInstanceOf[B], I am getting it as false. The output of Dataset is as follows:</p>

```+-----+
|  a  |
+-----+
|[1,2]|
+-----+
```

<p>How do we get all the fields of A and B under the C object while iterating over it in foreach?</p>

<p>Code :-</p>

```object TestApp extends App {

  implicit val sparkSession = SparkSession.builder()
    .appName("Test-App")
    .config("spark.sql.codegen.wholeStage", value = false)
    .master("local[1]")
    .getOrCreate()

  var schema = new StructType().
    add("a", new ArrayType(new StructType().add("a", IntegerType, true).add("b", IntegerType, true), true))

  var dd = sparkSession.read.schema(schema).json("Test.txt")

  var ff = dd.as(Encoders.bean[C](classOf[C]))
  ff.show(truncate = false)

  ff.foreach(f => {
    println(f.getA.get(0).isInstanceOf[A])//---true
    println(f.getA.get(0).isInstanceOf[B])//---false
  })
```

Content of File : {"a":[{"a":1,"b":2}]}

答:
Spark-catalyst uses google reflection to get schema out of java beans.
Please take a look at the JavaTypeInference.scala#inferDataType. This class uses getters to collect the field name and the returnType of getters to compute the SparkType.

Since class C has getter named getA() with returnType as A and A, in turn, has getter as getA() with returnType as int,
Schema will be created as struct<a:struct> where struct is derived from the getA of class A.

The solution to this problem that I can think of is -

// Modify your class C to have Real class reference rather its super type
public class C {

    private B a;

    public B getA() {
        return a;
    }

    public void setA(B a) {
        this.a = a;
    }
}
```

<p>Output-</p>

```root
 |-- a: struct (nullable = true)
 |    |-- a: integer (nullable = false)
 |    |-- b: integer (nullable = false)

+------+
|a     |
+------+
|[1, 2]|
+------+
```

Body:
I am trying to convert a Dataframe to a Dataset, and the java classes structure is as follows:

class A:

public class A {

    private int a;

    public int getA() {
        return a;
    }

    public void setA(int a) {
        this.a = a;
    }
}

class B:

public class B extends A {

    private int b;

    public int getB() {
        return b;
    }

    public void setB(int b) {
        this.b = b;
    }
}

and class C

public class C {

    private A a;

    public A getA() {
        return a;
    }

    public void setA(A a) {
        this.a = a;
    }
}

and the data in the dataframe is as follows :

+-----+
|  a  |
+-----+
|[1,2]|
+-----+

When I am trying to apply Encoders.bean[C](classOf[C]) to the dataframe. The object reference A which is a instance of B in class C is not returning true when I am checking for .isInstanceOf[B], I am getting it as false. The output of Dataset is as follows:

+-----+
|  a  |
+-----+
|[1,2]|
+-----+

How do we get all the fields of A and B under the C object while iterating over it in foreach?

Code :-

object TestApp extends App {

  implicit val sparkSession = SparkSession.builder()
    .appName("Test-App")
    .config("spark.sql.codegen.wholeStage", value = false)
    .master("local[1]")
    .getOrCreate()

  var schema = new StructType().
    add("a", new ArrayType(new StructType().add("a", IntegerType, true).add("b", IntegerType, true), true))

  var dd = sparkSession.read.schema(schema).json("Test.txt")

  var ff = dd.as(Encoders.bean[C](classOf[C]))
  ff.show(truncate = false)

  ff.foreach(f => {
    println(f.getA.get(0).isInstanceOf[A])//---true
    println(f.getA.get(0).isInstanceOf[B])//---false
  })

Content of File : {"a":[{"a":1,"b":2}]}

Body:
Spark-catalyst uses google reflection to get schema out of java beans.
Please take a look at the JavaTypeInference.scala#inferDataType. This class uses getters to collect the field name and the returnType of getters to compute the SparkType.

Since class C has getter named getA() with returnType as A and A, in turn, has getter as getA() with returnType as int,
Schema will be created as struct<a:struct<a:int>> where struct<a:int> is derived from the getA of class A.

The solution to this problem that I can think of is -

// Modify your class C to have Real class reference rather its super type
public class C {

    private B a;

    public B getA() {
        return a;
    }

    public void setA(B a) {
        this.a = a;
    }
}

Output-

root
 |-- a: struct (nullable = true)
 |    |-- a: integer (nullable = false)
 |    |-- b: integer (nullable = false)

+------+
|a     |
+------+
|[1, 2]|
+------+


问:
I am looking for Objective C example of how to retrieve emails for MacOS and iOS
I am looking for Objective C example of how to retrieve emails for MacOS and iOS. I find examples on sending email(Mac's SBSendEmail sample) but not retrieving email. If anybody knows... thank you.</p>

答:
Have a look at libEtPan!. I use it in an app, works quite well. It's a POP3/IMAP/more lib with a C interface.

It's not very well documented, but the code of etPanKit helped me a lot.

You should read and understand RFC3501 and RFC1939 too. A telnet client (and/or openssl) and Wireshark will be helpful too.


问:
How to call js function in php file?
i have a problem when i want to call js function, the chart is not show up, i dont know how to call js function because i need to show my chart

js function

```<code><script type="text/javascript">
    var ctx = document.getElementById('myChart2').getContext('2d');
    var myChart2 = new Chart(ctx, {
        type: 'line',
        data: {
            labels: $labelChart2, //Jamnya
            datasets: [{
                backgroundColor: 'rgba(232,72,163,0.2)',
                borderColor: '#e848a3',
                label: $dtDateChart2,
                data: $totalChart2,
                fill: true,
                pointRadius: 5,
                pointHoverRadius: 10,
                showLine: true
            }]
        }, options: {
            responsive: true,
            maintainAspectRatio: false,
            title: {
                display: true,
                text: 'Total Online Yesterday',
                position: 'top',
                fontSize: 15,
                fontStyle: 'bold'
            },
            legend: {
                display: false
            },
            elements: {
                point: {
                    pointStyle: 'circle'
                }
            },
            scales: {
                xAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                        labelString: 'TIME'
                    },
                    ticks: {
                        major: {
                            fontStyle: 'bold',
                            fontColor: '#FF0000'
                        }
                    }
                }],
                yAxes: [{
                    display: true,
                    scaleLabel: {
                        display: true,
                    }
                }]
            },
            tooltips:{
                callbacks: {
                    title: function(tooltipItem, data) {
                      return '$dtDateChart2 '+data['labels'][tooltipItem[0]['index']];
                    },
                    label: function(tooltipItem, data) {
                      return 'TOTAL : '+data['datasets'][0]['data'][tooltipItem['index']]+'';
                    },
                },
                titleFontSize: 15,
                bodyFontSize: 15,
                displayColors: false
            }
        }
    });
</script>
</code>```

my php

```<code><canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';

</code>```

anyoone have ever meet with this problem ? when i put in global boddy. the function is call for global and always show value that i define null in other class except class for chart

答:
The issue might be in the following line:

```<code>data: $totalChart2,

</code>```

If $totalChart2 is a php variable, js will not be able to read it.

If your js function is in a php file, you will have to use the following at the least:

```<code>data: <?php echo $totalChart2 ?>,

</code>```

Also make sure the echo command prints a valid js array or object.

Title: How to call js function in php file?

Body:
i have a problem when i want to call js function, the chart is not show up, i dont know how to call js function because i need to show my chart

js function

my php

<canvas id="myChart2" class="canpas chartjs-render-monitor" style="display: block; width: 454px; height: 300px;" width="454" height="300"></canvas>';

anyoone have ever meet with this problem ? when i put in global boddy. the function is call for global and always show value that i define null in other class except class for chart

Body:
The issue might be in the following line:

data: $totalChart2,

If $totalChart2 is a php variable, js will not be able to read it.

If your js function is in a php file, you will have to use the following at the least:

data: <?php echo $totalChart2 ?>,

Also make sure the echo command prints a valid js array or object.


问:
Tableau data layer to one state only
I'm looking to mask all of the detail in Tableau maps other than the state I'm filtered on.  The data layer can seemingly only be applied to all or nothing.  I'm unable to filter or limit to the dataset to which I'm working.  Seems simple, yet 30min of google search can't find answer.  Thank you!

答: Try this-Right click on the filter state and click show filter.Again right click on filter select "Multiple values(drop down) and then click the Customize and show apply button.Then choose the filter values and apply filter.enter image description here</p>

Title: Tableau data layer to one state only


问:
Can SQL with CASE condition use index in PostgreSQL?
When I write a SQL like
SELECT * FROM table WHERE table.col && object, I could use the index I built (as it support && operator), but with

```<code>SELECT * FROM table WHERE
    CASE
    WHEN table.col && object = true THEN true
    ELSE false
    END
</code>```

It seems I can't use the index?

What is the reason of this? Is there any way to solve it?
Actually I want to implement a logic like CASE WHEN a&&b = true THEN ab END with the support of index, is that possible?

答:
You actually don't need to even use a CASE expression here:

```<code>SELECT *
FROM yourTable
WHERE (some_condition AND a < b) OR (!some_condition AND a > b);
</code>```

That being said, I am surprised that an index cannot be used, because in general your logic can probably be optimized to something like the above, without needing a CASE expression.

Body:
When I write a SQL like
SELECT * FROM table WHERE table.col && object, I could use the index I built (as it support && operator), but with

SELECT * FROM table WHERE
    CASE
    WHEN table.col && object = true THEN true
    ELSE false
    END

It seems I can't use the index?

What is the reason of this? Is there any way to solve it?
Actually I want to implement a logic like CASE WHEN a&&b = true THEN ab END with the support of index, is that possible?

Body:
You actually don't need to even use a CASE expression here:

SELECT *
FROM yourTable
WHERE (some_condition AND a < b) OR (!some_condition AND a > b);

That being said, I am surprised that an index cannot be used, because in general your logic can probably be optimized to something like the above, without needing a CASE expression.


问:
I cannot select main class on netbeans
I created the easiest project "Hello world". But I cannot run it because I cannot choose the main class.

```<code>public class NewMain {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}
</code>```

答:
Solution A

Right click on your project

Select Properties

Click Run

Select your class Package.ClassName

Click OK button

Solution B

Right click on your project

Select Set Configuration, choose Customize

Select your class Package.ClassName

Title: I cannot select main class on netbeans

Body:
I created the easiest project "Hello world". But I cannot run it because I cannot choose the main class.

public class NewMain {
    public static void main(String[] args) {
        System.out.println("Hello world");
    }
}


问:
Javascript form validation
How do I let users know that "there are changes left to be saved on the form if they try to close the browser window?"

I have a form with couple of fields, Now if the user changes some of the fields and clicks on Close button on the browser window, my script should alert him of unsaved changes. How do I implement this? I have put in basic form validation but can't seem to think of a solution for window.close() event. Any sample links would be helpful.

答: You can use the beforeunload even to run a function that checks the default values of successful form controls with their current value. If there are any differences, prompt the user. Otherwise, do nothing.

Title: Javascript form validation


问:
Repeat text + n times with google sheet
Input:

testing 18

Output Goal:

testing1

testing2

testing3

testing4

testing5

....

testing18

Cant seem to get them to count as it print out 18 times.

```<code>=ARRAYFORMULA(TRANSPOSE(SPLIT(JOIN(,REPT(B33&"±",C33)),"±")))
</code>```

答:
Try this:</p>

```<code>=ARRAYFORMULA(B33&ROW(A1:INDEX(A:A,C33)))
</code>```

Title: Repeat text + n times with google sheet

Body:
Input:

testing 18

Output Goal:

testing1

testing2

testing3

testing4

testing5

....

testing18

Cant seem to get them to count as it print out 18 times.

=ARRAYFORMULA(TRANSPOSE(SPLIT(JOIN(,REPT(B33&"±",C33)),"±")))

Body:
Try this:

=ARRAYFORMULA(B33&ROW(A1:INDEX(A:A,C33)))


问:
Show dynamic content based on clicked tab
I am trying to display content for a particular tab dynamically.

If a particular navigation tab is clicked it has to show the respective contents on the right.

Currently, it's showing all the tab information together. Is there a way this can be handled using jquery/js.

Tab:

```<code><div class="ibm-tab-section">
            <ul class="ibm-tabs" role="tablist">
                <li><a aria-selected="true" role="tab" href="#example2b-tab1">Example 2b Tab 1</a></li>
                <li><a role="tab" href="#example2b-tab2">Example 2b Tab 2</a></li>
                <li><a role="tab" href="#example2b-tab3">Example 2b Tab 3</a></li>
                <li><a role="tab" href="#example2b-tab4">Example 2b Tab 4</a></li>
            </ul>
        </div>
</code>```

Tab 1 content:

```<code>    <div id="example2b-tab1" class="ibm-tabs-content">
            <p>Example 2b Tab 1 contents</p>
        </div>
</code>```

Tab 2 content :

```<code><div id="example2b-tab2" class="ibm-tabs-content">
            <p>Example 2b Tab 2 contents</p>
            <form>
                <p>
                    <select>
                        <option value="">Select one</option>
                        <option value="1">Mr.</option>
                        <option value="1">Mrs.</option>
                        <option value="1">Dude</option>
                    </select>
                </p>
            </form>
        </div>
</code>```

答:
Hide all the .ibm-tabs-content elements using CSS

On click of the a element, hide .ibm-tabs-content element and show the respective content element on the basis of href attribute that is mapped.

$(function() {
    $("#example2b-tab1").show();
});
$('.ibm-tabs li a').on('click', function(e) {
  e.preventDefault();
  $('.ibm-tabs-content').hide();
  let IDSelector = $(this).attr('href');
  $(IDSelector).show();
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.ibm-tabs-content {
  display: none;
}</code>```

Example 2b Tab 1

Example 2b Tab 2

Example 2b Tab 3

Example 2b Tab 4

Example 2b Tab 1 contents

Example 2b Tab 2 contents

  <form>

      <select>
        <option value="">Select one</option>
        <option value="1">Mr.</option>
        <option value="1">Mrs.</option>
        <option value="1">Dude</option>
      </select>

  </form>

```

Body:
I am trying to display content for a particular tab dynamically.

If a particular navigation tab is clicked it has to show the respective contents on the right.

Currently, it's showing all the tab information together. Is there a way this can be handled using jquery/js.

Tab:

Example 2b Tab 1

Example 2b Tab 2

Example 2b Tab 3

Example 2b Tab 4

Tab 1 content:

Example 2b Tab 1 contents

Tab 2 content :

Example 2b Tab 2 contents

            <form>

                    <select>
                        <option value="">Select one</option>
                        <option value="1">Mr.</option>
                        <option value="1">Mrs.</option>
                        <option value="1">Dude</option>
                    </select>

            </form>

Body:
Hide all the .ibm-tabs-content elements using CSS

On click of the a element, hide .ibm-tabs-content element and show the respective content element on the basis of href attribute that is mapped.

$(function() {
    $("#example2b-tab1").show();
});
$('.ibm-tabs li a').on('click', function(e) {
  e.preventDefault();
  $('.ibm-tabs-content').hide();
  let IDSelector = $(this).attr('href');
  $(IDSelector).show();
})

.ibm-tabs-content {
  display: none;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ibm-tab-section">
  <ul class="ibm-tabs" role="tablist">
    <li><a aria-selected="true" role="tab" href="#example2b-tab1">Example 2b Tab 1</a></li>
    <li><a role="tab" href="#example2b-tab2">Example 2b Tab 2</a></li>
    <li><a role="tab" href="#example2b-tab3">Example 2b Tab 3</a></li>
    <li><a role="tab" href="#example2b-tab4">Example 2b Tab 4</a></li>
  </ul>
</div>

<div id="example2b-tab1" class="ibm-tabs-content">
  <p>Example 2b Tab 1 contents</p>
</div>

<div id="example2b-tab2" class="ibm-tabs-content">
  <p>Example 2b Tab 2 contents</p>
  <form>
    <p>
      <select>
        <option value="">Select one</option>
        <option value="1">Mr.</option>
        <option value="1">Mrs.</option>
        <option value="1">Dude</option>
      </select>
    </p>
  </form>
</div>


问:
How to check invisible checkbox in android studio
I have created a checkbox with text and set as invisible. Currently it is unchecked and I know the position of the checkbox as I have boxes above. I want the box to be checked and visible when I tap at the position ( invisible at the moment ).

I am not sure if this is possible or not as I could not find anything after hours of Googling.Sharing the codes below.

xml code

```<code>        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_diabetes"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:layout_gravity="center_vertical"
                android:fontFamily="@font/ubuntu_regular"
                android:layout_weight="0.2"
                android:text="@string/diabetes"
                android:textColor="@color/textColorAsh"
                android:textSize="16sp" />

            <CheckBox
                android:id="@+id/check_diabetes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:theme="@style/checkBoxStyle"
                android:visibility="invisible" />
        </LinearLayout>
</code>```

Here is how I am try to make it visible programmatically. However it is not getting visible when I tap on the place where it is rendered.

```<code>       case R.id.check_diabetes:
            if (b == true) {
                tv_diabetes.setTextColor(getResources().getColor(R.color.textColorBlue));
                check_diabetes.setVisibility(View.VISIBLE);
                diabetes = "1";
            } else {...
</code>```

答:
Simply, use onCheckedChangeListener

```<code>checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
  if(isChecked) {
  buttonView.setVisibility = View.VISIBLE
</code>```

}

Body:
I have created a checkbox with text and set as invisible. Currently it is unchecked and I know the position of the checkbox as I have boxes above. I want the box to be checked and visible when I tap at the position ( invisible at the moment ).

I am not sure if this is possible or not as I could not find anything after hours of Googling.Sharing the codes below.

xml code

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="10dp"
            android:layout_marginBottom="5dp"
            android:orientation="horizontal">

            <TextView
                android:id="@+id/tv_diabetes"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:gravity="center_vertical"
                android:layout_gravity="center_vertical"
                android:fontFamily="@font/ubuntu_regular"
                android:layout_weight="0.2"
                android:text="@string/diabetes"
                android:textColor="@color/textColorAsh"
                android:textSize="16sp" />

            <CheckBox
                android:id="@+id/check_diabetes"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:theme="@style/checkBoxStyle"
                android:visibility="invisible" />
        </LinearLayout>

Here is how I am try to make it visible programmatically. However it is not getting visible when I tap on the place where it is rendered.

       case R.id.check_diabetes:
            if (b == true) {
                tv_diabetes.setTextColor(getResources().getColor(R.color.textColorBlue));
                check_diabetes.setVisibility(View.VISIBLE);
                diabetes = "1";
            } else {...

Body:
Simply, use onCheckedChangeListener

checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
  if(isChecked) {
  buttonView.setVisibility = View.VISIBLE

}


问:
How to save images in camera roll in iphone programmatically?
I am developing one application. In that I want to save my pictures in camera roll. So how to save my pictures in camera roll through code?</p>

答: See this blog post..UIImageWriteToSavedPhotosAlbum is your friend..</p>


问:
Trying to figure out how to get this executable containerised for docker
I am having rough time trying to create a docker image that exposes Cloudflare's Tunnel executable for linux. Thus far I got to this stage with my docker image for it (image comes from https://github.com/jakejarvis/docker-cloudflare-argo/blob/master/Dockerfile)

```<code>FROM ubuntu:18.04

LABEL maintainer="Jake Jarvis <jake@jarv.is>"

RUN apt-get update \
  && apt-get install -y --no-install-recommends wget ca-certificates \
  && rm -rf /var/lib/apt/lists/*

RUN wget -O cloudflared.tgz https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz \
  && tar -xzvf cloudflared.tgz \
  && rm cloudflared.tgz \
  && chmod +x cloudflared

ENTRYPOINT ["./cloudflared"]
</code>```

And following official documentation for their kubernetes setup I added it to my deployment as a sidecar via: (here cloudflare-argo:5 is image built from dockerfile above)

```<code>    - name: cloudflare-argo
      image: my-registry/cloudflare-argo:5
      imagePullPolicy: Always
      command: ["cloudflared", "tunnel"]
      args:
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate
      volumeMounts:
        - mountPath: /etc/cloudflared
          name: cloudflare-argo-secret
          readOnly: true
      resources:
        requests:
          cpu: "50m"
        limits:
          cpu: "200m"
  volumes:
    - name: cloudflare-argo-secret
      secret:
        secretName: my-website.com
</code>```

However once I deploy I get CrashLoopBackOff error on my pod with following kubectl describe output

Created container cloudflare-argo

Error: failed to start container "cloudflare-argo": Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"cloudflared\": executable file not found in $PATH": unknown

答:
In your Dockerfile move the cloudflared binary to /usr/local/bin folder instead of running it from current WORKDIR.

```<code>  && chmod +x cloudflared \
  && mv cloudflared /usr/local/bin

ENTRYPOINT ["cloudflared"]
</code>```

Body:
I am having rough time trying to create a docker image that exposes Cloudflare's Tunnel executable for linux. Thus far I got to this stage with my docker image for it (image comes from https://github.com/jakejarvis/docker-cloudflare-argo/blob/master/Dockerfile)

FROM ubuntu:18.04

LABEL maintainer="Jake Jarvis <jake@jarv.is>"

RUN apt-get update \
  && apt-get install -y --no-install-recommends wget ca-certificates \
  && rm -rf /var/lib/apt/lists/*

RUN wget -O cloudflared.tgz https://bin.equinox.io/c/VdrWdbjqyF/cloudflared-stable-linux-amd64.tgz \
  && tar -xzvf cloudflared.tgz \
  && rm cloudflared.tgz \
  && chmod +x cloudflared

ENTRYPOINT ["./cloudflared"]

And following official documentation for their kubernetes setup I added it to my deployment as a sidecar via: (here cloudflare-argo:5 is image built from dockerfile above)

    - name: cloudflare-argo
      image: my-registry/cloudflare-argo:5
      imagePullPolicy: Always
      command: ["cloudflared", "tunnel"]
      args:
        - --url=http://localhost:8080
        - --hostname=my-website
        - --origincert=/etc/cloudflared/cert.pem
        - --no-autoupdate
      volumeMounts:
        - mountPath: /etc/cloudflared
          name: cloudflare-argo-secret
          readOnly: true
      resources:
        requests:
          cpu: "50m"
        limits:
          cpu: "200m"
  volumes:
    - name: cloudflare-argo-secret
      secret:
        secretName: my-website.com

However once I deploy I get CrashLoopBackOff error on my pod with following kubectl describe output

Created container cloudflare-argo

Error: failed to start container "cloudflare-argo": Error response from daemon: OCI runtime create failed: container_linux.go:349: starting container process caused "exec: \"cloudflared\": executable file not found in $PATH": unknown

Body:
In your Dockerfile move the cloudflared binary to /usr/local/bin folder instead of running it from current WORKDIR.

  && chmod +x cloudflared \
  && mv cloudflared /usr/local/bin

ENTRYPOINT ["cloudflared"]


问:
How to send logs to email on exception or error in Symfony?
My requirements: Whenever an error occurs in application send that error logs to email.

I am trying to send any exception/error logs to email which occurs in our app. Here is what I tried but I am not receiving logs in email.

Note: Email sending functionality is working fine because I have tested it in a test controller. But it's not working with this Listener.

What happens when I hit TestController Index Route?

When I vist index route it throws 500 internal server error ( because we intentionality thrown an exception ). However if this exception occurs it should send the logs to email. Because in the ExceptionListener I have coded the email sending of logs. But it is not sending logs (:

ExceptionListener.php:

```<code><?php

namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ExceptionListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onKernelException(EmailService $emailService, ExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $emailService->sendLogToMail("myemail@gmail.com", $message);
        } catch (TransportExceptionInterface $e) {
            //
        }

    }
}
</code>```

I have registered the Listener in services.yaml:

```<code>App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }
</code>```

TestController where I intentionality generate an exception:

```<code><?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Exception;

class TestController extends AbstractController
{

    public function index() {

      throw new Exception("It's bad");

    }

}
</code>```

I am using Symfony v4.4

答:
First your listener's service definition is missing the method property:

- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
```

<p>Now run the following command to list the registered event listeners/handlers for the <code>kernel.exception</code> event.</p>

<pre class="lang-sh prettyprint-override"><code>php app/console debug:event-dispatcher kernel.exception
</code>```

If your listener does not show up check your service configuration.

If it does show up but still isn't invoked check the priority of your listener. It might have a lower priority than the default listeners provided by the framework and the exception may already handled by another listener that stops further propagation of the event.

If this is the case raise the priority (higher priority is called first) of your listener to have it called earlier.

```<code>services:
  App\EventListener\ExceptionListener:
    tags:
      - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 1000 }
</code>```

Body:
My requirements: Whenever an error occurs in application send that error logs to email.

I am trying to send any exception/error logs to email which occurs in our app. Here is what I tried but I am not receiving logs in email.

Note: Email sending functionality is working fine because I have tested it in a test controller. But it's not working with this Listener.

What happens when I hit TestController Index Route?

When I vist index route it throws 500 internal server error ( because we intentionality thrown an exception ). However if this exception occurs it should send the logs to email. Because in the ExceptionListener I have coded the email sending of logs. But it is not sending logs (:

ExceptionListener.php:

<?php

namespace App\EventListener;

use App\Service\EmailService;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;

class ExceptionListener
{
    private $em;

    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    public function onKernelException(EmailService $emailService, ExceptionEvent $event)
    {
        // You get the exception object from the received event
        $exception = $event->getThrowable();
        $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
        );

        try {
            $emailService->sendLogToMail("myemail@gmail.com", $message);
        } catch (TransportExceptionInterface $e) {
            //
        }

    }
}

I have registered the Listener in services.yaml:

App\EventListener\ExceptionListener:
        tags:
            - { name: kernel.event_listener, event: kernel.exception }

TestController where I intentionality generate an exception:

<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Exception;

class TestController extends AbstractController
{

    public function index() {

      throw new Exception("It's bad");

    }

}

I am using Symfony v4.4

Body:
First your listener's service definition is missing the method property:

- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

Now run the following command to list the registered event listeners/handlers for the kernel.exception event.

php app/console debug:event-dispatcher kernel.exception

If your listener does not show up check your service configuration.

If it does show up but still isn't invoked check the priority of your listener. It might have a lower priority than the default listeners provided by the framework and the exception may already handled by another listener that stops further propagation of the event.

If this is the case raise the priority (higher priority is called first) of your listener to have it called earlier.

services:
  App\EventListener\ExceptionListener:
    tags:
      - { name: kernel.event_listener, event: kernel.exception, method: onKernelException, priority: 1000 }


问:
How to get the height of ListView.builder() widgets to be the height of the entire stack?
I have a ListView.builder() inside a column, and I would like to tell the LisView.builder to set the height according to the height of the widget that it will be returning from the builder method. How do I do that? </p>

答: Wrap your ListView in a SizedBox with some fixed height. Setting to children height is impractical since Flutter would have to check the size of every element in the list and calculate the maximum.


问:
No latest (4.3.0.) openCV library in opencv-python via PIP
Im using PyCharm to connect libraries but suppose is similar to using pip install opencv-python
Pycharm shows version 4.2.0.34 for opencv-python library when actual is 4.3.0

going to https://pypi.org/project/opencv-python/ i see only i see 4.2.0 version only.

Going to https://github.com/skvark/opencv-python I can see it was updated two month ago when 4.3 is out and even I can see some note of 4.3.
But Python shows version 4.2.0.34 and features of version 4.3.0 are not working.

Am I doing something wrong or is the only way to have 4.3 build it from source?

答:
Update: As of 6th July 2020, opencv-python wheels for 4.3.0 are available on PyPI. You can see that in the releases link below, and the issue linked to below is now closed. You should be able to install it via pip in the normal way.

Original:
According to the releases page for opencv-python, the latest built version is 4.2.0.34. There is also an open issue for 4.3 not being available, where the build maintainer explained that the newest version of OpenCV can't be built with the same automatic system as the previous versions (it can't be built with manylinux1), so it's not just a matter of triggering a new build. In other words, if you want OpenCV 4.3 for Python on your computer, yes, you will need to build it yourself.


问:
Make on Ubuntu a python executable that runs on Mac
Is there a way to create a python executable on Ubuntu that can also run on Mac?

Note:
This executable doesn't have to run on Linux.

答:
You can't!. Please refer to the following link:

https://dzone.com/articles/making-a-stand-alone-executable-from-a-python-scri

There it state:

The format/extension of the executable will depend on which operating
  system you used for compilation. For example, if you run the
  PyInstaller command on Windows the executable file will be .exe. If
  you run it on Linux the extension will depend on the distribution you
  are using.

A workaround to solve it is:

Run the OS virtually and, create executable in that virtual os and export it later.

WINE works as well! (Though, I didn’t try it myself), refer to the following link https://www.andreafortuna.org/2017/12/27/how-to-cross-compile-a-python-script-into-a-windows-executable-on-linux/


问:
Why does my code work in Xcode Playground but not in my project?
I am trying to parse the metadata.opf file that Calibre uses to manage ebooks with Swift.

I managed to parse the document in a playground:

```<code>
import Foundation

class Metadata: CustomStringConvertible {

    var uuid = ""
    var title = ""
    var creators = [""]
    var serie = ""
    var serieIndex = 0

    var description: String { return
        "UUID: \(uuid)\nTitre: \(title)\nAuteur(s): \(creators)\nSérie: Tome \(serieIndex) de la série \(serie)"
    }

}

class OPFParser: NSObject {
    var xmlParser: XMLParser?
    var metadata: [Metadata] = []
    var xmlText = ""
    var currentMetadata: Metadata?
    var calibreAttributes: [String: String] = [:]
    var isUUID = false

    init(withXML xml: String) {
        if let data = xml.data(using: .utf8){
            xmlParser = XMLParser(data: data)
        }
    }

    func parse() -> [Metadata] {
        xmlParser?.delegate = self
        xmlParser?.parse()
        return metadata
    }
}

extension OPFParser: XMLParserDelegate {
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        xmlText = ""
        if elementName == "metadata" {
            currentMetadata = Metadata()
        }
        if elementName == "meta" {
            //print("\(attributeDict["content"]) : \(attributeDict["name"])")
            if attributeDict["name"] == "calibre:series" {
                if let serie = attributeDict["content"] {
                    currentMetadata?.serie = serie
                }
            }
            if attributeDict["name"] == "calibre:series_index" {
                if let serieIndex = attributeDict["content"] {
                    currentMetadata?.serieIndex = Int(serieIndex) ?? 0
                }
            }
        }
        if elementName == "dc:identifier" {
            if let uuuid = attributeDict["opf:scheme"]{
                if uuuid == "uuid" {
                    isUUID = true
                } else  {isUUID = false}

            }
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        switch elementName {
        case "dc:identifier":
            if isUUID == true {
                currentMetadata?.uuid = xmlText.trimmingCharacters(in: .whitespacesAndNewlines)
            }
        case "dc:title":
            currentMetadata?.title = xmlText.trimmingCharacters(in: .whitespacesAndNewlines)
        case "dc:creator":
            currentMetadata?.creators.append(xmlText.trimmingCharacters(in: .whitespacesAndNewlines))
        case "metadata":
            if let meta = currentMetadata {
                metadata.append(meta)
            }
        default:
            break

    }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        xmlText += string
    }
}

class TestMetadata {
func metadataDisplay() {

    if let xmlUrl = Bundle.main.url(forResource: "metadata1", withExtension: "opf") {
        let xml = try! String(contentsOf: xmlUrl)
        let opfParser = OPFParser(withXML: xml)
        let bandeDessinees = opfParser.parse()
        for bandeDessinee in bandeDessinees {
            bandeDessinee.creators = bandeDessinee.creators.filter({ $0 != ""})
            print(bandeDessinee)
        }
    } else {print("fichier non trouvé")}

}
}

let testMetadata = TestMetadata()

testMetadata.metadataDisplay()

</code>```

The function metadataDisplay works, and prints formatted metadata. Unfortunately, when switched to my project, metadataDisplay doesn't print anything. The bandedessinees array is empty. I'm using the same code, except that i'm calling metadataDisplay from a button in a swiftUI file. I've tried to refactor the code multiple times, modifying the 'init()function of myOPFParser`class, but unfortunately i can't figure out why my metadata are not printed in the console.

Thank you for your help,
Aymane.

Sample metadata.opf file:

```<code><?xml version='1.0' encoding='utf-8'?>
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="uuid_id" version="2.0">
    <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
        <dc:identifier opf:scheme="calibre" id="calibre_id">143</dc:identifier>
        <dc:identifier opf:scheme="uuid" id="uuid_id">03badde9-0932-41ab-bd31-2dbba989a7f5</dc:identifier>
        <dc:title>Tome 1</dc:title>
        <dc:creator opf:file-as="Debeurme, Ludovic" opf:role="aut">Ludovic Debeurme</dc:creator>
        <dc:contributor opf:file-as="calibre" opf:role="bkp">calibre (4.15.0) [https://calibre-ebook.com]</dc:contributor>
        <dc:date>2018-05-20T16:16:27+00:00</dc:date>
        <dc:language>en</dc:language>
        <meta content="{"Ludovic Debeurme": ""}" name="calibre:author_link_map"/>
        <meta content="Epiphania" name="calibre:series"/>
        <meta content="1" name="calibre:series_index"/>
        <meta content="2020-05-16T13:01:05.580464+00:00" name="calibre:timestamp"/>
        <meta content="Tome 1" name="calibre:title_sort"/>
        <meta name="calibre:user_metadata:#shelves" content="{"table": "custom_column_1", "is_editable": true, "is_custom": true, "rec_index": 22, "is_category": true, "is_multiple2": {"ui_to_list": ",", "list_to_ui": ", ", "cache_to_list": "|"}, "name": "Shelves", "is_multiple": "|", "is_csp": false, "category_sort": "value", "#extra#": null, "kind": "field", "#value#": [], "display": {"is_names": false, "description": ""}, "search_terms": ["#shelves"], "datatype": "text", "colnum": 1, "label": "shelves", "link_column": "value", "column": "value"}"/>
    </metadata>
    <guide>
        <reference href="cover.jpg" title="Cover" type="cover"/>
    </guide>
</package>
</code>```

答: I finally got it right, the problem was in the encoding of the XML file. By switching from XMLParser(data: Data) to XMLParser(contentsOf: URL), the parser gave back a non-empty array.

Body:
I am trying to parse the metadata.opf file that Calibre uses to manage ebooks with Swift.

I managed to parse the document in a playground:

import Foundation

class Metadata: CustomStringConvertible {

    var uuid = ""
    var title = ""
    var creators = [""]
    var serie = ""
    var serieIndex = 0

    var description: String { return
        "UUID: \(uuid)\nTitre: \(title)\nAuteur(s): \(creators)\nSérie: Tome \(serieIndex) de la série \(serie)"
    }

}

class OPFParser: NSObject {
    var xmlParser: XMLParser?
    var metadata: [Metadata] = []
    var xmlText = ""
    var currentMetadata: Metadata?
    var calibreAttributes: [String: String] = [:]
    var isUUID = false

    init(withXML xml: String) {
        if let data = xml.data(using: .utf8){
            xmlParser = XMLParser(data: data)
        }
    }

    func parse() -> [Metadata] {
        xmlParser?.delegate = self
        xmlParser?.parse()
        return metadata
    }
}

extension OPFParser: XMLParserDelegate {
    func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
        xmlText = ""
        if elementName == "metadata" {
            currentMetadata = Metadata()
        }
        if elementName == "meta" {
            //print("\(attributeDict["content"]) : \(attributeDict["name"])")
            if attributeDict["name"] == "calibre:series" {
                if let serie = attributeDict["content"] {
                    currentMetadata?.serie = serie
                }
            }
            if attributeDict["name"] == "calibre:series_index" {
                if let serieIndex = attributeDict["content"] {
                    currentMetadata?.serieIndex = Int(serieIndex) ?? 0
                }
            }
        }
        if elementName == "dc:identifier" {
            if let uuuid = attributeDict["opf:scheme"]{
                if uuuid == "uuid" {
                    isUUID = true
                } else  {isUUID = false}

            }
        }
    }

    func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName qName: String?) {
        switch elementName {
        case "dc:identifier":
            if isUUID == true {
                currentMetadata?.uuid = xmlText.trimmingCharacters(in: .whitespacesAndNewlines)
            }
        case "dc:title":
            currentMetadata?.title = xmlText.trimmingCharacters(in: .whitespacesAndNewlines)
        case "dc:creator":
            currentMetadata?.creators.append(xmlText.trimmingCharacters(in: .whitespacesAndNewlines))
        case "metadata":
            if let meta = currentMetadata {
                metadata.append(meta)
            }
        default:
            break

    }
    }

    func parser(_ parser: XMLParser, foundCharacters string: String) {
        xmlText += string
    }
}

class TestMetadata {
func metadataDisplay() {

    if let xmlUrl = Bundle.main.url(forResource: "metadata1", withExtension: "opf") {
        let xml = try! String(contentsOf: xmlUrl)
        let opfParser = OPFParser(withXML: xml)
        let bandeDessinees = opfParser.parse()
        for bandeDessinee in bandeDessinees {
            bandeDessinee.creators = bandeDessinee.creators.filter({ $0 != ""})
            print(bandeDessinee)
        }
    } else {print("fichier non trouvé")}

}
}

let testMetadata = TestMetadata()

testMetadata.metadataDisplay()

The function metadataDisplay works, and prints formatted metadata. Unfortunately, when switched to my project, metadataDisplay doesn't print anything. The bandedessinees array is empty. I'm using the same code, except that i'm calling metadataDisplay from a button in a swiftUI file. I've tried to refactor the code multiple times, modifying the 'init()function of myOPFParser`class, but unfortunately i can't figure out why my metadata are not printed in the console.

Thank you for your help,
Aymane.

Sample metadata.opf file:

<?xml version='1.0' encoding='utf-8'?>
<package xmlns="http://www.idpf.org/2007/opf" unique-identifier="uuid_id" version="2.0">
    <metadata xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:opf="http://www.idpf.org/2007/opf">
        <dc:identifier opf:scheme="calibre" id="calibre_id">143</dc:identifier>
        <dc:identifier opf:scheme="uuid" id="uuid_id">03badde9-0932-41ab-bd31-2dbba989a7f5</dc:identifier>
        <dc:title>Tome 1</dc:title>
        <dc:creator opf:file-as="Debeurme, Ludovic" opf:role="aut">Ludovic Debeurme</dc:creator>
        <dc:contributor opf:file-as="calibre" opf:role="bkp">calibre (4.15.0) [https://calibre-ebook.com]</dc:contributor>
        <dc:date>2018-05-20T16:16:27+00:00</dc:date>
        <dc:language>en</dc:language>
        <meta content="{"Ludovic Debeurme": ""}" name="calibre:author_link_map"/>
        <meta content="Epiphania" name="calibre:series"/>
        <meta content="1" name="calibre:series_index"/>
        <meta content="2020-05-16T13:01:05.580464+00:00" name="calibre:timestamp"/>
        <meta content="Tome 1" name="calibre:title_sort"/>
        <meta name="calibre:user_metadata:#shelves" content="{"table": "custom_column_1", "is_editable": true, "is_custom": true, "rec_index": 22, "is_category": true, "is_multiple2": {"ui_to_list": ",", "list_to_ui": ", ", "cache_to_list": "|"}, "name": "Shelves", "is_multiple": "|", "is_csp": false, "category_sort": "value", "#extra#": null, "kind": "field", "#value#": [], "display": {"is_names": false, "description": ""}, "search_terms": ["#shelves"], "datatype": "text", "colnum": 1, "label": "shelves", "link_column": "value", "column": "value"}"/>
    </metadata>
    <guide>
        <reference href="cover.jpg" title="Cover" type="cover"/>
    </guide>
</package>


问:
how to use apiReources method with `only`?
I'm creating an api with Laravel and I am looking for an easy lazy way to to register Api resources.
I'm currently defining my routes like this:

```<code>Route::apiResource('categories', 'CategoryController')->only(['index', 'show']);
</code>```

I checked Laravel's controller documentation and I saw apiResources method which I can create multiple api resources at once.

the goal:
is to be able to use apiResources with only method like this

```<code>Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);
</code>```

current result:

Call to a member function only() on null

答:
long story short (if you don't want to read the whole story) you can just do it like this:

```<code>Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);
</code>```

When I was writing the question it passed to my mind to check the apiResources declaration and I found this:

```<code>   /**
     * Register an array of API resource controllers.
     *
     * @param  array  $resources
     * @param  array  $options
     * @return void
     */
    public function apiResources(array $resources, array $options = [])
    {
        foreach ($resources as $name => $controller) {
            $this->apiResource($name, $controller, $options);
        }
    }
</code>```

and since it is using apiResource under the hood and it is passing options parameter I can check what are these options

```<code>/**
 * Route an API resource to a controller.
 *
 * @param  string  $name
 * @param  string  $controller
 * @param  array  $options
 * @return \Illuminate\Routing\PendingResourceRegistration
 */
public function apiResource($name, $controller, array $options = [])
{
    $only = ['index', 'show', 'store', 'update', 'destroy'];

    if (isset($options['except'])) {
        $only = array_diff($only, (array) $options['except']);
    }

    return $this->resource($name, $controller, array_merge([
        'only' => $only,
    ], $options));
}
</code>```

Body:
I'm creating an api with Laravel and I am looking for an easy lazy way to to register Api resources.
I'm currently defining my routes like this:

Route::apiResource('categories', 'CategoryController')->only(['index', 'show']);

I checked Laravel's controller documentation and I saw apiResources method which I can create multiple api resources at once.

the goal:
is to be able to use apiResources with only method like this

Route::apiResources(['categories' => 'CategoryController', 'products' => 'ProductController'])->only(['index', 'show']);

current result:

Call to a member function only() on null

Body:
long story short (if you don't want to read the whole story) you can just do it like this:

Route::apiResources(['brands' => 'BrandController', 'categories' => 'CategoryController'], ['only' => ['index', 'show']]);

When I was writing the question it passed to my mind to check the apiResources declaration and I found this:

   /**
     * Register an array of API resource controllers.
     *
     * @param  array  $resources
     * @param  array  $options
     * @return void
     */
    public function apiResources(array $resources, array $options = [])
    {
        foreach ($resources as $name => $controller) {
            $this->apiResource($name, $controller, $options);
        }
    }

and since it is using apiResource under the hood and it is passing options parameter I can check what are these options

/**
 * Route an API resource to a controller.
 *
 * @param  string  $name
 * @param  string  $controller
 * @param  array  $options
 * @return \Illuminate\Routing\PendingResourceRegistration
 */
public function apiResource($name, $controller, array $options = [])
{
    $only = ['index', 'show', 'store', 'update', 'destroy'];

    if (isset($options['except'])) {
        $only = array_diff($only, (array) $options['except']);
    }

    return $this->resource($name, $controller, array_merge([
        'only' => $only,
    ], $options));
}


问:
How to check whether Alert Dialog is open in flutter
I am working on my flutter application and I want to check whether the alert dialog is open or not on the screen .
Can anyone tell me how to do that, basically I want to do some stuff just before and after alert dialog opens and closes.</p>

答:
I had the same problem. Maybe my solution would do any better for someone:

```<code>_isOpen = true;
showDialog(
    context: context,
    child: AlertDialog(
      title: Text("Some title!"),
      content: Text("Some content!"),
    )).then((_) => _isOpen = false);
</code>```

The then will run when the alert closes.

Body:
I had the same problem. Maybe my solution would do any better for someone:

_isOpen = true;
showDialog(
    context: context,
    child: AlertDialog(
      title: Text("Some title!"),
      content: Text("Some content!"),
    )).then((_) => _isOpen = false);

The then will run when the alert closes.


问:
Converting dataframe fraction to float
I would like to convert the string values in column b to float. Wondering how should I make it.</p>

```<code>A    B
1    16-1/4
2    3-1/4
3    21-1/4
4    8-1/4
</code>```

答:
Update:

Give map a try to avoid limit 100 rows on pd.eval

```<code>df['C'] = df.B.str.replace('-', '+').map(pd.eval)
</code>```

Original:

As your comment, it seems you adding the fraction to the whole number, so the solution would be

```<code>df['C'] = pd.eval(df.B.str.replace('-', '+'))

Out[5]:
   A       B      C
0  1  16-1/4  16.25
1  2   3-1/4   3.25
2  3  21-1/4  21.25
3  4   8-1/4   8.25
</code>```

Title: Converting dataframe fraction to float

Body:
I would like to convert the string values in column b to float. Wondering how should I make it.

A    B
1    16-1/4
2    3-1/4
3    21-1/4
4    8-1/4

Body:
Update:

Give map a try to avoid limit 100 rows on pd.eval

df['C'] = df.B.str.replace('-', '+').map(pd.eval)

Original:

As your comment, it seems you adding the fraction to the whole number, so the solution would be

df['C'] = pd.eval(df.B.str.replace('-', '+'))

Out[5]:
   A       B      C
0  1  16-1/4  16.25
1  2   3-1/4   3.25
2  3  21-1/4  21.25
3  4   8-1/4   8.25


答:
Your query is not so much clear.But as per assumption,you can do something like this

SELECT
CASE WHEN table.col && object = true THEN true ELSE false END as
INTO #TEMP_TABLE
FROM table

Then you can create a CLUSTERED/NON_CLUSTERED INDEX

CREATE INDEX idx_col on TABLE #TEMP_TABLE()

Then you can select the result:

SELECT * FROM #TEMP_TABLE WHERE  =

Title: Can SQL with CASE condition use index in PostgreSQL?

Body:
When I write a SQL like
SELECT * FROM table WHERE table.col && object, I could use the index I built (as it support && operator), but with

SELECT * FROM table WHERE
    CASE
    WHEN table.col && object = true THEN true
    ELSE false
    END

It seems I can't use the index?

What is the reason of this? Is there any way to solve it?
Actually I want to implement a logic like CASE WHEN a&&b = true THEN ab END with the support of index, is that possible?