问:
Selenium: get() not working with custom google profile
All what im trying to do is pretty much access whatsapp web where I have my whatsapp already linked, However when I use a custom profile the profile does open, however browser.get("https://web.whatsapp.com) doesn't seem to open. or any browser.get(). What could be the issue?

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException

options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/')
options.add_experimental_option("deatch", True)

browser = webdriver.Chrome(executable_path="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",chrome_options=options)
browser.get("https://web.whatsapp.com/")
</code>```

this is the updated version, it now opens whatsapp web however not in a custom profile, moreover I cant really use webdriver.options(), is there anything extra I have to import?.

```<code>from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/User Data/Default")
browser = webdriver.Chrome(executable_path="/Users/omarassouma/Downloads/chromedriver",options=options)
browser.get("https://web.whatsapp.com/")
</code>```

答:
You need to take care of a couple of things as follows:

To use a Custome Chrome Profile you have to pass the absolute path as follows:

```<code>options.add_argument("user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/User Data/Default")
</code>```

You can find a detailed discussion in How to use Chrome Profile in Selenium Webdriver Python 3

Instead of passing the absolute path of the google-chrome binary, you need to pass the absolute path of the ChromeDriver through the key executable_path.

Additionally, instead of chrome_options you need to use options as chrome_options is deprecated now.

You can find a detailed discussion in DeprecationWarning: use options instead of chrome_options error using Brave Browser With Python Selenium and Chromedriver on Windows

So effectively the line of code will be:

```<code>browser = webdriver.Chrome(executable_path="/path/to/chromedriver", options=options)
</code>```

Body:
All what im trying to do is pretty much access whatsapp web where I have my whatsapp already linked, However when I use a custom profile the profile does open, however browser.get("https://web.whatsapp.com) doesn't seem to open. or any browser.get(). What could be the issue?

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.common.exceptions import NoSuchElementException, TimeoutException, WebDriverException

options = webdriver.ChromeOptions()
options.add_argument('--user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/')
options.add_experimental_option("deatch", True)

browser = webdriver.Chrome(executable_path="/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",chrome_options=options)
browser.get("https://web.whatsapp.com/")

this is the updated version, it now opens whatsapp web however not in a custom profile, moreover I cant really use webdriver.options(), is there anything extra I have to import?.

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager

options = webdriver.ChromeOptions()
options.add_argument("user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/User Data/Default")
browser = webdriver.Chrome(executable_path="/Users/omarassouma/Downloads/chromedriver",options=options)
browser.get("https://web.whatsapp.com/")

Body:
You need to take care of a couple of things as follows:

To use a Custome Chrome Profile you have to pass the absolute path as follows:

options.add_argument("user-data-dir=/Users/omarassouma/Library/Application Support/Google/Chrome/User Data/Default")

You can find a detailed discussion in How to use Chrome Profile in Selenium Webdriver Python 3

Instead of passing the absolute path of the google-chrome binary, you need to pass the absolute path of the ChromeDriver through the key executable_path.

Additionally, instead of chrome_options you need to use options as chrome_options is deprecated now.

You can find a detailed discussion in DeprecationWarning: use options instead of chrome_options error using Brave Browser With Python Selenium and Chromedriver on Windows

So effectively the line of code will be:

browser = webdriver.Chrome(executable_path="/path/to/chromedriver", options=options)


来源: stackexchange

问:
Multiply defined standard allocator
I am trying to compile a C++ DLL with VC++2008. I already compiled it correctly with VC++2010, but with VC++2008, I get the following error:

```<code>1>msvcprt.lib(MSVCP90.dll) : error LNK2005: "public: unsigned short * __cdecl std::allocator<unsigned short>::allocate(unsigned __int64)" (?allocate@?$allocator@G@std@@QEAAPEAG_K@Z) already defined in cuda.obj
1>msvcprt.lib(MSVCP90.dll) : error LNK2005: "public: unsigned short * __cdecl std::allocator<unsigned short>::allocate(unsigned __int64)" (?allocate@?$allocator@G@std@@QEAAPEAG_K@Z) already defined in cuda.obj
</code>```

cuda.obj is compiled using nvcc, but as far as I can tell, I gave nvcc the exact same compiler options than for the other files.

What can I do, and where could this error come from?

答: Make sure that you use the same runtime library, check out this answer for how to set up the projects. Specifically, make sure you use /MTd for both the CUDA build rule and the standard C/C++ build (or /MT).</p>

ContentLicense: CC BY-SA 3.0

Title: Multiply defined standard allocator

Body:
I am trying to compile a C++ DLL with VC++2008. I already compiled it correctly with VC++2010, but with VC++2008, I get the following error:

1>msvcprt.lib(MSVCP90.dll) : error LNK2005: "public: unsigned short * __cdecl std::allocator<unsigned short>::allocate(unsigned __int64)" (?allocate@?$allocator@G@std@@QEAAPEAG_K@Z) already defined in cuda.obj
1>msvcprt.lib(MSVCP90.dll) : error LNK2005: "public: unsigned short * __cdecl std::allocator<unsigned short>::allocate(unsigned __int64)" (?allocate@?$allocator@G@std@@QEAAPEAG_K@Z) already defined in cuda.obj

cuda.obj is compiled using nvcc, but as far as I can tell, I gave nvcc the exact same compiler options than for the other files.

What can I do, and where could this error come from?


问:
CMB2 Attachment image output not works
I used CMB2 in my custom theme and I want to upload custom image in default categories page with CMB2.
Text field are correctly displayed on the front. But wp_get_attachment_image not works correctly. What's wrong goes here?

CMB meta box register:

```<code>    add_action( 'cmb2_admin_init', 'term_metabox_register' );

    function term_metabox_register() {
    $prefix = 'my_term_';

    $cat_field = new_cmb2_box( array(
        'id'            => $prefix . 'term_metabox',
        'title'         => esc_attr__( 'Category Options', 'text-domain' ),
        'object_types'     => array( 'term' ), // Tells CMB2 to use term_meta vs post_meta
        'taxonomies'       => array( 'category' ),
    ) );

    $cat_field->add_field( array(
        'name'             => 'Background Image',
        'desc'             => 'Upload your background image.',
        'id'               => $prefix . 'file',
        'type'             => 'file',
    ) );

    $cat_field->add_field( array(
        'name'             => 'Custom Text',
        'desc'             => 'Custom description.',
        'id'               => $prefix . 'custom_text',
        'type'             => 'text',
    ) );
}
</code>```

Output:

```<code>      $categories = get_the_category();
      $category_id = $categories[0]->cat_ID;

      echo get_term_meta( $category_id, 'my_term_custom_text', 1 ); // This works.
      echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file', 1 ), 'large' ); // Not works.
</code>```

答:
As second argument of get_term_meta(), you must add the string '_id' to your id 'my_term_file'

The resulting key string:

```<code>'my_term_file_id'
</code>```

This would be working :

```<code>echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file_id', 1 ), 'large' );
</code>```

You can see it in the doc : https://github.com/CMB2/CMB2/wiki/Field-Types#css-field-class-31

Title: CMB2 Attachment image output not works

Body:
I used CMB2 in my custom theme and I want to upload custom image in default categories page with CMB2.
Text field are correctly displayed on the front. But wp_get_attachment_image not works correctly. What's wrong goes here?

CMB meta box register:

    add_action( 'cmb2_admin_init', 'term_metabox_register' );

    function term_metabox_register() {
    $prefix = 'my_term_';

    $cat_field = new_cmb2_box( array(
        'id'            => $prefix . 'term_metabox',
        'title'         => esc_attr__( 'Category Options', 'text-domain' ),
        'object_types'     => array( 'term' ), // Tells CMB2 to use term_meta vs post_meta
        'taxonomies'       => array( 'category' ),
    ) );

    $cat_field->add_field( array(
        'name'             => 'Background Image',
        'desc'             => 'Upload your background image.',
        'id'               => $prefix . 'file',
        'type'             => 'file',
    ) );

    $cat_field->add_field( array(
        'name'             => 'Custom Text',
        'desc'             => 'Custom description.',
        'id'               => $prefix . 'custom_text',
        'type'             => 'text',
    ) );
}

Output:

      $categories = get_the_category();
      $category_id = $categories[0]->cat_ID;

      echo get_term_meta( $category_id, 'my_term_custom_text', 1 ); // This works.
      echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file', 1 ), 'large' ); // Not works.

Body:
As second argument of get_term_meta(), you must add the string '_id' to your id 'my_term_file'

The resulting key string:

'my_term_file_id'

This would be working :

echo wp_get_attachment_image( get_term_meta( $category_id, 'my_term_file_id', 1 ), 'large' );

You can see it in the doc : https://github.com/CMB2/CMB2/wiki/Field-Types#css-field-class-31

ContentLicense: CC BY-SA 4.0


问:
Possible to disable "Watch on Youtube" link?
I am building an app where I am embedding videos and specific sections of video clips. For example, it looks like this

```<code><iframe width="640" height="360" src="https://www.youtube.com/embed/pftnJbQjSBA&modestbranding=1&showinfo=0&autoplay=1&controls=0&modestbranding=1&disablekb=1&rel=0&start=10&end=20" frameborder="0"></iframe>
</code>```

Is it possible to disable "Watch on youtube" link so the user doesn't end up navigating elsewhere. Just to be clear, I only want to control the flow while the video is being watched (i.e not trying to interfere with ads or YouTube logo).

答:
So far, I tried a few combinations. I found a way to hide all the links to YouTube, and the Share link.

You might want to play around with the width and height values, to suit your video. But if you change them, you'll have to check for the links around the edges, because if you are off a little, the Share link might be clickable for 1px at the edge or something.

```

I used the Youtube Embed Code Generator, and combined that with the code here: How To Disable YouTube Title Links From Embedded Videos.

The sandbox attribute prevents clicking the YouTube links from working.

Using autoplay=1 in the URL prevents the "Watch on YouTube" link from showing.

If you don't actually want the video to autoplay, JS can be added that stops the video playback after it loads. Something like this Disable HTML5 autoplay browser extension. This worked to both hide the link and stop autoplay.

The style attribute hides the "top bar" links/channel and Share buttons. If you don't care about that, you don't need it. Clicking the Share buttons can provide a way for users to navigate elsewhere, though.

The style attribute also, in this example, hides the controls at the bottom. To show the controls, use style="height:400px; instead. However, this will leave a black bar along the bottom of the video, and cut off the top of the video.

Body:
I am building an app where I am embedding videos and specific sections of video clips. For example, it looks like this

Is it possible to disable "Watch on youtube" link so the user doesn't end up navigating elsewhere. Just to be clear, I only want to control the flow while the video is being watched (i.e not trying to interfere with ads or YouTube logo).

Body:
So far, I tried a few combinations. I found a way to hide all the links to YouTube, and the Share link.

You might want to play around with the width and height values, to suit your video. But if you change them, you'll have to check for the links around the edges, because if you are off a little, the Share link might be clickable for 1px at the edge or something.

<div style="height:351px; width:625px; overflow: hidden;">
  <iframe height="351" width="625"
    src="https://www.youtube.com/embed/XXXXXXXX?theme=dark&autoplay=1&keyboard=1&autohide=2&cc_load_policy=1&modestbranding=1&fs=0&showinfo=0&rel=0&iv_load_policy=3&mute=0&loop=0"
    sandbox="allow-forms allow-scripts allow-pointer-lock allow-same-origin allow-top-navigation"
    style="height:471px; background:#000000; bottom: 61px; position: relative;"
    frameborder="0">
  </iframe>
</div>

I used the Youtube Embed Code Generator, and combined that with the code here: How To Disable YouTube Title Links From Embedded Videos.

The sandbox attribute prevents clicking the YouTube links from working.

Using autoplay=1 in the URL prevents the "Watch on YouTube" link from showing.

If you don't actually want the video to autoplay, JS can be added that stops the video playback after it loads. Something like this Disable HTML5 autoplay browser extension. This worked to both hide the link and stop autoplay.

The style attribute hides the "top bar" links/channel and Share buttons. If you don't care about that, you don't need it. Clicking the Share buttons can provide a way for users to navigate elsewhere, though.

The style attribute also, in this example, hides the controls at the bottom. To show the controls, use style="height:400px; instead. However, this will leave a black bar along the bottom of the video, and cut off the top of the video.


问:
How to iterate over a range and an array of data and set the iterated array values until there's no data using GAS?
This may seem simple to you, but well....here I am.

The code below sets apparently the last value Mangas to all cells in the rangeList , while it should set Alca to A10, Mangas to F10 and stop, because there are only 2 elements.

```<code>const rngs = ["A10", "F10", "J10", "A12", "F12", "J12"];
const rangeList = sheetVendSobEnc.getRangeList(rngs).getRanges();
let coresPartes = ["Alca", "Mangas"]
  for (let a = 0; a < rangeList.length; a++) {
    for (let n = 0; n < coresPartes.length; n++) {
      rangeList[a].setValue(coresPartes[n])
    }
  }
</code>```

Thank you in advance!

答:
I think what you want is this?</p>
```<code>const rngs = ["A10", "F10", "J10", "A12", "F12", "J12"];
const rangeList = sheetVendSobEnc.getRangeList(rngs).getRanges();
let coresPartes = ["Alca", "Mangas"]
  for (let a = 0; a < rangeList.length; a++) {
    if( coresPartes[a] ===  undefined ) return;  // or break i'm no sure
    rangeList[a].setValue(coresPartes[a])
  }
}
</code>```

Body:
This may seem simple to you, but well....here I am.

The code below sets apparently the last value Mangas to all cells in the rangeList , while it should set Alca to A10, Mangas to F10 and stop, because there are only 2 elements.

const rngs = ["A10", "F10", "J10", "A12", "F12", "J12"];
const rangeList = sheetVendSobEnc.getRangeList(rngs).getRanges();
let coresPartes = ["Alca", "Mangas"]
  for (let a = 0; a < rangeList.length; a++) {
    for (let n = 0; n < coresPartes.length; n++) {
      rangeList[a].setValue(coresPartes[n])
    }
  }

Thank you in advance!

Body:
I think what you want is this?

const rngs = ["A10", "F10", "J10", "A12", "F12", "J12"];
const rangeList = sheetVendSobEnc.getRangeList(rngs).getRanges();
let coresPartes = ["Alca", "Mangas"]
  for (let a = 0; a < rangeList.length; a++) {
    if( coresPartes[a] ===  undefined ) return;  // or break i'm no sure
    rangeList[a].setValue(coresPartes[a])
  }
}


