问:
python relation between method and function
following the tutorial on https://docs.python.org/3/tutorial/classes.html (see below) to understand the matter deeper I would have expected, that

class Foo:
    def bar(self, spam='spam'):
        i = 3**33

x = Foo()
meth = x.bar
func = Foo.bar

%timeit x.bar('spam')      # 1
%timeit meth('spam')       # 2
%timeit func(x, 'spam')    # 3
```

should be in the order slow to fast. But it's not, the call to meth() takes 100ns, the call to func 110ns (#1 is slower as expected).

from the explanation below I would have thought, that in #2 the method f has to be unpacked into the function and the class instance, then the argument list prepended with the instance, and the function called. Why is it not slower then #3 where you have only the plain function call.

What is wrong?

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

答:
If you disassemble the bytecode that comes out of the three calls you get the following:

```<code>1         0 LOAD_NAME                0 (x)
          2 LOAD_METHOD              1 (bar)
          4 LOAD_CONST               0 ('spam')
          6 CALL_METHOD              1
          8 RETURN_VALUE

1         0 LOAD_NAME                0 (f)
          2 LOAD_CONST               0 ('spam')
          4 CALL_FUNCTION            1
          6 RETURN_VALUE

1         0 LOAD_NAME                0 (Foo)
          2 LOAD_METHOD              1 (bar)
          4 LOAD_NAME                2 (x)
          6 LOAD_CONST               0 ('spam')
          8 CALL_METHOD              2
         10 RETURN_VALUE
</code>```

You can see that the first and last ones actually end up doing more work. The middle one already has the function in hand so it can call it immediately (because you've already pulled it out of the class with f = x.bar) wheras the other ones still have to do a dict lookup in the class.

Body:
following the tutorial on https://docs.python.org/3/tutorial/classes.html (see below) to understand the matter deeper I would have expected, that

class Foo:
    def bar(self, spam='spam'):
        i = 3**33

x = Foo()
meth = x.bar
func = Foo.bar

%timeit x.bar('spam')      # 1
%timeit meth('spam')       # 2
%timeit func(x, 'spam')    # 3

should be in the order slow to fast. But it's not, the call to meth() takes 100ns, the call to func 110ns (#1 is slower as expected).

from the explanation below I would have thought, that in #2 the method f has to be unpacked into the function and the class instance, then the argument list prepended with the instance, and the function called. Why is it not slower then #3 where you have only the plain function call.

What is wrong?

If you still don’t understand how methods work, a look at the implementation can perhaps clarify matters. When a non-data attribute of an instance is referenced, the instance’s class is searched. If the name denotes a valid class attribute that is a function object, a method object is created by packing (pointers to) the instance object and the function object just found together in an abstract object: this is the method object. When the method object is called with an argument list, a new argument list is constructed from the instance object and the argument list, and the function object is called with this new argument list.

Body:
If you disassemble the bytecode that comes out of the three calls you get the following:

1         0 LOAD_NAME                0 (x)
          2 LOAD_METHOD              1 (bar)
          4 LOAD_CONST               0 ('spam')
          6 CALL_METHOD              1
          8 RETURN_VALUE

1         0 LOAD_NAME                0 (f)
          2 LOAD_CONST               0 ('spam')
          4 CALL_FUNCTION            1
          6 RETURN_VALUE

1         0 LOAD_NAME                0 (Foo)
          2 LOAD_METHOD              1 (bar)
          4 LOAD_NAME                2 (x)
          6 LOAD_CONST               0 ('spam')
          8 CALL_METHOD              2
         10 RETURN_VALUE

You can see that the first and last ones actually end up doing more work. The middle one already has the function in hand so it can call it immediately (because you've already pulled it out of the class with f = x.bar) wheras the other ones still have to do a dict lookup in the class.


来源: stackexchange

问:
how to fix "can't resolve rxkotlin" in android
I'm using room database and need to add rxKotlin to my project, so when I use this code:

```<code>`implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1'`
</code>```

I get this error:

```<code>`ERROR: Failed to resolve: io.reactivex.rxjava2:rxkotlin:2.0.1`
</code>```

how can I fix it?

答:
That's the correct repo</p>

```<code>implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1-RC1'
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using room database and need to add rxKotlin to my project, so when I use this code:

`implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1'`

I get this error:

`ERROR: Failed to resolve: io.reactivex.rxjava2:rxkotlin:2.0.1`

how can I fix it?

Body:
That's the correct repo

implementation 'io.reactivex.rxjava2:rxkotlin:2.0.1-RC1'


问:
Are there any diagnostics tools for troubleshooting content delivery with Opera Mini?
I have an application that I'm targeting a wide variety of devices and platforms. The application can render different HTML based upon the type of client.  However due to the complexity of the application, it shares a considerable amount of JavaScript libraries that rely on a number of async and ajax method calls.

One of the targets for the application is Opera Mini.  This "sort-of" works but it seems like sometimes when building up the specialized markup to send down to the Opera Mini JVM client it does not wait until the async calls are complete.  Are there any techniques or tools to see what's going on with the Opera Server (not my application web server) Side processing of the page to determine what I can do to make this solid?

答:
Your javascript will only be allowed a short time before it is aborted:

JavaScript running on the Mini server
  will only run for a couple of seconds
  before pausing, for resource
  constraint reasons. This applies to
  JavaScript run due to an event firing
  e.g. onload, as well as code run
  because of a user action.

~ http://dev.opera.com/articles/view/opera-mini-web-content-authoring-guidelines/#javascript

So the best would be to serve the least javascripty version of your site to the Opera Mini user-agent.

OwnerDisplayName: Kevin

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Angular RxJS: Hot Observable turned to Cold
This is my related code:

```<code>private searchClickSubject:Subject<void>;  // Submit form
private searchClick$:Observable<any>;
private metrics$:Observable<MetricGroup>;

constructor() {
    // Prepare observers
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}

public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: AmetriquesComponent.DEFAULT_PAGE_SIZE
        })
    );

    const loading = () => tap(() => this.loadingPage());
    const getAggregatedMetrics = () => switchMap((query: Query) => this.service.getAggregatedMetrics(query));
    const loaded = () => tap((aggregatedMetrics: MetricGroup) => this.loadedMetric(aggregatedMetrics));

    this.metrics$ = this.searchQuery$
        .pipe(
            loading(),
            getAggregatedMetrics(),
            loaded(),
            share()
        );
}
</code>```

First of all, I think searchClick$ Observable is hot, since form is generating on submit events regardless of any subscription is attached on.

As you can see, after an "submit" event is emitted, I make an http request. So for each "submit form" emitted a new http request is emitted.

When I attach a subscription on that last Observable, a separate http request is made, so it sounds like first Observable has turned on a cold Observable.

What do you think about my train of thoughs?

答: I still see this as a hot observable since it will never emit a complete notification. The inner subscription of getAggregatedMetrics will emit one, but not the outer one. Also share() turns cold observables hot per this article. Unless I'm not understanding the question?

Body:
This is my related code:

private searchClickSubject:Subject<void>;  // Submit form
private searchClick$:Observable<any>;
private metrics$:Observable<MetricGroup>;

constructor() {
    // Prepare observers
    this.searchClickSubject = new Subject<void>();
    this.searchClick$ = this.searchClickSubject.asObservable();
}

public ngOnInit() {
    // Grab search button click event
    this.searchQuery$ = this.searchClick$.pipe(
        map(() => <Query>{
            offset: 0,
            limit: AmetriquesComponent.DEFAULT_PAGE_SIZE
        })
    );

    const loading = () => tap(() => this.loadingPage());
    const getAggregatedMetrics = () => switchMap((query: Query) => this.service.getAggregatedMetrics(query));
    const loaded = () => tap((aggregatedMetrics: MetricGroup) => this.loadedMetric(aggregatedMetrics));

    this.metrics$ = this.searchQuery$
        .pipe(
            loading(),
            getAggregatedMetrics(),
            loaded(),
            share()
        );
}

First of all, I think searchClick$ Observable is hot, since form is generating on submit events regardless of any subscription is attached on.

As you can see, after an "submit" event is emitted, I make an http request. So for each "submit form" emitted a new http request is emitted.

When I attach a subscription on that last Observable, a separate http request is made, so it sounds like first Observable has turned on a cold Observable.

What do you think about my train of thoughs?


问:
Angular 2 Show and Hide an element
I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2.

this is the code for the div to show and hide:

```<code><div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>
</code>```

the variable is "edited" and it's stored in my component:

export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }, 3000);
  }
}
```

The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why?

答:
Just add bind(this) in your setTimeout function it will start working

```<code>setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);
</code>```

and in HTML change

```<code><div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>
</code>```

To

```<code><div *ngIf="edited" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>
</code>```

Title: Angular 2 Show and Hide an element

Body:
I'm having a problem hiding and showing an element depending of a boolean variable in Angular 2.

this is the code for the div to show and hide:

        List Saved! Your changes has been saved.

the variable is "edited" and it's stored in my component:

export class AppComponent implements OnInit{

  (...)
  public edited = false;
  (...)
  saveTodos(): void {
   //show box msg
   this.edited = true;
   //wait 3 Seconds and hide
   setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }, 3000);
  }
}

The element is hidden, when saveTodos function starts, the element is shown, but after 3 seconds, even if the variable come back to be false, the element does not hide. Why?

Body:
Just add bind(this) in your setTimeout function it will start working

setTimeout(function() {
       this.edited = false;
       console.log(this.edited);
   }.bind(this), 3000);

and in HTML change

<div *ngIf="edited==true" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>

To

<div *ngIf="edited" class="alert alert-success alert-dismissible fade in" role="alert">
        <strong>List Saved!</strong> Your changes has been saved.
</div>


问:
Stop execution while timer is running
I am building a board game using VB.net. My problem is that when I have a timer running (for sprite animation) the rest of my program continues executing. Is there some way to delay the execution of the program until the timer has been disabled?

I have tried using Threading.thread.sleep() but this only delays the whole process., I assume this is because both the timer and the function that starts it are running on the same thread?

While nextSpace <> endSpace
            nextSpace += 1
            timerMov.Start()
            Threading.Thread.Sleep(timerMov.Interval * 100)
End While

Private Sub mov_Tick(sender As Object, e As EventArgs) Handles timerMov.Tick
        curShip.img.Location = New Point(...)
        If i = 100 Then
            timerMov.Stop()
            i = 0
        End If
        i += 1
    End Sub
```

