问:
PHP Mobile Detect Script Slowdown
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

```<code><?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>
</code>```

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?

答: WordPress have a built-in function wp_is_mobile() to check if users using mobile or not. So you don't have to include and using unnessacry external script or function.

Title: PHP Mobile Detect Script Slowdown

Body:
I'm trying to integrate the PHP version of the mobile detection script from http://mobiledetect.net/ into my Wordpress installation.

I've used the following code to call and detect mobile usage

<?php
    include 'includes/Mobile_Detect.php';
    $detect = new Mobile_Detect;
    $isMobile = $detect->isMobile();
    if($isMobile) {
        //Do a thing;
    };
?>

While the code does work, I've found that the loading time of the page has risen by 1-2 seconds on a consistent basis. I've run some tests and just the include statement itself is causing a major slowdown.

Is this normal when using this script or is there supposed to be a better way to implement it?


来源: stackexchange

问:
Printing a Continuous Curve - MatplotLib
I am trying to implement a neural network in Python, and I want to plot the cost per iteration.

Here is what my current code looks like -

```<code>import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

for i in range(50000):

    if (i % 500 == 0):
        y = np.random.random()  # Cost Function.
        ax.scatter(i, y, label ='Cost')

plt.show()
</code>```

Here is the output -

Problem

The plot does not show one continuous curve. Instead, it shows different points in different colours depicting the (i, y) tuple at each iteration.

Also, the 'Label' is being printed on the legend for 100 times, which obviously is not what I want.

I am trying to print a continuous curve, and one legend.

I have tried ax.plot() instead of ax.scatter(), but it does not work.

Can someone please help? I am new to Python, and I am sure I am missing out something basic. I have tried searching for the answer in Google, but I am not getting anything definite.

Thanks !

答:
Using scatter will always plot points.  The plot function had a large selection of parameters (including the ability to plot points) with the default as plotting line segments between pairs of points.  Feeding plot a single point x, y at each step in a for loop such as:

```<code>for x,y in zip(range(10), range(10)):
    plt.plot(x, y)
</code>```

will not show anything.  This is because matplotlib is trying to draw a line between each of the input value of x and y.  Since only one value is passed at each step, it is drawing a line from (x,y) to (None, None), resulting in no line at all.

To plot a continuous line, you need to collect all of your coordinate pairs into an iterable (list, array, etc), and pass them to plot.

```<code>x = []
y = []
for i in range(50000):
    if (i % 500 == 0):
        x.append(i)
        y.append(np.random.random())  # Cost Function.
ax.plot(x, y, label ='Cost')
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement a neural network in Python, and I want to plot the cost per iteration.

Here is what my current code looks like -

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10, 8))
ax = fig.add_subplot(1, 1, 1)

for i in range(50000):

    if (i % 500 == 0):
        y = np.random.random()  # Cost Function.
        ax.scatter(i, y, label ='Cost')

plt.show()

Here is the output -

Problem

The plot does not show one continuous curve. Instead, it shows different points in different colours depicting the (i, y) tuple at each iteration.

Also, the 'Label' is being printed on the legend for 100 times, which obviously is not what I want.

I am trying to print a continuous curve, and one legend.

I have tried ax.plot() instead of ax.scatter(), but it does not work.

Can someone please help? I am new to Python, and I am sure I am missing out something basic. I have tried searching for the answer in Google, but I am not getting anything definite.

Thanks !

Body:
Using scatter will always plot points.  The plot function had a large selection of parameters (including the ability to plot points) with the default as plotting line segments between pairs of points.  Feeding plot a single point x, y at each step in a for loop such as:

for x,y in zip(range(10), range(10)):
    plt.plot(x, y)

will not show anything.  This is because matplotlib is trying to draw a line between each of the input value of x and y.  Since only one value is passed at each step, it is drawing a line from (x,y) to (None, None), resulting in no line at all.

To plot a continuous line, you need to collect all of your coordinate pairs into an iterable (list, array, etc), and pass them to plot.

x = []
y = []
for i in range(50000):
    if (i % 500 == 0):
        x.append(i)
        y.append(np.random.random())  # Cost Function.
ax.plot(x, y, label ='Cost')


问:
All support libraries must use the exact same version specification.Found 27.0.1.26.1.0
I am struggling with gradle build error i followed this this and this but none working for me. It was working fine but once i update Exoplayer lib to 2.6 from current but even after reverse i am getting same error. Also when i tried to followed First answer i am getting 7000+ errors in gradle build.

My libraries

答:
Hi Ritu you can update support lib version to 27.0.1 to make it work you also need to change compile SDK version to 27
No need to change target SDk it can be whatever below 27.
One more tips use gradle variable to use version so that it can be consistent and can be changed easily

Edit
Also you need to include google maven path

```<code>  maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
</code>```

Or google() if using latest gradle version ie. 3+

Body:
Hi Ritu you can update support lib version to 27.0.1 to make it work you also need to change compile SDK version to 27
No need to change target SDk it can be whatever below 27.
One more tips use gradle variable to use version so that it can be consistent and can be changed easily

Edit
Also you need to include google maven path

  maven {
            url 'https://maven.google.com/'
            name 'Google'
        }

Or google() if using latest gradle version ie. 3+


问:
Algorithm for optimal "intersection" of two results?
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

```<code>1. Karl
2. Fred
3. John
4. Peter
5. Sid
</code>```

Race 2.

```<code>1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin
</code>```

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out

答:
You can relate the positions to weights (think of it as points)
For instance 1st position has a weight of 20. 2nd has 18. 3rd 16, etc.

Participation miss could relate to a weight of -5.
You can adjust the numbers as required.

To find the final result you add everyone's weights and compare the numbers.

I think it should work..

ContentLicense: CC BY-SA 2.5

Body:
I have two results and like to get the best "order" of both these.
Example:

We have a race with 5 people in one race, and 7 in another. The outcome is:
Race 1.

1. Karl
2. Fred
3. John
4. Peter
5. Sid

Race 2.

1. Steven
2. John
3. Karl
4. Peter
5. Aron
6. Fred
7. Kevin

The questin is: whats the top 7 of both these races?

Its quite obvious that that nr 1 is Karl in this case, since he hold one 1st place and one 3rd, which is better than Johns second and third place. However, Steven could be equally good but he did only participate in one race and should suffer some kind of penalty for that.

What are the known algorithms for this problem? Are there any trivial solutions? I just can't figure it out


问:
Why is there an extra space in between a variable and punctuation in a string? Python
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

```<code>def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")
</code>```

This is the output it gives.

```<code>Right... So your name is Raven .
</code>```

How do I get rid of the space in between the name and the punctuation?

答:
The comma indicates a continuation on the same line with a space in between (you'll notice there's a space between "is" and "Raven", even though neither string has one in there). If you want to remove the spaces, the usual way to concatenate strings is with a plus

Edit: Plus, not ampersand... stupid me

Body:
There is an extra space in the output of a string. This is the section of the code where it happens. It happens in the string of the function, nameConfirmation().

def chooseName():
    name = ""
    name = raw_input("Let's begin with your name. What is it? ")

    return name

def nameConfirmation():
    name = chooseName()
    print ("Right... So your name is", name,".")

This is the output it gives.

Right... So your name is Raven .

How do I get rid of the space in between the name and the punctuation?


答:
You can append string with +.

```<code>print ("Right... So your name is", name + ".")
</code>```

Output:

```<code>Right... So your name is Raven.
</code>```

Title: Why is there an extra space in between a variable and punctuation in a string? Python

Body:
You can append string with +.

print ("Right... So your name is", name + ".")

Output:

Right... So your name is Raven.


问:
Unexpected results with if statement using passport.js

Hi, to explain my app briefly:
I have a User Schema and a "Tweet" Schema (Actually it's a 'Post' Schema but to avoid confusion with the 'post' method let's call it a "Tweet Schema').

User's have many "tweets" , but a "tweet" only has one User (like twitter). Inside my tweet schema I have a key of Original_Poster, which is a reference to the id of the User who created the post (see below for schema).

In a route to update a tweet, I have an if else statement to confirm if the tweet that the user is trying to update, is actually their tweet. This is functioning while using locally created users with mongodb/mongoose, but not with users created through passport-facebook.

Here is the if else statement:

```<code>        if(req.user._id == post.original_poster){
            console.log('nice')
        }else{
            console.log(req.user._id, post.original_poster);
            console.log(typeof req.user._id, typeof post.original_poster)
            console.log('wtf')
        }
</code>```

What I expect to see is in my console is:
 'nice'

What I am actually seeing is:

```<code>5a288913fa0d78257fd7b4d3 5a288913fa0d78257fd7b4d3
object object
wtf
</code>```

Clearly they are the same user ids, and the type is the same (though this shouldn't matter as I am using the double equals not the triple equals).

Can anyone explain this?

Edit:
Here is the full Post.find({}) for more info:

```<code>Post.findOne({_id: req.params.id}).then((post)=>{
    if(req.user._id == post.original_poster){
        console.log('nice')
    }else{
        console.log(req.user._id, post.original_poster);
        console.log(typeof req.user._id, typeof post.original_poster)
        console.log('wtf')
    }
})
</code>```

答:
Figured it out, though the answer is a bit weird to me, if anyone can explain why this works, please feel free to explain below

I changed if(req.user._id == post.original_poster) to if(String(req.user._id) == post.original_poster) and now 'nice' is being console.logged. Though this is a bit strange to me because I am using the == double equals not the === so the types of the things under comparison should not be considered.

```<code>if(String(req.user._id) == post.original_poster){
                console.log('nice')
            }else{
                console.log(req.user._id, post.original_poster);
                console.log(typeof req.user._id, typeof post.original_poster)
                console.log('wtf')
            }
