问:
Bootstrap - ASP.NET Core
I would like to ask how I can stretch the width throughout the modal form.

Here is my code:

```<code><form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">
<div id="myModal2" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Create New Employee</h4>
            </div>

            <div class="modal-body">
                <div class="form-group">
                    <input type="text" class="form-control"/>
                </div>
            </div>

            <div class="modal-footer">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

and it shows like this:

input text problem

Is there any way that I could fix this problem.

I think it has something to do with the bootstrap library but I don't know where it is located.

答:
Try this:

```<code><form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">
<div id="myModal2" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Create New Employee</h4>
            </div>

            <div class="modal-body">
                <div class="form-group">
                  <div class="col-sm-10">
                    <input type="text" class="form-control"/>
                   </div>
                </div>
            </div>

            <div class="modal-footer">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>
</code>```

Working example: https://jsfiddle.net/KyleMit/0fscmf3L/

Credits: Kyle Mitofsky

Title: Bootstrap - ASP.NET Core

Body:
I would like to ask how I can stretch the width throughout the modal form.

Here is my code:

<form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">

                <button type="button" class="close" data-dismiss="modal">×</button>

Create New Employee

                    <input type="text" class="form-control"/>

                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

and it shows like this:

input text problem

Is there any way that I could fix this problem.

I think it has something to do with the bootstrap library but I don't know where it is located.

Body:
Try this:

<form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">
<div id="myModal2" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Create New Employee</h4>
            </div>

            <div class="modal-body">
                <div class="form-group">
                  <div class="col-sm-10">
                    <input type="text" class="form-control"/>
                   </div>
                </div>
            </div>

            <div class="modal-footer">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

Working example: https://jsfiddle.net/KyleMit/0fscmf3L/

Credits: Kyle Mitofsky


来源: stackexchange

问:
Using tomcat Can I check if my HTTP REQUEST is a valid Request to my web services?
Basically the TOMCAT response will be a "Bad Request 400" if I have any mistake in my REQUEST PARAMS, are there any solution to detect that mistake  without writting a test code for the received REQUEST ?

答: JAVA validator is the solution : https://www.leveluplunch.com/java/tutorials/017-validate-spring-rest-webservice-request/</p>

ContentLicense: CC BY-SA 3.0


问:
Trying to understand isolation forest algorithm
I am trying to use isolation forest algorithm with Python scikit-learn.

I do not understand why do I have to generate the sets X_test and X_outliers, because, when I get my data, I have no idea if there are outliers or not in it. But maybe this is just an example and I do not have to generate and fill that sets for every case. I thought that isolation forest does not have to receive a clean X_train (with no outliers).

Did I misunderstand the algorithm? Do I have to use an other algorithm (I thought about one-class SVM but its X_train has to be as clean as possible)?

Does the isolation forest algorithm is an unsupervised algorithm or a supervised one (like the random forest algorithm)?

答:
"Does the isolation forest algorithm is an unsupervised algorithm or a supervised one (like the random forest algorithm)?"

Isolation tree is an unsupervised algorithm and therefore it does not need labels to identify the outlier/anomaly. It follows the following steps:

Random and recursive partition of data is carried out, which is represented as a tree (random forest). This is the training stage where the user defines the parameters of the subsample and the number of trees. The author (Liu and Ting, 2008) suggest the default value of 256 for sub sample and 100 trees. The convergence is reached as the number of tree increases. However, fine tuning may be required on the case basis.

The end of the tree is reached once the recursive partition of data is finished. It is expected that the distance taken to reach the outlier is far less than that for the normal data (see the figure).

The distance of the path is averaged and normalised to calculate the anomaly score. Anomaly score of 1 is considered as an outlier, values close to 0 is considered normal.

The judgment of the outlier is carried out on the basis of the score. There is no need for a label column. Therefore it is an unsupervised algorithm.


问:
com.jcraft.jsch.JSchException: Algorithm negotiation fail + mulesoft
I am executing following mulesoft code for FTP to File transfer.
Got source code from here :
read file from SFTP and dump to local folder using mulesoft

```<code><mule xmlns="http://www.mulesoft.org/schema/mule/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"
  xmlns:file="http://www.mulesoft.org/schema/mule/file"
  xmlns:spring="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
      http://www.mulesoft.org/schema/mule/sftp http://www.mulesoft.org/schema/mule/sftp/current/mule-sftp.xsd
      http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
      http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">

<!-- This placeholder bean lets you import the properties from the sftp.properties file. -->
<spring:bean id="property-placeholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <spring:property name="location" value="classpath:sftp.properties"/>
</spring:bean>

<flow name="sftp2file">
    <sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
                <file:filename-wildcard-filter pattern="*.txt,*.xml"/>
            </sftp:inbound-endpoint>
    <file:outbound-endpoint path="/tmp/incoming" outputPattern="#[message.inboundProperties.originalFilename]"/>
</flow>
</code>```

But I am getting following error :

```<code>    INFO  2017-03-29 18:43:20,877 [main] org.mule.transport.sftp.SftpConnector: Registering listener: sftp2file on endpointUri: sftp://{user}:****@{host}:22/incoming/test
INFO  2017-03-29 18:43:20,940 [main] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'null'. Object is: SftpMessageReceiver
INFO  2017-03-29 18:43:20,942 [main] org.mule.transport.sftp.SftpMessageReceiver: Connecting clusterizable message receiver
ERROR 2017-03-29 18:43:21,965 [main] org.mule.transport.sftp.SftpClient: Error during login to {user}@{host}
com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:583) ~[jsch-0.1.51.jar:?]
    at com.jcraft.jsch.Session.connect(Session.java:320) ~[jsch-0.1.51.jar:?]
    at com.jcraft.jsch.Session.connect(Session.java:183) ~[jsch-0.1.51.jar:?]
    at org.mule.transport.sftp.SftpClient.login(SftpClient.java:147) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnectionFactory.createClient(SftpConnectionFactory.java:116) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnector.createSftpClient(SftpConnector.java:195) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnector.createSftpClient(SftpConnector.java:178) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpReceiverRequesterUtil.getAvailableFiles(SftpReceiverRequesterUtil.java:72) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpMessageReceiver$2.doWork(SftpMessageReceiver.java:291) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.retry.policies.AbstractPolicyTemplate.execute(AbstractPolicyTemplate.java:63) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpMessageReceiver.doConnect(SftpMessageReceiver.java:280) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractMessageReceiver.connectHandler(AbstractMessageReceiver.java:448) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractTransportMessageHandler.connect(AbstractTransportMessageHandler.java:217) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractConnector.registerListener(AbstractConnector.java:1299) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.endpoint.DefaultInboundEndpoint.start(DefaultInboundEndpoint.java:105) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.api.lifecycle.LifecycleUtils.startIfNeeded(LifecycleUtils.java:92) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startMessageSource(DefaultMuleContext.java:381) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startPipelineMessageSources(DefaultMuleContext.java:372) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startMessageSources(DefaultMuleContext.java:335) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.start(DefaultMuleContext.java:320) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.application.DefaultMuleApplication.start(DefaultMuleApplication.java:139) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper$4.execute(ArtifactWrapper.java:105) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper.executeWithinArtifactClassLoader(ArtifactWrapper.java:136) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper.start(ArtifactWrapper.java:100) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:26) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployArtifact(DefaultArchiveDeployer.java:309) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:164) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:253) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:75) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.deployPackedApps(DeploymentDirectoryWatcher.java:278) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.start(DeploymentDirectoryWatcher.java:150) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.MuleDeploymentService.start(MuleDeploymentService.java:134) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.MuleContainer.start(MuleContainer.java:172) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:15) ~[tooling-support-3.8.3.jar:?]
