问:
Is NodeJS is suitable for websites - (ie. Port Blocking)?
I have gone through many painful months with is issue and I am now ready to let this go to the bin of "what-a-great-lie-for-websites-nodejs-is"!!!

All NodeJS tutorials discuss how to create a website. When done, it works. For one person at a time though. All requests sent to the port will be blocked by the first come-first-serve situation. Why? Because most requests sent to the nodejs server will have to get parsed, data requested from the database, data calculated and parsed, response prepared and sent back to the ajax call. (this is a mere simple website example).

Same applies for authentication - a request is made, data is parsed, authentication takes place, session is created and sent back to the requester.

No matter how you sugar coat this - All requests are done this way. Yes you can employ async functionality which will shorten the time spent on some portions, yes you can try promises, yes you can employ clustering, yes you can employ forking/spawning, etc... The result is always the same at all times: port gets blocked.

I tried responding with a reference so that we can use sockets to pass the data back and matching it with the reference - that also blocked it.

The point of the matter is this: when you ask for help, everyone wants all sort of code examples, but never go to the task of helping with an actual answer that works. The whole wide world!!!!! Which leads me to the answer that nodeJS is not suitable for websites.

I read many requests regarding this and all have been met with: "you must code properly"..! Really? Is there no NodeJS skilled and experienced person who can lend an answer on this one????!!!!!

Most of the NodeJS coders come from the PHP side - All websites using PHP never have to utilise any workaround whatsoever in order to display a web page and it never blocks 2 people at the same time. Thanks to the web server.

So how come NodeJS community cannot come to some sort of an asnwer on this one other than: "code carefully"???!!!

They want examples - each example is met with: "well that is a blocking code, do it another way", or "code carefully"!!! Come one people!!!

Think of the following scenario: One User, One page with 4 lists of records. Theoretically all lists should be filled up with records independently. What is happening because of how data is requested, prepared and responded, each list in reality is waiting for the next one to finish. That is on one session alone.

What about 2 people, 2 sessions at the same time?

So my question is this: is NodeJS suitable for a website and if it is, can anyone show and prove this with a short code??? If you can't prove it, then the answer is: "NodeJS is not suitable for websites!"

Here is an example based on the simplest tutorial and it is still blocking:

```<code>var express = require('express'),
    fs      = require("fs");

var app = express();
app.get('/heavyload', function (req, res) {
    var file    = '/media/sudoworx/www/sudo-sails/test.zip';

    res.send('Heavy Load');
    res.end();

    fs.readFile(file, 'utf8', function (err,fileContent) {

    });

});

app.get('/lightload', function (req, res) {
    var file    = '/media/sudoworx/www/sudo-sails/test.zip';
    res.send('Light Load');
    res.end();
});

app.listen(1337, function () {
    console.log('Listening!')
});
</code>```

Now, if you go to "/heavyload" it will immediately respond because that is the first thing sent to the browser, and then nodejs proceeds reading a heavy file (a large file). If you now go to the second call "/lightload" at the same time, you will see that it is waiting for the loading of the file to finish from the first call before it proceeds with the browser output. This is the simplest example of how nodejs simply fails in handling what otherwise would be simple in php and similar script languages.

Like mentioned before, I tried as many as 20 different ways to do this in my career of nodejs programmer. I totally love nodejs, but I cannot get past this obstacle... This is not a complaint - it is a call for help because I am at my end road with nodejs and I don't know what to do.

I thank you kindly.

答:
So here is what I found out. I will answer it with an example of a blocking code:

```<code>for (var k = 0; k < 15000; k++){
    console.log('Something Output');
}
res.status(200).json({test:'Heavy Load'});
</code>```

This will block because it has to do the for loop for a long time and then after it finished it will send the output.

Now if you do the same code like this it won't block:

```<code>function doStuff(){
    for (var k = 0; k < 15000; k++){
        console.log('Something Output');
    }
}
doStuff();

res.status(200).json({test:'Heavy Load'});
</code>```

Why? Because the functions are run asynchronously...! So how will I then send the resulting response to the requesting client? Currently I am doing it as follows:

Run the doStuff function

Send a unique call reference which is then received by the ajax call on the client side.

Put the callback function of the client side into a waiting object.

Listen on a socket

When the doStuff function is completed, it should issue a socket message with the resulting response together with the unique reference

When the socket on the client side gets the message with the unique reference and the resulting response, it will then match it with the waiting callback function and run it.

Done! A bit of a workaround (as mentioned before), but it's working! It does require a socket to be listening. And that is my solution to this port-blocking situation in NodeJS.

Is there some other way? I am hoping someone answers with another way, because I am still feeling like this is some workaround. Eish! ;)

Body:
I have gone through many painful months with is issue and I am now ready to let this go to the bin of "what-a-great-lie-for-websites-nodejs-is"!!!

All NodeJS tutorials discuss how to create a website. When done, it works. For one person at a time though. All requests sent to the port will be blocked by the first come-first-serve situation. Why? Because most requests sent to the nodejs server will have to get parsed, data requested from the database, data calculated and parsed, response prepared and sent back to the ajax call. (this is a mere simple website example).

Same applies for authentication - a request is made, data is parsed, authentication takes place, session is created and sent back to the requester.

No matter how you sugar coat this - All requests are done this way. Yes you can employ async functionality which will shorten the time spent on some portions, yes you can try promises, yes you can employ clustering, yes you can employ forking/spawning, etc... The result is always the same at all times: port gets blocked.

I tried responding with a reference so that we can use sockets to pass the data back and matching it with the reference - that also blocked it.

The point of the matter is this: when you ask for help, everyone wants all sort of code examples, but never go to the task of helping with an actual answer that works. The whole wide world!!!!! Which leads me to the answer that nodeJS is not suitable for websites.

I read many requests regarding this and all have been met with: "you must code properly"..! Really? Is there no NodeJS skilled and experienced person who can lend an answer on this one????!!!!!

Most of the NodeJS coders come from the PHP side - All websites using PHP never have to utilise any workaround whatsoever in order to display a web page and it never blocks 2 people at the same time. Thanks to the web server.

So how come NodeJS community cannot come to some sort of an asnwer on this one other than: "code carefully"???!!!

They want examples - each example is met with: "well that is a blocking code, do it another way", or "code carefully"!!! Come one people!!!

Think of the following scenario: One User, One page with 4 lists of records. Theoretically all lists should be filled up with records independently. What is happening because of how data is requested, prepared and responded, each list in reality is waiting for the next one to finish. That is on one session alone.

What about 2 people, 2 sessions at the same time?

So my question is this: is NodeJS suitable for a website and if it is, can anyone show and prove this with a short code??? If you can't prove it, then the answer is: "NodeJS is not suitable for websites!"

Here is an example based on the simplest tutorial and it is still blocking:

var express = require('express'),
    fs      = require("fs");

var app = express();
app.get('/heavyload', function (req, res) {
    var file    = '/media/sudoworx/www/sudo-sails/test.zip';

    res.send('Heavy Load');
    res.end();

    fs.readFile(file, 'utf8', function (err,fileContent) {

    });

});

app.get('/lightload', function (req, res) {
    var file    = '/media/sudoworx/www/sudo-sails/test.zip';
    res.send('Light Load');
    res.end();
});

app.listen(1337, function () {
    console.log('Listening!')
});

Now, if you go to "/heavyload" it will immediately respond because that is the first thing sent to the browser, and then nodejs proceeds reading a heavy file (a large file). If you now go to the second call "/lightload" at the same time, you will see that it is waiting for the loading of the file to finish from the first call before it proceeds with the browser output. This is the simplest example of how nodejs simply fails in handling what otherwise would be simple in php and similar script languages.

Like mentioned before, I tried as many as 20 different ways to do this in my career of nodejs programmer. I totally love nodejs, but I cannot get past this obstacle... This is not a complaint - it is a call for help because I am at my end road with nodejs and I don't know what to do.

I thank you kindly.

Body:
So here is what I found out. I will answer it with an example of a blocking code:

for (var k = 0; k < 15000; k++){
    console.log('Something Output');
}
res.status(200).json({test:'Heavy Load'});

This will block because it has to do the for loop for a long time and then after it finished it will send the output.

Now if you do the same code like this it won't block:

function doStuff(){
    for (var k = 0; k < 15000; k++){
        console.log('Something Output');
    }
}
doStuff();

res.status(200).json({test:'Heavy Load'});

Why? Because the functions are run asynchronously...! So how will I then send the resulting response to the requesting client? Currently I am doing it as follows:

Run the doStuff function

Send a unique call reference which is then received by the ajax call on the client side.

Put the callback function of the client side into a waiting object.

Listen on a socket

When the doStuff function is completed, it should issue a socket message with the resulting response together with the unique reference

When the socket on the client side gets the message with the unique reference and the resulting response, it will then match it with the waiting callback function and run it.

Done! A bit of a workaround (as mentioned before), but it's working! It does require a socket to be listening. And that is my solution to this port-blocking situation in NodeJS.

Is there some other way? I am hoping someone answers with another way, because I am still feeling like this is some workaround. Eish! ;)


来源: stackexchange

问:
I would like to Trim Spaces which is in a single string
```<code>                       :     VJ NT jdbc & hyC rayan asdALAYA
                                                                8 CHURCH ROAD 9 TH FLOOR
                                                PUNE 3256-34546561
                                                PUNE 412346
</code>```

<p>this is in  a  single string which has lots of spaces I would like trim all extra spaces and give a single space for each word.Please help me  </p>

答:
You could try replacing all blocks of multiple spaces with a single space:

```<code>String input = "    :     VJ NT jdbc & hyC rayan asdALAYA";
input = input.replaceAll("\\s+", " ");
</code>```

If you also want to remove a leading or trailing space which might be leftover, you can use String.trim() for that:

