问:
Apache 2.4 Rewrite URL matching full URL
I'm using Apache 2.4 as Reverse Proxy, and I need to redirect to an URL, only if credential is passed into URL. For Example, this is my URL:

https://user:password@myserver.mydomain.com/site1.php?1

I use this Rewrite Condition:

```<code>RewriteCond %{HTTP_HOST} ^user:password@ohab\.marcolino7\.myds\.me$
</code>```

But it do not match, i suppose because HTTP_HOST do not contain authentication data.
In there a way to match the URL with also authentication data and then so I can redirect?

Many Thanks
Marco

答:
As you correctly say, that is not part of the host header, so wouldn't match like that.

You can do it using the REMOTE_USER variable. How you do it depends on the context of your rules. See the documentation and specifically the quote below.

%{LA-U:variable} can be used for look-aheads which perform an
  internal (URL-based) sub-request to determine the final value of
  variable. This can be used to access variable for rewriting which is
  not available at the current stage, but will be set in a later phase.

For instance, to rewrite according to the REMOTE_USER variable from
  within the per-server context (httpd.conf file) you must use
  %{LA-U:REMOTE_USER} - this variable is set by the authorization
  phases, which come after the URL translation phase (during which
  mod_rewrite operates).

On the other hand, because mod_rewrite implements its per-directory
  context (.htaccess file) via the Fixup phase of the API and because
  the authorization phases come before this phase, you just can use
  %{REMOTE_USER} in that context.

Something like this in your httpd.conf file:

```<code>RewriteCond %{LA-U:REMOTE_USER} =user
</code>```

Or in .htaccess:

```<code>RewriteCond %{REMOTE_USER} =user
</code>```

Body:
I'm using Apache 2.4 as Reverse Proxy, and I need to redirect to an URL, only if credential is passed into URL. For Example, this is my URL:

https://user:password@myserver.mydomain.com/site1.php?1

I use this Rewrite Condition:

RewriteCond %{HTTP_HOST} ^user:password@ohab\.marcolino7\.myds\.me$

But it do not match, i suppose because HTTP_HOST do not contain authentication data.
In there a way to match the URL with also authentication data and then so I can redirect?

Many Thanks
Marco

Body:
As you correctly say, that is not part of the host header, so wouldn't match like that.

You can do it using the REMOTE_USER variable. How you do it depends on the context of your rules. See the documentation and specifically the quote below.

%{LA-U:variable} can be used for look-aheads which perform an
  internal (URL-based) sub-request to determine the final value of
  variable. This can be used to access variable for rewriting which is
  not available at the current stage, but will be set in a later phase.

For instance, to rewrite according to the REMOTE_USER variable from
  within the per-server context (httpd.conf file) you must use
  %{LA-U:REMOTE_USER} - this variable is set by the authorization
  phases, which come after the URL translation phase (during which
  mod_rewrite operates).

On the other hand, because mod_rewrite implements its per-directory
  context (.htaccess file) via the Fixup phase of the API and because
  the authorization phases come before this phase, you just can use
  %{REMOTE_USER} in that context.

Something like this in your httpd.conf file:

RewriteCond %{LA-U:REMOTE_USER} =user

Or in .htaccess:

RewriteCond %{REMOTE_USER} =user


来源: stackexchange

问:
Is there a keyboard shortcut to dismiss the intellisense panel (vscode)?
sometimes I want to hide the intellisense panel. I can do it with a click, but is there a way to do it with the keyboard?</p>

答:
ctrlspace toggles the intellisense in the suggest widget. This is bound to the toggleSuggestionDetails command.

To dismiss the the suggest widget itself, press esc which is bound to the hideSuggestWidget command.

You can customize these shortcuts with keybindings

ContentLicense: CC BY-SA 3.0


问:
Break out of a qx.data.Array forEach loop?
Is there a way to break out of the Qooxdoo qx.data.Array forEach loop?

For example,

```<code> myarray.forEach(function(obj){
   if(obj.match(/ra/i)){
       //break out of the loop
   }
 }
</code>```

答:
Not sure about the version that existed in 2013 but currently there is the array method some. If you return a Boolean true from the function passed in, the loop will terminate.

```<code>myarray.some(function(obj) {
    if(obj.match(/ra/i))
    {
        // do something
        return true;
    }
}, this);
</code>```

Body:
Is there a way to break out of the Qooxdoo qx.data.Array forEach loop?

For example,

 myarray.forEach(function(obj){
   if(obj.match(/ra/i)){
       //break out of the loop
   }
 }

Body:
Not sure about the version that existed in 2013 but currently there is the array method some. If you return a Boolean true from the function passed in, the loop will terminate.

myarray.some(function(obj) {
    if(obj.match(/ra/i))
    {
        // do something
        return true;
    }
}, this);


问:
Accessing Elasticsearch with Python 3
I want to use the Python 3 module urllib to access an Elasticsearch database at localhost:9200. My script gets a valid request (generated by Kibana) piped to STDIN in JSON format.

Here is what I did:

```<code>import json
import sys
import urllib.parse
import urllib.request

er = json.load(sys.stdin)
data = urllib.parse.urlencode(er)
data = data.encode('ascii')
uri = urllib.request.Request('http://localhost:9200/_search', data)
with urllib.request.urlopen(uri) as repsonse:
    response.read()
</code>```

(I understand that my repsonse.read() doesn't make much sense by itself but I just wanted to keep it simple.)

When I execute the script, I get an

```<code>HTTP Error 400: Bad request
</code>```

I am very sure that the JSON data I'm piping to the script is correct, since I had it printed and fed it via curl to Elasticsearch, and got back the documents I expected to get back.

Any ideas where I went wrong? Am I using urllib correctly? Do I maybe mess up the JSON data in the urlencode line? Am I querying Elasticsearch correctly?

Thanks for your help.

答:
With requests you can do one of two things

1) Either you create the string representation of the json object yourself and send it off like so:

```<code>payload = {'param': 'value'}
response = requests.post(url, data=json.dumps(payload))
</code>```

2) Or you have requests do it for you like so:

```<code>payload = {'param': 'value'}
response = requests.post(url, json = payload)
</code>```

So depending on what actually comes out of the sys.stdin call (probably - as Kibana would be sending that if the target was ElasticSearch - a string representation of a json object == equivalent of doing json.dumps on a dictionary), but you might have to adjust a bit depending on the output of sys.stdin.

My guess is that your code could work by just doing so:

```<code>import sys
import requests
payload  = sys.stdin
response = requests.post('http://localhost:9200/_search', data=payload)
</code>```

And if you then want to do some work with it in Python, requests has a built in support for this too. You just call this:

```<code>json_response = response.json()
</code>```

Hope this helps you on the right track. For further reading om json.dumps/loads - this answer has some good stuff on it.

Title: Accessing Elasticsearch with Python 3

Body:
I want to use the Python 3 module urllib to access an Elasticsearch database at localhost:9200. My script gets a valid request (generated by Kibana) piped to STDIN in JSON format.

Here is what I did:

import json
import sys
import urllib.parse
import urllib.request

er = json.load(sys.stdin)
data = urllib.parse.urlencode(er)
data = data.encode('ascii')
uri = urllib.request.Request('http://localhost:9200/_search', data)
with urllib.request.urlopen(uri) as repsonse:
    response.read()

(I understand that my repsonse.read() doesn't make much sense by itself but I just wanted to keep it simple.)

When I execute the script, I get an

HTTP Error 400: Bad request

I am very sure that the JSON data I'm piping to the script is correct, since I had it printed and fed it via curl to Elasticsearch, and got back the documents I expected to get back.

Any ideas where I went wrong? Am I using urllib correctly? Do I maybe mess up the JSON data in the urlencode line? Am I querying Elasticsearch correctly?

Thanks for your help.

Body:
With requests you can do one of two things

1) Either you create the string representation of the json object yourself and send it off like so:

payload = {'param': 'value'}
response = requests.post(url, data=json.dumps(payload))

2) Or you have requests do it for you like so:

payload = {'param': 'value'}
response = requests.post(url, json = payload)

So depending on what actually comes out of the sys.stdin call (probably - as Kibana would be sending that if the target was ElasticSearch - a string representation of a json object == equivalent of doing json.dumps on a dictionary), but you might have to adjust a bit depending on the output of sys.stdin.

My guess is that your code could work by just doing so:

import sys
import requests
payload  = sys.stdin
response = requests.post('http://localhost:9200/_search', data=payload)

And if you then want to do some work with it in Python, requests has a built in support for this too. You just call this:

json_response = response.json()

Hope this helps you on the right track. For further reading om json.dumps/loads - this answer has some good stuff on it.


问:
attempting to assign weaker access privileges; was public error for isCancelled
So i have this code for isCancelled in SwingWorker

```<code>boolean isCancelled() return true;
</code>```

and its giving me the error

attempting to assign weaker access privileges; was public error

I dont know how to fix it. Can anyone help me? Thank you

答:
Because if override methods you use same access in superclass or extend(package -> protected -> public).

Example if superclass:

```<code>boolean isCancelled(){}; // package local default access

protected boolean isCancelled(){};

public boolean isCancelled(){};
</code>```

In your sub class use(relatively):

```<code>@Override
boolean isCancelled(){}; //or add  protected or public

@Override
protected boolean isCancelled(){};//or change public

@Override
public boolean isCancelled(){};
</code>```

Body:
So i have this code for isCancelled in SwingWorker

boolean isCancelled() return true;

and its giving me the error

attempting to assign weaker access privileges; was public error

I dont know how to fix it. Can anyone help me? Thank you

Body:
Because if override methods you use same access in superclass or extend(package -> protected -> public).

Example if superclass:

boolean isCancelled(){}; // package local default access

protected boolean isCancelled(){};