问:
Rebuilding historical builds through TFS with version numbers
I have automatic build numbering setup, based on build date/name, using approach proposed by John Robbins from Wintellect described here. So the version/resource file is automatically created on build time but not checked-in.

I wonder how to approach a problem of rebuilding historical versions (based on labels) and having the original build number/name in them. Is it possible to detect 'GetVersion' parameter of MSBuild and try to recreate the original build name from it?

Is it a sane approach anyway? What alternatives do you see?

答:
It's not easy to build a specific changeset (though possible, if you pass the changeset number into your build script and modify the "Get Latest" portion of the build).

However, one easier way of handling this is to create a branch of your code.  You can branch at a specific date or changeset, which will create a copy of code from that point in time.  Your build scripts can then be pointed at this code.

With respect to your versioning problem: you may find that the only sensible way to do this is to hardcode the required version number.  My understanding of your version numbering strategy is that it doesn't relate to anything you can derive from the source (such as the changeset number, date, or file content), and it isn't checked in - so re-calculating it will be pretty complicated!


问:
Prevent calculation inside JSX from rendering
Maybe I am missing something here but I want to do {(dataIndex = dataIndex + 1)} inside some JSX.

I have two nested maps which are pulling together table header and table rows. I need to give each field a unique tabIndex.

Here is a simplified version =>

```<code>let dataIndex = 0;
const rows = data.map((row, index) => {
    return (
      <tr >
        <td />
            {columns.map((column, index2) => {
            return (
                <td tabIndex={dataIndex}>
                {(dataIndex = dataIndex + 1)}
                </td>
                );
            }
        </tr>
    );
}))
</code>```

Ive knocked this together really quickly its not exactly the same and I have abstracted out the bits which dont matter. I just dont understand why dataIndex is being displayed in each data field

答:
My issue was a misunderstanding of tabIndex. I just needed to set every  element to have a tab index of 0, meaning that they would be found by the keyboard.

It was actually just skipping over the table.

Body:
Maybe I am missing something here but I want to do {(dataIndex = dataIndex + 1)} inside some JSX.

I have two nested maps which are pulling together table header and table rows. I need to give each field a unique tabIndex.

Here is a simplified version =>

let dataIndex = 0;
const rows = data.map((row, index) => {
    return (

            {columns.map((column, index2) => {
            return (

                {(dataIndex = dataIndex + 1)}

                );
            }

    );
}))

Ive knocked this together really quickly its not exactly the same and I have abstracted out the bits which dont matter. I just dont understand why dataIndex is being displayed in each data field

Body:
My issue was a misunderstanding of tabIndex. I just needed to set every <td/> element to have a tab index of 0, meaning that they would be found by the keyboard.

It was actually just skipping over the table.


问:
How to restrict props.children in react typescript?
```<code>import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (
        <div className="App">
            <Message>
                <p>Hello World</p>
            </Message>
            <Message>
                <a>Hello World</a>
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>
        </div>
    );
}

export default App;

</code>```
```<code>import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (
        <h1>
            {children}
        </h1>
    );
};

export default Message;

</code>```

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

答:
You can render specific children with React.Children by checking its type.
Below example only renders p tag elements.

```<code>import React, { Children } from "react";

interface Props {
  children: React.ReactElement<HTMLParagraphElement | HTMLHeadElement>[] | React.ReactElement<HTMLParagraphElement | HTMLHeadElement>;
}

const Component: React.FC<Props> = ({ children }) => {
  const elements = Children.map(children, (child) => {
    if ((child as React.ReactElement).type === "p") {
      return child;
    }
    return null;

  })?.filter(Boolean);

  return <div>{elements}</div>;
};

export default Component;
</code>```

Note that type of custom component is a function, not string.
And if you want to check types of nested html elements, you need to recursively check types of react elements children.

I do not know what you are trying to do here, but there may be a better approach than restricting render of children elements.

Body:
import React from 'react';
import './App.css';
import Message from "./components/Message";

function App() {
    return (

            <Message>

Hello World

            </Message>
            <Message>
                Hello World
            </Message>
            <Message>
                <button>Hello World</button>
            </Message>

    );
}

export default App;

import React, {FunctionComponent} from 'react';

interface OwnProps {
    children: React.ReactElement<HTMLParagraphElement>;
}

type Props = OwnProps;

const Message: FunctionComponent<Props> = ({children}) => {

    return (

            {children}

    );
};

export default Message;

The above code I can pass any HTMLElementTag as props.

Is there any way to restrict ReactElement to only specific element ?
For example only with p tag or button tag etc.

Body:
You can render specific children with React.Children by checking its type.
Below example only renders p tag elements.

import React, { Children } from "react";

interface Props {
  children: React.ReactElement<HTMLParagraphElement | HTMLHeadElement>[] | React.ReactElement<HTMLParagraphElement | HTMLHeadElement>;
}

const Component: React.FC<Props> = ({ children }) => {
  const elements = Children.map(children, (child) => {
    if ((child as React.ReactElement).type === "p") {
      return child;
    }
    return null;

  })?.filter(Boolean);

  return <div>{elements}</div>;
};

export default Component;

Note that type of custom component is a function, not string.
And if you want to check types of nested html elements, you need to recursively check types of react elements children.

I do not know what you are trying to do here, but there may be a better approach than restricting render of children elements.


问:
How to detect empty areas on canvas in FabricJS?
I need to check is there any empty areas on canvas in FabricJS and display alert. I think this can be done by detecting pixels on canvas but I have no idea. How to do that?</p>

答:
In case if you wanna track click on an empty area, you can check event.subTargets</p>
```<code>canvas.on('mouse:down', (e) => {
  if (!event.subTargets.length) {
    //do stuff...
  }
})
</code>```

Body:
In case if you wanna track click on an empty area, you can check event.subTargets

canvas.on('mouse:down', (e) => {
  if (!event.subTargets.length) {
    //do stuff...
  }
})


问:
How to replace deprecated SeekToCurrentErrorHandler with DefaultErrorHandler (spring-kafka)?
I am trying to find a way to use the new DefaultErrorHandler instead of deprecated SeekToCurrentErrorHandler in spring-kafka 2.8.1, in order to override the retry default behavior in case of errors. I want to "stop" the retry process, so if an error occurs, no retry should be done.

Now I have, in a config class, the following bean that works as expected:

```<code>@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setErrorHandler(new **SeekToCurrentErrorHandler(new FixedBackOff(0L, 1L)**));
    factory.setConsumerFactory(requestConsumerFactory());
    factory.setReplyTemplate(kafkaTemplate());
    return factory;
}
</code>```

Since in this spring kafka version, the STCEH is deprecated, I tried to do the following, in the same config class:

```<code>@Bean
public DefaultErrorHandler eh() {
    return new DefaultErrorHandler(new FixedBackOff(0, 1));
}
</code>```

But it seems that it is not working. In case of error, the retry number is the default one, as I can see in logs:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] ERROR DefaultErrorHandler              - Backoff FixedBackOff{interval=0, currentAttempts=10, maxAttempts=9} exhausted for topicX