This results in things occurring before I want them to, i.e the user receives information about the space they have landed on before the animation has completed of them landing on said space.

Thanks for any help :)

答:
Essentially what happens is the timer is started from a while loop
  inside a subroutine. I want the while loop to wait until the timer has
  been stopped before looping again.

Get rid of the timer and use Async/Await.

Here is what it'd look like, boiled down to its essence:

```<code>Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' ... possibly more code ...

    While nextSpace <> endSpace
        nextSpace += 1

        For i As Integer = 0 To 100
            Await Task.Delay(someDelayIntervalHere)
            curShip.img.Location = New Point(...)
        Next
    End While

    ' ... possibly more code ...

End Sub
</code>```

Note that the Sub has been marked with Async in its declaration line.  Inside the loop the Await line causes it to pause (replacing the Tick event of the Timer), but does so in a way that doesn't cause the interface to freeze up.

Title: Stop execution while timer is running

Body:
I am building a board game using VB.net. My problem is that when I have a timer running (for sprite animation) the rest of my program continues executing. Is there some way to delay the execution of the program until the timer has been disabled?

I have tried using Threading.thread.sleep() but this only delays the whole process., I assume this is because both the timer and the function that starts it are running on the same thread?

While nextSpace <> endSpace
            nextSpace += 1
            timerMov.Start()
            Threading.Thread.Sleep(timerMov.Interval * 100)
End While

Private Sub mov_Tick(sender As Object, e As EventArgs) Handles timerMov.Tick
        curShip.img.Location = New Point(...)
        If i = 100 Then
            timerMov.Stop()
            i = 0
        End If
        i += 1
    End Sub

This results in things occurring before I want them to, i.e the user receives information about the space they have landed on before the animation has completed of them landing on said space.

Thanks for any help :)

Body:
Essentially what happens is the timer is started from a while loop
  inside a subroutine. I want the while loop to wait until the timer has
  been stopped before looping again.

Get rid of the timer and use Async/Await.

Here is what it'd look like, boiled down to its essence:

Private Async Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    ' ... possibly more code ...

    While nextSpace <> endSpace
        nextSpace += 1

        For i As Integer = 0 To 100
            Await Task.Delay(someDelayIntervalHere)
            curShip.img.Location = New Point(...)
        Next
    End While

    ' ... possibly more code ...

End Sub

Note that the Sub has been marked with Async in its declaration line.  Inside the loop the Await line causes it to pause (replacing the Tick event of the Timer), but does so in a way that doesn't cause the interface to freeze up.


问:
Is this a bug in the boost library
I'm compiling a project with autotools and am using g++ in version gcc version 5.3.1 and boost version 1_63. After aclocal, autoconf, autoheader, automake --add-missing, I ran configure with some options, which succedded and build make a Makefile. Running make fails and gives me the error (excerpt):

```<code>In file included from /usr/local/include/boost/ratio/ratio.hpp:46:0,
             from /usr/local/include/boost/chrono/duration.hpp:41,
             from /usr/local/include/boost/chrono/time_point.hpp:33,
             from /usr/local/include/boost/thread/lock_types.hpp:22,
             from /usr/local/include/boost/thread/pthread/mutex.hpp:16,
             from /usr/local/include/boost/thread/mutex.hpp:16,
             from src/cosupport-initializer/cpp/BasicInitializer.cpp:39:
/usr/local/include/boost/integer_traits.hpp:83:46: error: 'CHAR_MIN' was not declared in this scope
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                          ^
/usr/local/include/boost/integer_traits.hpp:83:56: error: 'CHAR_MAX' was not declared in this scope
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                                    ^
/usr/local/include/boost/integer_traits.hpp:83:64: error: template argument 2 is invalid
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:83:64: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:89:53: error: 'SCHAR_MIN' was not declared in this scope
public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                 ^
/usr/local/include/boost/integer_traits.hpp:89:64: error: 'SCHAR_MAX' was not declared in this scope
 public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:89:73: error: template argument 2 is invalid
public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                                     ^
/usr/local/include/boost/integer_traits.hpp:89:73: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:95:58: error: 'UCHAR_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned char, 0, UCHAR_MAX>
                                                      ^
/usr/local/include/boost/integer_traits.hpp:95:67: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned char, 0, UCHAR_MAX>
                                                               ^
/usr/local/include/boost/integer_traits.hpp:131:47: error: 'SHRT_MIN' was not declared in this scope
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                           ^
/usr/local/include/boost/integer_traits.hpp:131:57: error: 'SHRT_MAX' was not declared in this scope
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                                     ^
/usr/local/include/boost/integer_traits.hpp:131:65: error: template argument 2 is invalid
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                                             ^
/usr/local/include/boost/integer_traits.hpp:131:65: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:137:59: error: 'USHRT_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned short, 0, USHRT_MAX>
                                                       ^
/usr/local/include/boost/integer_traits.hpp:137:68: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned short, 0, USHRT_MAX>
                                                                ^
/usr/local/include/boost/integer_traits.hpp:143:45: error: 'INT_MIN' was not declared in this scope
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                         ^
/usr/local/include/boost/integer_traits.hpp:143:54: error: 'INT_MAX' was not declared in this scope
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                                  ^
/usr/local/include/boost/integer_traits.hpp:143:61: error: template argument 2 is invalid
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                                         ^
/usr/local/include/boost/integer_traits.hpp:143:61: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:149:57: error: 'UINT_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned int, 0, UINT_MAX>
                                                     ^
/usr/local/include/boost/integer_traits.hpp:149:65: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned int, 0, UINT_MAX>
                                                             ^
/usr/local/include/boost/integer_traits.hpp:155:46: error: 'LONG_MIN' was not declared in this scope
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                          ^
/usr/local/include/boost/integer_traits.hpp:155:56: error: 'LONG_MAX' was not declared in this scope
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                                    ^
/usr/local/include/boost/integer_traits.hpp:155:64: error: template argument 2 is invalid
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:155:64: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:161:58: error: 'ULONG_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned long, 0, ULONG_MAX>
                                                      ^
/usr/local/include/boost/integer_traits.hpp:161:67: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned long, 0, ULONG_MAX>
</code>```

This means e.g. that in /usr/local/include/boost/integer_traits.hpp on line 83, the constructor initialization fails:

```<code>template<>
class integer_traits<char>
  : public std::numeric_limits<char>,
    public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
{ };
</code>```

This means in the file /usr/local/include/boost/integer_traits.hpp and headers included in it, there's no definition of CHAR_MIN. So this is a bug in boost? Or what am I missing here?

UPDATE

The relevant code excerpts. Before the move:

```<code>#include <CoSupport/compatibility-glue/nullptr.h>
#include <CoSupport/Initializer/BasicInitializer.hpp>
#include <boost/thread/mutex.hpp>
#include <cassert>

namespace CoSupport {
...
}
</code>```

After the move:

```<code>#include <boost/thread/mutex.hpp>
#include <CoSupport/compatibility-glue/nullptr.h>
#include <CoSupport/Initializer/BasicInitializer.hpp>
#include <cassert>

namespace CoSupport {
...
}
</code>```

答:
This means in the file /usr/local/include/boost/integer_traits.hpp and headers included in it, there's no definition of CHAR_MIN

Which is as it should be - CHAR_MIN is defined in <climits>.

So this is a bug in boost? Or what am I missing here?

With 99% certainty, this is not a bug in boost. You probably have some include files of your own, in your project's include directories, masking climits or limits.h, or possibly another file which interger_traits.hpp includes and itself includes climits or limits.h.

Title: Is this a bug in the boost library

Body:
I'm compiling a project with autotools and am using g++ in version gcc version 5.3.1 and boost version 1_63. After aclocal, autoconf, autoheader, automake --add-missing, I ran configure with some options, which succedded and build make a Makefile. Running make fails and gives me the error (excerpt):

In file included from /usr/local/include/boost/ratio/ratio.hpp:46:0,
             from /usr/local/include/boost/chrono/duration.hpp:41,
             from /usr/local/include/boost/chrono/time_point.hpp:33,
             from /usr/local/include/boost/thread/lock_types.hpp:22,
             from /usr/local/include/boost/thread/pthread/mutex.hpp:16,
             from /usr/local/include/boost/thread/mutex.hpp:16,
             from src/cosupport-initializer/cpp/BasicInitializer.cpp:39:
/usr/local/include/boost/integer_traits.hpp:83:46: error: 'CHAR_MIN' was not declared in this scope
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                          ^
/usr/local/include/boost/integer_traits.hpp:83:56: error: 'CHAR_MAX' was not declared in this scope
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                                    ^
/usr/local/include/boost/integer_traits.hpp:83:64: error: template argument 2 is invalid
public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:83:64: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:89:53: error: 'SCHAR_MIN' was not declared in this scope
public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                 ^
/usr/local/include/boost/integer_traits.hpp:89:64: error: 'SCHAR_MAX' was not declared in this scope
 public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:89:73: error: template argument 2 is invalid
public detail::integer_traits_base<signed char, SCHAR_MIN, SCHAR_MAX>
                                                                     ^
/usr/local/include/boost/integer_traits.hpp:89:73: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:95:58: error: 'UCHAR_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned char, 0, UCHAR_MAX>
                                                      ^
/usr/local/include/boost/integer_traits.hpp:95:67: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned char, 0, UCHAR_MAX>
                                                               ^
/usr/local/include/boost/integer_traits.hpp:131:47: error: 'SHRT_MIN' was not declared in this scope
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                           ^
/usr/local/include/boost/integer_traits.hpp:131:57: error: 'SHRT_MAX' was not declared in this scope
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                                     ^
/usr/local/include/boost/integer_traits.hpp:131:65: error: template argument 2 is invalid
public detail::integer_traits_base<short, SHRT_MIN, SHRT_MAX>
                                                             ^
