问:
Virtual method with variadic arguments
I am trying to implement a logging system abstracted behind a locator service (in the style of this guide) in such a way that the logging system can be subclassed for various different logging situations. I would prefer to be able to use printf style format strings instead of <<, but that means supporting variable number of arguments. Variadic templates can easily solve this, however, they cannot be virtual, which means that the base logging class cannot be abstract (as an interface).

Ideally what I'd need is some way to have the parent method not templated but just accepting of a parameter pack which it would forward to the right (templated) child method. I've mostly seen two ways of doing this, one which is using va_list which apparently is unsafe, complicated and not really meant to interact with variadic templates easily, and CRTP, which would work but means that no pointer can be declared of the abstract base class in the locator object without knowing the subclass type, which defeats the purpose.

Here is example code assuming that virtual templates were a thing:

```<code>class Logger
{
    public:
        template <typename ... Args>
        virtual void print(char *filename, int line, std::string &&msg, Args&& ... args) = 0;

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }

};

class PrintLogger : public Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};
</code>```

Here is example code with the CRTP solution (which breaks the locator):

```<code>template <typename Loggertype>
class Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            Loggertype::print(filename, line, msg, args...);
        }

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }

};

class PrintLogger : public Logger<PrintLogger>
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};
</code>```

And here is the locator:

```<code>class Global {
    public:
        static void initialize() { logger = nullptr; }
        static Logger& logging()
        {
            if (logger == nullptr)
            {
                throw new std::runtime_error("Attempt to log something before a logging instance was created!");
            }
            return *logger;
        }
        static void provide_logging(Logger *new_logger) { logger = new_logger; }
    private:
        static Logger *logger;
};
</code>```

答:
You have to handle 2 issue:

iterate on packed argument

Call a virtual function with template argument.

The first issue you need is handle by recursion function
The second I used with boost::any

```<code>class Logger
{
public:

    template <typename ... Args>
    std::string print(Args&& ... args)
    {
        start_format();
        interate_on(args...);
        return end_format();
    }
protected:

    template <typename Arg>
    void interate_on(Arg&& arg)
    {
        print(arg);
    }

    template <typename Arg, typename ... Args>
    void interate_on(Arg&& arg, Args&& ... args)
    {
        print(arg);
        interate_on(std::forward<Args>(args)...);
    }

    virtual void start_format() = 0;

    virtual std::string end_format() = 0;

    virtual void print(boost::any& value) = 0;
};

class PrinterLogger : public Logger
{
protected:
    virtual void start_format()
    {

    }

    virtual std::string end_format()
    {
        return std::string();
    }

    virtual void print(boost::any& value)
    {
        // accumulate printf

    }
};
</code>```

Title: Virtual method with variadic arguments

Body:
I am trying to implement a logging system abstracted behind a locator service (in the style of this guide) in such a way that the logging system can be subclassed for various different logging situations. I would prefer to be able to use printf style format strings instead of <<, but that means supporting variable number of arguments. Variadic templates can easily solve this, however, they cannot be virtual, which means that the base logging class cannot be abstract (as an interface).

Ideally what I'd need is some way to have the parent method not templated but just accepting of a parameter pack which it would forward to the right (templated) child method. I've mostly seen two ways of doing this, one which is using va_list which apparently is unsafe, complicated and not really meant to interact with variadic templates easily, and CRTP, which would work but means that no pointer can be declared of the abstract base class in the locator object without knowing the subclass type, which defeats the purpose.

Here is example code assuming that virtual templates were a thing:

class Logger
{
    public:
        template <typename ... Args>
        virtual void print(char *filename, int line, std::string &&msg, Args&& ... args) = 0;

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }

};

class PrintLogger : public Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

Here is example code with the CRTP solution (which breaks the locator):

template <typename Loggertype>
class Logger
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            Loggertype::print(filename, line, msg, args...);
        }

    protected:
        template <typename ... Args>
        std::string format(char *filename, int line, std::string &msg, Args&& ... args)
        {
            std::string output = "%s at line %i: " + msg;
            int size = std::snprintf(nullptr, 0, output.c_str());
            // +1 for null termination
            std::vector<char> buf(size + 1);
            std::snprintf(&buf[0], buf.size(), output.c_str(), filename, line, args...);
            return std::string(&buf[0]);
        }

};

class PrintLogger : public Logger<PrintLogger>
{
    public:
        template <typename ... Args>
        void print(char *filename, int line, std::string &&msg, Args&& ... args)
        {
            std::cout << format(filename, line, msg, args...);
        }
};

And here is the locator:

class Global {
    public:
        static void initialize() { logger = nullptr; }
        static Logger& logging()
        {
            if (logger == nullptr)
            {
                throw new std::runtime_error("Attempt to log something before a logging instance was created!");
            }
            return *logger;
        }
        static void provide_logging(Logger *new_logger) { logger = new_logger; }
    private:
        static Logger *logger;
};

Body:
You have to handle 2 issue:

iterate on packed argument

Call a virtual function with template argument.

The first issue you need is handle by recursion function
The second I used with boost::any

class Logger
{
public:

    template <typename ... Args>
    std::string print(Args&& ... args)
    {
        start_format();
        interate_on(args...);
        return end_format();
    }
protected:

    template <typename Arg>
    void interate_on(Arg&& arg)
    {
        print(arg);
    }

    template <typename Arg, typename ... Args>
    void interate_on(Arg&& arg, Args&& ... args)
    {
        print(arg);
        interate_on(std::forward<Args>(args)...);
    }

    virtual void start_format() = 0;

    virtual std::string end_format() = 0;

    virtual void print(boost::any& value) = 0;
};

class PrinterLogger : public Logger
{
protected:
    virtual void start_format()
    {

    }

    virtual std::string end_format()
    {
        return std::string();
    }

    virtual void print(boost::any& value)
    {
        // accumulate printf

    }
};


来源: stackexchange

问:
How to mantain a JVM pointer in a DllMain call and prevent call JNI_CreateJavaVM twice
I'm loading a DLL and another program call a function I created. This function I made calls some java functions via JNI.

PS: I don't have the control of the DLL method call, it is called my another program.

When I create the JVM I do it with: JNI_CreateJavaVM.

After calling JNI methods I destroy the JVM with:
JNI_DestroyJVM().

The problem is that when the function in DLL is called, I create the JVM. But if the JVM is already loaded if fails becasuse of the following problem:

The problem:
Re-calling JNI_CreateJavaVM returns -1 after calling DestroyJavaVM

I know I can't call the JNI_CreateJavaVM twice because:
JNI_DestroyJVM(), it said "The JDK/JRE still does not support VM unloading, however." Just don't call it, and don't re-initialize it either.

1 - Why The JVM is still loaded in the memory after the DLL_PROCESS_DETACH?

2 - Is there a way to store a global variable in the DllMain?
Maybe I could store the (JavaVM *jvm); pointer, and not destroy the jvm after the dll call, so it would be destroyed when the process that call the dll is destroyed.

As I don't have the main program, I just have the DLL call, I can't store a global variable because the DLL_PROCESS_DETACH deletes every variable I created before.

答:
Do not call JNI_DestroyJVM if you wish to run Java code more than once during the process lifecycle. Call DetachCurrentThread instead.

Before calling JNI_CreateJavaVM make sure JVM is not already created. Use JNI_GetCreatedJavaVMs to get an instance of the loaded JVM, then AttachCurrentThread to get JNIEnv* handle.

ContentLicense: CC BY-SA 3.0


问:
SQL group by multiple columns but give one range value in clause
There is a PostgreSQL statement where multiple fields are selected and should be grouped.

```<code>select Max(field1),field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11
from table2
group by field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11
</code>```

Can I group by this query without giving all field names in group by clause? Something like

```<code>select Max(field1),field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11
from table2
group by [2-12]
</code>```

答:
Postgres allows you to use numbers as column references, but not ranges.  So, you can do:</p>

```<code>select Max(field1), field1, field2, field3, field4, field5, field6,
       field7, field8, field9,field10, field11
from table2
group by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;
</code>```

Body:
There is a PostgreSQL statement where multiple fields are selected and should be grouped.

select Max(field1),field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11
from table2
group by field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11

Can I group by this query without giving all field names in group by clause? Something like

select Max(field1),field1,field2,field3,field4,field5,field6,field7,field8,field9,field10, field11
from table2
group by [2-12]

Body:
Postgres allows you to use numbers as column references, but not ranges.  So, you can do:

select Max(field1), field1, field2, field3, field4, field5, field6,
       field7, field8, field9,field10, field11
from table2
group by 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12;


问:
VBA - split cells with value like =31+44-756+688-7433-899 into multiple cels
I have cells with formulas like below.

```<code>=31+44-756+688-7433-899
</code>```

Need a macro or an approach, using which I can separate the numbers into diff cells.

And shuld be like:

```<code>31, 44, -756, 688, -7433, -899.
</code>```

I can't use split as split can be used for only one delimiter.

答:
You can fool it:</p>

```<code>Dim strng As String
strng = "31+44-756+688-7433-899"

Dim numbers As Variant
numbers = Split(Replace(strng, "-", "+-"), "+")

Range("A1").Resize(UBound(numbers) + 1). Value = Application.Transpose(numbers)
</code>```

Body:
I have cells with formulas like below.

=31+44-756+688-7433-899

Need a macro or an approach, using which I can separate the numbers into diff cells.

And shuld be like:

31, 44, -756, 688, -7433, -899.

I can't use split as split can be used for only one delimiter.

Body:
You can fool it:

Dim strng As String
strng = "31+44-756+688-7433-899"

