问:
Auto scroll to search input field and do not show old search options on mobile
So I have a search input field on my website.

```<code> <input type="search" id="searchfield">
</code>```

When I click on it on mobile(Chrome browser) the keyboard appears. So I scroll up to make it surely visible.

```<code>$('input').on('focus', function () {
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        document.body.scrollTop = this.getBoundingClientRect().top - screen.height / 4;
    }
});
</code>```

But it can show the old inputs for the search field in a menu and it makes a scrolldown about a half page and hides the kinda whole page behind it.

It looks like this

I hope you can help me. :)

答:
You only have to turn off the autocomplete attribute.

<input type="search" id="searchfield" autocomplete="off"/>

Body:
So I have a search input field on my website.

 <input type="search" id="searchfield">

When I click on it on mobile(Chrome browser) the keyboard appears. So I scroll up to make it surely visible.

$('input').on('focus', function () {
    if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
        document.body.scrollTop = this.getBoundingClientRect().top - screen.height / 4;
    }
});

But it can show the old inputs for the search field in a menu and it makes a scrolldown about a half page and hides the kinda whole page behind it.

It looks like this

I hope you can help me. :)


来源: stackexchange

问:
python 3.6 put number is str
```<code>def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0
</code>```

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

答:
In python, to change the type of anything, the only thing you have to do is wrap that in str(), int(), float()... or whatever type you want to change it to.

more details: http://usingpython.com/python-casting/

edit: sorry, didn't realize the recursive problem, still, I don't see why you can't just change the type after the function returns, seems the easiest thing to do.

if you insist though:

```<code>def binary(n):
  if int(n)>0:
    return str( int(binary(str(int(n)//2)))*10 + (int(n)%2))

  else:
    return str(0)
</code>```

ContentLicense: CC BY-SA 3.0

Title: python 3.6 put number is str