</code>```

Body:
Hi, to explain my app briefly:
I have a User Schema and a "Tweet" Schema (Actually it's a 'Post' Schema but to avoid confusion with the 'post' method let's call it a "Tweet Schema').

User's have many "tweets" , but a "tweet" only has one User (like twitter). Inside my tweet schema I have a key of Original_Poster, which is a reference to the id of the User who created the post (see below for schema).

In a route to update a tweet, I have an if else statement to confirm if the tweet that the user is trying to update, is actually their tweet. This is functioning while using locally created users with mongodb/mongoose, but not with users created through passport-facebook.

Here is the if else statement:

        if(req.user._id == post.original_poster){
            console.log('nice')
        }else{
            console.log(req.user._id, post.original_poster);
            console.log(typeof req.user._id, typeof post.original_poster)
            console.log('wtf')
        }

What I expect to see is in my console is:
 'nice'

What I am actually seeing is:

5a288913fa0d78257fd7b4d3 5a288913fa0d78257fd7b4d3
object object
wtf

Clearly they are the same user ids, and the type is the same (though this shouldn't matter as I am using the double equals not the triple equals).

Can anyone explain this?

Edit:
Here is the full Post.find({}) for more info:

Post.findOne({_id: req.params.id}).then((post)=>{
    if(req.user._id == post.original_poster){
        console.log('nice')
    }else{
        console.log(req.user._id, post.original_poster);
        console.log(typeof req.user._id, typeof post.original_poster)
        console.log('wtf')
    }
})

Body:
Figured it out, though the answer is a bit weird to me, if anyone can explain why this works, please feel free to explain below

I changed if(req.user._id == post.original_poster) to if(String(req.user._id) == post.original_poster) and now 'nice' is being console.logged. Though this is a bit strange to me because I am using the == double equals not the === so the types of the things under comparison should not be considered.

if(String(req.user._id) == post.original_poster){
                console.log('nice')
            }else{
                console.log(req.user._id, post.original_poster);
                console.log(typeof req.user._id, typeof post.original_poster)
                console.log('wtf')
            }


问:
Angular 4-5 HttpClientModule display data
With HttpModule I used this code to get data from Express.js REST API:

```<code>getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}
</code>```

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

```<code>this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });
</code>```

But it doesn't work.

答:
HttpClientModule works almost the same as the older HttpModule. The default responseType for HttpClient is json, so you would skip the step of converting your response to json and instead use your response directly like you did before:

```<code>this.httpClient.get('http://localhost:3000/api/articles')
    .subscribe(data => this.results = data); // result is passed directly
</code>```

Body:
With HttpModule I used this code to get data from Express.js REST API:

getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });

But it doesn't work.

Body:
HttpClientModule works almost the same as the older HttpModule. The default responseType for HttpClient is json, so you would skip the step of converting your response to json and instead use your response directly like you did before:

this.httpClient.get('http://localhost:3000/api/articles')
    .subscribe(data => this.results = data); // result is passed directly


问:
Creating incremental df file from 2 different df files
Is there a method to create an incremental .df file from 2 different .df files? Or do I have to load both files into 2 blank databases and then use the create incremental .df file feature from Data Administration tool?

I'm using Openedge 10.2B08

答:
A Data Definition (.df) file is a listing of things to add, drop or update in a database. It is in plain text so you can view it in a text editor. You can cut-and-paste the contents of one .df file into another. However, you may run into problems if the changes from the two files conflict. For example, file 1 may say to drop field xyz, while file 2 says to update field xyz. This will cause an error and the entire .df will be backed out.

If you're sure there are no conflicts, just paste the contents of file 2 into file 1, just above the footer. The footer is the last five lines in the file:

```<code>.
PSC
cpstream=ISO8859-1
.
0000000610
</code>```

The very last line is a character count. You may have trouble loading the new .df if you don't update that to match the new file length. And be sure to test the .df before trying it in production.

Body:
A Data Definition (.df) file is a listing of things to add, drop or update in a database. It is in plain text so you can view it in a text editor. You can cut-and-paste the contents of one .df file into another. However, you may run into problems if the changes from the two files conflict. For example, file 1 may say to drop field xyz, while file 2 says to update field xyz. This will cause an error and the entire .df will be backed out.

If you're sure there are no conflicts, just paste the contents of file 2 into file 1, just above the footer. The footer is the last five lines in the file:

.
PSC
cpstream=ISO8859-1
.
0000000610

The very last line is a character count. You may have trouble loading the new .df if you don't update that to match the new file length. And be sure to test the .df before trying it in production.


问:
Add textile into rails-i18n
I need to add some sort of markup in my localization files of my rails project. I want something like this:

```<code>en:
 hello: **Hello** world!

it:
 hello: ciao **mondo**!