ERROR 2017-03-29 18:43:21,969 [main] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Trying to reconnect to SFTP server sftp://{user}:****@{host}:22/incoming/test. Root Exception was: Error during login to {user}@{host}: Algorithm negotiation fail. Type: class java.io.IOException
ERROR 2017-03-29 18:43:21,971 [main] org.mule.module.launcher.application.DefaultMuleApplication: Failed to start inbound endpoint "endpoint.sftp.{host}.22.incoming.test"
INFO  2017-03-29 18:43:21,978 [main] org.mule.module.launcher.application.DefaultMuleApplication:
</code>```

Is there a way to configure inbound SFTP which will handle SSH issues?

答:
Be aware of SFTP configured to the host, to which your SFTP connector connects, and the access permissions of the directory in which file should be placed.
https://winscp.net/eng/docs/guide_windows_openssh_server</p>

Body:
I am executing following mulesoft code for FTP to File transfer.
Got source code from here :
read file from SFTP and dump to local folder using mulesoft

<mule xmlns="http://www.mulesoft.org/schema/mule/core"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:sftp="http://www.mulesoft.org/schema/mule/sftp"
  xmlns:file="http://www.mulesoft.org/schema/mule/file"
  xmlns:spring="http://www.springframework.org/schema/beans"
  xsi:schemaLocation="
      http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-current.xsd
      http://www.mulesoft.org/schema/mule/sftp http://www.mulesoft.org/schema/mule/sftp/current/mule-sftp.xsd
      http://www.mulesoft.org/schema/mule/file http://www.mulesoft.org/schema/mule/file/current/mule-file.xsd
      http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">

<spring:bean id="property-placeholder" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    <spring:property name="location" value="classpath:sftp.properties"/>
</spring:bean>

<flow name="sftp2file">
    <sftp:inbound-endpoint host="${sftp.host}" port="${sftp.port}" path="/home/test/sftp-files" user="${sftp.user}" password="${sftp.password}">
                <file:filename-wildcard-filter pattern="*.txt,*.xml"/>
            </sftp:inbound-endpoint>
    <file:outbound-endpoint path="/tmp/incoming" outputPattern="#[message.inboundProperties.originalFilename]"/>
</flow>

But I am getting following error :

    INFO  2017-03-29 18:43:20,877 [main] org.mule.transport.sftp.SftpConnector: Registering listener: sftp2file on endpointUri: sftp://{user}:****@{host}:22/incoming/test
INFO  2017-03-29 18:43:20,940 [main] org.mule.lifecycle.AbstractLifecycleManager: Initialising: 'null'. Object is: SftpMessageReceiver
INFO  2017-03-29 18:43:20,942 [main] org.mule.transport.sftp.SftpMessageReceiver: Connecting clusterizable message receiver
ERROR 2017-03-29 18:43:21,965 [main] org.mule.transport.sftp.SftpClient: Error during login to {user}@{host}
com.jcraft.jsch.JSchException: Algorithm negotiation fail
    at com.jcraft.jsch.Session.receive_kexinit(Session.java:583) ~[jsch-0.1.51.jar:?]
    at com.jcraft.jsch.Session.connect(Session.java:320) ~[jsch-0.1.51.jar:?]
    at com.jcraft.jsch.Session.connect(Session.java:183) ~[jsch-0.1.51.jar:?]
    at org.mule.transport.sftp.SftpClient.login(SftpClient.java:147) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnectionFactory.createClient(SftpConnectionFactory.java:116) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnector.createSftpClient(SftpConnector.java:195) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpConnector.createSftpClient(SftpConnector.java:178) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpReceiverRequesterUtil.getAvailableFiles(SftpReceiverRequesterUtil.java:72) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpMessageReceiver$2.doWork(SftpMessageReceiver.java:291) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.retry.policies.AbstractPolicyTemplate.execute(AbstractPolicyTemplate.java:63) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.sftp.SftpMessageReceiver.doConnect(SftpMessageReceiver.java:280) ~[mule-transport-sftp-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractMessageReceiver.connectHandler(AbstractMessageReceiver.java:448) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractTransportMessageHandler.connect(AbstractTransportMessageHandler.java:217) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.transport.AbstractConnector.registerListener(AbstractConnector.java:1299) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.endpoint.DefaultInboundEndpoint.start(DefaultInboundEndpoint.java:105) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.api.lifecycle.LifecycleUtils.startIfNeeded(LifecycleUtils.java:92) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startMessageSource(DefaultMuleContext.java:381) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startPipelineMessageSources(DefaultMuleContext.java:372) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.startMessageSources(DefaultMuleContext.java:335) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.DefaultMuleContext.start(DefaultMuleContext.java:320) ~[mule-core-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.application.DefaultMuleApplication.start(DefaultMuleApplication.java:139) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper$4.execute(ArtifactWrapper.java:105) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper.executeWithinArtifactClassLoader(ArtifactWrapper.java:136) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.artifact.ArtifactWrapper.start(ArtifactWrapper.java:100) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArtifactDeployer.deploy(DefaultArtifactDeployer.java:26) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployArtifact(DefaultArchiveDeployer.java:309) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:164) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:253) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DefaultArchiveDeployer.deployPackagedArtifact(DefaultArchiveDeployer.java:75) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.deployPackedApps(DeploymentDirectoryWatcher.java:278) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.DeploymentDirectoryWatcher.start(DeploymentDirectoryWatcher.java:150) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.MuleDeploymentService.start(MuleDeploymentService.java:134) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.module.launcher.MuleContainer.start(MuleContainer.java:172) ~[mule-module-launcher-3.8.3.jar:3.8.3]
    at org.mule.tooling.server.application.ApplicationDeployer.main(ApplicationDeployer.java:15) ~[tooling-support-3.8.3.jar:?]
ERROR 2017-03-29 18:43:21,969 [main] org.mule.retry.notifiers.ConnectNotifier: Failed to connect/reconnect: Trying to reconnect to SFTP server sftp://{user}:****@{host}:22/incoming/test. Root Exception was: Error during login to {user}@{host}: Algorithm negotiation fail. Type: class java.io.IOException
ERROR 2017-03-29 18:43:21,971 [main] org.mule.module.launcher.application.DefaultMuleApplication: Failed to start inbound endpoint "endpoint.sftp.{host}.22.incoming.test"
INFO  2017-03-29 18:43:21,978 [main] org.mule.module.launcher.application.DefaultMuleApplication:

Is there a way to configure inbound SFTP which will handle SSH issues?


问:
How to associate public Ip Address with an existing domain name
i don t understand how DNS works!

I have an public IP address bouaght from AZURE and Now my website already has a domain name (myWebsite.com) that is tied to my old server.

Now I have bought a new VM in AZURE ( it is a Ubuntu).

Now, how can i change that my domain name (myWebsite.com) to point now to the new Public IP ADDRESS of my VM at azure.

Do i have to do it in the command line or not?
??

答:
You should gave a look at the article that Walter linked to - that covers the full scenario end to end.

I assume that you're using Azure Resource Manager, as you've specifically mentioned the Public IP Address resource. You don't mention if you've configured a DNS name for that Public IP Address, or if it has a static or dynamic IP address. You can find the full details for the Public IP Address resource here:
https://learn.microsoft.com/en-us/rest/api/network/create-or-update-a-public-ip-address

You're going to need to log into the service on which you're hosting myWebsite.com and create a DNS record. What that record is depends on the below:

-if you need users to hit the zone apex and resolve your website (i.e. myWebsite.com), then you need to ensure that the Public IP Address is static, and create an A record to that IP address. This will look like:
myWebsite.com A {The static Public IP Address}

-if users will instead be using a sub-domain (i.e. www.myWebsite.com), then you should add a DNS name to the Public IP Address, and then create a CNAME from the sub-domain that users will hit to that DNS name. This will look like: www.myWebsite.com CNAME {your service ename}.{region}.cloudapp.azure.com

To expand on the reasoning for the above -

Using an A record with a dynamic IP address means that you'd have to update
the DNS record any time the IP changed during which time your website is effectively offline

Creating a CNAME record is not supported for the zone root or apex (i.e. myWebsite.com) as per the RFCs

Please note that there may be a small charge for static Public IP Addresses. See here for more information:
https://azure.microsoft.com/en-us/pricing/

Regards,
Stephen Malone - Azure Networking


问:
Parsing XML in PHP: String could not be parsed as XML
I want to parse XML returned from SOAP service into PHP arra. Here is the sample response:

https://gist.github.com/anonymous/0c83d7d8789f844575e3fd78434a970d

The content of url above is response in the code below:

```<code>    ...
    $client = new \SoapClient($wsUrl);
    $result = $client->__soapCall(
        "GetList",
        [],
        Null,
        $header
    );
    if (is_soap_fault($result)) {
        trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
    } else {
        return $result;
    }
    $sxe = new \SimpleXMLElement($result);
    $sxe->registerXPathNamespace('d', 'urn:schemas-microsoft-com:xml-msdata');
    $result = $sxe->xpath("//NewDataSet");
    ...
</code>```

Getting following error:

```<code>String could not be parsed as XML. SimpleXMLElement::__construct(): Entity: line 1: parser error : Extra content at the end of the document
</code>```

What am I doing wrong?

答:
Here is a re-formatted sample of the code linked in the question (note: it's best to include such an example directly, in case the external link becomes inaccessible).

```<code><xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="rows" msdata:UseCurrentLocale="true">
        <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="rows">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="id" type="xs:int" minOccurs="0"/>
                            <xs:element name="semt" type="xs:string" minOccurs="0"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:choice>
        </xs:complexType>
    </xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <DocumentElement xmlns="">
        <rows diffgr:id="rows1" msdata:rowOrder="0">
            <id>1</id>
            <semt>_</semt>
        </rows>
        <!-- many more "rows" blocks similar to the above -->
    </DocumentElement>
</diffgr:diffgram>
</code>```

Formatted like this, it's clear that there are two different root elements, <xs:schema>...</xs:schema> and <diffgr:diffgram>...</diffgr:diffgram>. A valid XML document must have a single root node, so this is the error the parser is detecting. (The "end of document" as far as it is concerned is "</xs:schema>", so the "extra content" is the entire block starting at "<diffgr:diffgram".)

Looking at the two blocks, it's clear that they are actually intended as two different XML documents: one is a schema (a description of the expected format) and the other is the document itself.

You could handle this in one of two ways:

split the string into two, e.g. by finding the first occurrence of "<diffgr" (this might break if the format of the XML changes slightly).

wrap the string in a fake extra element, e.g. $xml = "<dummy>$response</dummy>, so that the result is a valid XML document

Body:
I want to parse XML returned from SOAP service into PHP arra. Here is the sample response:

https://gist.github.com/anonymous/0c83d7d8789f844575e3fd78434a970d

The content of url above is response in the code below:

    ...
    $client = new \SoapClient($wsUrl);
    $result = $client->__soapCall(
        "GetList",
        [],
        Null,
        $header
    );
    if (is_soap_fault($result)) {
        trigger_error("SOAP Fault: (faultcode: {$result->faultcode}, faultstring: {$result->faultstring})", E_USER_ERROR);
    } else {
        return $result;
    }
    $sxe = new \SimpleXMLElement($result);
    $sxe->registerXPathNamespace('d', 'urn:schemas-microsoft-com:xml-msdata');
    $result = $sxe->xpath("//NewDataSet");
    ...

Getting following error:

String could not be parsed as XML. SimpleXMLElement::__construct(): Entity: line 1: parser error : Extra content at the end of the document

What am I doing wrong?

Body:
Here is a re-formatted sample of the code linked in the question (note: it's best to include such an example directly, in case the external link becomes inaccessible).

<xs:schema xmlns="" xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" id="NewDataSet">
    <xs:element name="NewDataSet" msdata:IsDataSet="true" msdata:MainDataTable="rows" msdata:UseCurrentLocale="true">
        <xs:complexType>
            <xs:choice minOccurs="0" maxOccurs="unbounded">
                <xs:element name="rows">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="id" type="xs:int" minOccurs="0"/>
                            <xs:element name="semt" type="xs:string" minOccurs="0"/>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:choice>
        </xs:complexType>
    </xs:element>
</xs:schema>
<diffgr:diffgram xmlns:msdata="urn:schemas-microsoft-com:xml-msdata" xmlns:diffgr="urn:schemas-microsoft-com:xml-diffgram-v1">
    <DocumentElement xmlns="">
        <rows diffgr:id="rows1" msdata:rowOrder="0">
            <id>1</id>
            <semt>_</semt>
        </rows>
        <!-- many more "rows" blocks similar to the above -->
    </DocumentElement>
</diffgr:diffgram>

Formatted like this, it's clear that there are two different root elements, <xs:schema>...</xs:schema> and <diffgr:diffgram>...</diffgr:diffgram>. A valid XML document must have a single root node, so this is the error the parser is detecting. (The "end of document" as far as it is concerned is "</xs:schema>", so the "extra content" is the entire block starting at "<diffgr:diffgram".)

Looking at the two blocks, it's clear that they are actually intended as two different XML documents: one is a schema (a description of the expected format) and the other is the document itself.

You could handle this in one of two ways:

split the string into two, e.g. by finding the first occurrence of "<diffgr" (this might break if the format of the XML changes slightly).

wrap the string in a fake extra element, e.g. $xml = "<dummy>$response</dummy>, so that the result is a valid XML document


问:
SQL Advice - selecting based upon column in another table
I'm having a bit of headache with some SQL I'm trying to write. Basically, there's 2 tables that have the following fields (only relevant ones to SQL displayed):

Invoices

```<code> accno (fk, linked to id on accounts)
</code>```

Accounts

```<code> id (pk)
 allocateduser