/usr/local/include/boost/integer_traits.hpp:131:65: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:137:59: error: 'USHRT_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned short, 0, USHRT_MAX>
                                                       ^
/usr/local/include/boost/integer_traits.hpp:137:68: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned short, 0, USHRT_MAX>
                                                                ^
/usr/local/include/boost/integer_traits.hpp:143:45: error: 'INT_MIN' was not declared in this scope
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                         ^
/usr/local/include/boost/integer_traits.hpp:143:54: error: 'INT_MAX' was not declared in this scope
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                                  ^
/usr/local/include/boost/integer_traits.hpp:143:61: error: template argument 2 is invalid
public detail::integer_traits_base<int, INT_MIN, INT_MAX>
                                                         ^
/usr/local/include/boost/integer_traits.hpp:143:61: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:149:57: error: 'UINT_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned int, 0, UINT_MAX>
                                                     ^
/usr/local/include/boost/integer_traits.hpp:149:65: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned int, 0, UINT_MAX>
                                                             ^
/usr/local/include/boost/integer_traits.hpp:155:46: error: 'LONG_MIN' was not declared in this scope
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                          ^
/usr/local/include/boost/integer_traits.hpp:155:56: error: 'LONG_MAX' was not declared in this scope
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                                    ^
/usr/local/include/boost/integer_traits.hpp:155:64: error: template argument 2 is invalid
public detail::integer_traits_base<long, LONG_MIN, LONG_MAX>
                                                            ^
/usr/local/include/boost/integer_traits.hpp:155:64: error: template argument 3 is invalid
/usr/local/include/boost/integer_traits.hpp:161:58: error: 'ULONG_MAX' was not declared in this scope
public detail::integer_traits_base<unsigned long, 0, ULONG_MAX>
                                                      ^
/usr/local/include/boost/integer_traits.hpp:161:67: error: template argument 3 is invalid
public detail::integer_traits_base<unsigned long, 0, ULONG_MAX>

This means e.g. that in /usr/local/include/boost/integer_traits.hpp on line 83, the constructor initialization fails:

template<>
class integer_traits<char>
  : public std::numeric_limits<char>,
    public detail::integer_traits_base<char, CHAR_MIN, CHAR_MAX>
{ };

This means in the file /usr/local/include/boost/integer_traits.hpp and headers included in it, there's no definition of CHAR_MIN. So this is a bug in boost? Or what am I missing here?

UPDATE

The relevant code excerpts. Before the move:

#include <CoSupport/compatibility-glue/nullptr.h>
#include <CoSupport/Initializer/BasicInitializer.hpp>
#include <boost/thread/mutex.hpp>
#include <cassert>

namespace CoSupport {
...
}

After the move:

#include <boost/thread/mutex.hpp>
#include <CoSupport/compatibility-glue/nullptr.h>
#include <CoSupport/Initializer/BasicInitializer.hpp>
#include <cassert>

namespace CoSupport {
...
}


问:
Question about wordpress blog
I have started a wordpress blog hosted on (free)wordpress.com. Now it has good alexa ranking. I post after two or three days. I want to earn from this blog via google adsense. What is the best way to earn money from this. Please Give Suggestions.

Thanks.

答:
Buy a domain and hosting, Host wordpress blog there. Work hard to generate unique and quality contents.

Then apply for google adsence account...!
That's it.

Title: Question about wordpress blog


问:
Google Cloud Function - Function load error: File main.py that is expected to define function doesn't exist
I am trying to implement a Google Cloud function that is based on code in a Git style repository.  I have the code linked to Google Cloud Platform's "Source Repositories" and my function runs fine when I copy and paste the code into the GCP Function "Inline editor".  When I switch to the "Cloud Source repository" option, I can tell that it is reading from that repository; I worked through other errors prior to this one.  However, after resolving prior/other issues, now I'm getting this error:

Function load error: File main.py that is expected to define function doesn't exist

my files are in a structure similar to this, with main.py in the root directory:

```<code>.
├── package
|   ├──script1.py
|   └──script2.py
├── package2
├── ...
├── main.py
└── requirements.txt
</code>```

It's reading fine from requirements.txt (some of the prior errors came from that reading process), but why is it not reading from main.py?  My setup in the GCP Function looks like this:

I have tried to move main.py to another directory in the project and setting the "Directory with source code" to that directory, but that gave me an error saying that it couldn't find that directory.  Any constructive ideas?

Edit / Additional Information

I am using a branch from my repository other than master, and I am using a Google Cloud Pubsub topic trigger for this function.

答:
If you're trying to upload your code zip using a GCS bucket or the file upload function, make sure that you don't zip the folder that contains your code but just the code files.

```<code>CodeFolder
├── package
|   ├──script1.py
|   └──script2.py
├── package2
├── ...
├── main.py
└── requirements.txt
</code>```

Do NOT create a Zip file from the CodeFolder.

Instead, create a zip file from main.py and requirement.txt and package.

Source

Body:
I am trying to implement a Google Cloud function that is based on code in a Git style repository.  I have the code linked to Google Cloud Platform's "Source Repositories" and my function runs fine when I copy and paste the code into the GCP Function "Inline editor".  When I switch to the "Cloud Source repository" option, I can tell that it is reading from that repository; I worked through other errors prior to this one.  However, after resolving prior/other issues, now I'm getting this error:

Function load error: File main.py that is expected to define function doesn't exist

my files are in a structure similar to this, with main.py in the root directory:

.
├── package
|   ├──script1.py
|   └──script2.py
├── package2
├── ...
├── main.py
└── requirements.txt

It's reading fine from requirements.txt (some of the prior errors came from that reading process), but why is it not reading from main.py?  My setup in the GCP Function looks like this:

I have tried to move main.py to another directory in the project and setting the "Directory with source code" to that directory, but that gave me an error saying that it couldn't find that directory.  Any constructive ideas?

Edit / Additional Information

I am using a branch from my repository other than master, and I am using a Google Cloud Pubsub topic trigger for this function.

Body:
If you're trying to upload your code zip using a GCS bucket or the file upload function, make sure that you don't zip the folder that contains your code but just the code files.

CodeFolder
├── package
|   ├──script1.py
|   └──script2.py
├── package2
├── ...
├── main.py
└── requirements.txt

Do NOT create a Zip file from the CodeFolder.

Instead, create a zip file from main.py and requirement.txt and package.

Source


问:
How to re-run failed TestNG tests using Gradle
I know what TestNG generates testng-failed.xml with information about failed test.
I'd like to use it in Gradle to created new task for running failed tests:

```<code>task secondTry(type: Test) {
onlyIf {
    file("build/reports/tests/test/testng-failed.xml").exists()
}
println file("build/reports/tests/test/testng-failed.xml").exists()

testClassesDir = sourceSets.test.output.classesDir
classpath = sourceSets.test.runtimeClasspath

useTestNG() {
    suites("build/reports/tests/test/testng-failed.xml")
}
}
</code>```

Aftrer running task secondTry I got true for println file("build/reports/tests/test/testng-failed.xml").exists(), but failed tests are not run and task is skipped: secondTry SKIPPED

Does anyone experience in such cases, how to make tests run?

UPDATE:
I've tried to modify task a bit, so just run testng-failed.xml:

```<code>task secondTry(type: Test) {
useTestNG() {
    useDefaultListeners = true
    reports.html.enabled = false
    options.suites("build/reports/tests/test/testng-failed.xml")
}
}
</code>```

As result, build is successfully executed, including secondTry task, but failed tests still are not run.

答: This can be achieved by a TestNG's feature called RetryAnalyzer. With few little tweaks, we can tell TestNG that how many times a test should get retried until it gets passed and what kind of exceptions/errors would trigger the retrying of the failed test methods.</p>

Body:
I know what TestNG generates testng-failed.xml with information about failed test.
I'd like to use it in Gradle to created new task for running failed tests:

task secondTry(type: Test) {
onlyIf {
    file("build/reports/tests/test/testng-failed.xml").exists()
}
println file("build/reports/tests/test/testng-failed.xml").exists()

testClassesDir = sourceSets.test.output.classesDir
classpath = sourceSets.test.runtimeClasspath

useTestNG() {
    suites("build/reports/tests/test/testng-failed.xml")
}
}

Aftrer running task secondTry I got true for println file("build/reports/tests/test/testng-failed.xml").exists(), but failed tests are not run and task is skipped: secondTry SKIPPED

Does anyone experience in such cases, how to make tests run?

UPDATE:
I've tried to modify task a bit, so just run testng-failed.xml:

task secondTry(type: Test) {
useTestNG() {
    useDefaultListeners = true
    reports.html.enabled = false
    options.suites("build/reports/tests/test/testng-failed.xml")
}
}

As result, build is successfully executed, including secondTry task, but failed tests still are not run.


问:
Apache Ignite 2.7: ODBC Linux - Bad data returned
I am testing out the Apache Ignite 2.7 Linux ODBC Driver, and it's not working correctly for some reason.

When I run a SQL statement, like SELECT Id FROM MyTable, the value is "garbled" returning a value like 8\00\05\07\09\0d\09\08\0-\0 for the the Id column. It's similar to the value I expect, though, which is 80579d98-9010-4610-b12e-ed33ed7d3c62. I don't know if those are ASCII null characters (\0), or what, but something isn't right and I can't figure it out.

When I use the SQLLine tool, the values are not "garbled". I also installed the Windows ODBC driver, and that worked fine, but I need the Linux ODBC Driver.

I built the driver with the following libraries:

```<code>gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
GNU Make 4.1
libtoolize 2.4.6
aclocal 1.15
autoheader 2.69
automake 1.15
autoreconf 2.69
unixodbc 2.3.4-1
libssl 1.0.2r-1~deb9u1
</code>```

Here's the contents of the ignite-odbc-install.ini:

```<code># cat /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
[Apache Ignite]
Description=Apache Ignite
Driver=/usr/local/lib/libignite-odbc.so
Setup=/usr/local/lib/libignite-odbc.so
DriverODBCVer=03.00
FileUsage=0
</code>```

Here's the result of running odbcinst:

