问:
Vue-Head => How can i change the information in the meta function asynchronously

Am trying to change the social sharing meta tags of my website to the data that is coming from the back-end database through an API call

```<code>head: {
// To use "this" in the component, it is necessary to return the object through a function
title: function () {
  return {
    inner: this.title
  }
},
meta: function () {
  return [
     { name: 'description', content: this.meta.description, id: 'desc' },
     { name: 'application-name', content: this.meta.application_name },
    // Twitter
    { name: 'twitter:title', content: this.title },
    // with shorthand
    { n: 'twitter:description', c: this.meta.description },
    // Google+ / Schema.org
    { itemprop: 'name', content: this.meta.application_name },
    { itemprop: 'description', content: this.meta.description },
    // Facebook / Open Graph
    { property: 'fb:app_id', content: '150240095600075' },
    { property: 'og:title', content: this.title },
    // with shorthand
    { p: 'og:image', c: 'http://jekalowa.com/static/favicon.png' }
  ]
}
</code>```

}

then in my method object

```<code>methods: {
getAsyncData: function () {
  var self = this
  window.setTimeout(function () {
    self.title = self.artist.stagename + ' | ' + self.title
    self.meta: function () {
      return [
         { name: 'description', content: this.meta.description, id: 'desc' },
         { name: 'application-name', content: this.meta.application_name },
        // Twitter
        { name: 'twitter:title', content: this.title },
        // with shorthand
        { n: 'twitter:description', c: this.meta.description },
        // Google+ / Schema.org
        { itemprop: 'name', content: this.meta.application_name },
        { itemprop: 'description', content: this.meta.description },
        // Facebook / Open Graph
        { property: 'fb:app_id', content: '150240095600075' },
        { property: 'og:title', content: this.title },
        // with shorthand
        { p: 'og:image', c: 'http://example.com/static/favicon.png' }
      ]
    }
    self.$emit('updateHead')
  }, 3000)
}
</code>```

}

I want the social sharing meta tags like Facebook, Twitter, LinkedIn and Google+ and other meta tag information of the page to change when the page has been fully rendered(mounted or loaded) since all the information is coming from the back-end database so that when a user shares the page to Facebook, Twitter, LinkedIn and Google+ the image, title, description and information will be that which came from the database.

i get these error when webpack compiles the code:

Parsing error: Unexpected token, expected ;

答:
There does seem to be an issue here I think:

```<code>self.title = self.artist.stagename + ' | ' + self.title
self.meta: function () {
</code>```

Don't you have to say:

```<code>self.meta = function() ... OR { ... } ?
</code>```

I think there is definitely a syntax error here.

Body:
Am trying to change the social sharing meta tags of my website to the data that is coming from the back-end database through an API call

head: {
// To use "this" in the component, it is necessary to return the object through a function
title: function () {
  return {
    inner: this.title
  }
},
meta: function () {
  return [
     { name: 'description', content: this.meta.description, id: 'desc' },
     { name: 'application-name', content: this.meta.application_name },
    // Twitter
    { name: 'twitter:title', content: this.title },
    // with shorthand
    { n: 'twitter:description', c: this.meta.description },
    // Google+ / Schema.org
    { itemprop: 'name', content: this.meta.application_name },
    { itemprop: 'description', content: this.meta.description },
    // Facebook / Open Graph
    { property: 'fb:app_id', content: '150240095600075' },
    { property: 'og:title', content: this.title },
    // with shorthand
    { p: 'og:image', c: 'http://jekalowa.com/static/favicon.png' }
  ]
}

}

then in my method object

methods: {
getAsyncData: function () {
  var self = this
  window.setTimeout(function () {
    self.title = self.artist.stagename + ' | ' + self.title
    self.meta: function () {
      return [
         { name: 'description', content: this.meta.description, id: 'desc' },
         { name: 'application-name', content: this.meta.application_name },
        // Twitter
        { name: 'twitter:title', content: this.title },
        // with shorthand
        { n: 'twitter:description', c: this.meta.description },
        // Google+ / Schema.org
        { itemprop: 'name', content: this.meta.application_name },
        { itemprop: 'description', content: this.meta.description },
        // Facebook / Open Graph
        { property: 'fb:app_id', content: '150240095600075' },
        { property: 'og:title', content: this.title },
        // with shorthand
        { p: 'og:image', c: 'http://example.com/static/favicon.png' }
      ]
    }
    self.$emit('updateHead')
  }, 3000)
}

}

I want the social sharing meta tags like Facebook, Twitter, LinkedIn and Google+ and other meta tag information of the page to change when the page has been fully rendered(mounted or loaded) since all the information is coming from the back-end database so that when a user shares the page to Facebook, Twitter, LinkedIn and Google+ the image, title, description and information will be that which came from the database.

i get these error when webpack compiles the code:

Parsing error: Unexpected token, expected ;

Body:
There does seem to be an issue here I think:

self.title = self.artist.stagename + ' | ' + self.title
self.meta: function () {

Don't you have to say:

self.meta = function() ... OR { ... } ?

I think there is definitely a syntax error here.


来源: stackexchange

问:
django python date time set to midnight
I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same)

```<code>end_date = lastItem.pub_date
</code>```

currently the end date is 2002-01-11 12:34:56
What do I need to do to get this to change it to 00:00:00?

i tried:

```<code>end_date.hour = '00'
</code>```

but got: 'datetime.datetime' object attribute 'time' is read-only

答:
For tz-aware dates it should be:</p>

```<code>datetime.combine(dt.date(), datetime.min.time(), dt.tzinfo)
</code>```

ContentLicense: CC BY-SA 3.0

Title: django python date time set to midnight

Body:
I have a date time of my django object but it can be any time of the day. It can be at any time through the day, but I need to set my time to 00:00:00 (and another date to 23:59:59 but the principle will be the same)

end_date = lastItem.pub_date

currently the end date is 2002-01-11 12:34:56
What do I need to do to get this to change it to 00:00:00?

i tried:

end_date.hour = '00'

but got: 'datetime.datetime' object attribute 'time' is read-only

Body:
For tz-aware dates it should be:

datetime.combine(dt.date(), datetime.min.time(), dt.tzinfo)


问:
Why does Foldable inherit from Functor in Frege?
In Haskell, the class Foldable is standalone i.e.

```<code>class Foldable t where ...
</code>```

However, in Frege:

```<code>class Functor t => Foldable t where ...
</code>```

Why was this constraint introduced? What ill-formed programs/ideas can it rule out?

It prevented me from defining an instance Foldable HashSet, where HashSet is a custom data type which wraps Data.HashMap to provide a set-based interface. (It can be worked around by applying toList first, so it's not a serious issue.)

答: I think this discussion give you the whole feedback on the topic (especially part about Sets) Haskell : An example of a Foldable which is not a Functor (or not Traversable)?</p>

Body:
In Haskell, the class Foldable is standalone i.e.

class Foldable t where ...

However, in Frege:

class Functor t => Foldable t where ...

Why was this constraint introduced? What ill-formed programs/ideas can it rule out?

It prevented me from defining an instance Foldable HashSet, where HashSet is a custom data type which wraps Data.HashMap to provide a set-based interface. (It can be worked around by applying toList first, so it's not a serious issue.)


问:
Possible to copy specific characters of a file based on a predefined condition?
Possible to copy specific characters  of a file based on a predefined condition?

I have a method which copies a file, I need to add more functionality to this method so that characters before the = will solely be copied.

Current Config File:

```<code>runInTFS=true
browser=chrome
</code>```

My method will copy the file above to a new file (.properties) but nothing more:

public static void copyConfigFileForTFS(String configPropertiesDirectory, String tfsConfigPropertiesDirectory) throws IOException {
    FileReader in = null;
    FileWriter out = null;

```<code>try {
    in = new FileReader(configPropertiesDirectory);
    out = new FileWriter(tfsConfigPropertiesDirectory);

    int c;
    while ((c = in.read()) != -1) {
        char singleChararcter = (char) c;
        out.write(singleChararcter);
    }

} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}
</code>```

}

The method above will add a | after each character (For Testing purposes) i need a way to read :

Existing file (File which i will copy):

```<code>runInTFS=true
browser=chrome
url=example.com
</code>```

New output File should look like (All characters after = need to be removed):

```<code>runInTFS
browser
url
</code>```

I have the following method which will read and output the characters from the old file to the new file, I can append characters to singleChararcter and in turn will reflect the new file but how do I only read and write characters before the = on each line?

答:
Because you are reading a properties files and you are looking just for the keys, you can also load the file content into an instance of a java.util.Properties and then loop over the keys.

```<code>Properties prop = new Properties();
InputStream input = new FileInputStream(youtInputFile);

prop.load(input); // load the properties file

OutputStreamos = new FileOutputStream("yourOutPutFile");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

for(Object key: prop.keySet()) {  // loop over the property keys
    bw.write(key.toString());
    bw.newLine();
}
</code>```

This can give you the possibility to use Properties like browser=chrome=aaa=bbb=ccc=ddd without been concerned by the number of the position of the = sign

Body:
Possible to copy specific characters  of a file based on a predefined condition?

I have a method which copies a file, I need to add more functionality to this method so that characters before the = will solely be copied.

Current Config File:

runInTFS=true
browser=chrome

My method will copy the file above to a new file (.properties) but nothing more:

public static void copyConfigFileForTFS(String configPropertiesDirectory, String tfsConfigPropertiesDirectory) throws IOException {
    FileReader in = null;
    FileWriter out = null;

try {
    in = new FileReader(configPropertiesDirectory);
    out = new FileWriter(tfsConfigPropertiesDirectory);

    int c;
    while ((c = in.read()) != -1) {
        char singleChararcter = (char) c;
        out.write(singleChararcter);
    }

} finally {
    if (in != null) {
        in.close();
    }
    if (out != null) {
        out.close();
    }
}

}

The method above will add a | after each character (For Testing purposes) i need a way to read :

Existing file (File which i will copy):

runInTFS=true
browser=chrome
url=example.com

New output File should look like (All characters after = need to be removed):

runInTFS
browser
url

I have the following method which will read and output the characters from the old file to the new file, I can append characters to singleChararcter and in turn will reflect the new file but how do I only read and write characters before the = on each line?

Body:
Because you are reading a properties files and you are looking just for the keys, you can also load the file content into an instance of a java.util.Properties and then loop over the keys.

Properties prop = new Properties();
InputStream input = new FileInputStream(youtInputFile);

prop.load(input); // load the properties file

OutputStreamos = new FileOutputStream("yourOutPutFile");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));