</code>```

Basically, my SQL needs to return all invoices for which account has their current logged in name as the AllocatedUser, which is stored in a Session. Is this simple to do?

Thanks

答:
You can use semi-join:

```<code>SELECT *
  FROM invoice
 WHERE EXISTS(

SELECT 1
  FROM accounts
 WHERE allocateduser = @allocateduser_value
   AND pk = fk)
</code>```

@allocateduser_value is parameter you pass from your session. Beware on case of string, so John is not john ;-)

ContentLicense: CC BY-SA 2.5

Body:
I'm having a bit of headache with some SQL I'm trying to write. Basically, there's 2 tables that have the following fields (only relevant ones to SQL displayed):

Invoices

 accno (fk, linked to id on accounts)

Accounts

 id (pk)
 allocateduser

Basically, my SQL needs to return all invoices for which account has their current logged in name as the AllocatedUser, which is stored in a Session. Is this simple to do?

Thanks

Body:
You can use semi-join:

SELECT *
  FROM invoice
 WHERE EXISTS(

SELECT 1
  FROM accounts
 WHERE allocateduser = @allocateduser_value
   AND pk = fk)

@allocateduser_value is parameter you pass from your session. Beware on case of string, so John is not john ;-)


问:
How to get rid of transparent background usign OpenCV 3 and Python 2.7?
I'm trying to remove the transparent background (the excess whitespace which is not visible here) from the last image. It looks like this:

The code which I'm using is as follows:

```<code>import cv2
import numpy as np
import os
from matplotlib import pyplot as plt

##Change directory to desktop
os.chdir("/home/meh/Desktop/")

##Reading the image
img_gray_scale = cv2.imread('img2.jpg',0)
img_colored = cv2.imread('img2.jpg',1)