```<code># odbcinst -i -d -f /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
odbcinst: Driver installed. Usage count increased to 1.
    Target directory is /etc
</code>```

Here's the contents of the /usr/local/lib folder:

```<code># cd /usr/local/lib
# ls
libignite-binary-2.7.0.33575.so.0      libignite-common-2.7.0.33575.so.0      libignite-odbc-2.7.0.33575.so.0      libignite-thin-client-2.7.0.33575.so.0
libignite-binary-2.7.0.33575.so.0.0.0  libignite-common-2.7.0.33575.so.0.0.0  libignite-odbc-2.7.0.33575.so.0.0.0  libignite-thin-client-2.7.0.33575.so.0.0.0
libignite-binary.a                     libignite-common.a                     libignite-odbc.a                     libignite-thin-client.a
libignite-binary.la                    libignite-common.la                    libignite-odbc.la                    libignite-thin-client.la
libignite-binary.so                    libignite-common.so                    libignite-odbc.so                    libignite-thin-client.so
</code>```

Here's the result from the ldd command:

```<code># ldd /usr/local/lib/libignite-odbc.so
        linux-vdso.so.1 (0x00007fffa46d0000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f18d554c000)
        libignite-binary-2.7.0.33575.so.0 => /usr/local/lib/libignite-binary-2.7.0.33575.so.0 (0x00007f18d531d000)
        libodbcinst.so.2 => /usr/lib/x86_64-linux-gnu/libodbcinst.so.2 (0x00007f18d5108000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f18d4d86000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f18d4a82000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f18d46e3000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f18d44cc000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f18d59f8000)
        libignite-common-2.7.0.33575.so.0 => /usr/local/lib/libignite-common-2.7.0.33575.so.0 (0x00007f18d42b5000)
        libltdl.so.7 => /usr/lib/x86_64-linux-gnu/libltdl.so.7 (0x00007f18d40ab000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f18d3e8e000)
</code>```

UPDATE 1

I ran this from a .Net Core 2.2 C# Console program, with only the System.Data.Odbc 4.5.0 NuGet reference in a Docker Linux Environment.

IgniteGarbledDataReproducer.csproj

```<code><Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Data.Odbc" Version="4.5.0" />
  </ItemGroup>

</Project>
</code>```

Program.cs

```<code>using System;
using System.Data.Odbc;

namespace IgniteGarbledDataReproducer {
    internal class Program {
        private static void Main(string[] args) {
            Console.WriteLine("START");

            var connectionString = Environment.GetEnvironmentVariable("IGNITE_CONNECTION_STRING");
            Console.WriteLine(connectionString);

            using (var conn = new OdbcConnection(connectionString)) {
                conn.Open();

                Console.WriteLine("Connection Opened");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "DROP TABLE IF EXISTS MyTable;";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Table Dropped (if it existed)");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "CREATE TABLE MyTable (Id varchar(36) not null, FirstName varchar(255), LastName varchar(255), PRIMARY KEY (Id));";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Table Created");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "INSERT INTO MyTable (Id) VALUES ('80579d98-9010-4610-b12e-ed33ed7d3c62');";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Data Inserted");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "SELECT Id FROM MyTable;";
                    using (var rdr = cmd.ExecuteReader()) {
                        while (rdr.Read())
                            Console.WriteLine($"Id = '{rdr["Id"]}'");
                    }
                }

                Console.WriteLine("Data Returned");
            }

            Console.WriteLine("DONE");
        }
    }
}
</code>```

Dockerfile

```<code>FROM microsoft/dotnet:2.2-runtime AS base
WORKDIR /app

WORKDIR /src
# Install pre-requisites for building and installing Ignite ODBC Driver
RUN apt-get update \
    && apt-get install -y gcc g++ make automake autotools-dev libtool m4 libssl1.0-dev unixodbc-dev unixodbc-bin unzip \
    && apt-get clean -y

# Download and unzip Ignite binary release
#ADD http://apache.mirrors.hoobly.com/ignite/2.7.0/apache-ignite-2.7.0-bin.zip /src/
COPY apache-ignite-2.7.0-bin.zip .
RUN unzip -q /src/apache-ignite-2.7.0-bin.zip \
    && rm /src/apache-ignite-2.7.0-bin.zip

# Build Ignite ODBC Driver
ARG IGNITE_HOME=/src/apache-ignite-2.7.0-bin
WORKDIR /src/apache-ignite-2.7.0-bin/platforms/cpp
RUN libtoolize \
    && aclocal \
    && autoheader \
    && automake --add-missing \
    && autoreconf \
    && ./configure --enable-odbc --disable-core --disable-node \
    && make \
    && make install

# Install Ignite ODBC Driver
RUN apt-get update \
    && apt-get install -y unixodbc \
    && apt-get clean -y \
    && odbcinst -i -d -f /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY IgniteGarbledDataReproducer/IgniteGarbledDataReproducer.csproj IgniteGarbledDataReproducer/
RUN dotnet restore IgniteGarbledDataReproducer/IgniteGarbledDataReproducer.csproj
COPY . .
WORKDIR /src/IgniteGarbledDataReproducer
RUN dotnet build IgniteGarbledDataReproducer.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish IgniteGarbledDataReproducer.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "IgniteGarbledDataReproducer.dll"]
</code>```

docker-compose.yml

```<code>version: '3.4'

services:
  ignitegarbleddatareproducer:
    image: ${DOCKER_REGISTRY-}ignite-garbled-data-reproducer
    build:
      context: .
      dockerfile: IgniteGarbledDataReproducer/Dockerfile
</code>```

docker-compose-override.yml

```<code>version: '3.4'

services:
  ignitegarbleddatareproducer:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - IGNITE_CONNECTION_STRING=DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;
</code>```

Build

```<code># cat /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
[Apache Ignite]
Description=Apache Ignite
Driver=/usr/local/lib/libignite-odbc.so
Setup=/usr/local/lib/libignite-odbc.so
DriverODBCVer=03.00
FileUsage=0
</code>```0

Execute

```<code># cat /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
[Apache Ignite]
Description=Apache Ignite
Driver=/usr/local/lib/libignite-odbc.so
Setup=/usr/local/lib/libignite-odbc.so
DriverODBCVer=03.00
FileUsage=0
</code>```1

UPDATE 2

I turned on ODBC logging by adding the following to /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini and you can get the logs here.

```<code># cat /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
[Apache Ignite]
Description=Apache Ignite
Driver=/usr/local/lib/libignite-odbc.so
Setup=/usr/local/lib/libignite-odbc.so
DriverODBCVer=03.00
FileUsage=0
</code>```2

The end of the log after the SELECT Id From MyTable; statement is below for convenience.

```<code>[ODBC][1][1556564832.827181][SQLExecDirectW.c][177]
        Entry:
            Statement = 0xf27a80
            SQL = [SELECT Id FROM MyTable;][length = 23 (SQL_NTS)]
[ODBC][1][1556564832.847882][SQLExecDirectW.c][445]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.852889][SQLRowCount.c][173]
        Entry:
            Statement = 0xf27a80
            Row Count = 0x7ffd7da98f00
[ODBC][1][1556564832.856831][SQLRowCount.c][247]
        Exit:[SQL_SUCCESS]
            Row Count = 0x7ffd7da98f00 -> 0
[ODBC][1][1556564832.860335][SQLNumResultCols.c][156]
        Entry:
            Statement = 0xf27a80
            Column Count = 0x7ffd7da98f50
[ODBC][1][1556564832.864944][SQLNumResultCols.c][251]
        Exit:[SQL_SUCCESS]
            Count = 0x7ffd7da98f50 -> 1
[ODBC][1][1556564832.869909][SQLFetch.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.884876][SQLFetch.c][351]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.894173][SQLColAttributeW.c][156]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Field Identifier = SQL_DESC_NAME
            Character Attr = 0xf2e190
            Buffer Length = 4096
            String Length = 0x7ffd7da98f20
            Numeric Attribute = 0x7ffd7da98ee0
[ODBC][1][1556564832.898409][SQLColAttributeW.c][523]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.910800][SQLColAttributeW.c][156]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Field Identifier = SQL_DESC_CONCISE_TYPE
            Character Attr = 0xf2e190
            Buffer Length = 4096
            String Length = 0x7ffd7da98f40
            Numeric Attribute = 0x7ffd7da98f00
[ODBC][1][1556564832.914551][SQLColAttributeW.c][523]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.925913][SQLGetData.c][237]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Target Type = -8 SQL_WCHAR
            Buffer Length = 4094
            Target Value = 0xf2e190
            StrLen Or Ind = 0x7ffd7da98ee0
[ODBC][1][1556564832.929959][SQLGetData.c][534]
        Exit:[SQL_SUCCESS]
            Buffer = [8](unicode)
            Strlen Or Ind = 0x7ffd7da98ee0 -> 36
[ODBC][1][1556564832.934835][SQLFetch.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.938930][SQLFetch.c][351]
        Exit:[SQL_NO_DATA]
[ODBC][1][1556564832.943970][SQLMoreResults.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.960311][SQLMoreResults.c][345]
        Exit:[SQL_NO_DATA]
[ODBC][1][1556564832.965960][SQLFreeStmt.c][144]
        Entry:
            Statement = 0xf27a80
            Option = 0
[ODBC][1][1556564832.970025][SQLFreeStmt.c][266]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.975135][SQLFreeHandle.c][381]
        Entry:
            Handle Type = 3
            Input Handle = 0xf27a80
[ODBC][1][1556564832.981240][SQLFreeHandle.c][494]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.991337][SQLDisconnect.c][208]
        Entry:
            Connection = 0xf0a6f0
[ODBC][1][1556564832.996778][SQLDisconnect.c][379]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564833.001505][SQLFreeHandle.c][284]
        Entry:
            Handle Type = 2
            Input Handle = 0xf0a6f0
[ODBC][1][1556564833.006038][SQLFreeHandle.c][333]
        Exit:[SQL_SUCCESS]
</code>```

UPDATE 3

I have a hunch that it might have something to do with UTF-16 due to a similar question where characters are separated with a \0.

Maybe something to do with the UNICODE setting in this line from the ODBC logs?