How should this DefaultErrorHandler be used in order to achieve the desired behavior? Or should I use something else?

Thx in advance!

答:
factory.setErrorHandler(new SeekToCurrentErrorHandler(new FixedBackOff(0L, 1L))); Actually, it will retry a delivery up to 1 time (2 delivery attempts). (https://docs.spring.io/spring-kafka/docs/2.7.8/reference/html/#seek-to-current)

The default number of retries is **9(( (FixedBackOff(0L, 9L)) instead of 1 (https://docs.spring.io/spring-kafka/docs/2.8.1/reference/html/#default-eh)

You should try setCommonErrorHandler instead of setErrorHandler like factory.setCommonErrorHandler(new DefaultErrorHandler(new FixedBackOff(0L, 0L));

Body:
I am trying to find a way to use the new DefaultErrorHandler instead of deprecated SeekToCurrentErrorHandler in spring-kafka 2.8.1, in order to override the retry default behavior in case of errors. I want to "stop" the retry process, so if an error occurs, no retry should be done.

Now I have, in a config class, the following bean that works as expected:

@Bean
public KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
    ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
    factory.setErrorHandler(new **SeekToCurrentErrorHandler(new FixedBackOff(0L, 1L)**));
    factory.setConsumerFactory(requestConsumerFactory());
    factory.setReplyTemplate(kafkaTemplate());
    return factory;
}

Since in this spring kafka version, the STCEH is deprecated, I tried to do the following, in the same config class:

@Bean
public DefaultErrorHandler eh() {
    return new DefaultErrorHandler(new FixedBackOff(0, 1));
}

But it seems that it is not working. In case of error, the retry number is the default one, as I can see in logs:

[org.springframework.kafka.KafkaListenerEndpointContainer#0-0-C-1] ERROR DefaultErrorHandler              - Backoff FixedBackOff{interval=0, currentAttempts=10, maxAttempts=9} exhausted for topicX

How should this DefaultErrorHandler be used in order to achieve the desired behavior? Or should I use something else?

Thx in advance!


问:
Ruby regular expression help using match to extract pieces of html doc
I have an HTML document of this format:

```<code><tr><td colspan="4"><span class="fullName">Bill Gussio</span></td></tr>
    <tr>
        <td class="sectionHeader">Contact</td>
        <td class="sectionHeader">Phone</td>
        <td class="sectionHeader">Home</td>
        <td class="sectionHeader">Work</td>
    </tr>
    <tr valign="top">
        <td class="sectionContent"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>
        <td class="sectionContent"><span>Mobile: </span><span>2404173223</span></td>
        <td class="sectionContent"><span>NY</span><br><span>New York</span><br><span>78642</span></td>
        <td class="sectionContent"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>
    </tr>

    <tr><td colspan="4"><hr class="contactSeparator"></td></tr>

    <tr><td colspan="4"><span class="fullName">Eddie Osefo</span></td></tr>
    <tr>
        <td class="sectionHeader">Contact</td>
        <td class="sectionHeader">Phone</td>
        <td class="sectionHeader">Home</td>
        <td class="sectionHeader">Work</td>
    </tr>
    <tr valign="top">
        <td class="sectionContent"><span>Screen Name:</span> <span>eddieOS</span><br><span>Email 1:</span> <span>osefo@wam.umd.edu</span></td>
        <td class="sectionContent"></td>
        <td class="sectionContent"><span></span></td>
        <td class="sectionContent"><span></span></td>
    </tr>

    <tr><td colspan="4"><hr class="contactSeparator"></td></tr>
</code>```

So it alternates - chunk of contact info and then a "contact separator".  I want to grab the contact info so my first obstacle is to grab the chunks in between the contact separator.  I have already figured out the regular expression using rubular.  It is:

```<code>/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/
</code>```

You can check on rubular to verify that this isolates chunks.

However my big issue is that I am having trouble with the ruby code.  I use the built in match function and make prints, but do not get the results I expect.  Here is the code:

```<code>page = agent.get uri.to_s
chunks = page.body.match(/<tr><td colspan="4"><span class="fullName">((.|\s)*?)<hr class="contactSeparator">/).captures

chunks.each do |chunk|
   puts "new chunk: " + chunk.inspect
end
</code>```

Note that page.body is just the body of the html document grabbed by Mechanize.  The html document is much larger but has this format.  So, the unexpected output is below:

```<code>new chunk: "Bill Gussio</span></td></tr>\r\n\t<tr>\r\n\t\t<td class=\"sectionHeader\">Contact</td>\r\n\t\t<td class=\"sectionHeader\">Phone</td>\r\n\t\t<td class=\"sectionHeader\">Home</td>\r\n\t\t<td class=\"sectionHeader\">Work</td>\r\n\t</tr>\r\n\t<tr valign=\"top\">\r\n\t\t<td class=\"sectionContent\"><span>Screen Name:</span> <span>bhjiggy</span><br><span>Email 1:</span> <span>wmgussio@erols.com</span></td>\r\n\t\t<td class=\"sectionContent\"><span>Mobile: </span><span>2404173223</span></td>\r\n\t\t<td class=\"sectionContent\"><span>NY</span><br><span>New York</span><br><span>78642</span></td>\r\n\t\t<td class=\"sectionContent\"><span>MD</span><br><span>Owings Mills</span><br><span>21093</span></td>\r\n\t</tr>\r\n\t\r\n\t<tr><td colspan=\"4\">"
new chunk: ">"
</code>```

There are 2 surprises here for me:

1) There are not 2 matches that contain the chunks of contact info, even though on rubular I have verified that these chunks should be extracted.

2) All of the \r\n\t (line feeds, tabs, etc.) are showing up in the matches.

Can anyone see the issue here?

Alternatively, if anyone knows of a good free AOL contacts importer, that would be great.  I have been using blackbook but it keeps failing for me on AOL and I am attempting to fix it.  Unfortunately, AOL has no contacts API yet.

Thank you!

答:
Use a HTML parser such as hpricot will save you lots of headaches :)

sudo gem install hpricot

It's mostly written in C, so it's fast as well

Here is How to use it:

http://wiki.github.com/why/hpricot/hpricot-basics

OwnerDisplayName: Tony

ContentLicense: CC BY-SA 2.5

Body:
I have an HTML document of this format:

Bill Gussio

        Contact
        Phone
        Home
        Work

        Screen Name: bhjiggy
Email 1: wmgussio@erols.com
        Mobile: 2404173223
        NY
New York
78642
        MD
Owings Mills
21093

Eddie Osefo

        Contact
        Phone
        Home
        Work

        Screen Name: eddieOS
Email 1: osefo@wam.umd.edu

So it alternates - chunk of contact info and then a "contact separator".  I want to grab the contact info so my first obstacle is to grab the chunks in between the contact separator.  I have already figured out the regular expression using rubular.  It is:

/
((.|\s)*?)
/

You can check on rubular to verify that this isolates chunks.

However my big issue is that I am having trouble with the ruby code.  I use the built in match function and make prints, but do not get the results I expect.  Here is the code:

page = agent.get uri.to_s
chunks = page.body.match(/
((.|\s)*?)
/).captures

chunks.each do |chunk|
   puts "new chunk: " + chunk.inspect
end

Note that page.body is just the body of the html document grabbed by Mechanize.  The html document is much larger but has this format.  So, the unexpected output is below:

new chunk: "Bill Gussio
\r\n\t
\r\n\t\tContact	\r\n\t\tPhone	\r\n\t\tHome	\r\n\t\tWork	\r\n\t
\r\n\t
\r\n\t\tScreen Name: bhjiggy
Email 1: wmgussio@erols.com	\r\n\t\tMobile: 2404173223	\r\n\t\tNY
New York
78642	\r\n\t\tMD
Owings Mills
21093	\r\n\t
\r\n\t\r\n\t
"
new chunk: ">"

There are 2 surprises here for me:

1) There are not 2 matches that contain the chunks of contact info, even though on rubular I have verified that these chunks should be extracted.

2) All of the \r\n\t (line feeds, tabs, etc.) are showing up in the matches.

Can anyone see the issue here?

Alternatively, if anyone knows of a good free AOL contacts importer, that would be great.  I have been using blackbook but it keeps failing for me on AOL and I am attempting to fix it.  Unfortunately, AOL has no contacts API yet.

Thank you!

LastEditorDisplayName: Chad Birch

OwnerDisplayName: Aaron Qian


问:
How to disable highlighting effect of TouchableOpacity when scrolling?
```<code><TouchableOpacity style={{ flex: 1 }} >
  <ImageBackground
    source={require('../../images/home.jpg')}>
      <View style={styles.item} collapsable={false}>
        <H3>{contentData[i].name}</H3>
        <Text>{contentData[i].description}</Text>
      </View>
  </ImageBackground>
</TouchableOpacity>
</code>```

I have a list of TouchableOpacity inside a ScrollView. I want to disable highlighting effect of TouchableOpacity. When scrolling I want to highlight only when onPress event is triggered. Because it may confuse the user that it is pressed.

答:
We implemeted a custom Touchable component using TouchableOpacity as click element and a wrapper View handling the opacity of the children elements.

By setting activeOpacity={1} to default and the pressed state to true when clicking, we can delay the rest of the onPress functionality by a unnoticeable 100ms to display an opacity shift when clicking. Which is shipped to the wrapper View. The View is wrapped inside the touchable instead of outside to better preserve styling.