###CONTOURS FOR IMAGE SEGMENTAITON####
##Gray scale image must be used
ret, thresh =     cv2.threshold(img_gray_scale,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =     cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

####Extracting just the ROI
###First argument img is the source of image
###Second is the countours which should be passed as python list
###Third is index of contours (to draw all contours pass -1)
####remaining are color and thickness
mask2 = cv2.drawContours(thresh, contours, 0, (255,0,0), -1)

masked_data = cv2.bitwise_and(img_gray_scale,img_gray_scale, mask = mask2)

b,g,r = cv2.split(img_colored)
rgba = [b,g,r, thresh]
dst = cv2.merge(rgba,4)

cv2.imwrite('phone_original_without_background.png',dst)

dst = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
cv2.imwrite('phone_grayscale_without_background.png',dst)
</code>```

My question is, how do I remove the transparent background and just keep the phone's image?

答:
I tried your code and it seems to do nothing. Assuming that you want to crop out all the outer color pixels, here's my solution

Get all point of interest:

```<code>height,width = img_gray_scale.shape

fg = []

for col in range(width):
    for row in range(height):
        if thresh[row][col] < 255:
            fg.append((col,row))
</code>```

Get the minimal rectangle:

```<code>rotatedRect = cv2.minAreaRect(np.array(fg))
</code>```

Use warpAffine to crop out the region of interest:

```<code>def subimage2(image, rotatedRect):
    center, rotatedRect, angle = rotatedRect
    width,height = int(shape[0]),int(shape[1])

    # convert angle to radian and build affine transformation mat
    theta = angle * np.pi/180
    cosine,sine = np.cos(theta), np.sin(theta)
    mapping = np.array([[cosine, sine, -center[0]+width/2],
                        [-sine, cosine, -center[1]+height/2]])

    # write output
    return cv2.warpAffine(image,mapping,(width,height))

cropped = subimage2(dst,rotatedRect)
</code>```

And here's what we get

Body:
I'm trying to remove the transparent background (the excess whitespace which is not visible here) from the last image. It looks like this:

The code which I'm using is as follows:

import cv2
import numpy as np
import os
from matplotlib import pyplot as plt

##Change directory to desktop
os.chdir("/home/meh/Desktop/")

##Reading the image
img_gray_scale = cv2.imread('img2.jpg',0)
img_colored = cv2.imread('img2.jpg',1)

###CONTOURS FOR IMAGE SEGMENTAITON####
##Gray scale image must be used
ret, thresh =     cv2.threshold(img_gray_scale,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
im2, contours, hierarchy =     cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

####Extracting just the ROI
###First argument img is the source of image
###Second is the countours which should be passed as python list
###Third is index of contours (to draw all contours pass -1)
####remaining are color and thickness
mask2 = cv2.drawContours(thresh, contours, 0, (255,0,0), -1)

masked_data = cv2.bitwise_and(img_gray_scale,img_gray_scale, mask = mask2)

b,g,r = cv2.split(img_colored)
rgba = [b,g,r, thresh]
dst = cv2.merge(rgba,4)

cv2.imwrite('phone_original_without_background.png',dst)

dst = cv2.cvtColor(dst,cv2.COLOR_BGR2GRAY)
cv2.imwrite('phone_grayscale_without_background.png',dst)

My question is, how do I remove the transparent background and just keep the phone's image?

Body:
I tried your code and it seems to do nothing. Assuming that you want to crop out all the outer color pixels, here's my solution

Get all point of interest:

height,width = img_gray_scale.shape

fg = []

for col in range(width):
    for row in range(height):
        if thresh[row][col] < 255:
            fg.append((col,row))

Get the minimal rectangle:

rotatedRect = cv2.minAreaRect(np.array(fg))

Use warpAffine to crop out the region of interest:

def subimage2(image, rotatedRect):
    center, rotatedRect, angle = rotatedRect
    width,height = int(shape[0]),int(shape[1])

    # convert angle to radian and build affine transformation mat
    theta = angle * np.pi/180
    cosine,sine = np.cos(theta), np.sin(theta)
    mapping = np.array([[cosine, sine, -center[0]+width/2],
                        [-sine, cosine, -center[1]+height/2]])

    # write output
    return cv2.warpAffine(image,mapping,(width,height))

cropped = subimage2(dst,rotatedRect)

And here's what we get


问:
plot corner of ternary plot only
I am trying to plot just the corner of a ternary plot (where all my data reside) but cannot seem to figure it out using the scale_"X"_continuous(limits=c(0,20)) , with "X" being set to T, L and R respectively.

dropbox link to dummy data set

Here's what the figure I'm making looks like.  I'd like to plot that smallest triangle, if possible.  I assume I'd incorrectly defining the limits, because I recieve an error stating "Error: Invalid Ternary Limits, Each Point Must Sum to Unity..."

答:
The scale_X_continous() limits arguments seems to need values < 1 to work. This does what you want:

```<code> ggtern(data=dummy,aes(x=x,y=y,z=z,col=type)) +
 geom_point() +
 scale_T_continuous(limits=c(0,.2))+
 scale_L_continuous(limits=c(0,.2))+
 scale_R_continuous(limits=c(0.8,1))
</code>```

Title: plot corner of ternary plot only

Body:
The scale_X_continous() limits arguments seems to need values < 1 to work. This does what you want:

 ggtern(data=dummy,aes(x=x,y=y,z=z,col=type)) +
 geom_point() +
 scale_T_continuous(limits=c(0,.2))+
 scale_L_continuous(limits=c(0,.2))+
 scale_R_continuous(limits=c(0.8,1))


问:
Translate Python function to apply mask to image into Java
I'm trying to translate the following Python function, that applies a mask to an image, into Java:

# Applies an image mask.
def region_of_interest(img, vertices):
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image
```

<p>So far, this is what I've got:</p>

```public static opencv_core.Mat applyMask(opencv_core.Mat image, opencv_core.MatVector vertices) {
  opencv_core.Mat mask = opencv_core.Mat.zeros(image.size(), opencv_core.CV_8U).asMat();

  opencv_core.Scalar color = new opencv_core.Scalar(image.channels()); // 3
  double[] colors = new double[] {
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0};
  color.put(colors, 0, colors.length);

  opencv_imgproc.fillPoly(mask, vertices, color);

  opencv_core.Mat dst = new opencv_core.Mat();
  opencv_core.bitwise_and(image, mask, dst);
  return dst;
}
```

<p>But, it isn't working. When I try invoking this method like in the following example:</p>

```opencv_core.MatVector points = new opencv_core.MatVector(
  new opencv_core.Mat(2, 3, opencv_core.CV_32F, new IntPointer(1, 2, 3, 4, 5, 6))
);

opencv_core.MatVector vertices = new opencv_core.MatVector(points);
opencv_core.Mat masked = LaneManager.applyMask(src, vertices);
```

<p>(I'm assuming this is the right way to build a 2x3 matrix of three points with two coordinates each <code>(1,2)</code>, <code>(3, 4)</code> and <code>(5,6)</code>)</p>

<p>I get an exception:</p>

```java.lang.RuntimeException: std::bad_alloc
at org.bytedeco.javacpp.opencv_imgproc.fillPoly(Native Method)
```

I'm using OpenCV as provided by org.bytedeco.javacpp-presets:opencv-platform:3.2.0-1.3 via Maven Central.

I must admit that I'm at a loss here: What's the idiomatic Java way of doing the same thing as the Python function above?

答:
Maybe some whiz has the complete answers. Here is food for thought:

The Java API is a direct copy of the CPP API: http://opencv.org/opencv-java-api.html

The error std::bad_alloc occurs when you fail to allocate required storage space. (http://answers.opencv.org/question/28959/cascade-training-killed-and-bad_alloc/)

There are two CPP methods:

C++: void fillPoly(Mat& img, const Point** pts, const int* npts, int ncontours, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() ), and

C++: void fillPoly(InputOutputArray img, InputArrayOfArrays pts, const Scalar& color, int lineType=LINE_8, int shift=0, Point offset=Point() )

You don't need to convert from Mat to InputArray, but you can (and should) just pass a Mat object where an InputArray is requested (https://stackoverflow.com/a/32976883/1587329)

Body:
I'm trying to translate the following Python function, that applies a mask to an image, into Java:

# Applies an image mask.
def region_of_interest(img, vertices):
    #defining a blank mask to start with
    mask = np.zeros_like(img)

    #defining a 3 channel or 1 channel color to fill the mask with depending on the input image
    if len(img.shape) > 2:
        channel_count = img.shape[2]  # i.e. 3 or 4 depending on your image
        ignore_mask_color = (255,) * channel_count
    else:
        ignore_mask_color = 255

    #filling pixels inside the polygon defined by "vertices" with the fill color
    cv2.fillPoly(mask, vertices, ignore_mask_color)

    #returning the image only where mask pixels are nonzero
    masked_image = cv2.bitwise_and(img, mask)
    return masked_image

So far, this is what I've got:

public static opencv_core.Mat applyMask(opencv_core.Mat image, opencv_core.MatVector vertices) {
  opencv_core.Mat mask = opencv_core.Mat.zeros(image.size(), opencv_core.CV_8U).asMat();

  opencv_core.Scalar color = new opencv_core.Scalar(image.channels()); // 3
  double[] colors = new double[] {
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0,
    255.0, 255.0, 255.0, 255.0};
  color.put(colors, 0, colors.length);

  opencv_imgproc.fillPoly(mask, vertices, color);

  opencv_core.Mat dst = new opencv_core.Mat();
  opencv_core.bitwise_and(image, mask, dst);
  return dst;
}

But, it isn't working. When I try invoking this method like in the following example:

opencv_core.MatVector points = new opencv_core.MatVector(
  new opencv_core.Mat(2, 3, opencv_core.CV_32F, new IntPointer(1, 2, 3, 4, 5, 6))
);

opencv_core.MatVector vertices = new opencv_core.MatVector(points);
opencv_core.Mat masked = LaneManager.applyMask(src, vertices);

(I'm assuming this is the right way to build a 2x3 matrix of three points with two coordinates each (1,2), (3, 4) and (5,6))

I get an exception:

java.lang.RuntimeException: std::bad_alloc
at org.bytedeco.javacpp.opencv_imgproc.fillPoly(Native Method)

I'm using OpenCV as provided by org.bytedeco.javacpp-presets:opencv-platform:3.2.0-1.3 via Maven Central.

I must admit that I'm at a loss here: What's the idiomatic Java way of doing the same thing as the Python function above?


Title: How to iterate over columns in a df and compare value with previous column and perform a action in Python

Body:
The operation I am trying to perform is similar to this mysql delete statement :

   DELETE FROM ABCD WHERE val_2001>val_2000*1.5 OR val_2001>val_1999*POW(1.5,2);

And the column_names varies from val_2001 to val_2017.

All the data from the table ABCD is dumped into a csv and loaded into df.

How to iterate over each column and compare with previous column and perform a delete? ( new to python)

The table data sample :

val_2000   val_2001        val_2002            val_2003
100     112.058663384525    119.070787312921    117.033250060214
100     118.300395256917    124.655238202362    128.723125524235
100     109.333236619151    116.785836024946    117.390803371386
100     120.954175930764    126.099776250454    124.491022271481
100     107.776153227575    105.560100052722    108.07490649383
100     151.596517146962    306.608812920781    124.610273175528

Note: there are columns which need not be iterated as well.

The sample output :

val_2000   val_2001        val_2002            val_2003
100     112.058663384525    119.070787312921    117.033250060214
100     118.300395256917    124.655238202362    128.723125524235
100     109.333236619151    116.785836024946    117.390803371386
100     120.954175930764    126.099776250454    124.491022271481
100     107.776153227575    105.560100052722    108.07490649383
100     NULL                   NULL             124.610273175528

EDIT : - Currently trying this way:

    df = pd.read_csv("singleDataFile.csv")
   for values in xrange(2000,2016):
        val2 = values+1
        df['val_'+str(val2)] = df['val_'+str(val2)].where((df['val_'+str(val2)]>df['val_'+str(values)]*1.5) |  (df['val_'+str(val2)]<df['val_'+str(values)]*0.75))

   print(df)

Getting a format error

Body:
This code creates a random DataFrame that fairly closely mimics your DataFrame.  It seems one of the key components of your questions was iterating through multiple columns, which this does (via pandas).

Build DataFrame:

cols = [ 'val_{}'.format(c) for c in range(2000, 2018)]

d = {}
for c in cols:
    d[c] = np.random.rand(10) * 200 + 100

df = pd.DataFrame(d, columns = cols)

Output:

     val_2000    val_2001    val_2002    val_2003    val_2004    val_2005  \
0  138.795742  178.467087  131.461771  151.475698  217.449107  107.680520
1  127.857106  217.484552  248.528498  155.661208  281.914679  211.313490
2  278.366253  137.543827  167.605495  129.869768  272.923010  190.659691
3  221.798435  206.622385  145.636888  236.499951  212.404028  122.954408
4  122.994183  299.793792  171.987895  246.948802  290.938506  127.846811
5  264.400326  203.226235  121.972832  137.858361  161.812761  270.464277
6  156.253907  280.101596  138.100352  164.018757  121.044386  297.869079
7  186.572007  146.406624  110.309996  270.895300  101.975819  229.314098
8  195.470896  286.125937  251.778581  259.112738  207.539354  127.895095
9  168.135585  261.295740  203.234246  279.825177  188.648541  197.145975

Core Code:

df[(df.shift(axis = 1) > df * 1.5) | (df.shift(axis = 1) < df * 0.75)] = 'NULL'

Output:

     val_2000 val_2001    val_2002 val_2003 val_2004 val_2005   \
0  138.795742  178.467  131.461771  151.476     NULL  107.681
1  127.857106     NULL  248.528498  155.661     NULL  211.313
2  278.366253  137.544  167.605495   129.87     NULL   190.66
3  221.798435  206.622  145.636888     NULL  212.404  122.954
4  122.994183     NULL  171.987895     NULL  290.939  127.847
5  264.400326  203.226  121.972832  137.858  161.813     NULL
6  156.253907     NULL  138.100352  164.019  121.044     NULL
7  186.572007  146.407  110.309996     NULL  101.976     NULL
8  195.470896     NULL  251.778581  259.113  207.539  127.895
9  168.135585     NULL  203.234246     NULL  188.649  197.146


问:
Map LDAP specific attribute to Keycloak roles
I have a LDAP connection set up in my Keycloak. I've managed to import the normal LDAP roles into keycloak with a mapper. In our LDAP we have roles also mapped as user attributes, so like cn, sn, c ... we have attributeRoles. Of course these are not really roles from the technical point of view but user attributes(They are used in our application as roles).

What I want to achieve is to map these user attribute roles(attributeRoles) to real roles in keycloak.

Did any of you have this specific problem and managed to solve it somehow?

Any help would be appreciated.

答:
Update the onImportUserFromLDAP in the RoleLDAPStorageMapper with the following code:

```<code>Map<String, Set<String>> attributes = ldapUser.getAttributes();
    for (Map.Entry<String, Set<String>> entry : attributes.entrySet()){
        if(entry.getKey().equals(<ATTRIBUTE>)){
            // Try to import the attribute to Keycloak roles
            importAttributesFunction(user, realm, entry.getValue());
        }
    }
</code>```

and here you have the importAttributesFunction:

```<code>public void importAttributesFunction(UserModel user, RealmModel realm, Set<String> sRoles) {
    for(String sRole: sRoles){
        RoleContainerModel roleContainer = getTargetRoleContainer(realm);
        RoleModel role = roleContainer.getRole(sRole);

        if (role == null) {
            role = roleContainer.addRole(sRole);
        }

        if(!user.hasRole(role)) {
            user.grantRole(role);
        }
    }
}
</code>```

Hope it helps.

Body:
Update the onImportUserFromLDAP in the RoleLDAPStorageMapper with the following code:

Map<String, Set<String>> attributes = ldapUser.getAttributes();
    for (Map.Entry<String, Set<String>> entry : attributes.entrySet()){
        if(entry.getKey().equals(<ATTRIBUTE>)){
            // Try to import the attribute to Keycloak roles
            importAttributesFunction(user, realm, entry.getValue());
        }
    }

and here you have the importAttributesFunction:

public void importAttributesFunction(UserModel user, RealmModel realm, Set<String> sRoles) {
    for(String sRole: sRoles){
        RoleContainerModel roleContainer = getTargetRoleContainer(realm);
        RoleModel role = roleContainer.getRole(sRole);

        if (role == null) {
            role = roleContainer.addRole(sRole);
        }

        if(!user.hasRole(role)) {
            user.grantRole(role);
        }
    }
}

Hope it helps.


问:
SQL Query for Left join and Count of Max Value of Top 5
I have 2 tables as category and task,in category i have 2 fields as catID and catName, and in task i have only 1 field as catID which can be duplicate. what i want is to have a sql query to match the task.catID with category table to get catName, and in return i want to verify the count of that catname in TASK table. i have tried some different queries but can't retrieve the results. queries are as below.

```<code>SELECT categories.catId, categories.catName, MAX(catName)
FROM tasks
    LEFT JOIN categories ON tasks.catId = categories.catId
WHERE tasks.catId = categories.catId
</code>```

2nd query is

```<code>SELECT MAX(catId), count(catid) as countof
from tasks
group by catId
ORDER BY `countof` DESC
LIMIT 5
</code>```

my table is like as

```<code>Category                   task
catID --- catName          catID
1         ABC1              1
2         ABC2              1
3         ABC3              1
4         ABC4              2
5         ABC5              3
6         ABC6              2
7         ABC7              5
8         ABC8              5
</code>```

I WANT TO HAVE THE RESULTS AS BELOW for top 5 count.

```<code>catName  catName Count
ABC1      3
ABC2      2
ABC5      2
</code>```

any help in this regard would be appreciated. kindly help me to get these results.

答:
Your 2nd query is almost there.  This should give you what you want:</p>

```<code>select Category.catName, Count(Category.catName) countof
from Task
join Category on Category.catID = Task.catID
group by Category.catID
order by countof desc limit 5
</code>```

Body:
I have 2 tables as category and task,in category i have 2 fields as catID and catName, and in task i have only 1 field as catID which can be duplicate. what i want is to have a sql query to match the task.catID with category table to get catName, and in return i want to verify the count of that catname in TASK table. i have tried some different queries but can't retrieve the results. queries are as below.

SELECT categories.catId, categories.catName, MAX(catName)
FROM tasks
    LEFT JOIN categories ON tasks.catId = categories.catId
WHERE tasks.catId = categories.catId

2nd query is

SELECT MAX(catId), count(catid) as countof
from tasks
group by catId
ORDER BY `countof` DESC
LIMIT 5

my table is like as

Category                   task
catID --- catName          catID
1         ABC1              1
2         ABC2              1
3         ABC3              1
4         ABC4              2
5         ABC5              3
6         ABC6              2
7         ABC7              5
8         ABC8              5

I WANT TO HAVE THE RESULTS AS BELOW for top 5 count.

catName  catName Count
ABC1      3
ABC2      2
ABC5      2

any help in this regard would be appreciated. kindly help me to get these results.

Body:
Your 2nd query is almost there.  This should give you what you want:

select Category.catName, Count(Category.catName) countof
from Task
join Category on Category.catID = Task.catID
group by Category.catID
order by countof desc limit 5


问:
Excel 2007 simple copy and paste vba not working in excel 2016
I've put together what is an audit workbook which is supposed to copy and paste some hidden cells to a data storage sheet that is hidden the collective data in the hidden sheet is then used for KPI reports.

The problem is that I've put it together in Excel 2007, in which it works perfectly but now it needs to be used in Excel 2016.

I'm running the macro from a button, if the button is pressed  it copies the data and selects the field in the hidden sheet but doesn't paste, no error dialogues either.

When I step  through the code in the vba editor it works fine, but not from the button despite the button being linked to the code. I'm a bit lost or what to do as I don't know how to correct the code.

Here's the code:

```<code>Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Select
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Select
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub
</code>```

答:
I found the issue, where Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect were taking focus away from the sheet it was run from Phone Audit it was more than likely copying E49:T49 from the Data Phone sheet.

See the following code that includes a new line to bring focus back to the Phone Audit sheet.

```<code>Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Sheets("Phone Audit").Activate '***************
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Activate
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Activate
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub
</code>```

Cheers

John

Body:
I've put together what is an audit workbook which is supposed to copy and paste some hidden cells to a data storage sheet that is hidden the collective data in the hidden sheet is then used for KPI reports.

The problem is that I've put it together in Excel 2007, in which it works perfectly but now it needs to be used in Excel 2016.

I'm running the macro from a button, if the button is pressed  it copies the data and selects the field in the hidden sheet but doesn't paste, no error dialogues either.

When I step  through the code in the vba editor it works fine, but not from the button despite the button being linked to the code. I'm a bit lost or what to do as I don't know how to correct the code.

Here's the code:

Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Select
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Select
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub

Body:
I found the issue, where Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect were taking focus away from the sheet it was run from Phone Audit it was more than likely copying E49:T49 from the Data Phone sheet.

See the following code that includes a new line to bring focus back to the Phone Audit sheet.

Sub CopyPhoneAuditToDB()
'
'
' Copy Phone Audit To DB

'
    Application.ScreenUpdating = False
    Sheets("Data Phone").Visible = xlSheetVisible
    Sheets("Data Phone").Unprotect
    Sheets("Phone Audit").Activate '***************
    Range("E49:T49").Select
    Selection.Copy
    Sheets("Data Phone").Activate
    Range("A2").Select
    Cells(Rows.Count, "A").End(xlUp).Offset(1).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    ActiveSheet.Protect
    Sheets("Phone Audit").Activate
    Range("H5:J5").Select
    Sheets("Data Phone").Visible = xlSheetVeryHidden
    ActiveWorkbook.Save
End Sub

Cheers

John


答:
You have to use bootstrap grid system.

#inpt {
width: 100%;
}
.modal-body {
height: 200px;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
button
<div id="myModal2" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">×</button>
                <h4 class="modal-title">Create New Employee</h4>
            </div>

            <div class="modal-body">
                <div  class="form-group col-xs-12">
                    <input id="inpt" type="text" class="form-control"/>
                </div>
            </div>

            <div class="modal-footer">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div></code>```

Title: Bootstrap - ASP.NET Core

Body:
I would like to ask how I can stretch the width throughout the modal form.

Here is my code:

<form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">

                <button type="button" class="close" data-dismiss="modal">×</button>

Create New Employee

                    <input type="text" class="form-control"/>

                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

and it shows like this:

input text problem

Is there any way that I could fix this problem.

I think it has something to do with the bootstrap library but I don't know where it is located.

Body:
You have to use bootstrap grid system.

#inpt {
width: 100%;
}
.modal-body {
height: 200px;}

<form asp-controller="Employee" asp-action="Create" method="post" class="form-inline" role="form">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<a href="" data-toggle="modal" data-target="#myModal2">button</a>
<div id="myModal2" class="modal fade" role="dialog">
    <div class="modal-dialog modal-lg">
        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Create New Employee</h4>
            </div>

            <div class="modal-body">
                <div  class="form-group col-xs-12">
                    <input id="inpt" type="text" class="form-control"/>
                </div>
            </div>

            <div class="modal-footer">
                <input type="hidden" id="Id">
                <button type="submit" class="btn btn-danger"><span class="glyphicon glyphicon-trash" style="vertical-align:middle;margin-top: -5px"></span> Create</button>
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>


问:
Shared preference for Multiuser
In my app , to store data I am using SharedPreferences. I am able to add and retrieve data from SharedPreferences. My problem is when I switched to New user,SharedPreferences are not creating for new user. It is always fetching data from owner not from Newuser. How to create SharedPreferences so it should create both owner and Newuser ?

Thanks

答:
You would have user identifier to differentiate between owner and new user. If not then you have to maintain it.

You can use below single SharedPreferences util class to deal with all. I made it singleton and have used enum it to ensure type-safety.

```<code>
public class SharedPreferencesUtil
{
    public enum KEY
    {
        FIRST_TIME_USER("first_time"),
        REGISTERED_USER("registered"),
        SKIPPED_REGISTRATION("is_skipped_registration"),
        DEVICE_INFO("device_information"),
        DEVICE_LATITUDE("device_latitude"),
        DEVICE_LONGITUDE("device_longitude"),
        ONLINE_APPS("online_apps");

        private final String value;

        KEY(String value)
        {
           this.value = value;
        }

        public String getValue()
        {
            return this.value;
        }
    }

    private static SharedPreferencesUtil sharedPreferencesUtil = null;
    private static SharedPreferences sharedPreferences = null;

    private SharedPreferencesUtil(Context context, String spName)
    {
        sharedPreferences = QCleaner.getInstance().getActivity().getSharedPreferences("mobi_pref", Context.MODE_PRIVATE);
    }

    public static synchronized SharedPreferencesUtil getInstance(Context context, String spName)
    {
        if(sharedPreferencesUtil == null)
        {
            sharedPreferencesUtil = new SharedPreferencesUtil(context, pName);
        }

        return sharedPreferencesUtil;
    }

    public boolean hasKey(KEY key)
    {
        boolean isKeyExist = false;

        /*if(sharedPreferences.contains(key.getValue()) && !TextUtils.isEmpty(sharedPreferences.getString(key.getValue(), "")))
        {
            isKeyExist = true;
        }*/

        if(sharedPreferences.contains(key.getValue()))
        {
            isKeyExist = true;
        }

        return isKeyExist;
    }

    public boolean saveString(KEY key, String value)
    {
        return sharedPreferences.edit().putString(key.getValue(), value).commit();
    }

    public boolean saveInt(KEY key, int value)
    {
        return sharedPreferences.edit().putInt(key.getValue(), value).commit();
    }

    public boolean saveBoolean(KEY key, boolean value)
    {
        return sharedPreferences.edit().putBoolean(key.getValue(), value).commit();
    }

    public boolean saveFloat(KEY key, float value)
    {
        return sharedPreferences.edit().putFloat(key.getValue(), value).commit();
    }

    public boolean saveDataLong(KEY key, long value)
    {
        return sharedPreferences.edit().putLong(key.getValue(), value).commit();
    }

    /*public boolean saveDataStringSetInSharedPreference(String key, Set value)
    {
        return sharedPreferences.edit().putStringSet(key, value).commit();
    }*/

    public String getString(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getString(key.getValue(), "");
        }
        else
        {
            return null;
        }
    }

    public boolean getBoolean(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getBoolean(key.getValue(), false);
        }
        else
        {
            return false;
        }
    }

    public float getFloat(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getFloat(key.getValue(), 0.0f);
        }
        else
        {
            return 0.0f;
        }
    }

    public float getLong(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getLong(key.getValue(), 0L);
        }
        else
        {
            return 0L;
        }
    }

    public boolean removeKey(KEY key)
    {
        boolean isDeleted = false;
        if(sharedPreferences.contains(key.getValue()))
        {
            isDeleted = sharedPreferences.edit().remove(key.getValue()).commit();
        }

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

How to use this?

```<code>SharedPreferencesUtil.getInstance(context, your_shared_preference_name).saveString(SharedPreferencesUtil.KEY.ONLINE_APPS, object.toString());
</code>```

If you are using single name shared preference then you can customise it and you would not have to pass context and sharedpreference name each time.

Title: Shared preference for Multiuser

Body:
You would have user identifier to differentiate between owner and new user. If not then you have to maintain it.

You can use below single SharedPreferences util class to deal with all. I made it singleton and have used enum it to ensure type-safety.

public class SharedPreferencesUtil
{
    public enum KEY
    {
        FIRST_TIME_USER("first_time"),
        REGISTERED_USER("registered"),
        SKIPPED_REGISTRATION("is_skipped_registration"),
        DEVICE_INFO("device_information"),
        DEVICE_LATITUDE("device_latitude"),
        DEVICE_LONGITUDE("device_longitude"),
        ONLINE_APPS("online_apps");

        private final String value;

        KEY(String value)
        {
           this.value = value;
        }

        public String getValue()
        {
            return this.value;
        }
    }

    private static SharedPreferencesUtil sharedPreferencesUtil = null;
    private static SharedPreferences sharedPreferences = null;

    private SharedPreferencesUtil(Context context, String spName)
    {
        sharedPreferences = QCleaner.getInstance().getActivity().getSharedPreferences("mobi_pref", Context.MODE_PRIVATE);
    }

    public static synchronized SharedPreferencesUtil getInstance(Context context, String spName)
    {
        if(sharedPreferencesUtil == null)
        {
            sharedPreferencesUtil = new SharedPreferencesUtil(context, pName);
        }

        return sharedPreferencesUtil;
    }

    public boolean hasKey(KEY key)
    {
        boolean isKeyExist = false;

        /*if(sharedPreferences.contains(key.getValue()) && !TextUtils.isEmpty(sharedPreferences.getString(key.getValue(), "")))
        {
            isKeyExist = true;
        }*/

        if(sharedPreferences.contains(key.getValue()))
        {
            isKeyExist = true;
        }

        return isKeyExist;
    }

    public boolean saveString(KEY key, String value)
    {
        return sharedPreferences.edit().putString(key.getValue(), value).commit();
    }

    public boolean saveInt(KEY key, int value)
    {
        return sharedPreferences.edit().putInt(key.getValue(), value).commit();
    }

    public boolean saveBoolean(KEY key, boolean value)
    {
        return sharedPreferences.edit().putBoolean(key.getValue(), value).commit();
    }

    public boolean saveFloat(KEY key, float value)
    {
        return sharedPreferences.edit().putFloat(key.getValue(), value).commit();
    }

    public boolean saveDataLong(KEY key, long value)
    {
        return sharedPreferences.edit().putLong(key.getValue(), value).commit();
    }

    /*public boolean saveDataStringSetInSharedPreference(String key, Set value)
    {
        return sharedPreferences.edit().putStringSet(key, value).commit();
    }*/

    public String getString(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getString(key.getValue(), "");
        }
        else
        {
            return null;
        }
    }

    public boolean getBoolean(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getBoolean(key.getValue(), false);
        }
        else
        {
            return false;
        }
    }

    public float getFloat(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getFloat(key.getValue(), 0.0f);
        }
        else
        {
            return 0.0f;
        }
    }

    public float getLong(KEY key)
    {
        if(sharedPreferences.contains(key.getValue()))
        {
            return sharedPreferences.getLong(key.getValue(), 0L);
        }
        else
        {
            return 0L;
        }
    }

    public boolean removeKey(KEY key)
    {
        boolean isDeleted = false;
        if(sharedPreferences.contains(key.getValue()))
        {
            isDeleted = sharedPreferences.edit().remove(key.getValue()).commit();
        }

        return isDeleted;
    }
}