```<code>input = input.trim();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
                       :     VJ NT jdbc & hyC rayan asdALAYA
                                                                8 CHURCH ROAD 9 TH FLOOR
                                                PUNE 3256-34546561
                                                PUNE 412346

this is in  a  single string which has lots of spaces I would like trim all extra spaces and give a single space for each word.Please help me

Body:
You could try replacing all blocks of multiple spaces with a single space:

String input = "    :     VJ NT jdbc & hyC rayan asdALAYA";
input = input.replaceAll("\\s+", " ");

If you also want to remove a leading or trailing space which might be leftover, you can use String.trim() for that:

input = input.trim();


问:
NSXMLParser and the "£" symbol
Hey all, slight problem when i read in an XML form.
NSXMLParse correctly see's the "£" symbol but its prints out the unicode, \U00a3.

I am just reading it to a string.

```<code>   [pre_Currency appendString:[self cleanString:string]];
</code>```

CleanString removes \n - \t and i even added parsing out the unicode and replace it with the Char symbol for the "£".

Oddly enough a NSLog here print a "£" symbol, but when it didEndElement i add it to the dictionary,

```<code>    [number setObject:[self cleanString:pre_Currency] forKey:@"pre_currency"];
</code>```

It add it as a unicode Char.

Cant understand why, looking at google theres very little aimed at parsing unicode chars.

答:
Yes, it happens for symbols and for other languages fonts in they are not in english, I also got reply here that we will have to decode it as follows:

```<code>int c = ... /* your 4 text digit unicode ordinal converted to an integer */
charString = [ NSString stringWithFormat:@"%C", c ];
</code>```

Original link - How to display Text in Arabic in UIlabel

ContentLicense: CC BY-SA 2.5

Title: NSXMLParser and the "£" symbol

Body:
Hey all, slight problem when i read in an XML form.
NSXMLParse correctly see's the "£" symbol but its prints out the unicode, \U00a3.

I am just reading it to a string.

   [pre_Currency appendString:[self cleanString:string]];

CleanString removes \n - \t and i even added parsing out the unicode and replace it with the Char symbol for the "£".

Oddly enough a NSLog here print a "£" symbol, but when it didEndElement i add it to the dictionary,

    [number setObject:[self cleanString:pre_Currency] forKey:@"pre_currency"];

It add it as a unicode Char.

Cant understand why, looking at google theres very little aimed at parsing unicode chars.

Body:
Yes, it happens for symbols and for other languages fonts in they are not in english, I also got reply here that we will have to decode it as follows:

int c = ... /* your 4 text digit unicode ordinal converted to an integer */
charString = [ NSString stringWithFormat:@"%C", c ];

Original link - How to display Text in Arabic in UIlabel


问:
Why chdir does not support in java?
I would like to know the actual reason behind why Java does not provide chdir call implementation however it provides native interfaces for the same.</p>

答:
The full evaluation can be found in Sun/Oracle's bug database with issue number
JDK-4045688 : Add chdir or equivalent notion of changing working directory

It was decided to close the ticket because there are major issues with any solution, and none of the customers that reported the bug really needed it - all of them were able to use a workaround.

One excerpt from the bug database that highlights the issues with adding such a call:

EVALUATION

This feature can be interpreted in two ways: chdir could change the
  current working directory of the process containing the JVM, causing
  all threads to change simultaneously, or to provide a more "virtual"
  per-thread concept of current directory, which could conceptually be a
  ThreadLocal.  This would be merely a convenience for building up
  complete path names to pass to the underlying operating system API.

This is how the current directory works in Emacs - it's just a
  variable, but a magic one that can have buffer-local values.  Emacs
  buffers are kinda sorta like Java threads in this sense. Such an
  implementation would offer convenience and safety. Having each thread
  with a ThreadLocal current directory gives a programmer experience
  familiar to old Unix greybeards, except that Threads replace
  Processes.

Many workarounds are also described there, such as executing a subprocess with a new current directory, or always qualifying your file accesses with the parent directory from where you want your relative part to start.

Title: Why chdir does not support in java?


问:
angular i18n .xlf file ID's - confused when they change
ok, so I've done everything to translate my app, as described here. And I got different versions working. But I'm confused on that ID's topic:

As the application evolves, you will change the i18n markup and re-run the ng-xi18n extraction tool many times. The new markup that you add is not a problem; but most changes to existing markup trigger generation of new ids for the affected translation units.
    After an id changes, the translation files are no longer in-sync. All translated versions of the application will fail during re-compilation. The error messages identify the old ids that are no longer valid but they don't tell you what the new ids should be.
    Commit all translation message files to source control, especially the English source messages.xlf. The difference between the old and the new messages.xlf file help you find and update id changes across your translation files.

I tried to add new paragraphs to my html templates and existing translate-units have not changed. So, when those ID change, how to prevent them from changing if I change component's templates, what is the best practice to maintain translations while developing app? I don't find answers to those questions anywhere.

答:
So, it happens that you can specify your own @id for i18n attribute. In this case those id's won't change.

Here's an example:

```<code><a class="active item" [routerLink]="''" i18n="Home link@@[your-id-goes-here]">Home</a>
</code>```

I suggest using GUID's.

Body:
So, it happens that you can specify your own @id for i18n attribute. In this case those id's won't change.

Here's an example:

<a class="active item" [routerLink]="''" i18n="Home link@@[your-id-goes-here]">Home</a>

I suggest using GUID's.


问:
Having issues with my ionic login app
i am trying to create a login application with create account option.When i run the ionic serve i get a white screen.
Heres code i have done so far
(am totally new to this stuff )

index.html

```<code><body ng-app="starter">

  <ion-nav-view></ion-nav-view>

  </body>
</code>```

login.html

```<code><ion-view>
 <ion-content>

  <div class="login-image">
     <img src="../img/img3.jpg" width="100%" class="padding">
   </div>

   <div class="padding">
    <form ng-submit="doLogin()" >
        <div class="list">
          <label class="item item-input">
            <span class="input-label"></span>
            <input type="text" ng-model="loginData.username" placeholder="Username">
          </label><br>
          <label class="item item-input">
            <span class="input-label"></span>
            <input type="password" ng-model="loginData.password" placeholder="Password">
          </label><br>
           <div style=" text-align: right;">
             <a href="#/"> Forgot Password </a>
           </div><br>
          <label>
            <button class="button button-block button-positive" type="submit" href = "template/dashboard.html">Log in</button>
          </label>
          <br>
           <div style=" text-align: center;">
             <a href="template/createaccount.html">Create Account</a>
           </div>
        </div>
      </form>
   </div>

 </ion-content>
</ion-view>
</code>```

createaccount.html

```<code><ion-view>
  <ion-content>
    <div>
      <form name="createaccountform" class="padding">
        <div>
            <label class="item item-input item-floating-label">
                <span class="input-label">First Name</span>
                <input type="text" name="firstname" placeholder="First Name">
            </label>
            <label class="item item-input item-floating-label">
                <span class="input-label">Last Name</span>
                <input type="text" name="lastname" placeholder="Last Name">
            </label>
            <label class="item item-input item-floating-label">
                <span class="input-label">Email</span>
                <input type="email" name="email" placeholder="Email">
            </label>
            <label class="item item-input item-floating-label">
                <span class="input-label">Username</span>
                <input type="text" name="Username" placeholder="Username">
            </label>
            <label class="item item-input item-floating-label">
                <span class="input-label">Password</span>
                <input type="password" name="password" placeholder="Password">
            </label>
            <label>
             <button class="button button-block button-positive" type="submit" href="template/login.html">Create Account </button>
           </label>
        </div>
      </form>
    </div>
  </ion-content>
</ion-view>
</code>```

app.js

```<code>.config(function($stateProvider,$urlRouterProvider){
  $stateProvider

    .state('index',{
      url: '/index',
      abstract: true,
      templateUrl: '/index.html'

       })

    .state('login',{
      url: '/login',
      templateUrl: 'templates/login.html'
    })

    .state('createaccount',{
      url: '/createaccount',
      templateUrl: 'templates/createaccount.html'
    });

    //allows for fallback when page not found or not exist
    $urlRouterProvider.otherwise('templates/login.html');

});
</code>```

Dont know what am dong wrong but i really need a guide on this.

答:
After of run your command, need to access to the following URL to see your login page:

```<code>http://localhost:8000/login
</code>```

The routing is handled in your app.js file throughout state manager.
I suggest taking at look at the official documentation to understand how works.

Title: Having issues with my ionic login app

Body:
i am trying to create a login application with create account option.When i run the ionic serve i get a white screen.
Heres code i have done so far
(am totally new to this stuff )

index.html

  <ion-nav-view></ion-nav-view>

login.html

<ion-view>
 <ion-content>

    <form ng-submit="doLogin()" >

            <input type="text" ng-model="loginData.username" placeholder="Username">

            <input type="password" ng-model="loginData.password" placeholder="Password">

              Forgot Password

            <button class="button button-block button-positive" type="submit" href = "template/dashboard.html">Log in</button>

             Create Account

      </form>

 </ion-content>
</ion-view>

createaccount.html

<ion-view>
  <ion-content>

      <form name="createaccountform" class="padding">

                First Name
                <input type="text" name="firstname" placeholder="First Name">

                Last Name
                <input type="text" name="lastname" placeholder="Last Name">

                Email
                <input type="email" name="email" placeholder="Email">

                Username
                <input type="text" name="Username" placeholder="Username">

                Password
                <input type="password" name="password" placeholder="Password">

             <button class="button button-block button-positive" type="submit" href="template/login.html">Create Account </button>

      </form>

  </ion-content>
</ion-view>

app.js

.config(function($stateProvider,$urlRouterProvider){
  $stateProvider

    .state('index',{
      url: '/index',
      abstract: true,
      templateUrl: '/index.html'

       })

    .state('login',{
      url: '/login',
      templateUrl: 'templates/login.html'
    })

    .state('createaccount',{
      url: '/createaccount',
      templateUrl: 'templates/createaccount.html'
    });

    //allows for fallback when page not found or not exist
    $urlRouterProvider.otherwise('templates/login.html');

});

Dont know what am dong wrong but i really need a guide on this.

Body:
After of run your command, need to access to the following URL to see your login page:

http://localhost:8000/login

The routing is handled in your app.js file throughout state manager.
I suggest taking at look at the official documentation to understand how works.


问:
Lagom + akka-http integration
What is the simplest solution to integrate Akka HTTP service with / into Lagom?

I have two services - akkahttp:8000 and lagom:9000, they are serving methods for Angular application. It would be great to have one endpoint for all the services - x:8888 for x:8888/akkahttp and x:8888/lagom.

答:
This problem is often solved by using some kind of reverse proxy server that faces clients and forwards traffic to your Akka HTTP and Lagom services over an internal network.

Popular reverse proxy solutions include:

HAProxy

nginx

AWS Application Load Balancer (for AWS deployments)

Lightbend ConductR is the recommended and supported deployment environment for Lagom and Akka based services. It includes a built-in, HAProxy-based dynamic proxy that supports this kind of configuration.

Title: Lagom + akka-http integration


问:
What is the algorithm unix du command uses to calculate disk space?
I've tried using du to calculate disk usage today on a single directory. The size of directory is 6GB and it took the following amount of time to calculate:

```<code>prompt> time du -sh .
6.0G   .