public boolean isCancelled(){};

In your sub class use(relatively):

@Override
boolean isCancelled(){}; //or add  protected or public

@Override
protected boolean isCancelled(){};//or change public

@Override
public boolean isCancelled(){};


问:
"The import org.springframework cannot be resolved."
Here is my POM.xml file:

```<code><project>
    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.2.RELEASE</spring.version>
        <spring.batch.version>2.2.0.RELEASE</spring.batch.version>
        <mysql.driver.version>5.1.25</mysql.driver.version>
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>

        <!-- Spring Core -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring jdbc, for database -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- Spring XML to/back object -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>

        <!-- Spring Batch dependencies -->
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-infrastructure</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <!-- Spring Batch unit test -->
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>spring-batch</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>
</code>```

And below there is my java class:

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        String[] springConfig  =
            {
                "spring/batch/jobs/job-hello-world.xml"
            };
        ApplicationContext context =
            new ClassPathXmlApplicationContext(springConfig);
        JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean("helloWorldJob");
        try {
            JobExecution execution = jobLauncher.run(job, new JobParameters());
            System.out.println("Exit Status : " + execution.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
```

I am getting an error in import statements in my App.java classnd this is the message:

"The import org.springframework cannot be resolved."

I clearly mentioned the dependencies in POM.xml, but my java class still cannot pick the dependency from there.

答:
org.springframework.beans.factory.support.beannamegenerator , was my error. I did a maven clean, maven build etc., which was not useful and I found that my .m2 folder is not present in my eclipse installation folder. I found the .m2 folder out side of the eclipse folder which I pasted in the eclipse folder and then in eclipse I happened to do this :-

Open configure build path
  maven
  Java EE integration
  Select Maven archiver generates files under the build directory
  apply and close

My project is up and running now.

ContentLicense: CC BY-SA 4.0

Body:
Here is my POM.xml file:

<project>
    <properties>
        <jdk.version>1.6</jdk.version>
        <spring.version>3.2.2.RELEASE</spring.version>
        <spring.batch.version>2.2.0.RELEASE</spring.batch.version>
        <mysql.driver.version>5.1.25</mysql.driver.version>
        <junit.version>4.11</junit.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-oxm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.driver.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-core</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-infrastructure</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.batch</groupId>
            <artifactId>spring-batch-test</artifactId>
            <version>${spring.batch.version}</version>
        </dependency>

        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>

    </dependencies>
    <build>
        <finalName>spring-batch</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-eclipse-plugin</artifactId>
                <version>2.9</version>
                <configuration>
                    <downloadSources>true</downloadSources>
                    <downloadJavadocs>false</downloadJavadocs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>2.3.2</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

And below there is my java class:

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
    public static void main(String[] args) {
        String[] springConfig  =
            {
                "spring/batch/jobs/job-hello-world.xml"
            };
        ApplicationContext context =
            new ClassPathXmlApplicationContext(springConfig);
        JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
        Job job = (Job) context.getBean("helloWorldJob");
        try {
            JobExecution execution = jobLauncher.run(job, new JobParameters());
            System.out.println("Exit Status : " + execution.getStatus());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

I am getting an error in import statements in my App.java classnd this is the message:

"The import org.springframework cannot be resolved."

I clearly mentioned the dependencies in POM.xml, but my java class still cannot pick the dependency from there.


问:
Offline Java Documentation
I've finally gotten around to learning Java and am looking for some documentation for Java that I can download and read offline. Something like Sun's stuff but zipped up or as a PDF or CHM.

I'm using Eclipse so something that integrates with that would be nice. It already seems to have some of what I want somewhere (the javadoc stuff) but I don't see how to search it and I'm not seeing a language ref.

答:
I'm not sure that I fully understand your question.

If you are interested in materials about learning Java (rather than API references), you can download all of it as a zip file. It will be multiple HTML files, but I've never seen a real problem with browsing them unless I wanted a printout. If you need a printout of the tutorial, just get the tutorial in book form.

If you are looking for the JavaDocs for a specific API, and you use Eclipse, your best bet might be to use the version of Eclipse that is specific for Java and comes packaged with the JDK source code (or just download the source code). You can then read the documentation of methods through different views like the Java Browsing view.

OwnerDisplayName: BCS

Title: Offline Java Documentation

LastEditorDisplayName: Gamecat

OwnerDisplayName: Uri

ContentLicense: CC BY-SA 2.5


问:
How to add a custom button state
For instance, the default button has the following dependencies between its states and background images:

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true"
        android:drawable="@drawable/btn_default_normal" />
    <item android:state_window_focused="false" android:state_enabled="false"
        android:drawable="@drawable/btn_default_normal_disable" />
    <item android:state_pressed="true"
        android:drawable="@drawable/btn_default_pressed" />
    <item android:state_focused="true" android:state_enabled="true"
        android:drawable="@drawable/btn_default_selected" />
    <item android:state_enabled="true"
        android:drawable="@drawable/btn_default_normal" />
    <item android:state_focused="true"
        android:drawable="@drawable/btn_default_normal_disable_focused" />
    <item
        android:drawable="@drawable/btn_default_normal_disable" />
</selector>
</code>```

How can I define my own custom state (smth like android:state_custom), so then I could use it to dynamically change my button visual appearance?

答: This thread shows how to add custom states to buttons and the like. (If you can't see the new Google groups in your browser, there's a copy of the thread here.)</p>

Title: How to add a custom button state

Body:
For instance, the default button has the following dependencies between its states and background images:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:state_enabled="true"
        android:drawable="@drawable/btn_default_normal" />
    <item android:state_window_focused="false" android:state_enabled="false"
        android:drawable="@drawable/btn_default_normal_disable" />
    <item android:state_pressed="true"
        android:drawable="@drawable/btn_default_pressed" />
    <item android:state_focused="true" android:state_enabled="true"
        android:drawable="@drawable/btn_default_selected" />
    <item android:state_enabled="true"
        android:drawable="@drawable/btn_default_normal" />
    <item android:state_focused="true"
        android:drawable="@drawable/btn_default_normal_disable_focused" />
    <item
        android:drawable="@drawable/btn_default_normal_disable" />
</selector>

How can I define my own custom state (smth like android:state_custom), so then I could use it to dynamically change my button visual appearance?


问:
WampServer Apache module Unable to start
I run Swiftmailer from my local wampserver, but after I formated my pc and  wanted to setup again I get error trying to enable "LoadModule ssl_module modules/mod_ssl.so" . I run swiftmailer with smtp and ssl/tls support. So I needed to enable php_openssl.dll, php_smtp.dll,php_socket.dll in php.ini, everything works at this stage and until I un commented  the "LoadModule ssl_module modules/mod_ssl.so" line. Apache stopped starting.

How do I load The "LoadModule ssl_module modules/mod_ssl.so"?

答: There's a good chance that something else is holding port 443 open. In a Windows command prompt check: netstat -a to get a list of port numbers actively being listen on. Make sure WAMP is shut down before checking.


问:
Optimising a sentence search across multiple documents
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

```<code>$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];
</code>```

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

```<code>$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}
</code>```

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.

答:
Definitely answer is an regex. You should probably split it into three stages:

Convert your list of sentences into one big regex or a list of regexes to be run in a loop. You can convert spaces to whitespaces \s and make the search un-greedy /regex/U.

Iterate over files and remove line endings replacing it with spaces. Just in case an sentence is spread across multiple lines.

Use preg_match to find out if the sentence is in the file. You can do it in the loop if you decide for multiple regexes.

Body:
I am having issues optimising a search I created in PHP, this search is for one time use, so flexibility is not that important.

I have a array of sentences, like:

$arr = [
   'potato',
   'hi my name is Ivan'
    ..
];

The array contains about 1k sentences.

And I have a hard disk with 200 GB of files.

I need to search all of the files and see if any of these sentences are inside the files, and if so, to print out the path, a checksum, etc in a specific format.

The issue I am facing is search time, when doing something like this, which seems inefficient:

$objections = [];
foreach ($files as $file) {

    if (!in_array($file->getExtension(), $allowedExt))
        continue;

    $txt = file_get_contents($file);

    foreach ($words as $word) {
        if (stripos($txt, $word) !== false ||
            stripos($file->getFilename(), $word) !== false
            ) {
            $file->c_md5 = getCMD5($file);
            $objections[] = $file;
        }
    }
}

The search it self is taking ages 1h+, and I am on a new MacBook with the latest i7. With PHP memory etc maxed.

It is not relevant which word is matched in the array of words, so I was wondering if there is some more clever way to perform the search instead of looping the words inside the file loop. Would a very long REGEX string with OR's be faster?

Or is there some third way which is a lot fast.


问:
Allow a login form from website to sign into my Rails 5 app using Devise
I am using Rails 5 and Devise.

I want to put a login form with email and password on a website (www.abc.com) that's not within the Rails app (www.xyz.com).

I put the form one www.abc.com with a POST to www.xyz.com. Of course now I get an error because of the missing auth token (protect_from_forgery).

To avoid this I can put protect_from_forgery with: :null_session in my session controller. But I was wondering if there are better ways to do this.

Has Devise some native functionality for this?
How can I allow protect_from_forgery with: :null_session only for requests from www.abc.com?

答:
http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Something along the lines of

```<code>protect_from_forgery with: :null_session,
                     if: -> { request.domain.include?("abc.com") }
</code>```

Body:
http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Something along the lines of

protect_from_forgery with: :null_session,
                     if: -> { request.domain.include?("abc.com") }


问:
Autocorrelation function with non-zero padding in MATLAB
I need to compute peak value of autocorrelation function(ACF) for a noisy image. In the computation of the ACF, I need to consider the end effects. Padding the ends of the array with zero is not appropriate in my work, as this will exclude the contribution of the nonoverlapping ends to the value of the ACF(so I can’t use xcorr2). Instead, it is suggested that the ends are padded with either the average value of the image, or the image is wrapped around, but only the N2 values contained within the original image boundary are counted so as to preserve the total energy content of the image. How can I write MATLAB code for this non-zero padding ACF?</p>

答:
```<code>A=randn(100); %noisy image

[i,j]=size(A);
border = 10;
B=ones([i+2*border,j+2*border]).*mean(A(:)); %put mean value of A in B
B(border+1:end-border,border+1:end-border)=A; %put A in centre of B
</code>```


问:
Laravel4 : The requested resource /admin was not found on this server
there is a very weird problem I face with simple Laravel routing.

Because some screenshots, say sometimes more than 1000 words. Here is what I am encountering.

It doesn't matter, if the route is set in laravel or not. It just won't accept the name "admin" and only "admin".  Every other name is routed correctly.

Can't explain this. And wouldn't want to make a fresh laravel installation.

I don't use appache, because "php artisan serve" does the job for me.

Any clues?

答:
In folder public->admin
place these files named

```<code>.htaccess
favicon.ico
index.php
robots.txt
web.config
</code>```

like

and change your index.php file in admin folder

from this to

into this

hopefully it will solve your problem.

It worked for me.

Body:
In folder public->admin
place these files named

.htaccess
favicon.ico
index.php
robots.txt
web.config

like

and change your index.php file in admin folder

from this to

into this

hopefully it will solve your problem.

It worked for me.


问:
Layers within a layer in Caffe
I have a custom loss layer which I wrote, this layer applies softmax and sigmoid activation to part of the bottom[0] blob.

```<code>Ex: `bottom[0]` is of shape (say): `[20, 7, 7, 50]` (`NHWC` format)
I would like to apply `softmax` to `[20, 7, 7, 25]` (first 25 channels) and
`sigmoid` to `[20, 7, 7, 1]` (just one channel) and the remaining 24 channels are taken in as it is.
</code>```

How do I effectively allocate memory to the input blobs of these two softmax and sigmoid layers and also free this memory ?

答:
All the intermediate activations, along with the network's input and output blobs are managed by the net class and set up in the Net<Dtype>::Init function in src/caffe/net.cpp.

You don't need to allocate/deallocate the top and bottom blob memory from within the layer itself.

Title: Layers within a layer in Caffe

Body:
I have a custom loss layer which I wrote, this layer applies softmax and sigmoid activation to part of the bottom[0] blob.

Ex: `bottom[0]` is of shape (say): `[20, 7, 7, 50]` (`NHWC` format)
I would like to apply `softmax` to `[20, 7, 7, 25]` (first 25 channels) and
`sigmoid` to `[20, 7, 7, 1]` (just one channel) and the remaining 24 channels are taken in as it is.

How do I effectively allocate memory to the input blobs of these two softmax and sigmoid layers and also free this memory ?


问:
HTML5 acronym tag replacement using jQuery
Using jQuery, how would you replace every <acronym> tag with ?

答:
I'd try this, but I offer no warranty.

```<code>$('acronym').each(function(index)
{
  var old = this;
  var newElement = $("<abbr></abbr>");

  $.each(this.attributes, function(index)
  {
    $(newElement).attr(old.attributes[index].name, old.attributes[index].value);
  });

  $(newElement).html(old.html());

  $(this).after(newElement).remove();
});
</code>```

Good luck, and tell me if it's brokeded. If it's brokeded, I'll try to fix it.

Body:
I'd try this, but I offer no warranty.

$('acronym').each(function(index)
{
  var old = this;
  var newElement = $("<abbr></abbr>");

  $.each(this.attributes, function(index)
  {
    $(newElement).attr(old.attributes[index].name, old.attributes[index].value);
  });

  $(newElement).html(old.html());

  $(this).after(newElement).remove();
});

Good luck, and tell me if it's brokeded. If it's brokeded, I'll try to fix it.


问:
Disruptor dropping message issue
We have been using LMAX Disruptor in production for nearly a year now. Everything has been fine until last week when we saw messages dropped from Disruptor. Our Disruptor structure is pretty straightforward:

Kafka -> RingBuffer -> Eventhandler1 -> Eventhandler2 -> Eventhandler3

Each Eventhandler has a try-catch block to catch all Exceptions. The slowest is the Eventhandler2 which takes ~3 milliseconds for each message.

We sent 53 messages to Kafaka, all of them were processed by Eventhandler1. But somehow only 23 messages were picked up by Eventhandler2 and Eventhandler3, and we didn't see any Exceptions in logs.

We tried to reproduce this in our development environment but we did not see this issue.

So my questions are:

Is it possible for Disruptor to drop messages?

If yes, under what condition it may drop messages?

答:
Same issue I had on production and on testing env with load test.
It can drop or behave unpredictable in case you have 2 or more concurrent producers (ring buffer publishers) but Disruptor is initialized with ProducerType.SINGLE. Please check that.

ProducerType.MULTI usage example:

```<code>Disruptor<CustomEvent> disruptor = new Disruptor<CustomEvent>(eventFactory, bufferSize, executor, ProducerType.MULTI, new BlockingWaitStrategy());
</code>```

Title: Disruptor dropping message issue

Body:
Same issue I had on production and on testing env with load test.
It can drop or behave unpredictable in case you have 2 or more concurrent producers (ring buffer publishers) but Disruptor is initialized with ProducerType.SINGLE. Please check that.

ProducerType.MULTI usage example:

Disruptor<CustomEvent> disruptor = new Disruptor<CustomEvent>(eventFactory, bufferSize, executor, ProducerType.MULTI, new BlockingWaitStrategy());


问:
Converting HTML content to PDF file using jsPDF
Trying to automatically convert this  content to a pdf file. Based on how the rest of my code is setup, I have to have the button to click INSIDE the div that I want to export to pdf. Is this a problem? Here's what I have so far. When I click the button, it does nothing.

JS:

```<code><script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.debug.js"></script>

<script>
jQuery('#generatereport').click(function () {
    doc.fromHTML(jQuery('#lppresults').html(), 15, 15, {
        'width': 170
    });
    doc.save('sample-file.pdf');
});
</script>
</code>```

HTML:

```<code><div class="survey-results" style="display: none;" id="lppresults">
   <button id="generatereport">Download Report</button>
   TEST CONTENT
</div>
</code>```

答:
You need to initialize the jsPDF class : var doc = new jsPDF();

var doc = new jsPDF();
jQuery('#generatereport').click(function() {
  doc.fromHTML(jQuery('#lppresults').html(), 15, 15, {
    'width': 170
  });
  doc.save('sample-file.pdf');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

<div class="survey-results" id="lppresults">
  <button id="generatereport">Download Report</button> TEST CONTENT
</div></code>```

Body:
Trying to automatically convert this  content to a pdf file. Based on how the rest of my code is setup, I have to have the button to click INSIDE the div that I want to export to pdf. Is this a problem? Here's what I have so far. When I click the button, it does nothing.

JS:

HTML:

   <button id="generatereport">Download Report</button>
   TEST CONTENT

Body:
You need to initialize the jsPDF class : var doc = new jsPDF();

var doc = new jsPDF();
jQuery('#generatereport').click(function() {
  doc.fromHTML(jQuery('#lppresults').html(), 15, 15, {
    'width': 170
  });
  doc.save('sample-file.pdf');
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.4/jspdf.min.js"></script>

<div class="survey-results" id="lppresults">
  <button id="generatereport">Download Report</button> TEST CONTENT
</div>


问:
filter between two dates from API with angularjs
i retrieve details of an account from an API statement based on the user ID with the below script

```<code>    $http.post("http://testingserver.net/statement.php",{'id':$scope.account_number}).success
    (function(data){
    console.log(JSON.stringify(data));
$scope.statement=data;
    });
</code>```

From the log i'm able to get the data in detail. The data from the log contains a field called Date which is formatted 2017-02-01T00:00:00Z and what i want to achieve is to let the user select from two date ranges and push back the results to the user.

From the HTML below they are two fields namely sdate and edate

HTML

```<code><form method="post" name="statement" id="statement">
<div class="list">
  <label class="item item-input">
    <span class="input-label">Search From</span>
    <input type="date" ng-model="sdate">
  </label>
  <label class="item item-input">
    <span class="input-label">Search To</span>
    <input type="date" ng-model="edate">
  </label>
</div>
</form>
</br>
<div align="center">
<p><button class="button button-positive" ng-disabled="statement.$invalid" ng-click="state_request()">
  <i class="icon ion-android-search icon"></i> Search
</button></p>
</div>
</code>```

HTML for results

```<code><div ng-repeat="item in statement">
  <table width="100%" border="0" cellspacing="5" cellpadding="5">
    <tr>
      <td width="70%"><div align="left">
        <p><strong> Period</strong>      </p>
      </div></td>
      <td width="82%">{{item.Date |date: 'MMMM yyyy'}}</td>
    </tr>
    <tr>
      <td><p><strong>Category</strong></p></td>
      <td>{{item.Category}}</td>
    </tr>
    <tr>
      <td><div align="left">
        <p><strong>Amount</strong>      </p>
      </div></td>
      <td><div align="left">{{item.Amount}}</div></td>
    </tr>
    <tr>
      <td colspan="2"> </td>
    </tr>
  </table>
</div>
</code>```

答:
You have two ways to go:

1) add start/end dates and use server to do heavy lifting.

2) Send back all results and filter client side.

Former is probably best way to go. If you do that you'd need the dates sdate and edate in your url's query params that server would process and then have some sort of stored procedure to do date range checking. I'm not a PHP guy - Java is more my forte, and Angular 4/Ionic.

Body:
i retrieve details of an account from an API statement based on the user ID with the below script

    $http.post("http://testingserver.net/statement.php",{'id':$scope.account_number}).success
    (function(data){
    console.log(JSON.stringify(data));
$scope.statement=data;
    });

From the log i'm able to get the data in detail. The data from the log contains a field called Date which is formatted 2017-02-01T00:00:00Z and what i want to achieve is to let the user select from two date ranges and push back the results to the user.

From the HTML below they are two fields namely sdate and edate

HTML

<form method="post" name="statement" id="statement">

    Search From
    <input type="date" ng-model="sdate">

    Search To
    <input type="date" ng-model="edate">

</form>

<button class="button button-positive" ng-disabled="statement.$invalid" ng-click="state_request()">
   Search
</button>

HTML for results

 Period

      {{item.Date |date: 'MMMM yyyy'}}

Category

      {{item.Category}}

Amount

{{item.Amount}}


问:
.find() triggers run-time error 91 even though all variables are set VBA possibly due to bad references
I am writing code to create a template. This code populates a tab named "fullDistribution" from user-input on different tabs in the same wb. I have a working section of code that I wrote in a separate module (for testing) away from my master module. The code runs properly and executes completely when it is separate. When I pasted this section of code into my master module and ran it, I began receiving "Run-time error 91: object variable or with block variable not set" at the start of the newly-pasted code. I am not using any with blocks, and all of my variables are set. I made no changes in my code when I transferred it to my master module, and I carried over the new variables I created.

This is the selection of code that I wrote in a separate module:

```<code>Worksheets("bls2016").Activate
tcount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row))
acount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("K2:K7"))
Application.ScreenUpdating = False

Dim h As Integer
Dim f As Integer
Dim blstate As Range
Dim bl As Range
Dim state As Range
Dim deat As Range
Dim agje As Range
Dim e As Integer
Dim r As Integer
Dim ii As Integer

Set blstate = Worksheets("bls2016").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set state = Worksheets("detailedEntity").Range("Q1")
Set deat = Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set agje = Worksheets("detailedEntity").Range("L2:M" & Cells(Rows.Count, "M").End(xlUp).Row)

h = Activecolumn
f = Activerow
r = 2

x = 120
    For e = 1 To (acount * acount)
        blstate.Find(state).Select
        For ii = 1 To x
        'ccnt = acst.Offset(0, 1)
            ccgv = ActiveCell.Offset(0, 2)
            acem = ActiveCell.Offset(0, 5)
            Do While True
            vl1 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 2), deat, 1, False), 0)
                If vl1 = 0 Then
                    Worksheets("fullDistribution").Cells(r, 4) = 0
                Else:
                    vl2 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 1), agje, 2, False), 0)
                    If ActiveCell.Offset(0, 1).Value = "Unknown Or Undefined" Then
                        Exit Do
                    Else:
                        If vl2 = ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = acem
                        ElseIf vl2 <> ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = ActiveCell.Offset(x + 1, 5)
                        Else:
                            End If
                        End If
                    End If
                Exit Do
            Loop
            ActiveCell.Offset(f + 1, h).Select
        r = r + 1
        Next ii
    Next e