Dim numbers As Variant
numbers = Split(Replace(strng, "-", "+-"), "+")

Range("A1").Resize(UBound(numbers) + 1). Value = Application.Transpose(numbers)


问:
What's the best way to map the main urls in a django project?
I've got a django project that contain some apps.  The main urls.py includes the urls.py from the apps I've enabled, and all is good.

Now I want to configure the project so that when you go to http://testsite/, you'll get the same page that you get when you go to http://testsite/app/.

I can do this by duplicating the corresponding line in the apps urls.py in the projects urls.py, but this feels dirty.

Anyone know a better way?

答: A redirect is the way to go, because you don't want multiple canonical URLs for the same resource (wastes Google juice).  Ideally, you should do the redirect as close to the edge of your stack as possible to conserve server resources.  So you can do a Django redirect_to urlconf entry, but you'd be better off with an Apache or nginx or insert-your-webserver-here redirect, so the initial request never has to hit Django at all.</p>

OwnerDisplayName: Alf

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Carl Meyer


问:
Xcode derived data path error
I'm getting this error after adding a WatchKit extension to my app:

```<code>PBXCp DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app DerivedData/App/Build/Products/Debug/App.app/Watch/appwatch.app
    cd /Users/User/Documents/App-watchapp
    export PATH="/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    builtin-copy -exclude .DS_Store -exclude CVS -exclude .svn -exclude .git -exclude .hg -resolve-src-symlinks /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug/App.app/Watch

error: /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app: No such file or directory
</code>```

I've tried changing the path of the derived data folder, cleaning, deleting then re-adding the extension, and nothing has worked.

答:
Do you build with xcode or xcodebuild cli?
With xcodebuild I get almost the same error.
But when I exchange CONFIGURATION_BUILD_DIR with SYMROOT the error is gone and I can build and archive.</p>

Title: Xcode derived data path error

Body:
I'm getting this error after adding a WatchKit extension to my app:

PBXCp DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app DerivedData/App/Build/Products/Debug/App.app/Watch/appwatch.app
    cd /Users/User/Documents/App-watchapp
    export PATH="/Applications/Xcode-beta.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/usr/bin:/Applications/Xcode-beta.app/Contents/Developer/usr/bin:/usr/bin:/bin:/usr/sbin:/sbin"
    builtin-copy -exclude .DS_Store -exclude CVS -exclude .svn -exclude .git -exclude .hg -resolve-src-symlinks /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug/App.app/Watch

error: /Users/User/Documents/App-watchapp/DerivedData/App/Build/Products/Debug-watchsimulator/appwatch.app: No such file or directory

I've tried changing the path of the derived data folder, cleaning, deleting then re-adding the extension, and nothing has worked.


问:
Structuring a multi-dimensional object with varying data
I have three functions which create three objects, firstPayment, interimPayment and finalPayment

firstPayment will always have data. But interimPayment shouldn't always be used, same finalPayment.

The signifier that interimPayment or finalPayment isn't needed is based on another variable numberOfPayments.

If numberOfPayments === 1 then only firstPayment will have data. If numberOfPayments === 2 then both firstPayment and finalPayment are needed. And finally if numberOfPayments > 2 then all three payment objects are needed.

I'm trying to work out how to add all these objects to another object paymentSchedule based on the numberOfPayments variable.

Here's my start on the code but I'm a bit lost!

```<code>  getPaymentSchedule(id) {
    const firstPayment = this.getFirstPayment(id);
    const numberOfPayments = this.getNumberOfPayments(id);

    if (numberOfPayments === 2) {
      const finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
      const interimPayments = this.getInterimPayments(id);
    }
  }
</code>```

This is where I'm a bit stuck. I need to add the three objects firstPayment, getInterimPayments and finalPayment in that order, but obviously only if they have been set. I feel like I could do this some quicker way than lots and lots of if statements.

Example of paymentSchedule I am trying to achieve:

```<code>{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    interimPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

or

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}
</code>```

答:
You could use an array with objects. The array reflects the order and the objects.

```<code>[
    {                              // exists always
        name: 'firstPayment',
        label: 'foo',
        amount: 123
    },
    {                              // numberOfPayments > 2
        name: 'interimPayment',
        label: 'foo',
        amount: 123
    },
    {                              // numberOfPayments > 1
        name: 'finalPayment',
        label: 'foo',
        amount: 123
    }
]
</code>```

To generate, you could use something like this

```<code>var schedule = [].concat(
        this.getFirstPayment(id)
        numberOfPayments > 2 ? this.getInterimPayments(id) : [],
        numberOfPayments > 1 ? this.getFinalPayment(id) : []
    );
</code>```

This generates an array with the wanted payment date.

Body:
I have three functions which create three objects, firstPayment, interimPayment and finalPayment

firstPayment will always have data. But interimPayment shouldn't always be used, same finalPayment.

The signifier that interimPayment or finalPayment isn't needed is based on another variable numberOfPayments.

If numberOfPayments === 1 then only firstPayment will have data. If numberOfPayments === 2 then both firstPayment and finalPayment are needed. And finally if numberOfPayments > 2 then all three payment objects are needed.

I'm trying to work out how to add all these objects to another object paymentSchedule based on the numberOfPayments variable.

Here's my start on the code but I'm a bit lost!

  getPaymentSchedule(id) {
    const firstPayment = this.getFirstPayment(id);
    const numberOfPayments = this.getNumberOfPayments(id);

    if (numberOfPayments === 2) {
      const finalPayment = this.getFinalPayment(id);
    } else if (numberOfPayments > 2) {
      const interimPayments = this.getInterimPayments(id);
    }
  }

This is where I'm a bit stuck. I need to add the three objects firstPayment, getInterimPayments and finalPayment in that order, but obviously only if they have been set. I feel like I could do this some quicker way than lots and lots of if statements.

Example of paymentSchedule I am trying to achieve:

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    interimPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

or

{
    firstPayment: {
        label: "foo",
        amount: 123
    },
    finalPayment: {
        label: "foo",
        amount: 123
    },
}

Body:
You could use an array with objects. The array reflects the order and the objects.

[
    {                              // exists always
        name: 'firstPayment',
        label: 'foo',
        amount: 123
    },
    {                              // numberOfPayments > 2
        name: 'interimPayment',
        label: 'foo',
        amount: 123
    },
    {                              // numberOfPayments > 1
        name: 'finalPayment',
        label: 'foo',
        amount: 123
    }
]

To generate, you could use something like this

var schedule = [].concat(
        this.getFirstPayment(id)
        numberOfPayments > 2 ? this.getInterimPayments(id) : [],
        numberOfPayments > 1 ? this.getFinalPayment(id) : []
    );

This generates an array with the wanted payment date.


问:
babel-jest doesn't handle ES6 within modules
I am trying to set up Jest on a React based project which uses ES6 modules. However I seem to be having issues with ES6 modules, I am using babel-jest and believe I have this set up properly (Jest detects it automatically).

Jest doesn't seem to have a problem using ES6 imports however as soon as it hits on an import statement within one of the imported modules it chokes. It's as if it is only transpiling the initial test script and not any of the imported modules. I have tried various configurations and tried searching Google with no luck. Running tests without any imports works fine.

Here is the error:

```<code>({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Predications from './predications';
                                                                                ^^^^^^
SyntaxError: Unexpected token import
</code>```

Here are the relevant bits of config:

jest.conf.json

```<code>{
  "testRegex": "\/test\/spec\/.*\\.js$",
}
</code>```

.babelrc

```<code>{
  "presets": ["es2015", "stage-0", "react"]
}
</code>```

Test script

```<code>import React from 'react';
import { mount, shallow } from 'enzyme';
import Slider from 'react-slick';
import Carousel from '../../client/components/carousel/carousel.js'; // test chokes on when I include this module

describe('carousel component', () => {
  it('is a test test case', () => {
    expect(1 + 2).toEqual(3);
  });
});
</code>```

Update:

As suggested, I have tried running the test without jest.conf.js, however the testRegex is needed in order for Jest to find my tests, I tried moving tests to the default test directory and they still fail.

I would like to clarify that tests themselves are running fine, the issue seems to be where one of my imported modules uses ES6, in my example above, if I don't import my carousel component the test runs fine, as soon as I import that the test chokes on the import statement within that file. It seems as though the imported modules are not getting transpiled.

Update #2

After some investigation it appears the issue is that babel is not transpiling ES6 within node_modules. I have created an example repo to demonstrate this here: https://github.com/jamiedust/babel-jest-example

I understand that third party modules should be handling their own transpiling, however we have a number of modules which are hosted on our own npm registry and are re-used between projects, in these cases Webpack handles transpiling, for the Jest tests we need these node_modules to be transpiled by Babel, or a way of leveraging our webpack set up to do this for us.

Solution

Add the following config in package.json (or Jest config file).

```<code>"jest": {
  "transformIgnorePatterns": [
    "/node_modules/(?!test-component).+\\.js$"
  ]
}
</code>```

答:
By default any code in node_modules is ignored by babel-jest, see the Jest config option transformIgnorePatterns. I've also created a PR on your example repo, so you can see it working.

While this works, I've found it to be extremely slow in real applications that have a lot of dependencies containing ES modules. The Jest codebase has a slightly different approach to this as you can find in babel-jest transforming dependencies. This can also take much longer on Windows, see Taking 10 seconds on an empty repo.

If doing "unit" testing, mocking is probably the better way to go.

Body:
I am trying to set up Jest on a React based project which uses ES6 modules. However I seem to be having issues with ES6 modules, I am using babel-jest and believe I have this set up properly (Jest detects it automatically).