</code>```

and for example **word** could be converted with word. For example I'd like to add the textile support.
I've found r18n plugin that's is very nice, but it's way too different from the i18n-rails framework and has several features I don't actually need.

Do you know any plugin that could help me? I've not found anything so far. Do you have any suggestion about tutorial I can use to extend i18n and add this feature by my self. Is anyone interested in such functionality?

答:
Are you saying that

```<code>RedCloth.new(t(:hello)).to_html
</code>```

doesn't work?

Title: Add textile into rails-i18n

Body:
I need to add some sort of markup in my localization files of my rails project. I want something like this:

en:
 hello: **Hello** world!

it:
 hello: ciao **mondo**!

and for example **word** could be converted with word. For example I'd like to add the textile support.
I've found r18n plugin that's is very nice, but it's way too different from the i18n-rails framework and has several features I don't actually need.

Do you know any plugin that could help me? I've not found anything so far. Do you have any suggestion about tutorial I can use to extend i18n and add this feature by my self. Is anyone interested in such functionality?

Body:
Are you saying that

RedCloth.new(t(:hello)).to_html

doesn't work?


问:
Load class from exploded module using custom classloader
I have been playing around with simple custom classloaders in Java, and so far everything works as expected for non-module related classes. However, I can't seem to find any way to load a class from a module using my classloader, even though the module-related find*() methods have been overloaded. What I'm attempting to do is load a class from a module "HelloModularWorld" and run it's main. However, when I specify the directory where the package would be, it's loaded "normally" and reports as being in the unnamed module. What am I missing?

The classloader is just loading classes from elsewhere on the filesystem, nothing particularly special.

Classloader implementation:

```<code>package arch.classloaders;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class ModifiableClassLoader extends ClassLoader {
    private File searchPath;
    //...other ctors...
    public ModifiableClassLoader(File path, String name, ClassLoader parent) {
        super(name, parent); //Delegate to parent classloader as required.
        if (!path.isDirectory()) throw new IllegalArgumentException("Path must be a directory");
        searchPath = path;
    }

    public void setPath(File newPath) {...}

    public File getPath() {...}

    //Responsible for actual loading
    public Class<?> findClass(String binName) throws ClassNotFoundException {
        File classfile = new File(searchPath.getPath() + File.separator
                + binName.replace('.', File.separatorChar) + ".class");
        byte[] buf;
        FileInputStream fis;
        try {
            fis = new FileInputStream(classfile);
            buf = fis.readAllBytes();
            fis.close();
        } catch (IOException e) {
            throw new ClassNotFoundException("Error in defining " + binName + " in " + searchPath.getPath(),e);
        }
        return defineClass(binName, buf, 0, buf.length);
    }

    //Modules are expected to be in a folder with the same name as the module.
    //e.g. module hellomodularworld is expected to be in a folder
    //<SEARCHPATH>/<MODNAME>/
    //NOTE: Module-overloaded methods return null rather than throw when class isn't found.
    public Class<?> findClass(String modName, String binName) {
        if (null == modName) {
            try {
                return findClass(binName);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
        File classfile = new File(searchPath.getPath() + File.separator
                + modName + File.separator
                + binName.replace('.', File.separatorChar) + ".class");
        byte[] buf;
        FileInputStream fis;
        try {
            fis = new FileInputStream(classfile);
            buf = fis.readAllBytes();
            fis.close();
        } catch (IOException e) {
            return null;
        }
        return defineClass(binName, buf, 0, buf.length);
    }

    //Non-module
    public URL findResource(String resPath) {...}

    //Module version
    public URL findResource(String modName, String resPath) throws IOException {...}

    //Enumeration version; does nothing.
    public java.util.Enumeration<URL> findResources(String resPath) {...}
}
</code>```

Test code:

```<code>public class Test {
    public static void main(String[] args) {
        ModifiableClassLoader mcl = new ModifiableClassLoader(
                new File("C:\\Users\\archd\\Desktop\\"));
        try {
            Class<?> clazz = mcl.loadClass(
                    "hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld"
            );
            java.lang.reflect.Method mth = clazz.getMethod("main", String[].class);
            mth.invoke(null,new Object[] {null});
            System.out.println(clazz.getModule().getName());
        } catch (...) {
                //omitted
        }
}
</code>```

On line Class<?> clazz = mcl.loadClass("hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld"); I have tried:

"hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld" -
Does not work. ClassNotFoundException.

"hellomodularworld.com.archdukeliamus.hellomodularworld.HelloWorld" -
NoClassDefFoundException.

com/archdukeliamus/hellomodularworld/HelloWorld (wrong name: hellomodularworld/com/archdukeliamus/hellomodularworld/HelloWorld)

"com.archdukeliamus.hellomodularworld.HelloWorld" - Works as expected (with classloading folder changed appropriately) but uses the unnamed module.

EDIT: module-info.java

```<code>module hellomodularworld {

}
</code>```

The test class is not in any modules.
(I'm not entirely sure why this would matter, I should get an exception to the effect of "this package isn't exported" which I am not getting.)

EDIT 2:
Modified module to include exports com.archdukeliamus.hellomodularworld;. No changes in results.

答:
Module loading is a separate process from class loading. To load a module at runtime, you will need to create a new module layer using the ModuleFinder class, provided with a Path from a FileSystem (in this case the disk). You will then need to create a Configuration that you can use to resolve your modules. To ensure the sanity of the module loading process, you will need to derive the boot configuration. Then you will need to create your configuration, including a ModuleFinder to tell where modules are to be found, and a set of modules to be resolved. Then you instantiate the classloader you wish to use to load those modules' classes, and pass this to the define modules method. Finally you instantiate your class.

New test:

```<code>package arch.classloaders;

import java.lang.module.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.util.*;

public class Test2 {
    public static void main(String[] args) {
        //Get paths to module, and instantiate a ModuleFinder.
        Path pth = FileSystems.getDefault().getPath("C:\\Users\\archd\\Desktop");
        ModuleFinder mf = ModuleFinder.of(pth);
        //Create a new Configuration for a new module layer deriving from the boot configuration, and resolving
        //the "hellomodularworld" module.
        Configuration cfg = ModuleLayer.boot().configuration().resolve(mf,ModuleFinder.of(),Set.of("hellomodularworld"));
        //Create classloader
        ModifiableClassLoader mcl = new ModifiableClassLoader(
                new File("C:\\Users\\archd\\Desktop\\"));
        //make the module layer, using the configuration and classloader.
        ModuleLayer ml = ModuleLayer.boot().defineModulesWithOneLoader(cfg,mcl);
        //Show the configuration.
        System.out.println(ml.configuration()); //prints "hellomodularworld"
        try {
            //load and run class
            Class<?> clazz = ml.findLoader("hellomodularworld").loadClass(
                    "com.archdukeliamus.hellomodularworld.HelloWorld"
            );
            java.lang.reflect.Method mth = clazz.getMethod("main", String[].class);
            mth.invoke(null,new Object[] {null});
            //show the module this class is part of and list packages
            System.out.println(clazz.getModule()); //prints "module hellomodularworld"
            for (String pkgn : clazz.getModule().getPackages()) {
                System.out.println(pkgn); //prints "com.archdukeliamus.hellomodularworld"
            }
        } catch (ClassNotFoundException e) {
            ...omitted...
        }
    }
}
</code>```

Interestingly this still doesn't call the overloaded module-based findClass() methods, although it seems to work.

Body:
I have been playing around with simple custom classloaders in Java, and so far everything works as expected for non-module related classes. However, I can't seem to find any way to load a class from a module using my classloader, even though the module-related find*() methods have been overloaded. What I'm attempting to do is load a class from a module "HelloModularWorld" and run it's main. However, when I specify the directory where the package would be, it's loaded "normally" and reports as being in the unnamed module. What am I missing?

The classloader is just loading classes from elsewhere on the filesystem, nothing particularly special.

Classloader implementation:

package arch.classloaders;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;

public class ModifiableClassLoader extends ClassLoader {
    private File searchPath;
    //...other ctors...
    public ModifiableClassLoader(File path, String name, ClassLoader parent) {
        super(name, parent); //Delegate to parent classloader as required.
        if (!path.isDirectory()) throw new IllegalArgumentException("Path must be a directory");
        searchPath = path;
    }

    public void setPath(File newPath) {...}

    public File getPath() {...}

    //Responsible for actual loading
    public Class<?> findClass(String binName) throws ClassNotFoundException {
        File classfile = new File(searchPath.getPath() + File.separator
                + binName.replace('.', File.separatorChar) + ".class");
        byte[] buf;
        FileInputStream fis;
        try {
            fis = new FileInputStream(classfile);
            buf = fis.readAllBytes();
            fis.close();
        } catch (IOException e) {
            throw new ClassNotFoundException("Error in defining " + binName + " in " + searchPath.getPath(),e);
        }
        return defineClass(binName, buf, 0, buf.length);
    }

    //Modules are expected to be in a folder with the same name as the module.
    //e.g. module hellomodularworld is expected to be in a folder
    //<SEARCHPATH>/<MODNAME>/
    //NOTE: Module-overloaded methods return null rather than throw when class isn't found.
    public Class<?> findClass(String modName, String binName) {
        if (null == modName) {
            try {
                return findClass(binName);
            } catch (ClassNotFoundException e) {
                return null;
            }
        }
        File classfile = new File(searchPath.getPath() + File.separator
                + modName + File.separator
                + binName.replace('.', File.separatorChar) + ".class");
        byte[] buf;
        FileInputStream fis;
        try {
            fis = new FileInputStream(classfile);
            buf = fis.readAllBytes();
            fis.close();
        } catch (IOException e) {
            return null;
        }
        return defineClass(binName, buf, 0, buf.length);
    }

    //Non-module
    public URL findResource(String resPath) {...}

    //Module version
    public URL findResource(String modName, String resPath) throws IOException {...}

    //Enumeration version; does nothing.
    public java.util.Enumeration<URL> findResources(String resPath) {...}
}

Test code:

public class Test {
    public static void main(String[] args) {
        ModifiableClassLoader mcl = new ModifiableClassLoader(
                new File("C:\\Users\\archd\\Desktop\\"));
        try {
            Class<?> clazz = mcl.loadClass(
                    "hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld"
            );
            java.lang.reflect.Method mth = clazz.getMethod("main", String[].class);
            mth.invoke(null,new Object[] {null});
            System.out.println(clazz.getModule().getName());
        } catch (...) {
                //omitted
        }
}

On line Class<?> clazz = mcl.loadClass("hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld"); I have tried:

"hellomodularworld/com.archdukeliamus.hellomodularworld.HelloWorld" -
Does not work. ClassNotFoundException.

"hellomodularworld.com.archdukeliamus.hellomodularworld.HelloWorld" -
NoClassDefFoundException.

com/archdukeliamus/hellomodularworld/HelloWorld (wrong name: hellomodularworld/com/archdukeliamus/hellomodularworld/HelloWorld)

"com.archdukeliamus.hellomodularworld.HelloWorld" - Works as expected (with classloading folder changed appropriately) but uses the unnamed module.

EDIT: module-info.java

module hellomodularworld {

}

The test class is not in any modules.
(I'm not entirely sure why this would matter, I should get an exception to the effect of "this package isn't exported" which I am not getting.)

EDIT 2:
Modified module to include exports com.archdukeliamus.hellomodularworld;. No changes in results.

Body:
Module loading is a separate process from class loading. To load a module at runtime, you will need to create a new module layer using the ModuleFinder class, provided with a Path from a FileSystem (in this case the disk). You will then need to create a Configuration that you can use to resolve your modules. To ensure the sanity of the module loading process, you will need to derive the boot configuration. Then you will need to create your configuration, including a ModuleFinder to tell where modules are to be found, and a set of modules to be resolved. Then you instantiate the classloader you wish to use to load those modules' classes, and pass this to the define modules method. Finally you instantiate your class.

New test:

package arch.classloaders;

import java.lang.module.*;
import java.lang.reflect.InvocationTargetException;
import java.net.URI;
import java.io.*;
import java.nio.*;
import java.nio.file.*;
import java.util.*;

public class Test2 {
    public static void main(String[] args) {
        //Get paths to module, and instantiate a ModuleFinder.
        Path pth = FileSystems.getDefault().getPath("C:\\Users\\archd\\Desktop");
        ModuleFinder mf = ModuleFinder.of(pth);
        //Create a new Configuration for a new module layer deriving from the boot configuration, and resolving
        //the "hellomodularworld" module.
        Configuration cfg = ModuleLayer.boot().configuration().resolve(mf,ModuleFinder.of(),Set.of("hellomodularworld"));
        //Create classloader
        ModifiableClassLoader mcl = new ModifiableClassLoader(
                new File("C:\\Users\\archd\\Desktop\\"));
        //make the module layer, using the configuration and classloader.
        ModuleLayer ml = ModuleLayer.boot().defineModulesWithOneLoader(cfg,mcl);
        //Show the configuration.
        System.out.println(ml.configuration()); //prints "hellomodularworld"
        try {
            //load and run class
            Class<?> clazz = ml.findLoader("hellomodularworld").loadClass(
                    "com.archdukeliamus.hellomodularworld.HelloWorld"
            );
            java.lang.reflect.Method mth = clazz.getMethod("main", String[].class);
            mth.invoke(null,new Object[] {null});
            //show the module this class is part of and list packages
            System.out.println(clazz.getModule()); //prints "module hellomodularworld"
            for (String pkgn : clazz.getModule().getPackages()) {
                System.out.println(pkgn); //prints "com.archdukeliamus.hellomodularworld"
            }
        } catch (ClassNotFoundException e) {
            ...omitted...
        }
    }
}

Interestingly this still doesn't call the overloaded module-based findClass() methods, although it seems to work.


问:
Plot a small region of a map with ocean in ggplot2
I am trying to plot some parts of Canada using the ggplot2 package. I know that it could be tricky to keep the entire polygons because ggplot is getting rid of the points outside the limits (if you use limits in scale_x/y_continuous()). To overcome this, it is useful to plot the entire map and then to apply a zoom (coord_map). My polygons are all okay except that ocean is in the same color than Canada/Alaska. However, if I look at the entire map it is white.

A working example :

```<code>require(rgdal)
require(ggplot2)
YK <- map_data("world")  ##World

## Regions Canada
library(autoimage)
data(canada)
library(broom)
canada_df <- tidy(canada)

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black"))
p
</code>```

This gives a correct world map :

Then if I want to zoom at the west part of Canada :

```<code>p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + coord_map("mercator", xlim=c(-150, -120), ylim=c(50, 70)))
p
</code>```

This gives :

Regions are correct but the Pacific ocean should be in white in the left side...
So I tried with the other way :

```<code>p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + scale_x_continuous(limits = c(-150, -120))
      + scale_y_continuous(limits = c(50, 70)))
p
</code>```

Which gives :

The ocean is in white but as excepted, the polygons are cropped...

Is there a way to have this zoom with the entire polygons and the ocean in white ? Because like this, it is as if everything was the continent...

Thank you !

答:
As @Phil mentioned, something is not going right with the YK layer when you ask ggplot to plot the subregion in Canada. I do not have time to dissect this issue. But, I am guessing that, when you ask ggplot to subset the YK data, the order of data points for polygons are probably changing. Unless you have reasons to subset polygon data from world map, I would do the following. I downloaded a polygon data from GAMD with the raster package and converted it to data frame. When I drew the map, I used geom_cartogram(), which is similar to geom_map(). As you specified long/lat, I used scale_x/y_continuous() to draw a subregion on Canada. Sorry for not being able to dissect the cause behind your problem. But, I hope this map will let you get going.

EDIT

I investigated what is going on with your second case. I accessed to the data frame behind your graphic and my graphic using ggplot_build(). The first block is showing the data frame behind your graphic with scale_x/y_continuous(). I am showing a part of the data. As you see, y values are not in order. You can see that there are NA in the middle of Y values.

```<code>             x         y map_id PANEL group colour fill size linetype alpha
9593         NA 50.13589   187     1     NA gray70  0.5        1    NA
9594         NA 50.15318   187     1     NA gray70  0.5        1    NA
9595         NA 50.13906   187     1     NA gray70  0.5        1    NA
9596         NA 50.09707   187     1     NA gray70  0.5        1    NA
9597         NA 50.04688   187     1     NA gray70  0.5        1    NA
9598         NA 50.00244   187     1     NA gray70  0.5        1    NA
9599         NA       NA   187     1     NA gray70  0.5        1    NA
9600         NA       NA   187     1     NA gray70  0.5        1    NA
9601         NA       NA   187     1     NA gray70  0.5        1    NA
9602         NA       NA   187     1     NA gray70  0.5        1    NA
9603         NA       NA   187     1     NA gray70  0.5        1    NA
9604         NA 50.00000   187     1     NA gray70  0.5        1    NA
9605         NA 50.02388   187     1     NA gray70  0.5        1    NA
9606         NA 50.05283   187     1     NA gray70  0.5        1    NA
9607         NA 50.09414   187     1     NA gray70  0.5        1    NA
9608         NA 50.12988   187     1     NA gray70  0.5        1    NA
9609         NA 50.14380   187     1     NA gray70  0.5        1    NA
</code>```

This block is showing a part of the data behind my plot. As you can see y values are in order. As far as I checked the data, I did not see NAs staying in the middle of y values.

I am still not sure what is causing this difference. Yet, it is clear that something went wrong with your YK data when you drew the second Canadian map.

```<code>                x        y map_id PANEL group colour   fill size linetype alpha

770            NA 53.62133      1     1     1  black gray70  0.3        1    NA
771            NA 53.62124      1     1     1  black gray70  0.3        1    NA
772            NA 53.62115      1     1     1  black gray70  0.3        1    NA
773            NA 53.62107      1     1     1  black gray70  0.3        1    NA
774            NA 53.62097      1     1     1  black gray70  0.3        1    NA
775            NA 53.62088      1     1     1  black gray70  0.3        1    NA
776            NA 53.62083      1     1     1  black gray70  0.3        1    NA
777            NA 53.62079      1     1     1  black gray70  0.3        1    NA
778            NA 53.62070      1     1     1  black gray70  0.3        1    NA
779            NA 53.62061      1     1     1  black gray70  0.3        1    NA
</code>```

CODE

```<code>library(raster)
library(tidyverse)
library(ggalt)
library(ggthemes)

canada <- getData("GADM", country = "canada", level = 1)
foo <- fortify(canada)

g <- ggplot() +
     geom_cartogram(data = foo, aes(x = long, y = lat, map_id = id), map = foo,
                    fill = "gray70", color = "black", size = 0.3) +
     scale_x_continuous(limits = c(-150, -120)) +
     scale_y_continuous(limits = c(50, 70)) +
     theme_map()
</code>```

As stated in the comment, Chika wanted to have Alaska in a map. So here it is.

```<code>canada <- getData("GADM", country = "canada", level = 1)
usa <- getData("GADM", country = "usa", level = 1)
alaska <- subset(usa, NAME_1 == "Alaska")

ca <- fortify(canada)
al <- fortify(alaska)

g <- ggplot() +
     geom_cartogram(data = al, aes(x = long, y = lat, map_id = id), map = al) +
     geom_cartogram(data = ca, aes(x = long, y = lat, map_id = id), map = ca) +
     scale_x_continuous(limits = c(-170, -120)) +
     scale_y_continuous(limits = c(50, 70))
</code>```

Body:
I am trying to plot some parts of Canada using the ggplot2 package. I know that it could be tricky to keep the entire polygons because ggplot is getting rid of the points outside the limits (if you use limits in scale_x/y_continuous()). To overcome this, it is useful to plot the entire map and then to apply a zoom (coord_map). My polygons are all okay except that ocean is in the same color than Canada/Alaska. However, if I look at the entire map it is white.

A working example :

require(rgdal)
require(ggplot2)
YK <- map_data("world")  ##World

## Regions Canada
library(autoimage)
data(canada)
library(broom)
canada_df <- tidy(canada)

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black"))
p

This gives a correct world map :

Then if I want to zoom at the west part of Canada :

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + coord_map("mercator", xlim=c(-150, -120), ylim=c(50, 70)))
p

This gives :

Regions are correct but the Pacific ocean should be in white in the left side...
So I tried with the other way :

p <- (ggplot()
      + theme_bw()
      + geom_polygon(data = YK, aes(x=long, y = lat, group = group), fill="gray70")
      + geom_path(data = canada_df, aes(x=long, y=lat, group=group), colour="black")
      + scale_x_continuous(limits = c(-150, -120))
      + scale_y_continuous(limits = c(50, 70)))
p

Which gives :

The ocean is in white but as excepted, the polygons are cropped...

Is there a way to have this zoom with the entire polygons and the ocean in white ? Because like this, it is as if everything was the continent...

Thank you !

Body:
As @Phil mentioned, something is not going right with the YK layer when you ask ggplot to plot the subregion in Canada. I do not have time to dissect this issue. But, I am guessing that, when you ask ggplot to subset the YK data, the order of data points for polygons are probably changing. Unless you have reasons to subset polygon data from world map, I would do the following. I downloaded a polygon data from GAMD with the raster package and converted it to data frame. When I drew the map, I used geom_cartogram(), which is similar to geom_map(). As you specified long/lat, I used scale_x/y_continuous() to draw a subregion on Canada. Sorry for not being able to dissect the cause behind your problem. But, I hope this map will let you get going.

EDIT

I investigated what is going on with your second case. I accessed to the data frame behind your graphic and my graphic using ggplot_build(). The first block is showing the data frame behind your graphic with scale_x/y_continuous(). I am showing a part of the data. As you see, y values are not in order. You can see that there are NA in the middle of Y values.

             x         y map_id PANEL group colour fill size linetype alpha
9593         NA 50.13589   187     1     NA gray70  0.5        1    NA
9594         NA 50.15318   187     1     NA gray70  0.5        1    NA
9595         NA 50.13906   187     1     NA gray70  0.5        1    NA
9596         NA 50.09707   187     1     NA gray70  0.5        1    NA
9597         NA 50.04688   187     1     NA gray70  0.5        1    NA
9598         NA 50.00244   187     1     NA gray70  0.5        1    NA
9599         NA       NA   187     1     NA gray70  0.5        1    NA
9600         NA       NA   187     1     NA gray70  0.5        1    NA
9601         NA       NA   187     1     NA gray70  0.5        1    NA
9602         NA       NA   187     1     NA gray70  0.5        1    NA
9603         NA       NA   187     1     NA gray70  0.5        1    NA
9604         NA 50.00000   187     1     NA gray70  0.5        1    NA
9605         NA 50.02388   187     1     NA gray70  0.5        1    NA
9606         NA 50.05283   187     1     NA gray70  0.5        1    NA
9607         NA 50.09414   187     1     NA gray70  0.5        1    NA
9608         NA 50.12988   187     1     NA gray70  0.5        1    NA
9609         NA 50.14380   187     1     NA gray70  0.5        1    NA

This block is showing a part of the data behind my plot. As you can see y values are in order. As far as I checked the data, I did not see NAs staying in the middle of y values.

I am still not sure what is causing this difference. Yet, it is clear that something went wrong with your YK data when you drew the second Canadian map.

                x        y map_id PANEL group colour   fill size linetype alpha

770            NA 53.62133      1     1     1  black gray70  0.3        1    NA
771            NA 53.62124      1     1     1  black gray70  0.3        1    NA
772            NA 53.62115      1     1     1  black gray70  0.3        1    NA
773            NA 53.62107      1     1     1  black gray70  0.3        1    NA
774            NA 53.62097      1     1     1  black gray70  0.3        1    NA
775            NA 53.62088      1     1     1  black gray70  0.3        1    NA
776            NA 53.62083      1     1     1  black gray70  0.3        1    NA
777            NA 53.62079      1     1     1  black gray70  0.3        1    NA
778            NA 53.62070      1     1     1  black gray70  0.3        1    NA
779            NA 53.62061      1     1     1  black gray70  0.3        1    NA

CODE

library(raster)
library(tidyverse)
library(ggalt)
library(ggthemes)

canada <- getData("GADM", country = "canada", level = 1)
foo <- fortify(canada)

g <- ggplot() +
     geom_cartogram(data = foo, aes(x = long, y = lat, map_id = id), map = foo,
                    fill = "gray70", color = "black", size = 0.3) +
     scale_x_continuous(limits = c(-150, -120)) +
     scale_y_continuous(limits = c(50, 70)) +
     theme_map()

As stated in the comment, Chika wanted to have Alaska in a map. So here it is.

canada <- getData("GADM", country = "canada", level = 1)
usa <- getData("GADM", country = "usa", level = 1)
alaska <- subset(usa, NAME_1 == "Alaska")

ca <- fortify(canada)
al <- fortify(alaska)

g <- ggplot() +
     geom_cartogram(data = al, aes(x = long, y = lat, map_id = id), map = al) +
     geom_cartogram(data = ca, aes(x = long, y = lat, map_id = id), map = ca) +
     scale_x_continuous(limits = c(-170, -120)) +
     scale_y_continuous(limits = c(50, 70))


问:
Meteor: Force rendering an element
I have a generic template used several times in my app:

```<code><template name="genericCollapse">
  {{data-1}}
  <a href=# class='collapsed' data-toggle='collapse'
     data-target='#uniqueId'>Show/hide data-2</a>
  <div class='collapse' id='uniqueId'>
    {{data-2}}
  </div>
</template>
</code>```

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

```<code><a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})
</code>```

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

答:
It looks like you're fighting with bootstrap. The show class is added by bootstrap when you click on the link, correct? Because this class is not set by your html markup you need to remove it yourself when your underlying data changes. You can do by observing changes to your data and then modifying the DOM directly.

Here's a basic example:

```<code>Template.myTemplate.onCreated(function () {
  const query = MyCollection.find({},{fields: {data-1: 1, data-2: 1}});
  const handle = query.observeChanges({
    changed(id, fields) {
      $('.show').removeClass('show');
    }
});
</code>```

This assumes that there's a collection with fields data-1 and data-2 that you want to control off of. If your data-1 and data-2 are helpers that are performing some computations then you might want to approach this with a Tracker based on reactive vars instead.

Title: Meteor: Force rendering an element

Body:
I have a generic template used several times in my app:

<template name="genericCollapse">
  {{data-1}}
  Show/hide data-2

    {{data-2}}

</template>

By clicking somewhere else in the app, data-1 and data-2 change simultaneously (using Session Vars). However, in case the template is already on the screen, only data-1 and data-2 are changing but the collapse status of the div remains (obviously) unchanged. If it was open before, it remains open.

I want to achieve, that whenever data-1/data-2 changes, div as well as a are forced to be in status collapsed again.
I tried to add

<a href=# class='{{collapsed}}'

Template.genericCollapse.helpers({
  collapsed () {return "collapsed " + Random.Id()},
})

which is not only pretty ugly but also does not help, because the class of div still remains "collapse show" and even with a second helper for div, I can't get rid of "show".

Re-rendering the whole Template would be also acceptable, but I have difficulties to determine the parentNode for calling Blaze.render() - it is never the same - and I'm also not sure where to place such a call correctly.

How is this done?

Body:
It looks like you're fighting with bootstrap. The show class is added by bootstrap when you click on the link, correct? Because this class is not set by your html markup you need to remove it yourself when your underlying data changes. You can do by observing changes to your data and then modifying the DOM directly.

Here's a basic example:

Template.myTemplate.onCreated(function () {
  const query = MyCollection.find({},{fields: {data-1: 1, data-2: 1}});
  const handle = query.observeChanges({
    changed(id, fields) {
      $('.show').removeClass('show');
    }
});

This assumes that there's a collection with fields data-1 and data-2 that you want to control off of. If your data-1 and data-2 are helpers that are performing some computations then you might want to approach this with a Tracker based on reactive vars instead.


问:
can't get nice table with kable / kableExtra with knitr2html
I'm using knit2html to generate html reports from R code.

Been trying to use kable / kableExtra to get table printed out nicely however doesn't seems to work.

I will use this simple program to demonstrate, all attempt to print out the table generate pretty crude print out rather than nice print out as I seen on some of the tutorial (e.g. https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html)

R program:

```<code>#!/usr/bin/Rscript

library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))