We also added cleanup when component is unmounted in useEffect()

import React, { useEffect, useState } from "react";
import { View, TouchableOpacity } from "react-native";

const Touchable = (props) => {

  const { children, onPress } = props;

  const [pressed, setPressed] = useState(false);

  useEffect(() => {
    return setPressed(false);
  }, []);

  return (
      <TouchableOpacity
        {...props}
        activeOpacity={1}
        onPress={() => {
          setPressed(true);
          setTimeout(() => {
            setPressed(false);
            onPress();
          }, 100);
        }}
      >
        <View style={{opacity: pressed ? 0.8 : 1}}>
        {children}
        </View>
      </TouchableOpacity>

  );
};
export default Touchable;
```

Body:
<TouchableOpacity style={{ flex: 1 }} >
  <ImageBackground
    source={require('../../images/home.jpg')}>
      <View style={styles.item} collapsable={false}>

{contentData[i].name}

        <Text>{contentData[i].description}</Text>
      </View>
  </ImageBackground>
</TouchableOpacity>

I have a list of TouchableOpacity inside a ScrollView. I want to disable highlighting effect of TouchableOpacity. When scrolling I want to highlight only when onPress event is triggered. Because it may confuse the user that it is pressed.


问:
How to rename multiple variables at once?
I have multiple columns with variables I need to reverse-code. Let's say my column names are A,B,C,D and each column has a mix of values from 1-4. I am trying to recode all the 4's as 1's, 3's as 2's. etc.

I am able to do it like this:

```<code>`dataNew$A <- as.numeric(dataNew$A)
levels(dataNew$A)[levels(dataNew$A)=="1"] <- "4"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "3"
levels(dataNew$A)[levels(dataNew$A)=="3"] <- "2"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "1"`
</code>```

Then I could repeat for columns B,  C, D

However, I'm wondering if there is a cleaner way to do this where I can change multiple numbers or multiple columns and numbers at once, rather than individually writing the above code for each column/number combination.

答:
If those are the only data frame values, then you can actually do something very simple, stealing @Michael Dewar's sample data code.

df <- data.frame(
  A = sample(1:4, 50, replace = TRUE),
  B = sample(1:4, 50, replace = TRUE),
  C = sample(1:4, 50, replace = TRUE),
  D = sample(1:4, 50, replace = TRUE)
)

head(df)
#>   A B C D
#> 1 3 4 4 3
#> 2 2 3 3 1
#> 3 1 4 1 2
#> 4 4 1 2 1
#> 5 4 3 3 2
#> 6 1 2 2 1

df <- 5 - df
head(df)
#>   A B C D
#> 1 2 1 1 2
#> 2 3 2 2 4
#> 3 4 1 4 3
#> 4 1 4 3 4
#> 5 1 2 2 3
#> 6 4 3 3 4
```
<p>If your <code>newData</code> is not numeric and you want to convert, you can easily convert into a numeric data frame using:</p>
<pre class="lang-r prettyprint-override"><code>as.data.frame(sapply(newData, as.numeric))
</code>```

However, since it appears your data might be factors, you should be careful how those are converted to as.numeric. See this thread for the details, but you might want to do:

as.data.frame(sapply(newData, \(x) as.numeric(levels(x)[x])))
```

Body:
I have multiple columns with variables I need to reverse-code. Let's say my column names are A,B,C,D and each column has a mix of values from 1-4. I am trying to recode all the 4's as 1's, 3's as 2's. etc.

I am able to do it like this:

`dataNew$A <- as.numeric(dataNew$A)
levels(dataNew$A)[levels(dataNew$A)=="1"] <- "4"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "3"
levels(dataNew$A)[levels(dataNew$A)=="3"] <- "2"
levels(dataNew$A)[levels(dataNew$A)=="2"] <- "1"`

Then I could repeat for columns B,  C, D

However, I'm wondering if there is a cleaner way to do this where I can change multiple numbers or multiple columns and numbers at once, rather than individually writing the above code for each column/number combination.

Body:
If those are the only data frame values, then you can actually do something very simple, stealing @Michael Dewar's sample data code.

df <- data.frame(
  A = sample(1:4, 50, replace = TRUE),
  B = sample(1:4, 50, replace = TRUE),
  C = sample(1:4, 50, replace = TRUE),
  D = sample(1:4, 50, replace = TRUE)
)

head(df)
#>   A B C D
#> 1 3 4 4 3
#> 2 2 3 3 1
#> 3 1 4 1 2
#> 4 4 1 2 1
#> 5 4 3 3 2
#> 6 1 2 2 1

df <- 5 - df
head(df)
#>   A B C D
#> 1 2 1 1 2
#> 2 3 2 2 4
#> 3 4 1 4 3
#> 4 1 4 3 4
#> 5 1 2 2 3
#> 6 4 3 3 4

If your newData is not numeric and you want to convert, you can easily convert into a numeric data frame using:

as.data.frame(sapply(newData, as.numeric))

However, since it appears your data might be factors, you should be careful how those are converted to as.numeric. See this thread for the details, but you might want to do:

as.data.frame(sapply(newData, \(x) as.numeric(levels(x)[x])))


问:
SpringBoot test fails with 'No bean named 'webHandler' available'
I am trying to run SpringBoot Webflux tests but am getting error No bean named 'webHandler' available
I was trying to follow the Spring test docs for webtestclient

The offending line seems to be in setup()

```<code>public WebTestClient webTestClient;

@Before
public void setUp() {
    webTestClient = WebTestClient.bindToApplicationContext(this.context).build();
</code>```

My annotations are:

```<code>@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = MyApplication.class)
@ActiveProfiles("offlineuno")
</code>```

The stack trace is:

```<code>org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'webHandler' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:771)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1111)
    at org.springframework.web.server.adapter.WebHttpHandlerBuilder.applicationContext(WebHttpHandlerBuilder.java:157)
    at org.springframework.test.web.reactive.server.ApplicationContextSpec.initHttpHandlerBuilder(ApplicationContextSpec.java:43)
    at org.springframework.test.web.reactive.server.AbstractMockServerSpec.configureClient(AbstractMockServerSpec.java:86)
    at org.springframework.test.web.reactive.server.AbstractMockServerSpec.build(AbstractMockServerSpec.java:107)
    at com.cme.clearing.btec.risk.btec.entity.management.web.EntityMgmtControllerTest.setUp(MyControllerTest.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
</code>```

Update: As a workaround, I am using

```<code> webTestClient = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();
</code>```

Now I manually run the spring boot server (in IntelliJ) and then run the Test client.

答: Adding @WebFluxTest solves the issue as commented by @aksh1618</p>

Body:
I am trying to run SpringBoot Webflux tests but am getting error No bean named 'webHandler' available
I was trying to follow the Spring test docs for webtestclient

The offending line seems to be in setup()

public WebTestClient webTestClient;

@Before
public void setUp() {
    webTestClient = WebTestClient.bindToApplicationContext(this.context).build();

My annotations are:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = MyApplication.class)
@ActiveProfiles("offlineuno")

The stack trace is:

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'webHandler' available
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:771)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1221)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1111)
    at org.springframework.web.server.adapter.WebHttpHandlerBuilder.applicationContext(WebHttpHandlerBuilder.java:157)
    at org.springframework.test.web.reactive.server.ApplicationContextSpec.initHttpHandlerBuilder(ApplicationContextSpec.java:43)
    at org.springframework.test.web.reactive.server.AbstractMockServerSpec.configureClient(AbstractMockServerSpec.java:86)
    at org.springframework.test.web.reactive.server.AbstractMockServerSpec.build(AbstractMockServerSpec.java:107)
    at com.cme.clearing.btec.risk.btec.entity.management.web.EntityMgmtControllerTest.setUp(MyControllerTest.java:55)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

Update: As a workaround, I am using

 webTestClient = WebTestClient.bindToServer().baseUrl("http://localhost:8080").build();

Now I manually run the spring boot server (in IntelliJ) and then run the Test client.


问:
Selenium window closes instantly when "requests" module is imported
I'm trying to use Selenium and Beautiful Soup together with Python but having a rather strange issue - Selenium window stays opened only if requests module is not imported, otherwise it stays opened for like 1 second and closes.
Important thing is that this only happens when I create the class in another file - when I create the class in the same file it stays opened normally.
Below are the two versions of code - 1st one where window stays opened, 2nd one where window instantly closes:

1: WORKS

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")
</code>```

2: CLOSES

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")
</code>```

答:
I'm wondering if this has something to do with the Keep-Alive and Connection Pooling in urllib3, even though the requests module is not used in the program code.

When your program terminates, the HTTP connections are released and the browser window closes.

Add this and you'll see that the browser window stays open until the program has finished running. The program simply terminates perfectly normally with no errors.

```<code>from time import sleep
for _ in range(10):
    sleep(1)
</code>```

[Edit] I have a solution!

detach (Boolean) — whether browser is closed when the driver is sent the quit command.

See Class: Selenium::WebDriver::Chrome::Options

```<code>from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from watcher import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=options)

tw = Watcher(driver)
tw.open_browser()
</code>```

Body:
I'm trying to use Selenium and Beautiful Soup together with Python but having a rather strange issue - Selenium window stays opened only if requests module is not imported, otherwise it stays opened for like 1 second and closes.
Important thing is that this only happens when I create the class in another file - when I create the class in the same file it stays opened normally.
Below are the two versions of code - 1st one where window stays opened, 2nd one where window instantly closes:

1: WORKS

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

2: CLOSES

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from test import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
driver = webdriver.Chrome(service=service)

tw = Watcher(driver)
tw.open_browser()

# OTHER FILE CALLED test
class Watcher:
    def __init__(self, driver):
        self.driver = driver

    def open_browser(self):
        self.driver.get("https://www.google.com")

Body:
I'm wondering if this has something to do with the Keep-Alive and Connection Pooling in urllib3, even though the requests module is not used in the program code.

When your program terminates, the HTTP connections are released and the browser window closes.

Add this and you'll see that the browser window stays open until the program has finished running. The program simply terminates perfectly normally with no errors.

from time import sleep
for _ in range(10):
    sleep(1)

[Edit] I have a solution!

detach (Boolean) — whether browser is closed when the driver is sent the quit command.