real    1m32.405s
user    0m2.053s
sys     0m16.552s
</code>```

What is the algorithm unix du command uses to calculate disk space? Why is it so slow? Are there any alternatives to calculate disk space more efficiently? The platform of invocation is Sun. The directory for which size was calculated is NFS mounted.

答:
du has to list all the directories and stat every file found so that ends up with read all over the disk

while getting the sizes of the files it sums them and when finished it prints the sum

for example on this one directory with like 2 million files on a sshfs filesystem:

```<code>prompt$ time du -sh .
367G    .

real    12m53.093s
user    0m3.848s
sys     0m14.265s
</code>```

but due to caching for the second run it only takes:

```<code>prompt$ time du -sh .
367G    .

real    4m56.875s
user    0m4.136s
sys     0m15.257s
</code>```

Body:
I've tried using du to calculate disk usage today on a single directory. The size of directory is 6GB and it took the following amount of time to calculate:

prompt> time du -sh .
6.0G   .

real    1m32.405s
user    0m2.053s
sys     0m16.552s

What is the algorithm unix du command uses to calculate disk space? Why is it so slow? Are there any alternatives to calculate disk space more efficiently? The platform of invocation is Sun. The directory for which size was calculated is NFS mounted.

Body:
du has to list all the directories and stat every file found so that ends up with read all over the disk

while getting the sizes of the files it sums them and when finished it prints the sum

for example on this one directory with like 2 million files on a sshfs filesystem:

prompt$ time du -sh .
367G    .

real    12m53.093s
user    0m3.848s
sys     0m14.265s

but due to caching for the second run it only takes:

prompt$ time du -sh .
367G    .

real    4m56.875s
user    0m4.136s
sys     0m15.257s


问:
Creating Static Values into a Sequelize model (no experience with migration)
I am working on a group project that tests our use of Sequelize vs. normal ORM generated back-end items.  Two of our models in a MySQL DB are category tables.  These will not be dynamically created, updated or destroyed, but need to be there when the program runs.  The class I am a part of hasn't covered instances or migrations.  Here is the model thus far..

```<code>module.exports = function(sequelize, DataTypes){
var maincategories = sequelize.define("maincategories", {
    maincategories_id: {
        //make primary key
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement:true
    },
    maincategories_name: {
        type: DataTypes.STRING,
        allowNull: false
    }
},
    {
        classMethods: {
            associate: function(models){
                maincategories.hasMany(models.posts),
                maincategories.hasMany(models.subcategories)
            }
        }
    });

// maincategories.create({ maincategories_name: 'For Sale'}).then(function(insertedCategory){
//  console.log(insertedCategory.dataValues);
// });
maincategories.create({ maincategories_name: 'Housing'})
maincategories.create({ maincategories_name: 'Personals'});

return maincategories;
// maincategories.hasMany(posts);
// maincategories.hasMany(subcategories);
};
</code>```

How can I get the Category table to have those values added to it at the time or prior to the node.js app starting?  Also, would the code reside in the model, api route or a separate file that is required in somewhere else?  As you can see I tried to do persistent instances but these did not work.  It would state that I had created these items in node CLI but nothing showed in the actual database.

Thank you.

答:
You need maincategories.sync() in order for sequelize to sync the defined models to your db.

http://docs.sequelizejs.com/en/v3/api/sequelize/#syncoptions-promise

Body:
I am working on a group project that tests our use of Sequelize vs. normal ORM generated back-end items.  Two of our models in a MySQL DB are category tables.  These will not be dynamically created, updated or destroyed, but need to be there when the program runs.  The class I am a part of hasn't covered instances or migrations.  Here is the model thus far..

module.exports = function(sequelize, DataTypes){
var maincategories = sequelize.define("maincategories", {
    maincategories_id: {
        //make primary key
        type: DataTypes.INTEGER,
        allowNull: false,
        primaryKey: true,
        autoIncrement:true
    },
    maincategories_name: {
        type: DataTypes.STRING,
        allowNull: false
    }
},
    {
        classMethods: {
            associate: function(models){
                maincategories.hasMany(models.posts),
                maincategories.hasMany(models.subcategories)
            }
        }
    });

// maincategories.create({ maincategories_name: 'For Sale'}).then(function(insertedCategory){
//  console.log(insertedCategory.dataValues);
// });
maincategories.create({ maincategories_name: 'Housing'})
maincategories.create({ maincategories_name: 'Personals'});

return maincategories;
// maincategories.hasMany(posts);
// maincategories.hasMany(subcategories);
};

How can I get the Category table to have those values added to it at the time or prior to the node.js app starting?  Also, would the code reside in the model, api route or a separate file that is required in somewhere else?  As you can see I tried to do persistent instances but these did not work.  It would state that I had created these items in node CLI but nothing showed in the actual database.

Thank you.


问:
Python: get first number of every float in a list
python beginner here. How can I convert

```<code>list = [2.4, 4.8532, 5.43253, 55.3838]
</code>```

to

```<code>list = [2, 4, 5, 5]
</code>```

Thanks.

答:
you can just use int(), Since int() always rounds <s>down</s> toward 0, which is the equivalent of chopping the decimals for floats. Note: do not use list as a variable name since it's already a built-in function and type.

```<code>lst = [2.4, 4.8532, 5.43253]
lst = [int(x) for x in lst]
print(lst)
</code>```

Output:

```<code>[2, 4, 5]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
python beginner here. How can I convert

list = [2.4, 4.8532, 5.43253, 55.3838]

to

list = [2, 4, 5, 5]

Thanks.

Body:
you can just use int(), Since int() always rounds <s>down</s> toward 0, which is the equivalent of chopping the decimals for floats. Note: do not use list as a variable name since it's already a built-in function and type.

lst = [2.4, 4.8532, 5.43253]
lst = [int(x) for x in lst]
print(lst)

Output:

[2, 4, 5]


问:
Datamapper update enum value through form
I have a model like this:

```<code>class Project
    include DataMapper::Resource
    property    :id, Serial
    property  :title, String
    property    :slug,  String
    property    :status, Enum[:open, :closed ], :default => :open
    has n, :issues
end
</code>```

I've created a view to update the project status:

```<code><form action="/project/update" method="post" id="project">
        <label for="status">Status
            <select id="status">
                <option value="0"
                <% if(@project.status == :open) %>
                    selected="selected"
                <% end %>
                >Open</option>
                <option value="1"
                <% if(@project.status == :closed) %>
                    selected="selected"
                <% end %>
                >Closed</option>
            </select>
        </label>
    </form>
</code>```

Here's the route:

```<code>    post '/project/update' do
            @project = Project.get(params[:project_id])
            @project.update(:title => params[:title])
    end
</code>```

What values does the form need to pass to the route to update the status? and what should the route look like in this instance?

Thanks,

答: "open" and "closed" - they will be converted to symbols automatically.</p>

Body:
I have a model like this:

class Project
    include DataMapper::Resource
    property    :id, Serial
    property  :title, String
    property    :slug,  String
    property    :status, Enum[:open, :closed ], :default => :open
    has n, :issues
end

I've created a view to update the project status:

<form action="/project/update" method="post" id="project">
        Status
            <select id="status">
                <option value="0"
                <% if(@project.status == :open) %>
                    selected="selected"
                <% end %>
                >Open</option>
                <option value="1"
                <% if(@project.status == :closed) %>
                    selected="selected"
                <% end %>
                >Closed</option>
            </select>

    </form>

Here's the route:

    post '/project/update' do
            @project = Project.get(params[:project_id])
            @project.update(:title => params[:title])
    end

What values does the form need to pass to the route to update the status? and what should the route look like in this instance?

Thanks,


问:
Are multiple `with` statements on one line equivalent to nested `with` statements, in python?
Are these two statements equivalent?

```<code>with A() as a, B() as b:
  # do something

with A() as a:
  with B() as b:
    # do something
</code>```

I ask because both a and b alter global variables (tensorflow here) and b depends on changes made by a. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?

答:
As others have said, it's the same result. Here's a more detailed example of how this syntax might be used:

blah.txt

```<code>1
2
3
4
5
</code>```

I can open one file and write its contents to another file in a succinct manner:

```<code>with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
    for line in infile:
        outfile.write(str(line))
</code>```

foo.txt now contains:

```<code>1
2
3
4
5
</code>```

Body:
Are these two statements equivalent?

with A() as a, B() as b:
  # do something

with A() as a:
  with B() as b:
    # do something

I ask because both a and b alter global variables (tensorflow here) and b depends on changes made by a. So I know the 2nd form is safe to use, but is it equivalent to shorten it to the 1st form?

Body:
As others have said, it's the same result. Here's a more detailed example of how this syntax might be used:

blah.txt

1
2
3
4
5

I can open one file and write its contents to another file in a succinct manner:

with open('blah.txt', 'r') as infile, open('foo.txt', 'w+') as outfile:
    for line in infile:
        outfile.write(str(line))

foo.txt now contains:

1
2
3
4
5


问:
wordpress external js not loading in my theme
I am making my first wordpress theme but when i tried to load external js in my theme its not loading in my page instead of that it load in wp-admin page

functions.php

```<code>wp_enqueue_script('jquery');
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'),'1.0', true );
</code>```

my script.js

```<code>(function($) {

    alert("it workd!!");
})(jQuery);
</code>```

答:
Here is the proper way to enqueue script or js file in WordPress wp-admin page

Enqueue a custom stylesheet in the admin

To load a CSS and/or Javascript file to all admin pages. You can do this from within your plugin or from your themes function file.

```<code>/** * Register and enqueue a custom stylesheet in the WordPress admin.*/
function enqueue_custom_admin_style() {

   //===============================
   // ========= CSS file ===========
   //===============================
   // Register Style
   wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );

    //Enqueue by register ID.
    wp_enqueue_style( 'custom_wp_admin_css' );
    //===============================
    // ======= End CSS file =========
    //===============================

    //===============================
    // ========= JS file ===========
    //===============================
    wp_enqueue_script( 'my_custom_script', get_template_directory_uri().'myscript.js', array(), '1.0' );
    //===============================
    // ======== End JS file =========
    //===============================
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_admin_style' );
</code>```