Body:
def binary(n):
    if n>0:
        return binary(n//2)*10 + (n%2)
    else:
        return 0

The answer is 10000000 but it have to be "10000000". How can I put str on the answer?

Body:
In python, to change the type of anything, the only thing you have to do is wrap that in str(), int(), float()... or whatever type you want to change it to.

more details: http://usingpython.com/python-casting/

edit: sorry, didn't realize the recursive problem, still, I don't see why you can't just change the type after the function returns, seems the easiest thing to do.

if you insist though:

def binary(n):
  if int(n)>0:
    return str( int(binary(str(int(n)//2)))*10 + (int(n)%2))

  else:
    return str(0)


问:
User entity gets incorrectly updated when i try to update another entity
I am trying to create a post on symfony (3.3) but I am having a problem and I dont know why,
Just if you are ROLE_ADMIN you can create a post, well the problem is that when I do symfony say

```<code>An exception occurred while executing 'UPDATE login SET password = ? WHERE id = ?' with params [null, 1]:
</code>```

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'password' cannot be null

and I am not trying to update nothing for my entity user
My entities are
User (id,password,email,token,role,active) is my user provider
Usuario(name,last_name,created_date,social_login,User ->here is the reference to the table user MenyToOne  )
Post (title,content,shor_content,etc and Usuario,(ManyToOne))
I dont know if this can help but i dont know why when i try to create a post i get this error,
Any idea?

答:
Hey i think i know what you meant. Had same issue second ago. The answer is to flush just post</p>

```<code>$user = $this->tokenStorage->getToken()->getUser();
$post->setUser($user);
$this->em->persist($post);
$this->em->flush($post); // make sure you put $post as parameter
</code>```

Body:
I am trying to create a post on symfony (3.3) but I am having a problem and I dont know why,
Just if you are ROLE_ADMIN you can create a post, well the problem is that when I do symfony say

An exception occurred while executing 'UPDATE login SET password = ? WHERE id = ?' with params [null, 1]:

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'password' cannot be null

and I am not trying to update nothing for my entity user
My entities are
User (id,password,email,token,role,active) is my user provider
Usuario(name,last_name,created_date,social_login,User ->here is the reference to the table user MenyToOne  )
Post (title,content,shor_content,etc and Usuario,(ManyToOne))
I dont know if this can help but i dont know why when i try to create a post i get this error,
Any idea?

Body:
Hey i think i know what you meant. Had same issue second ago. The answer is to flush just post

$user = $this->tokenStorage->getToken()->getUser();
$post->setUser($user);
$this->em->persist($post);
$this->em->flush($post); // make sure you put $post as parameter


问:
How do I prevent the enter key from closing my QDialog (Qt 4.8.1)
I have a QDialog with a QDialogButtonBox. The OK and Cancel buttons are active. Occasionally I disable or hide the OK button based on the state of my dialog. It seems, no matter what I do, the Enter key always activates the OK button. I really DON'T want this to happen. I have tried:

Setting default and autoDefault properties to false every time I show/hide/enable/disable/whatever the button

installing an event filter on the OK button to intercept key events (pressed and released) for return, enter and space

Setting the focus policy on the button to NoFocus

And with all combinations of those things above, the Enter key still accepts the dialog. Does anyone have any clue how to block this? It seems like I should be able to block something as simple as this?

答:
To avoid "OK" button or "Enter" key from closing dialog:
in the ui xml file, remove the connect/slot for accept/reject. Then, in your code , emmit accept() when and as needed;

example from ui file which connects accept() slot:

```<code> <connections>
  <connection>

   <sender>products_ButtonBox</sender>

    <signal>accepted()</signal>

     <receiver>Products_Dialog</receiver>
      <slot>accept()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>248</x>
         <y>254</y>
        </hint>
        <hint type="destinationlabel">
         <x>157</x>
         <y>274</y>
        </hint>e
       </hints>
      </connection>
</code>```

Body:
To avoid "OK" button or "Enter" key from closing dialog:
in the ui xml file, remove the connect/slot for accept/reject. Then, in your code , emmit accept() when and as needed;

example from ui file which connects accept() slot:

 <connections>
  <connection>

   <sender>products_ButtonBox</sender>

    <signal>accepted()</signal>

     <receiver>Products_Dialog</receiver>
      <slot>accept()</slot>
       <hints>
        <hint type="sourcelabel">
         <x>248</x>
         <y>254</y>
        </hint>
        <hint type="destinationlabel">
         <x>157</x>
         <y>274</y>
        </hint>e
       </hints>
      </connection>


问:
Laravel Passport tokensExpireIn seems not working
i'm using Larave 5.4 passport to create SPA application. However, i was able to make authentication work. but access token are always short-lived tokens with 600s expiration time.

i could not increase expiration time with:

```<code>Passport::tokensExpireIn(Carbon::now()->addDays(15));

Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));
</code>```

it have no effect at all.

any help? thanks in advance.

答:
I have the same issue before for my application, I spent two days try to find what is the problem, The best solution that I came up with is to change the expire date directly in the PassportServiceProvider

Go to vendor/laravel/passport/src/PassportServiceProvider.php line 108

```<code>new PersonalAccessGrant, new DateInterval('P1Y')
</code>```

for example to set the expire date to one week

```<code>new PersonalAccessGrant, new DateInterval('P1W')
</code>```

I know this is a bad solution for fixing the issue, recently I have found the same issue on Laravel Git repo

https://github.com/laravel/passport/issues/47

Body:
i'm using Larave 5.4 passport to create SPA application. However, i was able to make authentication work. but access token are always short-lived tokens with 600s expiration time.

i could not increase expiration time with:

Passport::tokensExpireIn(Carbon::now()->addDays(15));

Passport::refreshTokensExpireIn(Carbon::now()->addDays(30));

it have no effect at all.

any help? thanks in advance.

Body:
I have the same issue before for my application, I spent two days try to find what is the problem, The best solution that I came up with is to change the expire date directly in the PassportServiceProvider

Go to vendor/laravel/passport/src/PassportServiceProvider.php line 108

new PersonalAccessGrant, new DateInterval('P1Y')

for example to set the expire date to one week

new PersonalAccessGrant, new DateInterval('P1W')

I know this is a bad solution for fixing the issue, recently I have found the same issue on Laravel Git repo

https://github.com/laravel/passport/issues/47


问:
How to test graphical output of functions?
I am wondering how to test functions that produce graphics. I have a simple
plotting function img:

```<code>img <- function() {
  plot(1:10)
}
</code>```

In my package I like to create a unit test for this function using testthat.
Because plot and its friends in base graphics just return NULL a simple
expect_identical is not working:

```<code>library("testthat")

## example for a successful test
expect_identical(plot(1:10), img()) ## equal (as expected)

## example for a test failure
expect_identical(plot(1:10, col="red"), img()) ## DOES NOT FAIL!
# (because both return NULL)
</code>```

First I thought about plotting into a file and compare the md5 checksums to
ensure that the output of the functions is equal:

```<code>md5plot <- function(expr) {
  file <- tempfile(fileext=".pdf")
  on.exit(unlink(file))
  pdf(file)
  expr
  dev.off()
  unname(tools::md5sum(file))
}

## example for a successful test
expect_identical(md5plot(img()),
                 md5plot(plot(1:10))) ## equal (as expected)

## example for a test failure
expect_identical(md5plot(img()),
                 md5plot(plot(1:10, col="red"))) ## not equal (as expected)
</code>```

That works well on Linux but not on Windows. Surprisingly
md5plot(plot(1:10)) results in a new md5sum at each call.
Aside this problem I need to create a lot of temporary files.

Next I used recordPlot (first creating a null-device, call the plotting
function and record its output). This works as expected:

```<code>recPlot <- function(expr) {
  pdf(NULL)
  on.exit(dev.off())
  dev.control(displaylist="enable")
  expr
  recordPlot()
}

## example for a successful test
expect_identical(recPlot(plot(1:10)),
                 recPlot(img())) ## equal (as expected)

## example for a test failure
expect_identical(recPlot(plot(1:10, col="red")),
                 recPlot(img())) ## not equal (as expected)
</code>```

Does anybody know a better way to test the graphical output of functions?

EDIT: regarding the points @josilber asks in his comments.

While the recordPlot approach works well you have to rewrite the whole plotting function in the unit test. That becomes complicated for complex plotting functions. It would be nice to have an approach that allows to store a file (*.RData or *.pdf, ...) which contains an image against you could compare in future tests. The md5sum approach isn't working because the md5sums differ on different platforms. Via recordPlot you could create an *.RData file but you could not rely on its format (from the recordPlot manual page):

The format of recorded plots may change between R versions.
       Recorded plots can not be used as a permanent storage format for
       R plots.

Maybe it would be possible to store an image file (*.png, *.bmp, etc), import it and compare it pixel by pixel ...

EDIT2: The following code illustrate the desired reference file approach using svg as output. First the needed helper functions:

```<code>## plot to svg and return file contant as character
plot_image <- function(expr) {
  file <- tempfile(fileext=".svg")
  on.exit(unlink(file))
  svg(file)
  expr
  dev.off()
  readLines(file)
}

## the IDs differ at each `svg` call, that's why we simple remove them
ignore_svg_id <- function(lines) {
  gsub(pattern = "(xlink:href|id)=\"#?([a-z0-9]+)-?(?<![0-9])[0-9]+\"",
       replacement = "\\1=\"\\2\"", x = lines, perl = TRUE)
}

## compare svg character vs reference
expect_image_equal <- function(object, expected, ...) {
  stopifnot(is.character(expected) && file.exists(expected))
  expect_equal(ignore_svg_id(plot_image(object)),
               ignore_svg_id(readLines(expected)), ...)
}

## create reference image
create_reference_image <- function(expr, file) {
  svg(file)
  expr
  dev.off()
}
</code>```

A test would be:

```<code>create_reference_image(img(), "reference.svg")

## create tests
library("testthat")

expect_image_equal(img(), "reference.svg") ## equal (as expected)
expect_image_equal(plot(1:10, col="red"), "reference.svg") ## not equal (as expected)
</code>```

Sadly this is not working across different platforms. The order (and the names)
of the svg elements completely differs on Linux and Windows.

Similar problems exist for png, jpeg and recordPlot. The resulting files
differ on all platforms.

Currently the only working solution is the recPlot approach above. But therefore
I need to rewrite the whole plotting functions in my unit tests.

P.S.:
I am completley confused about the different md5sums on Windows. It seems they depending on the creation time of the temporary files:

```<code># on Windows
table(sapply(1:100, function(x)md5plot(plot(1:10))))
#4693c8bcf6b6cb78ce1fc7ca41831353 51e8845fead596c86a3f0ca36495eacb
#                              40                               60
</code>```

答: It's worth noting that the vdiffr package also supports comparing plots. A nice feature is that it integrates with the testthat package -- it's actually used for testing in ggplot2 -- and it has an add-in for RStudio to help manage your testsuite.</p>

Body:
I am wondering how to test functions that produce graphics. I have a simple
plotting function img:

img <- function() {
  plot(1:10)
}

In my package I like to create a unit test for this function using testthat.
Because plot and its friends in base graphics just return NULL a simple
expect_identical is not working:

library("testthat")

## example for a successful test
expect_identical(plot(1:10), img()) ## equal (as expected)

## example for a test failure
expect_identical(plot(1:10, col="red"), img()) ## DOES NOT FAIL!
# (because both return NULL)

First I thought about plotting into a file and compare the md5 checksums to
ensure that the output of the functions is equal:

md5plot <- function(expr) {
  file <- tempfile(fileext=".pdf")
  on.exit(unlink(file))
  pdf(file)
  expr
  dev.off()
  unname(tools::md5sum(file))
}

## example for a successful test
expect_identical(md5plot(img()),
                 md5plot(plot(1:10))) ## equal (as expected)

## example for a test failure
expect_identical(md5plot(img()),
                 md5plot(plot(1:10, col="red"))) ## not equal (as expected)

That works well on Linux but not on Windows. Surprisingly
md5plot(plot(1:10)) results in a new md5sum at each call.
Aside this problem I need to create a lot of temporary files.

Next I used recordPlot (first creating a null-device, call the plotting
function and record its output). This works as expected:

recPlot <- function(expr) {
  pdf(NULL)
  on.exit(dev.off())
  dev.control(displaylist="enable")
  expr
  recordPlot()
}

## example for a successful test
expect_identical(recPlot(plot(1:10)),
                 recPlot(img())) ## equal (as expected)

## example for a test failure
expect_identical(recPlot(plot(1:10, col="red")),
                 recPlot(img())) ## not equal (as expected)

Does anybody know a better way to test the graphical output of functions?

EDIT: regarding the points @josilber asks in his comments.

While the recordPlot approach works well you have to rewrite the whole plotting function in the unit test. That becomes complicated for complex plotting functions. It would be nice to have an approach that allows to store a file (*.RData or *.pdf, ...) which contains an image against you could compare in future tests. The md5sum approach isn't working because the md5sums differ on different platforms. Via recordPlot you could create an *.RData file but you could not rely on its format (from the recordPlot manual page):

The format of recorded plots may change between R versions.
       Recorded plots can not be used as a permanent storage format for
       R plots.

Maybe it would be possible to store an image file (*.png, *.bmp, etc), import it and compare it pixel by pixel ...

EDIT2: The following code illustrate the desired reference file approach using svg as output. First the needed helper functions:

## plot to svg and return file contant as character
plot_image <- function(expr) {
  file <- tempfile(fileext=".svg")
  on.exit(unlink(file))
  svg(file)
  expr
  dev.off()
  readLines(file)
}

## the IDs differ at each `svg` call, that's why we simple remove them
ignore_svg_id <- function(lines) {
  gsub(pattern = "(xlink:href|id)=\"#?([a-z0-9]+)-?(?<![0-9])[0-9]+\"",
       replacement = "\\1=\"\\2\"", x = lines, perl = TRUE)
}

## compare svg character vs reference
expect_image_equal <- function(object, expected, ...) {
  stopifnot(is.character(expected) && file.exists(expected))
  expect_equal(ignore_svg_id(plot_image(object)),
               ignore_svg_id(readLines(expected)), ...)
}

## create reference image
create_reference_image <- function(expr, file) {
  svg(file)
  expr
  dev.off()
}

A test would be:

create_reference_image(img(), "reference.svg")

## create tests
library("testthat")

expect_image_equal(img(), "reference.svg") ## equal (as expected)
expect_image_equal(plot(1:10, col="red"), "reference.svg") ## not equal (as expected)

Sadly this is not working across different platforms. The order (and the names)
of the svg elements completely differs on Linux and Windows.

Similar problems exist for png, jpeg and recordPlot. The resulting files
differ on all platforms.

Currently the only working solution is the recPlot approach above. But therefore
I need to rewrite the whole plotting functions in my unit tests.

P.S.:
I am completley confused about the different md5sums on Windows. It seems they depending on the creation time of the temporary files:

# on Windows
table(sapply(1:100, function(x)md5plot(plot(1:10))))
#4693c8bcf6b6cb78ce1fc7ca41831353 51e8845fead596c86a3f0ca36495eacb
#                              40                               60


问:
Sort Objects From a File
(At time of posting, I do not have access to code, will add later)

I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.

When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.

This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.

So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you

```<code>static void employeeSort(Employee[] emply, int size)
{
    int i;
    Employee temp;

    boolean flag = true;

        while(flag)
        {
            flag = false;
            for(i = 0; i < size; i++)
            {

                if (emply[i].getName().compareTo(emply[i+1].getName())>0)
                   {
                       System.out.println(emply[i].getName());
                       temp = emply[i];
                       emply[i] = emply[i+1];
                       emply[i+1] = temp;
                       flag = true;
                   }

            }
        }

}
</code>```

On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.

```<code>public class Employee implements Serializable
{
int     prefHours;
String  name;
String  avail;

Employee( String nam, int hours, String aval )
{
    name = nam;
    prefHours = hours;
    avail = aval;
}

void prnEmpl()
{
    System.out.print("Name: " + name);
    System.out.println();
    System.out.print("Prefered hours: " + prefHours);
    System.out.println();
    System.out.print("Availability: " + avail);
    System.out.println();
}

String getName()
{
    return name;
}

String getAvail()
{
    return avail;
}
</code>```

}

答: Without your code it is hard to figure out what's the problem. As far as I understand I think you should use java.util.PriorityQueue instead of Array.

Title: Sort Objects From a File

Body:
(At time of posting, I do not have access to code, will add later)

I have an array of Employee objects, which hold a name, availability, and preferred hours. And I sort the objects by Alphabetical order, according to the employees name.

When the program starts, it checks the files, and if they are empty, it asks you how many employees, and then you proceed to fill in the data. And it sorts properly A-Z.

This issue comes that when I try to add a new employee, after resizing the array, it adds it to the end, even though the sort completes.

So it sorts the first time, but not again after re running the program. I will post the code when I get home, but wanted to see if anyone had any answers in the mean time. Thank you

static void employeeSort(Employee[] emply, int size)
{
    int i;
    Employee temp;

    boolean flag = true;

        while(flag)
        {
            flag = false;
            for(i = 0; i < size; i++)
            {

                if (emply[i].getName().compareTo(emply[i+1].getName())>0)
                   {
                       System.out.println(emply[i].getName());
                       temp = emply[i];
                       emply[i] = emply[i+1];
                       emply[i+1] = temp;
                       flag = true;
                   }

            }
        }

}

On the first run through, it sorts everything correctly, but once the array is read from a file, the program terminates in the sort. I tried implementing the priority queue, but i needed to make the Class comparable, and its already implemented Serializable.

public class Employee implements Serializable
{
int     prefHours;
String  name;
String  avail;

Employee( String nam, int hours, String aval )
{
    name = nam;
    prefHours = hours;
    avail = aval;
}

void prnEmpl()
{
    System.out.print("Name: " + name);
    System.out.println();
    System.out.print("Prefered hours: " + prefHours);
    System.out.println();
    System.out.print("Availability: " + avail);
    System.out.println();
}

String getName()
{
    return name;
}

String getAvail()
{
    return avail;
}

}


问:
maxlength ignored for input type="number" in Chrome
The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

```<code><input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>
</code>```

答:
I once got into the same problem and found this solution with respect to my needs.
It may help Some one.

```<code><input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>
</code>```

Happy Coding :)

Body:
The maxlength attribute is not working with <input type="number">. This happens only in Chrome.

<input type="number" class="test_css"  maxlength="4"  id="flight_number" name="number"/>

Body:
I once got into the same problem and found this solution with respect to my needs.
It may help Some one.

<input type="number" placeholder="Enter 4 Digits" max="9999" min="0"
onKeyDown="if(this.value.length==4 && event.keyCode>47 && event.keyCode < 58)return false;"
/>

Happy Coding :)


问:
Node.js quick file server (static files over HTTP)
Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

```<code>D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg
</code>```

Then starting in D:\Folder\ node node-file-server.js
I could access file via

```<code>http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg
</code>```

Why is my node static file server dropping requests?
reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related:
Basic static file server in NodeJS

答:
Here is my one-file/lightweight node.js static file web-server pet project with no-dependency that I believe is a quick and rich tool which its use is as easy as issuing this command on your Linux/Unix/macOS terminal (or termux on Android) when node.js (or nodejs-legacy on Debian/Ubuntu) is installed:

```<code>curl pad.js.org | node
</code>```

(different commands exist for Windows users on the documentation)

It supports different things that I believe can be found useful,

Hierarchical directory index creation/serving

With sort capability on the different criteria

Upload from browser by [multi-file] drag-and-drop and file/text-only copy-paste and system clipboard screen-shot paste on Chrome, Firefox and other browsers may with some limitations (which can be turned off by command line options it provides)

Folder/note-creation/upload button

Serving correct MIMEs for well known file types (with possibility for disabling that)

Possibility of installation as a npm package and local tool or, one-linear installation as a permanent service with Docker

HTTP 206 file serving (multipart file transfer) for faster transfers

Uploads from terminal and browser console (in fact it was originally intended to be a file-system proxy for JS console of browsers on other pages/domains)

CORS download/uploads (which also can be turned off)

Easy HTTPS integration

Lightweight command line options for achieving better secure serving with it:

With my patch on node.js 8, you can have access to the options without first installation: curl pad.js.org | node - -h

Or first install it as a system-global npm package by [sudo] npm install -g pad.js and then use its installed version to have access to its options: pad -h

Or use the provided Docker image which uses relatively secure options by default. [sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js

The features described above are mostly documented on the main page of the tool http://pad.js.org which by some nice trick I used is also the place the tool source itself is also served from!

The tool source is on GitHub which welcomes your feedback, feature requests and ⭐s!

Body:
Is there Node.js ready-to-use tool (installed with npm), that would help me expose folder content as file server over HTTP.

Example, if I have

D:\Folder\file.zip
D:\Folder\file2.html
D:\Folder\folder\file-in-folder.jpg

Then starting in D:\Folder\ node node-file-server.js
I could access file via

http://hostname/file.zip
http://hostname/file2.html
http://hostname/folder/file-in-folder.jpg

Why is my node static file server dropping requests?
reference some mystical

standard node.js static file server

If there's no such tool, what framework should I use?

Related:
Basic static file server in NodeJS

Body:
Here is my one-file/lightweight node.js static file web-server pet project with no-dependency that I believe is a quick and rich tool which its use is as easy as issuing this command on your Linux/Unix/macOS terminal (or termux on Android) when node.js (or nodejs-legacy on Debian/Ubuntu) is installed:

curl pad.js.org | node

(different commands exist for Windows users on the documentation)

It supports different things that I believe can be found useful,

Hierarchical directory index creation/serving

With sort capability on the different criteria

Upload from browser by [multi-file] drag-and-drop and file/text-only copy-paste and system clipboard screen-shot paste on Chrome, Firefox and other browsers may with some limitations (which can be turned off by command line options it provides)

Folder/note-creation/upload button

Serving correct MIMEs for well known file types (with possibility for disabling that)

Possibility of installation as a npm package and local tool or, one-linear installation as a permanent service with Docker

HTTP 206 file serving (multipart file transfer) for faster transfers

Uploads from terminal and browser console (in fact it was originally intended to be a file-system proxy for JS console of browsers on other pages/domains)

CORS download/uploads (which also can be turned off)

Easy HTTPS integration

Lightweight command line options for achieving better secure serving with it:

With my patch on node.js 8, you can have access to the options without first installation: curl pad.js.org | node - -h

Or first install it as a system-global npm package by [sudo] npm install -g pad.js and then use its installed version to have access to its options: pad -h

Or use the provided Docker image which uses relatively secure options by default. [sudo] docker run --restart=always -v /files:/files --name pad.js -d -p 9090:9090 quay.io/ebraminio/pad.js

The features described above are mostly documented on the main page of the tool http://pad.js.org which by some nice trick I used is also the place the tool source itself is also served from!

The tool source is on GitHub which welcomes your feedback, feature requests and ⭐s!


问:
Why doesn't my selection sort algorithm do what it's supposed to (java)?
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

```<code>public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(c<A.length) {
            if(x>A[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}
</code>```

But I get a weird output:

```<code>0 0 0 0 0 2 2
</code>```

答:
```<code>public class Selectionsort {

    public static void main(String[] args) {
        int[] myArray = {9, 6, 1, 3, 0, 4, 2};

        for (int i = 0; i < myArray.length; i++) {

            int pos = findMIN(myArray, i);
            int element = myArray[pos];

            //swap
            int temp = myArray[i];
            myArray[i] = element;
            myArray[pos] = temp;

        }

        System.out.println(Arrays.toString(myArray));
    }

    //get the postion
    static int findMIN(int[] A, int c) {
        int x = A[c];
        int position = c;
        while (c < A.length) {
            if (x > A[c]) {
                x = A[c];
                position = c;
            }
            c++;
        }
        return position;
    }
}
</code>```

Body:
In the last hours I have tried to write the selection sort algorithm in Java without looking at finished code. I just read how the algorithm works (by words).

I won't copy paste the explanation but rather depict it (to check if I understood it):

-We have one unsorted array A and an empty array B (which has the same size as A)

-Now take the unsorted array A and find its smallest element. Smallest element found, now switch this element with the first element of the unsorted array A

-Put the first element (=smallest element of array A) into the array B

-Repeat till we are done with every element of A

I tried to code that in Java:

public class Selectionsort{

    public static void main(String[] args) {
        int[] myArray = {9,6,1,3,0,4,2};
        int[] B = new int[myArray.length];

        for(int i=0; i<myArray.length; i++) {
            B[i]=findMIN(myArray, i);
        }
    }

    static int findMIN(int[] A, int c) {
        int x = A[c];
        while(cA[c]) {
                x=A[c];
            }
            c++;
        }
        return x;
    }
}

But I get a weird output:

0 0 0 0 0 2 2


问:
TCA selectCheckBox - Output in fluid template
I use in TCA

```<code>        'uebersetzungen' => [
        'exclude' => true,
        'label' => 'LLL:EXT:maschinen/Resources/Private/Language/locallang_db.xlf:tx_maschinen_domain_model_maschine.uebersetzungen',
        'config' => [
            'type' => 'select',
            'renderType' => 'selectSingle',
            'items' => [
                ['6:1', 1],
                ['8:1', 2],
                ['11:1', 3],
                ['14:1', 4],
            ],
            'size' => 4,
            'maxitems' => 1,
            'eval' => ''
        ],
    ],
</code>```

to get the output in fluid template with

```<code>        <f:switch expression="{maschine.uebersetzungen}">
            <f:case value="1">6:1</f:case>
            <f:case value="2">8:1</f:case>
            <f:case value="3">11:1</f:case>
            <f:case value="4">14:1</f:case>
        </f:switch>
</code>```

Now I want to change the renderType to

```<code>'renderType' => 'selectSingleBox'
</code>```

but I have no idea how to get the several values.

I read TYPO3 TCA type select in FLUID?
but I'm not sure whether it's the same problem because I have a different syntax in TCA

答:
Thanks to @Paul Beck I found an answer for my problem.

I can use the solution posted here: TYPO3 TCA type select in FLUID?

But I had to change the line

```<code>protected $featuresDecoded;
</code>```

to

```<code>protected $featuresDecoded = [];
</code>```

Body:
I use in TCA

        'uebersetzungen' => [
        'exclude' => true,
        'label' => 'LLL:EXT:maschinen/Resources/Private/Language/locallang_db.xlf:tx_maschinen_domain_model_maschine.uebersetzungen',
        'config' => [
            'type' => 'select',
            'renderType' => 'selectSingle',
            'items' => [
                ['6:1', 1],
                ['8:1', 2],
                ['11:1', 3],
                ['14:1', 4],
            ],
            'size' => 4,
            'maxitems' => 1,
            'eval' => ''
        ],
    ],

to get the output in fluid template with

        <f:switch expression="{maschine.uebersetzungen}">
            <f:case value="1">6:1</f:case>
            <f:case value="2">8:1</f:case>
            <f:case value="3">11:1</f:case>
            <f:case value="4">14:1</f:case>
        </f:switch>

Now I want to change the renderType to

'renderType' => 'selectSingleBox'

but I have no idea how to get the several values.

I read TYPO3 TCA type select in FLUID?
but I'm not sure whether it's the same problem because I have a different syntax in TCA

Body:
Thanks to @Paul Beck I found an answer for my problem.

I can use the solution posted here: TYPO3 TCA type select in FLUID?

But I had to change the line

protected $featuresDecoded;

to

protected $featuresDecoded = [];


问:
Get all photo names from Firebase Storage
I have stored users photos in firebase with unique names using NSUUID. I can delete the images with a reference to their exact names one after the other.
My question is, I had like to get all the photos names for bulk deletion but how?</p>

答:
There is no public API in Firebase to list the files in Cloud Storage. So unless you already have a list of the names, you will have to either delete them from the Firebase console, or by using the Google Cloud Storage API.

See:

Delete folder with contents from Firebase Storage

FirebaseStorage: How to Delete Directory

How to get an array with all pictures?

How to search for a file in Firebase Storage?


问:
How to initialise a variable in Struct just once in Swift
This is my struct:

```<code>struct BookingDetailViewModel {

    private let bookingDetail:BookingDetail

    init(bookingDetail:BookingDetail) {
       self.bookingDetail = bookingDetail
    }

    var pricingCharts:[PricingChartViewModel] {

       let chartArray = bookingDetail.priceCharts

       var pricingChartArray:[PricingChartViewModel] = Array()
        for chart in chartArray {
           let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
           pricingChartArray.append(pricingChartViewModel)
        }
        return pricingChartArray
    }
}
</code>```

This is my viewModel and when I try to access the value of bookingDetailViewModel.pricingCharts,  the array inside is computed again and again when accessed from tableView datasource which doesn't make any sense to me because the pricingCharts will always remain the same.

Is there any possible way of computing this pricingCharts just once, so I can get a better performance?

Am I doing it correctly or should I follow some other pattern while setting the pricingCharts.

答:
What you have is a custom getter for your pricingCharts, and it behaves as it should - it recalculates (i.e. gets) its value every time it is needed.

What you need/want is a lazy var. Simply change your pricingCharts to :

```<code>lazy var pricingCharts:[PricingChartViewModel] = {

   let chartArray = self.bookingDetail.priceCharts

   var pricingChartArray:[PricingChartViewModel] = Array()
    for chart in chartArray {
       let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
       pricingChartArray.append(pricingChartViewModel)
    }
    return pricingChartArray
}()
</code>```

There were three changes made :

lazy keyword before var

= sign between type and block

() braces at the end of the block

As usually you can red more in the docs.

Body:
This is my struct:

struct BookingDetailViewModel {

    private let bookingDetail:BookingDetail

    init(bookingDetail:BookingDetail) {
       self.bookingDetail = bookingDetail
    }

    var pricingCharts:[PricingChartViewModel] {

       let chartArray = bookingDetail.priceCharts

       var pricingChartArray:[PricingChartViewModel] = Array()
        for chart in chartArray {
           let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
           pricingChartArray.append(pricingChartViewModel)
        }
        return pricingChartArray
    }
}

This is my viewModel and when I try to access the value of bookingDetailViewModel.pricingCharts,  the array inside is computed again and again when accessed from tableView datasource which doesn't make any sense to me because the pricingCharts will always remain the same.

Is there any possible way of computing this pricingCharts just once, so I can get a better performance?

Am I doing it correctly or should I follow some other pattern while setting the pricingCharts.

Body:
What you have is a custom getter for your pricingCharts, and it behaves as it should - it recalculates (i.e. gets) its value every time it is needed.

What you need/want is a lazy var. Simply change your pricingCharts to :

lazy var pricingCharts:[PricingChartViewModel] = {

   let chartArray = self.bookingDetail.priceCharts

   var pricingChartArray:[PricingChartViewModel] = Array()
    for chart in chartArray {
       let pricingChartViewModel = PricingChartViewModel(pricingChart: chart)
       pricingChartArray.append(pricingChartViewModel)
    }
    return pricingChartArray
}()

There were three changes made :

lazy keyword before var

= sign between type and block

() braces at the end of the block

As usually you can red more in the docs.


问:
Internationalization in the Spring project
I create internationalization for my application and am wondering if I can create several files to create translated messages. I do not think it's advisable, but I prefer to ask.

The thing is that I have a 'messages.properties' file where I have some text already

```<code>http s://pastebin.com/WdyE0Aaj
</code>```

And this is just the beginning. What if I will have dozens of pages and for each page I will have to declare here translation. After all, this file will go on in the hundreds and then thousands. Can it be somehow divided into more files?

答:
Of course you can (and probably should, to keep things maintainable).

The Spring-boot reference says:

```<code>spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.
</code>```

So, just add as many basenames as you want to your spring boot properties/yaml file, and they will all be agregated in a single MessageSource. Just make sure to avoid conflicts in the i18n property names.

Body:
I create internationalization for my application and am wondering if I can create several files to create translated messages. I do not think it's advisable, but I prefer to ask.

The thing is that I have a 'messages.properties' file where I have some text already

http s://pastebin.com/WdyE0Aaj

And this is just the beginning. What if I will have dozens of pages and for each page I will have to declare here translation. After all, this file will go on in the hundreds and then thousands. Can it be somehow divided into more files?

Body:
Of course you can (and probably should, to keep things maintainable).

The Spring-boot reference says:

spring.messages.basename=messages # Comma-separated list of basenames, each following the ResourceBundle convention.

So, just add as many basenames as you want to your spring boot properties/yaml file, and they will all be agregated in a single MessageSource. Just make sure to avoid conflicts in the i18n property names.


问:
getting warning with this link of code
```<code> -(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}
</code>```

<p>StringWithContentsOfURL is deprecated.... </p>

答:
If what made you confused is this "StringWithContentsOfURL is deprecated". A quick search in Apple's documentation shows that:

stringWithContentsOfURL:
Returns a string created by reading data from the file named by a given URL. (Deprecated in iOS 2.0. Use stringWithContentsOfURL:encoding:error: or stringWithContentsOfURL:usedEncoding:error: instead.)

An example would be:

```<code>stringWithContentsOfURL:yourURL encoding:NSUTF8StringEncoding error:NULL
</code>```

Title: getting warning with this link of code

Body:
 -(CLLocationCoordinate2D) addressLocation {

    NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps/geo?q=%@&output=csv",
   [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSString *locationString = [NSString stringWithContentsOfURL:[NSURL URLWithString:urlString]];
    NSLog(@"locationString %@",locationString);
    NSArray *listItems = [locationString componentsSeparatedByString:@","];

    double latitude = 0.0;
    double longitude = 0.0;

    if([listItems count] >= 4 && [[listItems objectAtIndex:0] isEqualToString:@"200"]) {
        latitude = [[listItems objectAtIndex:2] doubleValue];
        longitude = [[listItems objectAtIndex:3] doubleValue];
        NSLog(@"listItems %@",[listItems objectAtIndex:2]);
    }
    else {
        //Show error
    }
    CLLocationCoordinate2D location;
    location.latitude = latitude;
    location.longitude = longitude;

    return location;
}

StringWithContentsOfURL is deprecated....

Body:
If what made you confused is this "StringWithContentsOfURL is deprecated". A quick search in Apple's documentation shows that:

stringWithContentsOfURL:
Returns a string created by reading data from the file named by a given URL. (Deprecated in iOS 2.0. Use stringWithContentsOfURL:encoding:error: or stringWithContentsOfURL:usedEncoding:error: instead.)

An example would be:

stringWithContentsOfURL:yourURL encoding:NSUTF8StringEncoding error:NULL

ContentLicense: CC BY-SA 2.5


问:
RPart on PCA and centering data
I am using the results of PCA in a classification model.  All is well, but I am observing one artifact that has me puzzled.

Basically, when running the PCA model using prcomp(), if I set the "center=T" parameter, my classification accuracy suffers (0.83).  If I set "center=F", then my classification accuracy improves (0.90).

My question is: why?  I cannot think of any specific reason why centering data during prcomp() will cause subsequent prediction using it to suffer?

The code is below.  Any help in understanding this behavior will be much appreciated.  Thanks a lot in advance!

```<code>library(rpart)
library(caret)
library(rpart.plot)

data(iris)
index <- sample(1:nrow(iris), size=0.2*nrow(iris))
test <- iris[index, ]
train <- iris[-index, ]

# Build the model on raw data for a sanity check.
model <- rpart(Species~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, method="class", data=train)
pred <- predict(model, test[, 1:4], type="class")

# The confusion matrix below shows an accuracy of 0.90.
confusionMatrix(pred, test[, 5])

# Now do the PCA part for classification
pca <- prcomp(train[, 1:4], scale.=T, center=T) # <---- NOTE if we change this to F, we get better performance

# "Fit" the test data into Z-space based on the loadings (or rotations) from the training.
test.zspace <- predict(pca, newdata=test[, 1:4])
pca.train.df <- as.data.frame(pca$x)
pca.train.df$Species <- train[, 5]

# Build the model on the PCs.
pca.model <- rpart(Species ~ ., method="class", data=pca.train.df)

pca.test.df <- as.data.frame(test.zspace)
pca.test.df$Species <- test[, 5]
pca.pred <- predict(pca.model, pca.test.df[, 1:4], type="class")

# Confusion matrix below shows an accuracy of 0.83.  If I do NOT center the data during prcomp(), it will show 0.90.
confusionMatrix(pca.pred, test[, 5])
</code>```

答:
It is important that when you compare some results, you have an estimation of the variance of these two results in order to know if one is statistically significantly better than the other.
For example, if you perfom some bootstrap, you can see that these two results are not significantly different:

```<code>rep1 <- replicate(1e4, {
  ind <- sample(length(pred), replace = TRUE)
  mean(pca.pred[ind] == test[ind, 5])
})

rep2 <- replicate(1e4, {
  ind <- sample(length(pred), replace = TRUE)
  mean(pred[ind] == test[ind, 5])
})

boxplot(cbind(rep1, rep2))
</code>```

I think it is always a good idea to use centering AND scaling of your matrix before using PCA. You can find why in the first part of my blog post.

Title: RPart on PCA and centering data

Body:
I am using the results of PCA in a classification model.  All is well, but I am observing one artifact that has me puzzled.

Basically, when running the PCA model using prcomp(), if I set the "center=T" parameter, my classification accuracy suffers (0.83).  If I set "center=F", then my classification accuracy improves (0.90).

My question is: why?  I cannot think of any specific reason why centering data during prcomp() will cause subsequent prediction using it to suffer?

The code is below.  Any help in understanding this behavior will be much appreciated.  Thanks a lot in advance!

library(rpart)
library(caret)
library(rpart.plot)

data(iris)
index <- sample(1:nrow(iris), size=0.2*nrow(iris))
test <- iris[index, ]
train <- iris[-index, ]

# Build the model on raw data for a sanity check.
model <- rpart(Species~Sepal.Length+Sepal.Width+Petal.Length+Petal.Width, method="class", data=train)
pred <- predict(model, test[, 1:4], type="class")

# The confusion matrix below shows an accuracy of 0.90.
confusionMatrix(pred, test[, 5])

# Now do the PCA part for classification
pca <- prcomp(train[, 1:4], scale.=T, center=T) # <---- NOTE if we change this to F, we get better performance

# "Fit" the test data into Z-space based on the loadings (or rotations) from the training.
test.zspace <- predict(pca, newdata=test[, 1:4])
pca.train.df <- as.data.frame(pca$x)
pca.train.df$Species <- train[, 5]

# Build the model on the PCs.
pca.model <- rpart(Species ~ ., method="class", data=pca.train.df)

pca.test.df <- as.data.frame(test.zspace)
pca.test.df$Species <- test[, 5]
pca.pred <- predict(pca.model, pca.test.df[, 1:4], type="class")

# Confusion matrix below shows an accuracy of 0.83.  If I do NOT center the data during prcomp(), it will show 0.90.
confusionMatrix(pca.pred, test[, 5])

Body:
It is important that when you compare some results, you have an estimation of the variance of these two results in order to know if one is statistically significantly better than the other.
For example, if you perfom some bootstrap, you can see that these two results are not significantly different:

rep1 <- replicate(1e4, {
  ind <- sample(length(pred), replace = TRUE)
  mean(pca.pred[ind] == test[ind, 5])
})

rep2 <- replicate(1e4, {
  ind <- sample(length(pred), replace = TRUE)
  mean(pred[ind] == test[ind, 5])
})

boxplot(cbind(rep1, rep2))

I think it is always a good idea to use centering AND scaling of your matrix before using PCA. You can find why in the first part of my blog post.


问:
Why is SCNRenderer so out of sync / laggy when drawing into an OpenGL context?
I have a SceneKit SCNRenderer that I'm using to draw some objects into an existing OpenGL application.

renderer = SCNRenderer( context: EAGLContext.current(), options: nil )

I invoke it from the glkView method for each frame, after updating its camera transforms:

```<code>override func glkView(_ view: GLKView, drawIn rect: CGRect) {
    // render my OpenGL stuff
    ...
    // Render the SceneKit
    cameraNode.transform = SCNMatrix4Invert(SCNMatrix4FromGLKMatrix4(matrices.mvMatrix))
    cameraNode.camera!.projectionTransform = SCNMatrix4FromGLKMatrix4(matrices.cameraMatrix)
    SCNTransaction.flush() // <= This solved the problem!
    renderer.render(atTime: 0)
</code>```

My OpenGL app renders at 60fps by itself and if I only render the SceneKit as above it also renders fluidly.  But when I combine them what happens is the SceneKit seems to lag behind rendering maybe 1 fps.  In the following screencap (reduced to gif) the plane is being drawn by OpenGL and it tracks my finger perfectly, but the box drawn by SceneKit lags way behind.  If I comment out the plane drawing code the box tracks perfectly.

I'm afraid the answer is going to be to invert this and do my OpenGL drawing inside the SceneKit run loop.  Hoping there's some other path.

UPDATE: I can't post the animated gif but here's the link.

UPDATE 2: Adding the scene flush() call as suggested by Toyos solved the problem.

答: I'm not sure in what thread you are rendering but just in case you should flush your scene graph modification before rendering with [SCNTransaction flush].</p>

Body:
I have a SceneKit SCNRenderer that I'm using to draw some objects into an existing OpenGL application.

renderer = SCNRenderer( context: EAGLContext.current(), options: nil )

I invoke it from the glkView method for each frame, after updating its camera transforms:

override func glkView(_ view: GLKView, drawIn rect: CGRect) {
    // render my OpenGL stuff
    ...
    // Render the SceneKit
    cameraNode.transform = SCNMatrix4Invert(SCNMatrix4FromGLKMatrix4(matrices.mvMatrix))
    cameraNode.camera!.projectionTransform = SCNMatrix4FromGLKMatrix4(matrices.cameraMatrix)
    SCNTransaction.flush() // <= This solved the problem!
    renderer.render(atTime: 0)

My OpenGL app renders at 60fps by itself and if I only render the SceneKit as above it also renders fluidly.  But when I combine them what happens is the SceneKit seems to lag behind rendering maybe 1 fps.  In the following screencap (reduced to gif) the plane is being drawn by OpenGL and it tracks my finger perfectly, but the box drawn by SceneKit lags way behind.  If I comment out the plane drawing code the box tracks perfectly.

I'm afraid the answer is going to be to invert this and do my OpenGL drawing inside the SceneKit run loop.  Hoping there's some other path.

UPDATE: I can't post the animated gif but here's the link.

UPDATE 2: Adding the scene flush() call as suggested by Toyos solved the problem.


问:
How to create selector like jQuery with additional functions?
I am trying to understand  how to work jQuery and other libraries. I would like to know how to create a selector with this format:

```<code>$("#selector").get();
</code>```

By the moment, I am trying the next, but i don't know how to run internal functions (get(), set()):

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

    var jQuery = {
        get: function() {
            console.log("get() function!!");
            return this;
        },
        set: function() {
            console.log("set() function!!");
            return this;
        }
    };

    return function(el) {
        return document.querySelector(el);
    }
})();
</code>```

I have read something about modular pattern design in JavaScript, but I don't understand all.

答:
The way to make chainable functions, is to first and foremost create instances with the new keyword.

This can be done "automatically" by making sure the this value of the called function is an instance of itself, if not explicitly call it with new.

Then it's just a matter of returning the instance and using prototyped methods.

var $ = function(selector) {
  if (! (this instanceof $) ) {
    return new $(selector);
  }
  this.el = document.querySelectorAll(selector);
  return this;
}

$.prototype.css = function(prop, val) {
  this.el.forEach(function(element) {
    element.style[prop] = val;
  });

  return this;
}

$('#test').css('color', 'red').css('font-size', '30px')```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="test">test</div></code>```

Body:
I am trying to understand  how to work jQuery and other libraries. I would like to know how to create a selector with this format:

$("#selector").get();

By the moment, I am trying the next, but i don't know how to run internal functions (get(), set()):

var $ = (function() {

    var jQuery = {
        get: function() {
            console.log("get() function!!");
            return this;
        },
        set: function() {
            console.log("set() function!!");
            return this;
        }
    };

    return function(el) {
        return document.querySelector(el);
    }
})();

I have read something about modular pattern design in JavaScript, but I don't understand all.

Body:
The way to make chainable functions, is to first and foremost create instances with the new keyword.

This can be done "automatically" by making sure the this value of the called function is an instance of itself, if not explicitly call it with new.

Then it's just a matter of returning the instance and using prototyped methods.

var $ = function(selector) {
  if (! (this instanceof $) ) {
    return new $(selector);
  }
  this.el = document.querySelectorAll(selector);
  return this;
}

$.prototype.css = function(prop, val) {
  this.el.forEach(function(element) {
    element.style[prop] = val;
  });

  return this;
}

$('#test').css('color', 'red').css('font-size', '30px')

<div id="test">test</div>


问:
Create NEWS.md from github commits with RStudio
is there a proper way to create NOT by hand a NEWS file for a package in R/RStudio?

Is it ok if i find a way to use the description of commits from the github repo to create this file?

Thank you

答:
You have to interact with the GitHub API using R(REST API v3) to read the commits

You can use R Bindings for the Github v3 API
I'm not sure if it cover all API needed to read the commits (or you can deploy it)

You should take into account that you should standard all changes/bug fixes and version number to get meaningful commits in the NEWS file.

My advice Do it manually (by hand) :)


问:
React: Click on a component to change parents state
Pretty new to React, can't quite figure out how to fix this.
I want to click on a component (Project) and have this change the state of the parent, determining what is then rendered.

App.js, in the App component, has

```<code>constructor(props){
  super(props);
  this.state = {
    load: ''
  }
}

handleClick(e){
  this.setState({load: e.target.value});
  console.log("Clicked!");
  console.log(e);
  console.log(e.target.value);
}

display(load){
  if (load === 'bmi') {
    return <Bmi />
  }
  else return "";
}

render() {
    return (
      <div className="App">

      <div className="App-header">

        <h2>Projects</h2>

      </div>
      <div className="box">
        <Project projectName="BMI Calculator"
           projectDescription="A simple React program, using sliders to select weight and height to calculate BMI."
           imgAddress="https://cdn.vertex42.com/ExcelTemplates/Images/bmi-chart.gif"
           value="bmi"
           onClick={this.handleClick}/>

        <Project projectName="..."
           projectDescription="..."

        <Project projectName="Something Else"
           projectDescription="Describing that other thing that I did." />
      </div>
      <div className={this.state.item}>
        {this.display(this.state.item)}
      </div>

  </div>

);
}
</code>```

Project is called from Project.js, which has:

```<code>render(){
    return(
        <div className="third" value={this.props.value} onClick={this.props.onClick}>

            <h3>{this.props.projectName}</h3>

            <div className="container">

                <img src={this.props.imgAddress} className="image" />

                <div className="middle">

                    <div className="text">{this.props.projectDescription}</div>

                </div>

            </div>

        </div>
    )
}
</code>```

When I click on the first  the console shows:

```<code>clicked!
Proxy {dispatchConfig: Object, _targetInst: ReactDOMComponent, nativeEvent: MouseEvent, type: "click", target: img.image…}
undefined
</code>```

Because of the target: img.image shown in the console, I tried giving that element th same value, onClick properties as div.third, but that didn't work.
I then tried giving that to all the elements in the render of Project.js but that did not work either.

答:
You can use the props directly if you create an intermediate click handler in the child component:

App.js

```<code>handleClick (value) {
  console.log('clicked', value);
  this.setState({load: value});
}
</code>```

Project.js

```<code>_onClick = () => {
  this.props.onClick(this.props.value);
}

render() {
  return (
    <div className="third" onClick={this._onClick}>
      <h3>{this.props.projectName}</h3>
      <div className="container">
        <img src={this.props.imgAddress} className="image" />
        <div className="middle">
          <div className="text">{this.props.projectDescription}</div>
        </div>
      </div>
    </div>
  );
}
</code>```

Here _onClick uses the props directly instead of dealing with the event. You will need to use the property initializer syntax for es6 classes because es6 classes do not autobind: _onClick = () => {}

Body:
Pretty new to React, can't quite figure out how to fix this.
I want to click on a component (Project) and have this change the state of the parent, determining what is then rendered.

App.js, in the App component, has

constructor(props){
  super(props);
  this.state = {
    load: ''
  }
}

handleClick(e){
  this.setState({load: e.target.value});
  console.log("Clicked!");
  console.log(e);
  console.log(e.target.value);
}

display(load){
  if (load === 'bmi') {
    return <Bmi />
  }
  else return "";
}

render() {
    return (

Projects

        <Project projectName="BMI Calculator"
           projectDescription="A simple React program, using sliders to select weight and height to calculate BMI."
           imgAddress="https://cdn.vertex42.com/ExcelTemplates/Images/bmi-chart.gif"
           value="bmi"
           onClick={this.handleClick}/>

        <Project projectName="..."
           projectDescription="..."

        <Project projectName="Something Else"
           projectDescription="Describing that other thing that I did." />

        {this.display(this.state.item)}

);
}

Project is called from Project.js, which has:

render(){
    return(

{this.props.projectName}

{this.props.projectDescription}

    )
}

When I click on the first  the console shows:

clicked!
Proxy {dispatchConfig: Object, _targetInst: ReactDOMComponent, nativeEvent: MouseEvent, type: "click", target: img.image…}
undefined

Because of the target: img.image shown in the console, I tried giving that element th same value, onClick properties as div.third, but that didn't work.
I then tried giving that to all the elements in the render of Project.js but that did not work either.

Body:
You can use the props directly if you create an intermediate click handler in the child component:

App.js

handleClick (value) {
  console.log('clicked', value);
  this.setState({load: value});
}

Project.js

_onClick = () => {
  this.props.onClick(this.props.value);
}

render() {
  return (
    <div className="third" onClick={this._onClick}>
      <h3>{this.props.projectName}</h3>
      <div className="container">
        <img src={this.props.imgAddress} className="image" />
        <div className="middle">
          <div className="text">{this.props.projectDescription}</div>
        </div>
      </div>
    </div>
  );
}

Here _onClick uses the props directly instead of dealing with the event. You will need to use the property initializer syntax for es6 classes because es6 classes do not autobind: _onClick = () => {}


问:
Getting the class label using DynamicTimeWarping using Accord.NET
I'm developing a project in which I need to do gesture recognition.
After searching for a way to do this I came across dynamic time warping.
To try this idea, and since my project is in C#, I decided to try Accord.NET.
Before I tried this out in my project, I created a clean project and modified the example on Accord.NET's documentation, that can be found here:

http://accord-framework.net/docs/html/T_Accord_Statistics_Kernels_DynamicTimeWarping.htm

So, what I'm trying right now, is to train my algorithm with a set of learning data (composed of the gestures swipe right, swipe left and double tap) and then, use the same examples in the learning data to see if the algorithm is identifying the correct gesture. The values are just an exemple, not the real deal.

The documentation is not very clear on how to do this, since the Decide method used on the example only returns a boolean.
I've searched the documentation for a way to identify the correct class but to no avail.

The only thing I've found was the following line, but what it returns is an int value of 0 or 1, instead of a boolean:

var res1 = ((IClassifier)svm.ToMulticlass()).Decide(sequences[0]);

Can anyone point me in the right direction on how to correctly identify the gesture?
This is my first attempt at machine learning and Accord.NET, so this is all absolutelly new to me.
The example code can be found bellow.

```<code>namespace DynamicTimeWarpingExample
{
    public class Program
    {
        public static void Main(string[] args)
        {

            double[][][] sequences =
            {
                new double[][] // Swipe left
                {
                    new double[] { 1, 1, 1 },
                    new double[] { 1, 2, 1 },
                    new double[] { 1, 2, 2 },
                    new double[] { 2, 2, 2 },
                },

                new double[][] // Swipe right
                {
                    new double[] { 1, 10, 6 },
                    new double[] { 1, 5, 6 },
                    new double[] { 6, 7, 1 },
                },

                new double[][] // Double tap
                {
                    new double[] { 8, 2, 5 },
                    new double[] { 1, 50, 4 },
                }
            };

            int[] outputs =
            {
                    0,  // Swipe left
                    1,  // Swipe right
                    2  // Double tap
            };

            var smo = new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>()
            {
                Complexity = 1.5,

                Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
            };

            var svm = smo.Learn(sequences, outputs);

            bool[] predicted = svm.Decide(sequences);

            double error = new ZeroOneLoss(outputs).Loss(predicted); // error will be 0.0

            var res1 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[0]); // returns 0

            var res2 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[1]); // returns 1

            var res3 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[2]); // returns 1
        }
    }
}
</code>```

***************** New Version *****************

```<code>public static void Main(string[] args)
{
    double[][][] sequences =
    {
        new double[][] // Swipe left
        {
            new double[] { 1, 1, 1 },
            new double[] { 1, 2, 1 },
            new double[] { 1, 2, 2 },
            new double[] { 2, 2, 2 },
        },

        new double[][] // Swipe right
        {
            new double[] { 1, 10, 6 },
            new double[] { 1, 5, 6 },
            new double[] { 6, 7, 1 },
        },

        new double[][] // Double tap
        {
            new double[] { 8, 2, 5 },
            new double[] { 1, 50, 4 },
        }
    };

    int[] outputs =
    {
            0,  // Swipe left
            1,  // Swipe right
            2  // Double tap
    };

    var teacher = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
    {
        // Configure the learning algorithm to use SMO to train the
        //  underlying SVMs in each of the binary class subproblems.
        Learner = (param) => new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>
        {
            Complexity = 1.5,
            Kernel = new DynamicTimeWarping(alpha: 1, degree: 1),
            //UseKernelEstimation = true
        }
    };

    // Learn a machine
    var machine = teacher.Learn(sequences, outputs);

    // Create the multi-class learning algorithm for the machine
    var calibration = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
    {
        Model = machine, // We will start with an existing machine

        // Configure the learning algorithm to use Platt's calibration
        Learner = (param) => new ProbabilisticOutputCalibration<DynamicTimeWarping, double[][]>()
        {
            Model = param.Model // Start with an existing machine
        }
    };

    // Configure parallel execution options
    calibration.ParallelOptions.MaxDegreeOfParallelism = 1;

    // Learn a machine
    calibration.Learn(sequences, outputs);

    double decision1, decision2, decision3, decision4, decision5, decision6;

    var res1 = machine.Probability(sequences[0], out decision1); // decision 0 - Probability 0.78698604216159851 - Score 1
    var res2 = machine.Probability(sequences[1], out decision2); // decision 1 - Probability 0.67246889837875257 - Score 1
    var res3 = machine.Probability(sequences[2], out decision3); // decision 2 - Probability 0.78698604216159851 - Score 1

    var newGesture1 = new double[][]
    {
        new double[] { 1, 1, 1 },
        new double[] { 1, 2, 1 },
        new double[] { 1, 2, 2 },
        new double[] { 2, 2, 2 },
    };

    var newGesture2 = new double[][]
    {
        new double[] { 1, 10, 6 },
        new double[] { 1, 5, 6 },
        new double[] { 6, 7, 1 },
    };

    var newGesture3 = new double[][]
    {
        new double[] { 8, 2, 5 },
        new double[] { 1, 50, 4 },
    };

    var res5 = machine.Score(newGesture1, out decision5); // decision 0 - Probability 0.35577588944247057 - Score 0.051251948605637254
    var res6 = machine.Score(newGesture2, out decision6); // decision 1 - Probability 0.40733908994050544 - Score 0.19912250476931792
    var res4 = machine.Score(newGesture3, out decision4); // decision 2 - Probability 0.71853321355842836 - Score 0.816934034911964
}
</code>```

答:
The problem is that you are creating a binary classifier for a problem that actually involves multiple classes.

In your case, instead of doing:

```<code>var smo = new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>()
{
    Complexity = 1.5,
    Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
};