Jest doesn't seem to have a problem using ES6 imports however as soon as it hits on an import statement within one of the imported modules it chokes. It's as if it is only transpiling the initial test script and not any of the imported modules. I have tried various configurations and tried searching Google with no luck. Running tests without any imports works fine.

Here is the error:

({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import Predications from './predications';
                                                                                ^^^^^^
SyntaxError: Unexpected token import

Here are the relevant bits of config:

jest.conf.json

{
  "testRegex": "\/test\/spec\/.*\\.js$",
}

.babelrc

{
  "presets": ["es2015", "stage-0", "react"]
}

Test script

import React from 'react';
import { mount, shallow } from 'enzyme';
import Slider from 'react-slick';
import Carousel from '../../client/components/carousel/carousel.js'; // test chokes on when I include this module

describe('carousel component', () => {
  it('is a test test case', () => {
    expect(1 + 2).toEqual(3);
  });
});

Update:

As suggested, I have tried running the test without jest.conf.js, however the testRegex is needed in order for Jest to find my tests, I tried moving tests to the default test directory and they still fail.

I would like to clarify that tests themselves are running fine, the issue seems to be where one of my imported modules uses ES6, in my example above, if I don't import my carousel component the test runs fine, as soon as I import that the test chokes on the import statement within that file. It seems as though the imported modules are not getting transpiled.

Update #2

After some investigation it appears the issue is that babel is not transpiling ES6 within node_modules. I have created an example repo to demonstrate this here: https://github.com/jamiedust/babel-jest-example

I understand that third party modules should be handling their own transpiling, however we have a number of modules which are hosted on our own npm registry and are re-used between projects, in these cases Webpack handles transpiling, for the Jest tests we need these node_modules to be transpiled by Babel, or a way of leveraging our webpack set up to do this for us.

Solution

Add the following config in package.json (or Jest config file).

"jest": {
  "transformIgnorePatterns": [
    "/node_modules/(?!test-component).+\\.js$"
  ]
}

ContentLicense: CC BY-SA 4.0


问:
Image loading speed
how to display image loading speed in html and JavaScript ? I have got image size and my internet speed then time also.But i don't know how can i get count value in parameter of putimage and how can i implement this code....</p>

```<code><html>
<script type="text/javascript">
function putImage( iterations, update )
{
       var index = 0,count = 0,
            timer = window.setInterval( check, 1000 ); //check every 1 seconds

//calculating size of the image....
            function getRandomString( sizeInMb )
                    {
                        var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789~!@#$%^&*()_+`-=[]\{}|;':,./<>?", //random data prevents gzip effect
                            iterations = sizeInMb * 1024 * 1024, //get byte count
                            result = '';
                        for( var index = 0; index < iterations; index++ )
                        {
                            result += chars.charAt( Math.floor( Math.random() * chars.length ) );
                        };
                        return result;
                    };

                                //showing file size....
                                if(window.ActiveXObject)
                                    {
                                        var fso = new ActiveXObject("Scripting.FileSystemObject");
                                        var filepath = document.getElementById('select_image').value;
                                        var thefile = fso.getFile(filepath);
                                        var sizeinbytes = thefile.size;
                                    }
                                else
                                    {
                                        var sizeinbytes = document.getElementById('select_image').files[0].size;
                                    }

                                // var fSExt = new Array('Bytes', 'KB', 'MB', 'GB');
                                var fSExt = 'KB';
                                fSize = sizeinbytes; i=0;
                                while(fSize>900)
                                {
                                    fSize/=1024;i++;
                                }
                                //alert((Math.round((fSize*100)/100)*1024)+' '+fSExt);  //showing total image size...

//calculating internet speed....
        var speed = 0;
        check();
        //alert("sss"+speed)
        function check()
        {
            var xhr = new XMLHttpRequest(),
                url = '?cache=' + Math.floor( Math.random() * 10000 ), //random number prevents url caching
                data = getRandomString( 1 ), //1 meg POST size handled by all servers
                startTime;
                speed;
                count;

            xhr.onreadystatechange = function ( event )
            {
                if( xhr.readyState == 4 )
                {
                    speed = Math.round( 1024 / ( ( new Date() - startTime ) / 1000 ) );
                     // alert(speed);
                    update( speed );
                    index++;
                    //return speed;
                    if( index == iterations )
                    {
                        window.clearInterval( timer );
                    };
                };
                            };
            //alert(speed);
            xhr.open( 'POST', url, true );
            startTime = new Date();
            xhr.send( data );
            //alert(speed);
            a=((Math.round((fSize*100)/100)*1024));  //showing total image size...
            //alert(a);
            count=a/speed;
            //alert(count);
            return count;
            //alert((Math.round((fSize*100)/100)*1024)+' '+fSExt);
        }
                /*showing image*/
                    var src = document.getElementById("select_image");
                    var target = document.getElementById("target");
                    showImage(src, target);
                    function showImage(src, target)
                    {
                        var fr = new FileReader();

                        fr.onload = function (e)
                        {
                            target.src = this.result;
                        };

                            fr.readAsDataURL(src.files[0]);
                    }

}
//alert(count);
putImage(count, function ( speed )
    {
         //document.getElementById( 'speed' ).textContent = 'speed: ' + speed + 'kbs';
        document.getElementById( 'speed' ).textContent = 'speed: ' + speed;
    } );
</script>
<body>
<div id="speed">speed: 0kbs</div>
<img id="target" />
<input type="file" id="select_image" name="image" onchange="putImage()"> </input>

</body>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
</html>
</code>```

答:
You can use this for showing the progress bar with percentage. For file size, you'll have to do simple calculations like if the file size is 5MB and uploaded percentage is 50% then just divide the file size by 2 and display the uploaded size: 2.5MB /5MB

$(document).ready(function() {
    var maxWidth = 400;
    var duration = 3000;
    var $log = $('#log');
    var $start = $('#start');
    var $stop = $('#stop');
    var timer;

    $start.on('click', function() {
        var $bar = $('#bar');
        Horloge(maxWidth);
        timer = setInterval('Horloge('+maxWidth+')', 100);

        $bar.animate({
            width: maxWidth
        }, duration, function() {
            $(this).css('background-color', 'green');
            $start.attr('disabled', true);
            $stop.attr('disabled', true);
            $log.html('100 %');
            clearInterval(timer);
        });
    });

    $stop.on('click', function() {
        var $bar = $('#bar');
        $bar.stop();

        clearInterval(timer);

        var w = $bar.width();
        var percent = parseInt((w * 100) / maxWidth);
        $log.html(percent + ' %');
    });

});

function Horloge(maxWidth) {
    var w = $('#bar').width();
    var percent = parseInt((w * 100) / maxWidth);
    $('#log').html(percent + ' %');
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
 margin:10px;
}
#bar {
    width:0px;
    height:25px;
    border:1px solid black;
    background-color:yellow;
    border-radius:3px;
}</code>```

<button id="start">Start</button>
<button id="stop">Stop</button>

```

Title: Image loading speed

Body:
how to display image loading speed in html and JavaScript ? I have got image size and my internet speed then time also.But i don't know how can i get count value in parameter of putimage and how can i implement this code....

speed: 0kbs

<input type="file" id="select_image" name="image" onchange="putImage()"> </input>

Body:
You can use this for showing the progress bar with percentage. For file size, you'll have to do simple calculations like if the file size is 5MB and uploaded percentage is 50% then just divide the file size by 2 and display the uploaded size: 2.5MB /5MB

$(document).ready(function() {
    var maxWidth = 400;
    var duration = 3000;
    var $log = $('#log');
    var $start = $('#start');
    var $stop = $('#stop');
    var timer;

    $start.on('click', function() {
        var $bar = $('#bar');
        Horloge(maxWidth);
        timer = setInterval('Horloge('+maxWidth+')', 100);

        $bar.animate({
            width: maxWidth
        }, duration, function() {
            $(this).css('background-color', 'green');
            $start.attr('disabled', true);
            $stop.attr('disabled', true);
            $log.html('100 %');
            clearInterval(timer);
        });
    });

    $stop.on('click', function() {
        var $bar = $('#bar');
        $bar.stop();

        clearInterval(timer);

        var w = $bar.width();
        var percent = parseInt((w * 100) / maxWidth);
        $log.html(percent + ' %');
    });

});

function Horloge(maxWidth) {
    var w = $('#bar').width();
    var percent = parseInt((w * 100) / maxWidth);
    $('#log').html(percent + ' %');
}

body {
 margin:10px;
}
#bar {
    width:0px;
    height:25px;
    border:1px solid black;
    background-color:yellow;
    border-radius:3px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="start">Start</button>
<button id="stop">Stop</button>

<div id="bar"></div>
<div id="log"></div>


问:
Using C preprocessor to create multiple table layouts
I need to lay out multiple tables (and structs) based on a common set of definitions.  In order to keep everything consistent, I'd like to keep all the definitions in a single place and use the magic of C macros to expand the definitions into various tables (and structs).

There's one catch: not all of the tables are the same length.  A simplified statement of the problem goes like this:

```<code>// Here is the master list of things
#define THING_DEFINITIONS \
  THING(apple, true) \
  THING(pear, true) \
  THING(caddilac, false) \
  THING(mango, true)

// I want a table of all thing names -- this works fine
#undef THING
#define THING(name, is_fruit) #name,
char *all_things[] = {
  THING_DEFINITIONS
};

// Now I want a table of just fruits -- the following does not work
#undef THING
#define THING(name, is_fruit) \
#if is_fruit \
 #name,      \