</code>```

The error triggers at the line "blstate.find(state).select" which tells excel to look in a dynamic range that contains the names of states and select the first instance of the state to use as the Activecell. Again, this works when it's run outside of the main module.

I believe this has something to do with a reference area. When this runs alone and finishes, I have to have a specific worksheet activated for it to run properly. If my excel workbook is open to a different tab, it will not run. My main module too only executes properly if it is run on a specific worksheet/tab.

If need be, I can edit my post and provide my whole master code.

答:
```<code>blstate.Find(state).Select
</code>```

Your code assumes that .Find finds what it's looking for. When Find doesn't find what it's looking for, the function returns Nothing, which is essentially a null object reference - and you can't make member calls on Nothing without getting run-time error 91.

Split it up:

```<code>Dim result As Range
Set result = blstate.Find(state)
If Not result Is Nothing Then
    result.Select 'questionable anyway, but that's another issue
Else
    MsgBox "Value '" & state & "' was not found in " & blstate.Address(External:=True) & "."
    Exit Sub
End If
</code>```

As for why it's not finding what you're looking for, Tim Williams already answered that:

Find recalls all settings used in the last call (even if you use the GUI to perform the Find), so make sure you specify the settings you want when you call it via VBA. If you don't do that, it may not work as you expect.... – Tim Williams 42 mins ago

Body:
I am writing code to create a template. This code populates a tab named "fullDistribution" from user-input on different tabs in the same wb. I have a working section of code that I wrote in a separate module (for testing) away from my master module. The code runs properly and executes completely when it is separate. When I pasted this section of code into my master module and ran it, I began receiving "Run-time error 91: object variable or with block variable not set" at the start of the newly-pasted code. I am not using any with blocks, and all of my variables are set. I made no changes in my code when I transferred it to my master module, and I carried over the new variables I created.

This is the selection of code that I wrote in a separate module:

Worksheets("bls2016").Activate
tcount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row))
acount = WorksheetFunction.CountA(Worksheets("detailedEntity").Range("K2:K7"))
Application.ScreenUpdating = False

Dim h As Integer
Dim f As Integer
Dim blstate As Range
Dim bl As Range
Dim state As Range
Dim deat As Range
Dim agje As Range
Dim e As Integer
Dim r As Integer
Dim ii As Integer

Set blstate = Worksheets("bls2016").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set state = Worksheets("detailedEntity").Range("Q1")
Set deat = Worksheets("detailedEntity").Range("D2:D" & Cells(Rows.Count, "D").End(xlUp).Row)
Set agje = Worksheets("detailedEntity").Range("L2:M" & Cells(Rows.Count, "M").End(xlUp).Row)

h = Activecolumn
f = Activerow
r = 2

x = 120
    For e = 1 To (acount * acount)
        blstate.Find(state).Select
        For ii = 1 To x
        'ccnt = acst.Offset(0, 1)
            ccgv = ActiveCell.Offset(0, 2)
            acem = ActiveCell.Offset(0, 5)
            Do While True
            vl1 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 2), deat, 1, False), 0)
                If vl1 = 0 Then
                    Worksheets("fullDistribution").Cells(r, 4) = 0
                Else:
                    vl2 = Application.IfNa(Application.VLookup(Worksheets("fullDistribution").Cells(r, 1), agje, 2, False), 0)
                    If ActiveCell.Offset(0, 1).Value = "Unknown Or Undefined" Then
                        Exit Do
                    Else:
                        If vl2 = ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = acem
                        ElseIf vl2 <> ccgv Then
                            Worksheets("fullDistribution").Cells(r, 4) = ActiveCell.Offset(x + 1, 5)
                        Else:
                            End If
                        End If
                    End If
                Exit Do
            Loop
            ActiveCell.Offset(f + 1, h).Select
        r = r + 1
        Next ii
    Next e

The error triggers at the line "blstate.find(state).select" which tells excel to look in a dynamic range that contains the names of states and select the first instance of the state to use as the Activecell. Again, this works when it's run outside of the main module.

I believe this has something to do with a reference area. When this runs alone and finishes, I have to have a specific worksheet activated for it to run properly. If my excel workbook is open to a different tab, it will not run. My main module too only executes properly if it is run on a specific worksheet/tab.

If need be, I can edit my post and provide my whole master code.

Body:
blstate.Find(state).Select

Your code assumes that .Find finds what it's looking for. When Find doesn't find what it's looking for, the function returns Nothing, which is essentially a null object reference - and you can't make member calls on Nothing without getting run-time error 91.

Split it up:

Dim result As Range
Set result = blstate.Find(state)
If Not result Is Nothing Then
    result.Select 'questionable anyway, but that's another issue
Else
    MsgBox "Value '" & state & "' was not found in " & blstate.Address(External:=True) & "."
    Exit Sub
End If

As for why it's not finding what you're looking for, Tim Williams already answered that:

Find recalls all settings used in the last call (even if you use the GUI to perform the Find), so make sure you specify the settings you want when you call it via VBA. If you don't do that, it may not work as you expect.... – Tim Williams 42 mins ago


答:
Use jQuery's replaceWith. I am assuming you are only using the title attribute.

```<code>$("acronym").each(function(){//for each acronym element
       var abbr = $("<abbr></abbr>");//create a new abbr element
       var title = $(this).attr("title");//get the title attribute from the acronym element
       abbr.attr("title",title);//add it to the new abbr element
       abbr.html($(this).html());//add in the content of the acronym element
       $(this).replaceWith(abbr);//replace the old with the new!
    });