var svm = smo.Learn(sequences, outputs);
</code>```

You would want to wrap this binary learning problem into a multi-class learning using

```<code>// Create the multi-class learning algorithm for the machine
var teacher = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
{
    // Configure the learning algorithm to use SMO to train the
    //  underlying SVMs in each of the binary class subproblems.
    Learner = (param) => new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>
    {
        Complexity = 1.5,
        Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
    };
}

// Learn a  machine
var svm = teacher.Learn(inputs, outputs);
</code>```

Body:
I'm developing a project in which I need to do gesture recognition.
After searching for a way to do this I came across dynamic time warping.
To try this idea, and since my project is in C#, I decided to try Accord.NET.
Before I tried this out in my project, I created a clean project and modified the example on Accord.NET's documentation, that can be found here:

http://accord-framework.net/docs/html/T_Accord_Statistics_Kernels_DynamicTimeWarping.htm

So, what I'm trying right now, is to train my algorithm with a set of learning data (composed of the gestures swipe right, swipe left and double tap) and then, use the same examples in the learning data to see if the algorithm is identifying the correct gesture. The values are just an exemple, not the real deal.

The documentation is not very clear on how to do this, since the Decide method used on the example only returns a boolean.
I've searched the documentation for a way to identify the correct class but to no avail.

The only thing I've found was the following line, but what it returns is an int value of 0 or 1, instead of a boolean:

var res1 = ((IClassifier)svm.ToMulticlass()).Decide(sequences[0]);

Can anyone point me in the right direction on how to correctly identify the gesture?
This is my first attempt at machine learning and Accord.NET, so this is all absolutelly new to me.
The example code can be found bellow.

namespace DynamicTimeWarpingExample
{
    public class Program
    {
        public static void Main(string[] args)
        {

            double[][][] sequences =
            {
                new double[][] // Swipe left
                {
                    new double[] { 1, 1, 1 },
                    new double[] { 1, 2, 1 },
                    new double[] { 1, 2, 2 },
                    new double[] { 2, 2, 2 },
                },

                new double[][] // Swipe right
                {
                    new double[] { 1, 10, 6 },
                    new double[] { 1, 5, 6 },
                    new double[] { 6, 7, 1 },
                },

                new double[][] // Double tap
                {
                    new double[] { 8, 2, 5 },
                    new double[] { 1, 50, 4 },
                }
            };

            int[] outputs =
            {
                    0,  // Swipe left
                    1,  // Swipe right
                    2  // Double tap
            };

            var smo = new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>()
            {
                Complexity = 1.5,

                Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
            };

            var svm = smo.Learn(sequences, outputs);

            bool[] predicted = svm.Decide(sequences);

            double error = new ZeroOneLoss(outputs).Loss(predicted); // error will be 0.0

            var res1 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[0]); // returns 0

            var res2 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[1]); // returns 1

            var res3 = ((IClassifier<double[][], int>)svm.ToMulticlass()).Decide(sequences[2]); // returns 1
        }
    }
}

***************** New Version *****************

public static void Main(string[] args)
{
    double[][][] sequences =
    {
        new double[][] // Swipe left
        {
            new double[] { 1, 1, 1 },
            new double[] { 1, 2, 1 },
            new double[] { 1, 2, 2 },
            new double[] { 2, 2, 2 },
        },

        new double[][] // Swipe right
        {
            new double[] { 1, 10, 6 },
            new double[] { 1, 5, 6 },
            new double[] { 6, 7, 1 },
        },

        new double[][] // Double tap
        {
            new double[] { 8, 2, 5 },
            new double[] { 1, 50, 4 },
        }
    };

    int[] outputs =
    {
            0,  // Swipe left
            1,  // Swipe right
            2  // Double tap
    };

    var teacher = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
    {
        // Configure the learning algorithm to use SMO to train the
        //  underlying SVMs in each of the binary class subproblems.
        Learner = (param) => new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>
        {
            Complexity = 1.5,
            Kernel = new DynamicTimeWarping(alpha: 1, degree: 1),
            //UseKernelEstimation = true
        }
    };

    // Learn a machine
    var machine = teacher.Learn(sequences, outputs);

    // Create the multi-class learning algorithm for the machine
    var calibration = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
    {
        Model = machine, // We will start with an existing machine

        // Configure the learning algorithm to use Platt's calibration
        Learner = (param) => new ProbabilisticOutputCalibration<DynamicTimeWarping, double[][]>()
        {
            Model = param.Model // Start with an existing machine
        }
    };

    // Configure parallel execution options
    calibration.ParallelOptions.MaxDegreeOfParallelism = 1;

    // Learn a machine
    calibration.Learn(sequences, outputs);

    double decision1, decision2, decision3, decision4, decision5, decision6;

    var res1 = machine.Probability(sequences[0], out decision1); // decision 0 - Probability 0.78698604216159851 - Score 1
    var res2 = machine.Probability(sequences[1], out decision2); // decision 1 - Probability 0.67246889837875257 - Score 1
    var res3 = machine.Probability(sequences[2], out decision3); // decision 2 - Probability 0.78698604216159851 - Score 1

    var newGesture1 = new double[][]
    {
        new double[] { 1, 1, 1 },
        new double[] { 1, 2, 1 },
        new double[] { 1, 2, 2 },
        new double[] { 2, 2, 2 },
    };

    var newGesture2 = new double[][]
    {
        new double[] { 1, 10, 6 },
        new double[] { 1, 5, 6 },
        new double[] { 6, 7, 1 },
    };

    var newGesture3 = new double[][]
    {
        new double[] { 8, 2, 5 },
        new double[] { 1, 50, 4 },
    };

    var res5 = machine.Score(newGesture1, out decision5); // decision 0 - Probability 0.35577588944247057 - Score 0.051251948605637254
    var res6 = machine.Score(newGesture2, out decision6); // decision 1 - Probability 0.40733908994050544 - Score 0.19912250476931792
    var res4 = machine.Score(newGesture3, out decision4); // decision 2 - Probability 0.71853321355842836 - Score 0.816934034911964
}

Body:
The problem is that you are creating a binary classifier for a problem that actually involves multiple classes.

In your case, instead of doing:

var smo = new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>()
{
    Complexity = 1.5,
    Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
};

var svm = smo.Learn(sequences, outputs);

You would want to wrap this binary learning problem into a multi-class learning using

// Create the multi-class learning algorithm for the machine
var teacher = new MulticlassSupportVectorLearning<DynamicTimeWarping, double[][]>()
{
    // Configure the learning algorithm to use SMO to train the
    //  underlying SVMs in each of the binary class subproblems.
    Learner = (param) => new SequentialMinimalOptimization<DynamicTimeWarping, double[][]>
    {
        Complexity = 1.5,
        Kernel = new DynamicTimeWarping(alpha: 1, degree: 1)
    };
}

// Learn a  machine
var svm = teacher.Learn(inputs, outputs);


问:
How do I debug a C++ application in vscode using the Visual Studio 2017 Toolchain
I have read the guide, and as far as I understand it I should be able to set the type in launch.json to cppvsdbg but this shows up greyed out, I'm guessing that indicates some kind of error? Then when I actually click debug I get this error:

```<code>Unable to start debugging.
Launch options string provided by the project system is invalid.
Unable to determine path to debugger. Please specify the "MIDebuggerPath" option.
</code>```

However, when I actually go to set the MIDebuggerPath option to cdb.exe it tells me:

```<code>property MIDebuggerPath: is not allowed
</code>```

Here are the extensions I'm using in case there's any possible conflict going on here:

答:
Okay after some more digging I've at least figured out a work around. I was hitting this Debug button in the status bar at the bottom of the screen.

But if I switch to the debug mode by hitting the bug button on the left and then hit the green run arrow my debugger actually seems to work.

I still have no idea why these buttons do different things, or why the one on bottom doesn't work, but at least I can work around it for now. If anyone has any more insight on this I'd be happy to learn more.

Body:
I have read the guide, and as far as I understand it I should be able to set the type in launch.json to cppvsdbg but this shows up greyed out, I'm guessing that indicates some kind of error? Then when I actually click debug I get this error:

Unable to start debugging.
Launch options string provided by the project system is invalid.
Unable to determine path to debugger. Please specify the "MIDebuggerPath" option.

However, when I actually go to set the MIDebuggerPath option to cdb.exe it tells me:

property MIDebuggerPath: is not allowed

Here are the extensions I'm using in case there's any possible conflict going on here:


问:
Php : Get a record Function but Error : Undefined property
I have this problem when i try to build my function ! I need to build a function to get a record in database! And my error is Notice: Undefined property: mysqli_result::$fetch_assoc in database.php</p>

```<code>function db_get_row($sql){
    db_connect(); // Connect to Database
    global $connect; // Get Global Variable
    $row = array(); // Create array
    $result = $connect->query($sql); // Excute the query and return a record
    if($result->num_rows > 0){ // If record > 0 -> TRUE
        $row = $result->fetch_assoc; // I get that record into $row      HERE IS MY ERROR
    }
    return $row; // Return array
}
</code>```

答:
Based on :- http://php.net/manual/en/mysqli-result.fetch-assoc.php

```<code>$row = $result->fetch_assoc;
</code>```

Need to be

```<code>$row[] = $result->fetch_assoc(); //it's a function and you are assigning to array
</code>```

Body:
I have this problem when i try to build my function ! I need to build a function to get a record in database! And my error is Notice: Undefined property: mysqli_result::$fetch_assoc in database.php

function db_get_row($sql){
    db_connect(); // Connect to Database
    global $connect; // Get Global Variable
    $row = array(); // Create array
    $result = $connect->query($sql); // Excute the query and return a record
    if($result->num_rows > 0){ // If record > 0 -> TRUE
        $row = $result->fetch_assoc; // I get that record into $row      HERE IS MY ERROR
    }
    return $row; // Return array
}

Body:
Based on :- http://php.net/manual/en/mysqli-result.fetch-assoc.php

$row = $result->fetch_assoc;

Need to be

$row[] = $result->fetch_assoc(); //it's a function and you are assigning to array


问:
Check if an array is descending, ascending or not sorted?
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

```<code>        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }
</code>```

答:
Array.prototype.every passes its predicate an index, which you can use to get an element’s predecessor:

```<code>function isAscending(arr) {
    return arr.every(function (x, i) {
        return i === 0 || x >= arr[i - 1];
    });
}
</code>```

Here, we’re checking that every item (x) is greater than or equal to the item before it (arr[i - 1]) or has no item before it (i === 0).

Flip >= to <= for isDescending.

Body:
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }

Body:
Array.prototype.every passes its predicate an index, which you can use to get an element’s predecessor:

function isAscending(arr) {
    return arr.every(function (x, i) {
        return i === 0 || x >= arr[i - 1];
    });
}

Here, we’re checking that every item (x) is greater than or equal to the item before it (arr[i - 1]) or has no item before it (i === 0).

Flip >= to <= for isDescending.


问:
Implementing Disjoint Sets (Union Find) in C++
I am trying to implement Disjoint Sets for use in Kruskal's algorithm, but I am having trouble understanding exactly how it should be done and in particular, how to manage the forest of trees. After reading the Wikipedia description of Disjoint Sets and after reading the description in Introduction to Algorithms (Cormen et al) I have come up with the following:

```<code>    class DisjointSet
    {
    public:
        class   Node
        {
        public:
            int         data;
            int         rank;

            Node*       parent;

            Node() : data(0),
                     rank(0),
                     parent(this) { } // the constructor does MakeSet
        };

        Node*   find(Node*);
        Node*   merge(Node*, Node*); // Union
    };

    DisjointSet::Node*   DisjointSet::find(DisjointSet::Node* n)
    {
        if (n != n->parent) {
            n->parent = find(n->parent);
        }
        return n->parent;
    }

    DisjointSet::Node* DisjointSet::merge(DisjointSet::Node* x,
                                          DisjointSet::Node* y)
    {
        x = find(x);
        y = find(y);

        if (x->rank > y->rank) {
            y->parent = x;
        } else {
            x->parent = y;
            if (x->rank == y->rank) {
                ++(y->rank);
            }
        }
    }