```<code>[ODBC][1][1556564832.214691][SQLDriverConnectW.c][290]
        Entry:
            Connection = 0xf0a6f0
            Window Hdl = (nil)
            Str In = [DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;][length = 115 (SQL_NTS)]
            Str Out = (nil)
            Str Out Max = 0
            Str Out Ptr = 0x7ffd7da98dd0
            Completion = 0
        UNICODE Using encoding ASCII 'ANSI_X3.4-1968' and UNICODE 'UCS-2LE'
</code>```

UPDATE 4

I found this document from Microsoft which said

If the ASCII character encoding is not UTF-8, for example:

UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'   There
  is more than one Driver Manager installed and your application is
  using the wrong one, or the Driver Manager was not built correctly.

I'm assuming my driver isn't built correctly.

And this document said to use --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE.

UPDATE 5

I also found this git issue related to .Net Core, unixODBC, and UTF16.

UPDATE 6

I tried adding --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE when calling unixODBC's configure, which changed the ODBC connection to UNICODE Using encoding ASCII 'UTF8' and UNICODE 'UTF16LE', but I got the same bad data back regardless. I also tried --with-iconv-ucode-enc=UNICODE, but no change.

This is how I changed my Dockerfile. I removed unixodbc from apt-get and added the following to my Dockerfile

```<code>ADD ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.7.tar.gz .
RUN gunzip unixODBC*.tar.gz && tar xvf unixODBC*.tar

WORKDIR /src/unixODBC-2.3.7
RUN ./configure --enable-gui=no --enable-drivers=no --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE
RUN make && make install

ENV LD_LIBRARY_PATH="/usr/local/lib"
</code>```

And this is what the odbc log looks like now:

```<code>[ODBC][7][1556723781.839804][SQLDriverConnectW.c][290]
        Entry:
            Connection = 0x1ddff70
            Window Hdl = (nil)
            Str In = [DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;][length = 115 (SQL_NTS)]
            Str Out = (nil)
            Str Out Max = 0
            Str Out Ptr = 0x7ffeca3331a0
            Completion = 0
        UNICODE Using encoding ASCII 'UTF8' and UNICODE 'UTF16LE'
</code>```

UPDATE 7

I connected via isql and got the correct response, but when I connected via iusql I got the "bad data" from my reproducer.

UPDATE 8

Adding some odbc installation info:

```<code>root@4efdb5ed98b5:/app# odbc_config --cflags
-DHAVE_UNISTD_H -DHAVE_PWD_H -DHAVE_SYS_TYPES_H -DHAVE_LONG_LONG -DSIZEOF_LONG_INT=8 -I/usr/local/include
root@4efdb5ed98b5:/app# odbc_config --ulen
-DSIZEOF_SQLULEN=8
root@4efdb5ed98b5:/app# odbcinst -j
unixODBC 2.3.7
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8
</code>```

答:
This is a bug with Apache Ignite 2.7.0, so there is no answer. An issue has been filed with Apache Ignite to fix it.

http://issues.apache.org/jira/browse/IGNITE-11845

Body:
I am testing out the Apache Ignite 2.7 Linux ODBC Driver, and it's not working correctly for some reason.

When I run a SQL statement, like SELECT Id FROM MyTable, the value is "garbled" returning a value like 8\00\05\07\09\0d\09\08\0-\0 for the the Id column. It's similar to the value I expect, though, which is 80579d98-9010-4610-b12e-ed33ed7d3c62. I don't know if those are ASCII null characters (\0), or what, but something isn't right and I can't figure it out.

When I use the SQLLine tool, the values are not "garbled". I also installed the Windows ODBC driver, and that worked fine, but I need the Linux ODBC Driver.

I built the driver with the following libraries:

gcc 6.3.0 20170516 (Debian 6.3.0-18+deb9u1)
GNU Make 4.1
libtoolize 2.4.6
aclocal 1.15
autoheader 2.69
automake 1.15
autoreconf 2.69
unixodbc 2.3.4-1
libssl 1.0.2r-1~deb9u1

Here's the contents of the ignite-odbc-install.ini:

# cat /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
[Apache Ignite]
Description=Apache Ignite
Driver=/usr/local/lib/libignite-odbc.so
Setup=/usr/local/lib/libignite-odbc.so
DriverODBCVer=03.00
FileUsage=0

Here's the result of running odbcinst:

# odbcinst -i -d -f /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini
odbcinst: Driver installed. Usage count increased to 1.
    Target directory is /etc

Here's the contents of the /usr/local/lib folder:

# cd /usr/local/lib
# ls
libignite-binary-2.7.0.33575.so.0      libignite-common-2.7.0.33575.so.0      libignite-odbc-2.7.0.33575.so.0      libignite-thin-client-2.7.0.33575.so.0
libignite-binary-2.7.0.33575.so.0.0.0  libignite-common-2.7.0.33575.so.0.0.0  libignite-odbc-2.7.0.33575.so.0.0.0  libignite-thin-client-2.7.0.33575.so.0.0.0
libignite-binary.a                     libignite-common.a                     libignite-odbc.a                     libignite-thin-client.a
libignite-binary.la                    libignite-common.la                    libignite-odbc.la                    libignite-thin-client.la
libignite-binary.so                    libignite-common.so                    libignite-odbc.so                    libignite-thin-client.so

Here's the result from the ldd command:

# ldd /usr/local/lib/libignite-odbc.so
        linux-vdso.so.1 (0x00007fffa46d0000)
        libdl.so.2 => /lib/x86_64-linux-gnu/libdl.so.2 (0x00007f18d554c000)
        libignite-binary-2.7.0.33575.so.0 => /usr/local/lib/libignite-binary-2.7.0.33575.so.0 (0x00007f18d531d000)
        libodbcinst.so.2 => /usr/lib/x86_64-linux-gnu/libodbcinst.so.2 (0x00007f18d5108000)
        libstdc++.so.6 => /usr/lib/x86_64-linux-gnu/libstdc++.so.6 (0x00007f18d4d86000)
        libm.so.6 => /lib/x86_64-linux-gnu/libm.so.6 (0x00007f18d4a82000)
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007f18d46e3000)
        libgcc_s.so.1 => /lib/x86_64-linux-gnu/libgcc_s.so.1 (0x00007f18d44cc000)
        /lib64/ld-linux-x86-64.so.2 (0x00007f18d59f8000)
        libignite-common-2.7.0.33575.so.0 => /usr/local/lib/libignite-common-2.7.0.33575.so.0 (0x00007f18d42b5000)
        libltdl.so.7 => /usr/lib/x86_64-linux-gnu/libltdl.so.7 (0x00007f18d40ab000)
        libpthread.so.0 => /lib/x86_64-linux-gnu/libpthread.so.0 (0x00007f18d3e8e000)

UPDATE 1

I ran this from a .Net Core 2.2 C# Console program, with only the System.Data.Odbc 4.5.0 NuGet reference in a Docker Linux Environment.

IgniteGarbledDataReproducer.csproj

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.2</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="System.Data.Odbc" Version="4.5.0" />
  </ItemGroup>

</Project>

Program.cs

using System;
using System.Data.Odbc;

namespace IgniteGarbledDataReproducer {
    internal class Program {
        private static void Main(string[] args) {
            Console.WriteLine("START");

            var connectionString = Environment.GetEnvironmentVariable("IGNITE_CONNECTION_STRING");
            Console.WriteLine(connectionString);

            using (var conn = new OdbcConnection(connectionString)) {
                conn.Open();

                Console.WriteLine("Connection Opened");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "DROP TABLE IF EXISTS MyTable;";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Table Dropped (if it existed)");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "CREATE TABLE MyTable (Id varchar(36) not null, FirstName varchar(255), LastName varchar(255), PRIMARY KEY (Id));";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Table Created");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "INSERT INTO MyTable (Id) VALUES ('80579d98-9010-4610-b12e-ed33ed7d3c62');";
                    cmd.ExecuteNonQuery();
                }

                Console.WriteLine("Data Inserted");

                using (var cmd = conn.CreateCommand()) {
                    cmd.CommandText = "SELECT Id FROM MyTable;";
                    using (var rdr = cmd.ExecuteReader()) {
                        while (rdr.Read())
                            Console.WriteLine($"Id = '{rdr["Id"]}'");
                    }
                }

                Console.WriteLine("Data Returned");
            }

            Console.WriteLine("DONE");
        }
    }
}

Dockerfile

FROM microsoft/dotnet:2.2-runtime AS base
WORKDIR /app

WORKDIR /src
# Install pre-requisites for building and installing Ignite ODBC Driver
RUN apt-get update \
    && apt-get install -y gcc g++ make automake autotools-dev libtool m4 libssl1.0-dev unixodbc-dev unixodbc-bin unzip \
    && apt-get clean -y

# Download and unzip Ignite binary release
#ADD http://apache.mirrors.hoobly.com/ignite/2.7.0/apache-ignite-2.7.0-bin.zip /src/
COPY apache-ignite-2.7.0-bin.zip .
RUN unzip -q /src/apache-ignite-2.7.0-bin.zip \
    && rm /src/apache-ignite-2.7.0-bin.zip

# Build Ignite ODBC Driver
ARG IGNITE_HOME=/src/apache-ignite-2.7.0-bin
WORKDIR /src/apache-ignite-2.7.0-bin/platforms/cpp
RUN libtoolize \
    && aclocal \
    && autoheader \
    && automake --add-missing \
    && autoreconf \
    && ./configure --enable-odbc --disable-core --disable-node \
    && make \
    && make install

# Install Ignite ODBC Driver
RUN apt-get update \
    && apt-get install -y unixodbc \
    && apt-get clean -y \
    && odbcinst -i -d -f /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY IgniteGarbledDataReproducer/IgniteGarbledDataReproducer.csproj IgniteGarbledDataReproducer/
RUN dotnet restore IgniteGarbledDataReproducer/IgniteGarbledDataReproducer.csproj
COPY . .
WORKDIR /src/IgniteGarbledDataReproducer
RUN dotnet build IgniteGarbledDataReproducer.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish IgniteGarbledDataReproducer.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "IgniteGarbledDataReproducer.dll"]