How to use this?

SharedPreferencesUtil.getInstance(context, your_shared_preference_name).saveString(SharedPreferencesUtil.KEY.ONLINE_APPS, object.toString());

If you are using single name shared preference then you can customise it and you would not have to pass context and sharedpreference name each time.


问:
Hide column field using sql query
How to hide column field using sql query.

My query is:

```<code>Select Name,Email,Mobile from Table_Reg where Email not in('raj@gmail.com')
</code>```

So i am not getting raj@gmail.com user details and output like below.

```<code>Name          Email         Mobile
Mazhar   mazhar@gmail.com   9030349582
</code>```

I need to visible false email Id while in select query and also I want to add where email not in condition compulsory and I dont want to show email detail but email condition should compulsory. Output should like below.

```<code> Name      Mobile
 Mazhar    9030349582
</code>```

答:
I am not sure what you actually need but give a go for below query:</p>

```<code>Select
    Name,
    case when Email in ('raj@gmail.com') then 'not visible'
        else Email
    end as Email,
    Mobile
from Table_Reg
</code>```

Title: Hide column field using sql query

Body:
How to hide column field using sql query.

My query is:

Select Name,Email,Mobile from Table_Reg where Email not in('raj@gmail.com')

So i am not getting raj@gmail.com user details and output like below.