knit2html('test.Rmd')
</code>```

Rmd file:

```<code>```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```
</code>```

A screen capture of result html:

Am I missing something here?

答: Use rmarkdown::render() instead of knitr::knit2html(). The latter should have been retired long time ago, and exists pretty much only for historical reasons. Specifically, rmarkdown::render() calls Pandoc to convert Markdown output, and knitr::knit2html() calls the markdown package. See this article for more information.

Body:
I'm using knit2html to generate html reports from R code.

Been trying to use kable / kableExtra to get table printed out nicely however doesn't seems to work.

I will use this simple program to demonstrate, all attempt to print out the table generate pretty crude print out rather than nice print out as I seen on some of the tutorial (e.g. https://cran.r-project.org/web/packages/kableExtra/vignettes/awesome_table_in_html.html)

R program:

#!/usr/bin/Rscript

library(data.table)
library(knitr)
library(kableExtra)

test_data=data.table(a=c(1,2,3,4,5),
                     b=rep('a', 5),
                     c=rep(2.0, 5),
                     d=rep('a', 5),
                     e=rep(2.0, 5),
                     f=rep('a', 5),
                     g=rep(2.0, 5))

knit2html('test.Rmd')

Rmd file:

```{r testprint1, echo=FALSE}
test_data
```
```{r testprint2, echo=FALSE}
kable(test_data)
```
```{r testprint3, echo=FALSE}
test_data %>% kable("html")
```
```{r testprint4, echo=FALSE}
test_data %>% kable("html") %>% kable_styling()
```

A screen capture of result html:

Am I missing something here?


问:
Module 'socket" not found
Error when run
I created a program in ZeroBrane, and I compiled it using srlua.
However, since it has some usage of socket get requests, it seems like it is looking for files such as socket.dll to be in the same folder

I am aware that there are other questions just like this.
My socket should be somewhere in my lua folder, but I have found core.dll under the socket, which didn't work.

I'm wondering if I'm approaching this right, and looking for a way to make sure the program can find these files. (it seems to be more than one file required)

答: You need to have socket.lua in a folder that is available through package.path (or have to be packaged together with your script with srlua) and you also need to have socket\core.dll available through package.cpath, as socket.lua does require "socket.core" and expects to find a DLL that implements that.

Title: Module 'socket" not found


问:
Get min and max of unsorted list
I am hypothetically given an unsorted list of x numbers and I would like to find the min. and max. numbers in the list.

Now based on the research I have done the most efficient sorting method seems to be quick sort.

答:
You dont need to sort the values and get the first and last indexed values - the following simply iterates over the array of numbers and checks against the minNum and maxNum values and sets / resets those accordingly.

let numbers = [10,7,4,6,3,77,232,56,99];
let minNum = numbers[0];
let maxNum = numbers[0];

numbers.forEach(function(number) {
  if(number < minNum ) {minNum = number};
  if(number > maxNum ) {maxNum = number};
})

console.log(minNum) // gives 3
console.log(maxNum) // gives 232```