Body:
I am making my first wordpress theme but when i tried to load external js in my theme its not loading in my page instead of that it load in wp-admin page

functions.php

wp_enqueue_script('jquery');
wp_enqueue_script('scripts', get_template_directory_uri() . '/js/scripts.js', array('jquery'),'1.0', true );

my script.js

(function($) {

    alert("it workd!!");
})(jQuery);

Body:
Here is the proper way to enqueue script or js file in WordPress wp-admin page

Enqueue a custom stylesheet in the admin

To load a CSS and/or Javascript file to all admin pages. You can do this from within your plugin or from your themes function file.

/** * Register and enqueue a custom stylesheet in the WordPress admin.*/
function enqueue_custom_admin_style() {

   //===============================
   // ========= CSS file ===========
   //===============================
   // Register Style
   wp_register_style( 'custom_wp_admin_css', get_template_directory_uri() . '/admin-style.css', false, '1.0.0' );

    //Enqueue by register ID.
    wp_enqueue_style( 'custom_wp_admin_css' );
    //===============================
    // ======= End CSS file =========
    //===============================

    //===============================
    // ========= JS file ===========
    //===============================
    wp_enqueue_script( 'my_custom_script', get_template_directory_uri().'myscript.js', array(), '1.0' );
    //===============================
    // ======== End JS file =========
    //===============================
}
add_action( 'admin_enqueue_scripts', 'enqueue_custom_admin_style' );


问:
Logic behind :hover selector in dropdown menus
Might be a small thing, but I am struggling to find out how the hover selector works logically in dropdown menus.
Here's the entire code in question: https://jsfiddle.net/5dcd9zLh/

```<code>.droplist {
   display:none;
}

li:hover > .droplist {
   display: block;
}
</code>```

Here's my understanding of the current code.

Step 1: li is being hovered over

Step 2: Select all child elements .droplist

Step 3: Apply styling display:block to .droplist

Wouldn't that mean the moment I start to hover my cursor from li over to droplist, the styling would revert back to display:none? Why is it that .droplist maintains its display:block property when li is no longer being hovered over?

答:
Because .droplist is child of li tag. Thus, when you hover to .droplist, this still known as you hover on li tag.

The :hover selector can be known is: "When mouse over me or all of my childs"

Hope this will help you understand this!

Body:
Might be a small thing, but I am struggling to find out how the hover selector works logically in dropdown menus.
Here's the entire code in question: https://jsfiddle.net/5dcd9zLh/

.droplist {
   display:none;
}

li:hover > .droplist {
   display: block;
}

Here's my understanding of the current code.

Step 1: li is being hovered over

Step 2: Select all child elements .droplist

Step 3: Apply styling display:block to .droplist

Wouldn't that mean the moment I start to hover my cursor from li over to droplist, the styling would revert back to display:none? Why is it that .droplist maintains its display:block property when li is no longer being hovered over?


问:
Azure power shell cmdlet: Login-AzureRmAccount interactive doesn't work on windows server R8
PowerShell Version

3.0

Azrue powershell Module Version

3.7.0

OS Version

Windows Server R8

Description

Interactive Login does not work. Login seems successful but power shell doesn't login. Already disabled IE ESC

Debug Output

```<code>Login-AzureRmAccount : Service returned error. Check InnerException for more details: The underlying connection was
closed: An unexpected error occurred on a receive.
At line:1 char:1

Login-AzureRmAccount
  + CategoryInfo          : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
  + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand
</code>```

答:
You could upgrade your PowerShell to 5.0. PowerShell 5.0 supports Windows 2008R2SP1. You could download it from the link.

Notes: Please select Win7AndW2K8R2-KB3134760-x64.msu when you download installer file.

If it also does not work, you could try to reinstall Azure PowerShell, you could install the latest version .msi file from the link.

Update:

You should  installed Windows Management framework 5.1, see this answer.

Body:
PowerShell Version

3.0

Azrue powershell Module Version

3.7.0

OS Version

Windows Server R8

Description

Interactive Login does not work. Login seems successful but power shell doesn't login. Already disabled IE ESC

Debug Output

Login-AzureRmAccount : Service returned error. Check InnerException for more details: The underlying connection was
closed: An unexpected error occurred on a receive.
At line:1 char:1

Login-AzureRmAccount
  + CategoryInfo          : CloseError: (:) [Add-AzureRmAccount], AadAuthenticationFailedException
  + FullyQualifiedErrorId : Microsoft.Azure.Commands.Profile.AddAzureRMAccountCommand


问:
looking for a text pattern in all the files
We have got lot of files with the text like:

create user user_name

identified by crsny

tablespace tab1

Is there anyway to search for   identified by **** /n
and then replace with somethingelse in Notepad++.

答:
Yes; use a standard regex in the Replace dialog (Ctrl+H). You'd probably want something like this in Find what:

```<code>^identified by (\S+)$
</code>```

And then in Replace with, \1.

There are four major parts to this. First are the anchors: ^ matches a zero-width position at the start of a line, and $ does the same thing at the end. () makes a capturing subgroup (automatically indexed from 1 on up by order in the string), which is then dropped into the replacement string with \1 (or \2, or any other subgroup index with a backslash in front). Finally, \S+ matches one or more non-whitespace characters, in lieu of a more specific validation that precisely matches all allowable usernames.

As Jorge suggests, you can use the same patterns in the Find in files tab to do the replacement on all files at a time, but you should probably do this after checking on one file first.

Body:
Yes; use a standard regex in the Replace dialog (Ctrl+H). You'd probably want something like this in Find what:

^identified by (\S+)$

And then in Replace with, \1.

There are four major parts to this. First are the anchors: ^ matches a zero-width position at the start of a line, and $ does the same thing at the end. () makes a capturing subgroup (automatically indexed from 1 on up by order in the string), which is then dropped into the replacement string with \1 (or \2, or any other subgroup index with a backslash in front). Finally, \S+ matches one or more non-whitespace characters, in lieu of a more specific validation that precisely matches all allowable usernames.

As Jorge suggests, you can use the same patterns in the Find in files tab to do the replacement on all files at a time, but you should probably do this after checking on one file first.


答: Its speed depends on files/directories count. If you have a directory with 6 1Gb files, it will take much less time to calculate. It calculates files size in the given directory, and recursively for each child directory.</p>

Title: What is the algorithm unix du command uses to calculate disk space?


问:
How can I efficiently find the maximum element and its indices in a scipy csr_matrix?
I have a sparse undirected graph stored in a scipy csr_matrix, and I need to find out the edge with maximum weight, which means that I need to find the maximum value and its corresponding row and column indices (actually I have to find the K largest values but to simplify the problem). Hence I wrote:

```<code>M=M.toarray()
for i in range(1,len(M)):
    for j in range(i+1,len(M[i])):
        if M[i][j] > maximum:
            row,col,maximum = i,j,M[i][j]
</code>```

It seems to be clumsy and performs poorly. Is there any better way to do this?

答:
If you want to find the maximum alone, M.max() is enough:

```<code>>>> m = scipy.sparse.rand(1000, 1000, format='csr')
>>> type(m)
<class 'scipy.sparse.csr.csr_matrix'>
>>> m.max()
0.99991127228906729
</code>```

If you want find the index as well, besides converting to a coo_matrix, you can to operate on the .data, .indices and .indptr directly. The relationship between these members is mentioned in the documentation,

csr_matrix((data, indices, indptr), [shape=(M, N)])

is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]].

So,

```<code>>>> m.sort_indices()
>>> numpy.argmax(m.data)
1171
>>> index = _
>>> m.indices[index]
483
>>> col = _
>>> numpy.searchsorted(m.indptr, index, side='right') - 1
116
>>> row = _
>>> m[row, col]
0.99991127228906729
</code>```

Body:
I have a sparse undirected graph stored in a scipy csr_matrix, and I need to find out the edge with maximum weight, which means that I need to find the maximum value and its corresponding row and column indices (actually I have to find the K largest values but to simplify the problem). Hence I wrote:

M=M.toarray()
for i in range(1,len(M)):
    for j in range(i+1,len(M[i])):
        if M[i][j] > maximum:
            row,col,maximum = i,j,M[i][j]

It seems to be clumsy and performs poorly. Is there any better way to do this?

Body:
If you want to find the maximum alone, M.max() is enough:

>>> m = scipy.sparse.rand(1000, 1000, format='csr')
>>> type(m)
<class 'scipy.sparse.csr.csr_matrix'>
>>> m.max()
0.99991127228906729

If you want find the index as well, besides converting to a coo_matrix, you can to operate on the .data, .indices and .indptr directly. The relationship between these members is mentioned in the documentation,

csr_matrix((data, indices, indptr), [shape=(M, N)])

is the standard CSR representation where the column indices for row i are stored in indices[indptr[i]:indptr[i+1]] and their corresponding values are stored in data[indptr[i]:indptr[i+1]].

So,

>>> m.sort_indices()
>>> numpy.argmax(m.data)
1171
>>> index = _
>>> m.indices[index]
483
>>> col = _
>>> numpy.searchsorted(m.indptr, index, side='right') - 1
116
>>> row = _
>>> m[row, col]
0.99991127228906729


问:
How can I upload my local wordpress to a digital ocean droplet I have set up?
I have recently finished developing my first wordpress site for a client, I have set up a digital ocean droplet and installed Wordpress (which works successfully!).

Can somebody please give me layman terms instructions on how to upload my local site to the digital ocean droplet please?

I am a beginner and struggling!

Many thanks in advance!

答:
Since you are a beginner, just follow the below simple steps,

1. Create a DB in digital ocean server.

2. Move all the files to the server.

3. Edit the DB connection information in wp-config.php file with the DB data you created in step 1.

4. Export DB from your local.

5. Open the sql file and find/replace all the occurrence of local url into your live website url. You can find this url in wp_options table as site url.

6. Import the sql into the live DB which you created at step 1.

You are done.


问:
GSuite sso login issue
I have created an SSO application in app engine for G Suite. Normally it is working fine but when users are trying to login between the time 5:30am - 6:30am IST(UTC timing 00:00hours - 01:00hours),they are getting the following issue:

"This service cannot be accessed because your login credentials are not yet valid. Please log in and try again."

As per Google's solution it is asking to 'Check the clock on your Identity Provider's server'.The IDP here is Google app engine.Can anyone please help me out with the solution?