Name          Email         Mobile
Mazhar   mazhar@gmail.com   9030349582

I need to visible false email Id while in select query and also I want to add where email not in condition compulsory and I dont want to show email detail but email condition should compulsory. Output should like below.

 Name      Mobile
 Mazhar    9030349582

Body:
I am not sure what you actually need but give a go for below query:

Select
    Name,
    case when Email in ('raj@gmail.com') then 'not visible'
        else Email
    end as Email,
    Mobile
from Table_Reg


问:
Dalek and Phantomjs not detecting values put by javascript
I am using Dalek to automate test my webpage. The webpage makes a  jQuery ajax API call and gets a JSON object in return. I use an attribute of that object to display data on my webpage.

When I try to run the test, it always fails and shows that no value was detected in that particular div with id name even though the name is being displayed.

Dalek Test:

```<code>test .open('http://localhost:3000/details.html?id=4')
.wait(2000)
.assert.title().is('User Details', 'User Details Displayed')
.assert.text('#username').is('Karianne','')
.done();
</code>```

Result:

What is the reason behind this? Does PhantomJS doesn't execute jQuery?

答:
Try to use a screenshot feature to see what is going on when the page loads:</p>

```<code>.assert.text('#username').is('Karianne','')
.screenshot('/tmp/localhost_3000:datetime.png')
</code>```

Body:
I am using Dalek to automate test my webpage. The webpage makes a  jQuery ajax API call and gets a JSON object in return. I use an attribute of that object to display data on my webpage.

When I try to run the test, it always fails and shows that no value was detected in that particular div with id name even though the name is being displayed.

Dalek Test:

test .open('http://localhost:3000/details.html?id=4')
.wait(2000)
.assert.title().is('User Details', 'User Details Displayed')
.assert.text('#username').is('Karianne','')
.done();

Result:

What is the reason behind this? Does PhantomJS doesn't execute jQuery?

Body:
Try to use a screenshot feature to see what is going on when the page loads:

.assert.text('#username').is('Karianne','')
.screenshot('/tmp/localhost_3000:datetime.png')


问:
Angular2 boolean Input parameter not working
In my Planning component I have the following directive where selectedPerson is an object on the service and showModal is a local boolean parameter in the Planning component:

```<code><person-popup [person]="planningService.selectedPerson" [show]="showModal"></person-popup>
</code>```

The PersonPopop component has the following simple structure:

```<code>import { Component, Input } from '@angular/core';
import { Counselor } from '../entities/counselor';
import { Person } from '../entities/person';
import { Request } from '../entities/request';

@Component({
    selector: 'person-popup',
    templateUrl: './person-popup.component.html',
    styleUrls: ['./person-popup.component.css']
})

export class PersonPopupComponent {

    @Input() person: Person;
    @Input() show: boolean;

    constructor() { }

    public displayCss() {
        return this.show ? "displayBlock" : "";
    }

    public toggleShow() {
        this.show = !this.show;
        console.log("toggleShow: ", this.show)
    }
}
</code>```

The corresponding HTML view currently looks like this:

```<code><p>{{show}}</p>
<p>{{person?.name}}</p>
<button (click)="toggleShow()">Show</button>

<div class="modal-background {{displayCss()}}" (click)="toggleShow()">
    <div class="modal-content animate">
        {{person?.name}}
    </div>
</div>
</code>```

When the Planning component is initiated the show property is null.
Changes of selectedPerson are always propagated to the popup component but the same is NOT true for the showModal parameter.

When showModal is first set to true in the parent it is set to true in the child component.

The child component will then set its local show property to false.
After that it seems "the Input connection is lost" and all subsequent changes of showModal will not propagate to show.

Any suggestions on how to redesign this?

答:
You need to use two way binding if you want to propagate the changes from child to parent :

```<code>export class PersonPopupComponent {

    @Input() person: Person;
    @Input() show: boolean;
    @Ouput() showChange= new EventEmitter<boolean>();

    constructor() { }

    public displayCss() {
        return this.show ? "displayBlock" : "";
    }

    public toggleShow() {
        this.show = !this.show;
        this.showChange.emit(this.show);
        console.log("toggleShow: ", this.show)
    }
}
</code>```

then in parent :

```<code><person-popup [person]="planningService.selectedPerson" [(show)]="showModal"></person-popup>
</code>```

Body:
In my Planning component I have the following directive where selectedPerson is an object on the service and showModal is a local boolean parameter in the Planning component:

<person-popup [person]="planningService.selectedPerson" [show]="showModal"></person-popup>

The PersonPopop component has the following simple structure:

import { Component, Input } from '@angular/core';
import { Counselor } from '../entities/counselor';
import { Person } from '../entities/person';
import { Request } from '../entities/request';

@Component({
    selector: 'person-popup',
    templateUrl: './person-popup.component.html',
    styleUrls: ['./person-popup.component.css']
})

export class PersonPopupComponent {

    @Input() person: Person;
    @Input() show: boolean;

    constructor() { }

    public displayCss() {
        return this.show ? "displayBlock" : "";
    }

    public toggleShow() {
        this.show = !this.show;
        console.log("toggleShow: ", this.show)
    }
}