</code>```

Try it!

Title: HTML5 acronym tag replacement using jQuery

Body: Using jQuery, how would you replace every <acronym> tag with ?

Body:
Use jQuery's replaceWith. I am assuming you are only using the title attribute.

$("acronym").each(function(){//for each acronym element
       var abbr = $("<abbr></abbr>");//create a new abbr element
       var title = $(this).attr("title");//get the title attribute from the acronym element
       abbr.attr("title",title);//add it to the new abbr element
       abbr.html($(this).html());//add in the content of the acronym element
       $(this).replaceWith(abbr);//replace the old with the new!
    });

Try it!


问:
DocBook 5, add (MathML) namespace to HTML output?
I'm typing a book with some math formulas written in MathML.  The book has a "main" XML file which includes all the chapter files like this:

```<code><?xml version="1.0" encoding="utf-8"?>
<book xmlns="http://docbook.org/ns/docbook"
      xmlns:xi="http://www.w3.org/2001/XInclude"
      version="5.1"
      xml:lang="en">
  <title>Some title</title>
  <xi:include href="intro.xml"/>
</book>
</code>```

And intro.xml goes as

```<code><?xml version="1.0" encoding="utf-8"?>
<chapter xml:id="ch-intro" xmlns:m="http://www.w3.org/1998/Math/MathML">
  <title>Introduction</title>
  <para>Some text
  <inlineequation>
    <m:math><m:msqrt><m:mi>a</m:mi></m:msqrt></m:math>
  </inlineequation>
  Some other text.
  </para>