</code>```

I am pretty sure this is incomplete though and that I am missing something.

Introduction to Algorithms mentions that there should be a forest of trees, but it does not give any explanation for a practical implementation of this forest. I watched CS 61B Lecture 31: Disjoint Sets ( http://www.youtube.com/watch?v=wSPAjGfDl7Q ) and here the lecturer uses only an array to store both the forest and all its trees and values. There is no explicit 'Node' type of class as I have, mentioned. I have also found many other sources (I cannot post more than one link), which also use this technique. I would be happy to do this, except that this relies on the indices of the array for lookup and since I want to store values of type other than int, I need to use something else (std::map comes to mind).

Another issue that I am unsure about is memory allocation because I am using C++. I am storing trees of pointers and my MakeSet operation will be: new DisjointSet::Node; . Now, these Nodes only have pointers to their parents, so I'm not sure how to find the bottom of a tree. How will I be able to traverse my trees to deallocate them all?

I understand the basic concept of this data structure, but I'm just a bit confused about the implementation. Any advice and suggestions would be most welcome, thank you.

答: I can't speak about the algorithm, but for memory management, typically you will use something called a smart pointer, which will free what it points to. You can get shared ownership and single ownership smart pointers, and non-ownership too. Correct use of these will guarantee no memory issues.</p>

Body:
I am trying to implement Disjoint Sets for use in Kruskal's algorithm, but I am having trouble understanding exactly how it should be done and in particular, how to manage the forest of trees. After reading the Wikipedia description of Disjoint Sets and after reading the description in Introduction to Algorithms (Cormen et al) I have come up with the following:

    class DisjointSet
    {
    public:
        class   Node
        {
        public:
            int         data;
            int         rank;

            Node*       parent;

            Node() : data(0),
                     rank(0),
                     parent(this) { } // the constructor does MakeSet
        };

        Node*   find(Node*);
        Node*   merge(Node*, Node*); // Union
    };

    DisjointSet::Node*   DisjointSet::find(DisjointSet::Node* n)
    {
        if (n != n->parent) {
            n->parent = find(n->parent);
        }
        return n->parent;
    }

    DisjointSet::Node* DisjointSet::merge(DisjointSet::Node* x,
                                          DisjointSet::Node* y)
    {
        x = find(x);
        y = find(y);

        if (x->rank > y->rank) {
            y->parent = x;
        } else {
            x->parent = y;
            if (x->rank == y->rank) {
                ++(y->rank);
            }
        }
    }

I am pretty sure this is incomplete though and that I am missing something.

Introduction to Algorithms mentions that there should be a forest of trees, but it does not give any explanation for a practical implementation of this forest. I watched CS 61B Lecture 31: Disjoint Sets ( http://www.youtube.com/watch?v=wSPAjGfDl7Q ) and here the lecturer uses only an array to store both the forest and all its trees and values. There is no explicit 'Node' type of class as I have, mentioned. I have also found many other sources (I cannot post more than one link), which also use this technique. I would be happy to do this, except that this relies on the indices of the array for lookup and since I want to store values of type other than int, I need to use something else (std::map comes to mind).

Another issue that I am unsure about is memory allocation because I am using C++. I am storing trees of pointers and my MakeSet operation will be: new DisjointSet::Node; . Now, these Nodes only have pointers to their parents, so I'm not sure how to find the bottom of a tree. How will I be able to traverse my trees to deallocate them all?

I understand the basic concept of this data structure, but I'm just a bit confused about the implementation. Any advice and suggestions would be most welcome, thank you.


问:
Joining CSV fields
I need to convert

```<code>Name | Org
a    | 5
a    | 6
b    | 5
c    | 7
</code>```

into

```<code>Name | Org
a    | 5,6
b    |  5
c    |  7
</code>```

my first attempt was with this code

```<code>    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1
</code>```

which just ends up with the result

```<code>Name | Org
a    |
b    |
c    |
</code>```

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

答:
Here is another solution that can be generic to have delimiter for input and output file.

```<code>def parseData(fileName, delimiter):
    dictionary={}
    with open(fileName, 'r') as iFile:
        for line in iFile.readlines():
            row = line.split(delimiter)
            values = []
            if (row[0] in dictionary.keys()):
                values = dictionary[row[0]]
                values.append(row[1].replace('\n',''))
            else:
                values.append(row[1].replace('\n',''))
                dictionary[row[0]] = values
        dictionary[row[0]] = values
    ## print for debugging purpose
    print(dictionary)
    return dictionary

