问:
Maven: extract files from jar
I'm developing a client application of a WebService and I have the corresponding WSDL file inside a jar.

I'm using ant to generate the java code from the wsdl with the following build.xml:

```<code><project name="wsimport" default="wsimport" basedir=".">
<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" />

  <target name="wsimport">
     <echo message="Starting wsimport"/>
     <mkdir dir="target/generated-sources/jaxws-wsimport"/>
     <wsimport
        wsdl="???"
        sourcedestdir="target/generated-sources/jaxws-wsimport"
        extension="true"
        verbose="true"
        target="2.0"
        xnocompile="true"
        catalog="src/jax-ws-catalog.xml"
        wsdlLocation="/MyWebService/MyWebServiceV1_0?wsdl">
        <binding dir="src/main/resources/bindings/v1_0" includes="*.xml"/>
        <xjcarg value="-XhashCode"/>
        <xjcarg value="-Xequals"/>
        <xjcarg value="-XtoString"/>
     </wsimport>

   </target>
</project>
</code>```

How do I load the WSDL file from a jar? The WSDL references an XSD which is also in the same jar.

答:
Answering to my own question, the approach I used was to extract the files from the jar.

Actually I use maven to build the project and the antrun plugin to generate the sources from the wsdl, so I used the maven-dependency-plugin to unpack the files from the jar:

```<code>            <!-- extract WSDL and XSD from dependency jar -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>my.company</groupId>
                                    <artifactId>my.artifact</artifactId>
                                    <version>1.0</version>
                                    <outputDirectory>${project.build.directory}/wsdl</outputDirectory>
                                    <includes>**\/*.xsd, **\/*.wsdl</includes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
</code>```

Title: Maven: extract files from jar

Body:
I'm developing a client application of a WebService and I have the corresponding WSDL file inside a jar.

I'm using ant to generate the java code from the wsdl with the following build.xml:

<project name="wsimport" default="wsimport" basedir=".">
<taskdef name="wsimport" classname="com.sun.tools.ws.ant.WsImport" />

  <target name="wsimport">
     <echo message="Starting wsimport"/>
     <mkdir dir="target/generated-sources/jaxws-wsimport"/>
     <wsimport
        wsdl="???"
        sourcedestdir="target/generated-sources/jaxws-wsimport"
        extension="true"
        verbose="true"
        target="2.0"
        xnocompile="true"
        catalog="src/jax-ws-catalog.xml"
        wsdlLocation="/MyWebService/MyWebServiceV1_0?wsdl">
        <binding dir="src/main/resources/bindings/v1_0" includes="*.xml"/>
        <xjcarg value="-XhashCode"/>
        <xjcarg value="-Xequals"/>
        <xjcarg value="-XtoString"/>
     </wsimport>

   </target>
</project>

How do I load the WSDL file from a jar? The WSDL references an XSD which is also in the same jar.

Body:
Answering to my own question, the approach I used was to extract the files from the jar.