for(Object key: prop.keySet()) {  // loop over the property keys
    bw.write(key.toString());
    bw.newLine();
}

This can give you the possibility to use Properties like browser=chrome=aaa=bbb=ccc=ddd without been concerned by the number of the position of the = sign


问:
Ansible: How to pip install with --upgrade
I want to pip install with --upgrade, using Ansible.

What's the syntax?

答:
Eventually found the answer here:
https://groups.google.com/forum/#!topic/ansible-project/a19JEpdXzck

this is the syntax:

```<code>- name: install the package, force upgrade
  pip:
    name: <your package name>
    extra_args: --upgrade
</code>```

Body:
Eventually found the answer here:
https://groups.google.com/forum/#!topic/ansible-project/a19JEpdXzck

this is the syntax:

- name: install the package, force upgrade
  pip:
    name: <your package name>
    extra_args: --upgrade


问:
Custom errormessage for property converter
Is it possible to use a ressource to set the errormessage on a property convert error?

```<code>[Range(0, 10, ErrorMessageResourceName = "Error", ErrorMessageResourceType = typeof(Properties.Resources))]
[DataMember]
public int MyProperty
{
  get; set;
}
</code>```

The problem occourres if I try to set MyProperty to "aaa". I get an error saying "Cannot convert 'aaa'". It is that message that I wish to customize.

答:
A really good way to do this would be within a Try/Catch statement. The following is in VB.net, as I'm not yet perfectly well versed in VB.