#endif

char *just_fruits[] = {
  THING_DEFINITIONS
};
</code>```

The problem, of course, is that conditionals cannot appear inside of a macro definition, at least not the way it's shown here.

Is there a definition for THING such that when I expand THING_DEFINITIONS that it only emits fruits?

答:
Generate new macro name according the is_fruit:

```<code>// Options
#define THING_true(name) #name,
#define THING_false(name)

// Combine symbols
#define CONCAT(a, b) a ## b

// Final macro
#define THING(name, is_fruit)  CONCAT(THING_, is_fruit) (name)
</code>```

This will expand to:

```<code>THING_true(apple)
THING_true(pear)
THING_false(caddilac)
THING_true(mango)
</code>```

Which will finally expand to:

```<code>"apple",
"pear",

"mango",
</code>```

I did a small test on Ideone: http://ideone.com/TDR2WO

Body:
I need to lay out multiple tables (and structs) based on a common set of definitions.  In order to keep everything consistent, I'd like to keep all the definitions in a single place and use the magic of C macros to expand the definitions into various tables (and structs).

There's one catch: not all of the tables are the same length.  A simplified statement of the problem goes like this:

// Here is the master list of things
#define THING_DEFINITIONS \
  THING(apple, true) \
  THING(pear, true) \
  THING(caddilac, false) \
  THING(mango, true)

// I want a table of all thing names -- this works fine
#undef THING
#define THING(name, is_fruit) #name,
char *all_things[] = {
  THING_DEFINITIONS
};

// Now I want a table of just fruits -- the following does not work
#undef THING
#define THING(name, is_fruit) \
#if is_fruit \
 #name,      \
#endif

char *just_fruits[] = {
  THING_DEFINITIONS
};

The problem, of course, is that conditionals cannot appear inside of a macro definition, at least not the way it's shown here.

Is there a definition for THING such that when I expand THING_DEFINITIONS that it only emits fruits?

Body:
Generate new macro name according the is_fruit:

// Options
#define THING_true(name) #name,
#define THING_false(name)

// Combine symbols
#define CONCAT(a, b) a ## b

// Final macro
#define THING(name, is_fruit)  CONCAT(THING_, is_fruit) (name)

This will expand to:

THING_true(apple)
THING_true(pear)
THING_false(caddilac)
THING_true(mango)

Which will finally expand to:

"apple",
"pear",

"mango",

I did a small test on Ideone: http://ideone.com/TDR2WO


问:
How to avoid checkout of sources on master node with jenkins pipeline
I want to define my builds using the Jenkins 2 pipeline feature and I want this configuration to be loaded from sources in a Jenkinsfile.
However I don't want to clutter my master node with workspace.

Ideally, I could specify that a pipeline job is meant to be run a given node type but that doesn't seems possible.

I see 2 alternatives:

use a dedicated repository where the jenkins job configuration is stored.

use a cleaver git checkout strategy (shallow + sparse).

Did I miss something? What would be the best practice ?

答:
There's a Jenkins issue that claims this is now fixed, and only the Jenkinsfile itself needs to be checked out on the master: https://issues.jenkins-ci.org/browse/JENKINS-33273

(It isn't working for me at the moment though.)


问:
Change date format in datatable using Laravel and Symfony
I'm trying to change the format of a date field in the DataTable, so not in the form! These fields are created using the formbuilder Symfony. I have no clue how to do this, or were to place it. I Have tried to change the format of the date in DateForm.php but that doesn't change the data in the datatable. I hope this is enough code to understand the situation, else just tell me.

My datatable DateTable.php

```<code>class DateTable extends BaseDataTable{
    use FilterableDataTableTrait;
    public function ajax()
    {
        $view = view('admin::crud.actions');

        $query = $this->query();

        return $this->datatables
            ->eloquent($query)
            ->addColumn('id', function ($item) {
                return $item->id;
            })->addColumn('action', function ($item) use ($view) {
                $view = $item->relation ? view('admin::date.actions') : view('admin::date.actions');
                $view->with('item', $item);
                return $view->render();
            })->make(true);
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())

            ->addAction(['title' => '', 'width' => '100px'])
            ->ajax('')
            ->parameters(array_merge($this->getBuilderParameters(), ['autoWidth' => false]));
    }
 }