</chapter>
</code>```

This produces something like

```<code><p>Some text
<m:math xmlns:m="http://www.w3.org/1998/Math/MathML">
  <m:msqrt><m:mi>a</m:mi></m:msqrt>
</m:math>
Some other text.</p>
</code>```

I have a customization layer XSLT on top of the HTML XSLT from Docbook-XSL to load MathJax:

```<code><xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:m="http://www.w3.org/1998/Math/MathML"
                version="1.0">
  <xsl:import href="docbook-xsl-nons-snapshot/html/docbook.xsl"/>
  <!-- Add MathJax <script> tags to document <head> -->
  <xsl:template name="user.head.content">
    <script type="text/javascript" async="async" src="https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.1/MathJax.js?config=MML_CHTML"></script>
  </xsl:template>
</xsl:stylesheet>
</code>```

And this works in the sense that it does add the

答:
What happens if you override the template below by putting it into your main stylesheet module:

```<code><xsl:template match="*" mode="process.root">
  <xsl:variable name="doc" select="self::*"/>

  <xsl:call-template name="user.preroot"/>
  <xsl:call-template name="root.messages"/>

  <html>
    <xsl:call-template name="root.attributes"/>
    <head>
      <xsl:call-template name="system.head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:call-template name="head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:call-template name="user.head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
    </head>
    <body>
      <xsl:call-template name="body.attributes"/>
      <xsl:call-template name="user.header.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:apply-templates select="."/>
      <xsl:call-template name="user.footer.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
    </body>
  </html>
  <xsl:value-of select="$html.append"/>

  <!-- Generate any css files only once, not once per chunk -->
  <xsl:call-template name="generate.css.files"/>
</xsl:template>
</code>```

Given that that module has the MathML namespace declaration I would expect that the generated root element has it too.

Body:
I'm typing a book with some math formulas written in MathML.  The book has a "main" XML file which includes all the chapter files like this:

<?xml version="1.0" encoding="utf-8"?>
<book xmlns="http://docbook.org/ns/docbook"
      xmlns:xi="http://www.w3.org/2001/XInclude"
      version="5.1"
      xml:lang="en">
  <title>Some title</title>
  <xi:include href="intro.xml"/>
</book>

And intro.xml goes as

<?xml version="1.0" encoding="utf-8"?>
<chapter xml:id="ch-intro" xmlns:m="http://www.w3.org/1998/Math/MathML">
  <title>Introduction</title>
  <para>Some text
  <inlineequation>
    <m:math><m:msqrt><m:mi>a</m:mi></m:msqrt></m:math>
  </inlineequation>
  Some other text.
  </para>
</chapter>

This produces something like

Some text
<m:math xmlns:m="http://www.w3.org/1998/Math/MathML">
  <m:msqrt><m:mi>a</m:mi></m:msqrt>
</m:math>
Some other text.

I have a customization layer XSLT on top of the HTML XSLT from Docbook-XSL to load MathJax:

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:m="http://www.w3.org/1998/Math/MathML"
                version="1.0">
  <xsl:import href="docbook-xsl-nons-snapshot/html/docbook.xsl"/>

Body:
What happens if you override the template below by putting it into your main stylesheet module:

<xsl:template match="*" mode="process.root">
  <xsl:variable name="doc" select="self::*"/>

  <xsl:call-template name="user.preroot"/>
  <xsl:call-template name="root.messages"/>

  <html>
    <xsl:call-template name="root.attributes"/>
    <head>
      <xsl:call-template name="system.head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:call-template name="head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:call-template name="user.head.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
    </head>
    <body>
      <xsl:call-template name="body.attributes"/>
      <xsl:call-template name="user.header.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
      <xsl:apply-templates select="."/>
      <xsl:call-template name="user.footer.content">
        <xsl:with-param name="node" select="$doc"/>
      </xsl:call-template>
    </body>
  </html>
  <xsl:value-of select="$html.append"/>

  <!-- Generate any css files only once, not once per chunk -->
  <xsl:call-template name="generate.css.files"/>
</xsl:template>

Given that that module has the MathML namespace declaration I would expect that the generated root element has it too.


问:
applying a function of sqrt on a data frame
I want to compute the following equation between each two points, i dont know how to apply that in the whole data set:</p>

```<code>Point  x y z
1      4 3 8
2      8 5 4
3      5 4 7
4      2 7 4

D1,2 = sqrt((x2-x1)²+ (y2-y1)²+( z2-z1)²)
</code>```

答:
It would be best to use dist for calculating the distance as suggested in the comments.

```<code>data.frame(as.matrix(dist(df[,-1], diag = TRUE, upper = TRUE)))
</code>```

You could also use sapply to calculate the distance (or apply some other formula) by yourself

```<code>sapply(1:NROW(df), function(i)
    sapply(1:NROW(df), function(j)
        sqrt(diff(df$x[c(i,j)])^2 + diff(df$y[c(i,j)])^2 + diff(df$z[c(i,j)])^2)))
#         [,1]     [,2]     [,3]     [,4]
#[1,] 0.000000 6.000000 1.732051 6.000000
#[2,] 6.000000 0.000000 4.358899 6.324555
#[3,] 1.732051 4.358899 0.000000 5.196152
#[4,] 6.000000 6.324555 5.196152 0.000000
</code>```

Body:
I want to compute the following equation between each two points, i dont know how to apply that in the whole data set:

Point  x y z
1      4 3 8
2      8 5 4
3      5 4 7
4      2 7 4

D1,2 = sqrt((x2-x1)²+ (y2-y1)²+( z2-z1)²)

Body:
It would be best to use dist for calculating the distance as suggested in the comments.

data.frame(as.matrix(dist(df[,-1], diag = TRUE, upper = TRUE)))

You could also use sapply to calculate the distance (or apply some other formula) by yourself

sapply(1:NROW(df), function(i)
    sapply(1:NROW(df), function(j)
        sqrt(diff(df$x[c(i,j)])^2 + diff(df$y[c(i,j)])^2 + diff(df$z[c(i,j)])^2)))
#         [,1]     [,2]     [,3]     [,4]
#[1,] 0.000000 6.000000 1.732051 6.000000
#[2,] 6.000000 0.000000 4.358899 6.324555
#[3,] 1.732051 4.358899 0.000000 5.196152
#[4,] 6.000000 6.324555 5.196152 0.000000


问:
How to make a function call only once in Swift 3.1?
I have a class that looks a little like:

```<code>final class Token {

..........

public enum Result {

    case Success()
    case Failure(Error)

}

private var successClosure : (() -> Void)?
private var failureClosure : ((Error) -> Void)?

public func completed(withResult result: Token.Result) {

    switch result {
       case .Success: successClosure?()
       case .Failure(let error): failureClosure?(error)
    }

}

..........

}
</code>```

I would like to enforce the ability to call completed(withResult:) only once.

Is there a method of converting the above completed(withResult:) method to one that is compatible with Swift 3.1?

答: I don’t understand the requirement well enough to write a sample code that exactly addresses your needs, but generally speaking, you might consider using dispatch_once as documented here.

Body:
I have a class that looks a little like:

final class Token {

..........

public enum Result {

    case Success()
    case Failure(Error)

}

private var successClosure : (() -> Void)?
private var failureClosure : ((Error) -> Void)?

public func completed(withResult result: Token.Result) {

    switch result {
       case .Success: successClosure?()
       case .Failure(let error): failureClosure?(error)
    }

}

..........

}

I would like to enforce the ability to call completed(withResult:) only once.

Is there a method of converting the above completed(withResult:) method to one that is compatible with Swift 3.1?


答:
If you are insisting on using promises then, create a promise with a set timeout resolver.

Inside pop the array and do whatever you like. Promise all of an array of those promises would do the trick I think.

But why promises rather than a simple for loop with set timeout?

Title: JavaScript - dispatch 10 promises in every minute?

Body:
How can I dispatch 10 promises in every minute?

I have these dynamic dates in a list:

var dates = ["2016-08-31T23:00:00.000Z","2016-09-01T23:00:00.000Z","2016-09-02T23:00:00.000Z","2016-09-03T23:00:00.000Z","2016-09-04T23:00:00.000Z","2016-09-05T23:00:00.000Z","2016-09-06T23:00:00.000Z","2016-09-07T23:00:00.000Z","2016-09-08T23:00:00.000Z","2016-09-09T23:00:00.000Z","2016-09-10T23:00:00.000Z","2016-09-11T23:00:00.000Z","2016-09-12T23:00:00.000Z","2016-09-13T23:00:00.000Z","2016-09-14T23:00:00.000Z","2016-09-15T23:00:00.000Z","2016-09-16T23:00:00.000Z","2016-09-17T23:00:00.000Z","2016-09-18T23:00:00.000Z","2016-09-19T23:00:00.000Z","2016-09-20T23:00:00.000Z","2016-09-21T23:00:00.000Z","2016-09-22T23:00:00.000Z","2016-09-23T23:00:00.000Z","2016-09-24T23:00:00.000Z","2016-09-25T23:00:00.000Z","2016-09-26T23:00:00.000Z","2016-09-27T23:00:00.000Z","2016-09-28T23:00:00.000Z","2016-09-29T23:00:00.000Z","2016-09-30T23:00:00.000Z","2016-10-01T23:00:00.000Z"];

I want to get the content or result that associated with these dates. But I don't want to get them in one go, but every 10 items in every minute, until the date is no more.

This is my working code:

     var promises = dates.map(function (date, i) {
        return getContent(date);
    });

    Promise.all(promises).then((data) => {
        console.log(data);
    }).catch((err) => {
        console.log(err.message);
    });

It gets the content in a row, not exactly what I want.

But is it possible to achieve what I need? Any ideas?

Notes:

getContent(date) contains a massive of async await promises, so in that promse.all that calls it has to be a promise too i guess, otherwise I can get all return data in one place (which is console.log(data);) when the promises end.

EDIT:

const delayValue = (val, ms) => {
    new Promise(resolve => {
        setTimeout(resolve.bind(null, val), ms)
    });
}


问:
putting a key in json in a specific directory put the key in all directory (JsonPath.parse(String).put)
I have a json template which looks like this.

```<code>         {
        "parent": {
            "dir1": {
                "key11": {
                    "min": 1,
                    "max": 100
                },
                "key12": {
                    "sample1": "txt",
                    "sample2": "100.25"
                }
            },
            "dir2": {
                "key21": {
                    "min": 1,
                    "max": 100
                },
                "key22": {
                    "sample1": "USD",
                    "sample2": "100.25"
                }
            }
        }
     }