Try
'Your code for setting the property.
Catch
MessageBox.Show("Your error message text here", "Your Error Title Here", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

Basically, you are going to create a try/catch statement, with the code for setting the property under "Try". Then, under "Catch", you're going to show a message box.

ContentLicense: CC BY-SA 2.5

Body:
Is it possible to use a ressource to set the errormessage on a property convert error?

[Range(0, 10, ErrorMessageResourceName = "Error", ErrorMessageResourceType = typeof(Properties.Resources))]
[DataMember]
public int MyProperty
{
  get; set;
}

The problem occourres if I try to set MyProperty to "aaa". I get an error saying "Cannot convert 'aaa'". It is that message that I wish to customize.


问:
XHR failed loading: POST java spring
I am trying to send data from my jsp page to my controller with ajax.
However i cant get it done and everytime i get the error shown in the title of the post.

JSP content: (This is my modal where i load all my users, i want to add them to a project by sending both my users id and my current projects id to my controller)

```<code><div class="modal fade" id="myModal" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">×</button>
                    <h4 class="modal-title"></h4>
                </div>
                <div class="modal-body">
                    <h1 class="text-center">UserList</h1>
                    <br><br>
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>Photo</th>
                                <th>Firstname</th>
                                <th>Lastname</th>
                                <th>Function</th>
                                <th>Email</th>
                            </tr>
                        </thead>
                        <tbody>
                            <c:forEach var="u" items="${users}">
                                <tr>
                                    <td><img src="${u.getPhoto()}"
                                             alt="Alternate Text" class="img-responsive" /></td>
                                    <td>${u.getFirstname()}</td>
                                    <td>${u.getLastname()}</td>
                                    <td>${u.getFunction()}</td>
                                    <td>${u.getEmail()}</td>
                                    <td><Button type="Button" onclick="myFunction()" id="addButton" class="btn btn-default">Add</button></td>
                            <input type="hidden" id="currentProjectId" value="${p.getProjectId()}">
                            <input type="hidden" id="userId" value="${u.getUserId()}">
                            </tr>
                        </c:forEach>
                        </tbody>
                    </table>

                    <script>
                        function myFunction()
                        {
                            var currentProjectId = $('#currentProjectId').val();
                            var userId = $('#userId').val();

                            $.ajax({
                                type: "POST",
                                contentType: "application/json",
                                url: "addUserToProject",
                                data: JSON.stringify({projectId: currentProjectId, userId: userId}),
                                dataType: 'json',
                                timeout: 600000,
                                success: function (data) {
                                    console.log("SUCCESS: ", data);
                                },
                                error: function (e) {
                                    console.log("ERROR: ", e);
                                }
                            });
                        }
                    </script>

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

Controller content:

```<code>@RequestMapping(value = "/addUserToProject", method = RequestMethod.POST)
public @ResponseBody
String addUser(@RequestParam("projectId") String projectId, @RequestParam("userId") String userId) {

    UUID uid = UUID.fromString(userId);
    UUID pid = UUID.fromString(projectId);
    User u = UserList.getInstance().readUserById(uid);
    Project p = ProjectList.getInstance().readProjectByID(pid);

    ProjectList.getInstance().addUsertoProject(u, p);
    return "redirect:/projectpage";
}
</code>```

The result i get now looks like this:
Console output

What am i doing wrong here? any help would be very much appreciated!

答:
You should pass the parameters to the url that you would like to post, such as:

```<code>url: "/addUserToProject?projectId=" + currentProjectId + "&userId=" + userId;
</code>```

And don't forget to remove 'data' section from your ajax post.

PS: If you want to use 'data' in your ajax request, you need to remove @RequestParam annotation from your Java method. Instead, you can create a new model class and put the parameters along with their getter and setter methods. Pass that model to the Java method using @RequestBody annotation. Then you can use "data" in your ajax request.

Title: XHR failed loading: POST java spring

Body:
I am trying to send data from my jsp page to my controller with ajax.
However i cant get it done and everytime i get the error shown in the title of the post.

JSP content: (This is my modal where i load all my users, i want to add them to a project by sending both my users id and my current projects id to my controller)

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

UserList

                                Photo
                                Firstname
                                Lastname
                                Function
                                Email

                            <c:forEach var="u" items="${users}">

                                    ${u.getFirstname()}
                                    ${u.getLastname()}
                                    ${u.getFunction()}
                                    ${u.getEmail()}
                                    <Button type="Button" onclick="myFunction()" id="addButton" class="btn btn-default">Add</button>
                            <input type="hidden" id="currentProjectId" value="${p.getProjectId()}">
                            <input type="hidden" id="userId" value="${u.getUserId()}">

                        </c:forEach>

Controller content:

@RequestMapping(value = "/addUserToProject", method = RequestMethod.POST)
public @ResponseBody
String addUser(@RequestParam("projectId") String projectId, @RequestParam("userId") String userId) {

    UUID uid = UUID.fromString(userId);
    UUID pid = UUID.fromString(projectId);
    User u = UserList.getInstance().readUserById(uid);
    Project p = ProjectList.getInstance().readProjectByID(pid);

    ProjectList.getInstance().addUsertoProject(u, p);
    return "redirect:/projectpage";
}

The result i get now looks like this:
Console output

What am i doing wrong here? any help would be very much appreciated!

Body:
You should pass the parameters to the url that you would like to post, such as:

url: "/addUserToProject?projectId=" + currentProjectId + "&userId=" + userId;

And don't forget to remove 'data' section from your ajax post.

PS: If you want to use 'data' in your ajax request, you need to remove @RequestParam annotation from your Java method. Instead, you can create a new model class and put the parameters along with their getter and setter methods. Pass that model to the Java method using @RequestBody annotation. Then you can use "data" in your ajax request.


问:
Is there a way to implement some gui (message box that asks for multiple inputs ie. registration document) into a code ive written
I just want a simple popup message box that asks for multiple inputs and such.

```<code>System.out.println("Please enter  Name");
Name = name.nextLine();
System.out.println("Please enter  Age");
age=ages.nextInt();
System.out.println("Please enter  Gender");
Gender =gender.nextLine();
System.out.println("Please enter  Contact Number");
ConNum =number.nextLine();-->
</code>```

Is there a way to make a gui for this? (its a foundation level project)

答:
As @notyou mentioned you can use JOptionPane it's very simple to implement it into you code check this example :

```<code>import java.io.*;
import javax.swing.*;

public class SystemOutDialog {
    public static void main(String[] args) {

        // set up a custom print stream
        CustomPrintStream printStream = new CustomPrintStream();
        System.setOut(printStream);

        // from now on, the System.out.println() will shows a dialog message

        System.out.println("hello!");
        System.out.println("how are you?");
    }
}

class CustomPrintStream extends PrintStream {
    public CustomPrintStream() {
        super(new ByteArrayOutputStream());
    }

    public void println(String msg) {
        JOptionPane.showMessageDialog(null, msg);
    }
}
</code>```

Source link

Body:
I just want a simple popup message box that asks for multiple inputs and such.

System.out.println("Please enter  Name");
Name = name.nextLine();
System.out.println("Please enter  Age");
age=ages.nextInt();
System.out.println("Please enter  Gender");
Gender =gender.nextLine();
System.out.println("Please enter  Contact Number");
ConNum =number.nextLine();-->

Is there a way to make a gui for this? (its a foundation level project)

Body:
As @notyou mentioned you can use JOptionPane it's very simple to implement it into you code check this example :

import java.io.*;
import javax.swing.*;

public class SystemOutDialog {
    public static void main(String[] args) {

        // set up a custom print stream
        CustomPrintStream printStream = new CustomPrintStream();
        System.setOut(printStream);

        // from now on, the System.out.println() will shows a dialog message

        System.out.println("hello!");
        System.out.println("how are you?");
    }
}

class CustomPrintStream extends PrintStream {
    public CustomPrintStream() {
        super(new ByteArrayOutputStream());
    }

    public void println(String msg) {
        JOptionPane.showMessageDialog(null, msg);
    }
}

Source link


问:
Extract files from zip without keeping the structure using python ZipFile?
I try to extract all files from .zip containing subfolders in one folder.  I want all the files from subfolders extract in only one folder without keeping the original structure. At the moment, I extract all, move the files to a folder, then remove previous subfolders.  The files with same names are overwrited.

Is it possible to do it before writing files?

Here is a structure for example:

```<code>my_zip/file1.txt
my_zip/dir1/file2.txt
my_zip/dir1/dir2/file3.txt
my_zip/dir3/file4.txt
</code>```

At the end I whish this:

```<code>my_dir/file1.txt
my_dir/file2.txt
my_dir/file3.txt
my_dir/file4.txt
</code>```

What can I add to this code ?

```<code>import zipfile
my_dir = "D:\\Download\\"
my_zip = "D:\\Download\\my_file.zip"

zip_file = zipfile.ZipFile(my_zip, 'r')
for files in zip_file.namelist():
    zip_file.extract(files, my_dir)
zip_file.close()
</code>```

if I rename files path from zip_file.namelist(), I have this error:

```<code>KeyError: "There is no item named 'file2.txt' in the archive"
</code>```

答:
It is possible to iterate over the ZipFile.infolist(). On the returned ZipInfo objects you can then manipulate the filename to remove the directory part and finally extract it to a specified directory.

```<code>import zipfile
import os

my_dir = "D:\\Download\\"
my_zip = "D:\\Download\\my_file.zip"

with zipfile.ZipFile(my_zip) as zip:
    for zip_info in zip.infolist():
        if zip_info.is_dir():
            continue
        zip_info.filename = os.path.basename(zip_info.filename)
        zip.extract(zip_info, my_dir)
</code>```

Body:
I try to extract all files from .zip containing subfolders in one folder.  I want all the files from subfolders extract in only one folder without keeping the original structure. At the moment, I extract all, move the files to a folder, then remove previous subfolders.  The files with same names are overwrited.

Is it possible to do it before writing files?

Here is a structure for example:

my_zip/file1.txt
my_zip/dir1/file2.txt
my_zip/dir1/dir2/file3.txt
my_zip/dir3/file4.txt

At the end I whish this:

my_dir/file1.txt
my_dir/file2.txt
my_dir/file3.txt
my_dir/file4.txt

What can I add to this code ?

import zipfile
my_dir = "D:\\Download\\"
my_zip = "D:\\Download\\my_file.zip"

zip_file = zipfile.ZipFile(my_zip, 'r')
for files in zip_file.namelist():
    zip_file.extract(files, my_dir)
zip_file.close()

if I rename files path from zip_file.namelist(), I have this error:

KeyError: "There is no item named 'file2.txt' in the archive"

Body:
It is possible to iterate over the ZipFile.infolist(). On the returned ZipInfo objects you can then manipulate the filename to remove the directory part and finally extract it to a specified directory.

import zipfile
import os

my_dir = "D:\\Download\\"
my_zip = "D:\\Download\\my_file.zip"

with zipfile.ZipFile(my_zip) as zip:
    for zip_info in zip.infolist():
        if zip_info.is_dir():
            continue
        zip_info.filename = os.path.basename(zip_info.filename)
        zip.extract(zip_info, my_dir)

ContentLicense: CC BY-SA 4.0


问:
Modulus division to get multiples of 10
I'm currently doing a practice where I'm given a non-negative number "num", and return true if num is within 2 of a multiple of 10.

I have the idea of an if statement which would include the below, but a more working / similar version;

```<code>if (num-2 >= (num % 10 == 0) <= num+2);
</code>```

Seems like I'm trying to create a variable with all multiples of 10, however this seems a bit overkill. I feel it's basic arithmetic with something like num-2 >= x <= num+2, where x is a multiple of 10, but what is the solution?

答:
You are looking for numbers that end in 0,1,2,8 or 9, which means</p>

```<code>if (num % 10 <= 2 || num % 10 >= 8)
</code>```

Title: Modulus division to get multiples of 10

Body:
I'm currently doing a practice where I'm given a non-negative number "num", and return true if num is within 2 of a multiple of 10.

I have the idea of an if statement which would include the below, but a more working / similar version;

if (num-2 >= (num % 10 == 0) <= num+2);

Seems like I'm trying to create a variable with all multiples of 10, however this seems a bit overkill. I feel it's basic arithmetic with something like num-2 >= x <= num+2, where x is a multiple of 10, but what is the solution?

Body:
You are looking for numbers that end in 0,1,2,8 or 9, which means

if (num % 10 <= 2 || num % 10 >= 8)


问:
generic callback function with xmlhttp how to send the reference to a function when "this" changes
I am polling a database.
see the "<--------------" in the code below.

This works:

```<code>class MultiplayerGame{
...

...
callPhpWithAjax(url){
    var xmlhttp = new XMLHttpRequest();
    var instance = this;
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            instance.pollResponse(this.responseText); <-----------works, pollResponse is called and I can access the object with "this"
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

poll(){
    var url = "myurl.com"
    this.callPhpWithAjax(url);
}

pollResponse(response){
    this.variable = response;
}
</code>```

}

When I try to implement it a bit more generic, it doesn't work:

```<code>class MultiplayerGame{
...
callPhpWithAjaxGenericNOTWORKING(url,callbackfunction){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            callbackfunction(this.responseText); <----------callbackfunction not calling what I wanted.
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

poll(){
    var url = "myurl.com"
    this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse);  <---------------  it seems like this.pollResponse is not ok. I don't know how to do it.
}

pollResponse(response){
    this.variable = response;  <----- this.variable is undefined. (this is not the class instance i was hoping)
}
</code>```

When I call the function with the callbackfunction, I use "this", but apparently, it does not reference the same object. I am confused here.

How do I send the callbackfunction correctly as a paramenter?

答:
Add .bind(this) when using an object's method as a callback parameter.

So your code inside poll should be

```<code>this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse.bind(this))
</code>```

See Function.prototype.bind()

Body:
I am polling a database.
see the "<--------------" in the code below.

This works:

class MultiplayerGame{
...

...
callPhpWithAjax(url){
    var xmlhttp = new XMLHttpRequest();
    var instance = this;
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            instance.pollResponse(this.responseText); <-----------works, pollResponse is called and I can access the object with "this"
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

poll(){
    var url = "myurl.com"
    this.callPhpWithAjax(url);
}

pollResponse(response){
    this.variable = response;
}

}

When I try to implement it a bit more generic, it doesn't work:

class MultiplayerGame{
...
callPhpWithAjaxGenericNOTWORKING(url,callbackfunction){
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            callbackfunction(this.responseText); <----------callbackfunction not calling what I wanted.
        }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
}

poll(){
    var url = "myurl.com"
    this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse);  <---------------  it seems like this.pollResponse is not ok. I don't know how to do it.
}

pollResponse(response){
    this.variable = response;  <----- this.variable is undefined. (this is not the class instance i was hoping)
}

When I call the function with the callbackfunction, I use "this", but apparently, it does not reference the same object. I am confused here.

How do I send the callbackfunction correctly as a paramenter?

Body:
Add .bind(this) when using an object's method as a callback parameter.

So your code inside poll should be

this.callPhpWithAjaxGenericNOTWORKING(url, this.pollResponse.bind(this))

See Function.prototype.bind()


问:
Protractor: Chrome failed to start - exited abnormally
When i run my spec, it starts up Chrome and instantly opens another tab to the Chrome Settings page.  Totally clueless as to what is going on.  Here is the error message:</p>

```<code>[11:38:54] I/direct - Using ChromeDriver directly...
[11:38:54] I/launcher - Running 1 instances of WebDriver
[11:39:54] E/launcher - unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6),platform=Mac OS X 10.12.6 x86_64)
[11:39:54] E/launcher - WebDriverError: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6),platform=Mac OS X 10.12.6 x86_64)
        at WebDriverError
 (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:27:10)
    at Object.checkLegacyResponse (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:639:15)
    at parseHttpResponse (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:538:13)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:472:11
    at ManagedPromise.invokeCallback_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1379:14)
    at TaskQueue.execute_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
    at TaskQueue.executeNext_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2896:21)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2820:25
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (node.js:438:9)
From: Task: WebDriver.createSession()
    at Function.createSession (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:329:24)
    at Driver (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/chrome.js:778:38)
    at Direct.getNewDriver (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/driverProviders/direct.js:68:26)
    at Runner.createBrowser (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/runner.js:190:43)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/runner.js:264:30
    at _fulfilled (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:834:54)
    at self.promiseDispatch.done (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:863:30)
    at Promise.promise.promiseDispatch (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:796:13)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:556:49
    at runSingle (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:137:13)