def writeData(fileName, odelimiter, idelimiter, dictionary):
    with open(fileName, 'w') as oFile:
        for key, values in dictionary.items():
            data=""
            for value in values:
                data = data + value + idelimiter
            data=data[:-1]
            ## print for debugging purpose
            print(key, data)
            oFile.write(key + odelimiter + data + "\n")

## main
dictionary=parseData('inputPipe.txt', "|")
writeData('output.txt', "|", ",", dictionary)
</code>```

inputPipe.txt

```<code>a|5
a|6
b|5
c|7
</code>```

output.txt

```<code>a|5,6
b|5
c|7
</code>```

Sample Run

```<code>{'a': ['5', '6'], 'b': ['5'], 'c': ['7']}
a 5,6
b 5
c 7
</code>```

Title: Joining CSV fields

Body:
I need to convert

Name | Org
a    | 5
a    | 6
b    | 5
c    | 7

into

Name | Org
a    | 5,6
b    |  5
c    |  7

my first attempt was with this code

    while i < len(nameColumn):
    if nameColumn[i] not in resultC1:
        resultC1.append(nameColumn[i])
        while l < len(nameColumn):
            if nameColumn[l] == nameColumn[i]:
                tempdata += organizationColumn[l] + ','
            l += 1
        resultC2.append(tempdata[:-1])
        tempdata = ''
        k += 1
    i += 1

which just ends up with the result

Name | Org
a    |
b    |
c    |

Any help would be greatly appreciated. I havent had luck finding anything on this yet. I'm reading the data from a .CSV file into lists and working with that data and storing results into resultC1 and resultC2

Body:
Here is another solution that can be generic to have delimiter for input and output file.

def parseData(fileName, delimiter):
    dictionary={}
    with open(fileName, 'r') as iFile:
        for line in iFile.readlines():
            row = line.split(delimiter)
            values = []
            if (row[0] in dictionary.keys()):
                values = dictionary[row[0]]
                values.append(row[1].replace('\n',''))
            else:
                values.append(row[1].replace('\n',''))
                dictionary[row[0]] = values
        dictionary[row[0]] = values
    ## print for debugging purpose
    print(dictionary)
    return dictionary

def writeData(fileName, odelimiter, idelimiter, dictionary):
    with open(fileName, 'w') as oFile:
        for key, values in dictionary.items():
            data=""
            for value in values:
                data = data + value + idelimiter
            data=data[:-1]
            ## print for debugging purpose
            print(key, data)
            oFile.write(key + odelimiter + data + "\n")

## main
dictionary=parseData('inputPipe.txt', "|")
writeData('output.txt', "|", ",", dictionary)

inputPipe.txt

a|5
a|6
b|5
c|7

output.txt

a|5,6
b|5
c|7

Sample Run

{'a': ['5', '6'], 'b': ['5'], 'c': ['7']}
a 5,6
b 5
c 7


问:
I have a Block under my page and is pushing my page content up
I added a sidebar to my page and I am getting a block under my page which is fixed there and is pushing my content up. I am attaching a picture of it. When I try to inspect where it is coming from I get a <shadow> tag. I googled it and found that it's a Chrome DOM tag. But when I delete that the block still persists. Does anyone have any idea why it is formed in the first place and what I can do to remove it? Or is it a problem with my CSS??

Issue image

答:
Try display: none; in that object within the css.

If that doesn't work make sure you refresh your cache and reset the browser so that a local version of the css is not save in the browser.

Hope this helps..