The corresponding HTML view currently looks like this:

{{show}}

{{person?.name}}

<button (click)="toggleShow()">Show</button>

        {{person?.name}}

When the Planning component is initiated the show property is null.
Changes of selectedPerson are always propagated to the popup component but the same is NOT true for the showModal parameter.

When showModal is first set to true in the parent it is set to true in the child component.

The child component will then set its local show property to false.
After that it seems "the Input connection is lost" and all subsequent changes of showModal will not propagate to show.

Any suggestions on how to redesign this?

Body:
You need to use two way binding if you want to propagate the changes from child to parent :

export class PersonPopupComponent {

    @Input() person: Person;
    @Input() show: boolean;
    @Ouput() showChange= new EventEmitter<boolean>();

    constructor() { }

    public displayCss() {
        return this.show ? "displayBlock" : "";
    }

    public toggleShow() {
        this.show = !this.show;
        this.showChange.emit(this.show);
        console.log("toggleShow: ", this.show)
    }
}

then in parent :

<person-popup [person]="planningService.selectedPerson" [(show)]="showModal"></person-popup>


问:
Click on java element scrapy+selenium
I'm trying to scrape this page: http://www.newyorkerfiction.com/Pieces.aspx with scrapy and selenium. I need to click on the different pages but I cannot find a way. My script is:

```<code>def __init__(self):
    self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
    self.driver.set_window_size(1920, 1080); #Size

def parse(self, response):
    self.driver.get(response.url)
    element = self.driver.find_element(By.XPATH, '//div[@class="rgWrap rgNumPart"]//a[contains(@href, "javascript:__doPostBack")]')
    self.driver.execute_script("arguments[0].click();", element)
    self.driver.save_screenshot('screenshot.png')
    for sel in response.xpath('//body'):
        item = NyfictionItem()
        item["title"] = sel.xpath('//td[@class="title"]').extract()
        yield item
    self.driver.close()
</code>```

I don't understand what's wrong since I understood that execute_script makes selenium to interact with elements in javascript. I tested the xpath and it seems right.

Any ideas?

Thanks

答:
One problem is that your locator points to all the links in the pagination bar and, since you are getting the first one, you are actually trying to click the "1" link, but, instead, you meant to click the "next page" link, which can be located with input.rgPageNext CSS selector.

You, though, need to wait for it to be visible and clickable to make the process more reliable:

```<code>from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
driver.set_window_size(1920, 1080)

driver.get("http://www.newyorkerfiction.com/Pieces.aspx")

wait = WebDriverWait(driver, 10)
next_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.rgPageNext")))
next_link.click()

driver.save_screenshot('screenshot.png')

driver.close()
</code>```

Note that you might though need an another wait after clicking the "next page" link to let the new page results be loaded.

And, you would also need some additional logic to stop at the last page.

Title: Click on java element scrapy+selenium

Body:
I'm trying to scrape this page: http://www.newyorkerfiction.com/Pieces.aspx with scrapy and selenium. I need to click on the different pages but I cannot find a way. My script is:

def __init__(self):
    self.driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
    self.driver.set_window_size(1920, 1080); #Size

def parse(self, response):
    self.driver.get(response.url)
    element = self.driver.find_element(By.XPATH, '//div[@class="rgWrap rgNumPart"]//a[contains(@href, "javascript:__doPostBack")]')
    self.driver.execute_script("arguments[0].click();", element)
    self.driver.save_screenshot('screenshot.png')
    for sel in response.xpath('//body'):
        item = NyfictionItem()
        item["title"] = sel.xpath('//td[@class="title"]').extract()
        yield item
    self.driver.close()

I don't understand what's wrong since I understood that execute_script makes selenium to interact with elements in javascript. I tested the xpath and it seems right.

Any ideas?

Thanks

Body:
One problem is that your locator points to all the links in the pagination bar and, since you are getting the first one, you are actually trying to click the "1" link, but, instead, you meant to click the "next page" link, which can be located with input.rgPageNext CSS selector.

You, though, need to wait for it to be visible and clickable to make the process more reliable:

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

driver = webdriver.PhantomJS(executable_path='/usr/local/bin/phantomjs')
driver.set_window_size(1920, 1080)

driver.get("http://www.newyorkerfiction.com/Pieces.aspx")

wait = WebDriverWait(driver, 10)
next_link = wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input.rgPageNext")))
next_link.click()

driver.save_screenshot('screenshot.png')

driver.close()

Note that you might though need an another wait after clicking the "next page" link to let the new page results be loaded.

And, you would also need some additional logic to stop at the last page.


问:
Hive query to quickly find table size (number of rows)
Is there a Hive query to quickly find table size (i.e. number of rows) without launching a time-consuming MapReduce job? (Which is why I want to avoid COUNT(*).)

I tried DESCRIBE EXTENDED, but that yielded numRows=0 which is obviously not correct.

(Apologies for the newb question. I tried Googling and searching the apache.org documentation without success.)

答:
How about using :</p>

```<code>    hdfs dfs -du -s -h /path/to/table/name
</code>```

Body:
How about using :

    hdfs dfs -du -s -h /path/to/table/name


问:
Usng same Label Encoder to test dataset? or new Label Encoder?
I'm totally novice on scikit-learn.

I want to know whether I should use the same Label Encoder instance that had used on training dataset or not when I want to convert the same feature's categorical data on test dataset. And, it means like below

```<code>from sklearn import preprocessing

# trainig data label encoding
le_blood_type = preprocessing.LabelEncoder()
df_training[ 'BLOOD_TYPE' ] = le_blood_type.fit_transform( df_training[ 'BLOOD_TYPE' ] )    # labeling from string
....
1. Using same label encoder
   df_test[ 'BLOOD_TYPE' ] = le_blood_type.fit_transform( df_test[ 'BLOOD_TYPE' ] )

2. Using different label encoder
   le_for_test_blood_type = preprocessing.LabelEncoder()
   df_test[ 'BLOOD_TYPE' ] = le_for_test_blood_type.fit_transform( df_test[ 'BLOOD_TYPE' ] )
</code>```

Which one is right code?
Or, whatever I choose the above's code it does not make any differences
because training dataset's categorical data and test dataset's categorical data should be the same as a result.

答:
I think RPresle has already gave the answer. Just wanted to put it a little more direct to the situation in the question: </p>

<p>In general, you just need to fit LabelEncoder (with feature in training set) once and transforms the feature in testing set. But if your testing set has feature values that are not in training set, when you fit the label encoder put union of set of training feature and of testing set in it. </p>

Body:
I'm totally novice on scikit-learn.

I want to know whether I should use the same Label Encoder instance that had used on training dataset or not when I want to convert the same feature's categorical data on test dataset. And, it means like below

from sklearn import preprocessing

# trainig data label encoding
le_blood_type = preprocessing.LabelEncoder()
df_training[ 'BLOOD_TYPE' ] = le_blood_type.fit_transform( df_training[ 'BLOOD_TYPE' ] )    # labeling from string
....
1. Using same label encoder
   df_test[ 'BLOOD_TYPE' ] = le_blood_type.fit_transform( df_test[ 'BLOOD_TYPE' ] )

2. Using different label encoder
   le_for_test_blood_type = preprocessing.LabelEncoder()
   df_test[ 'BLOOD_TYPE' ] = le_for_test_blood_type.fit_transform( df_test[ 'BLOOD_TYPE' ] )

Which one is right code?
Or, whatever I choose the above's code it does not make any differences
because training dataset's categorical data and test dataset's categorical data should be the same as a result.

Body:
I think RPresle has already gave the answer. Just wanted to put it a little more direct to the situation in the question:

In general, you just need to fit LabelEncoder (with feature in training set) once and transforms the feature in testing set. But if your testing set has feature values that are not in training set, when you fit the label encoder put union of set of training feature and of testing set in it.


问:
TinyTds::Error Exception: Read from the server failed (serverName)
Using Windows 7, Ruby version 2.2.4, tiny_tds version 1.0.0, and the targeted sql server runs in SQL Server 2012.

Code:

require 'tiny_tds'

```<code>client = TinyTds::Client.new dataserver:'serverName', database: 'databaseName'
</code>```

Just an fyi, I am providing my actual serverName and databaseName in my actual code.

Running this gives the error "TinyTds::Error Exception: Read from the server failed (serverName)"

Has anyone had this issue and was able to fix it? I am assuming some issue caused by version updates of ruby and/or tiny_tds, since it was working few months back... but I am running out of ideas.
My apologies ahead of time if some other pertinent info is left out of this question. I would be more than happy to provide any extra info as needed.

Thank you

答:
You should provide all parameters for tiny_tds client depend on git doc, see the below:</p>

```<code>client = TinyTds::Client.new username: 'sa', password: 'secret', host: 'mydb.host.net'
</code>```

Body:
Using Windows 7, Ruby version 2.2.4, tiny_tds version 1.0.0, and the targeted sql server runs in SQL Server 2012.

Code:

require 'tiny_tds'

client = TinyTds::Client.new dataserver:'serverName', database: 'databaseName'

Just an fyi, I am providing my actual serverName and databaseName in my actual code.

Running this gives the error "TinyTds::Error Exception: Read from the server failed (serverName)"

Has anyone had this issue and was able to fix it? I am assuming some issue caused by version updates of ruby and/or tiny_tds, since it was working few months back... but I am running out of ideas.
My apologies ahead of time if some other pertinent info is left out of this question. I would be more than happy to provide any extra info as needed.

Thank you

Body:
You should provide all parameters for tiny_tds client depend on git doc, see the below:

client = TinyTds::Client.new username: 'sa', password: 'secret', host: 'mydb.host.net'


问:
casting functions into function pointers in a c programme
I am trying to understand a software for a Tire Pressure Monitoring System but I know little about C language.
In one of the header files there is these kind of definitions :