</code>```

In this I have a logic to parse the json and check (while iterating) if parent.dir1 has some specific key for e.g. "goldenKey".
If key is not found then put() the "key (goldenKey)" in jsonpath
JsonPath.parse(jsonString).put(jsonpath, key, value).json();

To get the jsonPath where to put key I am going back one node by splitting current jsonPath by "." from last and convert it to key which needs be to put.
like below code

```<code>try {
//set jsonpath, if key not found then catch
JsonPath.parse(json).set("$.parent.dir1.goldenKey", "golden").json();
} catch (final PathNotFoundException e) {
//json path of the key
String jsonpath = "$.parent.dir1.goldenKey";
//get the key by getting last index of "."
final String key = jsonpath.substring(jsonpath.lastIndexOf(".") +1);
jsonpath = jsonpath.substring(0, jsonpath.lastIndexOf("."));
JsonPath.parse(json).put(jsonpath, "goldenKey", "golden").json();}
</code>```

Issue is that, instead of putting the key, value on the given json path (i.e. dir1 in this code) it put the key and value in both dir1 and dir23

Please let me know if the explanation is not clear.

答: You are getting the substring from the hard coded jsonpath. jsonpath should be $.parent.dir1 when adding the value "goldenKey":"golden". This should add the key value pair under dir1 alone. Double check it once.

Body:
I have a json template which looks like this.

         {
        "parent": {
            "dir1": {
                "key11": {
                    "min": 1,
                    "max": 100
                },
                "key12": {
                    "sample1": "txt",
                    "sample2": "100.25"
                }
            },
            "dir2": {
                "key21": {
                    "min": 1,
                    "max": 100
                },
                "key22": {
                    "sample1": "USD",
                    "sample2": "100.25"
                }
            }
        }
     }

In this I have a logic to parse the json and check (while iterating) if parent.dir1 has some specific key for e.g. "goldenKey".
If key is not found then put() the "key (goldenKey)" in jsonpath
JsonPath.parse(jsonString).put(jsonpath, key, value).json();

To get the jsonPath where to put key I am going back one node by splitting current jsonPath by "." from last and convert it to key which needs be to put.
like below code

try {
//set jsonpath, if key not found then catch
JsonPath.parse(json).set("$.parent.dir1.goldenKey", "golden").json();
} catch (final PathNotFoundException e) {
//json path of the key
String jsonpath = "$.parent.dir1.goldenKey";
//get the key by getting last index of "."
final String key = jsonpath.substring(jsonpath.lastIndexOf(".") +1);
jsonpath = jsonpath.substring(0, jsonpath.lastIndexOf("."));
JsonPath.parse(json).put(jsonpath, "goldenKey", "golden").json();}

Issue is that, instead of putting the key, value on the given json path (i.e. dir1 in this code) it put the key and value in both dir1 and dir23

Please let me know if the explanation is not clear.


问:
Optimize jQuery triggered MySQL-Query
Hello to this great community!

I've already learned a lot by reading many of the questions and answers here. So here is my current problem:

I'm currently creating a simple code which includes PHP, MySQL and jQuery for a simple news ticker. The aim is to check the database for changes without the need of reloading the whole webpage. If there is a change in the database a javascript is executed to reload the whole webpage. With this I want to avoid, that the user has to reload the webpage manually.

This works nicely!

But there is one problem: When too many users are on the webpage a "Too many connections"-Mysql-error occurs. I think this happens because of the many parallel running updates()-functions.

Do you have an idea how to optimize this code?

```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="updates"></div></code>```

updates.php

```<code><?php

// Get latest value the database
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);

// Compare the value from the database with the current value which is saved in a session
if($_SESSION['update'] != $row->update) {

// If the values do not match, update the session and reload the whole webpage
$_SESSION['update'] = $row->update;

echo '<script>
location.reload();
</script>'

}
</code>```

答:
Try something like this instead of refreshing the whole page.

PHP

```<code><?php

header('Content-type: application/json');

$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);

if (($update = $_SESSION['update']) != $row->update) {
    $_SESSION['update'] = $row->update;
    echo json_encode(['update' => null]);
    exit;
}

echo json_encode(['update' => $update]);
</code>```

Javascript

```<code>$.post('updates.php')
    .done(function( data ){
        if( data.update){
            //update DOM with new update
        }
    });
</code>```

And increase your timeout interval. One request/1000ms is very frequent.

Title: Optimize jQuery triggered MySQL-Query

Body:
Hello to this great community!

I've already learned a lot by reading many of the questions and answers here. So here is my current problem:

I'm currently creating a simple code which includes PHP, MySQL and jQuery for a simple news ticker. The aim is to check the database for changes without the need of reloading the whole webpage. If there is a change in the database a javascript is executed to reload the whole webpage. With this I want to avoid, that the user has to reload the webpage manually.

This works nicely!

But there is one problem: When too many users are on the webpage a "Too many connections"-Mysql-error occurs. I think this happens because of the many parallel running updates()-functions.

Do you have an idea how to optimize this code?

updates.php

<?php

// Get latest value the database
$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);

// Compare the value from the database with the current value which is saved in a session
if($_SESSION['update'] != $row->update) {

// If the values do not match, update the session and reload the whole webpage
$_SESSION['update'] = $row->update;

echo ''

}

Body:
Try something like this instead of refreshing the whole page.

PHP

<?php

header('Content-type: application/json');

$result = mysql_query("SELECT update FROM updates_db");
$row = mysql_fetch_object($result);

if (($update = $_SESSION['update']) != $row->update) {
    $_SESSION['update'] = $row->update;
    echo json_encode(['update' => null]);
    exit;
}

echo json_encode(['update' => $update]);

Javascript

$.post('updates.php')
    .done(function( data ){
        if( data.update){
            //update DOM with new update
        }
    });

And increase your timeout interval. One request/1000ms is very frequent.


问:
dynamic update the data using EF4 in asp.net mvc
for example, i have a data table named [User], and mapping to User enetity with EF4:

```<code>Id, FullName, EmailAddress, Fax, Tel
</code>```

in the web page, i just only want to update the "EmailAddess" and "Fax" 2 properties below:

```<code>@using (Html.BeginForm("Edit", "User"))
{
    <label>Email Address:</label>
    @Html.TextBox("EmailAddress")
    <label>Fax:</label>
    @Html.TextBox("Fax")
    <input type="submit" value="Update" />
}
</code>```

and controller i did for this:

```<code>public ActionResult Edit(User user) {

var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();

_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;

context.SaveChanges();
}
</code>```

yes, i updated it and successful, but next time i also want to update "Tel", so i need to change the code like this:

```<code>_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;
_user.Tel = user.Tel;
</code>```

if i have 100 fields, i will be crazy for doing it :(

So, how can i only update the models to database for related fields in web page?

thanks

答:
You should definitely look into AutoMapper ( http://automapper.codeplex.com/ ).

```<code>AutoMapper.Mapper.CreateMap(typeof(User), typeof(UserViewModel));

AutoMapper.Mapper.CreateMap<User, UserViewModel>()
    .ForMember(d => d.Property1, f => f.MapFrom(s => s.Property1))
    .ForMember(d => d.Property2, f => f.MapFrom(s => s.Property2))
    .ForMember(d => d.Property3, f => f.MapFrom(s => s.Property3));