</code>```

My form DateForm.php:

```<code>class DateForm extends AbstractType{
private $data;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->data = $builder->getData();
    return $builder
        ->add('date', 'date',
            [
                'required' => true,
            ])
        ->add('description', 'textarea', ['required' => true
        ]);
}
}
</code>```

答:
You should use Laravel Carbon for it:

```<code>$date->format('d.m.Y'); //or another time format
</code>```

before inserting data into the DB.

Body:
I'm trying to change the format of a date field in the DataTable, so not in the form! These fields are created using the formbuilder Symfony. I have no clue how to do this, or were to place it. I Have tried to change the format of the date in DateForm.php but that doesn't change the data in the datatable. I hope this is enough code to understand the situation, else just tell me.

My datatable DateTable.php

class DateTable extends BaseDataTable{
    use FilterableDataTableTrait;
    public function ajax()
    {
        $view = view('admin::crud.actions');

        $query = $this->query();

        return $this->datatables
            ->eloquent($query)
            ->addColumn('id', function ($item) {
                return $item->id;
            })->addColumn('action', function ($item) use ($view) {
                $view = $item->relation ? view('admin::date.actions') : view('admin::date.actions');
                $view->with('item', $item);
                return $view->render();
            })->make(true);
    }

    public function html()
    {
        return $this->builder()
            ->columns($this->getColumns())

            ->addAction(['title' => '', 'width' => '100px'])
            ->ajax('')
            ->parameters(array_merge($this->getBuilderParameters(), ['autoWidth' => false]));
    }
 }

My form DateForm.php:

class DateForm extends AbstractType{
private $data;

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $this->data = $builder->getData();
    return $builder
        ->add('date', 'date',
            [
                'required' => true,
            ])
        ->add('description', 'textarea', ['required' => true
        ]);
}
}

Body:
You should use Laravel Carbon for it:

$date->format('d.m.Y'); //or another time format

before inserting data into the DB.


问:
NoSQL Databases for clients and transaction management
I pretend to build a intranet portal using nodejs+express+angular, however I would like to know if MongoDB would be a good choice for the database.

Users have to report their work hours to later submit invoices to clients

Clients have to be managed (added, edited, deleted)

I will have to show dashboards with invoice values, top clients and so on. (by performing arithmetic functions)

Would it be easy to relate, for example, the client ID in the hour record with the client itself?

Or should I used a SQL db such as MySQL?

I need facts based on Performance, scalability etc.

What will happen when my NoSQL DB goes bigger? Will it lose performance?

答:
My Experience: I have been using MongoDB & Mysql for the past 2 years 5 months.

Everything I write here is going to be from my personal view and experience.

These days MongoDB (NoSQL in general) is a buzz word everybody talks about mongoDB, couchDB, MEAN stack etc ... that why we started it and here is what happened:

we found a project that was perfect for mongodb:

We had very large user base

There was a lot inter dependencies
    between our entity objects i.e Entity A cant live without Entity B
    so we decided to embed the dependent entities.

Still we are using MongoDB for the same project but our database design is very different than our initial database design( which were designed following the mongodb principles):

Our app become very slow because sometimes we want to get data
from more than one collection and mongodb does ot allow us ( now it
is supported from version >= 3.2). Hence we to do the join on our
service layer pro grammatically.

Loading database entities become very heavy due to the embeded
documents so we have to move all embeded documents into separate
collections. Hence our database design is now very flat(i.e looks
like relational database design).

We found a lot orphaned data in our database; initially we
thought we can implement our data integrity on our repo/service
layer but it is obvious our implementation was not perfect and
sometimes we directly run mongo queries on the database console so
we were actually messing up our data while mongodb kept silent
laughing at us :)

After we finished most of our app's functionality we focused on
writing reports and doing analysis on our data we found out our
mongodb queries become very huge and unmanageable; which we believed
using relational databases like mysql could have eased this.

Bottom line when I started using MongoDB I was very fascinated about it but not afer I know how to use it:

It does not complain about data integrity violation. In fact you
could insert Car instance into Employee collection if you want :D

It is very easy to learn specially if you have good javascript
background; you dont have to learn database languages like SQL. All
mongo queries are combination of js functions and objects.

You can finish an app in matter of weeks or few months; in fact
we finished our app in 3 months(very complex app).

But now we got a similar project and we choose Mysql instead of Mongodb; we could have replicated the old project and finish it in few weeks but we learned our lesson. If you really care about your app ( ie. your data) go for Mysql(any relational database).

We are only using MongoDB for old projects and Kibana(because it is for logging and we dont care much about our log data)

Who said Mysql does not scale? Facebook is using 1,800 mysql servers!


问:
How to replace the following character with an empty space and write in next line?
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

```<code> string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "<br>");
</code>```

and

```<code> if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}
</code>```

But it is writing the whole line with  □....Any suggestion??

答: Use Trim() rather than TrimStart(), and it will trim it off the end

Body:
How to replace that character which is square in shape(□) with a \n or an empty space and write in next line using c#?...It is writing in text file with □... Here is my code....

 string line = dt.Rows[0].ItemArray[0].ToString().Replace(Environment.NewLine, "
");

and

 if (line.IndexOf(line2, StringComparison.CurrentCultureIgnoreCase) != -1)
    {
        if (!patternwritten)
        {
            dest.WriteLine("");
            dest.WriteLine("Pattern Name : " + line2 );
             patternwritten = true;
         }

  dest.WriteLine("LineNo : " + counter.ToString() + " : " + "" + line.TrimStart());
}

But it is writing the whole line with  □....Any suggestion??


问:
Aligning buttons in column in Red
I am brand new to Red/Rebol. I love it so far, I am experimenting with the GUI system.

I am trying to align some buttons in a vertical column so to speak.

This is what I have so far

```<code>    Red [ Title: "Editor"  needs: 'view]

    view [ size 800x600 title "Save Notes"
    t: text  ""
    a: area 500x500 black
    button "Click" [t/text: "Red is good !" ]  return
    text "" button "Close" [quit] return
    text "" button "Save" [save %notes.dat a/text t/text "Saved"]
        ]
</code>```

This is what it creates, which I have annotated with what I am trying to do:

答:
Welcome to Red!

In the VID dialect, the default direction where the next element will be put, is by default horizontal (across), so that a return will go to the next column. If you switch the direction to vertical (using below), then the next element will go in the next row, staying in the same column. So it gives you:

```<code>Red [ Title: "Editor"  needs: 'view]

view [ size 800x600 title "Save Notes"
    t: text  ""
    a: area 500x500 black
    below pad 10x0
    button "Click" [t/text: "Red is good !" ]
    text "hello" button "Close" [quit]
    text "world" button "Save" [save %notes.dat a/text t/text "Saved"]
]
</code>```

Note: I just put some text into your empty labels, so that we can see them in the layout, and how they affect the positionning of the buttons.

Have fun playing with it! ;-)

Title: Aligning buttons in column in Red

Body:
I am brand new to Red/Rebol. I love it so far, I am experimenting with the GUI system.

I am trying to align some buttons in a vertical column so to speak.

This is what I have so far

    Red [ Title: "Editor"  needs: 'view]

    view [ size 800x600 title "Save Notes"
    t: text  ""
    a: area 500x500 black
    button "Click" [t/text: "Red is good !" ]  return
    text "" button "Close" [quit] return
    text "" button "Save" [save %notes.dat a/text t/text "Saved"]
        ]

This is what it creates, which I have annotated with what I am trying to do:

Body:
Welcome to Red!

In the VID dialect, the default direction where the next element will be put, is by default horizontal (across), so that a return will go to the next column. If you switch the direction to vertical (using below), then the next element will go in the next row, staying in the same column. So it gives you:

Red [ Title: "Editor"  needs: 'view]

view [ size 800x600 title "Save Notes"
    t: text  ""
    a: area 500x500 black
    below pad 10x0
    button "Click" [t/text: "Red is good !" ]
    text "hello" button "Close" [quit]
    text "world" button "Save" [save %notes.dat a/text t/text "Saved"]
]

Note: I just put some text into your empty labels, so that we can see them in the layout, and how they affect the positionning of the buttons.

Have fun playing with it! ;-)


问:
Get Maps autocomplete as input Value
I am using Google Maps autocomplete API to help select places for input field. The issue is, if I try to get the input value to use in something such as Firebase or similar it only saves what I typed prior to selecting autocomplete. Please see this CodePen: https://codepen.io/Auzy/pen/KWRjNp?editors=1111 I've been using the below console.log to try to reflect the autocomplete value.

The usage is pretty basic so I'm surprised I haven't seen more of this issue.

HTML:

```<code><div class="container">
    <div class="form-group">
        <label for="exampleInputPassword1">Address</label>
        <input v-model="newPost.address" type="text" class="form-control" id="searchTextField" placeholder="Address">
    </div>
    <div class="place"></div>
</div>
</code>```

JS

```<code>const searchInput = document.getElementById('searchTextField');
const autocomplete = new google.maps.places.Autocomplete(searchInput);

searchInput.addEventListener("change", () => {
    setTimeout(function() {
        let addr = searchInput.value;
        let embed = "<label for='exampleInputPassword1'>Map Preview</label><iframe frameborder='0' scrolling='no' marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&q=" + encodeURIComponent(addr) + "&output=embed'></iframe>";

        $('.place').html(embed);
    }, 200);
    console.log(searchInput.value)

});
</code>```

答:
This is a little bit tricky because place is an object and the autocomplete results you are seeing are derived from the properties of Place object.

So the workaround I did to get to what you're trying to do is combine two place properties - place.name and place.formatted_address. You can find the full list here.

Here's the full demo which I tweaked from Place Autocomplete sample from Google.

```<code>var place = autocomplete.getPlace();
var inputValue = place.name + " " + place.formatted_address;
console.log(inputValue);
</code>```

Sample Autcomplete Demo

Looking for: Sydney Opera House

Autocomplete result:
Wilson Parking - Sydney Opera House, Macquarie Street, Sydney, New South Wales, Australia

place input value obtained:
Wilson Parking - Sydney Opera House 2 Macquarie St, Sydney NSW 2000, Australia

Looking for: Statue of Liberty

Autocomplete result:
Statue of Liberty Departure, New York, NY, United States

place input value obtained:
Statue of Liberty Departure New York, NY 10004, USA

You can see the results are almost exactly the same. You can now use the variable inputValue (which is an almost identical copy of the autocomplete result) however you want.
Hope this helps.

Title: Get Maps autocomplete as input Value

Body:
I am using Google Maps autocomplete API to help select places for input field. The issue is, if I try to get the input value to use in something such as Firebase or similar it only saves what I typed prior to selecting autocomplete. Please see this CodePen: https://codepen.io/Auzy/pen/KWRjNp?editors=1111 I've been using the below console.log to try to reflect the autocomplete value.

The usage is pretty basic so I'm surprised I haven't seen more of this issue.

HTML:

        Address
        <input v-model="newPost.address" type="text" class="form-control" id="searchTextField" placeholder="Address">

JS

const searchInput = document.getElementById('searchTextField');
const autocomplete = new google.maps.places.Autocomplete(searchInput);

searchInput.addEventListener("change", () => {
    setTimeout(function() {
        let addr = searchInput.value;
        let embed = "Map Preview";

        $('.place').html(embed);
    }, 200);
    console.log(searchInput.value)

});

Body:
This is a little bit tricky because place is an object and the autocomplete results you are seeing are derived from the properties of Place object.

So the workaround I did to get to what you're trying to do is combine two place properties - place.name and place.formatted_address. You can find the full list here.

Here's the full demo which I tweaked from Place Autocomplete sample from Google.

var place = autocomplete.getPlace();
var inputValue = place.name + " " + place.formatted_address;
console.log(inputValue);

Sample Autcomplete Demo

Looking for: Sydney Opera House

Autocomplete result:
Wilson Parking - Sydney Opera House, Macquarie Street, Sydney, New South Wales, Australia

place input value obtained:
Wilson Parking - Sydney Opera House 2 Macquarie St, Sydney NSW 2000, Australia

Looking for: Statue of Liberty

Autocomplete result:
Statue of Liberty Departure, New York, NY, United States

place input value obtained:
Statue of Liberty Departure New York, NY 10004, USA

You can see the results are almost exactly the same. You can now use the variable inputValue (which is an almost identical copy of the autocomplete result) however you want.
Hope this helps.


问:
SQL Select producing slightly different results in phpAdmin vs. phpHTML
I consistently miss the first row result, which is more noticeable when there is only one row result.

I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?

```<code><?php
$sql = "SELECT  * FROM Order_Items
        JOIN    Parts ON Parts.id = Order_Items.part_id
        WHERE   Order_Items.orders_id = $id
        AND     qty <> 0
        ORDER BY Parts.id";

        $q = $pdo->prepare($sql);
        $q->execute(array());
        $row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '<tr>';
            echo    '<td>' . $row['part_num'] . '</td>';
            echo    '<td>' . $row['part_desc'] . '</td>';
            echo    '<td>' . $row['qty'] . '</td>';
        }

    Database::disconnect();
?>
</code>```

答:
You are duplicating  $row = $q->fetch(PDO::FETCH_ASSOC);.
When you asing $q to $row, $q->fetch is cleared (with no data) so in the IF sentence you have no rows to fetch in $q.
You have to remove $row = $q->fetch(PDO::FETCH_ASSOC); and just use it in the IF.

Also try to do a fetchAll() to $q.

```<code>$result = $query -> fetchAll();

foreach( $result as $row ) {
    /*CODE*/
}
</code>```

Body:
I consistently miss the first row result, which is more noticeable when there is only one row result.

I have a problem with my PDO commands. Any suggestions for how to correct please? If I remove the $pod->prepare nothing works. Not sure what to do?

<?php
$sql = "SELECT  * FROM Order_Items
        JOIN    Parts ON Parts.id = Order_Items.part_id
        WHERE   Order_Items.orders_id = $id
        AND     qty <> 0
        ORDER BY Parts.id";

        $q = $pdo->prepare($sql);
        $q->execute(array());
        $row = $q->fetch(PDO::FETCH_ASSOC); // Roy says this is not needed

        while ($row = $q->fetch(PDO::FETCH_ASSOC))
        {
            echo    '
';
            echo    '' . $row['part_num'] . '	';
            echo    '' . $row['part_desc'] . '	';
            echo    '' . $row['qty'] . '	';
        }

    Database::disconnect();
?>

Body:
You are duplicating  $row = $q->fetch(PDO::FETCH_ASSOC);.
When you asing $q to $row, $q->fetch is cleared (with no data) so in the IF sentence you have no rows to fetch in $q.
You have to remove $row = $q->fetch(PDO::FETCH_ASSOC); and just use it in the IF.

Also try to do a fetchAll() to $q.

$result = $query -> fetchAll();

foreach( $result as $row ) {
    /*CODE*/
}


问:
Laravel 5 MethodNotAllowedHttpException in RouteCollection.php line 201:
I have a number of php files in my project:

admin.blade.php: this files contains the admin form.

When called it show the following error:

MethodNotAllowedHttpException in RouteCollection.php line 201

```<code><h2>Please Log In To Manage</h2>
<form id="form1" name="form1" method="post" action="<?=URL::to('/admin')?>">
   <input type="hidden" name="_token" value="{{ csrf_token() }}">
   User Name:<br />
   <input name="username" type="text" id="username" size="40" />
   <br /><br />
   Password:<br />
   <input name="password" type="password" id="password" size="40" />
   <br />
   <br />
   <br />
   <input type="submit" name="button" id="button" value="Log In" />
</form>
</code>```

In route.php, this call is made:

```<code>Route::get('/admin',array('uses'=>'student@admin'));
</code>```

This is the function in student.php

```<code>public function admin()
{
    return View::make('student.admin');
    $validator = Validator::make($data = Input::all() , User::rules());
    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    else
    {
        $check = 0;
        $check = DB::table('admin')->get();
        $username = Input::get('username');
        $password = Input::get('password');
        if (Auth::attempt(['username' => $username, 'password' => $password]))
        {
            return Redirect::intended('/');
        }
        return Redirect::back()->withInput()->withErrors('That username/password combo does not exist.');
    }
}
</code>```

I don't know much about creating an admin area, I am just trying to create it.

答:
In Routes web.php
Your code is

```<code>Route::get('/admin',array('uses'=>'student@admin'));
</code>```

which is wrong.
Actually submitting data in POST method its array of data so you need to route through post instead of get.
so correct code is

```<code>Route::post('/admin',array('uses'=>'student@admin'));
</code>```

Follow this tutorial form Laracast it might helpful,

https://laracasts.com/series/laravel-from-scratch-2017/episodes/16

Body:
I have a number of php files in my project:

admin.blade.php: this files contains the admin form.

When called it show the following error:

MethodNotAllowedHttpException in RouteCollection.php line 201

Please Log In To Manage

<form id="form1" name="form1" method="post" action="<?=URL::to('/admin')?>">
   <input type="hidden" name="_token" value="{{ csrf_token() }}">
   User Name:

   <input name="username" type="text" id="username" size="40" />

   Password:

   <input name="password" type="password" id="password" size="40" />

   <input type="submit" name="button" id="button" value="Log In" />
</form>

In route.php, this call is made:

Route::get('/admin',array('uses'=>'student@admin'));

This is the function in student.php

public function admin()
{
    return View::make('student.admin');
    $validator = Validator::make($data = Input::all() , User::rules());
    if ($validator->fails())
    {
        return Redirect::back()->withErrors($validator)->withInput();
    }
    else
    {
        $check = 0;
        $check = DB::table('admin')->get();
        $username = Input::get('username');
        $password = Input::get('password');
        if (Auth::attempt(['username' => $username, 'password' => $password]))
        {
            return Redirect::intended('/');
        }
        return Redirect::back()->withInput()->withErrors('That username/password combo does not exist.');
    }
}

I don't know much about creating an admin area, I am just trying to create it.

Body:
In Routes web.php
Your code is

Route::get('/admin',array('uses'=>'student@admin'));

which is wrong.
Actually submitting data in POST method its array of data so you need to route through post instead of get.
so correct code is

Route::post('/admin',array('uses'=>'student@admin'));

Follow this tutorial form Laracast it might helpful,

https://laracasts.com/series/laravel-from-scratch-2017/episodes/16


问:
In Javascript console.log I am not getting the result
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

```<code>    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };
</code>```

答:
```<code>document.getElementById("runButton").onclick = function run() {
    var lastName = "arm";
    var firstName;
    mygreeting = Greeting(firstName, lastName);
    console.log(mygreeting);
};
function Greeting(firstName, lastName) {
    if (typeof lastName === 'undefined') {
        return ("Hello, " + firstName + "!");
    } else if (typeof firstName === 'undefiend') {
        return ("hello, " + lastName + "!!");
    } else {
        return ("hello, " + firstName + lastName + "!!!");
    }
}
</code>```

You'd want your function to return a result and then assign the return of your function to a variable, then use that variable for something, in this care in console.log();

Body:
I want console.log to print only firstname if lastname was undefined, instead I get firstname + undefined on the console. What could I change in the code so it only gives me firstname or lastname if one of them is undefined without printing the word 'undefined' in the console, and if both are defined to print them both. This is the code I am trying:

    document.getElementById("runButton").onclick = function run() {
        var lastName = "arm";
        var firstName;
        function Greeting(firstName, lastName) {
            if (lastName = 'undefined') {
                console.log("Hello, " + firstName + "!");
            } else if (firstName = 'undefiend') {
                console.log("hello, " + lastName + "!!");
            } else {
                console.log("hello, " + firstName + lastName + "!!!");
            }
        }
        Greeting(firstName + " " + lastName);
    };

Body:
document.getElementById("runButton").onclick = function run() {
    var lastName = "arm";
    var firstName;
    mygreeting = Greeting(firstName, lastName);
    console.log(mygreeting);
};
function Greeting(firstName, lastName) {
    if (typeof lastName === 'undefined') {
        return ("Hello, " + firstName + "!");
    } else if (typeof firstName === 'undefiend') {
        return ("hello, " + lastName + "!!");
    } else {
        return ("hello, " + firstName + lastName + "!!!");
    }
}

You'd want your function to return a result and then assign the return of your function to a variable, then use that variable for something, in this care in console.log();


问:
CSS3 Rounded corner for input element without js/images
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

```<code><!DOCTYPE html>
<html>
<head>
    <title>xx</title>