See Class: Selenium::WebDriver::Chrome::Options

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from watcher import Watcher
import requests

service = Service("C:\Program Files (x86)\Development\chromedriver.exe")
options = webdriver.ChromeOptions()
options.add_experimental_option("detach", True)
driver = webdriver.Chrome(service=service, options=options)

tw = Watcher(driver)
tw.open_browser()


问:
Accessing fields from a text file
I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:

```<code>{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', u'screen_name': u'YouTube'}], u'hashtags': [], u'urls': [{u'indices': [52, 71], u'url': u'http://t.co/iQYW4d3', u'expanded_url': u'http://www.youtube.com/watch?v=-HGfFyqJMrk', u'display_url': u'youtube.com/watch?v=-HGfFy\u2026'}]}, u'contributors': None, u'truncated': False, u'text': u'Long Live Egypt.....A MUST watch..... Freeeeedom... http://t.co/iQYW4d3 via @youtube', u'created_at': u'Sun Feb 06 17:18:21 +0000 2011', u'retweeted': False, u'in_reply_to_status_id_str': None, u'coordinates': None, u'id': 34299873733902336L, u'source': u'<a href="http://twitter.com/tweetbutton" rel="nofollow">Tweet Button</a>', u'in_reply_to_status_id': None, u'id_str': u'34299873733902336', u'in_reply_to_screen_name': None, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'id': 191652149, u'verified': False, u'profile_sidebar_fill_color': u'c9c9c9', u'profile_text_color': u'1c1f23', u'followers_count': 43, u'protected': False, u'location': u'Damascus - Syria', u'profile_background_color': u'07090b', u'listed_count': 3, u'utc_offset': 7200, u'statuses_count': 113, u'description': u'In heaven, all the interesting people are missing ', u'friends_count': 149, u'profile_link_color': u'c34242', u'profile_image_url': u'http://a3.twimg.com/profile_images/1125299662/Untitled_normal.jpg', u'notifications': None, u'show_all_inline_media': False, u'geo_enabled': False, u'id_str': u'191652149', u'profile_background_image_url': u'http://a0.twimg.com/profile_background_images/150071579/x07823fa2328f1ff92c4d900c44bc34d.jpg', u'screen_name': u'NourZoukar', u'lang': u'en', u'following': None, u'profile_background_tile': True, u'favourites_count': 0, u'name': u'M.Nour  Zoukar', u'url': u'http://www.kawngroup.com', u'created_at': u'Fri Sep 17 00:19:26 +0000 2010', u'contributors_enabled': False, u'time_zone': u'Jerusalem', u'profile_sidebar_border_color': u'bfbfbf', u'is_translator': False}, u'place': None, u'retweet_count': 0, u'geo': None, u'in_reply_to_user_id_str': None, u'in_reply_to_user_id': None}
</code>```

I want my output to display the screen name that is 'NourZoukar' in this case.

答:
I very much doubt that that's the raw JSON text format. That to me looks like the output once you've loaded it into Python with json.loads().

Given that it's already a dictionary, you just do data['screen_name'].

Title: Accessing fields from a text file

Body:
I'm new to python. I need to access fields from a text file which is basically a tweet stream in json format. The text file looks like this:

{u'favorited': False, u'entities': {u'user_mentions': [{u'indices': [76, 84], u'id': 10228272, u'id_str': u'10228272', u'name': u'YouTube', u'screen_name': u'YouTube'}], u'hashtags': [], u'urls': [{u'indices': [52, 71], u'url': u'http://t.co/iQYW4d3', u'expanded_url': u'http://www.youtube.com/watch?v=-HGfFyqJMrk', u'display_url': u'youtube.com/watch?v=-HGfFy\u2026'}]}, u'contributors': None, u'truncated': False, u'text': u'Long Live Egypt.....A MUST watch..... Freeeeedom... http://t.co/iQYW4d3 via @youtube', u'created_at': u'Sun Feb 06 17:18:21 +0000 2011', u'retweeted': False, u'in_reply_to_status_id_str': None, u'coordinates': None, u'id': 34299873733902336L, u'source': u'Tweet Button', u'in_reply_to_status_id': None, u'id_str': u'34299873733902336', u'in_reply_to_screen_name': None, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'id': 191652149, u'verified': False, u'profile_sidebar_fill_color': u'c9c9c9', u'profile_text_color': u'1c1f23', u'followers_count': 43, u'protected': False, u'location': u'Damascus - Syria', u'profile_background_color': u'07090b', u'listed_count': 3, u'utc_offset': 7200, u'statuses_count': 113, u'description': u'In heaven, all the interesting people are missing ', u'friends_count': 149, u'profile_link_color': u'c34242', u'profile_image_url': u'http://a3.twimg.com/profile_images/1125299662/Untitled_normal.jpg', u'notifications': None, u'show_all_inline_media': False, u'geo_enabled': False, u'id_str': u'191652149', u'profile_background_image_url': u'http://a0.twimg.com/profile_background_images/150071579/x07823fa2328f1ff92c4d900c44bc34d.jpg', u'screen_name': u'NourZoukar', u'lang': u'en', u'following': None, u'profile_background_tile': True, u'favourites_count': 0, u'name': u'M.Nour  Zoukar', u'url': u'http://www.kawngroup.com', u'created_at': u'Fri Sep 17 00:19:26 +0000 2010', u'contributors_enabled': False, u'time_zone': u'Jerusalem', u'profile_sidebar_border_color': u'bfbfbf', u'is_translator': False}, u'place': None, u'retweet_count': 0, u'geo': None, u'in_reply_to_user_id_str': None, u'in_reply_to_user_id': None}

I want my output to display the screen name that is 'NourZoukar' in this case.


问:
Fit polynomial to point cloud in 3D using PolynomialFeatures
I have some points which represent movement of some particle in 3D. I am trying to fit polynomial to these points so that I can have one line representing the track the particle has taken. Moreover, it is clear that the track is either polynomial degree 2 or 3.

Following a suggestion here I have written the following code to fit polynomial to my data:

```<code>%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# Point cloud
data = np.array([[ 41. ,  57. ,  92. ],[ 39. ,  57.  , 92.4],[ 43. ,  57.  , 91.2], [ 23.,   47. , 119.6],
                 [ 27. ,  47. , 115.2], [ 25. ,  45. , 122. ], [ 25. ,  49. , 114. ],[ 29.,   49. , 109.6],
                 [ 29. ,  47. , 114.4], [ 27. ,  49. , 111.2], [ 23. ,  45. , 125.6], [ 31.,   49.,  106.8],
                 [ 25. ,  47. , 117.6], [ 39. ,  55. ,  95.6],[ 37.  , 53.  , 98.4], [ 35. ,  55. ,  96.8],
                 [ 33. ,  53. , 116.8], [ 23. ,  43. , 132.8], [ 25. ,  41. , 145.2],[ 25. ,  43.,  133.6],
                 [ 29. ,  51. , 106.4],[ 31.  , 53. , 121.2],[ 31., 51. , 104.8],[ 41.,   55.,   93.6],
                 [ 33. ,  51. , 103.6],[ 35.  , 53. ,  99.6],[ 37. ,  55. ,  96.4]])

x = data[:,0]
y = data[:,1]
z = data[:,2]

# sort data to avoid plotting problems
x, y, z = zip(*sorted(zip(x, y, z)))

x = np.array(x)
y = np.array(y)
z = np.array(z)

data_xy = np.array([x,y])

poly = PolynomialFeatures(degree=2)
X_t = poly.fit_transform(data_xy.transpose())

clf = LinearRegression()
clf.fit(X_t, z)
z_pred = clf.predict(X_t)
print(clf.coef_)
print(clf.intercept_)

fig = plt.figure()
ax = plt.subplot(projection='3d')
ax.plot(x, y, z_pred, 'r') # fit line
ax.scatter(x, y, z)
fig.set_dpi(150)
</code>```

The problem is, I am getting a very strange result:

Any idea what's going on?

EDIT: I would expect a line that fits to the data. For example, I applied the exact same method to different data, and this is what I got:

It is also possible to suggest other methods. Thank you!

答:
I was able to solve the problem. Actually my choice of dependent and independent variables is the issue here. If I assume X to be independent variable and Y and Z are dependent then I get better results:

```<code>from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score

def polynomial_regression3d(x, y, z, degree):
    # sort data to avoid plotting problems
    x, y, z = zip(*sorted(zip(x, y, z)))

    x = np.array(x)
    y = np.array(y)
    z = np.array(z)

    data_yz = np.array([y,z])
    data_yz = data_yz.transpose()

    polynomial_features= PolynomialFeatures(degree=degree)
    x_poly = polynomial_features.fit_transform(x[:, np.newaxis])

    model = LinearRegression()
    model.fit(x_poly, data_yz)
    y_poly_pred = model.predict(x_poly)

    rmse = np.sqrt(mean_squared_error(data_yz,y_poly_pred))
    r2 = r2_score(data_yz,y_poly_pred)
    print("RMSE:", rmse)
    print("R-squared", r2)

    # plot
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.scatter(x, data_yz[:,0], data_yz[:,1])
    ax.plot(x, y_poly_pred[:,0], y_poly_pred[:,1], color='r')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    plt.show()
    fig.set_dpi(150)
</code>```

However, when I compute R-squared, it shows a value of 0.8, which is not so bad but maybe could be improved?
Perhaps, using weighted least squares can improve that.

Body:
I have some points which represent movement of some particle in 3D. I am trying to fit polynomial to these points so that I can have one line representing the track the particle has taken. Moreover, it is clear that the track is either polynomial degree 2 or 3.

Following a suggestion here I have written the following code to fit polynomial to my data:

%matplotlib notebook
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression

# Point cloud
data = np.array([[ 41. ,  57. ,  92. ],[ 39. ,  57.  , 92.4],[ 43. ,  57.  , 91.2], [ 23.,   47. , 119.6],
                 [ 27. ,  47. , 115.2], [ 25. ,  45. , 122. ], [ 25. ,  49. , 114. ],[ 29.,   49. , 109.6],
                 [ 29. ,  47. , 114.4], [ 27. ,  49. , 111.2], [ 23. ,  45. , 125.6], [ 31.,   49.,  106.8],
                 [ 25. ,  47. , 117.6], [ 39. ,  55. ,  95.6],[ 37.  , 53.  , 98.4], [ 35. ,  55. ,  96.8],
                 [ 33. ,  53. , 116.8], [ 23. ,  43. , 132.8], [ 25. ,  41. , 145.2],[ 25. ,  43.,  133.6],
                 [ 29. ,  51. , 106.4],[ 31.  , 53. , 121.2],[ 31., 51. , 104.8],[ 41.,   55.,   93.6],
                 [ 33. ,  51. , 103.6],[ 35.  , 53. ,  99.6],[ 37. ,  55. ,  96.4]])