Title: Get min and max of unsorted list


答:
Each argument passed through the print command is automatically separated by a space.  I see you're in python 2, and I use python 3, so I'm not sure if this solution will work, but you can try doing this:

```<code>print ("Right... So your name is ", name,".",sep='')
</code>```

This basically (assuming it works in python 2 as well) changes the separation between arguments to no space instead of 1 space.

Body:
Each argument passed through the print command is automatically separated by a space.  I see you're in python 2, and I use python 3, so I'm not sure if this solution will work, but you can try doing this:

print ("Right... So your name is ", name,".",sep='')

This basically (assuming it works in python 2 as well) changes the separation between arguments to no space instead of 1 space.


问:
Value does not live long enough with a generic function that creates a container, adds items to it, then iterates over the items
I'm trying to write a generic function that creates a default value and iterates through its internal "buffer." All this happens within the function with no arguments nor return values. I seem to have the lifetimes declared incorrectly and I am having a hard time setting them correctly for this to work.

Here is an example type that implements the Default and IntoIterator traits, as well as a new trait called Foo that requires one method.

```<code>trait Foo<T> {
    fn add(&mut self, T);
}

struct FooBar<T> {
    buf: Vec<Option<T>>,
    len: usize,
}

impl<T> FooBar<T> {
    fn new() -> Self {
        let buf = Vec::new();
        let len = 0;
        Self { buf, len }
    }

    fn iter(&self) -> FooBarIter<T> {
        FooBarIter { foo: self, pos: 0 }
    }
}

impl<T> Foo<T> for FooBar<T> {
    fn add(&mut self, val: T) {
        self.buf.push(Some(val));
        self.len += 1;
    }
}

impl<T> Default for FooBar<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, T: 'a> IntoIterator for &'a FooBar<T> {
    type Item = &'a T;
    type IntoIter = FooBarIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}
</code>```

FooBar just adds values to a vector which it owns. To only allow a non-consuming iteration, I defined an iterator which borrows the underlying Vec and maintains the "current" index during the iteration, returning a reference to each element which the consumer borrows.

```<code>struct FooBarIter<'a, T: 'a> {
    foo: &'a FooBar<T>,
    pos: usize,
}

impl<'a, T> Iterator for FooBarIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.foo.len <= self.pos {
            return None;
        }

        self.pos += 1;
        self.foo.buf[self.pos - 1].as_ref()
    }
}
</code>```

A generic function creates a default value, adds some items (of type &str), then iterates though them by reference. I seem to have declared the lifetimes incorrectly because Rust complains that the borrowed value of FooBar doesn't live long enough. However, it says that it lives until the end of the function, so I'm confused as to how long Rust is expecting the borrow to actually live.

```<code>fn start<'a, T: 'a>()
where
    T: Foo<&'a str> + Default,
    &'a T: IntoIterator<Item = &'a &'a str>,
{
    let mut f = T::default();
    f.add("abcd");
    f.add("efgh");

    for val in &f {
        println!("{}", *val);
    }

    f.add("ijkl");

    for val in &f {
        println!("{}", *val);
    }
}

fn main() {
    start::<FooBar<&str>>();
}
</code>```