<style type="text/css">
input
{
    -webkit-border-radius: 15px;
    -moz-border-radius: 15px;
    border-radius: 15px;
}
</style>
</head>
<body>
<input type="text" value="test" />
</body>
</html>
</code>```

It does not work in firefox 3.6.12!

答:
CSS 3 will help you.

This style sheet works for input elements also [in modern browsers atleast], although did not tested in IE

```<code> border-radius: 16px; /* half of button size + padding */
-moz-border-radius: 16px;
background: -webkit-gradient(linear, left top, left bottom, from(#8cc0f6), to(#cfe4fa));
background: -moz-linear-gradient(top, #8cc0f6, #cfe4fa);
</code>```

Body:
Who I can make the rounded corner for input elements?

I need a way without using javascript and images..

Added:

<!DOCTYPE html>

    <title>xx</title>

<input type="text" value="test" />

It does not work in firefox 3.6.12!

Body:
CSS 3 will help you.

This style sheet works for input elements also [in modern browsers atleast], although did not tested in IE

 border-radius: 16px; /* half of button size + padding */
-moz-border-radius: 16px;
background: -webkit-gradient(linear, left top, left bottom, from(#8cc0f6), to(#cfe4fa));
background: -moz-linear-gradient(top, #8cc0f6, #cfe4fa);


问:
How to fetch json value from web api using ajax?
This may be dumb question but am struggling with this i cannot fetch the value from web api using ajax, let me explain my problem in detail i have created simple web api by using ajax i need to fetch the value how can i achieve this let me post my code what i have tried so far:

Webapi code:

```<code>  [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [HttpGet]
        [Route("~/api/getail/{id}/{criteriaid}")]
        public IHttpActionResult GetIncidentByResourceID(int id, int criteriaid)
        {
            IncidentDisplayApiModelCollection collection = objIncidentApiManager.GetDisplayList(id, criteriaid, 4);
            return Json(collection);
        }
</code>```

This is sample ajax request:

```<code>   <script src="js/jquery-3.2.0.min.js"></script>
              <script >
       $(document).ready(function(){
       $.ajax({
    url: "http://localhost:8080/sf/api/getail/1848/29",
    dataType: "json",
     success: function( response ) {
        console.log( response ); // server response
    },
    error: function( response ) {
        console.log( response ); // server response
    }
});

});
       </script>
</code>```

what am getting in firefox console is :

```<code>Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(), 9 more… }  index.html:59:9

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/sf/api/getail/1848/29. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
</code>```

I have downloaded cors in nuget manager and added confi.enablecors(); in webapi config.  can someone help me how to resolve this thanks in advance!!

答:
The origins parameter should contain the value of the Origin request header.

When request is made from page with file:// URI, browsers set the Origin header to be null (string) (I've tested in Firefox and Chrome).

So, try to add "null" to the origins parameter:

```<code>    [EnableCors(origins: "null", headers: "*", methods: "*")]
</code>```

but i'm not sure this will work (such an unusual value!)

Or, simpler, just set it to be "*" to allow requests from any origins:

```<code>    [EnableCors(origins: "*", headers: "*", methods: "*")]
</code>```

NOTE: (!) When deploying to production, consider carefully before allowing requests from any origin. It means that literally any website can make AJAX calls to your web API.

Hope it helps

Body:
This may be dumb question but am struggling with this i cannot fetch the value from web api using ajax, let me explain my problem in detail i have created simple web api by using ajax i need to fetch the value how can i achieve this let me post my code what i have tried so far:

Webapi code:

  [EnableCors(origins: "http://localhost:8080", headers: "*", methods: "*")]
        [HttpGet]
        [Route("~/api/getail/{id}/{criteriaid}")]
        public IHttpActionResult GetIncidentByResourceID(int id, int criteriaid)
        {
            IncidentDisplayApiModelCollection collection = objIncidentApiManager.GetDisplayList(id, criteriaid, 4);
            return Json(collection);
        }

This is sample ajax request:

what am getting in firefox console is :

Object { readyState: 0, getResponseHeader: .ajax/y.getResponseHeader(), getAllResponseHeaders: .ajax/y.getAllResponseHeaders(), setRequestHeader: .ajax/y.setRequestHeader(), overrideMimeType: .ajax/y.overrideMimeType(), statusCode: .ajax/y.statusCode(), abort: .ajax/y.abort(), state: .Deferred/e.state(), always: .Deferred/e.always(), catch: .Deferred/e.catch(), 9 more… }  index.html:59:9

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/sf/api/getail/1848/29. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

I have downloaded cors in nuget manager and added confi.enablecors(); in webapi config.  can someone help me how to resolve this thanks in advance!!

Body:
The origins parameter should contain the value of the Origin request header.

When request is made from page with file:// URI, browsers set the Origin header to be null (string) (I've tested in Firefox and Chrome).

So, try to add "null" to the origins parameter:

    [EnableCors(origins: "null", headers: "*", methods: "*")]

but i'm not sure this will work (such an unusual value!)

Or, simpler, just set it to be "*" to allow requests from any origins:

    [EnableCors(origins: "*", headers: "*", methods: "*")]

NOTE: (!) When deploying to production, consider carefully before allowing requests from any origin. It means that literally any website can make AJAX calls to your web API.

Hope it helps


问:
Android Camera deprecated
I had an Android app which was able to take a simple photo showing a preview in a SurfaceView using the deprecated hardware.Camera.

I did it this way:

```<code>protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.primeracapa);

    ajustes = getSharedPreferences("ajustes", MODE_PRIVATE);

    mySurfaceView = (SurfaceView) findViewById(R.id.surface);
    mySurfaceHolder = mySurfaceView.getHolder();
    mySurfaceHolder.addCallback(this);

    myInflater = LayoutInflater.from(this);
    View overView = myInflater.inflate(R.layout.segundacapa,null);
    this.addContentView(overView, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

    takePicture = (Button) findViewById(R.id.button);
    takePicture.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if(capturar==true || !ajustes.getBoolean("longitudAuto", true))
            {
                myCamera.takePicture(myShutterCallback, myPictureCallback, myJpeg);
            }
        }
    });
}