答: so, the app you're making is an Identity Provider itself and not an app that just uses SSO / SAML to authenticate into the app? i.e. you're making a OneLogin / Okta / etc replacement within App Engine?</p>

Title: GSuite sso login issue


问:
How to easily give if statement for checking one list contains some keyword
I want to check one list contains some keywords.

My writing is below:

```<code>if ('keyword1' or 'keyword2' or 'keyword3') in [list]:
</code>```

above works, but seems not good writing.

Any other method to improve it?

答:
you can use python built-in any method, https://docs.python.org/2/library/functions.html#any

```<code>search_terms = ['a', 'keyword1']
list = ['blabla', 'keyword1', 'keyword4']
if any(word in list for word in search_terms):
 // TRUE
</code>```

Body:
I want to check one list contains some keywords.

My writing is below:

if ('keyword1' or 'keyword2' or 'keyword3') in [list]:

above works, but seems not good writing.

Any other method to improve it?

Body:
you can use python built-in any method, https://docs.python.org/2/library/functions.html#any

search_terms = ['a', 'keyword1']
list = ['blabla', 'keyword1', 'keyword4']
if any(word in list for word in search_terms):
 // TRUE


答:
You will have to create a new list, such as with a comprehension. You might want to get the first digit of each element, or possibly get the floor value of each element:

```<code>>>> l = [2.4, 4.8532, 5.43253]
>>> l2 = [12.4, 374.8532, -505.43253]
>>> list(map(int, (i[0] for i in map(str, l))))
[2, 4, 5]
>>> list(map(int, l))
[2, 4, 5]
>>> list(map(int, (i[0] for i in map(str, l2))))
>>> [i[0] for i in map(str, l2)]
['1', '3', '-']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-'
>>> list(map(int, l2))
[12, 374, -505]
</code>```

Note how you will need to be more specific regarding the assumptions about the contents of the list. Can the numbers be greater than 10? Can they be negative? Do you want the first digit of a negative number, or the first character? If it's always 0 < number < 10, you have nothing to worry about.

Title: Python: get first number of every float in a list

Body:
You will have to create a new list, such as with a comprehension. You might want to get the first digit of each element, or possibly get the floor value of each element:

>>> l = [2.4, 4.8532, 5.43253]
>>> l2 = [12.4, 374.8532, -505.43253]
>>> list(map(int, (i[0] for i in map(str, l))))
[2, 4, 5]
>>> list(map(int, l))
[2, 4, 5]
>>> list(map(int, (i[0] for i in map(str, l2))))
>>> [i[0] for i in map(str, l2)]
['1', '3', '-']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '-'
>>> list(map(int, l2))
[12, 374, -505]

Note how you will need to be more specific regarding the assumptions about the contents of the list. Can the numbers be greater than 10? Can they be negative? Do you want the first digit of a negative number, or the first character? If it's always 0 < number < 10, you have nothing to worry about.


问:
How to compare 2 objects that are created in different subclasses
I looked everywhere and haven't seen anything like this. I'm fairly new to java and have a homework assignment. The assignment is a Library. It has Books and dvd's, new and used. Im tying to compare an object to determine the correct fine.

Im basically asking the program, hey, is this a book or a dvd? and then hey, is this a new book or dvd, or is this an older one.

```<code>public double isLate(LocalDate argDateCheckedOut, LIBRARYMATERIALS argMaterial)
{
    LocalDate dateCheckedIn =  LocalDate.now();
    double diff=ChronoUnit.DAYS.between(argDateCheckedOut, dateCheckedIn);

    double fine = 0;

    if(argMaterial.equals(BOOK))
    {
        //calculate fine for book
        if(argMaterial.getisNew() == true)
        {
            if(diff > 21)
            {
                fine = 1 + .25*diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 28)
            {
                fine = .25 * diff;
            }
        }
    }

    else if(argMaterial.equals(DVD))
    {
        //calculate fine for dvd
        if(argMaterial.getisNew() == true)
        {
            if(diff > 3)
            {
                fine = 5 + diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 7)
            {
                fine = diff;
            }
        }

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

答:
I would consider wiring this differently. I'd create a parent class or interface for Book and DVD (say called "LibraryResource") a public double getFine() method, perhaps make it abstract, and then I'd have Book and DVD override the parent method. Let the object calculate its own fine rather than make things difficult for yourself.

For example, if you had such a parent class:

```<code>public abstract class LibraryResource {
    private LocalDate checkOutDate;
    private boolean newResource;

    abstract public double calculateFine(); // **** make this abstract ****

    public LibraryResource(LocalDate checkOutDate, boolean newResource) {
        this.checkOutDate = checkOutDate;
        this.newResource = newResource;
    }

    public boolean isNewResource() {
        return newResource;
    }

    public void setNewResource(boolean newResource) {
        this.newResource = newResource;
    }

    public LocalDate getCheckOutDate() {
        return checkOutDate;
    }

}
</code>```

And then both Book and Dvd could have their own formulas for calculating a fine. For example, the Book class could look something like:

```<code>public class Book extends LibraryResource {
    private static final long SHORT_OVER_DUE_DIFF = 21;
    private static final long LONG_OVER_DUE_DIFF = 28;

    public Book(LocalDate checkOutDate, boolean newResource) {
        super(checkOutDate, newResource);
    }

    @Override
    public double calculateFine() {
        double fine = 0.0;
        LocalDate dateCheckedIn = LocalDate.now();
        long diff = ChronoUnit.DAYS.between(getCheckOutDate(), dateCheckedIn);

        if (isNewResource()) {
            if (diff > SHORT_OVER_DUE_DIFF) {
                fine = 1 + 0.25 * diff;
            } else if (diff > LONG_OVER_DUE_DIFF) {

                // .... ??

            }
        } else {
            // else it is NOT new
            if (diff > SHORT_OVER_DUE_DIFF) {

                // .... ??

            } else if (diff > LONG_OVER_DUE_DIFF) {
                fine = 0.25 * diff;
            }
        }
        return fine;
    }

}
</code>```

Body:
I looked everywhere and haven't seen anything like this. I'm fairly new to java and have a homework assignment. The assignment is a Library. It has Books and dvd's, new and used. Im tying to compare an object to determine the correct fine.

Im basically asking the program, hey, is this a book or a dvd? and then hey, is this a new book or dvd, or is this an older one.

public double isLate(LocalDate argDateCheckedOut, LIBRARYMATERIALS argMaterial)
{
    LocalDate dateCheckedIn =  LocalDate.now();
    double diff=ChronoUnit.DAYS.between(argDateCheckedOut, dateCheckedIn);

    double fine = 0;

    if(argMaterial.equals(BOOK))
    {
        //calculate fine for book
        if(argMaterial.getisNew() == true)
        {
            if(diff > 21)
            {
                fine = 1 + .25*diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 28)
            {
                fine = .25 * diff;
            }
        }
    }

    else if(argMaterial.equals(DVD))
    {
        //calculate fine for dvd
        if(argMaterial.getisNew() == true)
        {
            if(diff > 3)
            {
                fine = 5 + diff;
            }

        }
        else if(argMaterial.getisNew() == false)
        {
            if(diff > 7)
            {
                fine = diff;
            }
        }

    }
    return fine;
}

Body:
I would consider wiring this differently. I'd create a parent class or interface for Book and DVD (say called "LibraryResource") a public double getFine() method, perhaps make it abstract, and then I'd have Book and DVD override the parent method. Let the object calculate its own fine rather than make things difficult for yourself.

For example, if you had such a parent class:

public abstract class LibraryResource {
    private LocalDate checkOutDate;
    private boolean newResource;

    abstract public double calculateFine(); // **** make this abstract ****

    public LibraryResource(LocalDate checkOutDate, boolean newResource) {
        this.checkOutDate = checkOutDate;
        this.newResource = newResource;
    }

    public boolean isNewResource() {
        return newResource;
    }

    public void setNewResource(boolean newResource) {
        this.newResource = newResource;
    }

    public LocalDate getCheckOutDate() {
        return checkOutDate;
    }

}

And then both Book and Dvd could have their own formulas for calculating a fine. For example, the Book class could look something like:

public class Book extends LibraryResource {
    private static final long SHORT_OVER_DUE_DIFF = 21;
    private static final long LONG_OVER_DUE_DIFF = 28;

    public Book(LocalDate checkOutDate, boolean newResource) {
        super(checkOutDate, newResource);
    }

    @Override
    public double calculateFine() {
        double fine = 0.0;
        LocalDate dateCheckedIn = LocalDate.now();
        long diff = ChronoUnit.DAYS.between(getCheckOutDate(), dateCheckedIn);

        if (isNewResource()) {
            if (diff > SHORT_OVER_DUE_DIFF) {
                fine = 1 + 0.25 * diff;
            } else if (diff > LONG_OVER_DUE_DIFF) {

                // .... ??

            }
        } else {
            // else it is NOT new
            if (diff > SHORT_OVER_DUE_DIFF) {

                // .... ??

            } else if (diff > LONG_OVER_DUE_DIFF) {
                fine = 0.25 * diff;
            }
        }
        return fine;
    }

}


问:
How do I reload UITableView data when the app comes to foreground? (Xcode 8.3 / Swift 3)
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

```<code>//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}
</code>```

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

```<code>//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}
</code>```

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

答:
UIApplicationWillEnterForeground Notification

Posted shortly before an app leaves the background state on its way to becoming the active app.

Discussion

The object of the notification is the UIApplication object. There is no userInfo dictionary.

Declaration

```<code>static let UIApplicationWillEnterForeground: NSNotification.Name
</code>```

From Apple's Documentation.

It's super easy to use:

```<code>override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(self.handler), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}