x = data[:,0]
y = data[:,1]
z = data[:,2]

# sort data to avoid plotting problems
x, y, z = zip(*sorted(zip(x, y, z)))

x = np.array(x)
y = np.array(y)
z = np.array(z)

data_xy = np.array([x,y])

poly = PolynomialFeatures(degree=2)
X_t = poly.fit_transform(data_xy.transpose())

clf = LinearRegression()
clf.fit(X_t, z)
z_pred = clf.predict(X_t)
print(clf.coef_)
print(clf.intercept_)

fig = plt.figure()
ax = plt.subplot(projection='3d')
ax.plot(x, y, z_pred, 'r') # fit line
ax.scatter(x, y, z)
fig.set_dpi(150)

The problem is, I am getting a very strange result:

Any idea what's going on?

EDIT: I would expect a line that fits to the data. For example, I applied the exact same method to different data, and this is what I got:

It is also possible to suggest other methods. Thank you!

Body:
I was able to solve the problem. Actually my choice of dependent and independent variables is the issue here. If I assume X to be independent variable and Y and Z are dependent then I get better results:

from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score

def polynomial_regression3d(x, y, z, degree):
    # sort data to avoid plotting problems
    x, y, z = zip(*sorted(zip(x, y, z)))

    x = np.array(x)
    y = np.array(y)
    z = np.array(z)

    data_yz = np.array([y,z])
    data_yz = data_yz.transpose()

    polynomial_features= PolynomialFeatures(degree=degree)
    x_poly = polynomial_features.fit_transform(x[:, np.newaxis])

    model = LinearRegression()
    model.fit(x_poly, data_yz)
    y_poly_pred = model.predict(x_poly)

    rmse = np.sqrt(mean_squared_error(data_yz,y_poly_pred))
    r2 = r2_score(data_yz,y_poly_pred)
    print("RMSE:", rmse)
    print("R-squared", r2)

    # plot
    fig = plt.figure()
    ax = plt.axes(projection='3d')
    ax.scatter(x, data_yz[:,0], data_yz[:,1])
    ax.plot(x, y_poly_pred[:,0], y_poly_pred[:,1], color='r')
    ax.set_xlabel('X')
    ax.set_ylabel('Y')
    ax.set_zlabel('Z')

    plt.show()
    fig.set_dpi(150)

However, when I compute R-squared, it shows a value of 0.8, which is not so bad but maybe could be improved?
Perhaps, using weighted least squares can improve that.


问:
Google Tag Manager error: Uncaught TypeError: w[l].push is not a function
I'm seeing this error "Uncaught TypeError: w[l].push is not a function" in my Google Tag Manager javascript.  What's going on?

I'm using the normal GTM script, and I've got a simple dataLayer defined:

```<code><script>
  dataLayer = {
    "foo": "bar"
  }
</script>
</code>```

答:
May not be your case but I have seen this on my sites because I had a Adobe DTM DataLayer and also a GTM datalayer defined with the same name.

GTM datalayer object is an array were as the datalayer object in Adobe DTM is a json object.

To resolve this, I used a different variable(GTMDataLayer), this variable would replace the datalayer object used in gtag js for tracking.

I did face issue while using GTM datalayer object as in GTM datalayer object is an array were as the datalayer object in DTM is a json object.
So for GTM tracking I used a different variable(GTMDataLayer), this variable would replace the datalayer object used in gtag js for tracking.
Below is the code snippet.

```<code><script async src="https://www.googletagmanager.com/gtag/js?id=DC-
YOUR_ID_HERE&l=GTMDataLayer"></script>
<script>
window.**GTMDataLayer** = window.GTMDataLayer || [];
function gtag() { GTMDataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'DC-YOUR_ID_HERE);
</script>
</code>```

Body:
May not be your case but I have seen this on my sites because I had a Adobe DTM DataLayer and also a GTM datalayer defined with the same name.

GTM datalayer object is an array were as the datalayer object in Adobe DTM is a json object.

To resolve this, I used a different variable(GTMDataLayer), this variable would replace the datalayer object used in gtag js for tracking.

I did face issue while using GTM datalayer object as in GTM datalayer object is an array were as the datalayer object in DTM is a json object.
So for GTM tracking I used a different variable(GTMDataLayer), this variable would replace the datalayer object used in gtag js for tracking.
Below is the code snippet.