Here is the error which states that that &f does not live long enough because the "borrowed value only lives until" the end of the function.

error[E0597]: `f` does not live long enough
  --> src/main.rs:70:17
   |
70 |     for val in &f {
   |                 ^ does not live long enough
...
73 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 61:1...
  --> src/main.rs:61:1
   |
61 | / fn start<'a, T: 'a>()
62 | | where
63 | |     T: Foo<&'a str> + Default,
64 | |     &'a T: IntoIterator<Item = &'a &'a str>,
...  |
72 | |     }
73 | | }
   | |_^
```

<p>I've also tried setting a different lifetime parameter for the <code>&'a IntoIterator</code> trait, but then I end up going around in circles for other errors, not really getting close to setting the correct lifetimes.</p>

<p>To further illustrate what I'm trying to achieve with <code>FooBar</code>, here is an example of what I'm trying to do if <code>FooBar</code> was instead a <code>Vec</code>.</p>

```fn start() {
    let mut f = Vec::new();
    f.push("abcd");
    f.push("efgh");

    for val in &f {
        println!("{}", *val);
    }

    f.push("ijkl");

    for val in &f {
        println!("{}", *val);
    }
}
```

Am I even on the right track with trying to figure out the lifetime parameters, or is it something else entirely?

答:
I believe that what you are attempting is currently impossible.

To start with, your error message is because the caller is specifying the lifetime when passed to start:

```<code>fn start<'a, T: 'a>()
</code>```

This doesn't make any sense because the caller cannot control the lifetime. For example, what if the call was start::<Vec<&'static str>> but the function created some temporary values? This lifetime is also tied to the iterator implementation — if the reference to the value lives as long as the caller dictates, then it can be iterated.

In many similar cases, higher-ranked trait bounds are the solution, however, the closest I can get is a bit different:

```<code>trait Foo<T> {
    fn add(&mut self, T);
}

impl<T> Foo<T> for Vec<T> {
    fn add(&mut self, val: T) {
        self.push(val);
    }
}

fn start<T>()
where
    T: Default + Foo<&'static str>,
    for<'a> &'a T: IntoIterator,
    for<'a, 'b> &'a <&'b T as IntoIterator>::Item: std::fmt::Display,
{
    let mut f = T::default();
    f.add("abcd");
    f.add("efgh");

    for val in &f {
        println!("{}", &val);
    }

    f.add("ijkl");

    for val in &f {
        println!("{}", &val);
    }
}

fn main() {
    start::<Vec<&str>>();
}
</code>```

The main sticking point is T: Default + Foo<&'static str>. As far as what I can see, there's no way to pass in a concrete type for T that could use a HRTB defined by the function. In this case, we can use 'static. If we tried to use for <'a> T: Default + Foo<&'a str>, we get the error:

error[E0277]: the trait bound `for<'a> std::vec::Vec<&str>: Foo<&'a str>` is not satisfied
  --> src/main.rs:33:5
   |
33 |     start::<Vec<&str>>();
   |     ^^^^^^^^^^^^^^^^^^ the trait `for<'a> Foo<&'a str>` is not implemented for `std::vec::Vec<&str>`
   |
   = help: the following implementations were found:
             <std::vec::Vec<T> as Foo<T>>
   = note: required by `start`
```

The compiler doesn't know to match up the lifetime declared at the call site with the one specified by the HRTB. I believe, but am not sure, that generic associated types might address the problem.

Body:
I'm trying to write a generic function that creates a default value and iterates through its internal "buffer." All this happens within the function with no arguments nor return values. I seem to have the lifetimes declared incorrectly and I am having a hard time setting them correctly for this to work.

Here is an example type that implements the Default and IntoIterator traits, as well as a new trait called Foo that requires one method.

trait Foo<T> {
    fn add(&mut self, T);
}

struct FooBar<T> {
    buf: Vec<Option<T>>,
    len: usize,
}

impl<T> FooBar<T> {
    fn new() -> Self {
        let buf = Vec::new();
        let len = 0;
        Self { buf, len }
    }

    fn iter(&self) -> FooBarIter<T> {
        FooBarIter { foo: self, pos: 0 }
    }
}

impl<T> Foo<T> for FooBar<T> {
    fn add(&mut self, val: T) {
        self.buf.push(Some(val));
        self.len += 1;
    }
}

impl<T> Default for FooBar<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<'a, T: 'a> IntoIterator for &'a FooBar<T> {
    type Item = &'a T;
    type IntoIter = FooBarIter<'a, T>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

FooBar just adds values to a vector which it owns. To only allow a non-consuming iteration, I defined an iterator which borrows the underlying Vec and maintains the "current" index during the iteration, returning a reference to each element which the consumer borrows.

struct FooBarIter<'a, T: 'a> {
    foo: &'a FooBar<T>,
    pos: usize,
}

impl<'a, T> Iterator for FooBarIter<'a, T> {
    type Item = &'a T;

    fn next(&mut self) -> Option<Self::Item> {
        if self.foo.len <= self.pos {
            return None;
        }

        self.pos += 1;
        self.foo.buf[self.pos - 1].as_ref()
    }
}

A generic function creates a default value, adds some items (of type &str), then iterates though them by reference. I seem to have declared the lifetimes incorrectly because Rust complains that the borrowed value of FooBar doesn't live long enough. However, it says that it lives until the end of the function, so I'm confused as to how long Rust is expecting the borrow to actually live.

fn start<'a, T: 'a>()
where
    T: Foo<&'a str> + Default,
    &'a T: IntoIterator<Item = &'a &'a str>,
{
    let mut f = T::default();
    f.add("abcd");
    f.add("efgh");

    for val in &f {
        println!("{}", *val);
    }

    f.add("ijkl");

    for val in &f {
        println!("{}", *val);
    }
}

fn main() {
    start::<FooBar<&str>>();
}

Here is the error which states that that &f does not live long enough because the "borrowed value only lives until" the end of the function.

error[E0597]: `f` does not live long enough
  --> src/main.rs:70:17
   |
70 |     for val in &f {
   |                 ^ does not live long enough
...
73 | }
   | - borrowed value only lives until here
   |
note: borrowed value must be valid for the lifetime 'a as defined on the function body at 61:1...
  --> src/main.rs:61:1
   |
61 | / fn start<'a, T: 'a>()
62 | | where
63 | |     T: Foo<&'a str> + Default,
64 | |     &'a T: IntoIterator<Item = &'a &'a str>,
...  |
72 | |     }
73 | | }
   | |_^

I've also tried setting a different lifetime parameter for the &'a IntoIterator trait, but then I end up going around in circles for other errors, not really getting close to setting the correct lifetimes.

To further illustrate what I'm trying to achieve with FooBar, here is an example of what I'm trying to do if FooBar was instead a Vec.

fn start() {
    let mut f = Vec::new();
    f.push("abcd");
    f.push("efgh");

    for val in &f {
        println!("{}", *val);
    }

    f.push("ijkl");

    for val in &f {
        println!("{}", *val);
    }
}

Am I even on the right track with trying to figure out the lifetime parameters, or is it something else entirely?

Body:
I believe that what you are attempting is currently impossible.

To start with, your error message is because the caller is specifying the lifetime when passed to start:

fn start<'a, T: 'a>()

This doesn't make any sense because the caller cannot control the lifetime. For example, what if the call was start::<Vec<&'static str>> but the function created some temporary values? This lifetime is also tied to the iterator implementation — if the reference to the value lives as long as the caller dictates, then it can be iterated.

In many similar cases, higher-ranked trait bounds are the solution, however, the closest I can get is a bit different:

trait Foo<T> {
    fn add(&mut self, T);
}

impl<T> Foo<T> for Vec<T> {
    fn add(&mut self, val: T) {
        self.push(val);
    }
}

fn start<T>()
where
    T: Default + Foo<&'static str>,
    for<'a> &'a T: IntoIterator,
    for<'a, 'b> &'a <&'b T as IntoIterator>::Item: std::fmt::Display,
{
    let mut f = T::default();
    f.add("abcd");
    f.add("efgh");

    for val in &f {
        println!("{}", &val);
    }

    f.add("ijkl");

    for val in &f {
        println!("{}", &val);
    }
}

fn main() {
    start::<Vec<&str>>();
}

The main sticking point is T: Default + Foo<&'static str>. As far as what I can see, there's no way to pass in a concrete type for T that could use a HRTB defined by the function. In this case, we can use 'static. If we tried to use for <'a> T: Default + Foo<&'a str>, we get the error:

error[E0277]: the trait bound `for<'a> std::vec::Vec<&str>: Foo<&'a str>` is not satisfied
  --> src/main.rs:33:5
   |
33 |     start::<Vec<&str>>();
   |     ^^^^^^^^^^^^^^^^^^ the trait `for<'a> Foo<&'a str>` is not implemented for `std::vec::Vec<&str>`
   |
   = help: the following implementations were found:
             <std::vec::Vec<T> as Foo<T>>
   = note: required by `start`

The compiler doesn't know to match up the lifetime declared at the call site with the one specified by the HRTB. I believe, but am not sure, that generic associated types might address the problem.


问:
XPath axis, get all following nodes until
I have the following example of HTML:

```<code><!-- lots of html -->
<h2>Foo bar</h2>
<p>lorem</p>
<p>ipsum</p>
<p>etc</p>

<h2>Bar baz</h2>
<p>dum dum dum</p>
<p>poopfiddles</p>
<!-- lots more html ... -->
</code>```

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