[11:39:54] E/launcher - Process exited with error code 199
</code>```

答:
You are using old version of chrome driver. Update all drivers with </p>

```<code>webdriver-manager update
</code>```

Body:
When i run my spec, it starts up Chrome and instantly opens another tab to the Chrome Settings page.  Totally clueless as to what is going on.  Here is the error message:

[11:38:54] I/direct - Using ChromeDriver directly...
[11:38:54] I/launcher - Running 1 instances of WebDriver
[11:39:54] E/launcher - unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6),platform=Mac OS X 10.12.6 x86_64)
[11:39:54] E/launcher - WebDriverError: unknown error: Chrome failed to start: exited abnormally
(Driver info: chromedriver=2.26.436421 (6c1a3ab469ad86fd49c8d97ede4a6b96a49ca5f6),platform=Mac OS X 10.12.6 x86_64)
        at WebDriverError
 (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:27:10)
    at Object.checkLegacyResponse (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/error.js:639:15)
    at parseHttpResponse (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:538:13)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:472:11
    at ManagedPromise.invokeCallback_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1379:14)
    at TaskQueue.execute_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2913:14)
    at TaskQueue.executeNext_ (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2896:21)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2820:25
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:639:7
    at process._tickCallback (node.js:438:9)
From: Task: WebDriver.createSession()
    at Function.createSession (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver.js:329:24)
    at Driver (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/selenium-webdriver/chrome.js:778:38)
    at Direct.getNewDriver (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/driverProviders/direct.js:68:26)
    at Runner.createBrowser (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/runner.js:190:43)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/built/runner.js:264:30
    at _fulfilled (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:834:54)
    at self.promiseDispatch.done (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:863:30)
    at Promise.promise.promiseDispatch (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:796:13)
    at /Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:556:49
    at runSingle (/Users/hoseasteele/.nvm/versions/node/v4.8.4/lib/node_modules/protractor/node_modules/q/q.js:137:13)
[11:39:54] E/launcher - Process exited with error code 199

Body:
You are using old version of chrome driver. Update all drivers with

webdriver-manager update


问:
How to put session value store into database?
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

```<code>$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');
</code>```

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

```<code>array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]
</code>```

答:
I would use the array_get helper.

https://laravel.com/docs/5.5/helpers#method-array-get

```<code>array_get($orders, 'school_id');
</code>```

Additionally you can use a fallback as third parameter in case the value is not present in the session.

Body:
I wanted to retrieve session array and put into other model But throws `

Call to a member function pluck() on array

Controller I used :

$orders =  $request->session()->get('order');
$order = new Order();
$order->school_id = $orders->pluck('school_id');
$order->order_date = $orders->pluck('order_date');
$order->time_slot = $orders->pluck('time_slot');

How do i access the session data and put into other model?

Here is the response I get when i dd() the session :

array:1 [▼
  0 => array:3 [▼
    "school_id" => "4"
    "order_date" => "11/25/2017"
    "time_slot" => "10am - 8pm"
  ]
]

Body:
I would use the array_get helper.

https://laravel.com/docs/5.5/helpers#method-array-get

array_get($orders, 'school_id');

Additionally you can use a fallback as third parameter in case the value is not present in the session.


问:
How to import all databases at a time in wamp
I export whole databases sql file from localhost wamp. Now I want to import all databases and table by importing that one sql file. But I get sql error...database error with name...and following error. Plz give me solution for this.

MySQL said:

```<code>#1046 - No database was selected
</code>```

答: First select your database, then do the import. You can modify your sql file with a use databasename; to select a database for you during import

Body:
I export whole databases sql file from localhost wamp. Now I want to import all databases and table by importing that one sql file. But I get sql error...database error with name...and following error. Plz give me solution for this.

MySQL said:

#1046 - No database was selected


问:
What is an URI in android
I have recently come across an android object that makes no sense to me. I can't understand what is an URI?

Well I checked the Official Documentation and it said:

Immutable URI reference. A URI reference includes a URI and a
  fragment, the component of the URI following a '#'. Builds and parses
  URI references which conform to RFC 2396.

The problem is, you can't use a URI to explain what is a URI! I am totally confused.

I did some research and came across this article. But it said

Uri does nothing

Could someone please explain to me what does this mean!

答:
I am adding details from RFC that center around the abbreviation URI and some examples in use:

From,

http://www.faqs.org/rfcs/rfc2396.html

This document updates and merges "Uniform Resource Locators"

  [RFC1738] and "Relative Uniform Resource Locators" [RFC1808] in order
  to define a single, generic syntax for all URI.

And,

1.1 Overview of URI

URI are characterized by the following definitions:

```<code>  Uniform
     Uniformity provides several benefits: it allows different types
     of resource identifiers to be used in the same context, even
     when the mechanisms used to access those resources may differ;
     it allows uniform semantic interpretation of common syntactic
     conventions across different types of resource identifiers; it
     allows introduction of new types of resource identifiers
     without interfering with the way that existing identifiers are
     used; and, it allows the identifiers to be reused in many
     different contexts, thus permitting new applications or
     protocols to leverage a pre-existing, large, and widely-used
     set of resource identifiers.

  Resource
     A resource can be anything that has identity.  Familiar
     examples include an electronic document, an image, a service
     (e.g., "today's weather report for Los Angeles"), and a
     collection of other resources.  Not all resources are network
     "retrievable"; e.g., human beings, corporations, and bound
     books in a library can also be considered resources.

     The resource is the conceptual mapping to an entity or set of
     entities, not necessarily the entity which corresponds to that
     mapping at any particular instance in time.  Thus, a resource
     can remain constant even when its content---the entities to
     which it currently corresponds---changes over time, provided
     that the conceptual mapping is not changed in the process.

  Identifier
     An identifier is an object that can act as a reference to
     something that has identity.  In the case of URI, the object is
     a sequence of characters with a restricted syntax.
</code>```

Here are some in use:

1.3. Example URI

The following examples illustrate URI that are in common use.

ftp://ftp.is.co.za/rfc/rfc1808.txt
        -- ftp scheme for File Transfer Protocol services

gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
        -- gopher scheme for Gopher and Gopher+ Protocol services

http://www.math.uio.no/faq/compression-faq/part1.html
        -- http scheme for Hypertext Transfer Protocol services

mailto:mduerst@ifi.unizh.ch
        -- mailto scheme for electronic mail addresses

news:comp.infosystems.www.servers.unix
        -- news scheme for USENET news groups and articles

telnet://melvyl.ucop.edu/
        -- telnet scheme for interactive services via the TELNET Protocol

Title: What is an URI in android

Body:
I am adding details from RFC that center around the abbreviation URI and some examples in use:

From,

http://www.faqs.org/rfcs/rfc2396.html

This document updates and merges "Uniform Resource Locators"

  [RFC1738] and "Relative Uniform Resource Locators" [RFC1808] in order
  to define a single, generic syntax for all URI.

And,

1.1 Overview of URI

URI are characterized by the following definitions:

  Uniform
     Uniformity provides several benefits: it allows different types
     of resource identifiers to be used in the same context, even
     when the mechanisms used to access those resources may differ;
     it allows uniform semantic interpretation of common syntactic
     conventions across different types of resource identifiers; it
     allows introduction of new types of resource identifiers
     without interfering with the way that existing identifiers are
     used; and, it allows the identifiers to be reused in many
     different contexts, thus permitting new applications or
     protocols to leverage a pre-existing, large, and widely-used
     set of resource identifiers.

  Resource
     A resource can be anything that has identity.  Familiar
     examples include an electronic document, an image, a service
     (e.g., "today's weather report for Los Angeles"), and a
     collection of other resources.  Not all resources are network
     "retrievable"; e.g., human beings, corporations, and bound
     books in a library can also be considered resources.

     The resource is the conceptual mapping to an entity or set of
     entities, not necessarily the entity which corresponds to that
     mapping at any particular instance in time.  Thus, a resource
     can remain constant even when its content---the entities to
     which it currently corresponds---changes over time, provided
     that the conceptual mapping is not changed in the process.

  Identifier
     An identifier is an object that can act as a reference to
     something that has identity.  In the case of URI, the object is
     a sequence of characters with a restricted syntax.

Here are some in use:

1.3. Example URI

The following examples illustrate URI that are in common use.

ftp://ftp.is.co.za/rfc/rfc1808.txt
        -- ftp scheme for File Transfer Protocol services

gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles
        -- gopher scheme for Gopher and Gopher+ Protocol services

http://www.math.uio.no/faq/compression-faq/part1.html
        -- http scheme for Hypertext Transfer Protocol services

mailto:mduerst@ifi.unizh.ch
        -- mailto scheme for electronic mail addresses

news:comp.infosystems.www.servers.unix
        -- news scheme for USENET news groups and articles

telnet://melvyl.ucop.edu/
        -- telnet scheme for interactive services via the TELNET Protocol


问:
Show only a certain number of contacts
I have developed a program that shows a list of contacts from my phone book.
For this I use the following code:

```<code>    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            if (phones != null) {
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        contactList.add(new Contact(name, phoneNumber, id));
                    }

                phones.close();
            }
        }
        cursor.close();
    }
    adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
    recyclerView.setAdapter(adapter);
</code>```

Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example:
I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on

答:
Use below code that has limit cause. Replace your code with below

```<code>Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' ",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC LIMIT 10");
</code>```

It will get first 10 records. And in pull to refresh implementation, get more records on call back event of pull to refresh. Hope this will help you

Title: Show only a certain number of contacts