<script async src="https://www.googletagmanager.com/gtag/js?id=DC-
YOUR_ID_HERE&l=GTMDataLayer"></script>
<script>
window.**GTMDataLayer** = window.GTMDataLayer || [];
function gtag() { GTMDataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'DC-YOUR_ID_HERE);
</script>


问:
"SMTP Error: Could not authenticate" in Phpmailer library
I am trying to this to work using the phpmailer. Unfortunately I keep getting errors. my password contains an ! so I added the \ to allow special characters. My code below.

```<code><?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
                        'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                        )
                        );
$alert = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

Try {
    //Server settings
    $mail->isSMTP();
    $mail->CharSet = "UTF-8";
    $mail->Host      = gethostbyname('smtp.gmail.com');   //Set the SMTP server to send through
    //$mail->SMTPDebug = 2;
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'myemail@gmail.com';                   //SMTP username
    $mail->Password   = 'password\!';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = '587';

    $mail->setFrom('myemail@gmail.com');
    $mail->addAddress('myemail@gmail.com'); //Sent email from this
    $mail->isHTML(true);

    $mail->Subject = 'Material Request Form';
    $mail->Body    = '<h3>Name: $name <br>Email: $visitor_email <br>Message: $message </h3>';

    $mail->send();
    $alert = '<div class ="alert-success">
    <span>Message Sent! Thnk you for Contacting us.</span>
    </div>';
   }

   catch (Exception $e){
     $alert = '<div class ="alert-error">
     <span>'.$e->getMessage().'</span>
     </div>';
   }
 }

 ?>
</code>```

I tried many things such as changing to ssl and changing ports, I also know about the secure apps. I have that turned on using Gmail.

答: Okay, so I used an email that did not have two-step verification turned on and it worked!</p>

Body:
I am trying to this to work using the phpmailer. Unfortunately I keep getting errors. my password contains an ! so I added the \ to allow special characters. My code below.

<?php
//Import PHPMailer classes into the global namespace
//These must be at the top of your script, not inside a function
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once 'phpmailer/Exception.php';
require_once 'phpmailer/PHPMailer.php';
require_once 'phpmailer/SMTP.php';

//Create an instance; passing `true` enables exceptions
$mail = new PHPMailer(true);
$mail->SMTPOptions = array(
                        'ssl' => array(
                        'verify_peer' => false,
                        'verify_peer_name' => false,
                        'allow_self_signed' => true
                        )
                        );
$alert = '';
if(isset($_POST['submit'])) {
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

Try {
    //Server settings
    $mail->isSMTP();
    $mail->CharSet = "UTF-8";
    $mail->Host      = gethostbyname('smtp.gmail.com');   //Set the SMTP server to send through
    //$mail->SMTPDebug = 2;
    $mail->SMTPAuth   = true;                                   //Enable SMTP authentication
    $mail->Username   = 'myemail@gmail.com';                   //SMTP username
    $mail->Password   = 'password\!';                               //SMTP password
    $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
    $mail->Port       = '587';

    $mail->setFrom('myemail@gmail.com');
    $mail->addAddress('myemail@gmail.com'); //Sent email from this
    $mail->isHTML(true);

    $mail->Subject = 'Material Request Form';
    $mail->Body    = '
Name: $name
Email: $visitor_email
Message: $message
';

    $mail->send();
    $alert = '

    Message Sent! Thnk you for Contacting us.

';
   }

   catch (Exception $e){
     $alert = '

     '.$e->getMessage().'

';
   }
 }

 ?>

I tried many things such as changing to ssl and changing ports, I also know about the secure apps. I have that turned on using Gmail.


问:
Using nHibernate is it possible to mix a QueryOver result with a linq query?
I have a QueryOver result set

```<code>var res = GetResults(session, group_id, search_criteria).Select(x => x.GroupId);
</code>```

I know the following gives an error.

My question is whether there some way to use res in my linq query?

```<code>var linqResults = (from vg in session.Query<vGraph>()
  join rs in res on vg.vId equals res.GroupId
  select vg);
</code>```

答:
you can still resort to a linq query which uses the executed results of you first query to.</p>

```<code>var res = GetResults(session, group_id, search_criteria).Select(x => x.GroupId).List();

var linqResults =
    (from vg in session.Query<vGraph>()
     where vg.vId.IsIn(res)
     select vg);
</code>```

Body:
I have a QueryOver result set

var res = GetResults(session, group_id, search_criteria).Select(x => x.GroupId);

I know the following gives an error.

My question is whether there some way to use res in my linq query?

var linqResults = (from vg in session.Query<vGraph>()
  join rs in res on vg.vId equals res.GroupId
  select vg);

Body:
you can still resort to a linq query which uses the executed results of you first query to.

var res = GetResults(session, group_id, search_criteria).Select(x => x.GroupId).List();

var linqResults =
    (from vg in session.Query<vGraph>()
     where vg.vId.IsIn(res)
     select vg);


问:
how to add variable link in html
i have a remote php file located on a server

https://webserver.com/file.php

and i have several images in html file on another server that are linked through

    logo

```
</div>
</div>
</p>
<p>i want to replace the main link with a variable and add it to my images.</p>
<p>should appear link the following:</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="apps">
    <img src="https://anysite.com/image.jpeg" alt="image" border="0"></br>
    logo
</div></code>```

and the final link of the image will be:

https://webserver.com/file.php?type=1

Anyone can help please?

the html code is as follows:

    <?php
    var $variable = "https://webserver.com/file.php";
    ?>

    logo

    logo

```

答:
It's PHP, not Javascript question. You try something like this?

```<code><div class="apps">
    <a href = "<?php echo $variable; ?>?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a></br>
    logo
</div>
</code>```

EDIT:

complete example:

```<code><?php
    $variable = "https://webserver.com/file.php";
?>
<html>
    <head> </head>
    <body>
    <div class="apps">
    <a href="<?php echo $variable; ?>?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a>
    logo
</div>
<div class="apps">
    <a href="<?php echo $variable; ?>?type=2"><img src="https://anysite.com/image2.jpeg" alt="image2" border="0"></a>
    logo
</div>
</body>
</html>
</code>```

Title: how to add variable link in html

Body:
i have a remote php file located on a server

https://webserver.com/file.php

and i have several images in html file on another server that are linked through

    logo

i want to replace the main link with a variable and add it to my images.

should appear link the following:

    logo

and the final link of the image will be:

https://webserver.com/file.php?type=1

Anyone can help please?

the html code is as follows:

    <?php
    var $variable = "https://webserver.com/file.php";
    ?>

    logo

    logo

Body:
It's PHP, not Javascript question. You try something like this?

<div class="apps">
    <a href = "<?php echo $variable; ?>?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a></br>
    logo
</div>

EDIT:

complete example:

<?php
    $variable = "https://webserver.com/file.php";
?>
<html>
    <head> </head>
    <body>
    <div class="apps">
    <a href="<?php echo $variable; ?>?type=1"><img src="https://anysite.com/image.jpeg" alt="image" border="0"></a>
    logo
</div>
<div class="apps">
    <a href="<?php echo $variable; ?>?type=2"><img src="https://anysite.com/image2.jpeg" alt="image2" border="0"></a>
    logo
</div>
</body>
</html>


问:
Combine rows ignoring null values
I need to combine the rows which has null values and keep only the unique combination.

Output:

Query: I tried to take the maximum per group but since it considers null value it is not combining. Can you please suggest how to combine values.

```<code>SELECT SALES_ORG
              ,MAX(MATERIAL) OVER (PARTITION BY  SALES_ORG,MATERIAL ORDER BY MATERIAL) as MATERIAL
              ,MAX(MGROUP) OVER (PARTITION BY SALES_ORG,MATERIAL,MGROUP ORDER BY MGROUP  ) as MGROUP
              ,MAX(SERVICE) OVER (PARTITION BY SALES_ORG,MATERIAL,MGROUP,SERVICE ORDER BY SERVICE  ) as SERVICE

    FROM SALES

</code>```

答:
You can get your output by aggregating by the first 3 columns and taking the maximum of the service column:

SELECT sales_org,
       material,
       mgroup,
       MAX(service) AS service
FROM   table_name
GROUP BY
       sales_org,
       material,
       mgroup;
```
<p>Which, for the sample data:</p>
<pre class="lang-sql prettyprint-override"><code>CREATE TABLE table_name (sales_org, material, mgroup, service) AS
SELECT 'XS13', NULL, 10,   'ZSERV1' FROM DUAL UNION ALL
SELECT 'XS13', 'M1', 10,   'ZSERV1' FROM DUAL UNION ALL
SELECT 'XS13', NULL, 10,   NULL     FROM DUAL UNION ALL
SELECT 'XS13', NULL, 10,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS13', NULL, 11,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS13', 'M2', 12,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS14', 'M2', NULL, NULL     FROM DUAL;
</code>```

Gives the output:

SALES_ORG
MATERIAL
MGROUP
SERVICE

XS13
null
10
ZSERV2

XS13
M1
10
ZSERV1

XS13
null
11
ZSERV2

XS13
M2
12
ZSERV2

XS14
M2
null
null

Update:

From comments:

I have to first check MGROUP/SERVICE/MATERIAL if this combination is present then ignore all the other with the same value/combination. If only SERVICE/MATERIAL is present Then ignore all the otehr below combination.

You can use a hierarchical query to connect each row to more specific rows and then find the leaf rows:

SELECT DISTINCT
       sales_org,
       material,
       mgroup,
       service
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
      (PRIOR sales_org = sales_org OR PRIOR sales_org IS NULL)
  AND (PRIOR material  = material  OR PRIOR material  IS NULL)
  AND (PRIOR mgroup    = mgroup    OR PRIOR mgroup    IS NULL)
  AND (PRIOR service   = service   OR PRIOR service   IS NULL);
```

Which outputs the same as above.

db<>fiddle here

Title: Combine rows ignoring null values

Body:
I need to combine the rows which has null values and keep only the unique combination.

Output:

Query: I tried to take the maximum per group but since it considers null value it is not combining. Can you please suggest how to combine values.

SELECT SALES_ORG
              ,MAX(MATERIAL) OVER (PARTITION BY  SALES_ORG,MATERIAL ORDER BY MATERIAL) as MATERIAL
              ,MAX(MGROUP) OVER (PARTITION BY SALES_ORG,MATERIAL,MGROUP ORDER BY MGROUP  ) as MGROUP
              ,MAX(SERVICE) OVER (PARTITION BY SALES_ORG,MATERIAL,MGROUP,SERVICE ORDER BY SERVICE  ) as SERVICE

    FROM SALES

Body:
You can get your output by aggregating by the first 3 columns and taking the maximum of the service column:

SELECT sales_org,
       material,
       mgroup,
       MAX(service) AS service
FROM   table_name
GROUP BY
       sales_org,
       material,
       mgroup;

Which, for the sample data:

CREATE TABLE table_name (sales_org, material, mgroup, service) AS
SELECT 'XS13', NULL, 10,   'ZSERV1' FROM DUAL UNION ALL
SELECT 'XS13', 'M1', 10,   'ZSERV1' FROM DUAL UNION ALL
SELECT 'XS13', NULL, 10,   NULL     FROM DUAL UNION ALL
SELECT 'XS13', NULL, 10,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS13', NULL, 11,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS13', 'M2', 12,   'ZSERV2' FROM DUAL UNION ALL
SELECT 'XS14', 'M2', NULL, NULL     FROM DUAL;

Gives the output:

SALES_ORG
MATERIAL
MGROUP
SERVICE

XS13
null
10
ZSERV2

XS13
M1
10
ZSERV1

XS13
null
11
ZSERV2

XS13
M2
12
ZSERV2

XS14
M2
null
null

Update:

From comments:

I have to first check MGROUP/SERVICE/MATERIAL if this combination is present then ignore all the other with the same value/combination. If only SERVICE/MATERIAL is present Then ignore all the otehr below combination.

You can use a hierarchical query to connect each row to more specific rows and then find the leaf rows:

SELECT DISTINCT
       sales_org,
       material,
       mgroup,
       service
FROM   table_name
WHERE  CONNECT_BY_ISLEAF = 1
CONNECT BY NOCYCLE
      (PRIOR sales_org = sales_org OR PRIOR sales_org IS NULL)
  AND (PRIOR material  = material  OR PRIOR material  IS NULL)
  AND (PRIOR mgroup    = mgroup    OR PRIOR mgroup    IS NULL)
  AND (PRIOR service   = service   OR PRIOR service   IS NULL);

Which outputs the same as above.

db<>fiddle here


问:
Process last n records in pyspark kafka streaming
I need to do some operations on last 100 000 records (customer bills) of different stores each for every five minutes. What is the best approach or steps I need to follow in pyspark structured streaming? Input source is Kafka.
And also I have to gradually delete the old records beyond 100k records of each store, because I need only recent 100k records per every store at any time.

For example, I need to find out the details of the product 'p1' from last 100k records of store 'S1', and last 100k records from store 'S2' and so on.

答: Structured streaming don't have such option. One workaround is estimate messages per second, then calulate how long needed for 100K records. Finally, you can use startingTimestamp. Please refer https://spark.apache.org/docs/latest/structured-streaming-kafka-integration.html#creating-a-kafka-source-for-streaming-queries


问:
Remove subfolder using htaccess
I know that this has been requested a million times but i haven't found an answer.

Basically I want to remove amp from my site but I've a million pages indexed using /amp so if I remove it this will cause a mess.

What I want to do is to redirect all the url like these

```<code>https://*/amp
</code>```

will go to the same url without amp.

For example an article with this url

```<code>https://www.tuttosullapostaelettronica.it/blog/come-e-fatta-una-mail/amp
</code>```

will be redirected to the same article without /amp like

```<code>https://www.tuttosullapostaelettronica.it/blog/come-e-fatta-una-mail
</code>```

This has to be valid for whatever article url that end in /amp that has to be the /amp removed

Thanks!

答:
Assuming you need to remove amp on requests to the document (first example) and /amp on requests to other URLs then you would need a rule like the following using mod_rewrite, near the top of the .htaccess file:

```<code>RewriteEngine On

RewriteRule ^(?:(.+)/)?amp$ /$1 [R=301,L]
</code>```

The regex ^(?:(.+)/)?amp$ matches both amp and <something>/amp and removes amp or /amp respectively.

Test first with a 302 (temporary) redirect to avoid potential caching issues.

Title: Remove subfolder using htaccess

Body:
I know that this has been requested a million times but i haven't found an answer.

Basically I want to remove amp from my site but I've a million pages indexed using /amp so if I remove it this will cause a mess.

What I want to do is to redirect all the url like these

https://*/amp

will go to the same url without amp.

For example an article with this url

https://www.tuttosullapostaelettronica.it/blog/come-e-fatta-una-mail/amp

will be redirected to the same article without /amp like

https://www.tuttosullapostaelettronica.it/blog/come-e-fatta-una-mail

This has to be valid for whatever article url that end in /amp that has to be the /amp removed

Thanks!

Body:
Assuming you need to remove amp on requests to the document (first example) and /amp on requests to other URLs then you would need a rule like the following using mod_rewrite, near the top of the .htaccess file:

RewriteEngine On

RewriteRule ^(?:(.+)/)?amp$ /$1 [R=301,L]

The regex ^(?:(.+)/)?amp$ matches both amp and <something>/amp and removes amp or /amp respectively.

Test first with a 302 (temporary) redirect to avoid potential caching issues.


问:
Adding an event handerler to a custom control
I have a custom control i have created with a picture box, a label, and a combobox, i want to create a custom SelectedIndexChanged event handerler so i can perform actions when the index has been changed of the combobox, but with it being a custom control this event is not available to me by default, so im hoping i can create one.  custom controls and events are new to me.  any help would be apreciated, thanks a lot.</p>

答:
if you just want to fire the event without telling which items are now selected you can do this with:

```<code>public event EventHandler SelectionChanged;

protected virtual void OnSelectionChanged() {
    if (SelectionChanged != null) {
        SelectionChanged(this, new EventArgs());
    }
}
</code>```

just call OnSelectionChanged() within your control and the event SelectionChanged will be fired.

If you also want to tell which elements are now selected you can use the following, just replace object[] with your objectarray:

```<code>public event SelectionChangedEventHandler SelectionChanged;
public delegate void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);

protected virtual void OnSelectionChanged(object[] SelectedItems) {
    if (SelectionChanged != null) {
        SelectionChanged(this, new SelectionChangedEventArgs(SelectedItems));
    }
}

public class SelectionChangedEventArgs : EventArgs {
    public object[] SelectedItems { get; private set; }

    public SelectionChangedEventArgs(object[] SelectedItems) {
        this.SelectedItems = SelectedItems;
    }
}
</code>```

Body:
if you just want to fire the event without telling which items are now selected you can do this with:

public event EventHandler SelectionChanged;

protected virtual void OnSelectionChanged() {
    if (SelectionChanged != null) {
        SelectionChanged(this, new EventArgs());
    }
}

just call OnSelectionChanged() within your control and the event SelectionChanged will be fired.

If you also want to tell which elements are now selected you can use the following, just replace object[] with your objectarray:

public event SelectionChangedEventHandler SelectionChanged;
public delegate void SelectionChangedEventHandler(object sender, SelectionChangedEventArgs e);

protected virtual void OnSelectionChanged(object[] SelectedItems) {
    if (SelectionChanged != null) {
        SelectionChanged(this, new SelectionChangedEventArgs(SelectedItems));
    }
}

public class SelectionChangedEventArgs : EventArgs {
    public object[] SelectedItems { get; private set; }

    public SelectionChangedEventArgs(object[] SelectedItems) {
        this.SelectedItems = SelectedItems;
    }
}


问:
How to show all columns' names on a large pandas dataframe?
I have a dataframe that consist of hundreds of columns, and I need to see all column names.

What I did:

```<code>In[37]:
data_all2.columns
</code>```

The output is:

```<code>Out[37]:
Index(['customer_id', 'incoming', 'outgoing', 'awan', 'bank', 'family', 'food',
       'government', 'internet', 'isipulsa',
       ...
       'overdue_3months_feature78', 'overdue_3months_feature79',
       'overdue_3months_feature80', 'overdue_3months_feature81',
       'overdue_3months_feature82', 'overdue_3months_feature83',
       'overdue_3months_feature84', 'overdue_3months_feature85',
       'overdue_3months_feature86', 'loan_overdue_3months_total_y'],
      dtype='object', length=102)
</code>```

How do I show all columns, instead of a truncated list?

答:
I may be off the mark but I came to this thread with the same type of problem I found this is the simple answer if you want to see everything in a long list and the index.

This is what I use in Spyder:

```<code>print(df.info())
</code>```

or this be what is needed in Jupyter:

```<code>df.info()
</code>```

Body:
I have a dataframe that consist of hundreds of columns, and I need to see all column names.

What I did:

In[37]:
data_all2.columns

The output is:

Out[37]:
Index(['customer_id', 'incoming', 'outgoing', 'awan', 'bank', 'family', 'food',
       'government', 'internet', 'isipulsa',
       ...
       'overdue_3months_feature78', 'overdue_3months_feature79',
       'overdue_3months_feature80', 'overdue_3months_feature81',
       'overdue_3months_feature82', 'overdue_3months_feature83',
       'overdue_3months_feature84', 'overdue_3months_feature85',
       'overdue_3months_feature86', 'loan_overdue_3months_total_y'],
      dtype='object', length=102)

How do I show all columns, instead of a truncated list?

Body:
I may be off the mark but I came to this thread with the same type of problem I found this is the simple answer if you want to see everything in a long list and the index.

This is what I use in Spyder:

print(df.info())

or this be what is needed in Jupyter:

df.info()


问:
Using rbind within a pipe
Is it possible to use rbind within a pipe so that I don't have to define and store a variable to use it?

```<code>library(tidyverse)

## works fine
df <- iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup

df %>%
  rbind(df)

## anyway to make this work?
iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup %>%
  rbind(.)
</code>```

答:
I don't know why you would want to rbind something with itself, but here you go:

```<code>iris %>%
    group_by(Species) %>%
    summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
    ungroup %>%
    rbind(., .)
</code>```

Title: Using rbind within a pipe

Body:
Is it possible to use rbind within a pipe so that I don't have to define and store a variable to use it?

library(tidyverse)

## works fine
df <- iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup

df %>%
  rbind(df)

## anyway to make this work?
iris %>%
  group_by(Species) %>%
  summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
  ungroup %>%
  rbind(.)

Body:
I don't know why you would want to rbind something with itself, but here you go:

iris %>%
    group_by(Species) %>%
    summarise(Avg.Sepal.Length = mean(Sepal.Length)) %>%
    ungroup %>%
    rbind(., .)


问:
Can STRtOK function return a null/0 value?
I'm trying to use the strtok function to breakout a concatenated string.
This is what I have so far. My source tables are sitting in Teradata and I'm running the code via SAS.

```<code>proc sql;
connect to teradata as tera ( server='XXXXXX' authdomain='XXXXX';
execute(
         update DB.Table1
         from
       (
        select id, string_key
        from DB.Table2
        where date_time >= current_date
       ) c
set
       country = STRTOK (c.string_key,',',1),
       Expense      = STRTOK (c.string_key,',',2),
       First_Name    = STRTOK (c.string_key,',',3),

) by tera
disconnect from tera
quit;
</code>```

An example of a value in string_key is :

UK,244,Jack,Mathews

For the above example, my code has no problem creating the required output i.e:

Country
Expense
First name

UK
244
Jack

However in instances where a value in string_key has a null value after the delimiter, the strtok function returns the next available value in the wrong column.

for e.g when string_key is :

UK,244,,Mathews

then the output I get is

Country
Expense
First name

UK
244
Mathews

but what I want is that the First_name column should be empty as there is no value for it in the string_key.

i.e I want it is

Country
Expense
First name

UK
244

Could someone pls help tweak my code such that the column populates with a null value if the string has a null value?

Many thanks!

答:
STRTOK doesn't play nicely with consecutive delimiters.  You can replace consecutive delimiters with <delimiter><space><delimiter>. In your case:

```<code>trim(strtok(oreplace(string_key,',,',', ,'),',',3))
</code>```

Alternatively, you could use csvld:

```<code> select
 *
 from
 table (csvld(<table>.string_key,',','')
 returns(a varchar(100), b varchar(100), c varchar(100), d varchar (100))) as t;
</code>```

Body:
I'm trying to use the strtok function to breakout a concatenated string.
This is what I have so far. My source tables are sitting in Teradata and I'm running the code via SAS.

proc sql;
connect to teradata as tera ( server='XXXXXX' authdomain='XXXXX';
execute(
         update DB.Table1
         from
       (
        select id, string_key
        from DB.Table2
        where date_time >= current_date
       ) c
set
       country = STRTOK (c.string_key,',',1),
       Expense      = STRTOK (c.string_key,',',2),
       First_Name    = STRTOK (c.string_key,',',3),

) by tera
disconnect from tera
quit;

An example of a value in string_key is :

UK,244,Jack,Mathews

For the above example, my code has no problem creating the required output i.e:

Country
Expense
First name

UK
244
Jack

However in instances where a value in string_key has a null value after the delimiter, the strtok function returns the next available value in the wrong column.

for e.g when string_key is :

UK,244,,Mathews

then the output I get is

Country
Expense
First name

UK
244
Mathews

but what I want is that the First_name column should be empty as there is no value for it in the string_key.

i.e I want it is

Country
Expense
First name

UK
244

Could someone pls help tweak my code such that the column populates with a null value if the string has a null value?

Many thanks!

Body:
STRTOK doesn't play nicely with consecutive delimiters.  You can replace consecutive delimiters with <delimiter><space><delimiter>. In your case:

trim(strtok(oreplace(string_key,',,',', ,'),',',3))

Alternatively, you could use csvld:

 select
 *
 from
 table (csvld(<table>.string_key,',','')
 returns(a varchar(100), b varchar(100), c varchar(100), d varchar (100))) as t;


问:
Loading an Image from a DotNetZip Entry
How can I load an Image in WPF using the DotNetZip ZipEntry class.</p>

```<code>using (ZipFile file = ZipFile.Read ("Images.zip"))
{
    ZipEntry entry = file["Image.png"];
    uiImage.Source = ??
}
</code>```

答:
You could potentially use a BitmapSource, but the raw image data will still need to be decompressed, I'm not sure if opening the zip in the manner that you do actually decompresses on the fly so that, or not; but once you have that you ought to be able to do something like the following:

```<code>BitmapSource bitmap = BitmapSource.Create(
    width, height, 96, 96, pf, null, rawImage, rawStride);
</code>```

Where rawImage would be the bytes of the images file in the form of an array. Other arguments include the DPI and pixel format, which you should now or be able to determine.

In order to get the rawStride value, MSDN has the following sample as an example:

```<code>PixelFormat pf = PixelFormats.Bgr32;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;
</code>```

Title: Loading an Image from a DotNetZip Entry

Body:
How can I load an Image in WPF using the DotNetZip ZipEntry class.

using (ZipFile file = ZipFile.Read ("Images.zip"))
{
    ZipEntry entry = file["Image.png"];
    uiImage.Source = ??
}

Body:
You could potentially use a BitmapSource, but the raw image data will still need to be decompressed, I'm not sure if opening the zip in the manner that you do actually decompresses on the fly so that, or not; but once you have that you ought to be able to do something like the following:

BitmapSource bitmap = BitmapSource.Create(
    width, height, 96, 96, pf, null, rawImage, rawStride);

Where rawImage would be the bytes of the images file in the form of an array. Other arguments include the DPI and pixel format, which you should now or be able to determine.

In order to get the rawStride value, MSDN has the following sample as an example:

PixelFormat pf = PixelFormats.Bgr32;
int rawStride = (width * pf.BitsPerPixel + 7) / 8;