docker-compose.yml

version: '3.4'

services:
  ignitegarbleddatareproducer:
    image: ${DOCKER_REGISTRY-}ignite-garbled-data-reproducer
    build:
      context: .
      dockerfile: IgniteGarbledDataReproducer/Dockerfile

docker-compose-override.yml

version: '3.4'

services:
  ignitegarbleddatareproducer:
    environment:
      - ASPNETCORE_ENVIRONMENT=Development
      - IGNITE_CONNECTION_STRING=DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;

Build

docker build . -t ignitegarbleddatareproducer -f IgniteGarbledDataReproducer/Dockerfile

Execute

PS C:\IgniteGarbledDataReproducer> docker-compose up
Starting ignitegarbleddatareproducer_ignitegarbleddatareproducer_1 ... done
Attaching to ignitegarbleddatareproducer_ignitegarbleddatareproducer_1
ignitegarbleddatareproducer_1  | START
ignitegarbleddatareproducer_1  | DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;
ignitegarbleddatareproducer_1  | Connection Opened
ignitegarbleddatareproducer_1  | DROP TABLE IF EXISTS MyTable;
ignitegarbleddatareproducer_1  | Table Dropped (if it existed)
ignitegarbleddatareproducer_1  | CREATE TABLE MyTable (Id varchar(36) not null, FirstName varchar(255), LastName varchar(255), PRIMARY KEY (Id));
ignitegarbleddatareproducer_1  | Table Created
ignitegarbleddatareproducer_1  | INSERT INTO MyTable (Id) VALUES ('80579d98-9010-4610-b12e-ed33ed7d3c62');
ignitegarbleddatareproducer_1  | Data Inserted
ignitegarbleddatareproducer_1  | SELECT Id FROM MyTable;
ignitegarbleddatareproducer_1  | Id = '8 0 5 7 9 d 9 8 - '
ignitegarbleddatareproducer_1  | Data Returned
ignitegarbleddatareproducer_1  | DONE
ignitegarbleddatareproducer_ignitegarbleddatareproducer_1 exited with code 0

UPDATE 2

I turned on ODBC logging by adding the following to /src/apache-ignite-2.7.0-bin/platforms/cpp/odbc/install/ignite-odbc-install.ini and you can get the logs here.

[ODBC]
Trace=yes
TraceFile=/logs/odbc.log

The end of the log after the SELECT Id From MyTable; statement is below for convenience.

[ODBC][1][1556564832.827181][SQLExecDirectW.c][177]
        Entry:
            Statement = 0xf27a80
            SQL = [SELECT Id FROM MyTable;][length = 23 (SQL_NTS)]
[ODBC][1][1556564832.847882][SQLExecDirectW.c][445]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.852889][SQLRowCount.c][173]
        Entry:
            Statement = 0xf27a80
            Row Count = 0x7ffd7da98f00
[ODBC][1][1556564832.856831][SQLRowCount.c][247]
        Exit:[SQL_SUCCESS]
            Row Count = 0x7ffd7da98f00 -> 0
[ODBC][1][1556564832.860335][SQLNumResultCols.c][156]
        Entry:
            Statement = 0xf27a80
            Column Count = 0x7ffd7da98f50
[ODBC][1][1556564832.864944][SQLNumResultCols.c][251]
        Exit:[SQL_SUCCESS]
            Count = 0x7ffd7da98f50 -> 1
[ODBC][1][1556564832.869909][SQLFetch.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.884876][SQLFetch.c][351]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.894173][SQLColAttributeW.c][156]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Field Identifier = SQL_DESC_NAME
            Character Attr = 0xf2e190
            Buffer Length = 4096
            String Length = 0x7ffd7da98f20
            Numeric Attribute = 0x7ffd7da98ee0
[ODBC][1][1556564832.898409][SQLColAttributeW.c][523]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.910800][SQLColAttributeW.c][156]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Field Identifier = SQL_DESC_CONCISE_TYPE
            Character Attr = 0xf2e190
            Buffer Length = 4096
            String Length = 0x7ffd7da98f40
            Numeric Attribute = 0x7ffd7da98f00
[ODBC][1][1556564832.914551][SQLColAttributeW.c][523]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.925913][SQLGetData.c][237]
        Entry:
            Statement = 0xf27a80
            Column Number = 1
            Target Type = -8 SQL_WCHAR
            Buffer Length = 4094
            Target Value = 0xf2e190
            StrLen Or Ind = 0x7ffd7da98ee0
[ODBC][1][1556564832.929959][SQLGetData.c][534]
        Exit:[SQL_SUCCESS]
            Buffer = [8](unicode)
            Strlen Or Ind = 0x7ffd7da98ee0 -> 36
[ODBC][1][1556564832.934835][SQLFetch.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.938930][SQLFetch.c][351]
        Exit:[SQL_NO_DATA]
[ODBC][1][1556564832.943970][SQLMoreResults.c][162]
        Entry:
            Statement = 0xf27a80
[ODBC][1][1556564832.960311][SQLMoreResults.c][345]
        Exit:[SQL_NO_DATA]
[ODBC][1][1556564832.965960][SQLFreeStmt.c][144]
        Entry:
            Statement = 0xf27a80
            Option = 0
[ODBC][1][1556564832.970025][SQLFreeStmt.c][266]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.975135][SQLFreeHandle.c][381]
        Entry:
            Handle Type = 3
            Input Handle = 0xf27a80
[ODBC][1][1556564832.981240][SQLFreeHandle.c][494]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564832.991337][SQLDisconnect.c][208]
        Entry:
            Connection = 0xf0a6f0
[ODBC][1][1556564832.996778][SQLDisconnect.c][379]
        Exit:[SQL_SUCCESS]
[ODBC][1][1556564833.001505][SQLFreeHandle.c][284]
        Entry:
            Handle Type = 2
            Input Handle = 0xf0a6f0
[ODBC][1][1556564833.006038][SQLFreeHandle.c][333]
        Exit:[SQL_SUCCESS]

UPDATE 3

I have a hunch that it might have something to do with UTF-16 due to a similar question where characters are separated with a \0.

Maybe something to do with the UNICODE setting in this line from the ODBC logs?

[ODBC][1][1556564832.214691][SQLDriverConnectW.c][290]
        Entry:
            Connection = 0xf0a6f0
            Window Hdl = (nil)
            Str In = [DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;][length = 115 (SQL_NTS)]
            Str Out = (nil)
            Str Out Max = 0
            Str Out Ptr = 0x7ffd7da98dd0
            Completion = 0
        UNICODE Using encoding ASCII 'ANSI_X3.4-1968' and UNICODE 'UCS-2LE'

UPDATE 4

I found this document from Microsoft which said

If the ASCII character encoding is not UTF-8, for example:

UNICODE Using encoding ASCII 'ISO8859-1' and UNICODE 'UCS-2LE'   There
  is more than one Driver Manager installed and your application is
  using the wrong one, or the Driver Manager was not built correctly.

I'm assuming my driver isn't built correctly.

And this document said to use --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE.

UPDATE 5

I also found this git issue related to .Net Core, unixODBC, and UTF16.

UPDATE 6

I tried adding --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE when calling unixODBC's configure, which changed the ODBC connection to UNICODE Using encoding ASCII 'UTF8' and UNICODE 'UTF16LE', but I got the same bad data back regardless. I also tried --with-iconv-ucode-enc=UNICODE, but no change.

This is how I changed my Dockerfile. I removed unixodbc from apt-get and added the following to my Dockerfile

ADD ftp://ftp.unixodbc.org/pub/unixODBC/unixODBC-2.3.7.tar.gz .
RUN gunzip unixODBC*.tar.gz && tar xvf unixODBC*.tar

WORKDIR /src/unixODBC-2.3.7
RUN ./configure --enable-gui=no --enable-drivers=no --enable-iconv --with-iconv-char-enc=UTF8 --with-iconv-ucode-enc=UTF16LE
RUN make && make install

ENV LD_LIBRARY_PATH="/usr/local/lib"

And this is what the odbc log looks like now:

[ODBC][7][1556723781.839804][SQLDriverConnectW.c][290]
        Entry:
            Connection = 0x1ddff70
            Window Hdl = (nil)
            Str In = [DRIVER={Apache Ignite};ADDRESS=my-ignite-3e8b8cb9a4e192af.elb.us-east-1.amazonaws.com:10800;SSL_MODE=disable;][length = 115 (SQL_NTS)]
            Str Out = (nil)
            Str Out Max = 0
            Str Out Ptr = 0x7ffeca3331a0
            Completion = 0
        UNICODE Using encoding ASCII 'UTF8' and UNICODE 'UTF16LE'

UPDATE 7

I connected via isql and got the correct response, but when I connected via iusql I got the "bad data" from my reproducer.

UPDATE 8

Adding some odbc installation info:

root@4efdb5ed98b5:/app# odbc_config --cflags
-DHAVE_UNISTD_H -DHAVE_PWD_H -DHAVE_SYS_TYPES_H -DHAVE_LONG_LONG -DSIZEOF_LONG_INT=8 -I/usr/local/include
root@4efdb5ed98b5:/app# odbc_config --ulen
-DSIZEOF_SQLULEN=8
root@4efdb5ed98b5:/app# odbcinst -j
unixODBC 2.3.7
DRIVERS............: /usr/local/etc/odbcinst.ini
SYSTEM DATA SOURCES: /usr/local/etc/odbc.ini
FILE DATA SOURCES..: /usr/local/etc/ODBCDataSources
USER DATA SOURCES..: /root/.odbc.ini
SQLULEN Size.......: 8
SQLLEN Size........: 8
SQLSETPOSIROW Size.: 8


问:
Spark on YARN too less vcores used
I'm using Spark in a YARN cluster (HDP 2.4) with the following settings:

1 Masternode

64 GB RAM (50 GB usable)

24 cores (19 cores usable)

5 Slavenodes

64 GB RAM (50 GB usable) each

24 cores (19 cores usable) each

YARN settings

memory of all containers (of one host): 50 GB

minimum container size = 2 GB

maximum container size = 50 GB

vcores = 19

minimum #vcores/container = 1