Actually I use maven to build the project and the antrun plugin to generate the sources from the wsdl, so I used the maven-dependency-plugin to unpack the files from the jar:

            <!-- extract WSDL and XSD from dependency jar -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <executions>
                    <execution>
                        <id>unpack</id>
                        <phase>generate-sources</phase>
                        <goals>
                            <goal>unpack</goal>
                        </goals>
                        <configuration>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>my.company</groupId>
                                    <artifactId>my.artifact</artifactId>
                                    <version>1.0</version>
                                    <outputDirectory>${project.build.directory}/wsdl</outputDirectory>
                                    <includes>**\/*.xsd, **\/*.wsdl</includes>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>


来源: stackexchange

问:
Typescript interface for a Functional Component that requires children
I typically define my functional react components with the following pattern:

```<code>interface Props {
    title: string; //for example
}

export const MyComponent : React.FunctionComponent<Props> = (props) => {
    const {
        title,
        children //This is implied as allowed by the FunctionalCompoment interface I believe

    } = props;

     return <div>{title}{children}</div>
}
</code>```

I have a component that must have children, as a lot of react components do.

How do I enforce this?

On a related note, is it possible to enforce that the children must of a certain kind of React component?

答:
This is the built in way but children are optional in this type.

```<code>export const MyComponent : React.FunctionComponent<React.PropsWithChildren<Props>> = (props) => {
  const {
    title,
    children //This is implied as allowed by the FunctionalCompoment interface I believe

  } = props;

  return <div>{title}{children}</div>
}
</code>```

I would suggest creating your own type or interface

```<code>type MustHaveChildren<T> = T & { children: ReactNode }
</code>```

or

```<code>interface MustHaveChildren {
 children: ReactNode
}

interface T extends MustHaveChildren {
 .... // your types
}
</code>```

Usage:

Type

```<code>export const MyComponent : React.FunctionComponent<MustHaveChildren<Props>> =
  (props) => (...)
</code>```

Interface

```<code>export const MyComponent : React.FunctionComponent<Props> =
  (props) => (...)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I typically define my functional react components with the following pattern:

interface Props {
    title: string; //for example
}

export const MyComponent : React.FunctionComponent<Props> = (props) => {
    const {
        title,
        children //This is implied as allowed by the FunctionalCompoment interface I believe

    } = props;

     return
{title}{children}

}

I have a component that must have children, as a lot of react components do.

How do I enforce this?

On a related note, is it possible to enforce that the children must of a certain kind of React component?

Body:
This is the built in way but children are optional in this type.

export const MyComponent : React.FunctionComponent<React.PropsWithChildren<Props>> = (props) => {
  const {
    title,
    children //This is implied as allowed by the FunctionalCompoment interface I believe

  } = props;

  return <div>{title}{children}</div>
}

I would suggest creating your own type or interface

type MustHaveChildren<T> = T & { children: ReactNode }

or

interface MustHaveChildren {
 children: ReactNode
}

interface T extends MustHaveChildren {
 .... // your types
}

Usage:

Type

export const MyComponent : React.FunctionComponent<MustHaveChildren<Props>> =
  (props) => (...)

Interface

export const MyComponent : React.FunctionComponent<Props> =
  (props) => (...)


问:
I need to Undo my Redirection URL done by Redirection Plugin
I have used the REDIRECTION plugin and redirected the URL http://localhost/word/wordpress/product-category/sample/ to http://localhost/word/wordpress/sample/. The first thing it redirects all my product category page to destination URL. So, I need to undo this. But I couldn't find a solution for these. Kindly Suggest me some ideas.

I had tried to remove the redirects line from .htaccess, but nothing happened.

```<code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /word/wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /word/wordpress/index.php [L]
</IfModule>
</code>```

END WordPress

If I remove the redirect lines, it displays like,

Object not found!
       The requested URL was not found on this server. The link on the
       referring page seems to be wrong or outdated. Please inform the author
       of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost

Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/7.1.20

答:
Welcome to Stackoverflow!

The redirect lines in .htaccess are not added by redirection plugin. Those lines are added by Wordpress permalink to work. You are using the postname slug in the permalink url of wordpress. So, if you remove those lines from .htaccess, the permalink stops working and you are getting this error.

For the incorrect redirection, you only need to remove the redirection rule from the redirection plugin settings page or you can disable the plugin.

Body:
I have used the REDIRECTION plugin and redirected the URL http://localhost/word/wordpress/product-category/sample/ to http://localhost/word/wordpress/sample/. The first thing it redirects all my product category page to destination URL. So, I need to undo this. But I couldn't find a solution for these. Kindly Suggest me some ideas.

I had tried to remove the redirects line from .htaccess, but nothing happened.

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /word/wordpress/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /word/wordpress/index.php [L]
</IfModule>

END WordPress

If I remove the redirect lines, it displays like,

Object not found!
       The requested URL was not found on this server. The link on the
       referring page seems to be wrong or outdated. Please inform the author
       of that page about the error.

If you think this is a server error, please contact the webmaster.

Error 404

localhost

Apache/2.4.34 (Win32) OpenSSL/1.0.2o PHP/7.1.20


问:
How to write a long os.path.join chain while complying to PEP8
I am using a long chain of os.path.join() to generate a path (it ensures the path will work on any OS).

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',os.path.join('config', os.path.join('metadata',os.path.join('gmail_metadata.xml'))))),
```

<p>I would like to break it down into multiple lines the PEP8 way but I can't seem to make this happen.</p>

<p>I tried several things: </p>

<pre class="lang-py prettyprint-override"><code>"metadata": os.path.join(BASE_DIR,
            os.path.join('ServiceProvider',
            os.path.join('config',
            os.path.join('metadata',
            os.path.join('gmail_metadata.xml'))))),
</code>```

will get me the PEP8 error continuation line under-indented for visual indentpep8(E128)

and

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',
                                                    os.path.join('config', os.path.join('metadata',
                                                                                os.path.join('gmail_metadata.xml'))))),
```

which is actually what PEP8 autofix did, I'm getting the line too long error.

If it is not possible to fix the PEP8 errors in this case I would still like to know how you would do it !

答:
The pathlib module will allow you to chain things in an interesting and flexible way. Lovely tutorial here

```<code>import pathlib

# use / operator
path = pathlib.Path("BASE_DIR")
path /= "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") / "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") /
       "ServiceProvider" /
       "config" /
       "metadata" /
       "gmail_metadata.xml"
</code>```

If you want to use joinpath from os.path module or pathlib then you doint have to nest the joins, one is enough.

```<code>path = os.path.join(*[BASE_DIR, "ServiceProvider", "config", "metadata", "gmail_metadata.xml"])
# or
path = pathlib.Path("BASE_DIR").joinpath(*["ServiceProvider", "config", "metadata", "gmail_metadata.xml"])
</code>```

Body:
I am using a long chain of os.path.join() to generate a path (it ensures the path will work on any OS).

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',os.path.join('config', os.path.join('metadata',os.path.join('gmail_metadata.xml'))))),

I would like to break it down into multiple lines the PEP8 way but I can't seem to make this happen.

I tried several things:

"metadata": os.path.join(BASE_DIR,
            os.path.join('ServiceProvider',
            os.path.join('config',
            os.path.join('metadata',
            os.path.join('gmail_metadata.xml'))))),

will get me the PEP8 error continuation line under-indented for visual indentpep8(E128)

and

"metadata": os.path.join(BASE_DIR, os.path.join('ServiceProvider',
                                                    os.path.join('config', os.path.join('metadata',
                                                                                os.path.join('gmail_metadata.xml'))))),

which is actually what PEP8 autofix did, I'm getting the line too long error.

If it is not possible to fix the PEP8 errors in this case I would still like to know how you would do it !

Body:
The pathlib module will allow you to chain things in an interesting and flexible way. Lovely tutorial here

import pathlib

# use / operator
path = pathlib.Path("BASE_DIR")
path /= "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") / "ServiceProvider" / "config" / "metadata" / "gmail_metadata.xml"
# or
path = pathlib.Path("BASE_DIR") /
       "ServiceProvider" /
       "config" /
       "metadata" /
       "gmail_metadata.xml"

If you want to use joinpath from os.path module or pathlib then you doint have to nest the joins, one is enough.

path = os.path.join(*[BASE_DIR, "ServiceProvider", "config", "metadata", "gmail_metadata.xml"])
# or
path = pathlib.Path("BASE_DIR").joinpath(*["ServiceProvider", "config", "metadata", "gmail_metadata.xml"])


问:
Use different ip addresses in puppeteer requests
I have multiple ip interfaces in my server and I can't find how to force puppeteer to use them in its requests

I am using node v10.15.0 and puppeteer 1.11.0

答:
Maybe this will help. You can see the full code here</p>

```<code>'use strict';

const puppeteer = require('puppeteer');

(async() => {
  const browser = await puppeteer.launch({
    // Launch chromium using a proxy server on port 9876.
    // More on proxying:
    //    https://www.chromium.org/developers/design-documents/network-settings
    args: [ '--proxy-server=127.0.0.1:9876' ]
  });
  const page = await browser.newPage();
  await page.goto('https://google.com');
  await browser.close();
})();
</code>```

Body:
Maybe this will help. You can see the full code here

'use strict';

const puppeteer = require('puppeteer');

(async() => {
  const browser = await puppeteer.launch({
    // Launch chromium using a proxy server on port 9876.
    // More on proxying:
    //    https://www.chromium.org/developers/design-documents/network-settings
    args: [ '--proxy-server=127.0.0.1:9876' ]
  });
  const page = await browser.newPage();
  await page.goto('https://google.com');
  await browser.close();
})();


问:
How get a current position of textBox
How can I get a current position of textBox element when call this method?

```<code> private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
        {

        }
</code>```

UPDATE

```<code> GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
            Point offset = gt.Transform(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;
</code>```

When I use this controlTop and controlLeft are (0,0)

答:
I wanted all of my textboxes to go to the right edge (minus 20). They are all aligned horizontally on the left.

I enabled the page SizeChanged event handler then added:

```<code>        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GeneralTransform gt = tbSvcMsgOut.TransformToVisual(this);
            Point offset = gt.TransformPoint(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;
            double newWidth =  e.NewSize.Width - controlLeft - 20;
            if (newWidth > tbSvcMsgOut.MinWidth)
            {
                tbSvcMsgOut.Width = newWidth;
                tbDeviceMsgIn.Width = newWidth;
                tbSvcMsgIn.Width = newWidth;
                tbDeiceMsgOut.Width = newWidth;
            }
        }
</code>```

This works fine for me, :)

ContentLicense: CC BY-SA 3.0

Title: How get a current position of textBox

Body:
How can I get a current position of textBox element when call this method?

 private void UserTextBox_GotFocus(object sender, RoutedEventArgs e)
        {

        }

UPDATE

 GeneralTransform gt = this.TransformToVisual(Application.Current.RootVisual as UIElement);
            Point offset = gt.Transform(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;

When I use this controlTop and controlLeft are (0,0)

Body:
I wanted all of my textboxes to go to the right edge (minus 20). They are all aligned horizontally on the left.

I enabled the page SizeChanged event handler then added:

        private void Page_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            GeneralTransform gt = tbSvcMsgOut.TransformToVisual(this);
            Point offset = gt.TransformPoint(new Point(0, 0));
            double controlTop = offset.Y;
            double controlLeft = offset.X;
            double newWidth =  e.NewSize.Width - controlLeft - 20;
            if (newWidth > tbSvcMsgOut.MinWidth)
            {
                tbSvcMsgOut.Width = newWidth;
                tbDeviceMsgIn.Width = newWidth;
                tbSvcMsgIn.Width = newWidth;
                tbDeiceMsgOut.Width = newWidth;
            }
        }

This works fine for me, :)


问:
How to pass data from BottomSheetFragmentDialog?
the question is how to pass data from BottomSheetDialogFragment to Fragment or Activity and what would be the correct way ?

Here is my Fragment dialog that will be opened in my Frament and should save data from textview that is getting clicked on.

```<code>class BallTypeDialogFragment : BottomSheetDialogFragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
    inflater.inflate(R.layout.fragment_blood_type_dialog, container, false)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    text_view_ball_O.setOnClickListener {
        text_view_ball_O.text
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_A.setOnClickListener {
        text_view_ball_A.text
        Toast.makeText(context, "A+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AA.setOnClickListener {
        Toast.makeText(context, "AA+", Toast.LENGTH_SHORT).show()
    }
    text_view_blood_grop_minus.setOnClickListener {
        text_view_blood_grop_minus.text
        Toast.makeText(context, "-", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AAR.setOnClickListener {
        text_view_ball_AAR.text
        Toast.makeText(context, "R -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AARS.setOnClickListener {
        text_view_ball_AARS.text
        Toast.makeText(context, "AARS -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_OO.setOnClickListener {
        text_view_ball_OO.text
        Toast.makeText(context, "OO -", Toast.LENGTH_SHORT).show()
    }
}
}
</code>```

And i Simply open it in my Fragment like this,even though I understand it is incorrect.

```<code> private fun showDialog() {
    val dialog = BallTypeDialogFragment()

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}
</code>```

答:
Since you're using kotlin, you might consider passing a lambda to your dialogfragment.

E.g.
BallTypeDialogFragment(onData: (String) -> Unit)

and then you pass it by

```<code>private fun showDialog(onData: (String) -> Unit)) {
    val dialog = BallTypeDialogFragment(onData)

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}
</code>```

then in your DialogFragment you just do:

```<code>//something something
text_view_ball_O.setOnClickListener {
        onData(text_view_ball_O.text)
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
//something something

</code>```

Body:
the question is how to pass data from BottomSheetDialogFragment to Fragment or Activity and what would be the correct way ?

Here is my Fragment dialog that will be opened in my Frament and should save data from textview that is getting clicked on.

class BallTypeDialogFragment : BottomSheetDialogFragment() {

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?) =
    inflater.inflate(R.layout.fragment_blood_type_dialog, container, false)

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    text_view_ball_O.setOnClickListener {
        text_view_ball_O.text
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_A.setOnClickListener {
        text_view_ball_A.text
        Toast.makeText(context, "A+", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AA.setOnClickListener {
        Toast.makeText(context, "AA+", Toast.LENGTH_SHORT).show()
    }
    text_view_blood_grop_minus.setOnClickListener {
        text_view_blood_grop_minus.text
        Toast.makeText(context, "-", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AAR.setOnClickListener {
        text_view_ball_AAR.text
        Toast.makeText(context, "R -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_AARS.setOnClickListener {
        text_view_ball_AARS.text
        Toast.makeText(context, "AARS -", Toast.LENGTH_SHORT).show()
    }
    text_view_ball_OO.setOnClickListener {
        text_view_ball_OO.text
        Toast.makeText(context, "OO -", Toast.LENGTH_SHORT).show()
    }
}
}

And i Simply open it in my Fragment like this,even though I understand it is incorrect.

 private fun showDialog() {
    val dialog = BallTypeDialogFragment()

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}

Body:
Since you're using kotlin, you might consider passing a lambda to your dialogfragment.

E.g.
BallTypeDialogFragment(onData: (String) -> Unit)

and then you pass it by

private fun showDialog(onData: (String) -> Unit)) {
    val dialog = BallTypeDialogFragment(onData)

    dialog.show(childFragmentManager, "BallTypeDialogFragment")
}

then in your DialogFragment you just do:

//something something
text_view_ball_O.setOnClickListener {
        onData(text_view_ball_O.text)
        Toast.makeText(context, "O+", Toast.LENGTH_SHORT).show()
    }
//something something


问:
How to softcode map in SpringBoot application.properties file instead of hardcoding?
So, I want to return a JSON object which should look like:

```<code>{"Issues":[{"IssueName": "Loan"},{"IssueName": "Lease"},{"IssueName": "Other"}]}
</code>```

So far the closest I am to this format is through this code:

```<code>@RequestMapping(value="/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)
    public  Map<String, String> getIssue(){
        HashMap<String, String> issue = new HashMap<>();
        issue.put("issues", "Loan");
        issue.put("issues", "Lease");
        issue.put("issues", "Other");
        return issue;
    }
</code>```

While map gives me key value pairs in curly braces, it doesn't allow me to set same key to different values (for obvious reasons). Is there any other way to return the above JSON object? And is it possible to softcode it in application.properties so that if later I want to add more issue types I can do it easily?

答:
One way is to use a List of Entries instead of Map of Entries:

```<code>@Value("#{'${issues}'.split(',')}")
private List<String> issues;

@RequestMapping(value = "/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, List<Map.Entry<String, String>>> getIssue() {
    Map<String, List<Map.Entry<String, String>>> m = new LinkedHashMap<>();
    m.put("Issues", issues.stream()
            .map(s -> Map.entry("issueName", s))
            .collect(Collectors.toList()));
    return m;
}
</code>```

and in your application.properties:

```<code>issues=Loan,Lease,Other
</code>```

Output:

```<code>{"Issues":[{"issueName":"Loan"},{"issueName":"Lease"},{"issueName":"Other"}]}
</code>```

Body:
So, I want to return a JSON object which should look like:

{"Issues":[{"IssueName": "Loan"},{"IssueName": "Lease"},{"IssueName": "Other"}]}

So far the closest I am to this format is through this code:

@RequestMapping(value="/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)
    public  Map<String, String> getIssue(){
        HashMap<String, String> issue = new HashMap<>();
        issue.put("issues", "Loan");
        issue.put("issues", "Lease");
        issue.put("issues", "Other");
        return issue;
    }

While map gives me key value pairs in curly braces, it doesn't allow me to set same key to different values (for obvious reasons). Is there any other way to return the above JSON object? And is it possible to softcode it in application.properties so that if later I want to add more issue types I can do it easily?

Body:
One way is to use a List of Entries instead of Map of Entries:

@Value("#{'${issues}'.split(',')}")
private List<String> issues;

@RequestMapping(value = "/issueTypes", produces = MediaType.APPLICATION_JSON_VALUE)
public Map<String, List<Map.Entry<String, String>>> getIssue() {
    Map<String, List<Map.Entry<String, String>>> m = new LinkedHashMap<>();
    m.put("Issues", issues.stream()
            .map(s -> Map.entry("issueName", s))
            .collect(Collectors.toList()));
    return m;
}

and in your application.properties:

issues=Loan,Lease,Other

Output:

{"Issues":[{"issueName":"Loan"},{"issueName":"Lease"},{"issueName":"Other"}]}


问:
How do you get git bisect to ignore merged branches?
I'm aware that git bisect is branch-aware by design, so that if between good commit, G, and bad commit, B, you merged in a branch, it needs to take those changes into consideration as well, as the bug may be contained in the branch.

In my case I have a dependency as a side branch and I merge in changes to my main project from time to time. The dependency can be considered a library that has a different way of running, different build-system etc. from my main project, but I still want recent changes from it via merges to the main branch.

The problem is then that while bisecting in this scenario, you end up on non-compilable commits in the commits from the dependency.

I would really just want to consider each branch merge as a single commit while doing the bisection.

A workaround I've found so far is making a list of valid commits G..B with git log --first-parent, and then while bisecting, do git bisect skip if the current commit isn't in that list. That takes a lot of time though (lots of files to checkout/change for each skip).

So the question is: Is there any way of doing --first-parent with git bisect or providing a list of commits i feel are valid to be able to avoid checking out branches I know already are not compilable? How do we only check the commits marked o in the diagram?

```
G---o---o---o---o---o---o---B  main project branch
   /       /       /
  x---x---x---x---x            dependency
           \ /
            x'                 dependency project taskbranch
```

Edit: added diagram for clarity

答:
I've been looking for something like this too. As far as I've got is that git rev-list --bisect --first-parent seems to do what you want to, and the docs for rev-list implies that the --bisect option is what bisect uses internally - but getting git bisect to add that flag to its call(s) to rev-list seems less trivial:

The bisect command is implemented by a shell script git-bisect, which in turn uses a builtin command bisect--helper to actually do the interesting part ("computation, display and checkout" says the comment...), apparently based on a bunch of magic state files in .git/. And it seems to be the rev-list command that is reusing code from bisect--helper rather than the other way around as you might expect.

So, you'd have to extend the bisect--helper code's commit filtering to do it, I think.

As a workaround, something like this might work: after bisect checks something out for you, reset to a different one using git rev-list --bisect --first-parent, test that and mark it good/bad/skip and continue from there.

Body:
I'm aware that git bisect is branch-aware by design, so that if between good commit, G, and bad commit, B, you merged in a branch, it needs to take those changes into consideration as well, as the bug may be contained in the branch.

In my case I have a dependency as a side branch and I merge in changes to my main project from time to time. The dependency can be considered a library that has a different way of running, different build-system etc. from my main project, but I still want recent changes from it via merges to the main branch.

The problem is then that while bisecting in this scenario, you end up on non-compilable commits in the commits from the dependency.

I would really just want to consider each branch merge as a single commit while doing the bisection.

A workaround I've found so far is making a list of valid commits G..B with git log --first-parent, and then while bisecting, do git bisect skip if the current commit isn't in that list. That takes a lot of time though (lots of files to checkout/change for each skip).

So the question is: Is there any way of doing --first-parent with git bisect or providing a list of commits i feel are valid to be able to avoid checking out branches I know already are not compilable? How do we only check the commits marked o in the diagram?

G---o---o---o---o---o---o---B  main project branch
   /       /       /
  x---x---x---x---x            dependency
           \ /
            x'                 dependency project taskbranch

Edit: added diagram for clarity


问:
Get contents of a particular row
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

```<code>.
.
.

<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>

.
.
.
</code>```

I can get 'xyz' easily by using

```<code>required = soup.find('a', text = 'xyz')
print(required[0].text)
</code>```

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

```<code>xyz
address
phone number
</code>```

答:
With bs4 4.7.1 combine pseudo classes of :has and :contains to retrieve the row and tds within.

This bit targets the right a tag if present by its text

```<code>a:contains("xyz")
</code>```

You then retrieve the parent row (tr) having this a tag

```<code>tr:has(a:contains("xyz"))
</code>```

And finally use a descendant combinator and td type selector to get all the tds within that row. Using a list comprehension to return the list.

```<code>from bs4 import BeautifulSoup as bs

html = '''
<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>
'''

soup = bs(html, 'lxml')
items = [item.text.strip() for item in soup.select('tr:has(a:contains("xyz")) td')]
print(items)
</code>```

Title: Get contents of a particular row

Body:
I want to locate 'td' where text is 'xyz' so that I can find other attributes in the row. I only have 'xyz' with me and want to get other elements in that row.

.
.
.

        xyz

    address
    phone number

.
.
.

I can get 'xyz' easily by using

required = soup.find('a', text = 'xyz')
print(required[0].text)

but I'm not able to locate 'td' so that I can use find_next_siblings() to get other columns.

Expected output:

xyz
address
phone number

Body:
With bs4 4.7.1 combine pseudo classes of :has and :contains to retrieve the row and tds within.

This bit targets the right a tag if present by its text

a:contains("xyz")

You then retrieve the parent row (tr) having this a tag

tr:has(a:contains("xyz"))

And finally use a descendant combinator and td type selector to get all the tds within that row. Using a list comprehension to return the list.

from bs4 import BeautifulSoup as bs

html = '''
<tr>
    <td>
        <a>xyz</a>
    </td>
    <td>address</td>
    <td>phone number</td>
</tr>
'''

soup = bs(html, 'lxml')
items = [item.text.strip() for item in soup.select('tr:has(a:contains("xyz")) td')]
print(items)


问:
Docker + Xdebug + VSCode Could not connect to client
PHP version: 7.1.20

XDebug version: 2.7.0

I'm using a Docker container on MacOS Mojave.
On pressing "F5", it shows debug options Pause, Restart, and Stop. But Step Over, Step Into, Step Out are disabled.

I'm kind of learner because I was used to code till 2012-13 on Windows OS. After that year, I am back to coding this month. :) Even after reviewing a lot of posts on Google about how to resolve this issue, I'm not sure how to finally make it work. Please help.

My launch.json file:

```<code>{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/learn"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9001
        }
    ]
}
</code>```

XDebug php.ini config:

```<code>xdebug.remote_host = 172.20.0.1
xdebug.remote_port = 9001
xdebug.scream = 1
xdebug.remote_enable = 1
xdebug.show_local_vars = 1
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_log = "/var/www/html/xdebug.log"
xdebug.idekey = "VSCODE"
</code>```

XDebug logfile (from setting xdebug.remote_log in php.ini):

```<code>[12] Log opened at 2019-05-12 10:16:44
[12] I: Checking remote connect back address.
[12] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[12] I: Checking header 'REMOTE_ADDR'.
[12] I: Remote address found, connecting to 172.20.0.1:9001.
[12] W: Creating socket for '172.20.0.1:9001', poll success, but error: Operation now in progress (29).
[12] E: Could not connect to client. :-(
[12] Log closed at 2019-05-12 10:16:44
</code>```

Debug console:

```<code><- launchResponse
Response {
  seq: 0,
  type: 'response',
  request_seq: 2,
  command: 'launch',
  success: true }
</code>```

Here's the dockerfile.

```<code>FROM php:7.1.20-apache

RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y

# Install tools & libraries
RUN apt-get -y install apt-utils nano wget dialog \
    build-essential git curl libcurl3 libcurl3-dev zip

# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl3 libcurl3-dev zip \
    libmcrypt-dev libsqlite3-dev libsqlite3-0 mysql-client zlib1g-dev \
    libicu-dev libfreetype6-dev libjpeg62-turbo-dev libpng-dev

# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# PHP Extensions
RUN pecl install xdebug-2.7.0 \
    && docker-php-ext-enable xdebug \
    && docker-php-ext-install mcrypt \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pdo_sqlite \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install curl \
    && docker-php-ext-install tokenizer \
    && docker-php-ext-install json \
    && docker-php-ext-install zip \
    && docker-php-ext-install -j$(nproc) intl \
    && docker-php-ext-install mbstring \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd \
    && pecl install redis \
    && docker-php-ext-enable redis

# Enable apache modules
RUN a2enmod rewrite headers

ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]
</code>```

Here's the docker-compose.yml file.

```<code>version: "3"

services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
  mysql:
    build: ./bin/mysql
    container_name: '5.7-mysql'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes:
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tiger
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: 'sc-phpmyadmin'
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes:
      - /sessions
  redis:
    container_name: 'sc-redis'
    image: redis:latest
    ports:
      - "6379:6379"
</code>```

Thank you in advance.

答:
Try to open port 9001 in the docker-compose.yml by inserting:

```<code>ports:
 - "9001:9001"
</code>```

Example

```<code>services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
      - "9001:9001"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
</code>```

See more about configuring docker-compose.yml: https://docs.docker.com/compose/compose-file/

You might be able to use expose. We have that in some of our old Dockerfiles which is intended to allow xDebug connections, but I haven't used it personally.

```<code>    expose:
      - "9001"
</code>```

Body:
PHP version: 7.1.20

XDebug version: 2.7.0

I'm using a Docker container on MacOS Mojave.
On pressing "F5", it shows debug options Pause, Restart, and Stop. But Step Over, Step Into, Step Out are disabled.

I'm kind of learner because I was used to code till 2012-13 on Windows OS. After that year, I am back to coding this month. :) Even after reviewing a lot of posts on Google about how to resolve this issue, I'm not sure how to finally make it work. Please help.

My launch.json file:

{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Listen for XDebug",
            "type": "php",
            "request": "launch",
            "port": 9001,
            "log": true,
            "pathMappings": {
                "/var/www/html": "${workspaceFolder}/learn"
            }
        },
        {
            "name": "Launch currently open script",
            "type": "php",
            "request": "launch",
            "program": "${file}",
            "cwd": "${fileDirname}",
            "port": 9001
        }
    ]
}

XDebug php.ini config:

xdebug.remote_host = 172.20.0.1
xdebug.remote_port = 9001
xdebug.scream = 1
xdebug.remote_enable = 1
xdebug.show_local_vars = 1
xdebug.remote_autostart = 1
xdebug.remote_connect_back = 1
xdebug.remote_log = "/var/www/html/xdebug.log"
xdebug.idekey = "VSCODE"

XDebug logfile (from setting xdebug.remote_log in php.ini):

[12] Log opened at 2019-05-12 10:16:44
[12] I: Checking remote connect back address.
[12] I: Checking header 'HTTP_X_FORWARDED_FOR'.
[12] I: Checking header 'REMOTE_ADDR'.
[12] I: Remote address found, connecting to 172.20.0.1:9001.
[12] W: Creating socket for '172.20.0.1:9001', poll success, but error: Operation now in progress (29).
[12] E: Could not connect to client. :-(
[12] Log closed at 2019-05-12 10:16:44

Debug console:

<- launchResponse
Response {
  seq: 0,
  type: 'response',
  request_seq: 2,
  command: 'launch',
  success: true }

Here's the dockerfile.

FROM php:7.1.20-apache

RUN apt-get -y update --fix-missing
RUN apt-get upgrade -y

# Install tools & libraries
RUN apt-get -y install apt-utils nano wget dialog \
    build-essential git curl libcurl3 libcurl3-dev zip

# Install important libraries
RUN apt-get -y install --fix-missing apt-utils build-essential git curl libcurl3 libcurl3-dev zip \
    libmcrypt-dev libsqlite3-dev libsqlite3-0 mysql-client zlib1g-dev \
    libicu-dev libfreetype6-dev libjpeg62-turbo-dev libpng-dev

# Composer
RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer

# PHP Extensions
RUN pecl install xdebug-2.7.0 \
    && docker-php-ext-enable xdebug \
    && docker-php-ext-install mcrypt \
    && docker-php-ext-install pdo_mysql \
    && docker-php-ext-install pdo_sqlite \
    && docker-php-ext-install mysqli \
    && docker-php-ext-install curl \
    && docker-php-ext-install tokenizer \
    && docker-php-ext-install json \
    && docker-php-ext-install zip \
    && docker-php-ext-install -j$(nproc) intl \
    && docker-php-ext-install mbstring \
    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
    && docker-php-ext-install -j$(nproc) gd \
    && pecl install redis \
    && docker-php-ext-enable redis

# Enable apache modules
RUN a2enmod rewrite headers

ENTRYPOINT ["/usr/sbin/apache2ctl", "-D", "FOREGROUND"]

Here's the docker-compose.yml file.

version: "3"

services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2
  mysql:
    build: ./bin/mysql
    container_name: '5.7-mysql'
    restart: 'always'
    ports:
      - "3306:3306"
    volumes:
      - ${MYSQL_DATA_DIR-./data/mysql}:/var/lib/mysql
      - ${MYSQL_LOG_DIR-./logs/mysql}:/var/log/mysql
    environment:
      MYSQL_ROOT_PASSWORD: tiger
  phpmyadmin:
    image: phpmyadmin/phpmyadmin
    container_name: 'sc-phpmyadmin'
    links:
      - mysql
    environment:
      PMA_HOST: mysql
      PMA_PORT: 3306
    ports:
      - '8080:80'
    volumes:
      - /sessions
  redis:
    container_name: 'sc-redis'
    image: redis:latest
    ports:
      - "6379:6379"

Thank you in advance.

Body:
Try to open port 9001 in the docker-compose.yml by inserting:

ports:
 - "9001:9001"

Example

services:
  webserver:
    build:
      context: ./bin/webserver
    container_name: '7.1.x-webserver'
    restart: 'always'
    ports:
      - "80:80"
      - "443:443"
      - "9001:9001"
    links:
      - mysql
    volumes:
      - ${DOCUMENT_ROOT-./www}:/var/www/html
      - ${PHP_INI-./config/php/php.ini}:/usr/local/etc/php/php.ini
      - ${VHOSTS_DIR-./config/vhosts}:/etc/apache2/sites-enabled
      - ${LOG_DIR-./logs/apache2}:/var/log/apache2

See more about configuring docker-compose.yml: https://docs.docker.com/compose/compose-file/

You might be able to use expose. We have that in some of our old Dockerfiles which is intended to allow xDebug connections, but I haven't used it personally.

    expose:
      - "9001"


问:
How to handle data with two has_many associations
I'm new to Ruby on Rails. Just getting my head around modelling relationships and how to build CRUD with them. I'd like advice or suggestions on how to fix this problem.

In my system, a support user (student) has private support sessions (like classes) with their support worker (tutor). Here's how the system will be used: a support worker will log in, select a service user they work with, and record a support session, which includes things like how long the session lasted for and where it took place. Eventually, the system will produce time-sheets that can be used to invoice for the tutor's work in these private support sessions.

I'm not quite sure how to interact with this at a controller level. So far I've built my model and scaffolds - now I'm customising them.

I've been using the official tutorial to help me get started at: https://guides.rubyonrails.org/v3.2.8/getting_started.html but I think I've gone beyond that now.

```<code># Models
# Not entirely sure inverse_of is appropriate but several tutorials suggested it's worth putting in
class ServiceUser < ApplicationRecord
  has_many :support_sessions, inverse_of: :service_user
  has_many :support_workers, through: :support_sessions
end

class SupportWorker < ApplicationRecord
  has_many :support_sessions, inverse_of: :support_worker
  has_many :service_users, through: :support_sessions

class SupportSession < ApplicationRecord
  belongs_to :support_worker, inverse_of: :support_sessions
  belongs_to :service_user, inverse_of: :support_sessions
end

# Controller
class SupportSessionsController < ApplicationController
  # POST /support_sessions
  # POST /support_sessions.json
  def create
  # Auto-generated line:
  @support_session = SupportSession.new(support_session_params)

  # Get service_user_id from query string
  @service_user = ServiceUser.find(params[:service_user_id])

  # Lifted from RoR 'Getting started' article
  @support_session = @service_user.support_sessions.create(params[:service_user])

  respond_to do |format|
  if @support_session.save
  #format.html { redirect_to @support_session, notice: 'Support session was successfully created.' }
  format.html { redirect_to service_users_url, notice: 'Support session was successfully created.' }
  format.json { render :show, status: :created, location: @support_session }
  else
  format.html { render :new }
  format.json { render json: @support_session.errors, status: :unprocessable_entity }
  end
  end

  end
end

# Service user view/HTML form
# This is rendered as a partial on the service user's show.html.erb view
# select_support_workers() helper retrieves a list of ALL support workers in the system and the control value is the support_worker_id
<%= form_for([@service_user, @service_user.support_sessions.build]) do |f| %>
<tr>
  <td>
  <%= select_support_workers(f) %>
  </td>
  <td>
  <%= f.text_field :location %>
  </td>
  <td>
  <%= f.text_field :mode_of_delivery %>
  </td>
  <td>
  <%= f.text_field :started_at %>
  </td>
  <td>
  <%= f.text_field :ended_at %>
  </td>
  <td>
  <%= f.text_field :total_breaks %>
  </td>
  <td>
  <%= f.submit 'Save session' %>
  </td>
</tr>

<% end %>
</code>```

When I submit the form (which is being rendered as a partial on the service_user view show page), I seem to be ending up in the 'else' part of the if @support_session.save logic.

Error shown in my web browser is:

```<code>NameError in SupportSessions#create
Showing /Users/chris/git-local/timesheets/app/views/support_sessions/new.html.erb where line #5 raised:

undefined local variable or method `support_sessions_path' for #<#<Class:0x00007feb3412d028>:0x00007feb34163268>
Did you mean? @support_session
Extracted source (around line #5):

3 <%= render 'form', support_session: @support_session %>
4
5 <%= link_to 'Back', support_sessions_path %>

Rails.root: /Users/chris/git-local/timesheets

Application Trace | Framework Trace | Full Trace
app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb__485411543567831194_70324083953220'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"/xd16JX3LBjA7+9DVfnHwnJziucJkaICaWg/Sd6TK2rDOrugMcZu0r5qr6SO0TfqvXzzhBqvkydMIQqXp2NtrQ==",
 "support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""},
 "commit"=>"Save session",
 "service_user_id"=>"1"}
</code>```

Console output

```<code>Started GET "/service_users/" for ::1 at 2019-05-31 07:58:29 +0100
   (0.5ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  ↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:29 +0100
  Rendering service_users/index.html.erb within layouts/application
   (0.6ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  ↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  ServiceUser Load (0.7ms)  SELECT `service_users`.* FROM `service_users`
Processing by ServiceUsersController#show as HTML
  ↳ app/views/service_users/index.html.erb:22
  Parameters: {"id"=>"4"}
  Rendered service_users/index.html.erb within layouts/application (7.6ms)
  ServiceUser Load (2.4ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (0.9ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.2ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (7.5ms)
  Rendered service_users/show.html.erb within layouts/application (15.6ms)
Completed 200 OK in 94ms (Views: 91.2ms | ActiveRecord: 0.7ms)

Completed 200 OK in 115ms (Views: 105.7ms | ActiveRecord: 4.5ms)

Started GET "/service_users/" for ::1 at 2019-05-31 07:58:30 +0100
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:30 +0100
  Rendering service_users/index.html.erb within layouts/application
Processing by ServiceUsersController#show as HTML
  ServiceUser Load (1.5ms)  SELECT `service_users`.* FROM `service_users`
  Parameters: {"id"=>"4"}
  ↳ app/views/service_users/index.html.erb:22
  Rendered service_users/index.html.erb within layouts/application (5.9ms)
  ServiceUser Load (2.2ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (0.8ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.3ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (5.5ms)
  Rendered service_users/show.html.erb within layouts/application (12.1ms)
Completed 200 OK in 126ms (Views: 122.0ms | ActiveRecord: 1.5ms)

Completed 200 OK in 108ms (Views: 100.0ms | ActiveRecord: 4.3ms)

Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Processing by ServiceUsersController#show as HTML
  Parameters: {"id"=>"4"}
Processing by ServiceUsersController#show as HTML
  Parameters: {"id"=>"4"}
  ServiceUser Load (1.3ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  ServiceUser Load (1.5ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (1.5ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  SupportSession Load (0.7ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  Rendered collection of templates [0 times] (0.0ms)
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.4ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  SupportWorker Load (0.7ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (5.7ms)
  Rendered service_users/show.html.erb within layouts/application (11.7ms)
  Rendered support_sessions/_form.html.erb (5.8ms)
  Rendered service_users/show.html.erb within layouts/application (12.6ms)
Completed 200 OK in 80ms (Views: 71.4ms | ActiveRecord: 4.2ms)

Completed 200 OK in 82ms (Views: 74.2ms | ActiveRecord: 2.9ms)

Started POST "/service_users/4/support_sessions" for ::1 at 2019-05-31 07:58:35 +0100
Processing by SupportSessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"KZGBtom/9t6vYu5FyPRq3xA3Xmb6hkzG8LEA7c/qmOkUZGmtslduK+l2as5chNz7w4ikC+5fHRYh3Ak2IZwIvA==", "support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""}, "commit"=>"Save session", "service_user_id"=>"4"}
  ServiceUser Load (0.5ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/support_sessions_controller.rb:33
   (0.3ms)  BEGIN
  ↳ app/controllers/support_sessions_controller.rb:36
   (0.3ms)  ROLLBACK
  ↳ app/controllers/support_sessions_controller.rb:36
   (0.2ms)  BEGIN
  ↳ app/controllers/support_sessions_controller.rb:41
   (0.2ms)  ROLLBACK
  ↳ app/controllers/support_sessions_controller.rb:41
  Rendering support_sessions/new.html.erb within layouts/application
  SupportWorker Load (0.5ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (3.9ms)
  Rendered support_sessions/new.html.erb within layouts/application (324.5ms)
Completed 500 Internal Server Error in 336ms (ActiveRecord: 2.0ms)

ActionView::Template::Error (undefined local variable or method `support_sessions_path' for #<#<Class:0x00007ffb0925c658>:0x00007ffb083fa100>
Did you mean?  @support_session):
    2:
    3: <%= render 'form', support_session: @support_session %>
    4:
    5: <%= link_to 'Back', support_sessions_path %>

app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb___2840892112036112501_70358075950960'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'

# Crebs:timesheets chris$ rake routes -c support_session
                           Prefix Verb   URI Pattern                                                         Controller#Action
    service_user_support_sessions GET    /service_users/:service_user_id/support_sessions(.:format)          support_sessions#index
                                  POST   /service_users/:service_user_id/support_sessions(.:format)          support_sessions#create
 new_service_user_support_session GET    /service_users/:service_user_id/support_sessions/new(.:format)      support_sessions#new
edit_service_user_support_session GET    /service_users/:service_user_id/support_sessions/:id/edit(.:format) support_sessions#edit
     service_user_support_session GET    /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#show
                                  PATCH  /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#update
                                  PUT    /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#update
                                  DELETE /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#destroy
</code>```

答:
You have nested routes for support_sessions resource, so instead of

```<code><%= link_to 'Back', support_sessions_path %>
</code>```

you should use code like this to build correct path:

```<code><%= link_to 'Back', [@service_user, :support_sessions] %>
</code>```

or maybe like this one:

```<code><%= link_to 'Back', service_user_support_sessions_path(@service_user) %>
</code>```

Body:
I'm new to Ruby on Rails. Just getting my head around modelling relationships and how to build CRUD with them. I'd like advice or suggestions on how to fix this problem.

In my system, a support user (student) has private support sessions (like classes) with their support worker (tutor). Here's how the system will be used: a support worker will log in, select a service user they work with, and record a support session, which includes things like how long the session lasted for and where it took place. Eventually, the system will produce time-sheets that can be used to invoice for the tutor's work in these private support sessions.

I'm not quite sure how to interact with this at a controller level. So far I've built my model and scaffolds - now I'm customising them.

I've been using the official tutorial to help me get started at: https://guides.rubyonrails.org/v3.2.8/getting_started.html but I think I've gone beyond that now.

# Models
# Not entirely sure inverse_of is appropriate but several tutorials suggested it's worth putting in
class ServiceUser < ApplicationRecord
  has_many :support_sessions, inverse_of: :service_user
  has_many :support_workers, through: :support_sessions
end

class SupportWorker < ApplicationRecord
  has_many :support_sessions, inverse_of: :support_worker
  has_many :service_users, through: :support_sessions

class SupportSession < ApplicationRecord
  belongs_to :support_worker, inverse_of: :support_sessions
  belongs_to :service_user, inverse_of: :support_sessions
end

# Controller
class SupportSessionsController < ApplicationController
  # POST /support_sessions
  # POST /support_sessions.json
  def create
  # Auto-generated line:
  @support_session = SupportSession.new(support_session_params)

  # Get service_user_id from query string
  @service_user = ServiceUser.find(params[:service_user_id])

  # Lifted from RoR 'Getting started' article
  @support_session = @service_user.support_sessions.create(params[:service_user])

  respond_to do |format|
  if @support_session.save
  #format.html { redirect_to @support_session, notice: 'Support session was successfully created.' }
  format.html { redirect_to service_users_url, notice: 'Support session was successfully created.' }
  format.json { render :show, status: :created, location: @support_session }
  else
  format.html { render :new }
  format.json { render json: @support_session.errors, status: :unprocessable_entity }
  end
  end

  end
end

# Service user view/HTML form
# This is rendered as a partial on the service user's show.html.erb view
# select_support_workers() helper retrieves a list of ALL support workers in the system and the control value is the support_worker_id
<%= form_for([@service_user, @service_user.support_sessions.build]) do |f| %>

  <%= select_support_workers(f) %>

  <%= f.text_field :location %>

  <%= f.text_field :mode_of_delivery %>

  <%= f.text_field :started_at %>

  <%= f.text_field :ended_at %>

  <%= f.text_field :total_breaks %>

  <%= f.submit 'Save session' %>

<% end %>

When I submit the form (which is being rendered as a partial on the service_user view show page), I seem to be ending up in the 'else' part of the if @support_session.save logic.

Error shown in my web browser is:

NameError in SupportSessions#create
Showing /Users/chris/git-local/timesheets/app/views/support_sessions/new.html.erb where line #5 raised:

undefined local variable or method `support_sessions_path' for #<#<Class:0x00007feb3412d028>:0x00007feb34163268>
Did you mean? @support_session
Extracted source (around line #5):

3 <%= render 'form', support_session: @support_session %>
4
5 <%= link_to 'Back', support_sessions_path %>

Rails.root: /Users/chris/git-local/timesheets

Application Trace | Framework Trace | Full Trace
app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb__485411543567831194_70324083953220'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'
Request

Parameters:

{"utf8"=>"✓",
 "authenticity_token"=>"/xd16JX3LBjA7+9DVfnHwnJziucJkaICaWg/Sd6TK2rDOrugMcZu0r5qr6SO0TfqvXzzhBqvkydMIQqXp2NtrQ==",
 "support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""},
 "commit"=>"Save session",
 "service_user_id"=>"1"}

Console output

Started GET "/service_users/" for ::1 at 2019-05-31 07:58:29 +0100
   (0.5ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  ↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:29 +0100
  Rendering service_users/index.html.erb within layouts/application
   (0.6ms)  SET NAMES utf8,  @@SESSION.sql_mode = CONCAT(CONCAT(@@sql_mode, ',STRICT_ALL_TABLES'), ',NO_AUTO_VALUE_ON_ZERO'),  @@SESSION.sql_auto_is_null = 0, @@SESSION.wait_timeout = 2147483
  ↳ /Users/chris/.rvm/gems/ruby-2.6.3/gems/activerecord-5.2.3/lib/active_record/log_subscriber.rb:98
  ServiceUser Load (0.7ms)  SELECT `service_users`.* FROM `service_users`
Processing by ServiceUsersController#show as HTML
  ↳ app/views/service_users/index.html.erb:22
  Parameters: {"id"=>"4"}
  Rendered service_users/index.html.erb within layouts/application (7.6ms)
  ServiceUser Load (2.4ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (0.9ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.2ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (7.5ms)
  Rendered service_users/show.html.erb within layouts/application (15.6ms)
Completed 200 OK in 94ms (Views: 91.2ms | ActiveRecord: 0.7ms)

Completed 200 OK in 115ms (Views: 105.7ms | ActiveRecord: 4.5ms)

Started GET "/service_users/" for ::1 at 2019-05-31 07:58:30 +0100
Processing by ServiceUsersController#index as HTML
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:30 +0100
  Rendering service_users/index.html.erb within layouts/application
Processing by ServiceUsersController#show as HTML
  ServiceUser Load (1.5ms)  SELECT `service_users`.* FROM `service_users`
  Parameters: {"id"=>"4"}
  ↳ app/views/service_users/index.html.erb:22
  Rendered service_users/index.html.erb within layouts/application (5.9ms)
  ServiceUser Load (2.2ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (0.8ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.3ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (5.5ms)
  Rendered service_users/show.html.erb within layouts/application (12.1ms)
Completed 200 OK in 126ms (Views: 122.0ms | ActiveRecord: 1.5ms)

Completed 200 OK in 108ms (Views: 100.0ms | ActiveRecord: 4.3ms)

Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Started GET "/service_users/4" for ::1 at 2019-05-31 07:58:34 +0100
Processing by ServiceUsersController#show as HTML
  Parameters: {"id"=>"4"}
Processing by ServiceUsersController#show as HTML
  Parameters: {"id"=>"4"}
  ServiceUser Load (1.3ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  ServiceUser Load (1.5ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/service_users_controller.rb:69
  Rendering service_users/show.html.erb within layouts/application
  Rendering service_users/show.html.erb within layouts/application
  SupportSession Load (1.5ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  ↳ app/views/service_users/show.html.erb:18
  SupportSession Load (0.7ms)  SELECT `support_sessions`.* FROM `support_sessions` WHERE `support_sessions`.`service_user_id` = 4
  Rendered collection of templates [0 times] (0.0ms)
  ↳ app/views/service_users/show.html.erb:18
  Rendered collection of templates [0 times] (0.0ms)
  SupportWorker Load (1.4ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  SupportWorker Load (0.7ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (5.7ms)
  Rendered service_users/show.html.erb within layouts/application (11.7ms)
  Rendered support_sessions/_form.html.erb (5.8ms)
  Rendered service_users/show.html.erb within layouts/application (12.6ms)
Completed 200 OK in 80ms (Views: 71.4ms | ActiveRecord: 4.2ms)

Completed 200 OK in 82ms (Views: 74.2ms | ActiveRecord: 2.9ms)

Started POST "/service_users/4/support_sessions" for ::1 at 2019-05-31 07:58:35 +0100
Processing by SupportSessionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"KZGBtom/9t6vYu5FyPRq3xA3Xmb6hkzG8LEA7c/qmOkUZGmtslduK+l2as5chNz7w4ikC+5fHRYh3Ak2IZwIvA==", "support_session"=>{"support_worker_id"=>"3", "location"=>"", "mode_of_delivery"=>"", "started_at"=>"", "ended_at"=>"", "total_breaks"=>""}, "commit"=>"Save session", "service_user_id"=>"4"}
  ServiceUser Load (0.5ms)  SELECT  `service_users`.* FROM `service_users` WHERE `service_users`.`id` = 4 LIMIT 1
  ↳ app/controllers/support_sessions_controller.rb:33
   (0.3ms)  BEGIN
  ↳ app/controllers/support_sessions_controller.rb:36
   (0.3ms)  ROLLBACK
  ↳ app/controllers/support_sessions_controller.rb:36
   (0.2ms)  BEGIN
  ↳ app/controllers/support_sessions_controller.rb:41
   (0.2ms)  ROLLBACK
  ↳ app/controllers/support_sessions_controller.rb:41
  Rendering support_sessions/new.html.erb within layouts/application
  SupportWorker Load (0.5ms)  SELECT `support_workers`.* FROM `support_workers` ORDER BY `support_workers`.`given_name` ASC
  ↳ app/helpers/support_sessions_helper.rb:15
  Rendered support_sessions/_form.html.erb (3.9ms)
  Rendered support_sessions/new.html.erb within layouts/application (324.5ms)
Completed 500 Internal Server Error in 336ms (ActiveRecord: 2.0ms)

ActionView::Template::Error (undefined local variable or method `support_sessions_path' for #<#<Class:0x00007ffb0925c658>:0x00007ffb083fa100>
Did you mean?  @support_session):
    2:
    3: <%= render 'form', support_session: @support_session %>
    4:
    5: <%= link_to 'Back', support_sessions_path %>

app/views/support_sessions/new.html.erb:5:in `_app_views_support_sessions_new_html_erb___2840892112036112501_70358075950960'
app/controllers/support_sessions_controller.rb:46:in `block (2 levels) in create'
app/controllers/support_sessions_controller.rb:40:in `create'

# Crebs:timesheets chris$ rake routes -c support_session
                           Prefix Verb   URI Pattern                                                         Controller#Action
    service_user_support_sessions GET    /service_users/:service_user_id/support_sessions(.:format)          support_sessions#index
                                  POST   /service_users/:service_user_id/support_sessions(.:format)          support_sessions#create
 new_service_user_support_session GET    /service_users/:service_user_id/support_sessions/new(.:format)      support_sessions#new
edit_service_user_support_session GET    /service_users/:service_user_id/support_sessions/:id/edit(.:format) support_sessions#edit
     service_user_support_session GET    /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#show
                                  PATCH  /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#update
                                  PUT    /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#update
                                  DELETE /service_users/:service_user_id/support_sessions/:id(.:format)      support_sessions#destroy

Body:
You have nested routes for support_sessions resource, so instead of

<%= link_to 'Back', support_sessions_path %>

you should use code like this to build correct path:

<%= link_to 'Back', [@service_user, :support_sessions] %>

or maybe like this one:

<%= link_to 'Back', service_user_support_sessions_path(@service_user) %>


问:
Hide the outside element on click of parent div
This is my HTML code:

```<code><html>
<head>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
 <body>
     <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
       <div class="price-box price-final_price">
           <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display:
           inline;">From</span>100</span>

          </div>
     </div>

   <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>200</span>

        </div>
    </div>

    <div class="product details product-item-details">
     <div class="swatch-option text" >Large</div>
     <div class="price-box price-final_price">
          <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>300</span>

          </div>
  </div>
 <script>
  $(document).ready(function($){
     $('.product-item-details .swatch-option').live("click",function(){
        $(this).next('.price-final_price .price-container .price-label').hide();

    });
  });
  <script>

 </body>
</head>
</html>
</code>```

I need to hide "From" label of the span element "price-label" when a particular div is clicked.

The above jQuery code is not working for me,

Any help would be greatly appreciated. Thanks

答:
First of, dont use .live but use .on because As of jQuery 1.7, the .live() method is deprecated.

Then use $(this).next('.price-final_price').find(".price-container .price-label").hide();

```<code>$(document).ready(function() {
  $('.product-item-details .swatch-option').on("click", function() {
    $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});
</code>```

Demo

$(document).ready(function() {
  $('.product-item-details .swatch-option').on("click", function() {
    $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display:
           inline;">From</span>100</span>

  </div>
</div>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>200</span>

  </div>
</div>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>300</span>

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

Body:
This is my HTML code:

Large

            From100

Large

            From200

Large

            From300

Body:
First of, dont use .live but use .on because As of jQuery 1.7, the .live() method is deprecated.

Then use $(this).next('.price-final_price').find(".price-container .price-label").hide();

$(document).ready(function() {
  $('.product-item-details .swatch-option').on("click", function() {
    $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});

Demo

$(document).ready(function() {
  $('.product-item-details .swatch-option').on("click", function() {
    $(this).next('.price-final_price').find(".price-container .price-label").hide();
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display:
           inline;">From</span>100</span>

  </div>
</div>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>200</span>

  </div>
</div>

<div class="product details product-item-details">
  <div class="swatch-option text">Large</div>
  <div class="price-box price-final_price">
    <span class="price-container price-final_price tax weee">
            <span class="price-label" style="display: inline;">From</span>300</span>

  </div>
</div>


问:
Custom Html Helpers in Asp.net MVC Areas
I have some custom Html helpers for my Asp.net MVC 3 app. In the main application they work correctly as I have put the following in my Web.Config:

```<code><pages clientIDMode="AutoID">
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages"/>
    <add namespace="WebDibaelsaMVC.Utils.HtmlHelpers" />
    <add namespace="WebDibaelsaMVC.Utils.HtmlHelpers.DTOs" />
  </namespaces>
</pages>
</code>```

but I have now created an area and to make my custom helpers work I have to add a using in every page where I use them. Is there a way to add the default namespaces for that area?

答: If you are using Razor you might need to add the reference to the <namespaces> section in the ~/Views/web.config and ~/Areas/YourAreaName/Views/web.config and not the main ~/web.config file. Also make sure you recompile the project, open close the view, maybe even restart Visual Studio for changes to take effect (in terms of Intellisense, it will work if you run the project).

Body:
I have some custom Html helpers for my Asp.net MVC 3 app. In the main application they work correctly as I have put the following in my Web.Config:

<pages clientIDMode="AutoID">
  <namespaces>
    <add namespace="System.Web.Helpers" />
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="System.Web.WebPages"/>
    <add namespace="WebDibaelsaMVC.Utils.HtmlHelpers" />
    <add namespace="WebDibaelsaMVC.Utils.HtmlHelpers.DTOs" />
  </namespaces>
</pages>

but I have now created an area and to make my custom helpers work I have to add a using in every page where I use them. Is there a way to add the default namespaces for that area?


问:
is there any function to make touchable url while converting html text to plain text
I'm trying to convert HTML text into plain text but the URL present in HTML in not touchable in plain text </p>

```<code>var htmlString = """
<p style=\"text-align: justify;\">The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019. </p>\n<p style=\"text-align: justify;\">Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.  </p>\n<p style=\"text-align: justify;\">Stakeholders are advised to check the latest version before filing.</p>\n<p style=\"text-align: justify;\"><a href=\"http://www.mca.gov.in/ /
"""
let encodedData = htmlString.data(using: .unicode, allowLossyConversion: false)

var attributedString: NSAttributedString?

do {
    attributedString = try NSAttributedString(data: encodedData!, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)

} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}
print(encodedData!)
print(attributedString)
</code>```

答:
You can just go through UITextView for simple plain text with touchable.

Set UITextView property Link and Selectable is true, See the following.

Assign simple plain text to UITextView.

```<code>let htmlString = """
The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019.

Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.

Stakeholders are advised to check the latest version before filing.

http://www.mca.gov.in
"""
        txtView.text = htmlString
</code>```

Body:
I'm trying to convert HTML text into plain text but the URL present in HTML in not touchable in plain text

var htmlString = """

The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019.
\n
Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.
\n
Stakeholders are advised to check the latest version before filing.
\n
<a href=\"http://www.mca.gov.in/ /
"""
let encodedData = htmlString.data(using: .unicode, allowLossyConversion: false)

var attributedString: NSAttributedString?

do {
    attributedString = try NSAttributedString(data: encodedData!, options: [NSAttributedString.DocumentReadingOptionKey.documentType:NSAttributedString.DocumentType.html,NSAttributedString.DocumentReadingOptionKey.characterEncoding:NSNumber(value: String.Encoding.utf8.rawValue)], documentAttributes: nil)

} catch let error as NSError {
    print(error.localizedDescription)
} catch {
    print("error")
}
print(encodedData!)
print(attributedString)

Body:
You can just go through UITextView for simple plain text with touchable.

Set UITextView property Link and Selectable is true, See the following.

Assign simple plain text to UITextView.

let htmlString = """
The Ministry of Corporate Affairs (MCA) has informed vide Flash Alert that Form AGILE is likely to be revised on MCA21 Company Forms Download page with effect from May 31, 2019.

Form AGILE is an application for Goods and services tax Identification number, employees state Insurance corporation registration plus Employees provident fund organisation registration.

Stakeholders are advised to check the latest version before filing.

http://www.mca.gov.in
"""
        txtView.text = htmlString


问:
how to add infoWindowAdapters for multiple markers having different values?
```<code> Marker drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
 Marker selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));
</code>```

I am trying to add infoWindow to multiple markers in maps Activity. But the infoWindow adapter is showing the same data on all the markers after being initialized in onMapsReady. I want to show infoWindow on all the markers with their own information i.e. marker infoWindows to be initialized individually so that data becomes relevant.

答:
one way of doing it is by using tags for markers to differentiate between the markers in the infoWindowAdapter section. It is an easier way to do this job I thought.

```<code>selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));
                selfMark.setTag("user");

 drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
                    drMark.setTag("driver");
</code>```

this section for InfoWinfoAdapter:

```<code>     mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                            @Override
                            public View getInfoWindow(Marker marker) {
                                return null;
                            }

                                @Override
                                public View getInfoContents(final Marker marker) {
                                View view = getLayoutInflater().inflate(R.layout.driver_inf, null);

                                final TextView tvEmail = view.findViewById(R.id.emailDrive);
                                final TextView tvname = view.findViewById(R.id.nameDrive);
                                final TextView tvlocality = view.findViewById(R.id.localityDrive);
                                    if(marker.getTag().equals("driver")){
                                        tvEmail.setText("Driver");
                                    }
                                    else if (marker.getTag().equals("user")){
                                        tvEmail.setText("Passenger");
                                    }

                                tvname.setText(dC.getName());
                                Geocoder gc = new Geocoder(passengerAct.this, Locale.getDefault());
                                try {
                                    List<Address> adr = gc.getFromLocation(marker.getPosition().latitude, marker.getPosition().longitude, 1);
                                    Address address = adr.get(0);
                                    tvlocality.setText(address.getLocality() + "," + address.getCountryName());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return view;
                            }
                        });
</code>```

Body:
 Marker drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
 Marker selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));

I am trying to add infoWindow to multiple markers in maps Activity. But the infoWindow adapter is showing the same data on all the markers after being initialized in onMapsReady. I want to show infoWindow on all the markers with their own information i.e. marker infoWindows to be initialized individually so that data becomes relevant.

Body:
one way of doing it is by using tags for markers to differentiate between the markers in the infoWindowAdapter section. It is an easier way to do this job I thought.

selfMark=mMap.addMarker(new MarkerOptions().position(curLocation).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.passengermarker)));
                selfMark.setTag("user");

 drMark=mMap.addMarker(new MarkerOptions().position(drLoc).title("Lahore").icon(BitmapDescriptorFactory.fromResource(R.drawable.marker)));
                    drMark.setTag("driver");

this section for InfoWinfoAdapter:

     mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
                            @Override
                            public View getInfoWindow(Marker marker) {
                                return null;
                            }

                                @Override
                                public View getInfoContents(final Marker marker) {
                                View view = getLayoutInflater().inflate(R.layout.driver_inf, null);

                                final TextView tvEmail = view.findViewById(R.id.emailDrive);
                                final TextView tvname = view.findViewById(R.id.nameDrive);
                                final TextView tvlocality = view.findViewById(R.id.localityDrive);
                                    if(marker.getTag().equals("driver")){
                                        tvEmail.setText("Driver");
                                    }
                                    else if (marker.getTag().equals("user")){
                                        tvEmail.setText("Passenger");
                                    }

                                tvname.setText(dC.getName());
                                Geocoder gc = new Geocoder(passengerAct.this, Locale.getDefault());
                                try {
                                    List<Address> adr = gc.getFromLocation(marker.getPosition().latitude, marker.getPosition().longitude, 1);
                                    Address address = adr.get(0);
                                    tvlocality.setText(address.getLocality() + "," + address.getCountryName());
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                                return view;
                            }
                        });


问:
How to increment a particular value of a hash table without changing its key?
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that.

```<code>int ar[size]={0,2,0,1,4,6,8 ........ 8,6,7}; // array
auto hash=new int[10];   //here the value is initialized to zero

for(int i=0;i<size;i++)
  {
   //here i want to store the time a number occurred in the array with
   keys as number itself

  hash[ar[i]] = **valueof(hash[ar[i]])+1** // i want to do this
  }
</code>```

Edit

```<code>auto hash=new int[10]();
</code>```

答:
You can use following line of code:</p>

```<code>hash[ar[i]] += 1
</code>```

Body:
I am traversing over an array of numbers (0-9) and want to store there occurrence in hash table with that.

int ar[size]={0,2,0,1,4,6,8 ........ 8,6,7}; // array
auto hash=new int[10];   //here the value is initialized to zero

for(int i=0;i<size;i++)
  {
   //here i want to store the time a number occurred in the array with
   keys as number itself

  hash[ar[i]] = **valueof(hash[ar[i]])+1** // i want to do this
  }

Edit

auto hash=new int[10]();

Body:
You can use following line of code:

hash[ar[i]] += 1


问:
QueryFailedError: the column "price" contain null values - TypeORM - PostgreSQL
I've created a simple table:

```<code>import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Test {
    @PrimaryGeneratedColumn()
    public id!: number

    @Column({ nullable: false })
    public name!: string

    @Column({ nullable: false, type: "float" })
    public price!: number
}
</code>```

I generate the migration and run it also. When I have no data in the database and I run the server it succeed. But when I add 1 row in the database and I run it again it appears the following error:

QueryFailedError: the column «price» contain null values

The databse definetely has the row with all the data. I tried a lot of cases and none of them was correct.

Has anybody some idea for it?

答:
Set "synchronize": false in ormconfig.json will fix this issue:

```<code>{
   ....
   "synchronize": false,
   ....
}
</code>```

Body:
I've created a simple table:

import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"

@Entity()
export class Test {
    @PrimaryGeneratedColumn()
    public id!: number

    @Column({ nullable: false })
    public name!: string

    @Column({ nullable: false, type: "float" })
    public price!: number
}

I generate the migration and run it also. When I have no data in the database and I run the server it succeed. But when I add 1 row in the database and I run it again it appears the following error:

QueryFailedError: the column «price» contain null values

The databse definetely has the row with all the data. I tried a lot of cases and none of them was correct.

Has anybody some idea for it?

Body:
Set "synchronize": false in ormconfig.json will fix this issue:

{
   ....
   "synchronize": false,
   ....
}


问:
Page doesn't update on pagination click in Laravel SPA
I am creating an SPA with Laravel and VUEJS. Everything works well:

- The routing changes accurately from /people to /people?page=2

- The data in the table displays correctly.

But, the problem is, if I click the pagination, the data inside the table doesn't update. The URL is updated /people?page=3 but records are still the same. Here are my codes below.

routes.js

```<code>export default[
{
    path:'/people?page=:page',
    component: ListPeople,
    name: 'people.paginate',
    meta:{
        title: 'Paginate'
    }
},
{
    path: '/people',
    component: ListPeople,
    name: 'people.list',
    meta: {
      title: 'People List',
    }
},
</code>```

ListPeople.vue

I have listed here the table.

```<code><template>
<div class="container">
    <h1>People List</h1>
    <vue-table v-bind="{data:people.data,columns}"></vue-table>

    <vue-pagination  :pagination="people"
                 @paginate="getPeople"
                 :offset="4">
    </vue-pagination>
</div>
</code>```

Paginate.vue

From my pagination, I have something like below:

```<code><template>
  <!-- more codes here -->
<router-link class="page-link" :to="{ name:'people.paginate', params:{ page: page }}">{{ page }}</router-link>
  <!-- more codes here -->
</template>
<script>
 export default{
props: {
  pagination: {
      type: Object,
      required: true
  },
  offset: {
      type: Number,
      default: 4
  }
},
computed: {
  pagesNumber() {
    if (!this.pagination.to) {
      return [];
    }
    let from = this.pagination.current_page - this.offset;
    if (from < 1) {
      from = 1;
    }
    let to = from + (this.offset * 2);
    if (to >= this.pagination.last_page) {
      to = this.pagination.last_page;
    }
    let pagesArray = [];
    for (let page = from; page <= to; page++) {
      pagesArray.push(page);
    }
      return pagesArray;
  }
},
methods : {
  changePage(page) {
    this.pagination.current_page = page;
    this.$emit('paginate',page);
  }
}
 }
</script>
</code>```

答:
You need to add a key to your vue-table component that changes when the pagination changes.

```<code><vue-table v-bind="{data:people.data,columns}" :key="currentPage" ></vue-table>
</code>```

So in your ListPeople component perhaps in your getPeople method update the key as you paginate.

```<code>  data(){
     return:{
        currentPage: 1;
     }
  }
  methods:{
    getPeople(page){
      //.. do something
      this.currentPage = page;
    }
}
</code>```

If you include a key on a child component, when the parent template renders, Vue sets a getter/setter on the key and automatically adds it to the watcher instance of the component.  So when the key changes it automatically rerenders the child component.  Without the key the child component will remain in its cached state.

Body:
I am creating an SPA with Laravel and VUEJS. Everything works well:

- The routing changes accurately from /people to /people?page=2

- The data in the table displays correctly.

But, the problem is, if I click the pagination, the data inside the table doesn't update. The URL is updated /people?page=3 but records are still the same. Here are my codes below.

routes.js

export default[
{
    path:'/people?page=:page',
    component: ListPeople,
    name: 'people.paginate',
    meta:{
        title: 'Paginate'
    }
},
{
    path: '/people',
    component: ListPeople,
    name: 'people.list',
    meta: {
      title: 'People List',
    }
},

ListPeople.vue

I have listed here the table.

<template>

People List

    <vue-table v-bind="{data:people.data,columns}"></vue-table>

    <vue-pagination  :pagination="people"
                 @paginate="getPeople"
                 :offset="4">
    </vue-pagination>

Paginate.vue

From my pagination, I have something like below:

<template>

<router-link class="page-link" :to="{ name:'people.paginate', params:{ page: page }}">{{ page }}</router-link>

</template>

Body:
You need to add a key to your vue-table component that changes when the pagination changes.

<vue-table v-bind="{data:people.data,columns}" :key="currentPage" ></vue-table>

So in your ListPeople component perhaps in your getPeople method update the key as you paginate.

  data(){
     return:{
        currentPage: 1;
     }
  }
  methods:{
    getPeople(page){
      //.. do something
      this.currentPage = page;
    }
}

If you include a key on a child component, when the parent template renders, Vue sets a getter/setter on the key and automatically adds it to the watcher instance of the component.  So when the key changes it automatically rerenders the child component.  Without the key the child component will remain in its cached state.