问:
How to list all months between two dates using JS?
If I selected any two date,for example
      var d1 = '2014-05-01';
      var d2 = '2017-06-01';

Now I want to show all months between these two dates? Is it possible or not ?

答:
var namedMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
//Format: yyyy-mm-dd
function stringToDate(datestring) {
  var d = new Date(0);
  d.setHours(2);
  d.setFullYear(parseInt(datestring.substr(0, 4), 10));
  d.setMonth(parseInt(datestring.substr(5, 2), 10));
  d.setDate(parseInt(datestring.substr(8, 2), 10));
  return d;
}

function monthsBetween(from, to, cb) {
  if (cb === void 0) {
    cb = function(month) {};
  }
  //Convert to date objects
  var d1 = stringToDate(from);
  var d2 = stringToDate(to);
  //month counter
  var months = 0;
  //Call callback function with month
  cb(d1.getMonth());
  //While year or month mismatch, reduce by one day
  while (d2.getFullYear() != d1.getFullYear() || d2.getMonth() != d1.getMonth()) {
    var oldmonth = d1.getMonth();
    d1 = new Date(d1.getTime() + 86400000);
    //if we enter into new month, add to month counter
    if (oldmonth != d1.getMonth()) {
      //Call callback function with month
      cb(d1.getMonth());
      months++;
    }
  }
  //return month counter as result
  return months;
}
//test
var d1 = '2014-05-01';
var d2 = '2017-06-01';
console.log(monthsBetween(d1, d2, function(month) {
  console.log(namedMonths[month]);
}), "months between:", d1, "and", d2);```

EDIT 1 - Fixed the above snippet to include a callback function

Use the callback to do "by month" operations, like logging it to the console or writing it to your document.

Body:
var namedMonths = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
//Format: yyyy-mm-dd
function stringToDate(datestring) {
  var d = new Date(0);
  d.setHours(2);
  d.setFullYear(parseInt(datestring.substr(0, 4), 10));
  d.setMonth(parseInt(datestring.substr(5, 2), 10));
  d.setDate(parseInt(datestring.substr(8, 2), 10));
  return d;
}

function monthsBetween(from, to, cb) {
  if (cb === void 0) {
    cb = function(month) {};
  }
  //Convert to date objects
  var d1 = stringToDate(from);
  var d2 = stringToDate(to);
  //month counter
  var months = 0;
  //Call callback function with month
  cb(d1.getMonth());
  //While year or month mismatch, reduce by one day
  while (d2.getFullYear() != d1.getFullYear() || d2.getMonth() != d1.getMonth()) {
    var oldmonth = d1.getMonth();
    d1 = new Date(d1.getTime() + 86400000);
    //if we enter into new month, add to month counter
    if (oldmonth != d1.getMonth()) {
      //Call callback function with month
      cb(d1.getMonth());
      months++;
    }
  }
  //return month counter as result
  return months;
}
//test
var d1 = '2014-05-01';
var d2 = '2017-06-01';
console.log(monthsBetween(d1, d2, function(month) {
  console.log(namedMonths[month]);
}), "months between:", d1, "and", d2);

EDIT 1 - Fixed the above snippet to include a callback function

Use the callback to do "by month" operations, like logging it to the console or writing it to your document.


来源: stackexchange

问:
Get boost command line to parse array i supply rather than argv from main - emulate argv
Please excuse any ignorance, I'm new to c++.

I'm trying to use boost program_options and commandline parser for my command line program. The program uses getline to get some user inputted command. I want to parse that so it can be passed to boost but I can't seem to get the types right. I'm still learning pointers and all that jazz properly but I'm having a tough time.

Here's the code so you can get a idea of what I'm trying to do:

```<code>namespace po = boost::program_options;