func handler() {
    // self.tableView.reloadData()
}
</code>```

Hope it helps!

Body:
I have the following methods in my "ViewController" class to populate custom cells in a UITableView from a GET API call. This works fine when app first loads.

//ViewController
override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)
    loadDataInUITableViewCell()
}

func loadDataInUITableViewCell() {
        apiCentral.sharedInstance.fetchData() {
        result in
        guard result.error == nil else {
            self.handleError(result.error!)
            return
        }
        if let fetchedData = result.value {
            self.data = fetchedData
        }
        self.messagesTableView.reloadData()
    }
}

How do I refresh the data when the app comes to the foreground? Well, I added the following to AppDelegate to run the "loadDataInUITableViewCell" method so that the data reloads.

//AppDelegate
let mainViewController = ViewController()

func applicationWillEnterForeground(_ application: UIApplication) {
    mainViewController.loadDataInUITableViewCell()
}

ISSUE: The above mechanism works fine however, I get the following error when the app comes to the foreground.

"fatal error: unexpectedly found nil while unwrapping an Optional value"

The issue seems to be happening at "self.messagesTableView.reloadData()" line of code. I'm using Xcode 8.3 and coding in Swift 3. Any guidance would be appreciated. Thank you.

Body:
UIApplicationWillEnterForeground Notification

Posted shortly before an app leaves the background state on its way to becoming the active app.

Discussion

The object of the notification is the UIApplication object. There is no userInfo dictionary.

Declaration

static let UIApplicationWillEnterForeground: NSNotification.Name

From Apple's Documentation.

It's super easy to use:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)

    NotificationCenter.default.addObserver(self, selector: #selector(self.handler), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
}

func handler() {
    // self.tableView.reloadData()
}

Hope it helps!


问:
Longest common subsequence—where is my infinite loop?
I'm trying to implement the longest common subsequence algorithm in Ruby, but I'm getting the stack level too deep error message. I know this probably means I have an infinite loop, but I cannot spot it. Below is my best attempt—where am I going wrong?

```<code>def lcs(string1, string2)
  if !(string1.chars.any? { |x| string2.include?(x)})
    return ""
  elsif string1[-1] == string2[-1]
    return lcs(string1[0..-2], string2[0..-2]) + string1[-1]
  else
    x = lcs(string1, string2[0..-1])
    y = lcs(string1[0..-1], string2)
    x.length > y.length ? x : y
  end