答:
```<code>require 'nokogiri'

doc = Nokogiri::XML <<ENDXML
<root>
  <h2>Foo</h2>
  <p>lorem</p>
  <p>ipsum</p>
  <p>etc</p>

  <h2>Bar</h2>
  <p>dum dum dum</p>
  <p>poopfiddles</p>
</root>
ENDXML

a = doc.xpath( '//h2[text()="Foo"]/following::p[not(preceding::h2[text()="Bar"])]' )
puts a.map{ |n| n.to_s }
#=> <p>lorem</p>
#=> <p>ipsum</p>
#=> <p>etc</p>
</code>```

I suspected that it might be more efficient to just walk the DOM using next_sibling until you hit the end:

```<code>node = doc.at_xpath('//h2[text()="Foo bar"]').next_sibling
stop = doc.at_xpath('//h2[text()="Bar baz"]')
a = []
while node && node!=stop
  a << node unless node.type == 3 # skip text nodes
  node = node.next_sibling
end

puts a.map{ |n| n.to_s }
#=> <p>lorem</p>
#=> <p>ipsum</p>
#=> <p>etc</p>
</code>```

However, this is NOT faster. In a few simple tests, I found that xpath-only (the first solution) is about 2x as fast as this looping test, even when there are a very large number of paragraphs after the stop node. When there are many nodes to capture (and few after the stop) it performs even better, in the 6x-10x range.

Body:
I have the following example of HTML:

Foo bar

lorem

ipsum

etc

Bar baz

dum dum dum

poopfiddles

I'm looking to extract all paragraphs following the 'Foo bar' header, until I reach the 'Bar baz' header (the text for the 'Bar baz' header is unknown, so unfortunately I can't use the answer provided by bougyman). Now I can of course using something like //h2[text()='Foo bar']/following::p but that of course will grab all paragraphs following this header. So I have the option to traverse the nodeset and push paragraphs into an Array until the text matches that of the next following header, but let's be honest, that's never as cool as being able to do it in XPath.

Is there a way to do this that I'm missing?

Body:
require 'nokogiri'

doc = Nokogiri::XML <<ENDXML
<root>
  <h2>Foo</h2>
  <p>lorem</p>
  <p>ipsum</p>
  <p>etc</p>

  <h2>Bar</h2>
  <p>dum dum dum</p>
  <p>poopfiddles</p>
</root>
ENDXML

a = doc.xpath( '//h2[text()="Foo"]/following::p[not(preceding::h2[text()="Bar"])]' )
puts a.map{ |n| n.to_s }
#=> <p>lorem</p>
#=> <p>ipsum</p>
#=> <p>etc</p>

I suspected that it might be more efficient to just walk the DOM using next_sibling until you hit the end:

node = doc.at_xpath('//h2[text()="Foo bar"]').next_sibling
stop = doc.at_xpath('//h2[text()="Bar baz"]')
a = []
while node && node!=stop
  a << node unless node.type == 3 # skip text nodes
  node = node.next_sibling
end

puts a.map{ |n| n.to_s }
#=> <p>lorem</p>
#=> <p>ipsum</p>
#=> <p>etc</p>

However, this is NOT faster. In a few simple tests, I found that xpath-only (the first solution) is about 2x as fast as this looping test, even when there are a very large number of paragraphs after the stop node. When there are many nodes to capture (and few after the stop) it performs even better, in the 6x-10x range.


问:
using a graphml file for d3.js force-directed layout
How do I use a graphml file with d3.js ? [i would like to draw a force-directed graph]

is it simpler to convert the file to .json ? How ? I haven't been able to find a converter (I have found a python converter, but I'm not a python user)

is it possible to directly use the graphml file ? may be with d3.xml ?

Note :
The graphml looks like this

```<code><graph id="G" edgedefault="directed">
<node id="n0">
  <data key="v_name">JohnMaynardKe...</data>
  <data key="v_label">John Maynard Ke...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<node id="n1">
  <data key="v_name">JosephA.Schum...</data>
  <data key="v_label">Joseph A. Schum...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<edge source="n0" target="n1">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>
<edge source="n0" target="n7">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>
</code>```

....

答:
I will recommend that you convert your graphml file in a json file. I ran into the same issue and here's how I convert a graphml file in json using python and the networkx library:

```<code>import networkx as nx
import json
from networkx.readwrite import json_graph
import re

G=nx.read_graphml('YourFile.graphml', unicode)
data = json_graph.node_link_data(G)

for node in data['nodes']:
  str=node['id']
  node['id']=[int(s) for s in str.split("n") if s.isdigit()][0]

with open('YourFile.json', 'w') as f:
  json.dump(data, f, indent=4)
</code>```

The for loop in the code converts your node ids into numbers. This is very important since the sources and target in the json final file are already numbers (not characters).

Body:
How do I use a graphml file with d3.js ? [i would like to draw a force-directed graph]

is it simpler to convert the file to .json ? How ? I haven't been able to find a converter (I have found a python converter, but I'm not a python user)

is it possible to directly use the graphml file ? may be with d3.xml ?

Note :
The graphml looks like this

<graph id="G" edgedefault="directed">
<node id="n0">
  <data key="v_name">JohnMaynardKe...</data>
  <data key="v_label">John Maynard Ke...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<node id="n1">
  <data key="v_name">JosephA.Schum...</data>
  <data key="v_label">Joseph A. Schum...</data>
  <data key="v_size">4</data>
  <data key="v_label.cex">0.3</data>
  <data key="v_frame.color">#ffffff00</data>
  <data key="v_color">#54FF00CC</data>
</node>
<edge source="n0" target="n1">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>
<edge source="n0" target="n7">
  <data key="e_nombre">2</data>
  <data key="e_width">2</data>
  <data key="e_arrow.size">0</data>
  <data key="e_color">#00000021</data>
</edge>

....

Body:
I will recommend that you convert your graphml file in a json file. I ran into the same issue and here's how I convert a graphml file in json using python and the networkx library:

import networkx as nx
import json
from networkx.readwrite import json_graph
import re

G=nx.read_graphml('YourFile.graphml', unicode)
data = json_graph.node_link_data(G)

for node in data['nodes']:
  str=node['id']
  node['id']=[int(s) for s in str.split("n") if s.isdigit()][0]

with open('YourFile.json', 'w') as f:
  json.dump(data, f, indent=4)

The for loop in the code converts your node ids into numbers. This is very important since the sources and target in the json final file are already numbers (not characters).


问:
Photos Framework crash: 'This application is not allowed to access Photo data.'
App crashes if photo access permission is not granted and the object which asked for permission is about to deallocate.

Apple's sample code (for Photos framework) crashes too.

My app crashes with following stack trace:

```
*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'This application is not allowed to access Photo data.'

*** First throw call stack:
(
    0   CoreFoundation                      0x000000010a324f65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010c030deb objc_exception_throw + 48
    2   PhotoLibraryServices                0x000000011c1f7e2d -[PLPhotoLibrary initWithTransientContext:name:] + 1183
    3   Photos                              0x000000011bd6a445 __30-[PHPhotoLibrary photoLibrary]_block_invoke + 59
    4   libdispatch.dylib                   0x0000000110f5e49b _dispatch_client_callout + 8
    5   libdispatch.dylib                   0x0000000110f49e28 dispatch_once_f + 543
    6   Photos                              0x000000011bd6a404 -[PHPhotoLibrary photoLibrary] + 140
    7   Photos                              0x000000011bd3e5e8 -[PHCoreImageManager _cancelAndFlushPreheatItemsForAssets:CPLPrefetching:domain:operation:passingTestHandler:didCancelHandler:] + 174
    8   Photos                              0x000000011bd5900c -[PHImageManager dealloc] + 176
    9   libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    10  MyApp                               0x000000010f271812 _TToFC12MyApp16PhotosDataSourceE + 66
    11  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    12  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    13  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    14  MyApp                               0x000000010f271796 _TFC12MyApp16PhotosDataSourceD + 198
    15  MyApp                               0x000000010f2717c2 _TToFC12MyApp16PhotosDataSourceD + 34
    16  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    17  MyApp                               0x000000010f2668f2 _TToFC12MyApp25PhotoPickerViewControllerE + 178
    18  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    19  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    20  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    21  UIKit                               0x000000010adb54b9 -[UIResponder dealloc] + 130
    22  UIKit                               0x000000010ad40721 -[UIViewController dealloc] + 1949
    23  UIKit                               0x000000010ad1c97b -[UIPresentationController .cxx_destruct] + 262
    24  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    25  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    26  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    27  UIKit                               0x000000010ad185db -[UIPresentationController dealloc] + 56
    28  UIKit                               0x000000010b4a9046 -[_UIFullscreenPresentationController dealloc] + 56
    29  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    30  UIKit                               0x000000010ad1838c __destroy_helper_block_411 + 24
    31  libsystem_blocks.dylib              0x0000000110fdb6b1 _Block_release + 128
    32  UIKit                               0x000000010b568d9c -[_UIViewControllerTransitionContext .cxx_destruct] + 94
    33  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    34  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    35  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    36  UIKit                               0x000000010b567825 -[_UIViewControllerTransitionContext dealloc] + 56
    37  UIKit                               0x000000010b568e51 -[_UIViewControllerOneToOneTransitionContext dealloc] + 79
    38  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    39  MyApp                               0x000000010d4818d2 block_destroy_helper + 66
    40  MyApp                               0x000000010d481988 _TPA__TFFC16MyApp31CustomShrinkAnimator17animateTransitionFS0_FPSo36UIViewControllerContextTransitioning_T_U0_FSbT_ + 152
    41  MyApp                               0x000000010d481a28 _TPA__TTRXFo_dSb_dT__XFo_iSb_iT__ + 120
    42  MyApp                               0x000000010d481aed block_destroy_helper8 + 13
    43  libsystem_blocks.dylib              0x0000000110fdb6b1 _Block_release + 128
    44  UIKit                               0x000000010ac5ee47 -[UIViewAnimationBlockDelegate .cxx_destruct] + 43
    45  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    46  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    47  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    48  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    49  CoreFoundation                      0x000000010a228d4d -[__NSDictionaryI dealloc] + 141
    50  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    51  libobjc.A.dylib                     0x000000010c0450b8 _ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv + 488
    52  CoreFoundation                      0x000000010a2129c6 _CFAutoreleasePoolPop + 22
    53  CoreFoundation                      0x000000010a246941 __CFRunLoopRun + 2081
    54  CoreFoundation                      0x000000010a245e98 CFRunLoopRunSpecific + 488
    55  GraphicsServices                    0x0000000112598ad2 GSEventRunModal + 161
    56  UIKit                               0x000000010abb8676 UIApplicationMain + 171
    57  MyApp                               0x00000001082b470d main + 109
    58  libdyld.dylib                       0x0000000110f9392d start + 1
    59  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException
```