int _tmain(int argc, _TCHAR* argv[])
{
    std::string input;
    _TCHAR* parsedInput[20];

    while (std::cin) {
        std::getline(std::cin, input);
        boost::split(parsedInput, input, boost::is_any_of(" "), boost::token_compress_on);

        po::options_description desc("allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("compression", po::value<int>(), "set compression level")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(5, parsedInput, desc), vm);
        po::notify(vm);

        if (vm.count("help"))
            std::cout << desc << "\n";
    }

    return 0;
}
</code>```

po::store(po::parse_command_line(5, parsedInput, desc), vm); the 5 is arbitrary just while I'm trying to make this work.

With the code I'm not entirely sure what my issue is but I think it actually has something to do with splitting the input, this is the current error message error C2078: too many initializers.

I originally split the input into a vector of strings, which got me past that error but then I had problems with po::parse_command_line(5, parsedInput, desc) taking the wrong type, I assume it can't take a vector of strings. After looking at the documentation that does seem to be the case.

If anyone could give me a hand or point me in the right direction I would be grateful. Thank you.

答:
You can't split into a char const*[].

Instead, split into a vector of std::string and transform to the required vector:

```<code>#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>

namespace po = boost::program_options;

int main()
{
    std::string input;

    while (std::cin) {
        std::getline(std::cin, input);

        std::vector<std::string> parsedInput;
        boost::split(parsedInput, input, boost::is_any_of(" "), boost::token_compress_on);

        std::vector<char const*> args { "command" };
        for (auto& arg : parsedInput)
            args.push_back(arg.c_str());

        po::options_description desc("allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("compression", po::value<int>(), "set compression level")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(args.size(), args.data(), desc), vm);
        po::notify(vm);

        if (vm.count("help"))
            std::cout << desc << "\n";
    }
}
</code>```

Note that first argument (arg[0]) should be the program name

Live On Coliru

```<code>allowed options:
  --help                produce help message
  --compression arg     set compression level
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Please excuse any ignorance, I'm new to c++.

I'm trying to use boost program_options and commandline parser for my command line program. The program uses getline to get some user inputted command. I want to parse that so it can be passed to boost but I can't seem to get the types right. I'm still learning pointers and all that jazz properly but I'm having a tough time.

Here's the code so you can get a idea of what I'm trying to do:

namespace po = boost::program_options;

int _tmain(int argc, _TCHAR* argv[])
{
    std::string input;
    _TCHAR* parsedInput[20];

    while (std::cin) {
        std::getline(std::cin, input);
        boost::split(parsedInput, input, boost::is_any_of(" "), boost::token_compress_on);

        po::options_description desc("allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("compression", po::value<int>(), "set compression level")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(5, parsedInput, desc), vm);
        po::notify(vm);

        if (vm.count("help"))
            std::cout << desc << "\n";
    }

    return 0;
}

po::store(po::parse_command_line(5, parsedInput, desc), vm); the 5 is arbitrary just while I'm trying to make this work.

With the code I'm not entirely sure what my issue is but I think it actually has something to do with splitting the input, this is the current error message error C2078: too many initializers.

I originally split the input into a vector of strings, which got me past that error but then I had problems with po::parse_command_line(5, parsedInput, desc) taking the wrong type, I assume it can't take a vector of strings. After looking at the documentation that does seem to be the case.

If anyone could give me a hand or point me in the right direction I would be grateful. Thank you.

Body:
You can't split into a char const*[].

Instead, split into a vector of std::string and transform to the required vector:

#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <iostream>

namespace po = boost::program_options;

int main()
{
    std::string input;

    while (std::cin) {
        std::getline(std::cin, input);

        std::vector<std::string> parsedInput;
        boost::split(parsedInput, input, boost::is_any_of(" "), boost::token_compress_on);

        std::vector<char const*> args { "command" };
        for (auto& arg : parsedInput)
            args.push_back(arg.c_str());

        po::options_description desc("allowed options");
        desc.add_options()
            ("help", "produce help message")
            ("compression", po::value<int>(), "set compression level")
        ;

        po::variables_map vm;
        po::store(po::parse_command_line(args.size(), args.data(), desc), vm);
        po::notify(vm);

        if (vm.count("help"))
            std::cout << desc << "\n";
    }
}

Note that first argument (arg[0]) should be the program name

Live On Coliru

allowed options:
  --help                produce help message
  --compression arg     set compression level


问:
Python - Add residuals to subplots generated by a for loop
I just can't get the subplots to work when adding the residuals with add_axes. It works well without residuals and I can add residuals to just one plot. This is an example of what I'm doing:

First, just to give you an idea of what I'm ploting, (t, y) is the data I want to plot, fit is the fit to the data, and diff is the difference between fit and data.

```<code>t, s, fit = [], [], []
diff = []
for i in range(12):
    t.append(x / y[i])

    s.append(np.linspace(0, 1, num=100, endpoint=True))
    fit.append(UnivariateSpline(t[i], y, er, s=5e20))
    diff.append(fit[i](t[i]) - y)
</code>```

And this is the figure:

```<code>fig = plt.figure()
for i in range(12):
    plt.subplot(4,3,i+1)
    fig.add_axes((0.,0.3,0.7,0.9))
    plt.plot(s[i], fit[i](s[i]), 'r-') # this is the fit
    plt.errorbar(t[i], y, er, fmt='.k',ms=6) # this is the data
    plt.axis([0,1, 190, 360])

    fig.add_axes((0.,0.,0.7,0.3))
    plot(t[i],diff[i],'or') # this are the residuals
    plt.axis([0,1, 190, 360])
</code>```

So as you can see I'm generating 12 subplots, which works just fine until I add the fig.add_axes to separate each subplot between data+fit and the residuals, but what I get is one messy plot on top of the subplots (figure has been shrunken to see the subplots under):

And what I want is 12 subplots where each one looks like this:

答:
Usually plt.subplot(..) and  fig.add_axes(..) are complementary. This means that both commands create an axes inside the figure.

Their usage however would be a bit different. To create 12 subplots with subplot you would do

```<code>for i in range(12):
    plt.subplot(4,3,i+1)
    plt.plot(x[i],y[i])
</code>```

To create 12 subplots with add_axes you would need to do something like this

```<code>for i in range(12):
    ax = fig.add_axes([.1+(i%3)*0.8/3, 0.7-(i//3)*0.8/4, 0.2,.18])
    ax.plot(x[i],y[i])
</code>```

where the positions of the axes need to be passed to add_axes.

Both work fine. But combining them is not straight forward, as the subplots are positionned according to a grid, while using add_axes you would need to already know the grid positions.

So I would suggest starting from scratch. A reasonable and clean approach to create subplots is to use plt.subplots().

```<code>fig, axes = plt.subplots(nrows=4, ncols=3)
for i, ax in enumerate(axes.flatten()):
    ax.plot(x[i],y[i])
</code>```

Each subplot can be divided into 2 by using an axes divider (make_axes_locatable)

```<code>from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
ax2 = divider.append_axes("bottom", size=size, pad=pad)
ax.figure.add_axes(ax2)
</code>```

So looping over the axes and doing the above for every axes allows to get the desired grid.

```<code>import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams["font.size"] = 8

x = np.linspace(0,2*np.pi)
amp = lambda x, phase: np.sin(x-phase)
p = lambda x, m, n: m+x**(n)

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(8,6), sharey=True, sharex=True)

def createplot(ax, x, m, n, size="20%", pad=0):
    divider = make_axes_locatable(ax)
    ax2 = divider.append_axes("bottom", size=size, pad=pad)
    ax.figure.add_axes(ax2)
    ax.plot(x, amp(x, p(x,m,n)))
    ax2.plot(x, p(x,m,n), color="crimson")
    ax.set_xticks([])

for i in range(axes.shape[0]):
    for j in range(axes.shape[1]):
        phase = i*np.pi/2
        createplot(axes[i,j], x, i*np.pi/2, j/2.,size="36%")

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

Body:
I just can't get the subplots to work when adding the residuals with add_axes. It works well without residuals and I can add residuals to just one plot. This is an example of what I'm doing:

First, just to give you an idea of what I'm ploting, (t, y) is the data I want to plot, fit is the fit to the data, and diff is the difference between fit and data.

t, s, fit = [], [], []
diff = []
for i in range(12):
    t.append(x / y[i])

    s.append(np.linspace(0, 1, num=100, endpoint=True))
    fit.append(UnivariateSpline(t[i], y, er, s=5e20))
    diff.append(fit[i](t[i]) - y)

And this is the figure:

fig = plt.figure()
for i in range(12):
    plt.subplot(4,3,i+1)
    fig.add_axes((0.,0.3,0.7,0.9))
    plt.plot(s[i], fit[i](s[i]), 'r-') # this is the fit
    plt.errorbar(t[i], y, er, fmt='.k',ms=6) # this is the data
    plt.axis([0,1, 190, 360])

    fig.add_axes((0.,0.,0.7,0.3))
    plot(t[i],diff[i],'or') # this are the residuals
    plt.axis([0,1, 190, 360])

So as you can see I'm generating 12 subplots, which works just fine until I add the fig.add_axes to separate each subplot between data+fit and the residuals, but what I get is one messy plot on top of the subplots (figure has been shrunken to see the subplots under):

And what I want is 12 subplots where each one looks like this:

Body:
Usually plt.subplot(..) and  fig.add_axes(..) are complementary. This means that both commands create an axes inside the figure.

Their usage however would be a bit different. To create 12 subplots with subplot you would do

for i in range(12):
    plt.subplot(4,3,i+1)
    plt.plot(x[i],y[i])

To create 12 subplots with add_axes you would need to do something like this

for i in range(12):
    ax = fig.add_axes([.1+(i%3)*0.8/3, 0.7-(i//3)*0.8/4, 0.2,.18])
    ax.plot(x[i],y[i])

where the positions of the axes need to be passed to add_axes.

Both work fine. But combining them is not straight forward, as the subplots are positionned according to a grid, while using add_axes you would need to already know the grid positions.

So I would suggest starting from scratch. A reasonable and clean approach to create subplots is to use plt.subplots().

fig, axes = plt.subplots(nrows=4, ncols=3)
for i, ax in enumerate(axes.flatten()):
    ax.plot(x[i],y[i])

Each subplot can be divided into 2 by using an axes divider (make_axes_locatable)

from mpl_toolkits.axes_grid1 import make_axes_locatable
divider = make_axes_locatable(ax)
ax2 = divider.append_axes("bottom", size=size, pad=pad)
ax.figure.add_axes(ax2)

So looping over the axes and doing the above for every axes allows to get the desired grid.

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.rcParams["font.size"] = 8

x = np.linspace(0,2*np.pi)
amp = lambda x, phase: np.sin(x-phase)
p = lambda x, m, n: m+x**(n)

fig, axes = plt.subplots(nrows=3, ncols=4, figsize=(8,6), sharey=True, sharex=True)

def createplot(ax, x, m, n, size="20%", pad=0):
    divider = make_axes_locatable(ax)
    ax2 = divider.append_axes("bottom", size=size, pad=pad)
    ax.figure.add_axes(ax2)
    ax.plot(x, amp(x, p(x,m,n)))
    ax2.plot(x, p(x,m,n), color="crimson")
    ax.set_xticks([])

for i in range(axes.shape[0]):
    for j in range(axes.shape[1]):
        phase = i*np.pi/2
        createplot(axes[i,j], x, i*np.pi/2, j/2.,size="36%")

plt.tight_layout()
plt.show()


问:
Maximum number of allowable file uploads has been exceeded
We're uploading about 500 images at a time

```<code>max_file_uploads = 600
memory_limit = 200M ( most images are 12-15KB )
post_max_size = 200M
</code>```

Why are we still getting that warning?

EDIT: All these variables are set in the php.ini file and confirmed by checking using phpinfo();

答: The PHP script won't even start executing until all the files have been uploaded. That means that you cannot change the max_file_uploads directive from within PHP, e.g. with ini_set(): you need to do it in the php.ini file. Otherwise, when you change the setting the limit has already been hit.

ContentLicense: CC BY-SA 2.5

Body:
We're uploading about 500 images at a time

max_file_uploads = 600
memory_limit = 200M ( most images are 12-15KB )
post_max_size = 200M

Why are we still getting that warning?

EDIT: All these variables are set in the php.ini file and confirmed by checking using phpinfo();


问:
Common Lisp, list handling (append etc.)
I have to manage this situation:

```<code>(defun make-point (a b)
(cons a b))
</code>```

This function creates one of the point on the Cartesian axis (I omit generic controls for convenience). How can I implement a function where, each time make-point is called, it updates a list where all points are appended?

E.g.

```<code>'()
((1.1))
((1.1)(2.4))
((1.1)(2.4)(4.5))
</code>```

I will need the list as a parameter for a following function.

答:
You define a variable:

```<code>(defvar *points* '())
</code>```

The asterisks around the variable's name (called "earmuffs") is a very strong convention in CL to denote variables that are declared special, which is the case when using DEFVAR/DEFPARAMETER. Here I am using DEFVAR because I don't want the list of points to be reset to the empty list if I ever need to reload the compilation unit in  which the code resides.

Then, you can provide an interface for the programmer to abstract that list of points:

```<code>(defun clear-all-points ()
  (setf *points* nil))

(defun add-point (point)
  (push point *points*))
</code>```

Here you can see that I store the given point in front of the list of points, which is the natural way to work with lists; appending things at the end, requires you to traversal the list, which is wasteful and most of the time, not necessary. Also, how exactly you append a new element might change how the list of points can be used:

if you implement add-point as

```<code>(setf *points* (append *points* (list point)))
</code>```

... then the list referenced by *points* is a copy, and if you previously stored *points* in another place, you now have two lists of points (I am not saying if this is right or wrong here, just explaining what happens);

if, however, you mutate the list:

```<code>(setf *points* (nconc *points* (list point)))
</code>```

... then you can share the list among different objects, and whenever they read the list, they will have the up-to-date list of all points.

You might also need to consider how much memory you will be using with both approaches. If you append by copying, with APPEND, the previous list will eventually be reclaimed by the garbage collector; if you add points too frequently, you will start to trash memory in a way that can degrade performances.

If you need to put things at the end without resorting to NCONC consider using a queue or an array.
 A basic queue can be simply implemented on top of a list, through a queue object which is just a cons-cell where the car is the first cell of the underlying list and the cdr is the last cons-cell of the same list. When you append an element x to a list (e0 ... en), you go from this state:

```<code>( e0 . ( ...  (en . nil) ... ))
^first        ^last
</code>```

... to this one

```<code>( e0 . ( ...  (en . (x . nil)) ... ))
^first              ^last
</code>```

You could try implementing it as another exercise.

Then, you can keep your function untouched (but indented); you will probably have to make points without adding them into the global list, so it makes sense to keep things separate:

```<code>(defun make-point (a b)
  (cons a b))
</code>```

If you need it, you can define an auxiliary function which combine both actions:

```<code>(defun add-new-point (a b)
  (add-point (make-point a b)))
</code>```

Also, please note that whitespace is significant: what you wrote in the desired output (e.g. (1.1)) are lists of floating point numbers.

Body:
I have to manage this situation:

(defun make-point (a b)
(cons a b))

This function creates one of the point on the Cartesian axis (I omit generic controls for convenience). How can I implement a function where, each time make-point is called, it updates a list where all points are appended?

E.g.

'()
((1.1))
((1.1)(2.4))
((1.1)(2.4)(4.5))

I will need the list as a parameter for a following function.

Body:
You define a variable:

(defvar *points* '())

The asterisks around the variable's name (called "earmuffs") is a very strong convention in CL to denote variables that are declared special, which is the case when using DEFVAR/DEFPARAMETER. Here I am using DEFVAR because I don't want the list of points to be reset to the empty list if I ever need to reload the compilation unit in  which the code resides.

Then, you can provide an interface for the programmer to abstract that list of points:

(defun clear-all-points ()
  (setf *points* nil))

(defun add-point (point)
  (push point *points*))

Here you can see that I store the given point in front of the list of points, which is the natural way to work with lists; appending things at the end, requires you to traversal the list, which is wasteful and most of the time, not necessary. Also, how exactly you append a new element might change how the list of points can be used:

if you implement add-point as

(setf *points* (append *points* (list point)))

... then the list referenced by *points* is a copy, and if you previously stored *points* in another place, you now have two lists of points (I am not saying if this is right or wrong here, just explaining what happens);

if, however, you mutate the list:

(setf *points* (nconc *points* (list point)))

... then you can share the list among different objects, and whenever they read the list, they will have the up-to-date list of all points.

You might also need to consider how much memory you will be using with both approaches. If you append by copying, with APPEND, the previous list will eventually be reclaimed by the garbage collector; if you add points too frequently, you will start to trash memory in a way that can degrade performances.

If you need to put things at the end without resorting to NCONC consider using a queue or an array.
 A basic queue can be simply implemented on top of a list, through a queue object which is just a cons-cell where the car is the first cell of the underlying list and the cdr is the last cons-cell of the same list. When you append an element x to a list (e0 ... en), you go from this state:

( e0 . ( ...  (en . nil) ... ))
^first        ^last

... to this one

( e0 . ( ...  (en . (x . nil)) ... ))
^first              ^last

You could try implementing it as another exercise.

Then, you can keep your function untouched (but indented); you will probably have to make points without adding them into the global list, so it makes sense to keep things separate:

(defun make-point (a b)
  (cons a b))

If you need it, you can define an auxiliary function which combine both actions:

(defun add-new-point (a b)
  (add-point (make-point a b)))

Also, please note that whitespace is significant: what you wrote in the desired output (e.g. (1.1)) are lists of floating point numbers.


问:
Android studio error ndk then import telegram source code
hello i have this error  i use source drklo
https://github.com/DrKLO/Telegram

please help :(

External Native Build Issues
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/fat/foss/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\fat\foss\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=1 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86/debug/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86_SDK23/foss/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86_SDK23\foss\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=0 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7_SDK23/foss/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7_SDK23\foss\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/fat/release/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\fat\release\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86_SDK23/release/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86_SDK23\release\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=1 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7/debug/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7/release/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7\release\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=1 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7_SDK23/debug/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7_SDK23\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86/release/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86\release\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7/foss/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7\foss\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=0 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86/foss/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86\foss\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=armeabi-v7a NDK_ALL_ABIS=armeabi-v7a NDK_DEBUG=0 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/armv7_SDK23/release/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\armv7_SDK23\release\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_armeabi-v7a.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=1 APP_PLATFORM=android-14 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/fat/debug/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\fat\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
Build command failed.
Error while executing process F:\sdk\ndk-bundle\ndk-build.cmd with arguments {NDK_PROJECT_PATH=null APP_BUILD_SCRIPT=D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk NDK_APPLICATION_MK=D:\WorkSpace\Telegram\TMessagesProj\jni\Application.mk APP_ABI=x86 NDK_ALL_ABIS=x86 NDK_DEBUG=1 APP_PLATFORM=android-23 NDK_OUT=D:/WorkSpace/Telegram/TMessagesProj/build/intermediates/ndkBuild/x86_SDK23/debug/obj NDK_LIBS_OUT=D:\WorkSpace\Telegram\TMessagesProj\build\intermediates\ndkBuild\x86_SDK23\debug\lib NDK_APPLICATION_MK:=jni/Application.mk APP_PLATFORM:=android-14 APP_SHORT_COMMANDS=false LOCAL_SHORT_COMMANDS=false -B -n}
Android NDK: ERROR:D:\WorkSpace\Telegram\TMessagesProj\jni\Android.mk:WebRtcAec: LOCAL_SRC_FILES points to a missing file

Android NDK: Check that D:/WorkSpace/Telegram/TMessagesProj/jni/./libtgvoip/external/libWebRtcAec_android_x86.a exists  or that its path is correct

process_begin: CreateProcess(NULL, "", ...) failed.
F:\sdk\ndk-bundle\build\core\prebuilt-library.mk
Error:(44, 0) * Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0)  Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0) * Android NDK: Aborting    .  Stop.
Open File
Error:(44, 0) *** Android NDK: Aborting    .  Stop.
Open File

答:
You should download submodules for this project, i.e.

git clone https://github.com/DrKLO/Telegram.git

git submodule update --init


问:
How to skip exception thrown in a method annotated with @BeforeStep
I am using chunk Reader, Processor and Writer pattern to process our data. The approach i took is, before going to Reader's read method, i run a sql which connects to db and pulls all the required data. This is done in a method annotated with @BeforeStep and the output data becomes the source for the Reader's read method which iterates through this generated data and retrieves an item per read for processor. Any exception thrown during the flow is caught and retried using the @Retryable feature and skipped using the skippable exception feature.

One thing that is confusing for me is, any exception that is thrown in the method annotated with @BeforeStep is caught and a custom skippable exception is thrown by the app which isn't getting skipped by the system. Is this the desired behavior or am i missing something. Please help me in this.

Thanks,
raveendra

答:
If design force you to pull data from DB a reasonable solution is to create a step before the main one and move code from @BeforeStep into this new step; you can manage skippable-exception and retry condition better than in a listener.

You can look at this answer (Can we write a Spring Batch Job Without ItemReader and ItemWriter); in Tasklet#execute() write something like:

```<code>class MyTasklet implements Tasklet {
 @Override
 public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
  // Fetch data using JdbcTemplate (for example) and pull to external bean to let extracted data visible to next step
  return RepeatStatus.FINISHED;
 }
}
</code>```

Also check SO for 'passing data between steps spring batch' for extra info

Body:
If design force you to pull data from DB a reasonable solution is to create a step before the main one and move code from @BeforeStep into this new step; you can manage skippable-exception and retry condition better than in a listener.

You can look at this answer (Can we write a Spring Batch Job Without ItemReader and ItemWriter); in Tasklet#execute() write something like:

class MyTasklet implements Tasklet {
 @Override
 public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
  // Fetch data using JdbcTemplate (for example) and pull to external bean to let extracted data visible to next step
  return RepeatStatus.FINISHED;
 }
}

Also check SO for 'passing data between steps spring batch' for extra info


问:
Using Rmagick to resize height first
I am trying to resize an image with Rmagick and if I use the resize_to_fit method to always resize the height first, preferring that to width, but it seems as if most of my images are being resized to width first. IS there anyway using the resize_to_fit method to tell it "prefer height over width"?

答:
You can specify the height max value and let Rmagick calculate the corresponding width by using the change_geometry method.

This can be useful in case you want to set the max height of a landscape image and do not want to specify the corresponding width to preserve the ratio:

require "rmagick"
include Magick

img = ImageList.new("<path_to_your_img>") # assuming a landscape oriented img
img.change_geometry("x395") do |cols, rows, img| # set the max height
  img.resize(cols, rows)
end
```

Do remember you always have to pass a block to the change geometry method.
You can find more information on the official documentation.

Cheers

Title: Using Rmagick to resize height first

Body:
You can specify the height max value and let Rmagick calculate the corresponding width by using the change_geometry method.

This can be useful in case you want to set the max height of a landscape image and do not want to specify the corresponding width to preserve the ratio:

require "rmagick"
include Magick

img = ImageList.new("<path_to_your_img>") # assuming a landscape oriented img
img.change_geometry("x395") do |cols, rows, img| # set the max height
  img.resize(cols, rows)
end

Do remember you always have to pass a block to the change geometry method.
You can find more information on the official documentation.

Cheers


问:
How to implement Oracle's "func(...) keep (dense_rank ...)" In Hive
I have a table abcd in Oracle DB

```<code>  +-------------+----------+
  | abcd.speed  | abcd.ab  |
  +-------------+----------+
  | 4.0         | 2        |
  | 4.0         | 2        |
  | 7.0         | 2        |
  | 7.0         | 2        |
  | 8.0         | 1        |
  +-------------+----------+
</code>```

And I'm using a query like this:

```<code>select min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST) MOD from abcd;
</code>```

I'm trying to convert the code to Hive, but it looks like keep is not available in Hive.

Could you suggest an equivalent statement?

答:
```<code>select  -max(struct(ab,-speed)).col2 as mod
from    abcd
;
</code>```

```<code>+------+
| mod  |
+------+
| 4.0  |
+------+
</code>```

Let start by explaining min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST):
Find the row(s) with the max value of ab.

For this/those row(s), find the min value of speed.

We are using 2 tricks here.

The 1st is based on the ability to get the max value of a struct.

max(struct(c1,c2,c3,...)) returns the same result as if you have sorted the structs by c1, then by c2, then by c3 etc. and then chose the last element.

The 2nd trick is to use -speed (which is the same of -1*speed).
Finding the max of -speed and then taking the minus of that value (which gives us speed), is the same of finding the min of speed.

If we would have ordered the structs, it would have looked like this (since 2 is bigger than 1 and -4 is bigger than -7):

```<code>+----+-------+
| ab | speed |
+----+-------+
|  1 |  -8.0 |
|  2 |  -7.0 |
|  2 |  -7.0 |
|  2 |  -4.0 |
|  2 |  -4.0 |
+----+-------+
</code>```

The last struct in this case in struct(2,-4.0), therefore this is the result of the max function.

The fields names for a struct are col1, col2, col3 etc., so
struct(2,-4.0).col2 is -4.0. and preceding it with minus (which is the same as multiple it by -1) as in -struct(2,-4.0).col2 is 4.0.

Body:
I have a table abcd in Oracle DB

  +-------------+----------+
  | abcd.speed  | abcd.ab  |
  +-------------+----------+
  | 4.0         | 2        |
  | 4.0         | 2        |
  | 7.0         | 2        |
  | 7.0         | 2        |
  | 8.0         | 1        |
  +-------------+----------+

And I'm using a query like this:

select min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST) MOD from abcd;

I'm trying to convert the code to Hive, but it looks like keep is not available in Hive.

Could you suggest an equivalent statement?

Body:
select  -max(struct(ab,-speed)).col2 as mod
from    abcd
;

+------+
| mod  |
+------+
| 4.0  |
+------+

Let start by explaining min(speed) keep (dense_rank last order by abcd.ab NULLS FIRST):
Find the row(s) with the max value of ab.

For this/those row(s), find the min value of speed.

We are using 2 tricks here.

The 1st is based on the ability to get the max value of a struct.

max(struct(c1,c2,c3,...)) returns the same result as if you have sorted the structs by c1, then by c2, then by c3 etc. and then chose the last element.

The 2nd trick is to use -speed (which is the same of -1*speed).
Finding the max of -speed and then taking the minus of that value (which gives us speed), is the same of finding the min of speed.

If we would have ordered the structs, it would have looked like this (since 2 is bigger than 1 and -4 is bigger than -7):

+----+-------+
| ab | speed |
+----+-------+
|  1 |  -8.0 |
|  2 |  -7.0 |
|  2 |  -7.0 |
|  2 |  -4.0 |
|  2 |  -4.0 |
+----+-------+

The last struct in this case in struct(2,-4.0), therefore this is the result of the max function.

The fields names for a struct are col1, col2, col3 etc., so
struct(2,-4.0).col2 is -4.0. and preceding it with minus (which is the same as multiple it by -1) as in -struct(2,-4.0).col2 is 4.0.

ContentLicense: CC BY-SA 4.0


问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答:
All it does is slice. You pick. start stop and step so basically you're saying it should start at the beginning until the beginning but going backwards (-1).

If you do it with -2 it will skip letters:

```<code>>>> a[::-2]
'olh'
</code>```

When doing [0:5:-1] your'e starting at the first letter and going back directly to 5 and thus it will stop. only if you try [-1::-1] will it correctly be able to go to the beginning by doing steps of negative 1.

Edit to answer comments

As pointed out the documentation says

an omitted second index defaults to the size of the string being
  sliced.

Lets assume we have str with len(str) = 5. When you slice the string and omit, leave out, the second number it defaults to the length of the string being sliced, in this case - 5.
i.e str[1:] == str[1:5], str[2:] == str[2:5]. The sentence refers to the length of the original object and not the newly sliced object.

Also, this answer is great

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

Body:
All it does is slice. You pick. start stop and step so basically you're saying it should start at the beginning until the beginning but going backwards (-1).

If you do it with -2 it will skip letters:

>>> a[::-2]
'olh'

When doing [0:5:-1] your'e starting at the first letter and going back directly to 5 and thus it will stop. only if you try [-1::-1] will it correctly be able to go to the beginning by doing steps of negative 1.

Edit to answer comments

As pointed out the documentation says

an omitted second index defaults to the size of the string being
  sliced.

Lets assume we have str with len(str) = 5. When you slice the string and omit, leave out, the second number it defaults to the length of the string being sliced, in this case - 5.
i.e str[1:] == str[1:5], str[2:] == str[2:5]. The sentence refers to the length of the original object and not the newly sliced object.

Also, this answer is great


问:
undefined reference to _imp_sfBlendAlpha
I have recently installed MinGW and CSFML on my laptop and I run:

```<code>gcc shaders.c -csfml-system -csfml-graphics
</code>```

I get an error:

```<code>...\ccV1NsAK.o:shaders.c:(.text+0x247):' undefined reference to _imp__sfBlendAlpha'
</code>```

How do I fix this?

Kind Regards,
Boston Brooks.

Update 1

I've played around with installing to different search paths but I couldn't get this to work. I reinstalled MinGW and pasted the files from the CSFML package to the default path. Now I get:

```<code>gcc shaders.c -lcsfml-system -lcsfml-window -lcsfml-graphics
C:\Users\bbroo\AppData\Local\Temp\cc9QM4Nx.o:shaders.c:(.text+0x2d8): undefined reference to '_imp__sfBlendAlpha'
C:\Users\bbroo\AppData\Local\Temp\cc9QM4Nx.o:shaders.c:(.text+0x318): undefined reference to '_imp__sfTransform_Identity'
collect2.exe: error: ld returned 1 exit status
</code>```

Update 2

I copied CSFML to my home folder. I get:

```<code>$ gcc -B ~/CSFML -Ld: ~/CSFML shaders.c  -lcsfml-system -lcsfml-window -lcsfml-graphics
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find C:/MinGW/msys/1.0/home/bbroo/CSFML: Permission denied
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-system
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-window
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-graphics
collect2.exe: error: ld returned 1 exit status
</code>```

The header files can be accessed but the dot-a files are 'permission denied'
How do I set the permissions to Read-Write-Execute for all users on all files in CSFML using MSYS?

Same problem if I use C:\SFML

Update 3

When I unzip the files to the default path, a sub-folder is generated in the folder where my dot-a files are located. It contains several dot-a files, and a readme text file.

This README file is copied into the directory for GCC-only header files
when fixincludes is run by the makefile for GCC:

Many of the files in this directory were automatically edited from the
  standard system header files by the fixincludes process.  They are
  system-specific, and will not work on any other kind of system.  They
  are also not part of GCC.  The reason we have to do this is because
  GCC requires ANSI C headers and many vendors supply ANSI-incompatible
  headers.

Because this is an automated process, sometimes headers get "fixed"
  that do not, strictly speaking, need a fix.  As long as nothing is broken
  by the process, it is just an unfortunate collateral inconvenience.
  We would like to rectify it, if it is not "too inconvenient".

Update 4

Compiling without linking worked fine but linking separately didn't work:

```<code>bbroo@DESKTOP-1F1J3SM ~/Shaders
$ ld shaders.o libcsfml-system.a libcsfml-window.a libcsfml-graphics.a
shaders.o:shaders.c:(.text+0x10): undefined reference to `__main'
shaders.o:shaders.c:(.text+0x2d8): undefined reference to `_imp__sfBlendAlpha'
shaders.o:shaders.c:(.text+0x318): undefined reference to `_imp__sfTransform_Identity'
shaders.o:shaders.c:(.text+0x4bc): undefined reference to `sleep'
</code>```

Update 5

Now I get:

```<code>bbroo@DESKTOP-1F1J3SM ~/Shaders
$ ld shaders.o libcsfml-system.a libcsfml-window.a libcsfml-graphics.a csfml-system-2.dll csfml-window-2.dll csfml-graphics-2.dll
shaders.o:shaders.c:(.text+0x10): undefined reference to `__main'
shaders.o:shaders.c:(.text+0x4bc): undefined reference to `sleep'
</code>```

答:
gcc shaders.c libcsfml-system.a libcsfml-window.a libcsfml-graphics.a csfml-system-2.dll csfml-window-2.dll csfml-graphics-2.dll

it works for me.

Body:
I have recently installed MinGW and CSFML on my laptop and I run:

gcc shaders.c -csfml-system -csfml-graphics

I get an error:

...\ccV1NsAK.o:shaders.c:(.text+0x247):' undefined reference to _imp__sfBlendAlpha'

How do I fix this?

Kind Regards,
Boston Brooks.

Update 1

I've played around with installing to different search paths but I couldn't get this to work. I reinstalled MinGW and pasted the files from the CSFML package to the default path. Now I get:

gcc shaders.c -lcsfml-system -lcsfml-window -lcsfml-graphics
C:\Users\bbroo\AppData\Local\Temp\cc9QM4Nx.o:shaders.c:(.text+0x2d8): undefined reference to '_imp__sfBlendAlpha'
C:\Users\bbroo\AppData\Local\Temp\cc9QM4Nx.o:shaders.c:(.text+0x318): undefined reference to '_imp__sfTransform_Identity'
collect2.exe: error: ld returned 1 exit status

Update 2

I copied CSFML to my home folder. I get:

$ gcc -B ~/CSFML -Ld: ~/CSFML shaders.c  -lcsfml-system -lcsfml-window -lcsfml-graphics
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find C:/MinGW/msys/1.0/home/bbroo/CSFML: Permission denied
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-system
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-window
c:/mingw/bin/../lib/gcc/mingw32/5.3.0/../../../../mingw32/bin/ld.exe: cannot find -lcsfml-graphics
collect2.exe: error: ld returned 1 exit status

The header files can be accessed but the dot-a files are 'permission denied'
How do I set the permissions to Read-Write-Execute for all users on all files in CSFML using MSYS?

Same problem if I use C:\SFML

Update 3

When I unzip the files to the default path, a sub-folder is generated in the folder where my dot-a files are located. It contains several dot-a files, and a readme text file.

This README file is copied into the directory for GCC-only header files
when fixincludes is run by the makefile for GCC:

Many of the files in this directory were automatically edited from the
  standard system header files by the fixincludes process.  They are
  system-specific, and will not work on any other kind of system.  They
  are also not part of GCC.  The reason we have to do this is because
  GCC requires ANSI C headers and many vendors supply ANSI-incompatible
  headers.

Because this is an automated process, sometimes headers get "fixed"
  that do not, strictly speaking, need a fix.  As long as nothing is broken
  by the process, it is just an unfortunate collateral inconvenience.
  We would like to rectify it, if it is not "too inconvenient".

Update 4

Compiling without linking worked fine but linking separately didn't work:

bbroo@DESKTOP-1F1J3SM ~/Shaders
$ ld shaders.o libcsfml-system.a libcsfml-window.a libcsfml-graphics.a
shaders.o:shaders.c:(.text+0x10): undefined reference to `__main'
shaders.o:shaders.c:(.text+0x2d8): undefined reference to `_imp__sfBlendAlpha'
shaders.o:shaders.c:(.text+0x318): undefined reference to `_imp__sfTransform_Identity'
shaders.o:shaders.c:(.text+0x4bc): undefined reference to `sleep'

Update 5

Now I get:

bbroo@DESKTOP-1F1J3SM ~/Shaders
$ ld shaders.o libcsfml-system.a libcsfml-window.a libcsfml-graphics.a csfml-system-2.dll csfml-window-2.dll csfml-graphics-2.dll
shaders.o:shaders.c:(.text+0x10): undefined reference to `__main'
shaders.o:shaders.c:(.text+0x4bc): undefined reference to `sleep'


问:
I get error as "Method save does not exist." while updating the data
I want to update the record. I use mongo db and php and I am using laravel 5.4. while updating the data I get the error

BadMethodCallException in Macroable.php line 74:

Method save does not exist.

```<code>public function updatedata()
    {
        $id = DB::connection('mongodb')->collection('login2')->where('_id','=',1)->get();
        $id->name = 'Rajesh';
        $id->save();

        //return $id;
    }
</code>```

答:
This will do the Job! Let me know if it works!</p>

```<code>public function updatedata()
    {
        $id = DB::connection('mongodb')->collection('login2')->where('_id','=',1)->first();
        $id->name = 'Rajesh';
        $id->save();

        //return $id;
    }
</code>```

Body:
I want to update the record. I use mongo db and php and I am using laravel 5.4. while updating the data I get the error

BadMethodCallException in Macroable.php line 74:

Method save does not exist.

public function updatedata()
    {
        $id = DB::connection('mongodb')->collection('login2')->where('_id','=',1)->get();
        $id->name = 'Rajesh';
        $id->save();

        //return $id;
    }

Body:
This will do the Job! Let me know if it works!

public function updatedata()
    {
        $id = DB::connection('mongodb')->collection('login2')->where('_id','=',1)->first();
        $id->name = 'Rajesh';
        $id->save();

        //return $id;
    }


问:
How to make enter key as tab for input and submit if button found in angularjs?
I have a view where there are two buttons. one for save and another for update.: I want to use enter key as tab. If it reaches last input and find button, the form will be submitted (ng-click function will be triggered). Is it possible to do with two button or i should rely on only one button?

I tried:

```<code>     $('#truckform input ,#truckform button').on("keypress", function(e) {
                 // ENTER PRESSED
                if (e.keyCode == 13) {

                    console.log('tag')
                   // FOCUS ELEMENT
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);
console.log(idx)

                    console.log(inputs.length)
                    if (idx == inputs.length - 1) {
                        inputs[0].select()
                    } else {
                        inputs[idx + 1].focus(); //  handles submit buttons
                        inputs[idx + 1].select();
                    }
                    return false;
                }
            });
</code>```

I gives the error in console when button gets focus:

```<code>Uncaught TypeError: inputs[(idx + 1)].select is not a function
at HTMLInputElement.<anonymous> (truckEntry.js:56)
at HTMLInputElement.dispatch (jquery-2.2.3.min.js:3)
at HTMLInputElement.r.handle (jquery-2.2.3.min.js:3)
</code>```

But after the error, the saveData() function is triggered. But in the update mode, the updateData() is not triggered and the error remains all times till i press enter. How can i maake it functional? Any suggestion?
  My view:

```<code>  <form  name="truckform" id="truckform" novalidate>
               <table id="truckformTbl">
                   <tr>
                       <td class="text-center" colspan="6">
                           <h4 class="ok"> Truck Entry/Exit Form</h4>
                       </td>
                   </tr>
                    <tr ng-hide="hideManifestDetailsInput">
                        <th>Manifest No : </th>
                        <td>
                            <input type="text" ng-pattern='/^[0-9]{1,10}[/]{1}([0-9]{1,2}|[(A|a)]{1})$/' required="required" ng-disabled="disbleManifestNoInpForEditMode"  ng-model="ManifestNo" name="ManifestNo" id="Manifest_no" class="form-control input-sm" placeholder="Manifest No.">
                            <span class="error" ng-show='truckform.ManifestNo.$error.pattern'>
                                Input like: 256/12 Or 256/A
                            </span>
                            <span class="error" ng-show="submitted && !ManifestNo && !truckform.ManifestNo.$error.pattern">
                              Manifest No is required
                            </span>

                            <span class="error" ng-show="truckExceedInManifest">Manifest is full</span>
                        </td>
                        <th>  Manifest Date :</th>
                        <td>
                            <input type="text"  ng-model="manifest_date" required="required" name="manifest_date" id="manifest_date" class="form-control datePicker input-sm" placeholder="Manifest date">

                            <span ng-show="submitted && !manifest_date" class="error">Select a date</span>
                        </td>
                        <th> Goods Name :</th>

                        <td style="width: 15em; vertical-align: top" rowspan="8">
                           {{-- <select class="form-control input-sm" name="goods_id" ng-model="goods_id"
                                    ng-options="good.id as good.id +'-'+good.cargo_name group by good.category for good in allGoodsData ">

                                <option value="" selected="selected">Select Goods Name</option>
                            </select>
                            <span class="error" ng-show="truckform.goods_id.$dirty && truckform.goods_id.$touched && !goods_id ">
                             Select at least one goods
                            </span>--}}

                            <tags-input ng-model="goods_id"
                                        display-property="cargo_name"
                                        placeholder="Add New Item"
                                        replace-spaces-with-dashes="false"
                                        add-from-autocomplete-only="true"
                                        on-tag-added="tagAdded($tag)"
                                        on-tag-removed="tagRemoved($tag)">

                                <auto-complete source="loadGoods($query)"
                                               min-length="0"
                                               debounce-delay="0"
                                               max-results-to-show="10">

                                </auto-complete>

                            </tags-input>
                            <span ng-show="submitted && !goods_id ||goods_id.length==0" class="error">Choose at least one goods!</span>
                        </td>
                    </tr>

<tr>
    <td colspan="4"> </td>
</tr>
                    <tr>
                        <th>Truck Type :</th>
                        <td>
                            <input type="text" ng-model="truck_type" name="truck_type" id="truck_type" class="form-control input-sm" value="{{old('truck_type')}}"  placeholder="Truck Type">
                            <span class="error" ng-show="submitted && !truck_type">
                             Truck Type is required
                            </span>
                        </td>

                        <th>  Truck No :</th>
                        <td>
                            <input type="number" min="1" required="required" ng-model="truck_no" name="truck_no" id="truckNo" class="form-control input-sm" placeholder="Truck No" value="{{old('truck_no')}}">
                            <span class="error" ng-show="submitted && !truck_no">
                             Truck No is required
                            </span>
                        </td>

                    </tr>

                    <tr>
                        <td colspan="4"> </td>
                    </tr>

                    <tr>
                        <th>Driver Card No :</th>
                        <td>
                            <input type="number" ng-model="driver_card" name="DriverCardNo" id="DriverCardNo" class="form-control input-sm" placeholder="Driver Card No." value="{{old('DriverCardNo')}}">

                            <span class="error" ng-show="submitted && !driver_card">
                             Driver Card No. is required
                            </span>
                        </td>

                        <th>  Weight Bridge:</th>
                        <td>
                            <label class="radio-inline">
                                <input type="radio" name="fff" ng-init="weightment_flag=1"  ng-model="weightment_flag" ng-checked="true"  value="1">Yes
                            </label>
                            <label class="radio-inline">
                                <input type="radio"  ng-model="weightment_flag"  value="0" >No
                            </label>
                        </td>

                    </tr>
                   <tr>
                       <td colspan="4"> </td>
                   </tr>

                   <tr>
                       <th>  Driver Name :</th>
                       <td style="width: 15em;">
                           <input type="text" ng-model="driver_name" name="DriverName" id="driverName" class="form-control input-sm" placeholder="Driver Name" value="{{old('DriverName')}}">
                           <span class="error" ng-show="submitted && !driver_name">
                             Driver Name is required
                            </span>
                       </td>
                   </tr>
                    <tr>
                        <td colspan="3"></td>

                        <td colspan="1" class="text-center">
                            <br>
                            <button type="button" ng-click="saveData(truckform)" ng-hide="updateBtn" class="btn btn-primary btn-block center-block">
                                <span class="fa fa-download"></span>
                                Save
                            </button>
                            <button type="button" ng-click="updateData(truckform)" ng-show="updateBtn"  class="btn btn-primary center-block">
                                <span class="fa fa-download"></span>
                                Update
                            </button>
                        </td>
                        <td colspan="2"> </td>
                    </tr>

                   <tr>
                       <td colspan="2"></td>
                       <td class="text-center" colspan="3">

                           <div id="success" class="col-md-12 alert alert-success" ng-show="successMsg">
                               Successfully @{{ successMsgTxt }}!
                           </div>

                           <div id="error" class="col-md-12 alert alert-warning" ng-show="errorMsg">
                                @{{ errorMsgTxt }}!
                           </div>
                       </td>
                       <td colspan="1"> </td>
                   </tr>
                </table>
                </form>
</code>```

答:
Here you do not need to bind keypress events for input, by default in forms if you have buttons and if you hit enter, it will trigger the first button's click event,
if you have button's type as submit and if you hit enter when you are inside any of your input it will trigger form submit automatically. The example as like below.

I edited my original answer and now it acts as tab when you press enter key. Here is the working fiddle

```<code><body class="container" ng-app="myApp">
<div ng-controller="myCtrl">
    <form name="truckForm" ng-submit="submit(truckForm.$valid)" class="form-horizontal container" enter-to-tab>
        <div class="form-group">
            <label for="firstname">First Name</label>
            <input type="text" name="firstname"/>
        </div>
        <div class="form-group">
            <label for="lastname">Last Name</label>
            <input type="text" name="lastname"/>
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" name="email"/>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" name="password"/>
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password</label>
            <input type="confirm_password" name="confirm_password"/>
        </div>
        <button type="submit" class="btn btn-default">{{btnFlag}}</button>
    </form>
</div>
</body>
</code>```

and in your controller

```<code>    angular.module('myApp', [])
        .controller('myCtrl', myCtrl)
        .directive('enterToTab', enterToTab);

    myCtrl.$inject = ['$scope'];

    function myCtrl($scope) {
        $scope.updateBtn = true;
        $scope.submit = submit;

        function submit(valid) {
            console.log('hi', valid);
            if ($scope.updateBtn && valid) {
                updateData(/* your params if any */);
            } else if (valid) {
                saveData(/* your params if any */);
            }
        }

        function saveData(/* your params if any */) {
            console.log('save');
            // do your save action here
        }

        function updateData(/* your params if any */) {
            console.log('update');
            // do your update action here
        }
    }

    function enterToTab() {
        return {
            restrict: 'A',
            link: function(scope, attrs, element) {
                var elm = angular.element(element.$$element[0]);
                var inputs = angular.element('input', elm);
                var length = inputs.length - 1;
                var submit = angular.element('button[type=submit]', elm);
                inputs.on('keydown', function(e) {
                    if (e.which === 13) {
                        e.preventDefault();
                        var index = inputs.index(this);
                        if (index === length && submit.length) {
                            submit.focus();
                        } else if(index === length) {
                            inputs[0].focus();
                        } else {
                            inputs[index + 1].focus();
                        }
                    }
                })
            }
        };
    }
</code>```

Here type="submit" for button is important. And avoid any jquery like dom manipulations when you are developing an angularjs application, so I made it in angular way of doing this with directive. I have added enter-to-tab in form tag at HTML

Body:
I have a view where there are two buttons. one for save and another for update.: I want to use enter key as tab. If it reaches last input and find button, the form will be submitted (ng-click function will be triggered). Is it possible to do with two button or i should rely on only one button?

I tried:

     $('#truckform input ,#truckform button').on("keypress", function(e) {
                 // ENTER PRESSED
                if (e.keyCode == 13) {

                    console.log('tag')
                   // FOCUS ELEMENT
                    var inputs = $(this).parents("form").eq(0).find(":input");
                    var idx = inputs.index(this);
console.log(idx)

                    console.log(inputs.length)
                    if (idx == inputs.length - 1) {
                        inputs[0].select()
                    } else {
                        inputs[idx + 1].focus(); //  handles submit buttons
                        inputs[idx + 1].select();
                    }
                    return false;
                }
            });

I gives the error in console when button gets focus:

Uncaught TypeError: inputs[(idx + 1)].select is not a function
at HTMLInputElement.<anonymous> (truckEntry.js:56)
at HTMLInputElement.dispatch (jquery-2.2.3.min.js:3)
at HTMLInputElement.r.handle (jquery-2.2.3.min.js:3)

But after the error, the saveData() function is triggered. But in the update mode, the updateData() is not triggered and the error remains all times till i press enter. How can i maake it functional? Any suggestion?
  My view:

  <form  name="truckform" id="truckform" novalidate>

 Truck Entry/Exit Form

                        Manifest No :

                            <input type="text" ng-pattern='/^[0-9]{1,10}[/]{1}([0-9]{1,2}|[(A|a)]{1})$/' required="required" ng-disabled="disbleManifestNoInpForEditMode"  ng-model="ManifestNo" name="ManifestNo" id="Manifest_no" class="form-control input-sm" placeholder="Manifest No.">

                                Input like: 256/12 Or 256/A

                              Manifest No is required

                            Manifest is full

                          Manifest Date :

                            <input type="text"  ng-model="manifest_date" required="required" name="manifest_date" id="manifest_date" class="form-control datePicker input-sm" placeholder="Manifest date">

                            Select a date

                         Goods Name :

                           {{-- <select class="form-control input-sm" name="goods_id" ng-model="goods_id"
                                    ng-options="good.id as good.id +'-'+good.cargo_name group by good.category for good in allGoodsData ">

                                <option value="" selected="selected">Select Goods Name</option>
                            </select>

                             Select at least one goods
                            --}}

                            <tags-input ng-model="goods_id"
                                        display-property="cargo_name"
                                        placeholder="Add New Item"
                                        replace-spaces-with-dashes="false"
                                        add-from-autocomplete-only="true"
                                        on-tag-added="tagAdded($tag)"
                                        on-tag-removed="tagRemoved($tag)">

                                <auto-complete source="loadGoods($query)"
                                               min-length="0"
                                               debounce-delay="0"
                                               max-results-to-show="10">

                                </auto-complete>

                            </tags-input>
                            Choose at least one goods!

                        Truck Type :

                            <input type="text" ng-model="truck_type" name="truck_type" id="truck_type" class="form-control input-sm" value="{{old('truck_type')}}"  placeholder="Truck Type">

                             Truck Type is required

                          Truck No :

                            <input type="number" min="1" required="required" ng-model="truck_no" name="truck_no" id="truckNo" class="form-control input-sm" placeholder="Truck No" value="{{old('truck_no')}}">

                             Truck No is required

                        Driver Card No :

                            <input type="number" ng-model="driver_card" name="DriverCardNo" id="DriverCardNo" class="form-control input-sm" placeholder="Driver Card No." value="{{old('DriverCardNo')}}">

                             Driver Card No. is required

                          Weight Bridge:

                                <input type="radio" name="fff" ng-init="weightment_flag=1"  ng-model="weightment_flag" ng-checked="true"  value="1">Yes

                                <input type="radio"  ng-model="weightment_flag"  value="0" >No

                         Driver Name :

                           <input type="text" ng-model="driver_name" name="DriverName" id="driverName" class="form-control input-sm" placeholder="Driver Name" value="{{old('DriverName')}}">

                             Driver Name is required

                            <button type="button" ng-click="saveData(truckform)" ng-hide="updateBtn" class="btn btn-primary btn-block center-block">

                                Save
                            </button>
                            <button type="button" ng-click="updateData(truckform)" ng-show="updateBtn"  class="btn btn-primary center-block">

                                Update
                            </button>

                               Successfully @{{ successMsgTxt }}!

                                @{{ errorMsgTxt }}!

                </form>

Body:
Here you do not need to bind keypress events for input, by default in forms if you have buttons and if you hit enter, it will trigger the first button's click event,
if you have button's type as submit and if you hit enter when you are inside any of your input it will trigger form submit automatically. The example as like below.

I edited my original answer and now it acts as tab when you press enter key. Here is the working fiddle

<body class="container" ng-app="myApp">
<div ng-controller="myCtrl">
    <form name="truckForm" ng-submit="submit(truckForm.$valid)" class="form-horizontal container" enter-to-tab>
        <div class="form-group">
            <label for="firstname">First Name</label>
            <input type="text" name="firstname"/>
        </div>
        <div class="form-group">
            <label for="lastname">Last Name</label>
            <input type="text" name="lastname"/>
        </div>
        <div class="form-group">
            <label for="email">Email</label>
            <input type="email" name="email"/>
        </div>
        <div class="form-group">
            <label for="password">Password</label>
            <input type="password" name="password"/>
        </div>
        <div class="form-group">
            <label for="confirm_password">Confirm Password</label>
            <input type="confirm_password" name="confirm_password"/>
        </div>
        <button type="submit" class="btn btn-default">{{btnFlag}}</button>
    </form>
</div>
</body>

and in your controller

    angular.module('myApp', [])
        .controller('myCtrl', myCtrl)
        .directive('enterToTab', enterToTab);

    myCtrl.$inject = ['$scope'];

    function myCtrl($scope) {
        $scope.updateBtn = true;
        $scope.submit = submit;

        function submit(valid) {
            console.log('hi', valid);
            if ($scope.updateBtn && valid) {
                updateData(/* your params if any */);
            } else if (valid) {
                saveData(/* your params if any */);
            }
        }

        function saveData(/* your params if any */) {
            console.log('save');
            // do your save action here
        }

        function updateData(/* your params if any */) {
            console.log('update');
            // do your update action here
        }
    }

    function enterToTab() {
        return {
            restrict: 'A',
            link: function(scope, attrs, element) {
                var elm = angular.element(element.$$element[0]);
                var inputs = angular.element('input', elm);
                var length = inputs.length - 1;
                var submit = angular.element('button[type=submit]', elm);
                inputs.on('keydown', function(e) {
                    if (e.which === 13) {
                        e.preventDefault();
                        var index = inputs.index(this);
                        if (index === length && submit.length) {
                            submit.focus();
                        } else if(index === length) {
                            inputs[0].focus();
                        } else {
                            inputs[index + 1].focus();
                        }
                    }
                })
            }
        };
    }

Here type="submit" for button is important. And avoid any jquery like dom manipulations when you are developing an angularjs application, so I made it in angular way of doing this with directive. I have added enter-to-tab in form tag at HTML


问:
Determine the fastest unsigned integer type for basic arithmetic calculations
I'm writing some code for calculating with arbitrarily large unsigned integers. This is just for fun and training, otherwise I'd use libgmp. My representation uses an array of unsigned integers and for chosing the "base type", I use a typedef:

```<code>#include <limits.h>
#include <stdint.h>

typedef unsigned int hugeint_Uint;

typedef struct hugeint hugeint;

#define HUGEINT_ELEMENT_BITS (CHAR_BIT * sizeof(hugeint_Uint))
#define HUGEINT_INITIAL_ELEMENTS (256 / HUGEINT_ELEMENT_BITS)

struct hugeint
{
    size_t s;         // <- maximum number of elements
    size_t n;         // <- number of significant elements
    hugeint_Uint e[]; // <- elements of the number starting with least significant
};
</code>```

The code is working fine, so I only show the part relevant to my question here.

I would like to pick a better "base type" than unsigned int, so the calculations are the fastest possible on the target system (e.g. a 64bit type when targeting x86_64, a 32bit type when targeting i686, an 8bit type when targeting avr_attiny, ...)

I thought that uint_fast8_t should do what I want. But I found out it doesn't, see e.g. here the relevant part of stdint.h from MinGW:

```<code>/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef signed char int_fast8_t;
typedef unsigned char uint_fast8_t;
</code>```

The comment is interesting: for which purpose would an unsigned char be faster than an unsigned int on win32? Well, the important thing is: uint_fast8_t will not do what I want.

So is there some good and portable way to find the fastest unsigned integer type?

答:
It's not quite that black and white; processors may have different/specialized registers for certain operations, like AVX registers on x86_64, may operate most efficiently on half-sized registers or not have registers at all. The choice of the "fastest integer type" thus depends heavily on the actual calculation you need to perform.

Having said that, C99 defines uintmax_t which is meant to represent the maximum width unsigned integer type, but beware, it could be 64 bit simply because the compiler is able to emulate 64-bit math.

If you target commodity processors, size_t usually provides a good approximation for the "bitness" of the underlying hardware because it is directly tied to the memory addressing capability of the machine, and as such is most likely to be the most optimal size for integer math.

In any case you're going to have to test your solution on all hardware that you're planning to support.

Body:
I'm writing some code for calculating with arbitrarily large unsigned integers. This is just for fun and training, otherwise I'd use libgmp. My representation uses an array of unsigned integers and for chosing the "base type", I use a typedef:

#include <limits.h>
#include <stdint.h>

typedef unsigned int hugeint_Uint;

typedef struct hugeint hugeint;

#define HUGEINT_ELEMENT_BITS (CHAR_BIT * sizeof(hugeint_Uint))
#define HUGEINT_INITIAL_ELEMENTS (256 / HUGEINT_ELEMENT_BITS)

struct hugeint
{
    size_t s;         // <- maximum number of elements
    size_t n;         // <- number of significant elements
    hugeint_Uint e[]; // <- elements of the number starting with least significant
};

The code is working fine, so I only show the part relevant to my question here.

I would like to pick a better "base type" than unsigned int, so the calculations are the fastest possible on the target system (e.g. a 64bit type when targeting x86_64, a 32bit type when targeting i686, an 8bit type when targeting avr_attiny, ...)

I thought that uint_fast8_t should do what I want. But I found out it doesn't, see e.g. here the relevant part of stdint.h from MinGW:

/*  7.18.1.3  Fastest minimum-width integer types
 *  Not actually guaranteed to be fastest for all purposes
 *  Here we use the exact-width types for 8 and 16-bit ints.
 */
typedef signed char int_fast8_t;
typedef unsigned char uint_fast8_t;

The comment is interesting: for which purpose would an unsigned char be faster than an unsigned int on win32? Well, the important thing is: uint_fast8_t will not do what I want.

So is there some good and portable way to find the fastest unsigned integer type?


问:
Is it good practice to unit test properties?
I'm still getting to grips with the whole TDD concept. Should I be writing tests for properties? Should one only write tests on properties containing sufficient logic? Any thoughts or examples on this would be great.</p>

答: Test things that have a reasonable chance of failure - you gain no extra confidence by testing properties with no logic beyond get/set.</p>


问:
Prevent form from showing multiple times
In windows form (c#), i am showing a form when user click on button, it is working fine form is visible to user, but if user click again on the same button the same form is opening again two forms are displaying. Is there any way to prevent this, please give me any reference for this thank you. This is my code....</p>

```<code>private void button1_Click(object sender, EventArgs e)
{
  Form2 obj = new Form2();
  obj.Show();
}
</code>```

答:
```<code>foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(MyFormType))
    {
        form.Activate();
        return;
    }
}

Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();
</code>```

i tried more than a ways to compare which one is better.

but i think this solution must be better than the answer.

Body:
In windows form (c#), i am showing a form when user click on button, it is working fine form is visible to user, but if user click again on the same button the same form is opening again two forms are displaying. Is there any way to prevent this, please give me any reference for this thank you. This is my code....

private void button1_Click(object sender, EventArgs e)
{
  Form2 obj = new Form2();
  obj.Show();
}

Body:
foreach (Form form in Application.OpenForms)
{
    if (form.GetType() == typeof(MyFormType))
    {
        form.Activate();
        return;
    }
}

Form newForm = new MyFormType();
newForm.MdiParent = this;
newForm.Show();

i tried more than a ways to compare which one is better.

but i think this solution must be better than the answer.


问:
Xcode 8.2.1 Accessibility Inspector not working with iOS 9 devices
I have an iPhone 6 running iOS 9.3.3 that I've been using for development for quite a while not and have no issues deploying my code on it and debugging with Xcode 8.2.1.  The Accessibility Inspector has a "(not setup)" next to this iPhone in the drop down list to select the item to inspect.  If I pick the device it puts up an alert that says:

Device Not Setup

This device must be setup for development using Xcode.

I am very confused by this message because I am able to deploy and debug on it.  I see nothing in Xcode about needing any additional setup for the device.

I have another team member whose iOS 9.x.x devices are experiencing the same issue.  I am beginning to wonder if it has something to do with the iOS version being 9.x.  Unfortunately we can't upgrade these devices to iOS 10 at this time.  Also I have no issues with another device I have for development that is running iOS 10.

Is there a compatibility issue between the Accessibility Inspector in Xcode 8.2.1 and iOS 9.x devices?

答:
I have the same issue by xcode version 8.3.2 (actually all of versions by 8.x.x have problem) and ios 9  and ios 10

I am not sure what was your need and actually I see you have asked your question a long time ago; But I am writing another way to access frame of view and its constraints if you or another developers have this peoblem;

I have run app on device and goes to a view.
At the top of debug area there is a tool bar contains the breakpoint, continue, stop over and ...

From tools select Debug View Hierarchy

After a while you can see the iphone screen and by left click on a view and choosing Print Description of ... you can see the frame and constraints of UIView


问:
Stream over a List of Map and collect specific key
This is my List:

```<code>[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];
</code>```

I want to pluck name values and create another List like this:

```<code>["moe", "larry", "curly"]
</code>```

I've written this code and it works:

```<code>List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}
</code>```

But how to do it in using stream. I've tried this code which doesn't work.

```<code>List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
</code>```

答:
Since your List appears to be a List<Map<String,Object>, your stream pipeline would produce a List<Object>:

```<code>List<Object> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());
</code>```

Or you could cast the value to String if you are sure you are going to get only Strings:

```<code>List<String> newList = list.stream().map(x -> (String)x.get("name")).collect(Collectors.toList());
</code>```

Body:
This is my List:

[
    {name: 'moe', age: 40},
    {name: 'larry', age: 50},
    {name: 'curly', age: 60}
];

I want to pluck name values and create another List like this:

["moe", "larry", "curly"]

I've written this code and it works:

List<String> newList = new ArrayList<>();
for(Map<String, Object> entry : list) {
    newList.add((String) entry.get("name"));
}

But how to do it in using stream. I've tried this code which doesn't work.

List<String> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

Body:
Since your List appears to be a List<Map<String,Object>, your stream pipeline would produce a List<Object>:

List<Object> newList = list.stream().map(x -> x.get("name")).collect(Collectors.toList());

Or you could cast the value to String if you are sure you are going to get only Strings:

List<String> newList = list.stream().map(x -> (String)x.get("name")).collect(Collectors.toList());


问:
why int.TryParse cannot initialise multiple variables
I am using int.TryParse to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:

```<code>int min,
    max;
</code>```

using the following conditional statement:

```<code>bool lengthCompatible = int.TryParse(string1, out min) &&
                        int.TryParse(string2, out max);
</code>```

Visual Studio (2015) produces the following code highlighting:

Use of unassigned local variable 'max'

Local variable 'max' might not be initialized before accessing

However, if I use 2 conditional statements:

```<code>bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);
</code>```

I can compile with no errors.

Curiouser and curiouser! Any insight appreciated.

Cheers

答:
Because if the first int.TryParse(string1, out min) returns false, the second int.TryParse(string2, out max) will not be executed due to boolean short-circuiting.

In that case, max will not have been initialised.

You could just initialise max and min to zero:

```<code>int min = 0,
    max = 0;

...

bool lengthCompatible = int.TryParse(string1, out min) && int.TryParse(string2, out max);
</code>```

Or only use the max and min after checking the result of the && as per other answers.

Body:
I am using int.TryParse to parse to variables (saved as strings in the database) and am curious why I cannot initialise 2 variables:

int min,
    max;

using the following conditional statement:

bool lengthCompatible = int.TryParse(string1, out min) &&
                        int.TryParse(string2, out max);

Visual Studio (2015) produces the following code highlighting:

Use of unassigned local variable 'max'

Local variable 'max' might not be initialized before accessing

However, if I use 2 conditional statements:

bool minParse = int.TryParse(sentenceType.MinimumLength, out min);
bool maxParse = int.TryParse(sentenceType.MaximumLength, out max);

I can compile with no errors.

Curiouser and curiouser! Any insight appreciated.

Cheers

Body:
Because if the first int.TryParse(string1, out min) returns false, the second int.TryParse(string2, out max) will not be executed due to boolean short-circuiting.

In that case, max will not have been initialised.

You could just initialise max and min to zero:

int min = 0,
    max = 0;

...

bool lengthCompatible = int.TryParse(string1, out min) && int.TryParse(string2, out max);

Or only use the max and min after checking the result of the && as per other answers.


问:
When to use the CQRS design pattern?
My team and I have been discussing using the CQRS (Command Query Responsibility Segregation) design pattern and we are still trying to asses the pros and cons of using it. According to: http://martinfowler.com/bliki/CQRS.html

we haven't seen enough uses of CQRS in the field yet to be confident
  that we understand its pros and cons

So what do you guys think, when does a problem call for using CQRS?

答:
In real world scenario CQRS might be useful when you have front end/web service client which needs lots of data from multiple domains and retrieval of these data from database takes long time.

In such case you might consider creation of separate read model which will be faster to develop and might have faster execution time.

Title: When to use the CQRS design pattern?


问:
es6 arrow function
I would test this in browser

```<code>let foo = () => ({ bar: 2 })
</code>```

But accidentally typed

```<code>let foo = () => { bar: 2}
</code>```

Why didn't throw an error?

答:
In the second case, bar is a label. See: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/label

"2" is a valid statement in itself.

Title: es6 arrow function

Body:
I would test this in browser

let foo = () => ({ bar: 2 })

But accidentally typed

let foo = () => { bar: 2}

Why didn't throw an error?


答:
Well you're using &&, which is short-circuiting... if int.TryParse(string1, out min) returns false, the second call to int.TryParse won't be made, so max isn't definitely assigned.

You could write:

```<code>if (int.TryParse(string1, out min) &&
    int.TryParse(string2, out max))
{
    // Use min and max here
}
</code>```

... because then the compiler knows that you only reach the body of the if statement if both calls have been executed.

Alternatively you could use the non-short-circuiting version with & instead of &&:

```<code>bool lengthCompatible = int.TryParse(string1, out min) &
                        int.TryParse(string2, out max);
</code>```

That's slightly unusual though. The advantage of the if version above is that you'll retain the performance benefit of &&, in that you won't bother trying to parse string2 if you don't need to. (It depends on exactly what you're trying to do, of course.)

Title: why int.TryParse cannot initialise multiple variables

Body:
Well you're using &&, which is short-circuiting... if int.TryParse(string1, out min) returns false, the second call to int.TryParse won't be made, so max isn't definitely assigned.

You could write:

if (int.TryParse(string1, out min) &&
    int.TryParse(string2, out max))
{
    // Use min and max here
}

... because then the compiler knows that you only reach the body of the if statement if both calls have been executed.

Alternatively you could use the non-short-circuiting version with & instead of &&:

bool lengthCompatible = int.TryParse(string1, out min) &
                        int.TryParse(string2, out max);

That's slightly unusual though. The advantage of the if version above is that you'll retain the performance benefit of &&, in that you won't bother trying to parse string2 if you don't need to. (It depends on exactly what you're trying to do, of course.)