end
</code>```

n.b. I'm trying to return the subsequence itself, not its length.

答:
Try it with a sample string: abcd and bc and step through it.

You'll realise that these two lines have issues:

```<code>x = lcs(string1, string2[0..-1])
y = lcs(string1[0..-1], string2)
</code>```

Because 'abcd'[0..-1] -> 'abcd' so the moment it reaches x = ... line it'll get stuck.

It should be [0..-2] instead.

Also, you can use if string1.chars.none? { |x| string2.include?(x)}
to replace if !(string1.chars.any? { |x| string2.include?(x)})

Body:
I'm trying to implement the longest common subsequence algorithm in Ruby, but I'm getting the stack level too deep error message. I know this probably means I have an infinite loop, but I cannot spot it. Below is my best attempt—where am I going wrong?

def lcs(string1, string2)
  if !(string1.chars.any? { |x| string2.include?(x)})
    return ""
  elsif string1[-1] == string2[-1]
    return lcs(string1[0..-2], string2[0..-2]) + string1[-1]
  else
    x = lcs(string1, string2[0..-1])
    y = lcs(string1[0..-1], string2)
    x.length > y.length ? x : y
  end
end

n.b. I'm trying to return the subsequence itself, not its length.

Body:
Try it with a sample string: abcd and bc and step through it.

You'll realise that these two lines have issues:

x = lcs(string1, string2[0..-1])
y = lcs(string1[0..-1], string2)

Because 'abcd'[0..-1] -> 'abcd' so the moment it reaches x = ... line it'll get stuck.

It should be [0..-2] instead.

Also, you can use if string1.chars.none? { |x| string2.include?(x)}
to replace if !(string1.chars.any? { |x| string2.include?(x)})


问:
When is a factory appropriate?
Taken from wikipedia:

In object-oriented computer
  programming, a factory is an object
  for creating other objects. It is an
  abstraction of a constructor, and can
  be used to implement various
  allocation schemes.

Could anyone please explain when a factory class is required or beneficial?

I am currently working on a project where I have a class and use the constructor to initialize an object (duh!) but it can fail and not initialize at all. I have a Success property to check if it was created properly. Is this a good example for when a factory class should be implemented? This way the Create() method can return null and I can get rid of the Success property. Do I have the right idea?

答:
I will try a simple answer :)

From Wikipedia.

Use the factory pattern when:

The creation of the object precludes reuse without significantly duplicating code.

The creation of the object requires access to information or resources not appropriate to contain within the composing object.

The lifetime management of created objects needs to be centralised to ensure consistent behavior.

So I think you don't 'need' a factory in your particular case.
But I'd say having one does not hurt.

A common use for factories would be if you want to return an interface and hide the implementing class.

For instance:

```<code>public final class LoginFactory {

private final static Map<SomeEnum, LoginInterface> IMPLEMENTERS = new HashMap<SomeEnum, LoginInterface>();

static {
    IMPLEMENTERS.put(SomeEnum.QUICK, new QuickerLoginImpl());
    IMPLEMENTERS.put(SomeEnum.SECURE, new SecureLoginImpl());
}

public static LoginInterface getLoginImpl(SomeEnum type) { // my naming is bad ...
    return IMPLEMENTERS.get(type);
}
</code>```

}

This way you can change your SecureLoginImpl to MoreSecureLoginImpl for example without the user of your API even noticing.

You might also want to have a look at this wiki page Abstract Factory pattern.

Title: When is a factory appropriate?

Body:
I will try a simple answer :)

From Wikipedia.

Use the factory pattern when:

The creation of the object precludes reuse without significantly duplicating code.

The creation of the object requires access to information or resources not appropriate to contain within the composing object.

The lifetime management of created objects needs to be centralised to ensure consistent behavior.

So I think you don't 'need' a factory in your particular case.
But I'd say having one does not hurt.

A common use for factories would be if you want to return an interface and hide the implementing class.

For instance:

public final class LoginFactory {

private final static Map<SomeEnum, LoginInterface> IMPLEMENTERS = new HashMap<SomeEnum, LoginInterface>();

static {
    IMPLEMENTERS.put(SomeEnum.QUICK, new QuickerLoginImpl());
    IMPLEMENTERS.put(SomeEnum.SECURE, new SecureLoginImpl());
}

public static LoginInterface getLoginImpl(SomeEnum type) { // my naming is bad ...
    return IMPLEMENTERS.get(type);
}

}

This way you can change your SecureLoginImpl to MoreSecureLoginImpl for example without the user of your API even noticing.

You might also want to have a look at this wiki page Abstract Factory pattern.


问:
How to properly delete and re-add Entity Data Model
newbie to Entity Framework here.  Using VS 2010 and SQL Server 2008 express DB.

I was having trouble refreshing an Entity Data Model after adding new tables.  So, I followed a suggestion I found here to just delete and regenerate the model.

I get to the "Choose Your Data Connection" section of the Entity Data Model Wizard and "Save entity connection settings in Web.config as:" is checked.  However, my existing name has a 1 appended to it.  For example MyDatabaseEntities is now MyDatabaseEntities1.  Of course, I don't want the "1" appended.  I killed the existing connection string in Web.config and removed all references to that name in my solution.  Yet when I try to continue I'm presented with the following error:

"'MyDatabaseEntites' conflicts with an existing property name in the Application Settings.  Please choose a different name"

I can't find a reference to that name anywhere in the solution.  I can uncheck that option and it will continue, but it STILL won't add two of the tables in the database.  Next, I completely shut everything down, rebooted, and tried again.  This time I didn't get the error above, but two of my three new tables still do not get added to the edmx model.

Any ideas are appreciated.  Also this seems like it's still pretty buggy even in VS2010/.NET 4.  Help restore my faith...I feel like abandoning Entity Framework at this point.  Based on my experience so far and some of the other issues posted here, I feel like I'm going to spend more time chasing Entity Framework strangeness than writing useful code.

UPDATE:  I found a resolution.  The designer doesn't display errors.  You have have to look in the native XML (edmx file) to see the errors.  See here:  ADO.NET Entity Framework: Update Wizard will not add tables

答: Double check your connection strings, and keep scrolling to the right. Most often, when this happens to me, Visual Studio has appended a connection string behind another. I've done this a couple times, and wondered where my app config was (no, there is no app config, just web config in mvc), so the dialog is a little confusing. Sure enough, most likely that connection string is lurking directly behind another!</p>


问:
SQL how can I get latest row if a specific condition is matched
I am new to SQL but what I am trying to do is a comment reply feature . For instance lets say you have a profile_id of 11 and you commented a post with a post_id of 339 . If several other people commented on that post then I want to show you the latest comment on that post since you commented on it. Look at the first image below that is the table as you can see user 11 posted in the middle . I would like to get the last comment on that post that states blah blah since user 11 comments on it.

This is the table

 If I am user 11 I want to only see the latest comment posted on the same thread/post that I commented on . Which means that I want to see the post that says "Blah Blah" below however I am only getting my comment . Any suggestions would be great. I am using Postgres 9.6

答:
```<code>SELECT * FROM comment_replies ORDER BY last_reply_timestamp DESC LIMIT 1;
</code>```

This will order them by newest to oldest using Order By. It will also only show 1 result because of LIMIT 1

Body:
SELECT * FROM comment_replies ORDER BY last_reply_timestamp DESC LIMIT 1;

This will order them by newest to oldest using Order By. It will also only show 1 result because of LIMIT 1


问:
Visual Studio 2017 - Solution link not showing
I go to Visual Studio Team Services (xxxx.visualstudio.com), create a new project, go into Visual Studio 2017, Manage Connections > Connect to Project, select the project and Clone. Create new project message shows up, I create a new .Net Core API. Click on the Team Explorer tab:

Where is the new solution on the list? I click on Changes:

Yes, it sees the files that need to be committed, even when solution is not open, there is nothing on the solution explorer. Click the Home Icon on top, again, it's not finding the solution.

I have tried variations of this about 20 times, deleting and recreating, changing the order, etc.

I can click Open, under Solutions, and open the solution, but WHY OH WHY wont it show under Solutions. I don't have this issue in Visual Studio 2015.

答:
This is the change for VS2017. You can click show Folder view, it will show solution(s) in solution Explorer.

We’re working on transitioning the services formerly provided by the
  Solution section in Team Explorer to the new “AnyCode” support
  provided by the Solution Explorer.

Also you can find it in developer community.


问:
google map from dismo::gmap() and ggplot2
I obtained a map with the function dismo::gmap() and want to plot it with ggplot2 because I want to add different feautures using geom_point and other ggplot functions. I prefer to use dismo::gmap instead of ggmap::get_map() to download the google map layer. This is because dismo::gmap(), unlike ggmap::get_map(), returns a raster layer from package raster including complete CRS information and therefore is should be possible to modify the projection of the layer.

```<code>> head(data_info$latitude, 20)
#[1] 49.11306 49.39333 48.78083 51.85000 53.57361 50.67806 52.69083 52.21389 53.46361 50.99917 53.99750 53.54528 53.61417 48.00556 48.01306 53.45000
#[17] 51.93667 54.53083 51.95500 54.29639
> head(data_info$longitude, 20)
#[1] 13.134722 12.323056 13.803889 12.177778 14.143611 13.175833 12.649444 13.454167 11.629722 10.906111 11.415556  8.426944  7.160000 11.123889 10.786111
#[16] 12.766667 11.987222 13.091389 10.967500 13.684167

   e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

# plot the points on the map
ggplot(mapImageData2_proj, extent = "device") +
  geom_point(inherit.aes = FALSE, aes(x = data_info$longitude, y = data_info$latitude),
             data = gps, colour = "red", size = 1, pch = 20)
</code>```

After trying this, I get the following error:

Error: ggplot2 doesn't know how to deal with data of class
  RasterLayer

If I try this

```<code>plot(mapImageData2_proj)
</code>```

Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,
  :    no values associated with this RasterLayer

答:
There are two issues in this question.  One is how to get ggplot2 to plot a Raster* object.  The other is how to reproject a raster while retaining its values.

The OP contains the code

```<code>library(dismo)
e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")
</code>```

If we run this and then do plot(mapImageData2) we get a nice plot.  The OP then runs

```<code>mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")
</code>```

Now if we run plot(mapImageData2_proj) we get an error!  That's because projectExtent returns a RasterLayer with no values.  We need to use projectRaster() instead.  See ?projectExtent for details. So we run:

```<code>mapImageData2_proj <- projectRaster(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")
plot(mapImageData2_proj)
</code>```

Now we see the reprojected map.  Progress!  But we still can't plot mapImageData2_proj using ggplot2, because ggplot2 doesn't know how to handle a Raster* object.  We need to convert our raster to a dataframe. There are a few ways to do this, but without loading any additional packages, a good option is raster::rasterToPoints().  For example:

```<code>myPoints <- raster::rasterToPoints(myRaster)
myDataFrame <- data.frame(myPoints)
colnames(myDataFrame) <- c("Longitude", "Latitude", "Values")

ggplot(data=myDataFrame, aes_string(y = "Latitude", x = "Longitude")) +
   geom_raster(aes(fill = Values))
</code>```

So to put it all together in the OP's example:

```<code>library(dismo)
e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

plot(mapImageData2)

mapImageData2_proj <- projectRaster(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

plot(mapImageData2_proj)

myRaster <- mapImageData2_proj
myPoints <- raster::rasterToPoints(myRaster)
myDataFrame <- data.frame(myPoints)
colnames(myDataFrame) <- c("X", "Y", "Values")

ggplot(data=myDataFrame, aes_string(y = "Y", x = "X")) +
  geom_raster(aes(fill = Values))
</code>```

Body:
I obtained a map with the function dismo::gmap() and want to plot it with ggplot2 because I want to add different feautures using geom_point and other ggplot functions. I prefer to use dismo::gmap instead of ggmap::get_map() to download the google map layer. This is because dismo::gmap(), unlike ggmap::get_map(), returns a raster layer from package raster including complete CRS information and therefore is should be possible to modify the projection of the layer.

> head(data_info$latitude, 20)
#[1] 49.11306 49.39333 48.78083 51.85000 53.57361 50.67806 52.69083 52.21389 53.46361 50.99917 53.99750 53.54528 53.61417 48.00556 48.01306 53.45000
#[17] 51.93667 54.53083 51.95500 54.29639
> head(data_info$longitude, 20)
#[1] 13.134722 12.323056 13.803889 12.177778 14.143611 13.175833 12.649444 13.454167 11.629722 10.906111 11.415556  8.426944  7.160000 11.123889 10.786111
#[16] 12.766667 11.987222 13.091389 10.967500 13.684167

   e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

# plot the points on the map
ggplot(mapImageData2_proj, extent = "device") +
  geom_point(inherit.aes = FALSE, aes(x = data_info$longitude, y = data_info$latitude),
             data = gps, colour = "red", size = 1, pch = 20)

After trying this, I get the following error:

Error: ggplot2 doesn't know how to deal with data of class
  RasterLayer

If I try this

plot(mapImageData2_proj)

Error in .plotraster2(x, col = col, maxpixels = maxpixels, add = add,
  :    no values associated with this RasterLayer

Body:
There are two issues in this question.  One is how to get ggplot2 to plot a Raster* object.  The other is how to reproject a raster while retaining its values.

The OP contains the code

library(dismo)
e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

If we run this and then do plot(mapImageData2) we get a nice plot.  The OP then runs

mapImageData2_proj <- projectExtent(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

Now if we run plot(mapImageData2_proj) we get an error!  That's because projectExtent returns a RasterLayer with no values.  We need to use projectRaster() instead.  See ?projectExtent for details. So we run:

mapImageData2_proj <- projectRaster(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")
plot(mapImageData2_proj)

Now we see the reprojected map.  Progress!  But we still can't plot mapImageData2_proj using ggplot2, because ggplot2 doesn't know how to handle a Raster* object.  We need to convert our raster to a dataframe. There are a few ways to do this, but without loading any additional packages, a good option is raster::rasterToPoints().  For example:

myPoints <- raster::rasterToPoints(myRaster)
myDataFrame <- data.frame(myPoints)
colnames(myDataFrame) <- c("Longitude", "Latitude", "Values")

ggplot(data=myDataFrame, aes_string(y = "Latitude", x = "Longitude")) +
   geom_raster(aes(fill = Values))

So to put it all together in the OP's example:

library(dismo)
e = extent(-14 , 58 , 28 , 64)
mapImageData2 <- gmap(e, type = c("terrain"), lonlat = TRUE,
                      path = "&style=feature:all|element:labels|visibility:off&style=feature:administrative.country|element:geometry.stroke|visibility:off")

plot(mapImageData2)

mapImageData2_proj <- projectRaster(mapImageData2, crs = "+proj=utm +zone=31 +datum=WGS84")

plot(mapImageData2_proj)

myRaster <- mapImageData2_proj
myPoints <- raster::rasterToPoints(myRaster)
myDataFrame <- data.frame(myPoints)
colnames(myDataFrame) <- c("X", "Y", "Values")

ggplot(data=myDataFrame, aes_string(y = "Y", x = "X")) +
  geom_raster(aes(fill = Values))


问:
Navigator - SceneConfig Is It Possible To Have 'No' Transition?
Being able to use animated transitions is awesome in Navigator. But I want to be able to flip between routes without animation and just have it quickly pop there like you would with a Tab Bar. Like 1 frame it's route A and in the next frame it's route B.

Navigator.SceneConfigs.FadeAndroid comes close, but if I just simply accelerate the animation it has this undesirable flicker effect.

What would a non-animated SceneConfig look like?

Any ideas? Thanks!

答:
Here's a custom NoTransition.js:

```<code>import { Navigator } from 'react-native'
import buildStyleInterpolator from 'buildStyleInterpolator' // eslint-disable-line import/no-extraneous-dependencies

// Based on https://github.com/facebook/react-native/issues/1953#issuecomment-209872368

const NoTransition = {
  opacity: {
    type: 'constant',
    value: 1.0,
  },
}

export default Object.assign({}, Navigator.SceneConfigs.FadeAndroid, {
  animationInterpolators: {
    into: buildStyleInterpolator(NoTransition),
    out: buildStyleInterpolator(NoTransition),
  },
  defaultTransitionVelocity: 1000,
  gestures: null,
})
</code>```

Return it from Navigator's configureScene prop to use.

Body:
Here's a custom NoTransition.js:

import { Navigator } from 'react-native'
import buildStyleInterpolator from 'buildStyleInterpolator' // eslint-disable-line import/no-extraneous-dependencies

// Based on https://github.com/facebook/react-native/issues/1953#issuecomment-209872368

const NoTransition = {
  opacity: {
    type: 'constant',
    value: 1.0,
  },
}

export default Object.assign({}, Navigator.SceneConfigs.FadeAndroid, {
  animationInterpolators: {
    into: buildStyleInterpolator(NoTransition),
    out: buildStyleInterpolator(NoTransition),
  },
  defaultTransitionVelocity: 1000,
  gestures: null,
})

Return it from Navigator's configureScene prop to use.


问:
Binary Search in C - wrong exit code when integer not in the array
This C Binary search function is finding what it's supposed to but I'm getting the error: "\ expected an exit code of 1, not 0 " if the integer it's looking for is not in the array.  I have tried removing false at the end or removing the else statement but this doesn't work. Can anyone see why?

```<code>bool search(int value, int values[], int n)
{
    int min = 0;
    int max = n-1;
    int mid = (max + min) / 2;

    if(n <= 0)
        {
            return false;
        }

    while (values[max] >= values[min])
        {
            if (values[mid] == value)
                {
                    return true;
                }

            else if (values[mid] > value) //value's on the left of mid
                {
                    min = 0;
                    max = mid - 1;
                    return true;
                }

            else if (values[mid] < value) //value's on the right of mid
                {
                    max = n-1;
                    min = mid + 1;
                    return true;
                }

            else
                {
                    return false;
                }

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

I just modified the code to the following and got exactly the same result. Thought this might narrow down the problem.

```<code>bool search(int value, int values[], int n)
{
int min = 0;
int max = n-1;
int mid = (max + min) / 2;

if(n <= 0)
{
    return false;
}

if (values[max] >= values[min])
{
    if (values[mid] == value)
    {
        return true;
    }

    else if (values[mid] > value) //value's on the left of mid
    {
        min = 0;
        max = mid - 1;
        return true;
    }

    else if (values[mid] < value) //value's on the right of mid
    {
        max = n-1;
        min = mid + 1;
        return true;
    }

    else
    {
        return false;
    }

}
else
{
    return 1;
}
}
</code>```

答:
Note that true and false return codes depend on the context.

In C - False is considered to be only numeric 0, True is anything which is not 0.

In Linux - it's the opposite when talking about return code (or exit code) of a process. True is only 0 (means exited gracefully), and False is anything but 0 (means exited with some error, depends on the code).

Addition: You have also a logical bug - your search function code is not working. When you're checking if the value is left or on the right of mid:

You shouldn't return anything, the while loop should just continue. In your implementation, the while loop exits after one iteration - always. Regardless the input.

You're updating min (in the left check) and max (in the right check) wrongly. You always update them to be the first/last indices and it's wrong. Every iteration the range that you're searching supposed to be cut in half comparing to the previous one.

Body:
This C Binary search function is finding what it's supposed to but I'm getting the error: "\ expected an exit code of 1, not 0 " if the integer it's looking for is not in the array.  I have tried removing false at the end or removing the else statement but this doesn't work. Can anyone see why?

bool search(int value, int values[], int n)
{
    int min = 0;
    int max = n-1;
    int mid = (max + min) / 2;

    if(n <= 0)
        {
            return false;
        }

    while (values[max] >= values[min])
        {
            if (values[mid] == value)
                {
                    return true;
                }

            else if (values[mid] > value) //value's on the left of mid
                {
                    min = 0;
                    max = mid - 1;
                    return true;
                }

            else if (values[mid] < value) //value's on the right of mid
                {
                    max = n-1;
                    min = mid + 1;
                    return true;
                }

            else
                {
                    return false;
                }

        }
    return false;
}

I just modified the code to the following and got exactly the same result. Thought this might narrow down the problem.

bool search(int value, int values[], int n)
{
int min = 0;
int max = n-1;
int mid = (max + min) / 2;

if(n <= 0)
{
    return false;
}

if (values[max] >= values[min])
{
    if (values[mid] == value)
    {
        return true;
    }

    else if (values[mid] > value) //value's on the left of mid
    {
        min = 0;
        max = mid - 1;
        return true;
    }

    else if (values[mid] < value) //value's on the right of mid
    {
        max = n-1;
        min = mid + 1;
        return true;
    }

    else
    {
        return false;
    }

}
else
{
    return 1;
}
}


问:
User Trajectory Creation with Python
I'm in need of some assistance creating trajectories in python. I have a CSV with user_ids, timestamp, latitude, and longitude. I would like to create a 5th column in my file (or write to new file all together) containing the trajectory of each user_id, which requires grouping the coordinates by their user, and sorting (ascending) by the timestamp. I was able to accomplish in PostGIS, but the results are geometries and what I need are strings of coordinates. I have tried using collections and itertools, as well as Pandas, to group and sort, but I'm struggling.

For reference, here is a few lines of my data:

```<code>user_id, timestamp, latitude, longitude
478134225, 3/12/2017 9:04, 38.8940974, -77.0276216
478103585, 3/12/2017 9:04, 38.882584, -77.1124701
478073193, 3/12/2017 9:07, 39.00027849, -77.09480086
476194185, 3/12/2017 9:14, 38.8048355, -77.0469214
476162349, 3/12/2017 9:16, 38.8940974, -77.0276216
478073193, 3/12/2017 9:05, 38.8549, -76.8752
477899275, 3/12/2017 9:08, 38.90181532, -77.03733586
477452890, 3/12/2017 9:08, 38.96117237, -76.95561893
478073193, 3/12/2017 9:05, 38.7188716, -77.1542684
</code>```

As you can see, there are users with multiple entries, so I need to group by them and order the coordinates by time. E.g. something similar to below

```<code>478073193 (38.8549,-76.8752)(38.7188716,-77.1542684)(39.00027849,-77.09480086)
</code>```

I have well over 150k points, so doing by hand like I did above isn't an option.

答:
This should do it. It uses the popular pandas package and numpy.

```<code>import pandas as pd
import numpy as np

# First we import the data
data = pd.read_csv('data.csv', delimiter=', ')

# Now get a list of unique user_id values
uniqueIds = np.unique(data['user_id'].values)

# Now just get the ordered (by timestamp) coordinates for each user_id
output = [[id,data.loc[data['user_id']==id].sort_values(by='timestamp')[['latitude','longitude']].values.tolist()] for id in uniqueIds]
</code>```

The output is a list with each element of the form [id, list_of_paired_coordinates], e.g.:

```<code>[[476162349, [[38.8940974, -77.02762159999999]]],
 [478073193, [[38.8549, -76.8752],
              [38.7188716, -77.1542684],
              [39.00027849, -77.09480086]]],
 [478103585, [[38.882584, -77.11247009999998]]],
 [478134225, [[38.8940974, -77.02762159999999]]]]
</code>```

Edit

If you'd like to save the output in JSON format you could do something like:

```<code>import json

# Now turn our array into a dict {id:coordinates}
outputDict = {}
for i in output:
    outputDict[i[0]]=i[1]

with open('output.json', 'w') as f:
    json.dump(outputDict, f, sort_keys=True, indent=4, ensure_ascii=False, separators=(',',':'))
</code>```

Depending on how you'd like the output file formatted you may need to modify the structure of outputDict a little bit (let me know if this is the case). Right now the JSON file looks like:

```<code>{
    "476162349":[
        [
            38.8940974,
            -77.02762159999999
        ]
    ],
    "476194185":[
        [
            38.804835499999996,
            -77.0469214
        ]
    ....
</code>```

Edit 2

If you want to format the output JSON file you can add labels to the values stored in the dict:

```<code>outputDict = {}
for i in output:
    coords={}
    latList=[]
    longList=[]
    for j in i[1]:
    latList.append(j[0])
    longList.append(j[1])
    coords["latitude"]=latList
    coords["longitude"]=longList
    outputDict[i[0]]=coords
</code>```

The output JSON file would look this this:

```<code>{
    "476162349":{
        "latitude":[
            38.8940974
        ],
        "longitude":[
            -77.02762159999999
        ]
    },
    "476194185":{
        "latitude":[
            38.804835499999996
        ],
        "longitude":[
            -77.0469214
        ]
    }
        ....
</code>```

Title: User Trajectory Creation with Python

Body:
I'm in need of some assistance creating trajectories in python. I have a CSV with user_ids, timestamp, latitude, and longitude. I would like to create a 5th column in my file (or write to new file all together) containing the trajectory of each user_id, which requires grouping the coordinates by their user, and sorting (ascending) by the timestamp. I was able to accomplish in PostGIS, but the results are geometries and what I need are strings of coordinates. I have tried using collections and itertools, as well as Pandas, to group and sort, but I'm struggling.

For reference, here is a few lines of my data:

user_id, timestamp, latitude, longitude
478134225, 3/12/2017 9:04, 38.8940974, -77.0276216
478103585, 3/12/2017 9:04, 38.882584, -77.1124701
478073193, 3/12/2017 9:07, 39.00027849, -77.09480086
476194185, 3/12/2017 9:14, 38.8048355, -77.0469214
476162349, 3/12/2017 9:16, 38.8940974, -77.0276216
478073193, 3/12/2017 9:05, 38.8549, -76.8752
477899275, 3/12/2017 9:08, 38.90181532, -77.03733586
477452890, 3/12/2017 9:08, 38.96117237, -76.95561893
478073193, 3/12/2017 9:05, 38.7188716, -77.1542684

As you can see, there are users with multiple entries, so I need to group by them and order the coordinates by time. E.g. something similar to below

478073193 (38.8549,-76.8752)(38.7188716,-77.1542684)(39.00027849,-77.09480086)

I have well over 150k points, so doing by hand like I did above isn't an option.

Body:
This should do it. It uses the popular pandas package and numpy.

import pandas as pd
import numpy as np

# First we import the data
data = pd.read_csv('data.csv', delimiter=', ')

# Now get a list of unique user_id values
uniqueIds = np.unique(data['user_id'].values)

# Now just get the ordered (by timestamp) coordinates for each user_id
output = [[id,data.loc[data['user_id']==id].sort_values(by='timestamp')[['latitude','longitude']].values.tolist()] for id in uniqueIds]

The output is a list with each element of the form [id, list_of_paired_coordinates], e.g.:

[[476162349, [[38.8940974, -77.02762159999999]]],
 [478073193, [[38.8549, -76.8752],
              [38.7188716, -77.1542684],
              [39.00027849, -77.09480086]]],
 [478103585, [[38.882584, -77.11247009999998]]],
 [478134225, [[38.8940974, -77.02762159999999]]]]

Edit

If you'd like to save the output in JSON format you could do something like:

import json

# Now turn our array into a dict {id:coordinates}
outputDict = {}
for i in output:
    outputDict[i[0]]=i[1]

with open('output.json', 'w') as f:
    json.dump(outputDict, f, sort_keys=True, indent=4, ensure_ascii=False, separators=(',',':'))

Depending on how you'd like the output file formatted you may need to modify the structure of outputDict a little bit (let me know if this is the case). Right now the JSON file looks like:

{
    "476162349":[
        [
            38.8940974,
            -77.02762159999999
        ]
    ],
    "476194185":[
        [
            38.804835499999996,
            -77.0469214
        ]
    ....

Edit 2

If you want to format the output JSON file you can add labels to the values stored in the dict:

outputDict = {}
for i in output:
    coords={}
    latList=[]
    longList=[]
    for j in i[1]:
    latList.append(j[0])
    longList.append(j[1])
    coords["latitude"]=latList
    coords["longitude"]=longList
    outputDict[i[0]]=coords

The output JSON file would look this this:

{
    "476162349":{
        "latitude":[
            38.8940974
        ],
        "longitude":[
            -77.02762159999999
        ]
    },
    "476194185":{
        "latitude":[
            38.804835499999996
        ],
        "longitude":[
            -77.0469214
        ]
    }
        ....


问:
jQuery UI " $("#datepicker").datepicker is not a function"
When i use DatePicker, jQuery's UI plugin, in an existing .aspx page I get errors that:

```<code>$("#datepicker").datepicker is not a function
</code>```

However, when I copy and paste the same code that creates and uses the datePicker to an HTML file that's also in the same directory as the aspx page, it works flawlessly. This leads me to assume that there are some JS files in the aspx page that's preventing the datePicker or maybe jQuery's UI JS files to load properly.

Can anyone confirm my beliefs or provide any tips on finding the culprit that's interfering with jQuery's UI plugins?

答: I struggled with a similar problem for hours. It then turned out that jQuery was included twice, once by the program that I was adding a jQuery function to and once by our in-house debugger.</p>

Body:
When i use DatePicker, jQuery's UI plugin, in an existing .aspx page I get errors that:

$("#datepicker").datepicker is not a function

However, when I copy and paste the same code that creates and uses the datePicker to an HTML file that's also in the same directory as the aspx page, it works flawlessly. This leads me to assume that there are some JS files in the aspx page that's preventing the datePicker or maybe jQuery's UI JS files to load properly.

Can anyone confirm my beliefs or provide any tips on finding the culprit that's interfering with jQuery's UI plugins?