maximum #vcores/container = 19

When I run my spark application with the command spark-submit --num-executors 30 --executor-cores 3 --executor-memory 7g --driver-cores 1 --driver-memory 1800m ... YARN creates 31 containers (one for each executor process + one driver process) with the following settings:

Correct: Master container with 1 core & ~1800 MB RAM

Correct: 30 slave containers with ~7 GB RAM each

BUT INCORRECT: each slave container only runs with 1 core instead of 3, according to the YARN ResourceManager UI (it shows only 31 of 95 in use, instead of 91 = 30 * 3 + 1), see screenshot below

My question here: Why does the spark-submit parameter --executor-cores 3 have no effect?

答: The UI could be misleading. When vcore enforcement is disabled in YARN, it will just assume one core per container, whereas in fact, if you look at the actual CPU usage of the physical machine, it could be using all of the cores. Also check the core usage on your SparkUI, that usually gives a better understanding of the actual CPU usage. </p>

Title: Spark on YARN too less vcores used


问:
Why we need to use <uses-feature> attribute?
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

```<code><uses-permission android:name="android.permission.CAMERA"/>
</code>```

But besides that, there is one such

```<code><uses-feature android:name="android.hardware.camera"/>
</code>```

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?

答:
Google documentation for <uses-feature> itself clearly states:

Google Play uses the <uses-feature> elements declared in your app
  manifest to filter your app from devices that do not meet its hardware
  and software feature requirements.

By specifying the features that your application requires, you enable
  Google Play to present your application only to users whose devices
  meet the application's feature requirements, rather than presenting it
  to all users.

Some permissions in Android are connected to some hardware/software features of a device, like CAMERA. Since every Android device in the market differs in its hardware and software configuration, there's a greater possibility that some feature that you're trying to add in your app doesn't support all Android Devices. If you try to use the camera in a camera-less device (a superficial assumption), then your app will not behave as you expect.

In short, if you want your app to only be available for the set of devices having that particular capability, then you can add <uses-feature> tag inside the manifest with the desired capability.
This is just for filtering apps in Play Store based on device configuration and support.
You can define zero or more <uses-feature> capabilities based on your need.

Note: If you don't want your app to get filtered out just for the sake of a feature that doesn't impact the overall user experience of the app, you can smartly disable the particular feature if it's not available in your app.

For that, you have to write

```<code><uses-feature android:name="YOUR_NON_COMPULSORY_FEATURE" android:required="false" />
</code>```

For example, if your app uses CAMERA feature, but your app is not dependent on that feature, you can disable just the CAMERA feature to provide a non-buggy user experience.

Body:
My question is related to camera. When an application needs to use the system camera, we create an intent with ACTION_IMAGE_CAPTURE action and add a permission like this in the manifest file.

<uses-permission android:name="android.permission.CAMERA"/>

But besides that, there is one such

<uses-feature android:name="android.hardware.camera"/>

What is it for? I read that if this line is written, then if the phone does not have a camera the application will not install. Is it true? And besides this, why do we need this?

And for what the line <uses-feature/> is generally responsible in manifest file?

Body:
Google documentation for <uses-feature> itself clearly states:

Google Play uses the <uses-feature> elements declared in your app
  manifest to filter your app from devices that do not meet its hardware
  and software feature requirements.

By specifying the features that your application requires, you enable
  Google Play to present your application only to users whose devices
  meet the application's feature requirements, rather than presenting it
  to all users.

Some permissions in Android are connected to some hardware/software features of a device, like CAMERA. Since every Android device in the market differs in its hardware and software configuration, there's a greater possibility that some feature that you're trying to add in your app doesn't support all Android Devices. If you try to use the camera in a camera-less device (a superficial assumption), then your app will not behave as you expect.

In short, if you want your app to only be available for the set of devices having that particular capability, then you can add <uses-feature> tag inside the manifest with the desired capability.
This is just for filtering apps in Play Store based on device configuration and support.
You can define zero or more <uses-feature> capabilities based on your need.

Note: If you don't want your app to get filtered out just for the sake of a feature that doesn't impact the overall user experience of the app, you can smartly disable the particular feature if it's not available in your app.

For that, you have to write

<uses-feature android:name="YOUR_NON_COMPULSORY_FEATURE" android:required="false" />

For example, if your app uses CAMERA feature, but your app is not dependent on that feature, you can disable just the CAMERA feature to provide a non-buggy user experience.


问:
How can I solve this stream reading problem?
I am trying to read the response from an URL sending JSON body. But my code is not being able to read the complete response. There is a problem in my code but I am not getting that.

```<code>val url: URL = new URL("https://jsonplaceholder.typicode.com/todos/1")
val httpsConnection: HttpsURLConnection = url.openConnection().asInstanceOf[HttpsURLConnection]
httpsConnection.setRequestMethod("GET")
httpsConnection.setRequestProperty("Accept", "application/json")
httpsConnection.setRequestProperty("Accept-Language", "en_US")
val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream)
val bufferedReader = new BufferedReader(streamReader)
val stringBuffer: StringBuffer =new StringBuffer()
while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

println(stringBuffer.toString)
</code>```

This above code is not giving me the actual result.
But if I avoid the regular Java style and use scala source:

```<code>Source.fromInputStream(httpsConnection.getInputStream,"UTF8").getLines().foreach(println)
</code>```

this gives the actual JSON.

What is the problem in my first section of codes?

答:
I know it's not exactly what you're looking for but data manipulation can be quite complex at times, especially when you involve networks. So in the interest of simplicity I would recommend using external libraries to read a JSON file from URL.

The following code retrieves your JSON file from the link you provided employing methods provided by JSON.simple and Apache Commons IO:

```<code>public void getJson() throws IOException {

    java.net.URL url = new java.net.URL("https://jsonplaceholder.typicode.com/todos/1");
    String json = IOUtils.toString(url, Charset.forName("UTF-8"));
    System.out.println(json);
}
</code>```

Body:
I am trying to read the response from an URL sending JSON body. But my code is not being able to read the complete response. There is a problem in my code but I am not getting that.

val url: URL = new URL("https://jsonplaceholder.typicode.com/todos/1")
val httpsConnection: HttpsURLConnection = url.openConnection().asInstanceOf[HttpsURLConnection]
httpsConnection.setRequestMethod("GET")
httpsConnection.setRequestProperty("Accept", "application/json")
httpsConnection.setRequestProperty("Accept-Language", "en_US")
val streamReader: InputStreamReader = new InputStreamReader(httpsConnection.getInputStream)
val bufferedReader = new BufferedReader(streamReader)
val stringBuffer: StringBuffer =new StringBuffer()
while(bufferedReader.readLine() != null){
  stringBuffer.append(bufferedReader.readLine())
}

println(stringBuffer.toString)

This above code is not giving me the actual result.
But if I avoid the regular Java style and use scala source:

Source.fromInputStream(httpsConnection.getInputStream,"UTF8").getLines().foreach(println)

this gives the actual JSON.

What is the problem in my first section of codes?

Body:
I know it's not exactly what you're looking for but data manipulation can be quite complex at times, especially when you involve networks. So in the interest of simplicity I would recommend using external libraries to read a JSON file from URL.

The following code retrieves your JSON file from the link you provided employing methods provided by JSON.simple and Apache Commons IO:

public void getJson() throws IOException {

    java.net.URL url = new java.net.URL("https://jsonplaceholder.typicode.com/todos/1");
    String json = IOUtils.toString(url, Charset.forName("UTF-8"));
    System.out.println(json);
}


问:
Hover in CSS is not working with Electron
I'm starting to make my simple code editor. The window that I create with Electron is without frame (frame: false). Because of that, I created a div with class .drag, which has -webkit-app-region set to drag.

.drag {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #F0D6BA;
    -webkit-user-region: drag;
}

.drag:hover {
    height: 25px;
    background-color: #7EA5A3;
}
```

It works perfectly in the browser, but if I use it in Electron, nothing changes when I hover my mouse over element.

答: I understand why this happens now: Any elements with -webkit-app-region: drag do not receive mouse events. Thanks 41 72 6c!

Body:
I'm starting to make my simple code editor. The window that I create with Electron is without frame (frame: false). Because of that, I created a div with class .drag, which has -webkit-app-region set to drag.

.drag {
    position: absolute;
    top: 0;
    left: 0;
    background-color: #F0D6BA;
    -webkit-user-region: drag;
}

.drag:hover {
    height: 25px;
    background-color: #7EA5A3;
}

It works perfectly in the browser, but if I use it in Electron, nothing changes when I hover my mouse over element.


问:
Multiple axios calls after login that needs to wait each other, before redirecting user to dashboard on Vue.js [Timing issue]
Login.vue

```<code>methods: {
  loginUser() {
    this.$store.dispatch("auth/loginUser", { email: this.email, password: this.password })
    .then(() => {
      // Login ok, redirect user to dashboard
    })
    .catch(() => {
      // Show error
    })
  }
}
</code>```

Auth.js

```<code>actions: {
  async loginUser ({dispatch}, {email, password}) {
      return axios.post(url, {email, password})
        .then(response => {
          dispatch('otherAction');
        })
        .catch(response => {
      })
  },
  async otherAction ({ dispatch, commit }) {
    // Do other stuff
  }
}
</code>```

I use Vuex and actions to perform API calls. I need to wait otherAction dispatch before redirecting user to dashboard.
The problem is I can not use await in the then call. axios.post in the auth.js basically checks credentials of the user. After that I need to do a few more call to get all necessary data to show. Currently, user is redirected to dashboard, but I see errors on the dashboard because it doesn't wait until the 'get extra data of a user' call is completed to get the needed data. The thing is timing issue.

My way of thinking may be completely wrong. How can I make it work?

答: Make another action that dispatches all the other actions and stores the returned promises in an array then use Promise.all()</p>

Body:
Login.vue

methods: {
  loginUser() {
    this.$store.dispatch("auth/loginUser", { email: this.email, password: this.password })
    .then(() => {
      // Login ok, redirect user to dashboard
    })
    .catch(() => {
      // Show error
    })
  }
}

Auth.js

actions: {
  async loginUser ({dispatch}, {email, password}) {
      return axios.post(url, {email, password})
        .then(response => {
          dispatch('otherAction');
        })
        .catch(response => {
      })
  },
  async otherAction ({ dispatch, commit }) {
    // Do other stuff
  }
}

I use Vuex and actions to perform API calls. I need to wait otherAction dispatch before redirecting user to dashboard.
The problem is I can not use await in the then call. axios.post in the auth.js basically checks credentials of the user. After that I need to do a few more call to get all necessary data to show. Currently, user is redirected to dashboard, but I see errors on the dashboard because it doesn't wait until the 'get extra data of a user' call is completed to get the needed data. The thing is timing issue.

My way of thinking may be completely wrong. How can I make it work?


问:
creating dynamic component names in react with typescript 3.2.2
I've upgraded to typescript 3.2.2 and this code which used to compile is now not compiling:

```<code>export const Heading: React.SFC<HeadingProps> = ({ level, className, tabIndex, children, ...rest }) => {
  const Tag = `h${level}`;

  return (
    <Tag className={cs(className)} {...rest} tabIndex={tabIndex}>
      {children}
    </Tag>
  );
};
</code>```

With the error:

Property 'tabIndex' does not exist on type 'IntrinsicAttributes'.

答:
This is a little late and tested on TypeScript 3.4:

Replace

```<code>const Tag = `h${level}`;
</code>```

with

```<code>const Tag = `h${level}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";
</code>```