Body:
I have developed a program that shows a list of contacts from my phone book.
For this I use the following code:

    ContentResolver cr = getContentResolver();
    Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1'",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
    if (cursor != null && cursor.getCount() > 0) {
        while (cursor.moveToNext()) {
            String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
           Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_URI, String.valueOf(id));
            Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
                    null,
                    ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + id,
                    null,
                    null);
            if (phones != null) {
                    while (phones.moveToNext()) {
                        String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                        contactList.add(new Contact(name, phoneNumber, id));
                    }

                phones.close();
            }
        }
        cursor.close();
    }
    adapter = new ContactAdapter(contactList, R.layout.contacts_list_item, getApplicationContext());
    recyclerView.setAdapter(adapter);

Everything works, and the program displays all contacts from my phone book, but I want a certain number of contacts to be displayed. For example:
I open the program and load the first 50 contacts from the phone book, after scrolling, the next 50 contacts are loaded to the end of the list. and so on

Body:
Use below code that has limit cause. Replace your code with below

Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null,
            ContactsContract.Contacts.HAS_PHONE_NUMBER + " = '1' ",
            null,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC LIMIT 10");

It will get first 10 records. And in pull to refresh implementation, get more records on call back event of pull to refresh. Hope this will help you


答:
Session holds all data in Array and not Collection. Function pluck() can only be used for the collection.

Try doing array_get($orders, 'school_id'); as already mentioned by Marc or just $request->session()->get('order')['school_id'];

Title: How to put session value store into database?


问:
Make linux SPLIT command compatible with Mac OS terminal
I have a bash script that works fine in linux, but when I run it on my Mac terminal it fails, as the options for the splitcommand are slightly different in Mac terminal. My script is:

```<code>## Merge and half final two segments
last_file=`ls temp_filt.snplist_* | tail -n 1`
penultimate_file=`ls temp_filt.snplist_* | tail -n 2 | head -1`
cat $penultimate_file $last_file > temp && mv temp $penultimate_file
split -n l/2 $penultimate_file && mv xaa $penultimate_file; mv xab $last_file
</code>```

The script fails at the final line, since the -n l/2 doesn't exist in tcsh (default shel environment in Mac OS 10.x.x). I was wondering what is the equivalent script in tcsh.

Is there a generic way to run linux script in Mac OS terminal, without the need to change the script?

答:
An option is to use the language built-ins and limit external commands

Note the script contains several flaws: ls is useless and parsing ls output is not safe

```<code>array=(temp_filt.snplist_*)
last_file=${array[ -1]}
penultimate_file=${array[ -2]}
</code>```

If the files are big bash read built-in will be very slow.

A simple solution in this case using cat, wc, head and tail which are compatible between systems. Note when passed in a command variables must be double quoted to avoid word splitting.

```<code>cat "$penultimate_file" "$last_file" > temp || exit 1
nb_lines=$(wc -l < temp)
((half_nb_lines=nb_lines/2))
head "-$half_nb_lines" temp > "$penultimate_file" || exit 1
tail "+$((half_nb_lines+1))" temp > "$last_file" || exit 1
rm temp
</code>```

Note in the last line

```<code>command1 && command2 ; command3
</code>```

the command3 is executed whatever the first exit status, { ; } may be used for grouping commands

```<code>command1 && { command2 ; command3; }
</code>```

Body:
I have a bash script that works fine in linux, but when I run it on my Mac terminal it fails, as the options for the splitcommand are slightly different in Mac terminal. My script is:

## Merge and half final two segments
last_file=`ls temp_filt.snplist_* | tail -n 1`
penultimate_file=`ls temp_filt.snplist_* | tail -n 2 | head -1`
cat $penultimate_file $last_file > temp && mv temp $penultimate_file
split -n l/2 $penultimate_file && mv xaa $penultimate_file; mv xab $last_file

The script fails at the final line, since the -n l/2 doesn't exist in tcsh (default shel environment in Mac OS 10.x.x). I was wondering what is the equivalent script in tcsh.

Is there a generic way to run linux script in Mac OS terminal, without the need to change the script?

Body:
An option is to use the language built-ins and limit external commands

Note the script contains several flaws: ls is useless and parsing ls output is not safe

array=(temp_filt.snplist_*)
last_file=${array[ -1]}
penultimate_file=${array[ -2]}

If the files are big bash read built-in will be very slow.

A simple solution in this case using cat, wc, head and tail which are compatible between systems. Note when passed in a command variables must be double quoted to avoid word splitting.

cat "$penultimate_file" "$last_file" > temp || exit 1
nb_lines=$(wc -l < temp)
((half_nb_lines=nb_lines/2))
head "-$half_nb_lines" temp > "$penultimate_file" || exit 1
tail "+$((half_nb_lines+1))" temp > "$last_file" || exit 1
rm temp

Note in the last line

command1 && command2 ; command3

the command3 is executed whatever the first exit status, { ; } may be used for grouping commands

command1 && { command2 ; command3; }


问:
Matlab Draw a line of pixels (Vector to Raster image)
Really basic, I have a series of points while will create a line. I would like to turn that line into a series of pixels on a plane

```<code>x = [10 33 50];
y = [50 30 9];

imshow(BW); hold on;
plot(x,y)
</code>```

I originally had an idea of drawing the line by using poly2mask and expand it by drawing the line  from a 90 angle.

```<code>scalefactor = .08;

X1 = XData(1,1) - scalefactor*abs(YData(1,2) - YData(1,1));
X2 = XData(1,1) + scalefactor*abs(YData(1,2) - YData(1,1));
X3 = XData(1,2) + scalefactor*abs(YData(1,2) - YData(1,1));
X4 = XData(1,3) + scalefactor*abs(YData(1,2) - YData(1,3));
X5 = XData(1,3) - scalefactor*abs(YData(1,2) - YData(1,3));
X6 = XData(1,2) - scalefactor*abs(YData(1,2) - YData(1,1));

Y1 = YData(1,1) - scalefactor*abs(XData(1,2) - XData(1,1));
Y2 = YData(1,1) + scalefactor*abs(XData(1,2) - XData(1,1));
Y3 = YData(1,2) + scalefactor*abs(XData(1,2) - XData(1,1));
Y4 = YData(1,3) + scalefactor*abs(XData(1,2) - XData(1,3));
Y5 = YData(1,3) - scalefactor*abs(XData(1,2) - XData(1,3));
Y6 = YData(1,2) - scalefactor*abs(XData(1,2) - XData(1,1));

Xvect = [X1 X2 X3 X4 X5 X6];
Yvect = [Y1 Y2 Y3 Y4 Y5 Y6];

Lineimg = poly2mask(Xvect,Yvect,400,500);
</code>```

Problem with this was that if the line turned upside down, it would pretty much disappear. Now I'm thinking of just drawing a line of pixels and then diluting it. Question is how to draw the line.

答:
We consider whether a line can pass these points.

If you randomly choose three points in a plane, generically, they are non-collinear. This is called in general position. However, an arc can do this job. We fit these points with an arc.

```<code>Trial>> x = [10 33 50];
Trial>> y = [50 30 9];
Trial>> p = polyfit(x,y,1);
</code>```

P is the mathematical model of the line that you want. The next is to generate pixels. Suppose that we want the x coordinates of pixels vary from ten to fifteen.

```<code>x1 = linspace(10,50);
</code>```

With the mathematical model p, we calculate the y coordinates of pixels.

```<code>y1 = polyval(p,x1);
</code>```

Now, we draw the generated pixels and the given points together to see the result.

```<code>plot(x,y,'o')
hold on
plot(x1,y1)
hold off
</code>```

It is not exactly pass the given points; however, it is the line that is nearest these points from in the viewpoint of the polynomial curve fitting.

Body:
Really basic, I have a series of points while will create a line. I would like to turn that line into a series of pixels on a plane

x = [10 33 50];
y = [50 30 9];

imshow(BW); hold on;
plot(x,y)

I originally had an idea of drawing the line by using poly2mask and expand it by drawing the line  from a 90 angle.

scalefactor = .08;

X1 = XData(1,1) - scalefactor*abs(YData(1,2) - YData(1,1));
X2 = XData(1,1) + scalefactor*abs(YData(1,2) - YData(1,1));
X3 = XData(1,2) + scalefactor*abs(YData(1,2) - YData(1,1));
X4 = XData(1,3) + scalefactor*abs(YData(1,2) - YData(1,3));
X5 = XData(1,3) - scalefactor*abs(YData(1,2) - YData(1,3));
X6 = XData(1,2) - scalefactor*abs(YData(1,2) - YData(1,1));

Y1 = YData(1,1) - scalefactor*abs(XData(1,2) - XData(1,1));
Y2 = YData(1,1) + scalefactor*abs(XData(1,2) - XData(1,1));
Y3 = YData(1,2) + scalefactor*abs(XData(1,2) - XData(1,1));
Y4 = YData(1,3) + scalefactor*abs(XData(1,2) - XData(1,3));
Y5 = YData(1,3) - scalefactor*abs(XData(1,2) - XData(1,3));
Y6 = YData(1,2) - scalefactor*abs(XData(1,2) - XData(1,1));

Xvect = [X1 X2 X3 X4 X5 X6];
Yvect = [Y1 Y2 Y3 Y4 Y5 Y6];

Lineimg = poly2mask(Xvect,Yvect,400,500);

Problem with this was that if the line turned upside down, it would pretty much disappear. Now I'm thinking of just drawing a line of pixels and then diluting it. Question is how to draw the line.

Body:
We consider whether a line can pass these points.

If you randomly choose three points in a plane, generically, they are non-collinear. This is called in general position. However, an arc can do this job. We fit these points with an arc.

Trial>> x = [10 33 50];
Trial>> y = [50 30 9];
Trial>> p = polyfit(x,y,1);

P is the mathematical model of the line that you want. The next is to generate pixels. Suppose that we want the x coordinates of pixels vary from ten to fifteen.