ShutterCallback myShutterCallback = new ShutterCallback() {
    @Override
    public void onShutter() {
    }
};

PictureCallback myPictureCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera myCamera) {
        // Despues de hacer la foto que tiene que hacer
    }
};

PictureCallback myJpeg = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera myCamera) {
        if(data != null){

            File dir_image2 = new File (Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_DCIM), "foto");
            dir_image2.mkdirs();

            File tmpFile = new File(dir_image2,"TempGhost.jpg");

            try
            {
                FileOutputStream fos = new FileOutputStream(tmpFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            }

            if (!dir_image2.mkdirs()) {
                Log.e("TAG", "Directory not created");
            }
        }
    }
};

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    try{
        if(myPreviewRunning){
            myCamera.stopPreview();
            myPreviewRunning = false;
        }
        Camera.Parameters p = myCamera.getParameters();
        p.setJpegQuality(50);
        p.setPreviewSize(width,height);

        myCamera.setParameters(p);
        myCamera.setPreviewDisplay(holder);
        myCamera.startPreview();
        myPreviewRunning = true;
    }catch(Exception e){}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    myCamera.stopPreview();
    myPreviewRunning = false;
    myCamera.release();
    myCamera = null;
}

@Override
public void surfaceCreated(SurfaceHolder holder)
{
    myCamera = Camera.open();
}
</code>```

What I need to do now that Camera is deprecated is to do the same "simple" thing using camera2, and it's driving me crazy. Is it possible that camera2 is much more difficult to use.
I only need to see the preview of the camera on my SurfaceView and to be able to take a photo when a button is pressed and save it in a specific folder created by me.

答:
Was also playing around with the camera2 but in my case for video preview.
Perhaps you dont need the repeatingRequest but simple request. Hope this helps you a bit out to start with.</p>

```<code>CameraManager manager = (CameraManager)context.getSystemService(Context.CAMERA_SERVICE);
      if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        try {
          manager.openCamera(cameraId, new CameraDevice.StateCallback() {

                @Override
                public void onOpened(@NonNull CameraDevice camera) {
                    try {

                        CaptureRequest.Builder builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
                        builder.set(CaptureRequest.CONTROL_MODE,CaptureRequest.CONTROL_MODE_USE_SCENE_MODE);
                        builder.set(CaptureRequest.CONTROL_SCENE_MODE,CaptureRequest.CONTROL_SCENE_MODE_PORTRAIT);

                        builder.addTarget(preview);
                        final CaptureRequest req = builder.build();

                        camera.createCaptureSession(Arrays.asList(preview), new CameraCaptureSession.StateCallback() {
                            @Override
                            public void onConfigured(@NonNull CameraCaptureSession session) {
                                try {

                                    currentSession = session;
                                    session.setRepeatingRequest(req, new CameraCaptureSession.CaptureCallback() {
                                    },new Handler());
                                } catch (CameraAccessException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                                //do something
                            }
                        },new Handler());
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onDisconnected(@NonNull CameraDevice camera) {
                    camera.close();

                }

                @Override
                public void onError(@NonNull CameraDevice camera, int error) {

                }
            }, new Handler());
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
</code>```

Title: Android Camera deprecated

Body:
I had an Android app which was able to take a simple photo showing a preview in a SurfaceView using the deprecated hardware.Camera.

I did it this way:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.primeracapa);

    ajustes = getSharedPreferences("ajustes", MODE_PRIVATE);

    mySurfaceView = (SurfaceView) findViewById(R.id.surface);
    mySurfaceHolder = mySurfaceView.getHolder();
    mySurfaceHolder.addCallback(this);

    myInflater = LayoutInflater.from(this);
    View overView = myInflater.inflate(R.layout.segundacapa,null);
    this.addContentView(overView, new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));

    takePicture = (Button) findViewById(R.id.button);
    takePicture.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            if(capturar==true || !ajustes.getBoolean("longitudAuto", true))
            {
                myCamera.takePicture(myShutterCallback, myPictureCallback, myJpeg);
            }
        }
    });
}

ShutterCallback myShutterCallback = new ShutterCallback() {
    @Override
    public void onShutter() {
    }
};

PictureCallback myPictureCallback = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera myCamera) {
        // Despues de hacer la foto que tiene que hacer
    }
};

PictureCallback myJpeg = new PictureCallback() {
    @Override
    public void onPictureTaken(byte[] data, Camera myCamera) {
        if(data != null){

            File dir_image2 = new File (Environment.getExternalStoragePublicDirectory
                    (Environment.DIRECTORY_DCIM), "foto");
            dir_image2.mkdirs();

            File tmpFile = new File(dir_image2,"TempGhost.jpg");

            try
            {
                FileOutputStream fos = new FileOutputStream(tmpFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            } catch (IOException e) {
                Toast.makeText(getApplicationContext(),"Error",Toast.LENGTH_LONG).show();
            }

            if (!dir_image2.mkdirs()) {
                Log.e("TAG", "Directory not created");
            }
        }
    }
};

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
    try{
        if(myPreviewRunning){
            myCamera.stopPreview();
            myPreviewRunning = false;
        }
        Camera.Parameters p = myCamera.getParameters();
        p.setJpegQuality(50);
        p.setPreviewSize(width,height);

        myCamera.setParameters(p);
        myCamera.setPreviewDisplay(holder);
        myCamera.startPreview();
        myPreviewRunning = true;
    }catch(Exception e){}
}

@Override
public void surfaceDestroyed(SurfaceHolder holder)
{
    myCamera.stopPreview();
    myPreviewRunning = false;
    myCamera.release();
    myCamera = null;
}

@Override
public void surfaceCreated(SurfaceHolder holder)
{
    myCamera = Camera.open();
}

What I need to do now that Camera is deprecated is to do the same "simple" thing using camera2, and it's driving me crazy. Is it possible that camera2 is much more difficult to use.
I only need to see the preview of the camera on my SurfaceView and to be able to take a photo when a button is pressed and save it in a specific folder created by me.

Body:
Was also playing around with the camera2 but in my case for video preview.
Perhaps you dont need the repeatingRequest but simple request. Hope this helps you a bit out to start with.

CameraManager manager = (CameraManager)context.getSystemService(Context.CAMERA_SERVICE);
      if (ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        try {
          manager.openCamera(cameraId, new CameraDevice.StateCallback() {

                @Override
                public void onOpened(@NonNull CameraDevice camera) {
                    try {

                        CaptureRequest.Builder builder = camera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
                        builder.set(CaptureRequest.CONTROL_MODE,CaptureRequest.CONTROL_MODE_USE_SCENE_MODE);
                        builder.set(CaptureRequest.CONTROL_SCENE_MODE,CaptureRequest.CONTROL_SCENE_MODE_PORTRAIT);

                        builder.addTarget(preview);
                        final CaptureRequest req = builder.build();

                        camera.createCaptureSession(Arrays.asList(preview), new CameraCaptureSession.StateCallback() {
                            @Override
                            public void onConfigured(@NonNull CameraCaptureSession session) {
                                try {

                                    currentSession = session;
                                    session.setRepeatingRequest(req, new CameraCaptureSession.CaptureCallback() {
                                    },new Handler());
                                } catch (CameraAccessException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onConfigureFailed(@NonNull CameraCaptureSession session) {
                                //do something
                            }
                        },new Handler());
                    } catch (CameraAccessException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onDisconnected(@NonNull CameraDevice camera) {
                    camera.close();

                }

                @Override
                public void onError(@NonNull CameraDevice camera, int error) {

                }
            }, new Handler());
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }


问:
How to using container.Resolve in Module?
I am beginner with Autofac.
Does anyone know How to using container.Resolve in Module?

```<code>public class MyClass
{
  public bool Test(Type type)
    {
       if( type.Name.Begin("My") )  return true;
         return false;
    }
}

public class MyModule1 : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        var type = registration.Activator.LimitType;
        MyClass my = container.Resolve<MyClass>();  //How to do it in Module?
        my.Test(type);
        ...
    }
}
</code>```

How does I get container in module?

答:
You cannot resolve component from container in the module. But you can attach to each component resolution events individually. So when you meet interesting component you can do anything with it. It can be said that conceptually you resolving component.</p>

```<code>public class MyModule : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Activated += (sender, args) =>
        {
            var my = args.Instance as MyClass;
            if (my == null) return;

            var type = args.Component.Activator.LimitType;
            my.Test(type);
            ...
        };
    }
}
</code>```

Body:
I am beginner with Autofac.
Does anyone know How to using container.Resolve in Module?

public class MyClass
{
  public bool Test(Type type)
    {
       if( type.Name.Begin("My") )  return true;
         return false;
    }
}

public class MyModule1 : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry componentRegistry, IComponentRegistration registration)
    {
        var type = registration.Activator.LimitType;
        MyClass my = container.Resolve<MyClass>();  //How to do it in Module?
        my.Test(type);
        ...
    }
}

How does I get container in module?

Body:
You cannot resolve component from container in the module. But you can attach to each component resolution events individually. So when you meet interesting component you can do anything with it. It can be said that conceptually you resolving component.

public class MyModule : Autofac.Module
{
    protected override void AttachToComponentRegistration(IComponentRegistry registry, IComponentRegistration registration)
    {
        registration.Activated += (sender, args) =>
        {
            var my = args.Instance as MyClass;
            if (my == null) return;

            var type = args.Component.Activator.LimitType;
            my.Test(type);
            ...
        };
    }
}


答:
The condition should lastName===undefined not lastName= 'undefined'. You can either use ==(Equal to) or ===(Strict equal to) to check as the operator. = is assignment operator.

 document.getElementById("runButton").onclick = function run() {
    var lastName = "arm";
    var firstName;
    function Greeting(firstName, lastName) {
        if(typeof firstName !== 'undefined' &&  typeof lastName !== 'undefined'){
            console.log("hello, " + firstName + " " +  lastName + "!!!");
        } else if ( typeof lastName !== 'undefined') {
            console.log("Hello, " + lastName + "!");
        } else if (typeof firstName !== 'undefiend') {
            console.log("hello, " + firstName + "!!");
        }
    }
    Greeting(firstName,lastName);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="runButton">Click Me</button></code>```