I'm still not sure about tabIndex, but now TypeScript can infer other properties like children.

Body:
I've upgraded to typescript 3.2.2 and this code which used to compile is now not compiling:

export const Heading: React.SFC<HeadingProps> = ({ level, className, tabIndex, children, ...rest }) => {
  const Tag = `h${level}`;

  return (
    <Tag className={cs(className)} {...rest} tabIndex={tabIndex}>
      {children}
    </Tag>
  );
};

With the error:

Property 'tabIndex' does not exist on type 'IntrinsicAttributes'.

Body:
This is a little late and tested on TypeScript 3.4:

Replace

const Tag = `h${level}`;

with

const Tag = `h${level}` as "h1" | "h2" | "h3" | "h4" | "h5" | "h6";

I'm still not sure about tabIndex, but now TypeScript can infer other properties like children.


问:
Injecting a pipe for usage in an exported function (not in component code) in Angular
I have a utility file with a bunch of methods that I export for usage in my components. Basically, something like this.

```<code>export function shazoo(amount: number) : string { ... }
</code>```

On my components, I'm using a pipe for uniform formatting of the output to the screen. It looks like this.

```<code>@Pipe({ name: "format" })
export class FormatPipe implements PipeTransform {
  transform(value: number): string { ... }
}
</code>```

It seems to be a wise idea to apply that specific pipification even inside the method, which was the case while it resided in the component (because it was injected in the constructor of it).

Then I had the bright idea of moving it to utils.ts for general purpose and now the injection doesn't work because the exported function doesn't reside in a class. It's imply imported into the using components.

What is the proper way to inject the pipe in this case? Is it injectable to begin with?

答:
I recommend you to create a separate UtilityService with @Injectable(), provide it in root. here you can use FormatPipe as dependency

You can copy all your utility methods here and use FormatPipe in that methods.
now wherever you want to use utility methods, you can inject UtilityService in component and use it.

Body:
I have a utility file with a bunch of methods that I export for usage in my components. Basically, something like this.

export function shazoo(amount: number) : string { ... }

On my components, I'm using a pipe for uniform formatting of the output to the screen. It looks like this.

@Pipe({ name: "format" })
export class FormatPipe implements PipeTransform {
  transform(value: number): string { ... }
}

It seems to be a wise idea to apply that specific pipification even inside the method, which was the case while it resided in the component (because it was injected in the constructor of it).

Then I had the bright idea of moving it to utils.ts for general purpose and now the injection doesn't work because the exported function doesn't reside in a class. It's imply imported into the using components.

What is the proper way to inject the pipe in this case? Is it injectable to begin with?


问:
how to set width of spinner in android?
how to set width of the spinner programatically ? </p>

答:
In your layout file

```<code><Spinner
    android:id="@+id/spinner"
    android:layout_width="200dip"
    android:layout_height="fill_parent"
    android:prompt="@string/my_spinner"
/>
</code>```

would give the spinner a width of 200dip.

Title: how to set width of spinner in android?

Body:
In your layout file

<Spinner
    android:id="@+id/spinner"
    android:layout_width="200dip"
    android:layout_height="fill_parent"
    android:prompt="@string/my_spinner"
/>

would give the spinner a width of 200dip.


问:
How to run for loop with float-number in range
I tried running my long code but the idea in these short lines.

My issue needs two conditions. The first one which i is within range. The second one uses all values in the list

```<code>m = [181.452, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')
</code>```

you can see when values in list int:

```<code>m = [181, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')
</code>```

output to second code: Red

答:
You are using range() which returns an iterator of int values, so your code is not working. It means if you have written

```<code>if i in range(0,5)
</code>```

then it will translate to:

```<code>if i in (0, 1, 2, 3, 4)
</code>```

So your float values didn't got captured here. Also it's not a good practice to use iterator for comparison, when you have comparison operators.

Use below code:

```<code>m = [181.452, 147.0213, 480.33, 1000.05]

for i in m:
    if 0 <= i <= 200:     # this is pythonic way to write "if i >= 0 and i <= 200"
        print('Red')
    elif 200 < i <= 500:
        print ('white')
    elif 500 < i <= 1000:
        print ('green')
    elif 1000 < i <= 1500:
        print ('blue')
</code>```

Output:

```<code>Red
Red
white
blue
</code>```

Body:
I tried running my long code but the idea in these short lines.

My issue needs two conditions. The first one which i is within range. The second one uses all values in the list

m = [181.452, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')

you can see when values in list int:

m = [181, 147.0213, 480.33, 1000.05]
for i in m:
    if i in range(0 , 200):
        print ('Red')
    if i in range(201 , 500):
        print ('white')
    if i in range(501 , 1000):
        print ('green')
    if i in range(1000 , 1500):
        print ('blue')

output to second code: Red

Body:
You are using range() which returns an iterator of int values, so your code is not working. It means if you have written

if i in range(0,5)

then it will translate to:

if i in (0, 1, 2, 3, 4)

So your float values didn't got captured here. Also it's not a good practice to use iterator for comparison, when you have comparison operators.

Use below code:

m = [181.452, 147.0213, 480.33, 1000.05]

for i in m:
    if 0 <= i <= 200:     # this is pythonic way to write "if i >= 0 and i <= 200"
        print('Red')
    elif 200 < i <= 500:
        print ('white')
    elif 500 < i <= 1000:
        print ('green')
    elif 1000 < i <= 1500:
        print ('blue')

Output:

Red
Red
white
blue


问:
how can i populate a field with id while saving but id is not existing yet
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID.
Example:
The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021

my relevant code:
My Model:

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)
</code>```

I tried do populate the fields with a for loop in my views.py

```<code> def Index(request):
    ticket = Ticket.objects.all()
    for t in ticket:
      id = len(str(t.id))
      if id == 1:
        t.designation = "#" + str("0000") + str(t.id)
      elif id == 2:
        t.designation = "#" + str("000") + str(t.id)
      elif id == 3:
        t.designation = "#" + str("00") + str(t.id)
      elif id == 4:
        t.designation = "#" + str("0") + str(t.id)
      else:
        t.designation = "#" + str(t.id)
    context = {'ticket':ticket}
    return render(request, 'ticketsystem/index.html', context)
</code>```

and the output was correct, but I would like to have the population while creating the object

i tried the following, by adding it to my Ticket model:

```<code>class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        id = len(str(id))
        if id == 1:
            designation = "#" + str("0000") + str(id)
        elif id == 2:
            designation = "#" + str("000") + str(id)
        elif id == 3:
            designation = "#" + str("00") + str(id)
        elif id == 4:
            designation = "#" + str("0") + str(id)
        else:
            designation = "#" + str(id)
        super().save()
</code>```

but following error comes up:

local variable 'id' referenced before assignment

答:
You need to run the super call before everything else, otherwise, your object won't be in the DB.

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        if not self.pk:
            super().save()

        str_id = str(self.pk)
        if str_id == 1:
            self.designation = "#0000{}".format(str_id)
        elif str_id == 2:
            self.designation = "#000{}".format(str_id)
        elif str_id == 3:
            self.designation = "#00{}".format(str_id)
        elif str_id == 4:
            self.designation = "#0{}".format(str_id)
        else:
            self.designation = "#{}".format(str_id)

        return self.save()
```

Body:
I am building a helpdesk system and I would like to have a automated ticket designation based on the length of the ID.
Example:
The ID of a ticket is 47 so I would like to have a 5 Integer long designation -> #00047 or if ID 2021 designation should be #02021

my relevant code:
My Model:

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

I tried do populate the fields with a for loop in my views.py

 def Index(request):
    ticket = Ticket.objects.all()
    for t in ticket:
      id = len(str(t.id))
      if id == 1:
        t.designation = "#" + str("0000") + str(t.id)
      elif id == 2:
        t.designation = "#" + str("000") + str(t.id)
      elif id == 3:
        t.designation = "#" + str("00") + str(t.id)
      elif id == 4:
        t.designation = "#" + str("0") + str(t.id)
      else:
        t.designation = "#" + str(t.id)
    context = {'ticket':ticket}
    return render(request, 'ticketsystem/index.html', context)

and the output was correct, but I would like to have the population while creating the object

i tried the following, by adding it to my Ticket model:

class Ticket(models.Model):
    user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    designation = models.CharField(max_length=255, blank=True, null=True)

    def save(self):
        id = len(str(id))
        if id == 1:
            designation = "#" + str("0000") + str(id)
        elif id == 2:
            designation = "#" + str("000") + str(id)
        elif id == 3:
            designation = "#" + str("00") + str(id)
        elif id == 4:
            designation = "#" + str("0") + str(id)
        else:
            designation = "#" + str(id)
        super().save()

but following error comes up:

local variable 'id' referenced before assignment