x1 = linspace(10,50);

With the mathematical model p, we calculate the y coordinates of pixels.

y1 = polyval(p,x1);

Now, we draw the generated pixels and the given points together to see the result.

plot(x,y,'o')
hold on
plot(x1,y1)
hold off

It is not exactly pass the given points; however, it is the line that is nearest these points from in the viewpoint of the polynomial curve fitting.


问:
How can I make my code more efficient in R - It's to repetitive
I have a question regarding the efficiency of my code. I have 9 data frames in my environment and for each of them I need to perform the same steps. The steps and the code is (only shown for two of the data frames):

```<code>CDL <- aggregate(A$Frequency, by=list(Category=A$Words), FUN=sum)
wordcloud(words = CDL$Category, freq = CDL$x, min.freq = 2,
      max.words=250, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(6, "Dark2"))

Ltd <- aggregate(B$Frequency, by=list(Category=B$Words), FUN=sum)
wordcloud(words = Ltd$Category, freq = Ltd$x, min.freq = 2,
      max.words=250, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(6, "Dark2"))
</code>```

I first aggregate all the same words, sum their frequencies and then create a world cloud based on the aggregated results.

The object names in the environment start from 'A' and go all the way to 'I'. The variable 'Frequency' is just a number, the variable 'Words' contains a list of the words.

For the wordcloud:
The variable 'Category' contains the unique words taken from the 'Words' variable and 'x' is the aggregated sum of Frequencies taken from 'Frequency'

Is there any way I could perform the same but without repeating my code? Thanks

答:
If I am not mistaken, defining a function and loop it should work!

```<code>word_cloud <- function(df) {
  temp <- aggregate(df[,"Frequency"], by=list(Category=df[,"Words"]), FUN=sum)
  result <- wordcloud(words = temp[,"Category"],
    freq = temp[,"x"],
    min.freq = 2,
    max.words=250,
    random.order=FALSE,
    rot.per=0.35,
    colors=brewer.pal(6, "Dark2"))
  return(result)
}

input_list <- list(A,B,C,D,E,F,G,H,I)

for (df_inp in input_list) {
  word_cloud(df_inp)
}
</code>```

I do not know the output mode of wordcloud(), so you may want to save the results to a list or plot it! I hope that helps!

Body:
I have a question regarding the efficiency of my code. I have 9 data frames in my environment and for each of them I need to perform the same steps. The steps and the code is (only shown for two of the data frames):

CDL <- aggregate(A$Frequency, by=list(Category=A$Words), FUN=sum)
wordcloud(words = CDL$Category, freq = CDL$x, min.freq = 2,
      max.words=250, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(6, "Dark2"))

Ltd <- aggregate(B$Frequency, by=list(Category=B$Words), FUN=sum)
wordcloud(words = Ltd$Category, freq = Ltd$x, min.freq = 2,
      max.words=250, random.order=FALSE, rot.per=0.35,
      colors=brewer.pal(6, "Dark2"))

I first aggregate all the same words, sum their frequencies and then create a world cloud based on the aggregated results.

The object names in the environment start from 'A' and go all the way to 'I'. The variable 'Frequency' is just a number, the variable 'Words' contains a list of the words.

For the wordcloud:
The variable 'Category' contains the unique words taken from the 'Words' variable and 'x' is the aggregated sum of Frequencies taken from 'Frequency'

Is there any way I could perform the same but without repeating my code? Thanks

Body:
If I am not mistaken, defining a function and loop it should work!

word_cloud <- function(df) {
  temp <- aggregate(df[,"Frequency"], by=list(Category=df[,"Words"]), FUN=sum)
  result <- wordcloud(words = temp[,"Category"],
    freq = temp[,"x"],
    min.freq = 2,
    max.words=250,
    random.order=FALSE,
    rot.per=0.35,
    colors=brewer.pal(6, "Dark2"))
  return(result)
}

input_list <- list(A,B,C,D,E,F,G,H,I)

for (df_inp in input_list) {
  word_cloud(df_inp)
}

I do not know the output mode of wordcloud(), so you may want to save the results to a list or plot it! I hope that helps!


问:
Using Text::CSV to print a line on a csv files based on variables content
My script is fairly large but I'll simplify the code here.
Suppose that I create a CSV and I write the header like this:

```<code>my $csv = Text::CSV->new ({binary => 1}, eol => "\n");
open(my $out, ">", "$dir/out.csv") or die $!; #create
$out->print("CodeA,CodeB,Name,Count,Pos,Orientation\n"); #I write the header
</code>```

Suppose that I got the some values stored in different variables and I want to write those variables as a line in the CSV.
I cannot figure out how, because on the Text::CSV documentation the print is not clearly explained, there's no direct examples and i don't know what an array ref is.

答:
```<code>#!/usr/bin/perl
use strict;
use warnings;

use Text::CSV;

my $file = $ARGV[0] or die "Need to get CSV file on the command line\n";

my $csv = Text::CSV->new ({
  binary    => 1,
  auto_diag => 1,
  sep_char  => ','    # not really needed as this is the default
});

my $sum = 0;
open(my $data, '<:encoding(utf8)', $file) or die "Could not open '$file' $!\n";
while (my $fields = $csv->getline( $data )) {
  $sum += $fields->[2];
}
if (not $csv->eof) {
  $csv->error_diag();
}
close $data;
print "$sum\n";
</code>```

Body:
My script is fairly large but I'll simplify the code here.
Suppose that I create a CSV and I write the header like this:

my $csv = Text::CSV->new ({binary => 1}, eol => "\n");
open(my $out, ">", "$dir/out.csv") or die $!; #create
$out->print("CodeA,CodeB,Name,Count,Pos,Orientation\n"); #I write the header

Suppose that I got the some values stored in different variables and I want to write those variables as a line in the CSV.
I cannot figure out how, because on the Text::CSV documentation the print is not clearly explained, there's no direct examples and i don't know what an array ref is.


问:
Check if mountpoint exists but file does not
I am saving a list of files (absolute paths to a file). It can be of an internal storage or may be external storage.

While syncing those file to the Cloud (i.e. Google Drive), I am checking if file is exists or not at local(File.exists()), and if it does not delete it from the cloud.

But, when the external storage is not mounted, that is causing me to delete the file from the cloud. But, that should not happen. If the mount point is not available it should not check for the file. How can I check that condition?

For example, Files in the internal & external storage looks something like:

Internal: /storage/emulated/0/internal.txt

External: /storage/4XXX-1234/Android/media/com.example/Documents/external.txt

How can I check if storage is mounted only then check for the file existence?

答:
Just check if the directory exists.

So for instance check first if directory /storage/4XXX-1234 exists before use.

You can also check if directory /storage/4XXX-1234/Android/media/com.example/Documents exists before use.

```<code>String path = "/storage/4XXX-1234/Android/media/com.example/Documents/external.txt";

File file = new File (path);

if(!file.getParentFile().exists())
    return; // no dir. Not mounted
</code>```

Body:
Just check if the directory exists.

So for instance check first if directory /storage/4XXX-1234 exists before use.

You can also check if directory /storage/4XXX-1234/Android/media/com.example/Documents exists before use.

String path = "/storage/4XXX-1234/Android/media/com.example/Documents/external.txt";

File file = new File (path);

if(!file.getParentFile().exists())
    return; // no dir. Not mounted


问:
Filter by Bundle Drupal 8 Link Autocomplete
Does anyone know how to limit the autocomplete suggestions of Link Fields to only certain bundles -- not globally, but per Link Field  instance? I nearly found a solution in customizing https://github.com/minnur/Alter-Entity-Autocomplete , but this is global for all autocompletes, and I need to get the calling Link Field instance somehow.</p>

答:
I have written the following Drupal contributed module to solve the issue:

Link Field Autocomplete Filter

The module adds a Link Field configuration for filtering the allowed
content types in the autocomplete field.

You can install the module manually with the drupal core Update Manager module (must be enabled) using the Drupal backend:
http://yourSite/admin/reports/updates/install
and follow the instructions there.

Using Drush, you can install it with:

```<code>drush dl link_field_autocomplete_filter; // download
drush en link_field_autocomplete_filter; // enable the module
</code>```

You can also us Composer to download the module:

```<code>composer require drupal/link_field_autocomplete_filter
</code>```

Simply enable the module, and a series of checkboxes (one for each content type) will appear in the Link Field field-instance configuration form. If you check none, then all content types will appear as suggestions in the autocomplete. Otherwise only those checked will appear.

Body:
I have written the following Drupal contributed module to solve the issue:

Link Field Autocomplete Filter

The module adds a Link Field configuration for filtering the allowed
content types in the autocomplete field.

You can install the module manually with the drupal core Update Manager module (must be enabled) using the Drupal backend:
http://yourSite/admin/reports/updates/install
and follow the instructions there.

Using Drush, you can install it with:

drush dl link_field_autocomplete_filter; // download
drush en link_field_autocomplete_filter; // enable the module

You can also us Composer to download the module:

composer require drupal/link_field_autocomplete_filter

Simply enable the module, and a series of checkboxes (one for each content type) will appear in the Link Field field-instance configuration form. If you check none, then all content types will appear as suggestions in the autocomplete. Otherwise only those checked will appear.


问:
When using JASPIC for authentication, is web.xml still relevant in terms of authentication?
It's been a loooooong time since I've done JASPIC work.

I have a web.xml that looks like this:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>service-broker-related-resources</web-resource-name>
      <url-pattern>/v2/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>emcc</role-name>
    </auth-constraint>
  </security-constraint>

  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>Frob Service Broker</realm-name>
  </login-config>

  <security-role>
    <role-name>emcc</role-name>
  </security-role>