Any pointers would be really appreciated.

答:
My crash situation is using PHCachingImageManager as a property.

```<code>fileprivate let imageManager = PHCachingImageManager()
</code>```

I fix it by changing it to lazy var :

```<code>fileprivate lazy var imageManager = PHCachingImageManager()
</code>```

Body:
App crashes if photo access permission is not granted and the object which asked for permission is about to deallocate.

Apple's sample code (for Photos framework) crashes too.

My app crashes with following stack trace:

*** Terminating app due to uncaught exception 'NSObjectInaccessibleException', reason: 'This application is not allowed to access Photo data.'

*** First throw call stack:
(
    0   CoreFoundation                      0x000000010a324f65 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010c030deb objc_exception_throw + 48
    2   PhotoLibraryServices                0x000000011c1f7e2d -[PLPhotoLibrary initWithTransientContext:name:] + 1183
    3   Photos                              0x000000011bd6a445 __30-[PHPhotoLibrary photoLibrary]_block_invoke + 59
    4   libdispatch.dylib                   0x0000000110f5e49b _dispatch_client_callout + 8
    5   libdispatch.dylib                   0x0000000110f49e28 dispatch_once_f + 543
    6   Photos                              0x000000011bd6a404 -[PHPhotoLibrary photoLibrary] + 140
    7   Photos                              0x000000011bd3e5e8 -[PHCoreImageManager _cancelAndFlushPreheatItemsForAssets:CPLPrefetching:domain:operation:passingTestHandler:didCancelHandler:] + 174
    8   Photos                              0x000000011bd5900c -[PHImageManager dealloc] + 176
    9   libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    10  MyApp                               0x000000010f271812 _TToFC12MyApp16PhotosDataSourceE + 66
    11  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    12  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    13  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    14  MyApp                               0x000000010f271796 _TFC12MyApp16PhotosDataSourceD + 198
    15  MyApp                               0x000000010f2717c2 _TToFC12MyApp16PhotosDataSourceD + 34
    16  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    17  MyApp                               0x000000010f2668f2 _TToFC12MyApp25PhotoPickerViewControllerE + 178
    18  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    19  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    20  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    21  UIKit                               0x000000010adb54b9 -[UIResponder dealloc] + 130
    22  UIKit                               0x000000010ad40721 -[UIViewController dealloc] + 1949
    23  UIKit                               0x000000010ad1c97b -[UIPresentationController .cxx_destruct] + 262
    24  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    25  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    26  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    27  UIKit                               0x000000010ad185db -[UIPresentationController dealloc] + 56
    28  UIKit                               0x000000010b4a9046 -[_UIFullscreenPresentationController dealloc] + 56
    29  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    30  UIKit                               0x000000010ad1838c __destroy_helper_block_411 + 24
    31  libsystem_blocks.dylib              0x0000000110fdb6b1 _Block_release + 128
    32  UIKit                               0x000000010b568d9c -[_UIViewControllerTransitionContext .cxx_destruct] + 94
    33  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    34  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    35  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    36  UIKit                               0x000000010b567825 -[_UIViewControllerTransitionContext dealloc] + 56
    37  UIKit                               0x000000010b568e51 -[_UIViewControllerOneToOneTransitionContext dealloc] + 79
    38  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    39  MyApp                               0x000000010d4818d2 block_destroy_helper + 66
    40  MyApp                               0x000000010d481988 _TPA__TFFC16MyApp31CustomShrinkAnimator17animateTransitionFS0_FPSo36UIViewControllerContextTransitioning_T_U0_FSbT_ + 152
    41  MyApp                               0x000000010d481a28 _TPA__TTRXFo_dSb_dT__XFo_iSb_iT__ + 120
    42  MyApp                               0x000000010d481aed block_destroy_helper8 + 13
    43  libsystem_blocks.dylib              0x0000000110fdb6b1 _Block_release + 128
    44  UIKit                               0x000000010ac5ee47 -[UIViewAnimationBlockDelegate .cxx_destruct] + 43
    45  libobjc.A.dylib                     0x000000010c02f7bb _ZL27object_cxxDestructFromClassP11objc_objectP10objc_class + 127
    46  libobjc.A.dylib                     0x000000010c03a390 objc_destructInstance + 93
    47  libobjc.A.dylib                     0x000000010c03a3c3 object_dispose + 22
    48  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    49  CoreFoundation                      0x000000010a228d4d -[__NSDictionaryI dealloc] + 141
    50  libobjc.A.dylib                     0x000000010c044afe _ZN11objc_object17sidetable_releaseEb + 232
    51  libobjc.A.dylib                     0x000000010c0450b8 _ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv + 488
    52  CoreFoundation                      0x000000010a2129c6 _CFAutoreleasePoolPop + 22
    53  CoreFoundation                      0x000000010a246941 __CFRunLoopRun + 2081
    54  CoreFoundation                      0x000000010a245e98 CFRunLoopRunSpecific + 488
    55  GraphicsServices                    0x0000000112598ad2 GSEventRunModal + 161
    56  UIKit                               0x000000010abb8676 UIApplicationMain + 171
    57  MyApp                               0x00000001082b470d main + 109
    58  libdyld.dylib                       0x0000000110f9392d start + 1
    59  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

Any pointers would be really appreciated.

Body:
My crash situation is using PHCachingImageManager as a property.

fileprivate let imageManager = PHCachingImageManager()

I fix it by changing it to lazy var :

fileprivate lazy var imageManager = PHCachingImageManager()


问:
How to count row counts without running a SELECT COUNT(*) query?
I'm trying to get the count of rows in a BigQuery table, using Google App Script. This is how I try to do so

```<code>BigQuery.Tables.get(projectId, datasetId, tableId).numRows
</code>```

No matter what tableId I'm inserting, I'm always getting the value 265.
I'm at least sure that a single table has hundreds of millions of rows. So why am I getting 265 as a value for the numRows property ?!

And how can I get the total amount of rows for a BigQuery table without having to run a SELECT COUNT(*) FROM datasetId.tableId query so I don't consume much from my quota ?

答:
How can I get the total amount of rows for a BigQuery table without having to run a SELECT COUNT(*) FROM datasetId.tableId query so I don't consume much from my quota ?

1 - You might be surprised but SELECT COUNT(*) FROM datasetId.tableId does not incur any cost for you because BigQuery engine is smart enough to just get this stats from so called meta table. You can see the cost message for such type of query if you will open validator (to the right to buttons on BigQuery UI). The message will be - This query will process 0 B when run

2 - Moreover - you can query meta tables by your own as below example shows:

```<code>#standardSQL
SELECT table_id,
    DATE(TIMESTAMP_MILLIS(creation_time)) AS creation_date,
    DATE(TIMESTAMP_MILLIS(last_modified_time)) AS last_modified_date,
    row_count,
    size_bytes,
    CASE
        WHEN type = 1 THEN 'table'
        WHEN type = 2 THEN 'view'
        WHEN type = 3 THEN 'external'
        ELSE '?'
    END AS type,
    TIMESTAMP_MILLIS(creation_time) AS creation_time,
    TIMESTAMP_MILLIS(last_modified_time) AS last_modified_time,
    dataset_id,
    project_id
FROM `projectid.datasetid.__TABLES__`
</code>```

Body:
I'm trying to get the count of rows in a BigQuery table, using Google App Script. This is how I try to do so

BigQuery.Tables.get(projectId, datasetId, tableId).numRows

No matter what tableId I'm inserting, I'm always getting the value 265.
I'm at least sure that a single table has hundreds of millions of rows. So why am I getting 265 as a value for the numRows property ?!

And how can I get the total amount of rows for a BigQuery table without having to run a SELECT COUNT(*) FROM datasetId.tableId query so I don't consume much from my quota ?

Body:
How can I get the total amount of rows for a BigQuery table without having to run a SELECT COUNT(*) FROM datasetId.tableId query so I don't consume much from my quota ?

1 - You might be surprised but SELECT COUNT(*) FROM datasetId.tableId does not incur any cost for you because BigQuery engine is smart enough to just get this stats from so called meta table. You can see the cost message for such type of query if you will open validator (to the right to buttons on BigQuery UI). The message will be - This query will process 0 B when run

2 - Moreover - you can query meta tables by your own as below example shows:

#standardSQL
SELECT table_id,
    DATE(TIMESTAMP_MILLIS(creation_time)) AS creation_date,
    DATE(TIMESTAMP_MILLIS(last_modified_time)) AS last_modified_date,
    row_count,
    size_bytes,
    CASE
        WHEN type = 1 THEN 'table'
        WHEN type = 2 THEN 'view'
        WHEN type = 3 THEN 'external'
        ELSE '?'
    END AS type,
    TIMESTAMP_MILLIS(creation_time) AS creation_time,
    TIMESTAMP_MILLIS(last_modified_time) AS last_modified_time,
    dataset_id,
    project_id
FROM `projectid.datasetid.__TABLES__`