Title: In Javascript console.log I am not getting the result

Body:
The condition should lastName===undefined not lastName= 'undefined'. You can either use ==(Equal to) or ===(Strict equal to) to check as the operator. = is assignment operator.

 document.getElementById("runButton").onclick = function run() {
    var lastName = "arm";
    var firstName;
    function Greeting(firstName, lastName) {
        if(typeof firstName !== 'undefined' &&  typeof lastName !== 'undefined'){
            console.log("hello, " + firstName + " " +  lastName + "!!!");
        } else if ( typeof lastName !== 'undefined') {
            console.log("Hello, " + lastName + "!");
        } else if (typeof firstName !== 'undefiend') {
            console.log("hello, " + firstName + "!!");
        }
    }
    Greeting(firstName,lastName);
};

<button id="runButton">Click Me</button>


问:
Prevent Moment js guessing year when the year set as the year 20
I am using moment js and want to check the year the user has entered in the input box. My code looks like this.

```<code>const year = moment('10/12/20', 'DD/MM/YYYY').format("YYYY");
</code>```

year is being returning year as 2020 as opposed to 0020. Does anyone know how to prevent moment from being 'too clever'?

I am using version "moment": "2.17.1". Also, may be related to this issue.

It seems to work here so may be a version issue.

答:
Use the year token consisting of a single Y like here:

```<code>const year = moment('10/12/20', 'DD/MM/Y').format("YYYY");
</code>```

From the momentjs documentation:

YYYY from version 2.10.5 supports 2 digit years, and converts them to
  a year near 2000 (same as YY).

Y was added in 2.11.1. It will match any number, signed or unsigned.
  It is useful for years that are not 4 digits or are before the common
  era. It can be used for any year.

Body:
I am using moment js and want to check the year the user has entered in the input box. My code looks like this.

const year = moment('10/12/20', 'DD/MM/YYYY').format("YYYY");

year is being returning year as 2020 as opposed to 0020. Does anyone know how to prevent moment from being 'too clever'?

I am using version "moment": "2.17.1". Also, may be related to this issue.

It seems to work here so may be a version issue.

Body:
Use the year token consisting of a single Y like here:

const year = moment('10/12/20', 'DD/MM/Y').format("YYYY");

From the momentjs documentation:

YYYY from version 2.10.5 supports 2 digit years, and converts them to
  a year near 2000 (same as YY).

Y was added in 2.11.1. It will match any number, signed or unsigned.
  It is useful for years that are not 4 digits or are before the common
  era. It can be used for any year.


问:
How to get count of distinct values from two columns?
I have a table like below and I want to count distinct values from two columns (fruit1 and fruit2)

```<code>+------+--------+--------+--------+------+
| s_id | s_name | fruit1 | fruit2 | rs   |
+------+--------+--------+--------+------+
|    1 | ram    | apple  | mango  |   20 |
|    2 | raj    | apple  | banana |   13 |
|    3 | aman   | orange | banana |    7 |
|    4 | mangal | orange | apple  |   16 |
|    5 | ravi   | apple  | banana |   17 |
|    6 | pawan  | apple  | apple  |    9 |
|    7 | shyam  | apple  | orange |   11 |
+------+--------+--------+--------+------+
</code>```

I am able to do this for one column using below command, but not success for two column, not getting how to achieve this.

select fruit1, count(*) as count from s_info group by fruit1;

which results in

```<code>+--------+-------+
| fruit1 | count |
+--------+-------+
| apple  |     5 |
| orange |     2 |
+--------+-------+
</code>```

But below is my expected result, which I am not getting.

```<code>+--------+-------+
| fruits | count |
+--------+-------+
| apple  |     7 |
| orange |     3 |
| banana |     3 |
| mango  |     1 |
+--------+-------+
</code>```

答:
Use union all before doing the final aggregation:

```<code>select fruit, count(*)
from ((select fruit1 as fruit from s_info) union all
      (select fruit2 as fruit from s_info)
     ) i
group by fruit;
</code>```

Body:
I have a table like below and I want to count distinct values from two columns (fruit1 and fruit2)

+------+--------+--------+--------+------+
| s_id | s_name | fruit1 | fruit2 | rs   |
+------+--------+--------+--------+------+
|    1 | ram    | apple  | mango  |   20 |
|    2 | raj    | apple  | banana |   13 |
|    3 | aman   | orange | banana |    7 |
|    4 | mangal | orange | apple  |   16 |
|    5 | ravi   | apple  | banana |   17 |
|    6 | pawan  | apple  | apple  |    9 |
|    7 | shyam  | apple  | orange |   11 |
+------+--------+--------+--------+------+

I am able to do this for one column using below command, but not success for two column, not getting how to achieve this.

select fruit1, count(*) as count from s_info group by fruit1;

which results in

+--------+-------+
| fruit1 | count |
+--------+-------+
| apple  |     5 |
| orange |     2 |
+--------+-------+

But below is my expected result, which I am not getting.

+--------+-------+
| fruits | count |
+--------+-------+
| apple  |     7 |
| orange |     3 |
| banana |     3 |
| mango  |     1 |
+--------+-------+

Body:
Use union all before doing the final aggregation:

select fruit, count(*)
from ((select fruit1 as fruit from s_info) union all
      (select fruit2 as fruit from s_info)
     ) i
group by fruit;


问:
How long does RDD remain in memory?
Considering memory being limited, I had a feeling that spark automatically removes RDD from each node. I'd like to know is this time configurable? How does spark decide when to evict an RDD from memory

Note: I'm not talking about rdd.cache()

答:
Measuring the Impact of GC

The first step in GC tuning is to collect statistics on how frequently garbage collection occurs and the amount of time spent GC. This can be done by adding -verbose:gc -XX:+PrintGCDetails -XX:+PrintGCTimeStamps to the Java options. (See the configuration guide for info on passing Java options to Spark jobs.) Next time your Spark job is run, you will see messages printed in the worker’s logs each time a garbage collection occurs. Note these logs will be on your cluster’s worker nodes (in the stdout files in their work directories), not on your driver program.

Advanced GC Tuning

To further tune garbage collection, we first need to understand some basic information about memory management in the JVM:

Java Heap space is divided in to two regions Young and Old. The Young generation is meant to hold short-lived objects while the Old generation is intended for objects with longer lifetimes.

The Young generation is further divided into three regions [Eden, Survivor1, Survivor2].

A simplified description of the garbage collection procedure: When Eden is full, a minor GC is run on Eden and objects that are alive from Eden and Survivor1 are copied to Survivor2. The Survivor regions are swapped. If an object is old enough or Survivor2 is full, it is moved to Old. Finally when Old is close to full, a full GC is invoked.

Title: How long does RDD remain in memory?