</web-app>
</code>```

I have a Server Authentication Module (SAM) set up and installed as well.  It is mentioned in my glassfish-web.xml like this:

```<code><!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app httpservlet-security-provider="emccSAM">
</code>```

My SAM works fine.

In fact, it works a little too well!  It is intercepting all requests, not just the ones identified by the <url-pattern> of /v2/*.  That initially surprised me.

But then when I think hard about this, I think this makes a certain amount of sense: the SAM is now in charge of authentication, not the container, really.

So is the web.xml now essentially irrelevant?

Then I think some more about it and clearly it's relevant, because its contents also say what to do after authentication has taken place, i.e. if the user authenticated successfully through the SAM, now check to see if she has the emcc role.  If she does not, and, presumably, the request starts with /v2/, then we boot her out.  If she does not, and, presumably, the request starts with anything else, then we let her in.

So is it expected behavior, then, that my SAM has to effectively decide all on its own whether the incoming request deserves authentication?  I would expect that my SAM would be triggered "normally", i.e. only when someone attempts to access a URI that requires authentication, as described by the <security-constraint>.

It might be worth noting that the only servlet in play is the one installed by default when a JAX-RS Application class is annotated with @ApplicationPath("/v2").

答:
A SAM is indeed fully in charge of authentication. It may respect the declarative configuration, but is not required to. It could even perform authorization of Servlet requests on its own entirely (although doing so would fall well outside its contract's scope).

As per § 3.8.3 of the JASPIC spec, it is mandated that validateRequest be invoked on the configured ServerAuthContext (hence its single encapsulated SAM as well, in this case) "on every request that satisfies the corresponding connection requirements".

If a SAM wishes to know whether a Servlet endpoint should, descriptor- or annotation-wise, be considered "protected", it may call isMandatory on the request MessagePolicy argument relayed to it at initialization time, or probe, at message authentication time, the MessageInfo argument's map for presence of the "javax.security.auth.message.MessagePolicy.isMandatory" key and a mapped value equal to Boolean.valueOf(value).booleanValue() == true (spec § 3.8.1.1).

Last but not least -- are declarative security constraints irrelevant in terms of authorization? First of all I am unsure whether the various specs are okay with a SAM assigning undeclared roles. That aside, I haven't ever tried this, so I can only guess and provide a vague answer at this point. My take on this is that it would be more or less the same as with the authentication provider's case. You are essentially taking the responsibility of configuring the provider away from the AS, hence you must somehow compensate, i.e., provide alternative configuration interfaces. Say authorization is managed by some JACC provider. If it's the default, AS-provided one, it would, in the absence of declarative security constraints, fail to acknowledge the fact that a caller needs to be in the "emcc" role in order to access the /v2/* collection of resources, i.e., have an equivalent WebRoleRefPermission mapped to their Principal; thus, Policy::implies would always grant access. But a handcrafted provider, like a custom SAM, could retrieve that knowledge from elsewhere, such that @RolesAllowed and friends delegating to it still work. After all it is not as if the Java EE security model -- including the "plumbing" of populating Subjects, binding them to requests' threads' AccessControlContexts, handling Subject::doAs(Privileged) calls, and so forth -- became irrelevant, only how the provider obtains the constraints has. Naturally, the question whether your requirements justify the hassle, remains.

Body:
It's been a loooooong time since I've done JASPIC work.

I have a web.xml that looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                             http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
  <security-constraint>
    <web-resource-collection>
      <web-resource-name>service-broker-related-resources</web-resource-name>
      <url-pattern>/v2/*</url-pattern>
    </web-resource-collection>
    <auth-constraint>
      <role-name>emcc</role-name>
    </auth-constraint>
  </security-constraint>

  <login-config>
    <auth-method>BASIC</auth-method>
    <realm-name>Frob Service Broker</realm-name>
  </login-config>

  <security-role>
    <role-name>emcc</role-name>
  </security-role>

</web-app>

I have a Server Authentication Module (SAM) set up and installed as well.  It is mentioned in my glassfish-web.xml like this:

<!DOCTYPE glassfish-web-app PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Servlet 3.0//EN" "http://glassfish.org/dtds/glassfish-web-app_3_0-1.dtd">
<glassfish-web-app httpservlet-security-provider="emccSAM">

My SAM works fine.

In fact, it works a little too well!  It is intercepting all requests, not just the ones identified by the <url-pattern> of /v2/*.  That initially surprised me.

But then when I think hard about this, I think this makes a certain amount of sense: the SAM is now in charge of authentication, not the container, really.

So is the web.xml now essentially irrelevant?

Then I think some more about it and clearly it's relevant, because its contents also say what to do after authentication has taken place, i.e. if the user authenticated successfully through the SAM, now check to see if she has the emcc role.  If she does not, and, presumably, the request starts with /v2/, then we boot her out.  If she does not, and, presumably, the request starts with anything else, then we let her in.

So is it expected behavior, then, that my SAM has to effectively decide all on its own whether the incoming request deserves authentication?  I would expect that my SAM would be triggered "normally", i.e. only when someone attempts to access a URI that requires authentication, as described by the <security-constraint>.

It might be worth noting that the only servlet in play is the one installed by default when a JAX-RS Application class is annotated with @ApplicationPath("/v2").


问:
Check a weighted number range with switches in jQuery
I'm trying to have a random generator, that has some more common and more rare results, but it doesn't seem to work. Nothing happens when I click the button, that is supposed to generate the result. I used code I found here (jquery Using ranges in switch cases?) in other answers, but maybe it wasn't the right choice for my problem?</p>

```<code>function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return x; }
    else { return !raceNumber; }
}