```<code>#define TPMS_RESET         gu16AddressToFn = u16fnDALLinkFmw(gu8Derivative, FN_RESET);\
                       ((void(*)(void))(gu16AddressToFn))

/* UINT8 TPMS_READ_VOLTAGE(UINT16 *u16UUMA) */
#define  TPMS_READ_VOLTAGE  ((UINT8(*)(UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_READ_VOLT)))

/* UINT8 TPMS_COMP_VOLTAGE(UINT8 *u8CompVoltage, *UINT16 u16UUMA) */
#define  TPMS_COMP_VOLTAGE  ((UINT8(*)(UINT8*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_V)))

/* UINT8 TPMS_READ_TEMPERATURE(UINT16 *u16UUMA) */
#define  TPMS_READ_TEMPERATURE  ((UINT8(*)(UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_READ_T)))

/* UINT8 TPMS_COMP_TEMPERATURE(UINT8 *u8Temp, UINT16 *u16UUMA) */
#define  TPMS_COMP_TEMPERATURE   ((UINT8(*)(UINT8*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_T)))

/* UINT8 TPMS_READ_PRESSURE(UINT16 *u16UUMA, UINT8 u8Avg) */
#define  TPMS_READ_PRESSURE    ((UINT8(*)(UINT16*, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_P)))

/* UINT8 TPMS_COMP_PRESSURE(UINT16 *u16CompPressure, UINT16 *u16UUMA) */
#define  TPMS_COMP_PRESSURE    ((UINT8(*)(UINT16*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_P)))

/* UINT8 TPMS_READ_ACCEL_X(UINT16 *u16UUMA, UINT8 u8Avg, UINT8 u8FiltSelect, UINT8 u8DynamicOffset) */
#define  TPMS_READ_ACCEL_X  ((UINT8(*)(UINT16*, UINT8, UINT8, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_X)))

/* UINT8 TPMS_READ_ACCEL_Z(UINT16 *u16UUMA, UINT8 u8Avg, UINT8 u8FiltSelect, UINT8 u8DynamicOffset) */
#define  TPMS_READ_ACCEL_Z ((UINT8(*)(UINT16*, UINT8, UINT8, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_Z)))
</code>```

I don´t really understand this trick of casting into other functions. Have you got any idea?

答:
The macros you present are all ultimately defined in terms of a function (likely) or perhaps another macro (unlikely), u16fnDALLinkFmw().  I'll suppose it is a function.  You haven't quite understood what is going on here, however: the code in the macros' replacement texts are not casting that function; rather, they are casting its return value.

What seems to be going on here, therefore, is a variation on dynamic dispatch.  The macros provide for looking up each desired function in a specified table, by offset / id, and since the looked-up functions for different IDs may have different signatures, the macros cast the returned function pointer to the correct-signature function pointer type.

You would use these something like this:

```<code>uint16_t argument = 1;
uint8_t  result = TPMS_READ_VOLTAGE(&argument);
</code>```

Body:
I am trying to understand a software for a Tire Pressure Monitoring System but I know little about C language.
In one of the header files there is these kind of definitions :

#define TPMS_RESET         gu16AddressToFn = u16fnDALLinkFmw(gu8Derivative, FN_RESET);\
                       ((void(*)(void))(gu16AddressToFn))

/* UINT8 TPMS_READ_VOLTAGE(UINT16 *u16UUMA) */
#define  TPMS_READ_VOLTAGE  ((UINT8(*)(UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_READ_VOLT)))

/* UINT8 TPMS_COMP_VOLTAGE(UINT8 *u8CompVoltage, *UINT16 u16UUMA) */
#define  TPMS_COMP_VOLTAGE  ((UINT8(*)(UINT8*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_V)))

/* UINT8 TPMS_READ_TEMPERATURE(UINT16 *u16UUMA) */
#define  TPMS_READ_TEMPERATURE  ((UINT8(*)(UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_READ_T)))

/* UINT8 TPMS_COMP_TEMPERATURE(UINT8 *u8Temp, UINT16 *u16UUMA) */
#define  TPMS_COMP_TEMPERATURE   ((UINT8(*)(UINT8*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_T)))

/* UINT8 TPMS_READ_PRESSURE(UINT16 *u16UUMA, UINT8 u8Avg) */
#define  TPMS_READ_PRESSURE    ((UINT8(*)(UINT16*, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_P)))

/* UINT8 TPMS_COMP_PRESSURE(UINT16 *u16CompPressure, UINT16 *u16UUMA) */
#define  TPMS_COMP_PRESSURE    ((UINT8(*)(UINT16*, UINT16*))(u16fnDALLinkFmw(gu8Derivative, FN_COMP_P)))

/* UINT8 TPMS_READ_ACCEL_X(UINT16 *u16UUMA, UINT8 u8Avg, UINT8 u8FiltSelect, UINT8 u8DynamicOffset) */
#define  TPMS_READ_ACCEL_X  ((UINT8(*)(UINT16*, UINT8, UINT8, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_X)))

/* UINT8 TPMS_READ_ACCEL_Z(UINT16 *u16UUMA, UINT8 u8Avg, UINT8 u8FiltSelect, UINT8 u8DynamicOffset) */
#define  TPMS_READ_ACCEL_Z ((UINT8(*)(UINT16*, UINT8, UINT8, UINT8))(u16fnDALLinkFmw(gu8Derivative, FN_READ_Z)))

I don´t really understand this trick of casting into other functions. Have you got any idea?

Body:
The macros you present are all ultimately defined in terms of a function (likely) or perhaps another macro (unlikely), u16fnDALLinkFmw().  I'll suppose it is a function.  You haven't quite understood what is going on here, however: the code in the macros' replacement texts are not casting that function; rather, they are casting its return value.

What seems to be going on here, therefore, is a variation on dynamic dispatch.  The macros provide for looking up each desired function in a specified table, by offset / id, and since the looked-up functions for different IDs may have different signatures, the macros cast the returned function pointer to the correct-signature function pointer type.

You would use these something like this:

uint16_t argument = 1;
uint8_t  result = TPMS_READ_VOLTAGE(&argument);


问:
SQL BACKUP Query
how can i backup data from a query with MSSQL. I think about something like this:

```<code>BACKUP DATABASE 'sourceDB'
Select * from Table1 where Day = '12.01.2010';
TO DISK = 'F:\Program Files\Microsoft SQL Server\MSSQL\Backup\sourceDB.bak' WITH FORMAT
</code>```

Thank you for your support!

Cheers

Stefan

答:
The backup command is used to backup entire databases into a proprietary format.

To store the result of a query in a file, check out the bcp utility.  This allows you to run a query and store the result in a text file.  One example:

```<code>bcp "SELECT * FROM Northwind.dbo.Customers" queryout "c:\text.txt" -c -T -x
</code>```

Title: SQL BACKUP Query

Body:
how can i backup data from a query with MSSQL. I think about something like this:

BACKUP DATABASE 'sourceDB'
Select * from Table1 where Day = '12.01.2010';
TO DISK = 'F:\Program Files\Microsoft SQL Server\MSSQL\Backup\sourceDB.bak' WITH FORMAT

Thank you for your support!

Cheers

Stefan

Body:
The backup command is used to backup entire databases into a proprietary format.

To store the result of a query in a file, check out the bcp utility.  This allows you to run a query and store the result in a text file.  One example:

bcp "SELECT * FROM Northwind.dbo.Customers" queryout "c:\text.txt" -c -T -x


问:
How to re-index single product programmatically?
How to so index of single product?
I have tried below code but it's not working.

Mage::getSingleton('index/indexer')->processEntityAction( $product, Mage_Catalog_Model_Product::ENTITY, Mage_Index_Model_Event::TYPE_SAVE )

is there any other solution?

答:
You can do product indexing by their attribute like this:

```<code>$indexer = Mage::getSingleton('index/indexer')->processEntityAction($_product, 'catalog_url', Mage_Index_Model_Event::TYPE_SAVE);
</code>```

Hope, it works for you.

ContentLicense: CC BY-SA 4.0

Body:
You can do product indexing by their attribute like this:

$indexer = Mage::getSingleton('index/indexer')->processEntityAction($_product, 'catalog_url', Mage_Index_Model_Event::TYPE_SAVE);

Hope, it works for you.


问:
javascript variable in foreach loop
I try to have a parallax effect for my sections the speed of the parallax are given in the html with data-Lon1 like this

I get back the data-Lon1 and use it in my parallax function for having diferent speed for the sections

```<code>(function(){

  var parallax = document.querySelectorAll(".parallax"),

  window.onscroll = function(){
    [].slice.call(parallax).forEach(function(el,i){
     speed = parseFloat($(el).attr('data-lon1'));
      var windowYOffset = window.pageYOffset,
          elBackgrounPos = "0 " + (windowYOffset * speed) + "px";

      el.style.backgroundPosition = elBackgrounPos;

    });
  };

})();
</code>```

The sections aren't getting the speed value but if I given a speed value by default it works. How could I get each data-Lon1 section value and have three different speed ?

答:
This is always going to return the same value:

```<code>parseFloat($('.parallax').attr('data-lon1'))
</code>```

Because you're selecting all matching .parallax elements and trying to get one value from all of them, which is likely always going to default to the first in the set.

You probably want to get the value for the specific element being used in that iteration of the loop:

```<code>parseFloat($(el).attr('data-lon1'))
</code>```

Title: javascript variable in foreach loop

Body:
I try to have a parallax effect for my sections the speed of the parallax are given in the html with data-Lon1 like this

I get back the data-Lon1 and use it in my parallax function for having diferent speed for the sections

(function(){

  var parallax = document.querySelectorAll(".parallax"),

  window.onscroll = function(){
    [].slice.call(parallax).forEach(function(el,i){
     speed = parseFloat($(el).attr('data-lon1'));
      var windowYOffset = window.pageYOffset,
          elBackgrounPos = "0 " + (windowYOffset * speed) + "px";

      el.style.backgroundPosition = elBackgrounPos;

    });
  };

})();

The sections aren't getting the speed value but if I given a speed value by default it works. How could I get each data-Lon1 section value and have three different speed ?

Body:
This is always going to return the same value:

parseFloat($('.parallax').attr('data-lon1'))

Because you're selecting all matching .parallax elements and trying to get one value from all of them, which is likely always going to default to the first in the set.

You probably want to get the value for the specific element being used in that iteration of the loop:

parseFloat($(el).attr('data-lon1'))