</code>```

Then in your Edit you can do the following

```<code>public ActionResult Edit(User user) {
    var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();

    AutoMapper.Mapper.Map(user, _user);

    context.SaveChanges();
}
</code>```

Entity framework will only update the fields that have actually changed.

Pretty sure that's about all you need.

Body:
for example, i have a data table named [User], and mapping to User enetity with EF4:

Id, FullName, EmailAddress, Fax, Tel

in the web page, i just only want to update the "EmailAddess" and "Fax" 2 properties below:

@using (Html.BeginForm("Edit", "User"))
{
    Email Address:
    @Html.TextBox("EmailAddress")
    Fax:
    @Html.TextBox("Fax")
    <input type="submit" value="Update" />
}

and controller i did for this:

public ActionResult Edit(User user) {

var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();

_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;

context.SaveChanges();
}

yes, i updated it and successful, but next time i also want to update "Tel", so i need to change the code like this:

_user.Fax = user.Fax;
_user.EmailAddress = user.EmailAddress;
_user.Tel = user.Tel;

if i have 100 fields, i will be crazy for doing it :(

So, how can i only update the models to database for related fields in web page?

thanks

Body:
You should definitely look into AutoMapper ( http://automapper.codeplex.com/ ).

AutoMapper.Mapper.CreateMap(typeof(User), typeof(UserViewModel));

AutoMapper.Mapper.CreateMap<User, UserViewModel>()
    .ForMember(d => d.Property1, f => f.MapFrom(s => s.Property1))
    .ForMember(d => d.Property2, f => f.MapFrom(s => s.Property2))
    .ForMember(d => d.Property3, f => f.MapFrom(s => s.Property3));

Then in your Edit you can do the following

public ActionResult Edit(User user) {
    var _user = GetUsers().Where(a => a.Id == user.Id).SingleOrDefault();

    AutoMapper.Mapper.Map(user, _user);

    context.SaveChanges();
}

Entity framework will only update the fields that have actually changed.

Pretty sure that's about all you need.


问:
Can't import dependency installed with Cocoapods
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

```<code># Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end
</code>```

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:

答:
Select your Project Target

Go to Build Settings.

Search for Header Search Paths.

Add this value $(SRCROOT)/Pods with recursive, then Xcode will resolve the path for you.

Body:
I've installed FBSDK with Cocoapods but can't import it in my AppDelegate.swift file for some reason. The FBSDK kit appears in my Xcode project so I feel like it should be working.

I'm not an iOS developer by any means, I'm just trying to write a simple native plugin for Flutter SDK. Anyone an idea?

--Here is what the pod file looks like--

# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'

if ENV['FLUTTER_FRAMEWORK_DIR'] == nil
  abort('Please set FLUTTER_FRAMEWORK_DIR to the directory containing Flutter.framework')
end

target 'Runner' do
  use_frameworks!

  # Pods for Runner
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
pod 'FBSDKShareKit'

  # Flutter Pods
  pod 'Flutter', :path => ENV['FLUTTER_FRAMEWORK_DIR']

  if File.exists? '../.flutter-plugins'
    flutter_root = File.expand_path('..')
    File.foreach('../.flutter-plugins') { |line|
      plugin = line.split(pattern='=')
      if plugin.length == 2
        name = plugin[0].strip()
        path = plugin[1].strip()
        resolved_path = File.expand_path("#{path}/ios", flutter_root)
        pod name, :path => resolved_path
      else
        puts "Invalid plugin specification: #{line}"
      end
    }
  end
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['ENABLE_BITCODE'] = 'NO'
    end
  end
end

---EDIT---

I''m getting the following error atm: FBSDKCoreKit.framework: No such file or directory.When I open the Frameworks folder in xCode, all file names are in red:

But that exact folder in Finder is empty. So I guess that's why the error is showing. The question is how to fix this...

This is what my embedded binaries and linked frameworks and libraries look like in the project:


问:
Migration from .NET to angular2: How to redirect old (absolute) links?
Simply put, we want to have our old links redirect to our new routes.  I know how to do this with app-routes.ts, however, it doesn't exactly work.  Example:

    export const ROUTES: Routes = [
      {
        path: 'my-loads',
        component: MyLoadsComponent,
        canActivate: [AuthGuard]
      },
      {
        path: 'Applications/LoadBoard/CarrierBoard.aspx',
        redirectTo: 'my-loads'
      }
    ]

This redirect actually works, but only if the user tries to visit /#/Applications/MyApp/Controller.aspx (with hash), but will NOT work if the user tries to visit /Applications/MyApp/Controller.aspx (without hash, which is the URL users will have bookmarked).

This is because webpack/angular2 apparently uses relative URLs to load ALL of the scripts required to use the site.  It's trying to load script.bundle.js instead of /script.bundle.js, so it turns out to try to load /Applications/MyApp/script.bundle.js. This being the case, if you try to visit an absolute URL other than root, all you get is 404s for the required scripts, so none of the scripts run, and you're presented with "Loading..." and nothing else.

I get that the idea for that sort of compilation is to allow users to build webapps that do NOT reside in the root folder.  This is a good idea, but it is preventing us from redirecting old URLs.  Is there a (correct) way of implementing these redirects within angular2?

答:
Adding a <base href="/"> to the HTML  tag fixes the issue regarding angular trying to load scripts from the wrong path.

To get the route redirecting correctly, we have to remove hashes from our routes in our app.module.ts, changing the RouterModule line to

```<code>(RouterModule.forRoot(ROUTES, { useHash: false })
</code>```

Body:
Adding a <base href="/"> to the HTML <head> tag fixes the issue regarding angular trying to load scripts from the wrong path.

To get the route redirecting correctly, we have to remove hashes from our routes in our app.module.ts, changing the RouterModule line to

(RouterModule.forRoot(ROUTES, { useHash: false })


问:
Service Discovery with Vert.x gRPC and Consul
I have a service which runs a couple of verticles. The main verticle configures the remaining verticles and is also responsible for registering the service with consul. However, my gRPC server cannot run on the same port as the main verticle. Does this mean I need to register each verticle as a separate service, or is there some way to use consul to advertise the correct port for my gRPC server?</p>

答: It seems like tags are the way to go. I can't find the link to the github issue discussing single services with multiple ports, but that was the suggestion. Multiple ports is something being considered for a future API but there are obstacles such as the SRV entries to contend with before this is possible.</p>


问:
C++ How to overwrite data in text file in c++?
```<code>#include<iostream>
#include<fstream>
using namespace std;
string dataFile = "data.txt";
int counter;

int main()
{
    string input ="";
    fstream data;
    data.open(dataFile, ios::app | ios::out | ios::in );
    getline(data, input);
    if (input == "")//The file must be new
    {
        counter = 0;
    }else {
        counter = stoi(input);
    }

    /*
        Program does some stuff that increases the counter
        Right before program ends we update the file
    */
    data.clear();
    data << counter;
    data.close();
    return 0;
}
</code>```

So this is just some example code. The first time you run the program the counter starts at 0, which is accurate. Let's say you get 10 points this run through of the game. Your counter will be 10 when the game ends, and it is stored into the file no problem. So let's reopen the application, you see the counter is 10, cool, and you gain 6 points this time. So in game the counter reads 16. Before the application closes 16 is written to data.txt.

Inside of the data.txt it reads 1016, which is not accurate!

How can I clear the text inside of data.txt right before I write my accurate counter information to the file?

I was reading elsewhere that you cannot clear contents of a file using fstream, is there a more efficient way to overwrite data in a file?

Thank you.

答: Read the file into memory. Update the values. Rewrite the file.</p>

Body:
#include<iostream>
#include<fstream>
using namespace std;
string dataFile = "data.txt";
int counter;

int main()
{
    string input ="";
    fstream data;
    data.open(dataFile, ios::app | ios::out | ios::in );
    getline(data, input);
    if (input == "")//The file must be new
    {
        counter = 0;
    }else {
        counter = stoi(input);
    }

    /*
        Program does some stuff that increases the counter
        Right before program ends we update the file
    */
    data.clear();
    data << counter;
    data.close();
    return 0;
}

So this is just some example code. The first time you run the program the counter starts at 0, which is accurate. Let's say you get 10 points this run through of the game. Your counter will be 10 when the game ends, and it is stored into the file no problem. So let's reopen the application, you see the counter is 10, cool, and you gain 6 points this time. So in game the counter reads 16. Before the application closes 16 is written to data.txt.

Inside of the data.txt it reads 1016, which is not accurate!

How can I clear the text inside of data.txt right before I write my accurate counter information to the file?

I was reading elsewhere that you cannot clear contents of a file using fstream, is there a more efficient way to overwrite data in a file?

Thank you.


问:
Replace instance label with regex
I'm trying to replace the instance label of a given job. I understand that I can do this with the relabel_config. But I struggle with the regex and regex replace stuff.

My targets have an obscure target url like test1.mysite.de. There are reasons why I can't change these, so I need to do some relabeling.

This is my current config:

```<code>relabel_configs:
  - source_labels: [__address__]
    target_label: instance
    regex: ^test.*
    replacement: server
</code>```

But this relabels the url to server. What's my mistake?

答:
I think you want something like:</p>

```<code>regex: ^test(.*)
replacement: instance$1
</code>```

Title: Replace instance label with regex

Body:
I'm trying to replace the instance label of a given job. I understand that I can do this with the relabel_config. But I struggle with the regex and regex replace stuff.

My targets have an obscure target url like test1.mysite.de. There are reasons why I can't change these, so I need to do some relabeling.

This is my current config:

relabel_configs:
  - source_labels: [__address__]
    target_label: instance
    regex: ^test.*
    replacement: server

But this relabels the url to server. What's my mistake?

Body:
I think you want something like:

regex: ^test(.*)
replacement: instance$1


问:
Jenkins Shared Library instantiate util class and use in workflowscript
I'm creating my own Jenkins shared library to reuse some code between pipelines. I know how to create steps (really easy indeed) but I have a problem when I want to make accessible my "utils class" in the jenkinsfile (or WorkflowScript as Jenkins say in logs).
I call "Util class" a groovy class located in folder src/my/domain/... that have many methods, for example, i want to create a log class like this:

```<code># src/my/domain/group

package my.domain.group

class Console implements Serializable {

    def log(msg) {
        spit(msg, '\033[34m')
    }

    def error(msg) {
        spit(msg, '\033[31m')
    }

    def warning(msg){
        spit(msg, '\033[33m')
    }

    def success(msg){
        spit(msg, '\033[32m')
    }

    private def spit(msg, color){
        ansiColor('xterm') {
            echo color + msg + '\033[0m'
        }
    }

}
</code>```

And then I try to instantiate in a file in /vars/library.groovy so can be accessed from the Jenkinsfile with some code as for example:

```<code>node("mynode"){
   console.log("Hello World!")
}
</code>```

The idea is to avoid to instantiate the console in all the script and make it automatically, I have tried several things like

```<code># vars/library.groovy

import my.domain.group.Console
import groovy.transform.Field

@Field String console = new Console()
</code>```

or

```<code># vars/library.groovy

import my.domain.group.Console

def load(){
    this.console = new Console()
    // And also
    console = new Console()
}
</code>```

But when trying to access from jenkins file I always get the error:
groovy.lang.MissingPropertyException: No such property: console for class: WorkflowScript

I understand that this means that the instance is not at the right scope so cannot be directly seen by the script but how can I do that?

Thanks!

答:
Looks like you are using your vars script incorrectly inside your Jenkinsfile, but I will try to solve some confusions :)

Groovy scripts defined in the vars directory are called by their file name as "custom" step in your Jenkinsfile. Assuming your script name stays library.groovy, your Jenkinsfile should look like this

```<code>node ("mynode") {
     library("Hello World!")
}
</code>```

or alternatively (since the parentheses are optional)

```<code>node ("mynode") {
     library "Hello World!"
}
</code>```

Additionally vars scripts should only contain a single function named call and necessary imports. Since you want to pass your log message as a string, the call function additionally needs a parameter. So your library.groovy script in vars could look like this

```<code># vars/library.groovy

import my.domain.group.Console

def call(msg){
    Console console = new Console(steps)
    console.log(msg)
}
</code>```

Inside the call function you can use all basic Jenkins steps (sh, bat, etc.) as you could in your Jenkinsfile, plus any Groovy/Java classes imported via import (like your Console class).

As you may have noticed, I also added a steps variable (which does not have to declared or instantiated manually) to the constructor of your Console class. This is necessary since you cant use any Jenkins steps directly in any of your classes defined in the src directory. Resulting, the method

```<code>private def spit(msg, color){
    ansiColor('xterm') {
        echo color + msg + '\033[0m'
    }
}
</code>```

would not work, because echo is a Jenkins step. In order to use echo inside your class, you can pass the steps variable to the constructor and store it in another variable inside your class. Then you can call all Jenkins steps like steps.echo "Hello World"

```<code># src/my/domain/group

package my.domain.group

class Console implements Serializable {

     def steps

     Console(steps) {
         this.steps = steps
     }

     def log(msg) {
         spit(msg, '\033[34m')
     }

     def error(msg) {
         spit(msg, '\033[31m')
     }

     def warning(msg){
         spit(msg, '\033[33m')
     }

     def success(msg){
         spit(msg, '\033[32m')
     }

     private def spit(msg, color){
         ansiColor('xterm') {
             steps.echo color + msg + '\033[0m'
         }
     }
}
</code>```

That should make it work.

You should think about renaming your library.groovy inside vars though (for example myLog.groovy). Then your Jenkinsfile could look like this

```<code>node ("mynode") {
    myLog "Hello World!"
}
</code>```

In order to use the other methods of your Console class, you can create additional scripts inside vars. Using them could look like this

```<code>node ("mynode") {
    myLog "Hello World!"
    myWarning "Hello World!"
    myError "Hello World!"
    mySuccess "Hello World!"
}
</code>```

(im using the my prefix to avoid name collisions with already existing Jenkins steps. For example, the error step already exists and calling it in your Jenkinsfile will cancel your build)

For more info about shared libraries check out the Jenkins documentation at https://jenkins.io/doc/book/pipeline/shared-libraries/

You can find a complete list of all basic Jenkins steps at https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/

Getting Jenkins and pipelines to work can be a huge hassle, but in the end it's worth it. I hope this wall of text helps a bit. Good luck and happy coding :)

Body:
I'm creating my own Jenkins shared library to reuse some code between pipelines. I know how to create steps (really easy indeed) but I have a problem when I want to make accessible my "utils class" in the jenkinsfile (or WorkflowScript as Jenkins say in logs).
I call "Util class" a groovy class located in folder src/my/domain/... that have many methods, for example, i want to create a log class like this:

# src/my/domain/group

package my.domain.group

class Console implements Serializable {

    def log(msg) {
        spit(msg, '\033[34m')
    }

    def error(msg) {
        spit(msg, '\033[31m')
    }

    def warning(msg){
        spit(msg, '\033[33m')
    }

    def success(msg){
        spit(msg, '\033[32m')
    }

    private def spit(msg, color){
        ansiColor('xterm') {
            echo color + msg + '\033[0m'
        }
    }

}

And then I try to instantiate in a file in /vars/library.groovy so can be accessed from the Jenkinsfile with some code as for example:

node("mynode"){
   console.log("Hello World!")
}

The idea is to avoid to instantiate the console in all the script and make it automatically, I have tried several things like

# vars/library.groovy

import my.domain.group.Console
import groovy.transform.Field

@Field String console = new Console()

or

# vars/library.groovy

import my.domain.group.Console

def load(){
    this.console = new Console()
    // And also
    console = new Console()
}

But when trying to access from jenkins file I always get the error:
groovy.lang.MissingPropertyException: No such property: console for class: WorkflowScript

I understand that this means that the instance is not at the right scope so cannot be directly seen by the script but how can I do that?

Thanks!

Body:
Looks like you are using your vars script incorrectly inside your Jenkinsfile, but I will try to solve some confusions :)

Groovy scripts defined in the vars directory are called by their file name as "custom" step in your Jenkinsfile. Assuming your script name stays library.groovy, your Jenkinsfile should look like this

node ("mynode") {
     library("Hello World!")
}

or alternatively (since the parentheses are optional)

node ("mynode") {
     library "Hello World!"
}

Additionally vars scripts should only contain a single function named call and necessary imports. Since you want to pass your log message as a string, the call function additionally needs a parameter. So your library.groovy script in vars could look like this

# vars/library.groovy

import my.domain.group.Console

def call(msg){
    Console console = new Console(steps)
    console.log(msg)
}

Inside the call function you can use all basic Jenkins steps (sh, bat, etc.) as you could in your Jenkinsfile, plus any Groovy/Java classes imported via import (like your Console class).

As you may have noticed, I also added a steps variable (which does not have to declared or instantiated manually) to the constructor of your Console class. This is necessary since you cant use any Jenkins steps directly in any of your classes defined in the src directory. Resulting, the method

private def spit(msg, color){
    ansiColor('xterm') {
        echo color + msg + '\033[0m'
    }
}

would not work, because echo is a Jenkins step. In order to use echo inside your class, you can pass the steps variable to the constructor and store it in another variable inside your class. Then you can call all Jenkins steps like steps.echo "Hello World"

# src/my/domain/group

package my.domain.group

class Console implements Serializable {

     def steps

     Console(steps) {
         this.steps = steps
     }

     def log(msg) {
         spit(msg, '\033[34m')
     }

     def error(msg) {
         spit(msg, '\033[31m')
     }

     def warning(msg){
         spit(msg, '\033[33m')
     }

     def success(msg){
         spit(msg, '\033[32m')
     }

     private def spit(msg, color){
         ansiColor('xterm') {
             steps.echo color + msg + '\033[0m'
         }
     }
}

That should make it work.

You should think about renaming your library.groovy inside vars though (for example myLog.groovy). Then your Jenkinsfile could look like this

node ("mynode") {
    myLog "Hello World!"
}

In order to use the other methods of your Console class, you can create additional scripts inside vars. Using them could look like this

node ("mynode") {
    myLog "Hello World!"
    myWarning "Hello World!"
    myError "Hello World!"
    mySuccess "Hello World!"
}

(im using the my prefix to avoid name collisions with already existing Jenkins steps. For example, the error step already exists and calling it in your Jenkinsfile will cancel your build)

For more info about shared libraries check out the Jenkins documentation at https://jenkins.io/doc/book/pipeline/shared-libraries/

You can find a complete list of all basic Jenkins steps at https://jenkins.io/doc/pipeline/steps/workflow-basic-steps/

Getting Jenkins and pipelines to work can be a huge hassle, but in the end it's worth it. I hope this wall of text helps a bit. Good luck and happy coding :)


问:
Shorten if statement with same condition
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

```<code>bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}
</code>```

答: If you had the int data stored in an array, you could do a include check and made the if statement a single conditional.

Body:
Is there a way to shorten an if statement like this:

if(x == 1 && y == 1 && z == 1) -> if((x && y && z) == 1) or if((x,y,z) == 1)

Edit: Sorry for the inconvenience. Did it quick on my phone. Here is a full example:

This is a part of my connect fours game.

bool checkwin(string player) {
    for (int i = 0; i<10; i++) {
        for (int j = 0; j<10; j++) {
            if (grid[i][j] == player && grid[i + 1][j] == player && grid[i + 2][j] == player && grid[i + 3][j] == player) {
                return 1;
            }
            if (grid[i][j] == player && grid[i][j + 1] == player && grid[i][j + 2] == player && grid[i][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i + 1][j + 1] == player && grid[i + 2][j + 2] == player && grid[i + 3][j + 3] == player) {
                return 1;
            }

            if (grid[i][j] == player && grid[i - 1][j + 1] == player && grid[i - 2][j + 2] == player && grid[i - 3][j + 3] == player) {
                return 1;
            }
        }
    }
}


问:
HTML5 acronym tag replacement using jQuery
Using jQuery, how would you replace every <acronym> tag with ?

答:
Something along the lines of:

```<code>$('acronym').each(function(i, el) {
    $(this).replaceWith($('<abbr></abbr>').html($(this).html()));
});
</code>```

http://jsfiddle.net/7H4G6/1/

Edit: You'll want to copy attributes too if you have any... Took for granted that you don't.

Christian

Body:
Something along the lines of:

$('acronym').each(function(i, el) {
    $(this).replaceWith($('<abbr></abbr>').html($(this).html()));
});

http://jsfiddle.net/7H4G6/1/

Edit: You'll want to copy attributes too if you have any... Took for granted that you don't.

Christian