function race() {
    var raceNumber = Math.floor((Math.random()*100)+1);
    switch (raceNumber) {
        case checkRange(raceNumber, 1,14):
            return "Ambrier";
            break;
        case checkRange(raceNumber, 15,28):
            return "Barbar";
            break;
        case checkRange(raceNumber, 29,42):
            return "Wechselbalg";
            break;
        case checkRange(raceNumber, 43,56):
            return "Oger";
            break;
        case checkRange(raceNumber, 57,70):
            return "Kobold";
            break;
         case checkRange(raceNumber, 71,76):
            return "Zwerg";
            break;
         case checkRange(raceNumber, 77,82):
            return "Elf";
            break;
         case checkRange(raceNumber, 83,88):
            return "Entführter Mensch";
            break;
         case checkRange(raceNumber, 89,94):
            return "Troll";
            break;
         case checkRange(raceNumber, 95,100):
            return "Untoter";
            break;
    }
}
</code>```

答:
Modify the checkRange() function. Because x is undefined in your case.

replace

```<code>function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return x; }
    else { return !raceNumber; }
}
</code>```

by

```<code>function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return raceNumber ; }
    else { return !raceNumber; }
}
</code>```

Body:
I'm trying to have a random generator, that has some more common and more rare results, but it doesn't seem to work. Nothing happens when I click the button, that is supposed to generate the result. I used code I found here (jquery Using ranges in switch cases?) in other answers, but maybe it wasn't the right choice for my problem?

function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return x; }
    else { return !raceNumber; }
}

function race() {
    var raceNumber = Math.floor((Math.random()*100)+1);
    switch (raceNumber) {
        case checkRange(raceNumber, 1,14):
            return "Ambrier";
            break;
        case checkRange(raceNumber, 15,28):
            return "Barbar";
            break;
        case checkRange(raceNumber, 29,42):
            return "Wechselbalg";
            break;
        case checkRange(raceNumber, 43,56):
            return "Oger";
            break;
        case checkRange(raceNumber, 57,70):
            return "Kobold";
            break;
         case checkRange(raceNumber, 71,76):
            return "Zwerg";
            break;
         case checkRange(raceNumber, 77,82):
            return "Elf";
            break;
         case checkRange(raceNumber, 83,88):
            return "Entführter Mensch";
            break;
         case checkRange(raceNumber, 89,94):
            return "Troll";
            break;
         case checkRange(raceNumber, 95,100):
            return "Untoter";
            break;
    }
}

Body:
Modify the checkRange() function. Because x is undefined in your case.

replace

function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return x; }
    else { return !raceNumber; }
}

by

function checkRange(raceNumber, n, m) {
    if (raceNumber >= n && raceNumber <= m) { return raceNumber ; }
    else { return !raceNumber; }
}


问:
Why would you ever call .call() on Observable functions?
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

```<code>ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }
</code>```

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated

答:
To understand it, first you can have a look at the predefined JavaScript function method "call":

```<code>var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.call(myObject);  // Will return "Mary Doe"
</code>```

The reason of calling "call" is to invoke a function in object "person" and pass the context to it "myObject".

Similarly, the reason of this calling "call" below:

```<code>const inputValues$ = _do.call(this._valueChanges, value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
});
</code>```

is providing the context "this._valueChanges", but also provide the function to be called base on that context, that is the second parameter, the anonymous function

```<code>value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
}
</code>```

In the example that you're using:

this._valueChanges is the Input Event Observerable

The _do.call is for doing some side affects whenever the event input happens, then it returns a mirrored Observable of the source Observable (the event observable)

UPDATED
Example code: https://plnkr.co/edit/dJNRNI?p=preview

About the do calling:

You can call it on an Observable like this:

```<code>const source = Rx.Observable.of(1,2,3,4,5);
const example = source
.do(val => console.log(`BEFORE MAP: ${val}`))
.map(val => val + 10)
.do(val => console.log(`AFTER MAP: ${val}`));
const subscribe = example.subscribe(val => console.log(val));
</code>```

In this case you don't have to pass the first parameter as the context "Observable".

But when you call it from its own place like you said, you need to pass the first parameter as the "Observable" that you want to call on. That's the different.

as @Fan Cheung mentioned, if you don't want to call it from its own place, you can do it like:

```<code>const inputValues$=this._valueChanges.do(value=>{
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
})
</code>```

Body:
I am a relative beginner in Angular, and I am struggling to understand some source I am reading from the ng-bootstrap project. The source code can be found here.

I am very confused by the code in ngOnInit:

ngOnInit(): void {
    const inputValues$ = _do.call(this._valueChanges, value => {
      this._userInput = value;
      if (this.editable) {
        this._onChange(value);
      }
    });
    const results$ = letProto.call(inputValues$, this.ngbTypeahead);
    const processedResults$ = _do.call(results$, () => {
      if (!this.editable) {
        this._onChange(undefined);
      }
    });
    const userInput$ = switchMap.call(this._resubscribeTypeahead, () => processedResults$);
    this._subscription = this._subscribeToUserInput(userInput$);
  }

What is the point of calling .call(...) on these Observable functions? What kind of behaviour is this trying to achieve? Is this a normal pattern?

I've done a lot of reading/watching about Observables (no pun intended) as part of my Angular education but I have never come across anything like this. Any explanation would be appreciated

Body:
To understand it, first you can have a look at the predefined JavaScript function method "call":

var person = {
    firstName:"John",
    lastName: "Doe",
    fullName: function() {
        return this.firstName + " " + this.lastName;
    }
}
var myObject = {
    firstName:"Mary",
    lastName: "Doe",
}
person.fullName.call(myObject);  // Will return "Mary Doe"

The reason of calling "call" is to invoke a function in object "person" and pass the context to it "myObject".

Similarly, the reason of this calling "call" below:

const inputValues$ = _do.call(this._valueChanges, value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
});

is providing the context "this._valueChanges", but also provide the function to be called base on that context, that is the second parameter, the anonymous function

value => {
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
}

In the example that you're using:

this._valueChanges is the Input Event Observerable

The _do.call is for doing some side affects whenever the event input happens, then it returns a mirrored Observable of the source Observable (the event observable)

UPDATED
Example code: https://plnkr.co/edit/dJNRNI?p=preview

About the do calling:

You can call it on an Observable like this:

const source = Rx.Observable.of(1,2,3,4,5);
const example = source
.do(val => console.log(`BEFORE MAP: ${val}`))
.map(val => val + 10)
.do(val => console.log(`AFTER MAP: ${val}`));
const subscribe = example.subscribe(val => console.log(val));

In this case you don't have to pass the first parameter as the context "Observable".

But when you call it from its own place like you said, you need to pass the first parameter as the "Observable" that you want to call on. That's the different.

as @Fan Cheung mentioned, if you don't want to call it from its own place, you can do it like:

const inputValues$=this._valueChanges.do(value=>{
  this._userInput = value;
  if (this.editable) {
    this._onChange(value);
  }
})


问:
Missing .jar in Java Build Path with backslaches in path
I am adding new version of TestNG library. So I downloaded new testng-6.13.1.jar to the folder .../tools/testng, and trying to add reference to it the same way I did for previous version. But new jar is added with backslashes in path and is defined as (missing) by the IDE:

Why is it so?

答: If jar is inside somewhere in the workspace use Add JARs... open in this case it will use relative path but if the jar is outside the workspace then use Add External JARs... option which will point to the absolute jar file.</p>


问:
Cross-Platform Scanning Library
For a long time, it has annoyed me that you need special software for creating a multi-page PDF document from a flatbed scanner. Because "scanner" is an ambiguous word (which REALLY makes searching difficult!) let me clarify: I mean, for example, the process by which an HP F4280 printer/scanner device optically "scans" a paper document and creates a digital representation of it, usually ending up as a a .jpg or .tif file.

The problem is that I know of no program that is cross-platform, and capable of creating multi-page scans from a flatbed scanner. To do this, the software has to store each scanned page, one at a time, and ask the user if they want to scan another page. You cannot rely on the driver to handle multi-page scanning, because drivers only do that for form feed scanners that will "suck in" a stack of paper without pause, and combine the data before handing it off to the driver framework.

I am therefore starting on the road to creating such a program. At the low level, I want to support the TWAIN and SANE interfaces, on Windows XP or later, Mac OS X, and popular Linux 2.6 distros of approx. 2008 or later vintage.

Here is how I envision it will work. First, I need a library that provides a uniform API regardless of whether it is using TWAIN or SANE on the backend. The API must be able to provide a byte array of the bits, compressed or otherwise, of the scanned data. A few properties that are shared between TWAIN and SANE should be exposed: for example, the DPI, paper size, and color/grayscale/lineart. Then it should be possible to either specify explicitly, hint, or query the resulting image format of the byte array that is returned from a successful scan.

I'm not particularly concerned with the programming environment: I am familiar with all the popular imperative/OO languages. I'd prefer something like Java or C#, but C or C++ would work fine too.

Once I have such a library in hand, I can construct a GUI that just calls the routines as needed, and use one of several available PDF rendering libraries to create the output. I don't insist on "compile once, run anywhere", but I do insist on "write once, compile anywhere" at the least. Of course, because TWAIN and SANE are different APIs that are available on mutually-exclusive platforms, there will have to be at some point some #ifdefs or other method of distinguishing between platforms to determine which API to use.

I intend for my program and any libraries I directly link against to qualify as Free Software (per the FSF), but the only requirement I have of the programming environment is that it is available equivalently on Windows XP or later, Mac OS X, and Linux 2.6.

I've been googling quite a lot to find such a library, but I can't even find a proprietary one, let alone a free software one. If anyone has found such a gem, please provide me a link -- otherwise, any advice on getting started with my application would be appreciated. If necessary, I will do the development of the above-mentioned library myself, and release it as a separate project under the GNU LGPL. For the application's sake, I'd prefer to write it in Qt4/C++, .NET with GTK#, or Java/Swing, for maximum cross platform compatibility.

答: Unfortunatly, TWAIN is a severely limited standard.  Most manufacturers implement only enough TWAIN functionality to run their own GUI.   Trying to use lower level TWAIN functionality and your own GUI is not a practical solution unless you are really targeting a particular scanner.</p>

Title: Cross-Platform Scanning Library


问:
Vue.js - Pagination
I have the following pagination component.

If users adds remove items dynamically i.e via some ajax call, how do i ensure the correct active or disabled classes are applied on the pagination links?

For example if the user is currently on the last page which only has 1 item, if the user deletes that item, the pagination links re-render but then i lose the active disable class becuase that page no longer exists. i.e. the links should update to move the user to previous page.

```<code> <div class="comment-pager ">
    <div class="panel panel-default panel-highlight no-border ">
        <div class="panel-body padded-5">
            <nav v-if="totalItems > pageSize">
                <ul class="pagination">
                    <li v-bind:class="[currentPage == 1 ? disabled : '']">
                        <a v-on:click.prevent="previous()" aria-label="Previous">
                        <span aria-hidden="true">«</span>
                        </a>
                    </li>
                    <li v-bind:class="[currentPage == pages ? active : '']" v-for="page in pages" v-on:click.prevent="changePage(page)">
                        <a>{{ page }}</a>
                    </li>
                    <li v-bind:class="[currentPage == pages.length ? disabled : '']">
                        <a v-on:click.prevent="next()" aria-label="Next">
                        <span aria-hidden="true">»</span>
                        </a>
                    </li>
                </ul>
            </nav>
        </div>
   </div>
</div>

</template>

<script>

export default {

    props: ['totalItems', 'pageSize']

    data: function () {

        return {
            currentPage: 1,
            pages: [],
        }

    },

    watch: {
        totalItems: function () {

           var pagesCount = Math.ceil(this.totalItems / this.pageSize);
           this.pages = [];
           for (var i = 1; i <= pagesCount; i++)
            this.pages.push(i);
        }
    },

    methods: {

        changePage: function (page){

            this.currentPage = page;
            this.$emit('pageChanged', page);
        }

        previous: function (){
            if (this.currentPage == 1)
                return;

            this.currentPage--;

            this.$emit('pageChanged', this.currentPage);
        }

        next: function () {
            if (this.currentPage == this.pages.length)
                return;

            this.currentPage++;

            this.$emit('pageChanged', this.currentPage);
        }
    },

}

</script>

  <paginator v-bind:total-items="totalItems" v-bind:page-size="query.pageSize" v-on:pageChanged="onPageChange"></paginator>
</code>```

答:
You probably want to use watch property of a Vue instance.

```<code> var vm = new Vue({
  data: {
    count: 1
  },
  watch: {
    count: function (val, oldVal) {
      console.log('new: %s, old: %s', val, oldVal)
    }
})
</code>```

Title: Vue.js - Pagination

Body:
I have the following pagination component.

If users adds remove items dynamically i.e via some ajax call, how do i ensure the correct active or disabled classes are applied on the pagination links?

For example if the user is currently on the last page which only has 1 item, if the user deletes that item, the pagination links re-render but then i lose the active disable class becuase that page no longer exists. i.e. the links should update to move the user to previous page.

             pageSize">

                        «

                        {{ page }}

                        »

</template>

  <paginator v-bind:total-items="totalItems" v-bind:page-size="query.pageSize" v-on:pageChanged="onPageChange"></paginator>

Body:
You probably want to use watch property of a Vue instance.

 var vm = new Vue({
  data: {
    count: 1
  },
  watch: {
    count: function (val, oldVal) {
      console.log('new: %s, old: %s', val, oldVal)
    }
})