问:
JS - Detect brightness of image from other domain
I have an image loaded into  in the document and I am wanting to use JS to determine how "bright" on average the image is (to adjust the colour of overlay elements to improve visibility.

The answer here: Image Dark/Light Detection Client Sided Script works just fine...except for the fact that it doesn't work on cross origin resources. The images I will be needing to determine brightness for could be from any domain and I don't have control over setting the necessary CORS headers on the server to be passed back along with the response to make it easy for JS to use the image.

Is there some way to get the brightness of an image from an external domain without having to worry about CORS?

答:
Not directly: cross-domain images not loaded over CORS (with the crossorigin attribute) are consider to be "tainted", and anywhere it is drawn (such as on a canvas) will also become tainted. You can't read image data from a tainted canvas, which is why the method described in the linked answer (which uses getImageData to read image data) won't work. MDN has some more information on tainted images.

The reasoning behind this is the same as with any other CORS-restricted resource: You shouldn't be able to get information from other domains without their explicit permission (through the use of CORS headers), since the remote domain may never have intended such images to be accessed by other domains.

For example, an image sharing service could allow only access to private images for logged-in users; if this restriction did not exist, any website with the URL for such an image could make a request for that image as the logged-in user, then read the image, upload and publish it on their own site, which would definitely be a privacy issue.

You can work around this by using a CORS proxy, which routes your requests through a server that adds the CORS headers automatically. You can use a public service such as crossorigin.me (where you just add https://crossorigin.me/ before the URL), or you can run your own CORS proxy if you're uncomfortable sending requests through an unknown third party.


来源: stackexchange

问:
How do I pass the array from my function to return
I'm trying unsuccessfully pass my array to the outside function as a result of it? Here is working code in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output The result should be passed to returnSearch.</p>

```<code>var googleSuggest = function(returnSearch){

  var term = $('#searchInput').val();
  var result = [];
  var service = {
    youtube: { client: 'youtube', ds: 'yt' },
    books: { client: 'books', ds: 'bo' },
    products: { client: 'products-cc', ds: 'sh' },
    news: { client: 'news-cc', ds: 'n' },
    images: { client: 'img', ds: 'i' },
    web: { client: 'hp', ds: '' },
    recipes: { client: 'hp', ds: 'r' }
  };

  $.ajax({
    url: 'https://clients1.google.com/complete/search',
    dataType: 'jsonp',
    data: {
      q: term,
      nolabels: 't',
      client: service.web.client,
      ds: service.web.ds
    }
  }).done(function(data) {

      result.pop()

      $.each(data[1], function(item, value) {

        var stripedValue = value[0].replace(/<[^>]+>/g, '');

           result.push(stripedValue);

      })

      console.log(result)

    })

  returnSearch = ['ActionScript', 'AppleScript', 'Asp']

  return returnSearch

};
</code>```

答:
I think the only way to make it return the value you have in mind is to make the call synchronous, which means that whenever the call ajax call is made, you will have to wait for it to be ready (what you generally don't want). You could call the returnSearch function from within the result call like this:

```<code>  var googleSuggest = function(returnSearch){
  var term = $('#searchInput').val();
  var service = {
    youtube: { client: 'youtube', ds: 'yt' },
    books: { client: 'books', ds: 'bo' },
    products: { client: 'products-cc', ds: 'sh' },
    news: { client: 'news-cc', ds: 'n' },
    images: { client: 'img', ds: 'i' },
    web: { client: 'hp', ds: '' },
    recipes: { client: 'hp', ds: 'r' }
  };

 var promise = $.ajax({
    url: 'https://clients1.google.com/complete/search',
    dataType: 'jsonp',
    data: {
      q: term,
      nolabels: 't',
      client: service.web.client,
      ds: service.web.ds
    }
  })

  return promise
};

$(function() {
  $('#searchInput').autoComplete({
    minChars: 1,
    source: function(term, suggest){
      var promise = googleSuggest()
      returnSearch = function(term, choices) {
        console.log(choices)
        var suggestions = [];
        for (i=0;i<choices.length;i++)
         if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
          suggest(suggestions);
      }

      $.when(promise).then(function(data) {
        term = term.toLowerCase();
        var result = [];
        $.each(data[1], function(item, value) {
          var stripedValue = value[0].replace(/<[^>]+>/g, '');
             result.push(stripedValue);
        })
        returnSearch(term, result)
      })
    }
  });
})
</code>```

Also see this stackoverflow post.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying unsuccessfully pass my array to the outside function as a result of it? Here is working code in jsbin: https://jsbin.com/kugesozawi/edit?js,console,output The result should be passed to returnSearch.

var googleSuggest = function(returnSearch){

  var term = $('#searchInput').val();
  var result = [];
  var service = {
    youtube: { client: 'youtube', ds: 'yt' },
    books: { client: 'books', ds: 'bo' },
    products: { client: 'products-cc', ds: 'sh' },
    news: { client: 'news-cc', ds: 'n' },
    images: { client: 'img', ds: 'i' },
    web: { client: 'hp', ds: '' },
    recipes: { client: 'hp', ds: 'r' }
  };

  $.ajax({
    url: 'https://clients1.google.com/complete/search',
    dataType: 'jsonp',
    data: {
      q: term,
      nolabels: 't',
      client: service.web.client,
      ds: service.web.ds
    }
  }).done(function(data) {

      result.pop()

      $.each(data[1], function(item, value) {

        var stripedValue = value[0].replace(/<[^>]+>/g, '');

           result.push(stripedValue);

      })

      console.log(result)

    })

  returnSearch = ['ActionScript', 'AppleScript', 'Asp']

  return returnSearch

};

Body:
I think the only way to make it return the value you have in mind is to make the call synchronous, which means that whenever the call ajax call is made, you will have to wait for it to be ready (what you generally don't want). You could call the returnSearch function from within the result call like this:

  var googleSuggest = function(returnSearch){
  var term = $('#searchInput').val();
  var service = {
    youtube: { client: 'youtube', ds: 'yt' },
    books: { client: 'books', ds: 'bo' },
    products: { client: 'products-cc', ds: 'sh' },
    news: { client: 'news-cc', ds: 'n' },
    images: { client: 'img', ds: 'i' },
    web: { client: 'hp', ds: '' },
    recipes: { client: 'hp', ds: 'r' }
  };

 var promise = $.ajax({
    url: 'https://clients1.google.com/complete/search',
    dataType: 'jsonp',
    data: {
      q: term,
      nolabels: 't',
      client: service.web.client,
      ds: service.web.ds
    }
  })

  return promise
};

$(function() {
  $('#searchInput').autoComplete({
    minChars: 1,
    source: function(term, suggest){
      var promise = googleSuggest()
      returnSearch = function(term, choices) {
        console.log(choices)
        var suggestions = [];
        for (i=0;i<choices.length;i++)
         if (~choices[i].toLowerCase().indexOf(term)) suggestions.push(choices[i]);
          suggest(suggestions);
      }

      $.when(promise).then(function(data) {
        term = term.toLowerCase();
        var result = [];
        $.each(data[1], function(item, value) {
          var stripedValue = value[0].replace(/<[^>]+>/g, '');
             result.push(stripedValue);
        })
        returnSearch(term, result)
      })
    }
  });
})

Also see this stackoverflow post.


问:
maven error: element dependency can not have character children
I'm not sure what happened, but the POM for my project no longer works.  Its complaining about the dependency element.  Is it that the dependency no longer exists?  What does this error mean?  To be clear I haven't change the POM, it just does not work now.

The exact error message is cvc-complex-type.2.3:  Element 'dependency' cannot have character (children), because this type's content type is element-only.

```<code><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.medfusion</groupId>
  <artifactId>Estatements-core</artifactId>
  <version>14.6.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Estatements-core</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.group.id.Launcher1</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>2.3.2</version>
      </plugin>
    </plugins>
  </build>
<repositories>
    <repository>
        <id>nexus-qhg-dev</id>
        <name>Medfusion repo</name>
        <url>http://maven.qhg.local/nexus/content/groups/qhg-dev</url>
    </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>14.6.0-SNAPSHOT</version>
    <artifactId>notification-reference</artifactId>
  </dependency>
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>ihg-depot-trunk-SNAPSHOT</version>
    <artifactId>attachment-reference</artifactId>
  </dependency>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>ihg-depot-trunk-SNAPSHOT</version>
    <artifactId>eCommunication-core</artifactId>
  </dependency>
</dependencies>

</project>
</code>```

答:
As mentioned in the comment by Powerlord, this error is due to incorrect parsing of the XML file, because there are strange and hidden characters in between a/some <dependency>...</dependency> tag(s). Those characters could come from a copy paste from the Web.

To solve the issue, remove all spaces and newline characters between <dependency>...</dependency> tags definitions and put them back into your editor.

Body:
I'm not sure what happened, but the POM for my project no longer works.  Its complaining about the dependency element.  Is it that the dependency no longer exists?  What does this error mean?  To be clear I haven't change the POM, it just does not work now.

The exact error message is cvc-complex-type.2.3:  Element 'dependency' cannot have character (children), because this type's content type is element-only.

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.medfusion</groupId>
  <artifactId>Estatements-core</artifactId>
  <version>14.6.0-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>Estatements-core</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>
<build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
            <configuration>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>com.group.id.Launcher1</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-release-plugin</artifactId>
        <version>2.3.2</version>
      </plugin>
    </plugins>
  </build>
<repositories>
    <repository>
        <id>nexus-qhg-dev</id>
        <name>Medfusion repo</name>
        <url>http://maven.qhg.local/nexus/content/groups/qhg-dev</url>
    </repository>
</repositories>

<dependencies>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>14.6.0-SNAPSHOT</version>
    <artifactId>notification-reference</artifactId>
  </dependency>
  <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>ihg-depot-trunk-SNAPSHOT</version>
    <artifactId>attachment-reference</artifactId>
  </dependency>
  <dependency>
    <groupId>com.intuit.health</groupId>
    <version>ihg-depot-trunk-SNAPSHOT</version>
    <artifactId>eCommunication-core</artifactId>
  </dependency>
</dependencies>

</project>

ContentLicense: CC BY-SA 4.0


问:
How does Python JSON library dealing with time?
So I'm currently learning MongoDB and I'm using PyMongo rather than MongoDB shell.

When I started trying the basic CRUD operations, I found it is hard to load the bios data using PyMongo, since the original data posted on the website had a strange ISODATA for time.

The original python JSON library seemed to be not support this and the mongoimport seemed to be not support this either(not sure). But I found this, after modifying into {$date:"2017-04-01T05:00:00Z"}, mongoimport was working.

Right now I'm using subprocess to call a external command to import the data. So my question is, how to use python correctly read the JSON data and using PyMongo to insert the data.

Details

the bios data in the mongodb documentation looks like this

```<code>{
"_id" : 1,
"name" : {
    "first" : "John",
    "last" : "Backus"
},
"birth" : ISODate("1924-12-03T05:00:00Z"),
"death" : ISODate("2007-03-17T04:00:00Z"),
"contribs" : [
    "Fortran",
    "ALGOL",
    "Backus-Naur Form",
    "FP"
],
"awards" : [
    {
        "award" : "W.W. McDowell Award",
        "year" : 1967,
        "by" : "IEEE Computer Society"
    },
    {
        "award" : "National Medal of Science",
        "year" : 1975,
        "by" : "National Science Foundation"
    },
    {
        "award" : "Turing Award",
        "year" : 1977,
        "by" : "ACM"
    },
    {
        "award" : "Draper Prize",
        "year" : 1993,
        "by" : "National Academy of Engineering"
    }
]
}
</code>```

And when I try to parse it with Python's JSON library, I get a error messagejson.decoder.JSONDecodeError because of the "birth" : ISODate("1924-12-03T05:00:00Z"),. And mongoimport can not parse this because of the same reason.

When I modified,

"birth" : ISODate("1924-12-03T05:00:00Z"), into

"birth" : $date:"2017-04-01T05:00:00Z"

mongoimport was working but python still wasn't able to parse it.

What I am asking here is a way to deal this problem within Python and PyMongo rather than calling a external commands.

答:
The example that you're looking at was probably intended to be used within the mongo shell, where the use of the ISODate bson type can be parsed as shown.

Outside of that, we have the challenge that JSON does not have a date datatype, nor does it have a standard way of representing dates. To deal with this challenge, MongoDB created something called Extended JSON, which can encode dates in JSON similar to how you have shown with $date.

In order to work with Extended JSON in Python / PyMongo, you could use json_util.

Here's a brief example:

```<code>from bson.json_util import loads
from pymongo import MongoClient

json = '''
{
    "_id" : 1,
    "name" : {
        "first" : "John",
        "last" : "Backus"
    },
    "birth" : {"$date":"2017-04-01T05:00:00.000Z"},
    "death" : {"$date":"2017-04-01T05:00:00.000Z"}
}
'''

bson = loads(json)
print(str(bson))
db = MongoClient().test
collection = db.bios
collection.insert(bson)
</code>```

Body:
So I'm currently learning MongoDB and I'm using PyMongo rather than MongoDB shell.

When I started trying the basic CRUD operations, I found it is hard to load the bios data using PyMongo, since the original data posted on the website had a strange ISODATA for time.

The original python JSON library seemed to be not support this and the mongoimport seemed to be not support this either(not sure). But I found this, after modifying into {$date:"2017-04-01T05:00:00Z"}, mongoimport was working.

Right now I'm using subprocess to call a external command to import the data. So my question is, how to use python correctly read the JSON data and using PyMongo to insert the data.

Details

the bios data in the mongodb documentation looks like this

{
"_id" : 1,
"name" : {
    "first" : "John",
    "last" : "Backus"
},
"birth" : ISODate("1924-12-03T05:00:00Z"),
"death" : ISODate("2007-03-17T04:00:00Z"),
"contribs" : [
    "Fortran",
    "ALGOL",
    "Backus-Naur Form",
    "FP"
],
"awards" : [
    {
        "award" : "W.W. McDowell Award",
        "year" : 1967,
        "by" : "IEEE Computer Society"
    },
    {
        "award" : "National Medal of Science",
        "year" : 1975,
        "by" : "National Science Foundation"
    },
    {
        "award" : "Turing Award",
        "year" : 1977,
        "by" : "ACM"
    },
    {
        "award" : "Draper Prize",
        "year" : 1993,
        "by" : "National Academy of Engineering"
    }
]
}

And when I try to parse it with Python's JSON library, I get a error messagejson.decoder.JSONDecodeError because of the "birth" : ISODate("1924-12-03T05:00:00Z"),. And mongoimport can not parse this because of the same reason.

When I modified,

"birth" : ISODate("1924-12-03T05:00:00Z"), into

"birth" : $date:"2017-04-01T05:00:00Z"

mongoimport was working but python still wasn't able to parse it.

What I am asking here is a way to deal this problem within Python and PyMongo rather than calling a external commands.

Body:
The example that you're looking at was probably intended to be used within the mongo shell, where the use of the ISODate bson type can be parsed as shown.

Outside of that, we have the challenge that JSON does not have a date datatype, nor does it have a standard way of representing dates. To deal with this challenge, MongoDB created something called Extended JSON, which can encode dates in JSON similar to how you have shown with $date.

In order to work with Extended JSON in Python / PyMongo, you could use json_util.

Here's a brief example:

from bson.json_util import loads
from pymongo import MongoClient

json = '''
{
    "_id" : 1,
    "name" : {
        "first" : "John",
        "last" : "Backus"
    },
    "birth" : {"$date":"2017-04-01T05:00:00.000Z"},
    "death" : {"$date":"2017-04-01T05:00:00.000Z"}
}
'''

bson = loads(json)
print(str(bson))
db = MongoClient().test
collection = db.bios
collection.insert(bson)


问:
Is it possible to create home screen widgets for Android using Ionic Framework or React Native?
Widgets are android native constructs that extend a view on the application screen.

Is it possible build a homescreen widget using Ionic or react native?

答:
For React Native, at the moment this is not possible. There is an issue on their GitHub, and upvotes for this feature are welcome on the dedicated ProductPains page.

Probably this will eventually be implemented.


问:
canvas sprite sheet error
I found a lovely code snippet on canvas spritesheet animations. this is ts:

http://jsfiddle.net/m1erickson/h85Gq/

I tried to beautify this code, by writing an animate function that accepts Image objects, so that I can animate multiple images in my canvas simultaneously. This is my attempt at it:

```<code>    $(function(){
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var spritePosition=0;
        var spriteWidth=100;
        var spriteHeight=100;
        var spriteCount=40;
        var spritePlayCount=0;
        var maxSpritePlays=2;

        var objectS=new Image();
        objectS.src="sprites/first.png";

        var fps = 50;
        function animate(sprite) {
            setTimeout(function() {

                if(spritePlayCount<maxSpritePlays){
                    requestAnimationFrame(animate);
                }

                // Drawing code goes here
                ctx.clearRect(0,0,canvas.width,canvas.height);
                ctx.drawImage(sprite,spritePosition*spriteWidth, 0,spriteWidth, spriteHeight, 0,0,spriteWidth, spriteHeight);

                spritePosition++;
                if(spritePosition>spriteCount-1){
                    spritePosition=0;
                    spritePlayCount++;
                }
            }, 1000 / fps);
        }

        objectS.onload=function(){
            animate(objectS);
        }
    }); // end $(function(){});
</code>```

I am getting a much observed error, but I cant seem to find the fix for it:

index3.html:59 Uncaught TypeError: Failed to execute 'drawImage' on
  'CanvasRenderingContext2D': The provided value is not of type
  '(CSSImageValue or HTMLImageElement or HTMLVideoElement or
  HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Can you help me out finding my bug?

答:
OMDG!

quote OP "Imagine having 50 spritesheets you want to animate."

50!

Looking at the code "accepted answer version"

```<code>function animate(sprite) {
    // create a timer event to fire in 1/50th second
    setTimeout(function() {
         if (spritePlayCount < maxSpritePlays) {
            // create a animation frame event that may fire at some time
            // between 0 and 16ms or 32ms from now
            requestAnimationFrame(function() {
                animate(sprite);
            });
        }
        // Drawing code etc... Make canvas dirty
        // exiting with dirty canvas outside the requestAnimationFrame
        // forces DOM to swap canvas backbuffer immediately on exit.

    }, 1000 / 50);
}
</code>```

This is the worst possible way to animate one, let alone more than one sprite.

The timing is out of sync with the display refresh.

Using requestAnimationFrame's callback to create a timed event that renders, completely negates the reason for using requestAnimationFrame. requestAnimationFrame tells the DOM that what you draw in the callback is part of an animation. Using a timer to draw means you don't draw anything in the requested frame making the request redundant.

requestAnimationFrame does its best to get all the callbacks in before the next display refresh (1/60th) but it will delay the callback if there is no time to update the DOM (swap all dirty buffers) before the next refresh. You have no control over the timing of your animation, they may fire anywhere from 20ms to 36ms or more with no consistency over time.

By using timers to draw to the canvas you are forcing a backbuffer swap for each sprite you draw. This is an expensive process and will severely limit the speed that you can draw sprites at, and cause sprites to flicker and shear randomly during animation.

The best practice way.

Use a single animation loop triggered by requestAnimationFrame.

Use an array to store all sprites and update them in the main loop if/as needed.

Only render from within the main loop. Do not render or do anything (at a regular interval) to the DOM outside the main loop's execution.

Don't render inside events like timers, IO, or any other rapidly firing event.

Title: canvas sprite sheet error

Body:
I found a lovely code snippet on canvas spritesheet animations. this is ts:

http://jsfiddle.net/m1erickson/h85Gq/

I tried to beautify this code, by writing an animate function that accepts Image objects, so that I can animate multiple images in my canvas simultaneously. This is my attempt at it:

    $(function(){
        var canvas=document.getElementById("canvas");
        var ctx=canvas.getContext("2d");
        var spritePosition=0;
        var spriteWidth=100;
        var spriteHeight=100;
        var spriteCount=40;
        var spritePlayCount=0;
        var maxSpritePlays=2;

        var objectS=new Image();
        objectS.src="sprites/first.png";

        var fps = 50;
        function animate(sprite) {
            setTimeout(function() {

                if(spritePlayCount<maxSpritePlays){
                    requestAnimationFrame(animate);
                }

                // Drawing code goes here
                ctx.clearRect(0,0,canvas.width,canvas.height);
                ctx.drawImage(sprite,spritePosition*spriteWidth, 0,spriteWidth, spriteHeight, 0,0,spriteWidth, spriteHeight);

                spritePosition++;
                if(spritePosition>spriteCount-1){
                    spritePosition=0;
                    spritePlayCount++;
                }
            }, 1000 / fps);
        }

        objectS.onload=function(){
            animate(objectS);
        }
    }); // end $(function(){});

I am getting a much observed error, but I cant seem to find the fix for it:

index3.html:59 Uncaught TypeError: Failed to execute 'drawImage' on
  'CanvasRenderingContext2D': The provided value is not of type
  '(CSSImageValue or HTMLImageElement or HTMLVideoElement or
  HTMLCanvasElement or ImageBitmap or OffscreenCanvas)'

Can you help me out finding my bug?

Body:
OMDG!

quote OP "Imagine having 50 spritesheets you want to animate."

50!

Looking at the code "accepted answer version"

function animate(sprite) {
    // create a timer event to fire in 1/50th second
    setTimeout(function() {
         if (spritePlayCount < maxSpritePlays) {
            // create a animation frame event that may fire at some time
            // between 0 and 16ms or 32ms from now
            requestAnimationFrame(function() {
                animate(sprite);
            });
        }
        // Drawing code etc... Make canvas dirty
        // exiting with dirty canvas outside the requestAnimationFrame
        // forces DOM to swap canvas backbuffer immediately on exit.

    }, 1000 / 50);
}

This is the worst possible way to animate one, let alone more than one sprite.

The timing is out of sync with the display refresh.

Using requestAnimationFrame's callback to create a timed event that renders, completely negates the reason for using requestAnimationFrame. requestAnimationFrame tells the DOM that what you draw in the callback is part of an animation. Using a timer to draw means you don't draw anything in the requested frame making the request redundant.

requestAnimationFrame does its best to get all the callbacks in before the next display refresh (1/60th) but it will delay the callback if there is no time to update the DOM (swap all dirty buffers) before the next refresh. You have no control over the timing of your animation, they may fire anywhere from 20ms to 36ms or more with no consistency over time.

By using timers to draw to the canvas you are forcing a backbuffer swap for each sprite you draw. This is an expensive process and will severely limit the speed that you can draw sprites at, and cause sprites to flicker and shear randomly during animation.

The best practice way.

Use a single animation loop triggered by requestAnimationFrame.

Use an array to store all sprites and update them in the main loop if/as needed.

Only render from within the main loop. Do not render or do anything (at a regular interval) to the DOM outside the main loop's execution.

Don't render inside events like timers, IO, or any other rapidly firing event.


问:
Compiling Twisted on Alpine Linux for Python 3.6
I have the following Dockerfile, where I'm trying to compile Twisted with Python 3.6 as a target.

```<code>FROM alpine:3.5

RUN apk --update add \
      build-base libffi-dev openssl-dev python3-dev \
      libffi openssl ca-certificates python3
RUN apk add \
      py-pip \
      py-lxml \
      py-pillow
RUN \
    pip install --upgrade python-dateutil \
                          arrow \
                          pytz \
                          zope.interface \
                          https://files.pythonhosted.org/packages/source/T/Twisted/Twisted-17.1.0.tar.bz2 \
                          jinja2
RUN \
    apk del build-base libffi-dev openssl-dev python3-dev && \
    rm -rf /var/cache/apk/* && \
    rm -rf ~/.cache/ && \
    adduser -D -u 1001 noroot

USER noroot

CMD ["/bin/sh"]
</code>```

My problem is that I'm getting the following error, after Twisted has been copied:

```<code>gcc -fno-strict-aliasing -Os
  -fomit-frame-pointer -g -DNDEBUG -Os -fomit-frame-pointer
  -g -fPIC -I/usr/include/python2.7 -c src/twisted/test/raiser.c
  -o build/temp.linux-x86_64-2.7/src/twisted/test/raiser.o
  src/twisted/test/raiser.c:4:20: fatal error: Python.h: No such file or
  directory
</code>```

So it appears that something in Twisted is referring to the Python 2.7 headers, which I have not installed, as I'm not planning to target that version.

I can't find a special version of the Twisted download targeting Python 3.6.

I belong to those who stick to 2.7 mainly because of Twisted, and I was just trying to get my feet wet with 3.6, so keep that in mind when answering. I just wanted to check if my code runs on 3.6, what modifications I will have to make. But compiling Twisted is my first barrier.

答:
The py-pip package, which you are installing, is for python 2.x.  Because of this, when you call pip install ... you are installing packages for python 2.x.

The python3 packages provides a pip3 command for python 3.  In general, py-<something> is for Python 2.x, and py3-<something> is for Python 3.x.  In other words:

```<code>FROM alpine:3.5

RUN apk --update add \
      build-base libffi-dev openssl-dev python3-dev \
      libffi openssl ca-certificates python3
RUN apk add \
      py3-lxml \
      py3-pillow
RUN \
    pip3 install --upgrade python-dateutil \
                          arrow \
                          pytz \
                          zope.interface \
                          https://files.pythonhosted.org/packages/source/T/Twisted/Twisted-17.1.0.tar.bz2 \
                          jinja2
RUN \
    apk del build-base libffi-dev openssl-dev python3-dev && \
    rm -rf /var/cache/apk/* && \
    rm -rf ~/.cache/ && \
    adduser -D -u 1001 noroot

USER noroot

CMD ["/bin/sh"]
</code>```

Body:
I have the following Dockerfile, where I'm trying to compile Twisted with Python 3.6 as a target.

FROM alpine:3.5

RUN apk --update add \
      build-base libffi-dev openssl-dev python3-dev \
      libffi openssl ca-certificates python3
RUN apk add \
      py-pip \
      py-lxml \
      py-pillow
RUN \
    pip install --upgrade python-dateutil \
                          arrow \
                          pytz \
                          zope.interface \
                          https://files.pythonhosted.org/packages/source/T/Twisted/Twisted-17.1.0.tar.bz2 \
                          jinja2
RUN \
    apk del build-base libffi-dev openssl-dev python3-dev && \
    rm -rf /var/cache/apk/* && \
    rm -rf ~/.cache/ && \
    adduser -D -u 1001 noroot

USER noroot

CMD ["/bin/sh"]

My problem is that I'm getting the following error, after Twisted has been copied:

gcc -fno-strict-aliasing -Os
  -fomit-frame-pointer -g -DNDEBUG -Os -fomit-frame-pointer
  -g -fPIC -I/usr/include/python2.7 -c src/twisted/test/raiser.c
  -o build/temp.linux-x86_64-2.7/src/twisted/test/raiser.o
  src/twisted/test/raiser.c:4:20: fatal error: Python.h: No such file or
  directory

So it appears that something in Twisted is referring to the Python 2.7 headers, which I have not installed, as I'm not planning to target that version.

I can't find a special version of the Twisted download targeting Python 3.6.

I belong to those who stick to 2.7 mainly because of Twisted, and I was just trying to get my feet wet with 3.6, so keep that in mind when answering. I just wanted to check if my code runs on 3.6, what modifications I will have to make. But compiling Twisted is my first barrier.

Body:
The py-pip package, which you are installing, is for python 2.x.  Because of this, when you call pip install ... you are installing packages for python 2.x.

The python3 packages provides a pip3 command for python 3.  In general, py-<something> is for Python 2.x, and py3-<something> is for Python 3.x.  In other words:

FROM alpine:3.5

RUN apk --update add \
      build-base libffi-dev openssl-dev python3-dev \
      libffi openssl ca-certificates python3
RUN apk add \
      py3-lxml \
      py3-pillow
RUN \
    pip3 install --upgrade python-dateutil \
                          arrow \
                          pytz \
                          zope.interface \
                          https://files.pythonhosted.org/packages/source/T/Twisted/Twisted-17.1.0.tar.bz2 \
                          jinja2
RUN \
    apk del build-base libffi-dev openssl-dev python3-dev && \
    rm -rf /var/cache/apk/* && \
    rm -rf ~/.cache/ && \
    adduser -D -u 1001 noroot

USER noroot

CMD ["/bin/sh"]


问:
Merge sort implementation questions in Java
I'm in an algorithms course and am learning about merge sort. Our professor recommended we try to implement the pseudo code provided in the book.

Am I correct in using Integer.MAX_VALUE as a sentinel value when
sorting an array of integers (used in lines 8 & 9 in the Merge
method pseudo code below)?

For line 2 of the Merge-Sort pseudo code method, is it correct to code that in Java using Math.ceil() like I did? (Edit: It's actually floor and I updated my code to reflect this.)

If you see any other mistakes please let me know!

Here is the pseudo code the book gives for merge sort.

And, here is how I coded it in Java:

```<code>public void mergeSort(int[] arrNums, int p, int r) {
    if (p < r) {
        int q = (p + r) / 2;
        mergeSort(arrNums, p, q);
        mergeSort(arrNums, q + 1, r);
        merge(arrNums, p, q, r);
    }
}

public void merge(int[] arrNums, int p, int q, int r) {
    int nOne = q - p + 1;
    int nTwo = r - q;

    int[] arrLeft = new int[nOne + 1];
    int[] arrRight = new int[nTwo + 1];

    for (int i = 0; i < nOne; i++) {
        arrLeft[i] = arrNums[p + i - 1];
    }

    for (int j = 0; j < nTwo; j++) {
        arrRight[j] = arrNums[q + j];
    }

    arrLeft[nOne] = Integer.MAX_VALUE;
    arrRight[nTwo] = Integer.MAX_VALUE;

    // Tracks arrLeft index
    int i = 0;

    // Tracks arrRight index
    int j = 0;

    for (int k = p; k < r; k++) {
        if (arrLeft[i] <= arrRight[j]) {
            arrNums[k] = arrLeft[i];
            i++;
        } else {
            arrNums[k] = arrRight[j];
            j++;
        }
    }
}
</code>```

答:
The last for loop in your merge method, variable k should start from p - 1:

```<code>for (int k = p - 1; k < r; k++) {
    if (arrLeft[i] <= arrRight[j]) {
        arrNums[k] = arrLeft[i];
        i++;
    } else {
        arrNums[k] = arrRight[j];
        j++;
    }
}
</code>```

Pseudo code in many text books likes to start array index from 1, so here you need to subtract it by 1.

Body:
I'm in an algorithms course and am learning about merge sort. Our professor recommended we try to implement the pseudo code provided in the book.

Am I correct in using Integer.MAX_VALUE as a sentinel value when
sorting an array of integers (used in lines 8 & 9 in the Merge
method pseudo code below)?

For line 2 of the Merge-Sort pseudo code method, is it correct to code that in Java using Math.ceil() like I did? (Edit: It's actually floor and I updated my code to reflect this.)

If you see any other mistakes please let me know!

Here is the pseudo code the book gives for merge sort.

And, here is how I coded it in Java:

public void mergeSort(int[] arrNums, int p, int r) {
    if (p < r) {
        int q = (p + r) / 2;
        mergeSort(arrNums, p, q);
        mergeSort(arrNums, q + 1, r);
        merge(arrNums, p, q, r);
    }
}

public void merge(int[] arrNums, int p, int q, int r) {
    int nOne = q - p + 1;
    int nTwo = r - q;

    int[] arrLeft = new int[nOne + 1];
    int[] arrRight = new int[nTwo + 1];

    for (int i = 0; i < nOne; i++) {
        arrLeft[i] = arrNums[p + i - 1];
    }

    for (int j = 0; j < nTwo; j++) {
        arrRight[j] = arrNums[q + j];
    }

    arrLeft[nOne] = Integer.MAX_VALUE;
    arrRight[nTwo] = Integer.MAX_VALUE;

    // Tracks arrLeft index
    int i = 0;

    // Tracks arrRight index
    int j = 0;

    for (int k = p; k < r; k++) {
        if (arrLeft[i] <= arrRight[j]) {
            arrNums[k] = arrLeft[i];
            i++;
        } else {
            arrNums[k] = arrRight[j];
            j++;
        }
    }
}

Body:
The last for loop in your merge method, variable k should start from p - 1:

for (int k = p - 1; k < r; k++) {
    if (arrLeft[i] <= arrRight[j]) {
        arrNums[k] = arrLeft[i];
        i++;
    } else {
        arrNums[k] = arrRight[j];
        j++;
    }
}

Pseudo code in many text books likes to start array index from 1, so here you need to subtract it by 1.


问:
Getting run-time error running VBA code not my own
I need to reverse engineer someone else's code and make it run. Right now it is throwing an error at me complaining that some variable isn't set.

I'm not sure what it is talking about exactly. Here is the top part of the subroutine with the error.

```<code>Sub OBI_Vendor_Detail_Macro()
    Cells.Select
    With Selection
        .WrapText = False
        .MergeCells = False
    End With
    Range("C4").Select
    Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate
</code>```

The last line produces this error Run-time error '91': Object variable or With block variable not set

Hope I've provided enough info. If not please let me know. Thanks.

答:
You need to try to Find first, then check that you found something:

```<code>Dim foundCell As Range
Set foundCell = Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If Not foundCell Is Nothing Then
  foundCell.Activate
End If
</code>```

Body:
I need to reverse engineer someone else's code and make it run. Right now it is throwing an error at me complaining that some variable isn't set.

I'm not sure what it is talking about exactly. Here is the top part of the subroutine with the error.

Sub OBI_Vendor_Detail_Macro()
    Cells.Select
    With Selection
        .WrapText = False
        .MergeCells = False
    End With
    Range("C4").Select
    Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False).Activate

The last line produces this error Run-time error '91': Object variable or With block variable not set

Hope I've provided enough info. If not please let me know. Thanks.

Body:
You need to try to Find first, then check that you found something:

Dim foundCell As Range
Set foundCell = Cells.Find(What:="Grand Total", After:=ActiveCell, LookIn:=xlFormulas, _
        LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
        MatchCase:=False, SearchFormat:=False)

If Not foundCell Is Nothing Then
  foundCell.Activate
End If


问:
Accessing array elements using the associative index and numbered index
Is it possible to define an array where I can access the elements via their string and numeric index?</p>

答:
array_values() will return all values in an array with their indices replaced with numeric ones.

http://php.net/array-values

```<code>$x = array(
    'a' => 'x',
    'b' => 'y'
);
$x2 = array_values($x);

echo $x['a']; // 'x'
echo $x2[0]; // 'x'
</code>```

The alternative is to build a set of by-reference indices.

```<code>function buildReferences(& $array) {
    $references = array();
    foreach ($array as $key => $value) {
        $references[] =& $array[$key];
    }
    $array = array_merge($references, $array);
}

$array = array(
    'x' => 'y',
    'z' => 'a'
);

buildReferences($array);
</code>```

Note that this should only be done if you're not planning on adding or removing indices.  You can edit them though.

ContentLicense: CC BY-SA 2.5

Body:
array_values() will return all values in an array with their indices replaced with numeric ones.

http://php.net/array-values

$x = array(
    'a' => 'x',
    'b' => 'y'
);
$x2 = array_values($x);

echo $x['a']; // 'x'
echo $x2[0]; // 'x'

The alternative is to build a set of by-reference indices.

function buildReferences(& $array) {
    $references = array();
    foreach ($array as $key => $value) {
        $references[] =& $array[$key];
    }
    $array = array_merge($references, $array);
}

$array = array(
    'x' => 'y',
    'z' => 'a'
);

buildReferences($array);

Note that this should only be done if you're not planning on adding or removing indices.  You can edit them though.


问:
Setting up a frame in Java
I am new to Java and I've been trying to setup a frame, but my code does not work, either because the code is just wrong, or because there is something wrong with my software. I am using Eclipse.

So this is my code:

```<code>package Frame;

import javax.swing.JFrame;

public class App {

 class FrameApp extends JFrame {

     public static void main(String[] args) {

        JFrame frame = new JFrame("FirstFrame");
        frame.setTitle("MFF");
        frame.setSize(300, 700);
        frame.setVisible(true);

     }
  }

}
</code>```

it returns

The method main cannot be declared static; static methods can only be
  declared in a static or top level type

答:
You can do it this way, which is not extending JFrame.

```<code>import javax.swing.JFrame;

public class App{
    public App() {
        JFrame frame = new JFrame("FirstFrame"); // This sets the title
        frame.setTitle("MFF"); // Then you're resetting the title
        frame.setSize(300, 700);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
    public static void main(String[] args) {
        new App();
    }

}
</code>```

Or you can extend it

```<code>import javax.swing.JFrame;

public class App extends JFrame{
    public App() {
        // When you extend JFrame you're essentially creating a JFrame
        // This gets into OOP (which you of course need to learn)
        // Since you've extended the JFrame you can directly access its methods
        // like setTitle, setSize....
        setTitle("MFF");
        setSize(300, 700);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
    public static void main(String[] args) {
        new App();
    }

}
</code>```

I'm definitely not very experienced with Swing, but when choosing one approach
  over the other. I choose not to extend the Frame. And to answer your
  question, there's no reason to put another class within the App class
  when just creating this simple JFramethat is why I changed to the
  above.

Title: Setting up a frame in Java

Body:
I am new to Java and I've been trying to setup a frame, but my code does not work, either because the code is just wrong, or because there is something wrong with my software. I am using Eclipse.

So this is my code:

package Frame;

import javax.swing.JFrame;

public class App {

 class FrameApp extends JFrame {

     public static void main(String[] args) {

        JFrame frame = new JFrame("FirstFrame");
        frame.setTitle("MFF");
        frame.setSize(300, 700);
        frame.setVisible(true);

     }
  }

}

it returns

The method main cannot be declared static; static methods can only be
  declared in a static or top level type

Body:
You can do it this way, which is not extending JFrame.

import javax.swing.JFrame;

public class App{
    public App() {
        JFrame frame = new JFrame("FirstFrame"); // This sets the title
        frame.setTitle("MFF"); // Then you're resetting the title
        frame.setSize(300, 700);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
    public static void main(String[] args) {
        new App();
    }

}

Or you can extend it

import javax.swing.JFrame;

public class App extends JFrame{
    public App() {
        // When you extend JFrame you're essentially creating a JFrame
        // This gets into OOP (which you of course need to learn)
        // Since you've extended the JFrame you can directly access its methods
        // like setTitle, setSize....
        setTitle("MFF");
        setSize(300, 700);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 }
    public static void main(String[] args) {
        new App();
    }

}

I'm definitely not very experienced with Swing, but when choosing one approach
  over the other. I choose not to extend the Frame. And to answer your
  question, there's no reason to put another class within the App class
  when just creating this simple JFramethat is why I changed to the
  above.


问:
find cell, make active cell and repeat
I have this simple code to run on startup, it works fine except I need it to make the current founded cell with the "true" statement the ActiveCell and run the "Call" on that ActiveCell , and then move to the next "true" find and make that the ActiveCell and repeat the process.

```<code>For Each c In sheet1.Range("AU5:AU1000")
    If c.value = True Then
        Call startup.VALUES
    End If
Next c
</code>```

problem is it finds all the "true" values , but repeat the process on current ActiveCell

答:
Are you trying to send "True"to the sub "startup" if "True" is the value of the cell? </p>

```<code>Dim rng As  Range, c As Range

Set rng =  Worksheets("Sheet1").Range("AU5:AU1000")

For Each c in rng
    If c.value = True Then
     valToSend = c.value
    Call startup(valToSend)
 End If
Next c
</code>```

<p>I can't test this, as I'm on my phone. </p>

Title: find cell, make active cell and repeat

Body:
I have this simple code to run on startup, it works fine except I need it to make the current founded cell with the "true" statement the ActiveCell and run the "Call" on that ActiveCell , and then move to the next "true" find and make that the ActiveCell and repeat the process.

For Each c In sheet1.Range("AU5:AU1000")
    If c.value = True Then
        Call startup.VALUES
    End If
Next c

problem is it finds all the "true" values , but repeat the process on current ActiveCell

Body:
Are you trying to send "True"to the sub "startup" if "True" is the value of the cell?

Dim rng As  Range, c As Range

Set rng =  Worksheets("Sheet1").Range("AU5:AU1000")

For Each c in rng
    If c.value = True Then
     valToSend = c.value
    Call startup(valToSend)
 End If
Next c

I can't test this, as I'm on my phone.


问:
Is there a way (script ?) to redirect a first visitor of my website to, say welcomepage.html instead of index.html?
Hello I'm learning html/css by doing my own website. I'm curious as I want my website to show a different page than index.html for a first time visitor. I know it involve something like cookies and I've seen scripts in similar thread in php, but I don't now where should I put it. I don't know nothing about php, should I put it in a .php page? or Can someone suggest me a ressource to learn to do it comprehensively? </p>

答:
Let's play around with cookies!  Basically, when the user firsts visits, we set a a cookie.  Hence you get a "new visitor", after you click run again you will see, "Hello, old visitor".  I wrote an example:

```<code><?php

if (isset($_COOKIE['visit'])) {
    echo "Hello, old visitor.";
} else {
    echo "new visitor";
    setcookie("visit", true, time() + 5, "/"); //cookie will expire in 5 seconds
}

?>
</code>```

Body:
Let's play around with cookies!  Basically, when the user firsts visits, we set a a cookie.  Hence you get a "new visitor", after you click run again you will see, "Hello, old visitor".  I wrote an example:

<?php

if (isset($_COOKIE['visit'])) {
    echo "Hello, old visitor.";
} else {
    echo "new visitor";
    setcookie("visit", true, time() + 5, "/"); //cookie will expire in 5 seconds
}

?>


问:
Word splitting in Bash with IFS set to a non-whitespace character
I'm going through a Bash tutorial, and specifically the subject of word splitting.

This script, called "args", helps demonstrate word splitting examples:

```<code>#!/usr/bin/env bash
printf "%d args:" $#
printf " <%s>" "$@"
echo
</code>```

An example:

```<code>$ ./args hello world, here is "a string of text!"
5 args: <hello> <world,> <here> <is> <a string of text!>
</code>```

So far so good. I understand how this works.

However, when I replace IFS with a non-whitespace character, say :, the script does not perform word splitting if I pass the string directly as an argument.

```<code>$ ./args one:two:three
1 args: <one:two:three>
</code>```

However, the script does perform word splitting on the same string if I (1) assign the string to a variable, and then (2) pass the string to the script via parameter expansion.

```<code>$ IFS=:
$ variable="one:two:three"
$ ./args $variable
3 args: <one> <two> <three>
</code>```

Why? Specifically, why does passing the string as an argument undergo word splitting when IFS is unset and the delimiters are whitespace characters, but not when IFS is set to non-whitespace characters?

When I use read instead of this script, the same string also undergoes word splitting as expected.

```<code>$ IFS=:
$ read a b c
one:two:three
$ echo $a $b $c
one two three
</code>```

答:
You can read more about word splitting here.

The shell scans the results of parameter expansion, command substitution,
  and arithmetic expansion that did not occur within double quotes for word splitting.

When you pass the bare string one:two:three as an argument with IFS set to :, Bash doesn't do word splitting because the bare string is not one of parameter expansion, command substitution, or arithmetic expansion contexts.

However, when the same string is assigned to a variable and the variable is passed to the script unquoted, word splitting does occur as it is a case of parameter expansion.

The same thing applies to these as well (command substitution):

```<code>$ ./args $(echo one:two:three)
3 args: <one> <two> <three>

$ ./args "$(echo one:two:three)"
1 args: <one:two:three>
</code>```

As documented, read command does do word splitting on every line read, unless IFS has been set to an empty string.

Body:
I'm going through a Bash tutorial, and specifically the subject of word splitting.

This script, called "args", helps demonstrate word splitting examples:

#!/usr/bin/env bash
printf "%d args:" $#
printf " <%s>" "$@"
echo

An example:

$ ./args hello world, here is "a string of text!"
5 args: <hello> <world,> <here> <is>

So far so good. I understand how this works.

However, when I replace IFS with a non-whitespace character, say :, the script does not perform word splitting if I pass the string directly as an argument.

$ ./args one:two:three
1 args: <one:two:three>

However, the script does perform word splitting on the same string if I (1) assign the string to a variable, and then (2) pass the string to the script via parameter expansion.

$ IFS=:
$ variable="one:two:three"
$ ./args $variable
3 args: <one> <two> <three>

Why? Specifically, why does passing the string as an argument undergo word splitting when IFS is unset and the delimiters are whitespace characters, but not when IFS is set to non-whitespace characters?

When I use read instead of this script, the same string also undergoes word splitting as expected.

$ IFS=:
$ read a b c
one:two:three
$ echo $a $b $c
one two three

Body:
You can read more about word splitting here.

The shell scans the results of parameter expansion, command substitution,
  and arithmetic expansion that did not occur within double quotes for word splitting.

When you pass the bare string one:two:three as an argument with IFS set to :, Bash doesn't do word splitting because the bare string is not one of parameter expansion, command substitution, or arithmetic expansion contexts.

However, when the same string is assigned to a variable and the variable is passed to the script unquoted, word splitting does occur as it is a case of parameter expansion.

The same thing applies to these as well (command substitution):

$ ./args $(echo one:two:three)
3 args: <one> <two> <three>

$ ./args "$(echo one:two:three)"
1 args: <one:two:three>

As documented, read command does do word splitting on every line read, unless IFS has been set to an empty string.


问:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 23
I tried to use the following Mysql Query to create procedure, but I always get the error:

```<code> #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 23
</code>```

Here is my SQL Statement, basically I hope to get, set, update my data informtion.

```<code>USE AddressBook;
    DELIMITER $$
    CREATE PROCEDURE CreateContact (
                IN FirstName_IN VARCHAR(50) = null,
      IN LastName_IN VARCHAR(50) = null,
      IN Phone_IN VARCHAR(20) = null,
      IN Email_IN VARCHAR(50) = null,
      IN Address_IN VARCHAR(100) = null,
      IN City_IN VARCHAR(30) = null,
      IN State_IN VARCHAR(30) = null,
      IN Country_IN VARCHAR(30) = null,
      IN PostalCode_IN VARCHAR(10) = null,
      OUT id INT)
    BEGIN
      INSERT INTO AddressBook.Contact (
        FirstName,
        LastName,
        Phone,
        Email,
        Address,
        City,
        State,
        Country,
       PostalCode)
       VALUES (FirstName_IN, LastName_IN, Phone_IN, Email_IN, Address_IN, City_IN, State_IN, Country_IN, PostalCode_IN)$$
    END$$
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.CreateContactImage (
              IN FirstName_IN VARCHAR(50) = null,
      IN LastName_IN VARCHAR(50) = null,
      IN Phone_IN VARCHAR(20) = null,
      IN Email_IN VARCHAR(50) = null,
      IN Address_IN VARCHAR(100) = null,
      IN City_IN VARCHAR(30) = null,
      IN State_IN VARCHAR(30) = null,
      IN Country_IN VARCHAR(30) = null,
      IN PostalCode_IN VARCHAR(10) = null,
      Id INT OUTPUT)
    BEGIN
      INSERT INTO AddressBook.Contact (
        FirstName,
        LastName,
        Phone,
        Email,
        Address,
        City,
        State,
        Country,
       PostalCode)
       VALUES (FirstName_IN, LastName_IN, Phone_IN, Email_IN, Address_IN, City_IN, State_IN, Country_IN, PostalCode_IN)
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.CreateContactImage (
    IN ImageName_IN VARCHAR(50),
    IN ImagePath_IN VARCHAR(21844),
    IN ContactId_IN INT,
    Id INT OUTPUT)
    BEGIN
    INSERT INTO AddressBook.ContactImage (ImageName,ImagePath,ContactId)
         VALUES (ImageName_IN,ImagePath_IN,ContactId_IN)
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.DeleteContact (
    Id_IN INT)
    BEGIN
    DELETE FROM AddressBook.Contact
          WHERE Id = Id_IN
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetAllContacts ()
    BEGIN
    SELECT *  FROM dbo.Contact
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetAllImageByContactId (
    ContactId_IN INT)
    BEGIN
    SELECT * FROM  AddressBook.ContactImage
               where ContactId = ContactId_IN
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetContactById (
    Id_IN INT)
    BEGIN
    select *  FROM AddressBook.Contact
          WHERE Id = Id_IN
    END$$;
    DELIMITER $$;
    create procedure AddressBook.UpdateContact
    FirstName_IN VARCHAR(50) = null,
      LastName_IN VARCHAR(50) = null,
      Phone_IN VARCHAR(20) = null,
      Email_IN VARCHAR(50) = null,
      Address_IN VARCHAR(100) = null,
      City_IN VARCHAR(30) = null,
      State_IN VARCHAR(30) = null,
      Country_IN VARCHAR(30) = null,
      PostalCode_IN VARCHAR(10) = null,
      Id_IN INT)
    BEGIN
    UPDATE AddressBook.Contact
       SET FirstName = FirstName_IN
          ,LastName = LastName_IN
          ,Phone = Phone_IN
          ,Email = Email_IN
          ,Address = Address_IN
          ,City = City_IN
          ,State = State_IN
          ,Country = Country_IN
          ,PostalCode = PostalCode_IN
     WHERE Id = Id_IN
     END$$;
     DELIMITER ;
</code>```

Can anyone help me fix this error?

答:
I believe that you are also missing an opening parenthesis here:

```<code>create procedure AddressBook.UpdateContact
</code>```

... should be:

```<code>create procedure AddressBook.UpdateContact(
</code>```

Body:
I tried to use the following Mysql Query to create procedure, but I always get the error:

 #1064 - You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 23

Here is my SQL Statement, basically I hope to get, set, update my data informtion.

USE AddressBook;
    DELIMITER $$
    CREATE PROCEDURE CreateContact (
                IN FirstName_IN VARCHAR(50) = null,
      IN LastName_IN VARCHAR(50) = null,
      IN Phone_IN VARCHAR(20) = null,
      IN Email_IN VARCHAR(50) = null,
      IN Address_IN VARCHAR(100) = null,
      IN City_IN VARCHAR(30) = null,
      IN State_IN VARCHAR(30) = null,
      IN Country_IN VARCHAR(30) = null,
      IN PostalCode_IN VARCHAR(10) = null,
      OUT id INT)
    BEGIN
      INSERT INTO AddressBook.Contact (
        FirstName,
        LastName,
        Phone,
        Email,
        Address,
        City,
        State,
        Country,
       PostalCode)
       VALUES (FirstName_IN, LastName_IN, Phone_IN, Email_IN, Address_IN, City_IN, State_IN, Country_IN, PostalCode_IN)$$
    END$$
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.CreateContactImage (
              IN FirstName_IN VARCHAR(50) = null,
      IN LastName_IN VARCHAR(50) = null,
      IN Phone_IN VARCHAR(20) = null,
      IN Email_IN VARCHAR(50) = null,
      IN Address_IN VARCHAR(100) = null,
      IN City_IN VARCHAR(30) = null,
      IN State_IN VARCHAR(30) = null,
      IN Country_IN VARCHAR(30) = null,
      IN PostalCode_IN VARCHAR(10) = null,
      Id INT OUTPUT)
    BEGIN
      INSERT INTO AddressBook.Contact (
        FirstName,
        LastName,
        Phone,
        Email,
        Address,
        City,
        State,
        Country,
       PostalCode)
       VALUES (FirstName_IN, LastName_IN, Phone_IN, Email_IN, Address_IN, City_IN, State_IN, Country_IN, PostalCode_IN)
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.CreateContactImage (
    IN ImageName_IN VARCHAR(50),
    IN ImagePath_IN VARCHAR(21844),
    IN ContactId_IN INT,
    Id INT OUTPUT)
    BEGIN
    INSERT INTO AddressBook.ContactImage (ImageName,ImagePath,ContactId)
         VALUES (ImageName_IN,ImagePath_IN,ContactId_IN)
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.DeleteContact (
    Id_IN INT)
    BEGIN
    DELETE FROM AddressBook.Contact
          WHERE Id = Id_IN
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetAllContacts ()
    BEGIN
    SELECT *  FROM dbo.Contact
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetAllImageByContactId (
    ContactId_IN INT)
    BEGIN
    SELECT * FROM  AddressBook.ContactImage
               where ContactId = ContactId_IN
    END$$;
    DELIMITER $$;
    CREATE PROCEDURE AddressBook.GetContactById (
    Id_IN INT)
    BEGIN
    select *  FROM AddressBook.Contact
          WHERE Id = Id_IN
    END$$;
    DELIMITER $$;
    create procedure AddressBook.UpdateContact
    FirstName_IN VARCHAR(50) = null,
      LastName_IN VARCHAR(50) = null,
      Phone_IN VARCHAR(20) = null,
      Email_IN VARCHAR(50) = null,
      Address_IN VARCHAR(100) = null,
      City_IN VARCHAR(30) = null,
      State_IN VARCHAR(30) = null,
      Country_IN VARCHAR(30) = null,
      PostalCode_IN VARCHAR(10) = null,
      Id_IN INT)
    BEGIN
    UPDATE AddressBook.Contact
       SET FirstName = FirstName_IN
          ,LastName = LastName_IN
          ,Phone = Phone_IN
          ,Email = Email_IN
          ,Address = Address_IN
          ,City = City_IN
          ,State = State_IN
          ,Country = Country_IN
          ,PostalCode = PostalCode_IN
     WHERE Id = Id_IN
     END$$;
     DELIMITER ;

Can anyone help me fix this error?

Body:
I believe that you are also missing an opening parenthesis here:

create procedure AddressBook.UpdateContact

... should be:

create procedure AddressBook.UpdateContact(


问:
Pass struct by reference in C
Is this code correct? It runs as expected, but is this code correctly using the pointers and dot notation for the struct?</p>

```<code>struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}
</code>```

答:
That's correct usage of the struct. There are questions about your return values.

Also, because you are printfing a unsigned int, you should use %u instead of %d.

Title: Pass struct by reference in C

Body:
Is this code correct? It runs as expected, but is this code correctly using the pointers and dot notation for the struct?

struct someStruct {
 unsigned int total;
};

int test(struct someStruct* state) {
 state->total = 4;
}

int main () {
 struct someStruct s;
 s.total = 5;
 test(&s);
 printf("\ns.total = %d\n", s.total);
}


问:
Pandas multiindex dataframe - Selecting max from one index within multiindex
I've got a dataframe with a multi index of Year and Month like the following

```<code>     |     |Value
Year |Month|
     |  1  |  3
1992 |  2  |  5
     |  3  |  8
     | ... | ...
1993 |  1  |  2
     | ... | ...
</code>```

I'm trying to select the maximum Value for each year and put that in a DF like this:

```<code>     | Max
Year |
1992 |  5
1993 |  2
     | ...
</code>```

There's not much info on multi-indexes, should I simply do a group by and apply or something similar to make it more simple?

Body:
I've got a dataframe with a multi index of Year and Month like the following

     |     |Value
Year |Month|
     |  1  |  3
1992 |  2  |  5
     |  3  |  8
     | ... | ...
1993 |  1  |  2
     | ... | ...

I'm trying to select the maximum Value for each year and put that in a DF like this:

     | Max
Year |
1992 |  5
1993 |  2
     | ...

There's not much info on multi-indexes, should I simply do a group by and apply or something similar to make it more simple?

Body:
Exactly right:

df.groupby(level=0).apply(max)

In my sample DataFrame:

                     0
Caps Lower
A    a     0  0.246490
           1 -1.265711
           2 -0.477415
           3 -0.355812
           4 -0.724521
     b     0 -0.409198
           1 -0.062552
           2 -0.731789
           3  1.131616
           4  0.085248
B    a     0  0.193948
           1  2.010710
           2  0.289300
           3  0.305373
           4  1.376965
     b     0  0.210522
           1  1.431279
           2 -0.247171
           3  0.899074
           4  0.639926

Result:

             0
Caps
A     1.131616
B     2.010710

This is how I created the DataFrame, by the way:

df = pd.DataFrame(np.random.randn(5,4), columns = l)
df.columns = pd.MultiIndex.from_tuples(df.columns, names=['Caps','Lower'])
df = pd.DataFrame(df.unstack())


问:
Multilevel models in R using nmle package
I am using the nlme package to learn multilevel models, and following examples from the textbook "Discovering Statistics Using R" when it happened.

Mixed Models Code

The data set is Honeymoon Period.dat, also downloadable under their companion website.

Data Set - Multilevel Models

```<code>require(nlme)
require(reshape2)
satisfactionData = read.delim("Honeymoon Period.dat",  header = TRUE)

restructuredData<-melt(satisfactionData, id = c("Person", "Gender"), measured = c("Satisfaction_Base", "Satisfaction_6_Months", "Satisfaction_12_Months", "Satisfaction_18_Months"))
names(restructuredData)<-c("Person", "Gender", "Time", "Life_Satisfaction")

#print(restructuredData)
#restructuredData.sorted<-restructuredData[order(Person),]

intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)
randomIntercept <-lme(Life_Satisfaction ~1, data = restructuredData, random = ~1|Person, method = "ML",  na.action = na.exclude, control = list(opt="optim"))
anova(intercept, randomIntercept)

timeRI<-update(randomIntercept, .~. + Time)
timeRS<-update(timeRI, random = ~Time|Person)
ARModel<-update(timeRS, correlation = corAR1(0, form = ~Time|Person))
</code>```

The error occured at this moment, when I am trying to update "timeRS" model.
The error message is as follows:

Error in as.character.factor(X[[i]], ...) : malformed factor

Any stats people/programmers here who knows what this means?

答:
I have looked at this book. It appears that the coding is wrong. The error you are getting is because your time variable is a factor and you need it to be numeric. In the author's first figure in the book he represents time as numeric (0 - 3) but his code for the models is incorrect. I've recoded it for you:

```<code>## First, Time needs to be recoded as a numeric

restructuredData$Time.Numeric <- with(restructuredData, ifelse(Time == "Satisfaction_Base", 0,
        ifelse(Time == "Satisfaction_6_Months", 1,
        ifelse(Time == "Satisfaction_12_Months", 2,
        ifelse(Time == "Satisfaction_18_Months", 3, NA)))))

## Baseline Model

intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)

summary(intercept)

## Model where intercept can vary for Individuals

randomIntercept <- lme(Life_Satisfaction ~ 1, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(randomIntercept)

## Add time as a fixed effect

timeRI <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(timeRI)

## Add a random slope to the model by nesting the Individual within the test time

timeRS <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~Time.Numeric|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(timeRS)

## Modeling the covariance structure structure of the errors with a first-order autoregressive covariance structure

ARModel <- update(timeRS, correlation = corAR1(0, form = ~Time.Numeric|Person))

summary(ARModel)

anova(intercept, randomIntercept, timeRI, timeRS, ARModel)
</code>```

The anova read out for model comparisons is now exactly as shown in the book.

Body:
I am using the nlme package to learn multilevel models, and following examples from the textbook "Discovering Statistics Using R" when it happened.

Mixed Models Code

The data set is Honeymoon Period.dat, also downloadable under their companion website.

Data Set - Multilevel Models

require(nlme)
require(reshape2)
satisfactionData = read.delim("Honeymoon Period.dat",  header = TRUE)

restructuredData<-melt(satisfactionData, id = c("Person", "Gender"), measured = c("Satisfaction_Base", "Satisfaction_6_Months", "Satisfaction_12_Months", "Satisfaction_18_Months"))
names(restructuredData)<-c("Person", "Gender", "Time", "Life_Satisfaction")

#print(restructuredData)
#restructuredData.sorted<-restructuredData[order(Person),]

intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)
randomIntercept <-lme(Life_Satisfaction ~1, data = restructuredData, random = ~1|Person, method = "ML",  na.action = na.exclude, control = list(opt="optim"))
anova(intercept, randomIntercept)

timeRI<-update(randomIntercept, .~. + Time)
timeRS<-update(timeRI, random = ~Time|Person)
ARModel<-update(timeRS, correlation = corAR1(0, form = ~Time|Person))

The error occured at this moment, when I am trying to update "timeRS" model.
The error message is as follows:

Error in as.character.factor(X[[i]], ...) : malformed factor

Any stats people/programmers here who knows what this means?

Body:
I have looked at this book. It appears that the coding is wrong. The error you are getting is because your time variable is a factor and you need it to be numeric. In the author's first figure in the book he represents time as numeric (0 - 3) but his code for the models is incorrect. I've recoded it for you:

## First, Time needs to be recoded as a numeric

restructuredData$Time.Numeric <- with(restructuredData, ifelse(Time == "Satisfaction_Base", 0,
        ifelse(Time == "Satisfaction_6_Months", 1,
        ifelse(Time == "Satisfaction_12_Months", 2,
        ifelse(Time == "Satisfaction_18_Months", 3, NA)))))

## Baseline Model

intercept <-gls(Life_Satisfaction~1, data = restructuredData, method = "ML", na.action = na.exclude)

summary(intercept)

## Model where intercept can vary for Individuals

randomIntercept <- lme(Life_Satisfaction ~ 1, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(randomIntercept)

## Add time as a fixed effect

timeRI <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~1|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(timeRI)

## Add a random slope to the model by nesting the Individual within the test time

timeRS <- lme(Life_Satisfaction ~ Time.Numeric, data = restructuredData, random = ~Time.Numeric|Person, method = "ML", na.action = na.exclude, control = list(opt = "optim"))

summary(timeRS)

## Modeling the covariance structure structure of the errors with a first-order autoregressive covariance structure

ARModel <- update(timeRS, correlation = corAR1(0, form = ~Time.Numeric|Person))

summary(ARModel)

anova(intercept, randomIntercept, timeRI, timeRS, ARModel)

The anova read out for model comparisons is now exactly as shown in the book.


问:
Connect to POP3S server in linux
I want to connect to a POP3S (SSL security) server in linux(the pop3 server is dovecot). I tried with normal sockets but it doesn't work(i get no reply from server) new Socket("localhost", 995). I found this command searching on the internet: "openssl s_client -connect localhost:995" and it works from terminal (+OK Dovecot ready.). Any solutions? (with or without java.mail library) i prefer without java.mail, but its also good with it. Thanks!</p>

答:
You're getting no reply from the server when creating your own Socket because you're not creating an SSLSocket.

Try JavaMail, it should work fine.  Start at the JavaMail FAQ.

Title: Connect to POP3S server in linux


问:
IIB: Passing local variable to ESQL select statement
I need to retrieve datas from two tables based on the Job code which is given in the input xml in IIB/WMB.

SQL Query

```<code>SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM DEPT D JOIN EMP E on E.JOB ='MANAGER' OR E.JOB = 'CLERK'
</code>```

ESQL Query

Getting the JOB details from input xml and assigning it to local variable.

```<code>SET type1 = InputRoot.XMLNSC.Employee.Type[1];
SET type2 = InputRoot.XMLNSC.Employee.Type[2];
</code>```

Now I need to pass the above variables to my ESQL query.

```<code>SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES('type1','type2')) ;
</code>```

But the above query is not working.

答:
Add To Database.DBName after your PASSTHRU statement where DBName is your database name

Like this:

```<code>SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES(type1)) To Database.DBName ;
</code>```

Body:
I need to retrieve datas from two tables based on the Job code which is given in the input xml in IIB/WMB.

SQL Query

SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM DEPT D JOIN EMP E on E.JOB ='MANAGER' OR E.JOB = 'CLERK'

ESQL Query

Getting the JOB details from input xml and assigning it to local variable.

SET type1 = InputRoot.XMLNSC.Employee.Type[1];
SET type2 = InputRoot.XMLNSC.Employee.Type[2];

Now I need to pass the above variables to my ESQL query.

SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES('type1','type2')) ;

But the above query is not working.

Body:
Add To Database.DBName after your PASSTHRU statement where DBName is your database name

Like this:

SET Outputroot.XMLNSC.List[] = PASSTHRU('SELECT D.DEPTNO,D.DNAME,D.LOC,E.EMPNO,E.ENAME,E.JOB,E.SAL FROM Database.EMP AS E,Database.DEPT AS D where E.JOB =?' VALUES(type1)) To Database.DBName ;


问:
Adding mleader to AutoCAD
Currently my program has a leader with mtext in it and I wanted to convert it to a multi-leader so the text is infused and it's easier and nicer to move around. So for leader it's easier.. I just add .addleader(pointsarray, annotation, leadertype)

But for mleader it's : .addmleader(pointsarray, leaderlineindex as long)

So my question is... what's leader line index? And where does my leader text go?
Thank you in advance

答: Per AutoDesk knowledge base it is "Input index of the mleader cluster", whatever that is. Review AutoDesk AddMLeader. The example in that link shows declaring i but does not set it so it defaults to 0 which means the parameter is 0.</p>

Title: Adding mleader to AutoCAD


问:
Accessing variable in main program from external subroutine
I'm trying to solve a maximum likelihood problem in Fortran using the NAG optimization library, but I'm running into problems accessing the variables in the main program from the external subroutines funct and hess (see pseudo-code below). What is the best way to pass variables (e.g. b) from the main program to such routines, given that I cannot pass them directly as arguments (a restriction of the NAG library). I have tried to implement COMMON blocks, but without much succes.

```<code>MODULE user_parameters
    ! Define the user parameters
    INTEGER, PARAMETER :: a = 100
    ... other parameters
END MODULE user_parameters

MODULE process_data
    USE user_parameters

    ! Define some other variables
    INTEGER :: b
    ... other variables

CONTAINS

    SUBROUTINE read_data
        ... read the data (e.g. alter value of b)
    END SUBROUTINE read_data

    SUBROUTINE clean_data
        ... clean the data (e.g. alter value of b)
    END SUBROUTINE clean_data
END MODULE process_data

MODULE maximum_likelihood
    USE user_parameters
    USE process_data

CONTAINS

    SUBROUTINE funct
        ... returns the LL's function value and gradient
    END SUBROUTINE funct

    SUBROUTINE hess
        ... returns the LL's hessian
    END SUBROUTINE hess
END MODULE maximum_likelihood

PROGRAM estimation
    USE user_parameters
    USE process_data
    USE maximum_likelihood
    EXTERNAL funct, hess

    CALL read_data
    CALL clean_data

    ! Call minimization routine
    CALL E04LBF(funct, hess)

END PROGRAM estimation
</code>```

答:
How about writing your module maximum_likelihood something as following?

```<code>MODULE maximum_likelihood
    IMPLICIT NONE
    PRIVATE
    PUBLIC init, fin, funct, hess

    INTEGER, SAVE                         :: aa, bb
    REAL, DIMENSION(:), ALLOCATABLE, SAVE :: vv

CONTAINS

    SUBROUTINE init(aa_arg, bb_arg, vv_arg)
        ! set values module variables
    END SUBROUTINE init

    SUBROUTINE fin()
        deallocate(vv)
    END SUBROUTINE fin

    SUBROUTINE funct
        ... returns the LL's function value and gradient
        ! using the values of aa, bb, and/or vv
    END SUBROUTINE funct

    SUBROUTINE hess
        ... returns the LL's hessian
        ! using the values of aa, bb, and/or vv
    END SUBROUTINE hess

END MODULE maximum_likelihood
</code>```

Then, the main program will look like

```<code>PROGRAM estimation
    USE maximum_likelihood, ONLY: init, fin, funct, hess

    ! read values for the parameters aaa, bbb, vvv

    ! set these values in the module variables in maximum_likelihood
    CALL init(aaa, bbb, vvv)

    ! Call minimization routine
    CALL E04LBF(funct, hess)

    ! clean up the module variables in maximum_likelihood
    CALL fin()

END PROGRAM estimation
</code>```

Body:
I'm trying to solve a maximum likelihood problem in Fortran using the NAG optimization library, but I'm running into problems accessing the variables in the main program from the external subroutines funct and hess (see pseudo-code below). What is the best way to pass variables (e.g. b) from the main program to such routines, given that I cannot pass them directly as arguments (a restriction of the NAG library). I have tried to implement COMMON blocks, but without much succes.

MODULE user_parameters
    ! Define the user parameters
    INTEGER, PARAMETER :: a = 100
    ... other parameters
END MODULE user_parameters

MODULE process_data
    USE user_parameters

    ! Define some other variables
    INTEGER :: b
    ... other variables

CONTAINS

    SUBROUTINE read_data
        ... read the data (e.g. alter value of b)
    END SUBROUTINE read_data

    SUBROUTINE clean_data
        ... clean the data (e.g. alter value of b)
    END SUBROUTINE clean_data
END MODULE process_data

MODULE maximum_likelihood
    USE user_parameters
    USE process_data

CONTAINS

    SUBROUTINE funct
        ... returns the LL's function value and gradient
    END SUBROUTINE funct

    SUBROUTINE hess
        ... returns the LL's hessian
    END SUBROUTINE hess
END MODULE maximum_likelihood

PROGRAM estimation
    USE user_parameters
    USE process_data
    USE maximum_likelihood
    EXTERNAL funct, hess

    CALL read_data
    CALL clean_data

    ! Call minimization routine
    CALL E04LBF(funct, hess)

END PROGRAM estimation

Body:
How about writing your module maximum_likelihood something as following?

MODULE maximum_likelihood
    IMPLICIT NONE
    PRIVATE
    PUBLIC init, fin, funct, hess

    INTEGER, SAVE                         :: aa, bb
    REAL, DIMENSION(:), ALLOCATABLE, SAVE :: vv

CONTAINS

    SUBROUTINE init(aa_arg, bb_arg, vv_arg)
        ! set values module variables
    END SUBROUTINE init

    SUBROUTINE fin()
        deallocate(vv)
    END SUBROUTINE fin

    SUBROUTINE funct
        ... returns the LL's function value and gradient
        ! using the values of aa, bb, and/or vv
    END SUBROUTINE funct

    SUBROUTINE hess
        ... returns the LL's hessian
        ! using the values of aa, bb, and/or vv
    END SUBROUTINE hess

END MODULE maximum_likelihood

Then, the main program will look like

PROGRAM estimation
    USE maximum_likelihood, ONLY: init, fin, funct, hess

    ! read values for the parameters aaa, bbb, vvv

    ! set these values in the module variables in maximum_likelihood
    CALL init(aaa, bbb, vvv)

    ! Call minimization routine
    CALL E04LBF(funct, hess)

    ! clean up the module variables in maximum_likelihood
    CALL fin()

END PROGRAM estimation


问:
How to determine what changed a DependencyProperty
I've got two objects bound to the same dependencyProperty (in Silverlight).
Is there a way to determine which of these two objects changed the property?
I want to take different actions based on that information.

Unfortunately, I cannot attach two different eventHandlers (because it's a dependencyProperty)

```<code>   public int StartTime
    {
        get { return (int)GetValue(StartTimeProperty); }
        set { SetValue(StartTimeProperty, value); }
    }
    public static readonly DependencyProperty StartTimeProperty =
        DependencyProperty.Register("StartTime", typeof(int), typeof(Step),
        new PropertyMetadata(-1, new PropertyChangedCallback(OnStartTimeChanged)));

    private static void OnStartTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((Step)d).OnStartTimeChanged(e);
    }

    protected virtual void OnStartTimeChanged(DependencyPropertyChangedEventArgs e)
    {
        //if set from obj1 -> do something
        //if set from obj2 -> do something else
    }
</code>```

In this example I would be setting StartTime property from different objects and I want to know which of these object changed the property.

Thanks

答:
```<code>var descriptor = DependencyPropertyDescriptor.FromProperty(YourType.StartTimeProperty , tpeof(YourType));
descriptor.AddValueChanged(obj1, OnStartTimeChanged1);
descriptor.AddValueChanged(obj2, OnStartTimeChanged2);
</code>```

Body:
I've got two objects bound to the same dependencyProperty (in Silverlight).
Is there a way to determine which of these two objects changed the property?
I want to take different actions based on that information.

Unfortunately, I cannot attach two different eventHandlers (because it's a dependencyProperty)

   public int StartTime
    {
        get { return (int)GetValue(StartTimeProperty); }
        set { SetValue(StartTimeProperty, value); }
    }
    public static readonly DependencyProperty StartTimeProperty =
        DependencyProperty.Register("StartTime", typeof(int), typeof(Step),
        new PropertyMetadata(-1, new PropertyChangedCallback(OnStartTimeChanged)));

    private static void OnStartTimeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        ((Step)d).OnStartTimeChanged(e);
    }

    protected virtual void OnStartTimeChanged(DependencyPropertyChangedEventArgs e)
    {
        //if set from obj1 -> do something
        //if set from obj2 -> do something else
    }

In this example I would be setting StartTime property from different objects and I want to know which of these object changed the property.

Thanks


问:
Swift 3: UITabBarController error: '*** -[__NSArray0 objectAtIndex:]: index 1 beyond bounds for empty NSArray'
I have created a custom tab bar controller. I have done this via Storyboard and it works fine. I am now trying to achieve this through code, without storyboards but I keep getting a crash with this error.

```<code>'*** -[__NSArray0 objectAtIndex:]: index 1 beyond bounds for empty NSArray'
</code>```

Does anyone know what the issue is? Thank you guys...

```<code>import UIKit

class SecondController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
    }
}

class ThirdController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
    }
}

class AnimatedTabBarController: UITabBarController {

    var secondItemImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondItemView = self.tabBar.subviews[1]
        self.secondItemImageView = secondItemView.subviews.first as! UIImageView
        self.secondItemImageView.contentMode = .center

    }

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

        if item.tag == 1 {
            //do our animations
            self.secondItemImageView.transform = CGAffineTransform.identity

            UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: { () -> Void in

                let rotation = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
                self.secondItemImageView.transform = rotation

            }, completion: nil)

        }

    }

}

class CustomTabBarController: AnimatedTabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let firstController = ThirdController()
        let firstNavController = UINavigationController(rootViewController: firstController)
        firstNavController.title = "Requests"
        firstNavController.tabBarItem.image = UIImage(named: "home_selected")
        firstNavController.tabBarItem.tag = 0

        let secondController = SecondController()
        let secondNavController = UINavigationController(rootViewController: secondController)
        secondNavController.title = "Messenger"
        secondNavController.tabBarItem.image = UIImage(named: "home_selected")
        secondController.tabBarItem.tag = 1

        viewControllers = [firstNavController, secondNavController]

        tabBar.isTranslucent = false

        let topBorder = CALayer()
        topBorder.frame = CGRect(x: 0, y: 0, width: 1000, height: 0.5)
        topBorder.backgroundColor = UIColor.lightGray.cgColor

        tabBar.layer.addSublayer(topBorder)
        tabBar.clipsToBounds = true

    }
}
</code>```

答:
One thing I notice:

```<code>let secondItemView = self.tabBar.subviews[1]
</code>```

In the first line of AnimatedTabBarController.viewDidLoad(). However, the tab bar controllers aren't set up until right after that in CustomTabBarController.viewDidLoad(). I think you'll want to initialize the contained view controllers in your init method instead.

Body:
I have created a custom tab bar controller. I have done this via Storyboard and it works fine. I am now trying to achieve this through code, without storyboards but I keep getting a crash with this error.

'*** -[__NSArray0 objectAtIndex:]: index 1 beyond bounds for empty NSArray'

Does anyone know what the issue is? Thank you guys...

import UIKit

class SecondController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
    }
}

class ThirdController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = .white
    }
}

class AnimatedTabBarController: UITabBarController {

    var secondItemImageView: UIImageView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let secondItemView = self.tabBar.subviews[1]
        self.secondItemImageView = secondItemView.subviews.first as! UIImageView
        self.secondItemImageView.contentMode = .center

    }

    override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {

        if item.tag == 1 {
            //do our animations
            self.secondItemImageView.transform = CGAffineTransform.identity

            UIView.animate(withDuration: 0.7, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options: .curveEaseInOut, animations: { () -> Void in

                let rotation = CGAffineTransform(rotationAngle: CGFloat(M_PI_2))
                self.secondItemImageView.transform = rotation

            }, completion: nil)

        }

    }

}

class CustomTabBarController: AnimatedTabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let firstController = ThirdController()
        let firstNavController = UINavigationController(rootViewController: firstController)
        firstNavController.title = "Requests"
        firstNavController.tabBarItem.image = UIImage(named: "home_selected")
        firstNavController.tabBarItem.tag = 0

        let secondController = SecondController()
        let secondNavController = UINavigationController(rootViewController: secondController)
        secondNavController.title = "Messenger"
        secondNavController.tabBarItem.image = UIImage(named: "home_selected")
        secondController.tabBarItem.tag = 1

        viewControllers = [firstNavController, secondNavController]

        tabBar.isTranslucent = false

        let topBorder = CALayer()
        topBorder.frame = CGRect(x: 0, y: 0, width: 1000, height: 0.5)
        topBorder.backgroundColor = UIColor.lightGray.cgColor

        tabBar.layer.addSublayer(topBorder)
        tabBar.clipsToBounds = true

    }
}

Body:
One thing I notice:

let secondItemView = self.tabBar.subviews[1]

In the first line of AnimatedTabBarController.viewDidLoad(). However, the tab bar controllers aren't set up until right after that in CustomTabBarController.viewDidLoad(). I think you'll want to initialize the contained view controllers in your init method instead.


问:
Upload multiple files via AngularJS to Laravel Controller

I have

Browse files button

```<code><input type="file" upload-files multiple />
</code>```

Create Button

```<code><button class="btn btn-link" ng-click="store()" >Create</button>
</code>```

Directive

```<code>myApp.directive('uploadFiles', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            element.bind('change', function (event) {
                var files = event.target.files;
                for (var i = 0; i < files.length; i++) {
                    scope.$emit("seletedFile", { file: files[i] });
                }
            });
        }
    };
});
</code>```

Listen for the file selected

```<code>$scope.files = [];
$scope.$on("seletedFile", function (event, args) {

    console.log("event is ", event);
    console.log("args is ", args);

    $scope.$apply(function () {
        $scope.files.push(args.file);
    });

});
</code>```

Post data and selected files.

```<code>$scope.store = function() {

    $scope.model = {
      name: $scope.name,
      type: $scope.type
    };

    $http({
        method: 'POST',
        url: '/image/store',
        headers: { 'Content-Type': undefined },
        transformRequest: function (data) {
            console.log("data coming into the transform is ", data);
            var formData = new FormData();
            formData.append("model", angular.toJson(data.model));
            for (var i = 0; i < data.files; i++) {
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },

        data: { model: $scope.model, files: $scope.files }

    })

    .then(function successCallback(response) {
        console.log("%cSuccess!", "color: green;");
        console.log(response);
        $scope.refresh();
        $scope.showModal = false;
        }, function errorCallback(response) {
        console.log("%cError", "color: red;");
        console.log(response);
    });
};
</code>```

Result

In my console, I don't see my files got pass on to my controller in the back-end.

```<code>array:1 [
  "model" => "{"type":"wedding"}"
]
</code>```

Questions

What steps did I forget?

How would one go about and debug this further ?

答:
You can use FormData instead</p>

```<code>var formData = new FormData();

  formData.append('model[var]', $scope.var);

  // For add to the FormData other file
  for (var i = 0; i < $scope.files; i++) {
    formData.append('file' + i, $scope.files[i]);
  }

 // POST REQUEST MUST BE:
  $http.post('url', formData, {
    transformRequest: angular.identity,  //It is for allowing files
    headers: {'Content-Type': undefined}
    }).then(function(response)
  {
    // verify if response get 200
  });
</code>```

Body:
I have

Browse files button

<input type="file" upload-files multiple />

Create Button

<button class="btn btn-link" ng-click="store()" >Create</button>

Directive

myApp.directive('uploadFiles', function () {
    return {
        scope: true,
        link: function (scope, element, attrs) {
            element.bind('change', function (event) {
                var files = event.target.files;
                for (var i = 0; i < files.length; i++) {
                    scope.$emit("seletedFile", { file: files[i] });
                }
            });
        }
    };
});

Listen for the file selected

$scope.files = [];
$scope.$on("seletedFile", function (event, args) {

    console.log("event is ", event);
    console.log("args is ", args);

    $scope.$apply(function () {
        $scope.files.push(args.file);
    });

});

Post data and selected files.

$scope.store = function() {

    $scope.model = {
      name: $scope.name,
      type: $scope.type
    };

    $http({
        method: 'POST',
        url: '/image/store',
        headers: { 'Content-Type': undefined },
        transformRequest: function (data) {
            console.log("data coming into the transform is ", data);
            var formData = new FormData();
            formData.append("model", angular.toJson(data.model));
            for (var i = 0; i < data.files; i++) {
                formData.append("file" + i, data.files[i]);
            }
            return formData;
        },

        data: { model: $scope.model, files: $scope.files }

    })

    .then(function successCallback(response) {
        console.log("%cSuccess!", "color: green;");
        console.log(response);
        $scope.refresh();
        $scope.showModal = false;
        }, function errorCallback(response) {
        console.log("%cError", "color: red;");
        console.log(response);
    });
};

Result

In my console, I don't see my files got pass on to my controller in the back-end.

array:1 [
  "model" => "{"type":"wedding"}"
]

Questions

What steps did I forget?

How would one go about and debug this further ?

Body:
You can use FormData instead

var formData = new FormData();

  formData.append('model[var]', $scope.var);

  // For add to the FormData other file
  for (var i = 0; i < $scope.files; i++) {
    formData.append('file' + i, $scope.files[i]);
  }

 // POST REQUEST MUST BE:
  $http.post('url', formData, {
    transformRequest: angular.identity,  //It is for allowing files
    headers: {'Content-Type': undefined}
    }).then(function(response)
  {
    // verify if response get 200
  });


问:
"ImportError: cannot import name views" on Flask server but in PyCharm works
At the beginning, I'm newbie at Flask.

I received a working project made in Python using Flask framework. It worked in PyCharm. When I pasted it into server files and run flask server (I followed documentation on Flask site), the error has shown:

```<code>File "/home/web/app/__init__.py", line 22, in <module>
from app import views, models
ImportError: cannot import name views
</code>```

So that is the init.py file:

```<code>1 import os
2 from flask import Flask
3 from flask_sqlalchemy import SQLAlchemy
4 from flask_login import LoginManager
5 from flask_openid import OpenID
6 from config import basedir
7
8 app = Flask(__name__)
9 app.config.from_pyfile('config.py')
10
11 db = SQLAlchemy(app)
12
13 # Imports below help me fixing the database
14 # from app import models
15 # import database_migrate
16
17 lm = LoginManager()
18 lm.init_app(app)
19 lm.login_view = 'login'
20 oid = OpenID(app, os.path.join(basedir, 'tmp'))
21
22 from app import views, models
23
24 app.run(debug=True)
</code>```

When typed print(app) it shows None. All the modules are installed. Tried to run simple webapp printing "Hello world", and it worked. Flask has been reinstalled three times. Views has from app import app
I couldn't find any solution on stack or in any other place.

 Thanks in advance

答:
As your views.py and models.py are in the same directory, you can replace import statement with:

```<code>from . import views, models
</code>```

for proper import. As an alternative, you can also move them under a directory and put that directory name instead of the dot.

Body:
At the beginning, I'm newbie at Flask.

I received a working project made in Python using Flask framework. It worked in PyCharm. When I pasted it into server files and run flask server (I followed documentation on Flask site), the error has shown:

File "/home/web/app/__init__.py", line 22, in <module>
from app import views, models
ImportError: cannot import name views

So that is the init.py file:

1 import os
2 from flask import Flask
3 from flask_sqlalchemy import SQLAlchemy
4 from flask_login import LoginManager
5 from flask_openid import OpenID
6 from config import basedir
7
8 app = Flask(__name__)
9 app.config.from_pyfile('config.py')
10
11 db = SQLAlchemy(app)
12
13 # Imports below help me fixing the database
14 # from app import models
15 # import database_migrate
16
17 lm = LoginManager()
18 lm.init_app(app)
19 lm.login_view = 'login'
20 oid = OpenID(app, os.path.join(basedir, 'tmp'))
21
22 from app import views, models
23
24 app.run(debug=True)

When typed print(app) it shows None. All the modules are installed. Tried to run simple webapp printing "Hello world", and it worked. Flask has been reinstalled three times. Views has from app import app
I couldn't find any solution on stack or in any other place.

 Thanks in advance

Body:
As your views.py and models.py are in the same directory, you can replace import statement with:

from . import views, models

for proper import. As an alternative, you can also move them under a directory and put that directory name instead of the dot.