问:
SQL Server: set NULL value to today's value
I have a column EntryDate in a SQL Server database.

How can I set a NULL value to fill it with today's date (server time) if value was not provided in a query?

答:
Another solution:

Rename your table, and create a view with the same name that does the logic you want, i.e.:

```<code>CREATE VIEW TableName
AS
SELECT Column1, Column2, ... ISNULL(EntryDate, GETDATE())
FROM Old_TableName
</code>```

Then you don't alter your actual data, but if you get a null value for that table it reports today's date.

Body:
Another solution:

Rename your table, and create a view with the same name that does the logic you want, i.e.:

CREATE VIEW TableName
AS
SELECT Column1, Column2, ... ISNULL(EntryDate, GETDATE())
FROM Old_TableName

Then you don't alter your actual data, but if you get a null value for that table it reports today's date.


来源: stackexchange

问:
c++ parallel std::sort for floating values
I've a large file consisting of > millions of floating point values. I can easily sort them using std::sort by reading file into vector for now, eg -

```<code>std::vector<float> v;
std::sort(v.begin(), v.end());
</code>```

but is there any version of std::sort or similar algorithm which takes advantage of multiple cores available on my system? Since this is the only task that takes much time setting up, I'm looking for perf improvements from having > 1 core cpu.

I can use any latest releases of compilers on a x64 linux server and can compile the binary with -std=c++1z too.

答:
You're in luck.  The C++ Extensions for Parallelism Technical Specification added parallelized versions of the many of the standard algorithms including std::sort. They are available in C++17.  GCC has support for this and you can see their page about it here.  It looks as though they are utilizing OpenMP for multi-threading.

GCC Prerequisite Compiler Flags

Any use of parallel functionality requires additional compiler and runtime support, in particular support for OpenMP. Adding this support is not difficult: just compile your application with the compiler flag -fopenmp. This will link in libgomp, the GNU Offloading and Multi Processing Runtime Library, whose presence is mandatory.

In addition, hardware that supports atomic operations and a compiler capable of producing atomic operations is mandatory: GCC defaults to no support for atomic operations on some common hardware architectures. Activating atomic operations may require explicit compiler flags on some targets (like sparc and x86), such as -march=i686, -march=native or -mcpu=v9. See the GCC manual for more information.

I know you said you are using Linux but I also want to included that it appears MSVS, starting with version 2013 RTM, also has support for the Parallelism Technical Specification.

ContentLicense: CC BY-SA 3.0

Body:
I've a large file consisting of > millions of floating point values. I can easily sort them using std::sort by reading file into vector for now, eg -

std::vector<float> v;
std::sort(v.begin(), v.end());

but is there any version of std::sort or similar algorithm which takes advantage of multiple cores available on my system? Since this is the only task that takes much time setting up, I'm looking for perf improvements from having > 1 core cpu.

I can use any latest releases of compilers on a x64 linux server and can compile the binary with -std=c++1z too.


问:
SWRevealViewController from the right side on swift
I am using SWRevealViewController library to make a slide out menu in swift, but I am struggling to put this menu in the right side. I have seen on the library description this comment

```<code>// Optional right view controller, can be nil if not used
@property (nonatomic) UIViewController *rightViewController;
</code>```

but I am not familiar with objective C and I am not being able to do this on swift. This is a part of my code for the default(left) menu:

```<code>class ViewController: UIViewController, AVAudioPlayerDelegate {

@IBOutlet weak var playlistOutlet: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    playlistOutlet.target = self.revealViewController()
    playlistOutlet.action = Selector("revealToggle:")

    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

}
}
</code>```

And revealViewController is called from the SWRevealViewController library

答:
Swift 3

Add this code to yourViewController

```<code>if revealViewController() != nil{
        sideMenuBtn.target = revealViewController()
        sideMenuBtn.action = #selector(SWRevealViewController.rightRevealToggle(_:))
        view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }
</code>```

at MainStoryBoard

Set the segue identifier value to sw_right instead of sw_rear

Worked for me

Better Alternative: https://github.com/jonkykong/SideMenu

Body:
I am using SWRevealViewController library to make a slide out menu in swift, but I am struggling to put this menu in the right side. I have seen on the library description this comment

// Optional right view controller, can be nil if not used
@property (nonatomic) UIViewController *rightViewController;

but I am not familiar with objective C and I am not being able to do this on swift. This is a part of my code for the default(left) menu:

class ViewController: UIViewController, AVAudioPlayerDelegate {

@IBOutlet weak var playlistOutlet: UIBarButtonItem!

override func viewDidLoad() {
    super.viewDidLoad()

    playlistOutlet.target = self.revealViewController()
    playlistOutlet.action = Selector("revealToggle:")

    self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())

}
}

And revealViewController is called from the SWRevealViewController library

Body:
Swift 3

Add this code to yourViewController

if revealViewController() != nil{
        sideMenuBtn.target = revealViewController()
        sideMenuBtn.action = #selector(SWRevealViewController.rightRevealToggle(_:))
        view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
    }

at MainStoryBoard

Set the segue identifier value to sw_right instead of sw_rear

Worked for me

Better Alternative: https://github.com/jonkykong/SideMenu

ContentLicense: CC BY-SA 4.0


问:
What is a good design for an interface with optional components?
Suppose I have an interface that supports a few potential operations:

```<code>interface Frobnicator {
    int doFoo(double v);
    int doBar();
}
</code>```

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

```<code>interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}
</code>```

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

答:
I think you have a problem if you are saying that  class FooImpl implements interface Foo, but it doesn't really implement ALL of Foo.  The interface is supposed to be a contract indicating what methods the implementing class (at minimum) implement.

If something is calling the FooFactory to get a Foo object, the object should be able to do what Foos do.

So, where do you go from there?  I'd suggest your composition idea is a good one, using inheritance slightly less so.

Composition would work exactly as you have it with the getFooFrobnicator() and getBarFrobnicator() methods.  If you don't like that your Frobnicator doesn't really frobnicate, call it a FrobnicatorHolder.

Inheritance would have your Frobnicator containing only the methods that all Frobnicators have, and the sub-interfaces would have the additional methods.

```<code>public interface Frobnicator{
   public void frobnicate();
}

public interface FooFrobnicator{
   public void doFoo();
}

public interface BarFrobnicator{
   public void doBar();
}
</code>```

You could then use if (frobnicator instanceof FooFrobnicator) { ((FooFrobnicator) frobnicator).doFoo() } and life goes on.

Favor composition over inheritance.  You'll be happier.

ContentLicense: CC BY-SA 2.5

Body:
Suppose I have an interface that supports a few potential operations:

interface Frobnicator {
    int doFoo(double v);
    int doBar();
}

Now, some instances will only support one or the other of these operations.  They may support both.  The client code won't necessarily know until it actually gets one from the relevant factory, via dependency injection, or wherever it is getting instances from.

I see a few ways of handling this.  One, which seems to be the general tactic taken in the Java API, is to just have the interface as shown above and have unsupported methods raise UnsupportedOperationException.  This has the disadvantage, however, of not being fail-fast - client code can't tell whether doFoo will work until it tries to call doFoo.

This could be augmented with supportsFoo() and supportsBar() methods, defined to return true iff the corresponding do method works.

Another strategy is to factor the doFoo and doBar methods into FooFrobnicator and BarFrobnicator methods, respectively.  These methods would then return null if the operation is unsupported.  To keep the client code from having to do instanceof checks, I define a Frobnicator interface as follows:

interface Frobnicator {
    /* Get a foo frobnicator, returning null if not possible */
    FooFrobnicator getFooFrobnicator();
    /* Get a bar frobnicator, returning null if not possible */
    BarFrobnicator getBarFrobnicator();
}

interface FooFrobnicator {
    int doFoo(double v);
}

interface BarFrobnicator {
    int doBar();
}

Alternatively, FooFrobnicator and BarFrobnicator could extend Frobnicator, and the get* methods possibly be renamed as*.

One issue with this is naming: the Frobnicator really isn't a frobnicator, it's a way of getting frobnicators (unless I use the as* naming).  It also gets a tad unwieldy.  The naming may be further complicated, as the Frobnicator will be retrieved from a FrobnicatorEngine service.

Does anyone have any insight into a good, preferably well-accepted solution to this problem?  Is there an appropriate design pattern?  Visitor is not appropriate in this case, as the client code needs a particular type of interface (and should preferably fail-fast if it can't get it), as opposed to dispatching on what kind of object it got.  Whether or not different features are supported can vary on a variety of things - the implementation of Frobnicator, the run-time configuration of that implementation (e.g. it supports doFoo only if some system service is present to enable Foo), etc.

Update: Run-time configuration is the other monkey wrench in this business.  It may be possible to carry the FooFrobnicator and BarFrobnicator types through to avoid the problem, particularly if I make heaver use of Guice-modules-as-configuration, but it introduces complexity into other surrounding interfaces (such as the factory/builder that produces Frobnicators in the first place).  Basically, the implementation of the factory that produces frobnicators is configured at run-time (either via properties or a Guice module), and I want it to make it fairly easy for the user to say "hook up this frobnicator provider an this client".  I admit that it's a problem with potential inherent design problems, and that I may also be overthinking some of the generalization issues, but I'm going for some combination of least-ugliness and least-astonishment.

Body:
I think you have a problem if you are saying that  class FooImpl implements interface Foo, but it doesn't really implement ALL of Foo.  The interface is supposed to be a contract indicating what methods the implementing class (at minimum) implement.

If something is calling the FooFactory to get a Foo object, the object should be able to do what Foos do.

So, where do you go from there?  I'd suggest your composition idea is a good one, using inheritance slightly less so.

Composition would work exactly as you have it with the getFooFrobnicator() and getBarFrobnicator() methods.  If you don't like that your Frobnicator doesn't really frobnicate, call it a FrobnicatorHolder.

Inheritance would have your Frobnicator containing only the methods that all Frobnicators have, and the sub-interfaces would have the additional methods.

public interface Frobnicator{
   public void frobnicate();
}

public interface FooFrobnicator{
   public void doFoo();
}

public interface BarFrobnicator{
   public void doBar();
}

You could then use if (frobnicator instanceof FooFrobnicator) { ((FooFrobnicator) frobnicator).doFoo() } and life goes on.

Favor composition over inheritance.  You'll be happier.


问:
Bookshelf JS: "this.hasOne" is not a function
Attempting to work through the simplest examples of bookshelf, but can't get past a one-to-many relationship using "withRelated" in a fetch statement. Here is my code (with some things removed for privacy) representing a one-to-many from B to A.

```<code>"use strict";
var knex = require('knex') ({
    client: 'mysql',
    connection: {
        host: '127.0.0.1',
        user: '*******',
        password: '*******',
        database: '*******',
        charset: 'utf8'
    }
});

var bookshelf = require('bookshelf')(knex);

var A, B

A = bookshelf.Model.extend({
    tableName: 'A',
    propB: () => {
         return this.hasOne(B, 'A_id')
    }

B = bookshelf.Model.extend({
    tableName: 'B',
    propA: () => { return this.belongsTo(A, 'A_id') }
})

A.forge().fetch({withRelated: ['propB']}).then(function(x){console.log(x)})
</code>```

However, running this I get "Unhandled rejection TypeError: this.hasOne is not a function", referring to the this.hasOne in A. If I remove the "withRelated" clause, it runs just as expected and returns the correct entry in the database.

Why am I receiving this error? More info:
Nodejs: v4.4.1
Bookshelf: v0.9.4

答:
Shorthand function notation is shorter and binds to the this-context of the class.</p>

```<code>var A = bookshelf.Model.extend({
    tableName: 'A',
    propB() {
        return this.hasOne(B, 'A_id')
    }
})
</code>```

Body:
Attempting to work through the simplest examples of bookshelf, but can't get past a one-to-many relationship using "withRelated" in a fetch statement. Here is my code (with some things removed for privacy) representing a one-to-many from B to A.

"use strict";
var knex = require('knex') ({
    client: 'mysql',
    connection: {
        host: '127.0.0.1',
        user: '*******',
        password: '*******',
        database: '*******',
        charset: 'utf8'
    }
});

var bookshelf = require('bookshelf')(knex);

var A, B

A = bookshelf.Model.extend({
    tableName: 'A',
    propB: () => {
         return this.hasOne(B, 'A_id')
    }

B = bookshelf.Model.extend({
    tableName: 'B',
    propA: () => { return this.belongsTo(A, 'A_id') }
})

A.forge().fetch({withRelated: ['propB']}).then(function(x){console.log(x)})

However, running this I get "Unhandled rejection TypeError: this.hasOne is not a function", referring to the this.hasOne in A. If I remove the "withRelated" clause, it runs just as expected and returns the correct entry in the database.

Why am I receiving this error? More info:
Nodejs: v4.4.1
Bookshelf: v0.9.4

Body:
Shorthand function notation is shorter and binds to the this-context of the class.

var A = bookshelf.Model.extend({
    tableName: 'A',
    propB() {
        return this.hasOne(B, 'A_id')
    }
})


问:
How to write self modifying code in C?
I want to write a piece of code that changes itself continuously, even if the change is insignificant.

For example maybe something like

```
for i in 1 to  100, do
begin
   x := 200
   for j in 200 downto 1, do
    begin
       do something
    end
end
```

Suppose I want that my code should after first iteration change the line x := 200 to some other line x := 199 and then after next iteration change it to x := 198 and so on.

Is writing such a code possible ? Would I need to use inline assembly for that ?

EDIT :
Here is why I want to do it in C:

This program will be run on an experimental operating system and I can't / don't know how to use programs compiled from other languages. The real reason I need such a code is because this code is being run on a guest operating system on a virtual machine. The hypervisor is a binary translator that is translating chunks of code. The translator does some optimizations. It only translates the chunks of code once. The next time the same chunk is used in the guest, the translator will use the previously translated result. Now, if the code gets modified on the fly, then the translator notices that, and marks its previous translation as stale. Thus forcing a re-translation of the same code. This is what I want to achieve, to force the translator to do many translations. Typically these chunks are instructions between to branch instructions (such as jump instructions). I just think that self modifying code would be fantastic way to achieve this.

答:
Sorry, I am answering a bit late, but I think I found exactly what you are looking for : https://shanetully.com/2013/12/writing-a-self-mutating-x86_64-c-program/

In this article, they change the value of a constant by injecting assembly in the stack. Then they execute a shellcode by modifying the memory of a function on the stack.

Below is the first code :

```<code>#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>

void foo(void);
int change_page_permissions_of_address(void *addr);

int main(void) {
    void *foo_addr = (void*)foo;

    // Change the permissions of the page that contains foo() to read, write, and execute
    // This assumes that foo() is fully contained by a single page
    if(change_page_permissions_of_address(foo_addr) == -1) {
        fprintf(stderr, "Error while changing page permissions of foo(): %s\n", strerror(errno));
        return 1;
    }

    // Call the unmodified foo()
    puts("Calling foo...");
    foo();

    // Change the immediate value in the addl instruction in foo() to 42
    unsigned char *instruction = (unsigned char*)foo_addr + 18;
    *instruction = 0x2A;

    // Call the modified foo()
    puts("Calling foo...");
    foo();

    return 0;
}

void foo(void) {
    int i=0;
    i++;
    printf("i: %d\n", i);
}

int change_page_permissions_of_address(void *addr) {
    // Move the pointer to the page boundary
    int page_size = getpagesize();
    addr -= (unsigned long)addr % page_size;

    if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
        return -1;
    }

    return 0;
}
</code>```

Title: How to write self modifying code in C?

Body:
I want to write a piece of code that changes itself continuously, even if the change is insignificant.

For example maybe something like

for i in 1 to  100, do
begin
   x := 200
   for j in 200 downto 1, do
    begin
       do something
    end
end

Suppose I want that my code should after first iteration change the line x := 200 to some other line x := 199 and then after next iteration change it to x := 198 and so on.

Is writing such a code possible ? Would I need to use inline assembly for that ?

EDIT :
Here is why I want to do it in C:

This program will be run on an experimental operating system and I can't / don't know how to use programs compiled from other languages. The real reason I need such a code is because this code is being run on a guest operating system on a virtual machine. The hypervisor is a binary translator that is translating chunks of code. The translator does some optimizations. It only translates the chunks of code once. The next time the same chunk is used in the guest, the translator will use the previously translated result. Now, if the code gets modified on the fly, then the translator notices that, and marks its previous translation as stale. Thus forcing a re-translation of the same code. This is what I want to achieve, to force the translator to do many translations. Typically these chunks are instructions between to branch instructions (such as jump instructions). I just think that self modifying code would be fantastic way to achieve this.

Body:
Sorry, I am answering a bit late, but I think I found exactly what you are looking for : https://shanetully.com/2013/12/writing-a-self-mutating-x86_64-c-program/

In this article, they change the value of a constant by injecting assembly in the stack. Then they execute a shellcode by modifying the memory of a function on the stack.

Below is the first code :

#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/mman.h>

void foo(void);
int change_page_permissions_of_address(void *addr);

int main(void) {
    void *foo_addr = (void*)foo;

    // Change the permissions of the page that contains foo() to read, write, and execute
    // This assumes that foo() is fully contained by a single page
    if(change_page_permissions_of_address(foo_addr) == -1) {
        fprintf(stderr, "Error while changing page permissions of foo(): %s\n", strerror(errno));
        return 1;
    }

    // Call the unmodified foo()
    puts("Calling foo...");
    foo();

    // Change the immediate value in the addl instruction in foo() to 42
    unsigned char *instruction = (unsigned char*)foo_addr + 18;
    *instruction = 0x2A;

    // Call the modified foo()
    puts("Calling foo...");
    foo();

    return 0;
}

void foo(void) {
    int i=0;
    i++;
    printf("i: %d\n", i);
}

int change_page_permissions_of_address(void *addr) {
    // Move the pointer to the page boundary
    int page_size = getpagesize();
    addr -= (unsigned long)addr % page_size;

    if(mprotect(addr, page_size, PROT_READ | PROT_WRITE | PROT_EXEC) == -1) {
        return -1;
    }

    return 0;
}


问:
Recursively convert files in nested folders
I wanted to just comment on an answer to a question very similar to this but I don't have enough rep. I'm looking for a way to change this line of code:

```<code>for i in *.mkv; do ffmpeg -i "$i" "${i%.*}.mp4"; done
</code>```

So that it includes .avi files and so that it can search through nested folders. I want to be able to target /Videos and have the script automatically traverse through the folder tree into /Videos/2016/January, convert all of the video files contained within that folder, then do the same for /Videos/2016/February and so on.

Thanks in advance.

(credit for above line of code goes to LordNeckBeard, from this post.)

答:
Using LordNeckBeard's reference to find, I came up with the following solution:

```<code>find ./ -iname '*.avi' -o -iname '*.mkv' -exec bash -c 'ffmpeg -i "{}" -c:v libx265 -preset medium -crf 28 -c:a aac "{}".mp4' \;
</code>```

Tested and worked exactly how I expected, so it is currently running through the entire library.

If you want to give your converted files a different name to the original, see Parameter Expansion.

If you wish to destructively convert all files, be extremely careful with this command:

```<code>find ./ -iname '*.avi' -o -iname '*.mkv' -exec bash -c 'ffmpeg -i "{}" -c:v libx265 -preset medium -crf 28 -c:a aac "{}".mp4 && rm "{}"' \;
</code>```

NOTE: The command above isn't bulletproof and was removing some files BEFORE the conversion process had finished, meaning I have now lost those files (thank God for backups). I tested with disposable files and have made sure I have a fully functional back up of my data before starting this procedure.

Body:
I wanted to just comment on an answer to a question very similar to this but I don't have enough rep. I'm looking for a way to change this line of code:

for i in *.mkv; do ffmpeg -i "$i" "${i%.*}.mp4"; done

So that it includes .avi files and so that it can search through nested folders. I want to be able to target /Videos and have the script automatically traverse through the folder tree into /Videos/2016/January, convert all of the video files contained within that folder, then do the same for /Videos/2016/February and so on.

Thanks in advance.

(credit for above line of code goes to LordNeckBeard, from this post.)

Body:
Using LordNeckBeard's reference to find, I came up with the following solution:

find ./ -iname '*.avi' -o -iname '*.mkv' -exec bash -c 'ffmpeg -i "{}" -c:v libx265 -preset medium -crf 28 -c:a aac "{}".mp4' \;

Tested and worked exactly how I expected, so it is currently running through the entire library.

If you want to give your converted files a different name to the original, see Parameter Expansion.

If you wish to destructively convert all files, be extremely careful with this command:

find ./ -iname '*.avi' -o -iname '*.mkv' -exec bash -c 'ffmpeg -i "{}" -c:v libx265 -preset medium -crf 28 -c:a aac "{}".mp4 && rm "{}"' \;

NOTE: The command above isn't bulletproof and was removing some files BEFORE the conversion process had finished, meaning I have now lost those files (thank God for backups). I tested with disposable files and have made sure I have a fully functional back up of my data before starting this procedure.


问:
How to query this MySQL table in the most performant way?
Suppose I have a MySQL table that was created like this:

```<code>CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
</code>```

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

答:
You will have to do a full table scan, so this is probably the best solution:

```<code>select (case when id in (< your list >) then 'in' else 'out' end) as inlist,
       my_boolean_field, count(*)
from mytable t
group by (case when id in (< your list >) then 'in' else out' end),
         my_boolean_field;
</code>```

If your list is in a table with an index, then you can use a left join on it.  However, MySQL optimizes searches for in with constant values (it uses a binary search).  So this is likely to be the fastest method.

Body:
Suppose I have a MySQL table that was created like this:

CREATE TABLE `my_table` (
  `my_id` char(32) NOT NULL,
  `my_boolean_field` tinyint(1) DEFAULT NULL,
  PRIMARY KEY (`my_id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

This table is very large. It has approximately 10 million rows in it. my_boolean_field's only possible values are 1, 0 and null.

Now separately, I have a list of 500 IDs. Let's call this my_list. They are in a text file separated by newlines. The name of that file is myfile.txt.

I want to answer the following questions:

How many of the rows in my_table have and ID that is in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is in my_list and my_boolean_field==0.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field is null.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==1.

How many of the rows in my_table have and ID that is not in my_list and my_boolean_field==0.

What is the most performant way to get the above 6 counts??

Body:
You will have to do a full table scan, so this is probably the best solution:

select (case when id in (< your list >) then 'in' else 'out' end) as inlist,
       my_boolean_field, count(*)
from mytable t
group by (case when id in (< your list >) then 'in' else out' end),
         my_boolean_field;

If your list is in a table with an index, then you can use a left join on it.  However, MySQL optimizes searches for in with constant values (it uses a binary search).  So this is likely to be the fastest method.


问:
Laravel 5 Failed opening required bootstrap/../vendor/autoload.php
I have recently installed Laravel 5 via Composer. I tried creating a new controller using Artisan and got the following error. Am I missing something?

bootstrap/../vendor/autoload.php. Failed to open stream: No such file or directory. The "vendor" folder does not exist.

答:
Before you carry out the following instructions you need to make sure you have composer installed globally on your machine;
Open you Mac terminal and run the following command:

```<code>curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
</code>```

once composer is installed globally run the following command after you are in the directory of the project:

```<code>composer install
</code>```

once completed in it update and install all the required packages.

Body:
Before you carry out the following instructions you need to make sure you have composer installed globally on your machine;
Open you Mac terminal and run the following command:

curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer

once composer is installed globally run the following command after you are in the directory of the project:

composer install

once completed in it update and install all the required packages.


问:
Modifying assembly instructions before loading
I have a DLL that I need to load (I have written it and compiled it), and I would like to insert instructions between existing instructions of the assembly code before loading the DLL into memory. Of course, you can't just read every byte and insert them between there because instructions sometimes are multiple bytes.

I was thinking of using something like Udis86 and reading instructions one by one and then writing them to memory, and between them writing my other instructions. Is this a good approach or is there something better?

答: Im not sure where you are trying to insert the code. But if it is in the middle of the function body and not necessarily the function prologue or epilogue, then why dont you use an __asm block with a bunch of nop's to pad the area that you would write the code into. Then just fill in the code where the nop's are at runtime.</p>


问:
Android turn based multiplayer onTurnBasedMatchReceived doesn't trigger when game starts from Play Games
When i create a turn based game from my application and all players accept invitations in game then i'm able to control how each player takes turn by means of callback methods - onTurnBasedMatchReceived, onInvitationReceived etc. But when i start it from notification or from Play Games app i'm able just to take turn and another turn notification comes to Play Games but not in my callback methods. I'm wondering may be someone faced this situation too and is it possible to fix somehow?</p>

答: My bad, not registered it properly when game starts with existing bundle.</p>


问:
How do I view the Python Codes inside a Python Script?
I have a Python Script (with .py extension) and it was created by makepy.py.
Is there a way to view and copy the codes inside that script and load them into my Jupyter Notebook?

I have done a Google search but strangely, I can't find this mentioned anywhere.

Do I need a specific software to do this? Or can it be done at the Python command prompt level?

答:
All that can be done directly from the Jupyter Notebook or any IPython console.

to view the contents of the script

!cat myscript.py

to run the script as a program use this built-in magic command

%run myscript.py


问:
Which is the best way to redirect 2 different users to 2 different Activities after they login using their email and password?
I'm creating an application with 2 different users.

The first one is the student and the second one is the professor/teacher.

Which is the best way to redirect them to a different Activity after they login using their email and password?

All the students who will login will redirect in a different Activity from the teacher or professor.

答:
you can create a shared preference object  SharedPreferences preferences;

then define two boolean variables:

```<code>private static String STUDENT_LOG_IN_STATUS = "student_log_in_status";
private static String TEACHER_LOG_IN_STATUS = "teacher_log_in_status";
</code>```

then create setter and getter for each variable like that:

```<code>public void setLogInStatus(boolean status) {
        preferences.edit().putBoolean(STUDENT_LOG_IN_STATUS, status).apply();
    }

public boolean getLogInStatus() {
        return preferences.getBoolean(STUDENT_LOG_IN_STATUS, false);
    }
</code>```

and the same for TEACHER_LOG_IN_STATUS .

if the student or teacher logged in successfully set his login status to true if he logged out set the login status to false.

and check for these status every time you the app starts if any one of them is true redirect the user to the right screen based on his type if both of them are false open log in screen

Body:
you can create a shared preference object  SharedPreferences preferences;

then define two boolean variables:

private static String STUDENT_LOG_IN_STATUS = "student_log_in_status";
private static String TEACHER_LOG_IN_STATUS = "teacher_log_in_status";

then create setter and getter for each variable like that:

public void setLogInStatus(boolean status) {
        preferences.edit().putBoolean(STUDENT_LOG_IN_STATUS, status).apply();
    }

public boolean getLogInStatus() {
        return preferences.getBoolean(STUDENT_LOG_IN_STATUS, false);
    }

and the same for TEACHER_LOG_IN_STATUS .

if the student or teacher logged in successfully set his login status to true if he logged out set the login status to false.

and check for these status every time you the app starts if any one of them is true redirect the user to the right screen based on his type if both of them are false open log in screen


问:
Get Bitmap from ImageView loaded with Picasso
I had a method that loads images, if the image has not been loaded before it will look for it on a server. Then it stores it in the apps file system. If it is in the file system it loads that image instead as that is much faster than pulling the images from the server. If you have loaded the image before without closing the app it will be stored in a static dictionary so that it can be reloaded without using up more memory, to avoid out of memory errors.

This all worked fine until I started using the Picasso image loading library. Now I'm loading images into an ImageView but I don't know how to get the Bitmap that is returned so that I can store it in a file or the static dictionary. This has made things more difficult. because it means it tries to load the image from the server every time, which is something I don't want to happen. Is there a way I can get the Bitmap after loading it into the ImageView? Below is my code:

```<code>public Drawable loadImageFromWebOperations(String url,
        final String imagePath, ImageView theView, Picasso picasso) {
    try {
        if (Global.couponBitmaps.get(imagePath) != null) {
            scaledHeight = Global.couponBitmaps.get(imagePath).getHeight();
            return new BitmapDrawable(getResources(),
                    Global.couponBitmaps.get(imagePath));
        }
        File f = new File(getBaseContext().getFilesDir().getPath()
                .toString()
                + "/" + imagePath + ".png");

        if (f.exists()) {
            picasso.load(f).into(theView);
</code>```

This line below was my attempt at retrieving the bitmap it threw a null pointer exception, I assume this is because it takes a while for Picasso to add the image to the ImageView

```<code>            Bitmap bitmap = ((BitmapDrawable)theView.getDrawable()).getBitmap();
            Global.couponBitmaps.put(imagePath, bitmap);
            return null;
        } else {
            picasso.load(url).into(theView);
            return null;
        }
    } catch (OutOfMemoryError e) {
        Log.d("Error", "Out of Memory Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    } catch (NullPointerException e) {
        Log.d("Error", "Null Pointer Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    }
}
</code>```

Any help would be greatly appreciated, thank you!

答:
In this example I used to set the background of a colapsing toolbar.

```<code>public class MainActivity extends AppCompatActivity {

 CollapsingToolbarLayout colapsingToolbar;

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

  colapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.colapsingToolbar);
  ImageView imageView = new ImageView(this);
  String url ="www.yourimageurl.com"

  Picasso.with(this)
         .load(url)
         .resize(80, 80)
         .centerCrop()
         .into(image);

  colapsingToolbar.setBackground(imageView.getDrawable());

}
</code>```

I hope it helped you.

Body:
I had a method that loads images, if the image has not been loaded before it will look for it on a server. Then it stores it in the apps file system. If it is in the file system it loads that image instead as that is much faster than pulling the images from the server. If you have loaded the image before without closing the app it will be stored in a static dictionary so that it can be reloaded without using up more memory, to avoid out of memory errors.

This all worked fine until I started using the Picasso image loading library. Now I'm loading images into an ImageView but I don't know how to get the Bitmap that is returned so that I can store it in a file or the static dictionary. This has made things more difficult. because it means it tries to load the image from the server every time, which is something I don't want to happen. Is there a way I can get the Bitmap after loading it into the ImageView? Below is my code:

public Drawable loadImageFromWebOperations(String url,
        final String imagePath, ImageView theView, Picasso picasso) {
    try {
        if (Global.couponBitmaps.get(imagePath) != null) {
            scaledHeight = Global.couponBitmaps.get(imagePath).getHeight();
            return new BitmapDrawable(getResources(),
                    Global.couponBitmaps.get(imagePath));
        }
        File f = new File(getBaseContext().getFilesDir().getPath()
                .toString()
                + "/" + imagePath + ".png");

        if (f.exists()) {
            picasso.load(f).into(theView);

This line below was my attempt at retrieving the bitmap it threw a null pointer exception, I assume this is because it takes a while for Picasso to add the image to the ImageView

            Bitmap bitmap = ((BitmapDrawable)theView.getDrawable()).getBitmap();
            Global.couponBitmaps.put(imagePath, bitmap);
            return null;
        } else {
            picasso.load(url).into(theView);
            return null;
        }
    } catch (OutOfMemoryError e) {
        Log.d("Error", "Out of Memory Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    } catch (NullPointerException e) {
        Log.d("Error", "Null Pointer Exception");
        e.printStackTrace();
        return getResources().getDrawable(R.drawable.default1);
    }
}

Any help would be greatly appreciated, thank you!

Body:
In this example I used to set the background of a colapsing toolbar.

public class MainActivity extends AppCompatActivity {

 CollapsingToolbarLayout colapsingToolbar;

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

  colapsingToolbar = (CollapsingToolbarLayout) findViewById(R.id.colapsingToolbar);
  ImageView imageView = new ImageView(this);
  String url ="www.yourimageurl.com"

  Picasso.with(this)
         .load(url)
         .resize(80, 80)
         .centerCrop()
         .into(image);

  colapsingToolbar.setBackground(imageView.getDrawable());

}

I hope it helped you.


问:
UIBezierPath Creating Triangle,Square,Circle Swift
I am attempting to create three shapes: a Circle, Square & Triangle. I have created the circle & square, but am unable to create the triangle. My biggest issue is to keep all three shapes in the center of the screen. The circle and square are fine, but when I attempt to make the triangle it does not work. I am also trying to make the triangle look like a "play button" so that the "tip" of the triangle is facing to the right. Here is the code.

```<code>func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
    let path = UIBezierPath()

    let startX = center.x - side / 2
    let startY = center.y - side / 2

   path.move(to: CGPoint(x: startX, y: startY))
    path.addLine(to: CGPoint(x: startX, y: startY - side))
    path.addLine(to: CGPoint(x: startX + side, y: startY + side/2))
    path.close()

    return path
}

func circlePathWithCenter(center: CGPoint, radius: CGFloat) -> UIBezierPath {
    let circlePath = UIBezierPath()
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI/2), clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI/2), endAngle: 0, clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI/2), clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: CGFloat(M_PI/2), endAngle: CGFloat(M_PI), clockwise: true)
    circlePath.close()
    return circlePath
}

func squarePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
    let squarePath = UIBezierPath()
    let startX = center.x - side / 2
    let startY = center.y - side / 2

    squarePath.move(to: CGPoint(x: startX, y: startY))

    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY + side))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX, y: startY + side))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.close()
    return squarePath

}
</code>```

Where am I going wrong with the geometry for the triangle?

答:
You subtracted when you need to add.  Remember, +Y is down.

Change:

```<code>path.addLine(to: CGPoint(x: startX, y: startY - side))
</code>```

To:

```<code>path.addLine(to: CGPoint(x: startX, y: startY + side))
</code>```

Here it is running in a Playground:

Here's the full code for the Playground demo:

```<code>class Custom: UIView {
    override func draw(_ rect: CGRect) {
        let path = trainglePathWithCenter(center: self.center, side: self.bounds.width / 2)

        path.stroke()
    }

    func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
        let path = UIBezierPath()

        let startX = center.x - side / 2
        let startY = center.y - side / 2

        path.move(to: CGPoint(x: startX, y: startY))
        path.addLine(to: CGPoint(x: startX, y: startY + side))
        path.addLine(to: CGPoint(x: startX + side, y: startY + side/2))
        path.close()

        return path
    }
}

let custom = Custom(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
custom.backgroundColor = .white
</code>```

Body:
I am attempting to create three shapes: a Circle, Square & Triangle. I have created the circle & square, but am unable to create the triangle. My biggest issue is to keep all three shapes in the center of the screen. The circle and square are fine, but when I attempt to make the triangle it does not work. I am also trying to make the triangle look like a "play button" so that the "tip" of the triangle is facing to the right. Here is the code.

func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
    let path = UIBezierPath()

    let startX = center.x - side / 2
    let startY = center.y - side / 2

   path.move(to: CGPoint(x: startX, y: startY))
    path.addLine(to: CGPoint(x: startX, y: startY - side))
    path.addLine(to: CGPoint(x: startX + side, y: startY + side/2))
    path.close()

    return path
}

func circlePathWithCenter(center: CGPoint, radius: CGFloat) -> UIBezierPath {
    let circlePath = UIBezierPath()
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI), endAngle: -CGFloat(M_PI/2), clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: -CGFloat(M_PI/2), endAngle: 0, clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: 0, endAngle: CGFloat(M_PI/2), clockwise: true)
    circlePath.addArc(withCenter: center, radius: radius, startAngle: CGFloat(M_PI/2), endAngle: CGFloat(M_PI), clockwise: true)
    circlePath.close()
    return circlePath
}

func squarePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
    let squarePath = UIBezierPath()
    let startX = center.x - side / 2
    let startY = center.y - side / 2

    squarePath.move(to: CGPoint(x: startX, y: startY))

    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX + side, y: startY + side))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.addLine(to: CGPoint(x: startX, y: startY + side))
    squarePath.addLine(to: squarePath.currentPoint)
    squarePath.close()
    return squarePath

}

Where am I going wrong with the geometry for the triangle?

Body:
You subtracted when you need to add.  Remember, +Y is down.

Change:

path.addLine(to: CGPoint(x: startX, y: startY - side))

To:

path.addLine(to: CGPoint(x: startX, y: startY + side))

Here it is running in a Playground:

Here's the full code for the Playground demo:

class Custom: UIView {
    override func draw(_ rect: CGRect) {
        let path = trainglePathWithCenter(center: self.center, side: self.bounds.width / 2)

        path.stroke()
    }

    func trainglePathWithCenter(center: CGPoint, side: CGFloat) -> UIBezierPath {
        let path = UIBezierPath()

        let startX = center.x - side / 2
        let startY = center.y - side / 2

        path.move(to: CGPoint(x: startX, y: startY))
        path.addLine(to: CGPoint(x: startX, y: startY + side))
        path.addLine(to: CGPoint(x: startX + side, y: startY + side/2))
        path.close()

        return path
    }
}

let custom = Custom(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
custom.backgroundColor = .white


问:
SSDT Equivalent for Oracle Database
In SSDT there is a mechanism for managing DDL changes, for instance a new column or a change to a data type. Instead of putting an 'Alter Table' statement into the database project, instead we edit that original 'Create Table' statement which focuses on the final state that includes the new column. It detects the difference between older and new script and creates necessary 'Alter Table' script to use for deployment.

Is there any equivalent strategy to achieve the same in Oracle Database as I am using J2EE technologies and Eclipse IDE.

答:
It's not built into the IDE like SSDT is, but Redgate has comparison tools for Oracle that use the same methodology as SSDT Database Projects.

This can be used in conjunction with Redgate Source Control for Oracle, which maintains a schema model in your chosen VCS.

Title: SSDT Equivalent for Oracle Database


问:
PHP float numbers not adding correctly - decimal value missing
I am trying to get the total of my variables containing numbers, some may be decimals.  I need this to be to two decimal places and am using the number_format() function.

```<code>$total =  $order->order->net+$order->order->deductions+$order->order->vat+$order->order->postage+$order->order->postage_tax;
            echo number_format((float)$total, 2, '.', '');?>
</code>```

I have noticed the following values do not add up correctly and seems to be ignoring the decimal. The total should be 118.50 but instead I get 118.00.

100+0+17.5+1+0

I have researched this and found the below

http://floating-point-gui.de/basic/

I am a little confused by it.  Can anyone explain what I need to do?

*EDIT
Below is dump of the $order variable showing the numbers I am trying to add up.   You can see the 17.5 is 17.5 and not 17.  Is it because they are specified as being strings perhaps?

object(SimpleXMLElement)#12 (21) { ["id"]=> string(6) "922704" ["shopkeeper_orderno"]=> string(4) "1001" ["customer"]=> string(6) "797893" ["creationdate"]=> string(16) "29-05-2012 11:55" ["net"]=> string(3) "100" ["vat"]=> string(4) "17.5" ["status"]=> string(1) "1" ["isnew"]=> string(1) "0" ["deductions"]=> string(1) "0" ["postage"]=> string(1) "1" ["paymentmethod"]=> string(20) "PayPal " ["instructions"]=> object(SimpleXMLElement)#17 (0) { } [2]=> object(SimpleXMLElement)#22 (1) { ["items"]=> object(SimpleXMLElement)#30 (9) { ["id"]=> string(7) "1384486" ["headerID"]=> string(6) "922704" ["productID"]=> string(7) "4959678" ["description"]=> string(13) "Wedding dress" ["net"]=> string(3) "100" ["vat"]=> string(4) "17.5" ["qty"]=> string(1) "1" ["formID"]=> string(2) "-1" ["options"]=> object(SimpleXMLElement)#31 (1) { ["options"]=> array(2) { [0]=> object(SimpleXMLElement)#32 (6) { ["id"]=> string(6) "519981" ["orderDetailsID"]=> string(7) "1384486" ["optionid"]=> string(6) "646934" ["optionCost"]=> string(1) "0" ["optionVAT"]=> string(1) "0" ["customText"]=> string(9) "size : 12" } [1]=> object(SimpleXMLElement)#33 (6) { ["id"]=> string(6) "519982" ["orderDetailsID"]=> string(7) "1384486" ["optionid"]=> string(6) "647285" ["optionCost"]=> string(1) "0" ["optionVAT"]=> string(1) "0" ["customText"]=> string(14) "Colour : Ivory" } } } } } } ["postage_tax"]=> string(1) "0" ["dispatched"]=> string(1) "0" ["paybyotherid"]=> string(2) "-1" ["wheredidyouhearid"]=> string(2) "-1" }

答:
If you are looking for exact value without any correction or round you should use the bcadd following function to get the actual two decimal point             </p>

```<code>$total =  $order->order->net+$order->order->deductions+$order->order->vat+$order->order->postage+$order->order->postage_tax;
$total=bcadd(0,$total,2);
echo $total;
</code>```

Body:
I am trying to get the total of my variables containing numbers, some may be decimals.  I need this to be to two decimal places and am using the number_format() function.

$total =  $order->order->net+$order->order->deductions+$order->order->vat+$order->order->postage+$order->order->postage_tax;
            echo number_format((float)$total, 2, '.', '');?>

I have noticed the following values do not add up correctly and seems to be ignoring the decimal. The total should be 118.50 but instead I get 118.00.

100+0+17.5+1+0

I have researched this and found the below

http://floating-point-gui.de/basic/

I am a little confused by it.  Can anyone explain what I need to do?

*EDIT
Below is dump of the $order variable showing the numbers I am trying to add up.   You can see the 17.5 is 17.5 and not 17.  Is it because they are specified as being strings perhaps?

object(SimpleXMLElement)#12 (21) { ["id"]=> string(6) "922704" ["shopkeeper_orderno"]=> string(4) "1001" ["customer"]=> string(6) "797893" ["creationdate"]=> string(16) "29-05-2012 11:55" ["net"]=> string(3) "100" ["vat"]=> string(4) "17.5" ["status"]=> string(1) "1" ["isnew"]=> string(1) "0" ["deductions"]=> string(1) "0" ["postage"]=> string(1) "1" ["paymentmethod"]=> string(20) "PayPal " ["instructions"]=> object(SimpleXMLElement)#17 (0) { } [2]=> object(SimpleXMLElement)#22 (1) { ["items"]=> object(SimpleXMLElement)#30 (9) { ["id"]=> string(7) "1384486" ["headerID"]=> string(6) "922704" ["productID"]=> string(7) "4959678" ["description"]=> string(13) "Wedding dress" ["net"]=> string(3) "100" ["vat"]=> string(4) "17.5" ["qty"]=> string(1) "1" ["formID"]=> string(2) "-1" ["options"]=> object(SimpleXMLElement)#31 (1) { ["options"]=> array(2) { [0]=> object(SimpleXMLElement)#32 (6) { ["id"]=> string(6) "519981" ["orderDetailsID"]=> string(7) "1384486" ["optionid"]=> string(6) "646934" ["optionCost"]=> string(1) "0" ["optionVAT"]=> string(1) "0" ["customText"]=> string(9) "size : 12" } [1]=> object(SimpleXMLElement)#33 (6) { ["id"]=> string(6) "519982" ["orderDetailsID"]=> string(7) "1384486" ["optionid"]=> string(6) "647285" ["optionCost"]=> string(1) "0" ["optionVAT"]=> string(1) "0" ["customText"]=> string(14) "Colour : Ivory" } } } } } } ["postage_tax"]=> string(1) "0" ["dispatched"]=> string(1) "0" ["paybyotherid"]=> string(2) "-1" ["wheredidyouhearid"]=> string(2) "-1" }

Body:
If you are looking for exact value without any correction or round you should use the bcadd following function to get the actual two decimal point

$total =  $order->order->net+$order->order->deductions+$order->order->vat+$order->order->postage+$order->order->postage_tax;
$total=bcadd(0,$total,2);
echo $total;


问:
Pure virtual function
I know in C++,
virtual double f()=0; is a pure virtual function,
what about
virtual void f()
{return 0.0};?
Is this a pure virtual function?

答:
No. A function is pure virtual if and only if it is declared with = 0.

Note that it is possible to provide a definition for a pure function, but you have to do that in two steps:

```<code>struct X
{
    virtual double f() = 0;  // pure, X is abstract
};

double X::f() { return 0; }  // definition
</code>```

Usage:

```<code>X x;  // error, X is abstract

struct Y : X
{
    double f() override
    {
        return X::f();  // OK, calls pure virtual function
    }
};

Y y;  // OK, Y overrides X::f
</code>```

Title: Pure virtual function

Body:
No. A function is pure virtual if and only if it is declared with = 0.

Note that it is possible to provide a definition for a pure function, but you have to do that in two steps:

struct X
{
    virtual double f() = 0;  // pure, X is abstract
};

double X::f() { return 0; }  // definition

Usage:

X x;  // error, X is abstract

struct Y : X
{
    double f() override
    {
        return X::f();  // OK, calls pure virtual function
    }
};

Y y;  // OK, Y overrides X::f


问:
My nupkg is incompatible with my Unified API app
I've made a NuGet package that has a lib/Xamarin.iOS10 folder with a dll inside it.
I've created a test project (an iOS unified API Single View App) and I try to add my package but I get this response:

Could not install package 'mypackage 1.0'. You are trying to install
  this package into a project that targets 'Xamarin.iOS,Version=v1.0',
  but the package does not contain any assembly references or content
  files that are compatible with that framework. For more information,
  contact the package author.

Extracting the file, I can verify that my dll is present.

This is the nuspec file:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata minClientVersion="2.8">
    <id>MyPackage</id>
    <version>1.0</version>
    <title>My Package</title>
    <authors>Kristian</authors>
    <owners>Kristian</owners>
    <developmentDependency>true</developmentDependency>
    <licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Experiment Package</description>

    <language>en-US</language>
    <tags></tags>
    <dependencies>
      <dependency id="Fody" version="1.29.3"/>
    </dependencies>
  </metadata>
  <files>
    <file src="../MyPackage.XamarinIOS/bin/iPhone/Release/MyPackage.dll" target="lib/Xamarin.iOS10/MyPackage.dll" />
  </files>
</package>
```

Is there anything else I need to do? I am not using the new project.json format for my package.. I am using Xamarin Studio version 5.9.8.

答:
Shouldn't that be:

```<code>target="lib/xamarinios10/MyPackage.dll"
</code>```

Instead of your Xamarin.iOS10 path?

Body:
I've made a NuGet package that has a lib/Xamarin.iOS10 folder with a dll inside it.
I've created a test project (an iOS unified API Single View App) and I try to add my package but I get this response:

Could not install package 'mypackage 1.0'. You are trying to install
  this package into a project that targets 'Xamarin.iOS,Version=v1.0',
  but the package does not contain any assembly references or content
  files that are compatible with that framework. For more information,
  contact the package author.

Extracting the file, I can verify that my dll is present.

This is the nuspec file:

<?xml version="1.0"?>
<package xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">
  <metadata minClientVersion="2.8">
    <id>MyPackage</id>
    <version>1.0</version>
    <title>My Package</title>
    <authors>Kristian</authors>
    <owners>Kristian</owners>
    <developmentDependency>true</developmentDependency>
    <licenseUrl>http://www.opensource.org/licenses/mit-license.php</licenseUrl>
    <requireLicenseAcceptance>false</requireLicenseAcceptance>
    <description>Experiment Package</description>

    <language>en-US</language>
    <tags></tags>
    <dependencies>
      <dependency id="Fody" version="1.29.3"/>
    </dependencies>
  </metadata>
  <files>
    <file src="../MyPackage.XamarinIOS/bin/iPhone/Release/MyPackage.dll" target="lib/Xamarin.iOS10/MyPackage.dll" />
  </files>
</package>

Is there anything else I need to do? I am not using the new project.json format for my package.. I am using Xamarin Studio version 5.9.8.

Body:
Shouldn't that be:

target="lib/xamarinios10/MyPackage.dll"

Instead of your Xamarin.iOS10 path?


问:
Performing synchronus Requests using $.ajax
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

```<code>function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }
</code>```

答:
Your synchronized request will cause the UI thread (and therefore the browser) to wait until the XMLHttpRequest object returns (kind regardless whether it failed or succeded).

jQuery will execute your success / complete and error handler the same way it would execute when you're using a "normal" asynchronous request. But it will wait / block before it does so.

So the worst case scenario here would be, that the actual request takes a huge amount of time. Network latencys are pretty bad in this context, large data amounts.. all those will entirely lock up your UI thread which is obviously an aweful user expierence.

I really don't know where someone should use a synchronized ajax request nowadays.

Body:
we know that only synchrnous requests are done with $.ajax with an option of async:false
But i have seen in the Jquery manual saying that "synchronous requests may temporarily block the browser
disabling any actions while the request is active". I have some questions such as

I have seen some answers saying to use callback () How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?.
How can i implement this to my function .

In the below Function if the Request Fails  or if the response doesnot return How can i handle it .I mean Can i use "error:" or some thing like that .
How can I improve this Function efficently  i mean using call back  and error handling .It is said that (we can never have error and success call back with a request)

function empvalidate() {
          var exists = false;             // default return value is false
          var empno = $("#empno").val();
          if (empno != '') {
            $.ajax({
              url: "emp.php",
              async: false,
              dataType: "json",
              data: {'param1': $("#param1").val(), 'empno': $("#empno").val()},
              success: function (data) {
                exists = data.status;     // set status of existence to outer variable
              }
            });
          }
          return exists;                  // return actual value
        }


问:
Android Studio: Github commit warning - Access can be package-private
Warning displayed in android studio on GitHub commit request

I have created earthquake class to hold the relevant data and implemented its getter, setter methods.
I encountered a warning Warning:(7, 1) Access can be package-private while I was trying to commit the changes to GitHub.

My question for this is:
What is the best practice while defining such classes? Should I declare them public or just leave the access modifier undefined to make it package-private? Or any other suggestions to avoid this warning?

答:
Typically in development, you want to follow the principle of least privilege. This means that you only allow the least privilege needed. So unless it needs to be public, keep it private/protected. This is a good practice to get into, especially if you start writing SDK's and programs professionally, as public methods can be accessed by anyone, you could inadvertently allow access to methods you didn't intend to.

What you are seeing is just the IDE warning you that you aren't using the variable anywhere else, and could make it private, thus following the principle outlined above. If you want to, you can suppress those warnings, but it's definitely good to limit the access if possible. Consider it a best practice.


问:
Why is setState returning undefined?
I am trying to close a modal when a user presses outside of the Modal element. Somehow when Dismiss() is called, the state is still the same in the callback.

Why is this happening?

```<code>export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>
                    <h1>{this.state.id}</h1>
                </Modal>
            );
        } else {
            return null
        }
    }
}
</code>```

答:
Not sure why there's a state argument in your callback, should just be </p>

```<code>Dismiss() {
    this.setState({
        id: '',
        show: false
    }, function () {
        console.log(this.state)
    });
}
</code>```

Title: Why is setState returning undefined?

Body:
I am trying to close a modal when a user presses outside of the Modal element. Somehow when Dismiss() is called, the state is still the same in the callback.

Why is this happening?

export default class Message extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            id: "",
            show: false
        };
    }

    componentDidMount() {
        this.props.onRef(this);
    }

    Show(id) {
        this.setState({
            id: id,
            show: true
        });
    }

    Dismiss() {
        this.setState({
            id: '',
            show: false
        }, function (state) {
            console.log(state) // undefined
        });
    }

    render() {
        if (this.state.show) {
            return (
                <Modal close={() => this.Dismiss()}>

{this.state.id}

                </Modal>
            );
        } else {
            return null
        }
    }
}

Body:
Not sure why there's a state argument in your callback, should just be

Dismiss() {
    this.setState({
        id: '',
        show: false
    }, function () {
        console.log(this.state)
    });
}


问:
cannot resolve com.google.android.gsm;play-services:25.1.0
i was working on a project, everything was fine but when i tried to run the app, i couldn't,i guess because i'm using a bundled version of google play services. so i i made sure that i update android studio and install the lastest google repository.
but it still wouldn't work. And when i click on install Repostiroy and sync project, still nothing happens.

please help me : this is my gradle ;

```<code>apply plugin: 'com.android.application'

 android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.nefissa.pfe2"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner       "android.support.test.runner.AndroidJUnitRunner"
 }
  buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',     {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.google.android.gms:play-services:25.1.0'

testCompile 'junit:junit:4.12'
}
</code>```

please where did i go wrong?

a screenshot;please what can i do? the click on install wouldn't work

答:
There might one of these problems can cause this issue, try any one of them.

Solution 1:

Try to updated the gradle plugin.

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
}
</code>```

Then just Build->Clean project and everything works again.

Solution 2:

Go to the main module in your project, it's usually have the name app.

Then go to > Open Module Settings > in Properties change the Build Tools Version to 25.0.1

Then to make sure open the build.gradle file, and change compileSDKVersion & buildToolsVersion to 25 and 25.0.1 respectively.

If the above solution doesnt work.

Solution 3:

From this answer

"build cache" is enabled by default in build Android Plugin since 2.3.0. It creates files in build cache outside of project folder (e.g. in \Users\%username%.android\build-cache). Theese files are intended to be common between your projects.

And then Android Studio is unable to navigate in theese files.

You can disable Build Cache in gradle.properties file. just add android.enableBuildCache=false

Body:
i was working on a project, everything was fine but when i tried to run the app, i couldn't,i guess because i'm using a bundled version of google play services. so i i made sure that i update android studio and install the lastest google repository.
but it still wouldn't work. And when i click on install Repostiroy and sync project, still nothing happens.

please help me : this is my gradle ;

apply plugin: 'com.android.application'

 android {
compileSdkVersion 25
buildToolsVersion "25.0.2"
defaultConfig {
    applicationId "com.example.nefissa.pfe2"
    minSdkVersion 16
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner       "android.support.test.runner.AndroidJUnitRunner"
 }
  buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
}
}

dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2',     {
    exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile 'com.android.support:design:25.1.0'
compile 'com.android.support:cardview-v7:25.1.0'
compile 'com.google.android.gms:play-services:25.1.0'

testCompile 'junit:junit:4.12'
}

please where did i go wrong?

a screenshot;please what can i do? the click on install wouldn't work

Body:
There might one of these problems can cause this issue, try any one of them.

Solution 1:

Try to updated the gradle plugin.

dependencies {
    classpath 'com.android.tools.build:gradle:1.5.0'
}

Then just Build->Clean project and everything works again.

Solution 2:

Go to the main module in your project, it's usually have the name app.

Then go to > Open Module Settings > in Properties change the Build Tools Version to 25.0.1

Then to make sure open the build.gradle file, and change compileSDKVersion & buildToolsVersion to 25 and 25.0.1 respectively.

If the above solution doesnt work.

Solution 3:

From this answer

"build cache" is enabled by default in build Android Plugin since 2.3.0. It creates files in build cache outside of project folder (e.g. in \Users\%username%.android\build-cache). Theese files are intended to be common between your projects.

And then Android Studio is unable to navigate in theese files.

You can disable Build Cache in gradle.properties file. just add android.enableBuildCache=false


答: Pure virtual function is function marked with =0. It implicitly makes the class abstract. Abstract classes cannot be instantiated. Derived classes must to override inherited pure virtual functions or it will be abstract too.

Title: Pure virtual function

Body:
I know in C++,
virtual double f()=0; is a pure virtual function,
what about
virtual void f()
{return 0.0};?
Is this a pure virtual function?


问:
issue getting dynamic Config parameter in Grails taglib
I have a dynamic config parameter I want to get like:

```<code>    String srcProperty = "${attrs ['src']}.audio" + ((attrs['locale'])? "_${attrs['locale']}" : '')

    assert srcProperty == "prompt.welcomeMessageOverrideGreeting.audio"
</code>```

where my config has:

```<code>prompt{
    welcomeMessageOverrideGreeting {
        audio = "/en/someFileName.wav"
        txt = "Text alternative for /en/someFileName.wav"
        audio_es = "/es/promptFileName.wav"
        txt_es = "Texto alternativo para /es/someFileName.wav"
    }
}
</code>```

While this works fine:

```<code>String audio = "${config.prompt.welcomeMessageOverrideGreeting.audio}"
</code>```

and:
        assert "${config.prompt.welcomeMessageOverrideGreeting.audio}" == "/en/someFileName.wav"

I can not get this to work:

```<code>String audio = config.getProperty("prompt.welcomeMessageOverrideGreeting.audio")
</code>```

答:
Assuming myconfig.groovy in classpath:

```<code>    prompt{
     welcomeMessageOverrideGreeting {
      audio = "/en/someFileName.wav"
      txt = "Text alternative for /en/someFileName.wav"
      audio_es = "/es/promptFileName.wav"
      txt_es = "Texto alternativo para /es/someFileName.wav"
     }
    }
</code>```

We can get properties constructing their names dynamically:

```<code>def myconfig = this.class.getResource("/myconfig.groovy")
def config = new ConfigSlurper().parse(myconfig)

def dynamic = "welcomeMessageOverrideGreeting"
def dynamic2 = "audio"
def locale = "es"

assert config.prompt[dynamic].audio == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting[dynamic2] == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
assert config.prompt[dynamic]["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
</code>```

Body:
I have a dynamic config parameter I want to get like:

    String srcProperty = "${attrs ['src']}.audio" + ((attrs['locale'])? "_${attrs['locale']}" : '')

    assert srcProperty == "prompt.welcomeMessageOverrideGreeting.audio"

where my config has:

prompt{
    welcomeMessageOverrideGreeting {
        audio = "/en/someFileName.wav"
        txt = "Text alternative for /en/someFileName.wav"
        audio_es = "/es/promptFileName.wav"
        txt_es = "Texto alternativo para /es/someFileName.wav"
    }
}

While this works fine:

String audio = "${config.prompt.welcomeMessageOverrideGreeting.audio}"

and:
        assert "${config.prompt.welcomeMessageOverrideGreeting.audio}" == "/en/someFileName.wav"

I can not get this to work:

String audio = config.getProperty("prompt.welcomeMessageOverrideGreeting.audio")

Body:
Assuming myconfig.groovy in classpath:

    prompt{
     welcomeMessageOverrideGreeting {
      audio = "/en/someFileName.wav"
      txt = "Text alternative for /en/someFileName.wav"
      audio_es = "/es/promptFileName.wav"
      txt_es = "Texto alternativo para /es/someFileName.wav"
     }
    }

We can get properties constructing their names dynamically:

def myconfig = this.class.getResource("/myconfig.groovy")
def config = new ConfigSlurper().parse(myconfig)

def dynamic = "welcomeMessageOverrideGreeting"
def dynamic2 = "audio"
def locale = "es"

assert config.prompt[dynamic].audio == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting[dynamic2] == "/en/someFileName.wav"
assert config.prompt.welcomeMessageOverrideGreeting["${dynamic2}_${locale}"] == "/es/promptFileName.wav"
assert config.prompt[dynamic]["${dynamic2}_${locale}"] == "/es/promptFileName.wav"


问:
How do I chain ajax calls properly?
using jQuery 3.2.1 I'm chaining calls to $.ajax like this:

```<code>function get(i) {
    return $.ajax(...)
      .done(function() { console.log('get done: ' + i) })
      .fail(function() { console.log('get failed: ' + i) })
}

var p = Promise.resolve();
for (var i = 0; i < len; i++) {
    p = p.then(get(i));
}

p.done(function() { console.log('Finished') });
</code>```

and I would expect that the ajax call for i=1 would not execute until the call for i=0 had resolved.  similarly, the final done() should wait for all the calls to be performed in order

in reality I'm seeing 'Finished' before I see anything else and the 'get done' are coming back in random order (the first one finished comes back first is my guess).

I'm used to Bluebird where this would work.  what am I doing wrong?

* Addendum I *

to add to the above, I'm loading javascript files that have dependencies and thus need to be loaded in order.  therefore, the first must complete before the second fetch is initiated, otherwise dependencies will fail

答:
There are two issues:

The get function is executed immediately, while the then method should get a reference to that function for later execution by the Promise implementation. So replace:

```<code>p = p.then(get(i));
</code>```

with:

```<code>p = p.then(get.bind(null,i));
</code>```

JavaScript's native promises do not expose the done method, so replace:

```<code>p.done(function() { console.log('Finished') });
</code>```

with:

```<code>p.then(function() { console.log('Finished') });
</code>```

You should probably also add a catch call to the final promise.

Corrected version:

function get(i) {
    return $.ajax('https://jsonplaceholder.typicode.com/posts/'+(i+1))
      .done(function() { console.log('get done: ' + i) })
      .fail(function(err) { console.log('get failed: ' + i) })
}

var len = 4;
var p = Promise.resolve();
for (var i = 0; i < len; i++) {
    p = p.then(get.bind(null,i));
}

p.then(function() { console.log('Finished') })
 .catch(function () { console.log('Error occurred') });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script></code>```

Title: How do I chain ajax calls properly?

Body:
using jQuery 3.2.1 I'm chaining calls to $.ajax like this:

function get(i) {
    return $.ajax(...)
      .done(function() { console.log('get done: ' + i) })
      .fail(function() { console.log('get failed: ' + i) })
}

var p = Promise.resolve();
for (var i = 0; i < len; i++) {
    p = p.then(get(i));
}

p.done(function() { console.log('Finished') });

and I would expect that the ajax call for i=1 would not execute until the call for i=0 had resolved.  similarly, the final done() should wait for all the calls to be performed in order

in reality I'm seeing 'Finished' before I see anything else and the 'get done' are coming back in random order (the first one finished comes back first is my guess).

I'm used to Bluebird where this would work.  what am I doing wrong?

* Addendum I *

to add to the above, I'm loading javascript files that have dependencies and thus need to be loaded in order.  therefore, the first must complete before the second fetch is initiated, otherwise dependencies will fail

Body:
There are two issues:

The get function is executed immediately, while the then method should get a reference to that function for later execution by the Promise implementation. So replace:

p = p.then(get(i));

with:

p = p.then(get.bind(null,i));

JavaScript's native promises do not expose the done method, so replace:

p.done(function() { console.log('Finished') });

with:

p.then(function() { console.log('Finished') });

You should probably also add a catch call to the final promise.

Corrected version:

function get(i) {
    return $.ajax('https://jsonplaceholder.typicode.com/posts/'+(i+1))
      .done(function() { console.log('get done: ' + i) })
      .fail(function(err) { console.log('get failed: ' + i) })
}

var len = 4;
var p = Promise.resolve();
for (var i = 0; i < len; i++) {
    p = p.then(get.bind(null,i));
}

p.then(function() { console.log('Finished') })
 .catch(function () { console.log('Error occurred') });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


问:
ImportError after clean install of Tensorflow
I have just followed this tutorial on installing Tensorflow from source on Ubuntu 16.04, for Python 3.5 with full CUDA and GPU support on an Nvidia graphics cards. The installation was successful.

I am unable to import Tensorflow in a Python session.

Here is the terminal output:

```<code>user@user:~/Downloads/tensorflow$ python3.5
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
Traceback (most recent call last):
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
ImportError: No module named 'tensorflow.python.pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/Downloads/tensorflow/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/user/Downloads/tensorflow/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
ImportError: No module named 'tensorflow.python.pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.
</code>```

答:
I found the cause of the issue here, which is very trivial and so easy to overlook. It is also mentioned in the tutorial now.

One must simply move into another directory, i.e. out of the folder where all downloaded files especially the where the Git repository is stored.

I found this solution mentioned as a comment in a bug on Github.

Body:
I have just followed this tutorial on installing Tensorflow from source on Ubuntu 16.04, for Python 3.5 with full CUDA and GPU support on an Nvidia graphics cards. The installation was successful.

I am unable to import Tensorflow in a Python session.

Here is the terminal output:

user@user:~/Downloads/tensorflow$ python3.5
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
Traceback (most recent call last):
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
ImportError: No module named 'tensorflow.python.pywrap_tensorflow_internal'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/user/Downloads/tensorflow/tensorflow/__init__.py", line 24, in <module>
    from tensorflow.python import *
  File "/home/user/Downloads/tensorflow/tensorflow/python/__init__.py", line 51, in <module>
    from tensorflow.python import pywrap_tensorflow
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 52, in <module>
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "/home/user/Downloads/tensorflow/tensorflow/python/pywrap_tensorflow.py", line 41, in <module>
    from tensorflow.python.pywrap_tensorflow_internal import *
ImportError: No module named 'tensorflow.python.pywrap_tensorflow_internal'

Failed to load the native TensorFlow runtime.

See https://www.tensorflow.org/install/install_sources#common_installation_problems

for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


问:
Is there any way to obtain type's alignment in GDB's Python API (or directly in GDB)?
For a pretty-printer that I'm writing, I would like to know the alignment or the type which is used in a container. Unfortunately using alignof() or any similar "standard" operator doesn't work (https://sourceware.org/bugzilla/show_bug.cgi?id=17095). Using "typical" macro tricks that work directly in source code also doesn't work:

```<code>p ((char *)(&((struct { char c; double _h; } *)0)->_h) - (char *)0)
A syntax error in expression, near `{ char c; double _h; } *)0)->_h) - (char *)0)'.
</code>```

Is that possible at all, or maybe the only way is to have that supported by GDB internally?

答:
There's no way to get this information, because currently gdb does not have it.

Before DWARF version 5, there was no standard way to express alignment in the debug info.  DWARF 5 added DW_AT_alignment, but gdb still simply ignores this attribute; to expose it via the Python API would require reading it and storing it in gdb's internal struct type.  I don't know offhand whether compilers emit this attribute yet.

If you were very desperate you could do this either using the gdb compile feature or by running the compiler yourself, and having it emit the alignment in a way that can be extracted.

However, normally alignment is not too difficult to compute from the relevant type sizes, and if your target architectures are relatively limited then it's probably simpler to just roll your own alignment computer.

Body:
For a pretty-printer that I'm writing, I would like to know the alignment or the type which is used in a container. Unfortunately using alignof() or any similar "standard" operator doesn't work (https://sourceware.org/bugzilla/show_bug.cgi?id=17095). Using "typical" macro tricks that work directly in source code also doesn't work:

p ((char *)(&((struct { char c; double _h; } *)0)->_h) - (char *)0)
A syntax error in expression, near `{ char c; double _h; } *)0)->_h) - (char *)0)'.

Is that possible at all, or maybe the only way is to have that supported by GDB internally?


问:
IIS rewrite URL from .htaccess: match all files and folders starting with . and deny access
I am new to IIS and trying to translate into it the following Apache rule:

```<code># prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
# - except let's encrypt challenge
RedirectMatch 403 ^/?\.(?!/well-known/acme-challenge/[\w-]{43}$)

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]
</code>```

The idea of the rule is prevent IIS from serving:

Any file than starts with “.”, or

Any folder that starts with “.” but the folder “./well-known/acme-challenge”

Thanks in advance ;)

答:
It seems [E=BASE:%1] cannot be translated to IIS

the 1st part

```<code># prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
# - except let's encrypt challenge
RedirectMatch 403 ^/?\.(?!/well-known/acme-challenge/[\w-]{43}$)
</code>```

this will translated onto web.config as

```<code><rule name="Deny files and folderd starting with . but allow folder .well-known" patternSyntax="ECMAScript" stopProcessing="true">
   <match url="(^\.|\/\.(?!well-known))" ignoreCase="true" negate="false" />
   <conditions logicalGrouping="MatchAll">
   </conditions>
   <action type="AbortRequest" />
</rule>
</code>```

Hope it helps others ^^

Body:
I am new to IIS and trying to translate into it the following Apache rule:

# prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
# - except let's encrypt challenge
RedirectMatch 403 ^/?\.(?!/well-known/acme-challenge/[\w-]{43}$)

RewriteCond %{REQUEST_URI}::$1 ^(/.+)/(.*)::\2$
RewriteRule ^(.*) - [E=BASE:%1]

The idea of the rule is prevent IIS from serving:

Any file than starts with “.”, or

Any folder that starts with “.” but the folder “./well-known/acme-challenge”

Thanks in advance ;)

Body:
It seems [E=BASE:%1] cannot be translated to IIS

the 1st part

# prevent httpd from serving dotfiles (.htaccess, .svn, .git, etc.)
# - except let's encrypt challenge
RedirectMatch 403 ^/?\.(?!/well-known/acme-challenge/[\w-]{43}$)

this will translated onto web.config as

<rule name="Deny files and folderd starting with . but allow folder .well-known" patternSyntax="ECMAScript" stopProcessing="true">
   <match url="(^\.|\/\.(?!well-known))" ignoreCase="true" negate="false" />
   <conditions logicalGrouping="MatchAll">
   </conditions>
   <action type="AbortRequest" />
</rule>

Hope it helps others ^^


问:
Check if a function template is unary
I am trying to check if a function argument passed is unary or not, something like so

```<code>template <typename Func>
using EnableIfUnary = std::enable_if_t<std::is_same<
    decltype(std::declval<Func>()(std::declval<const int&>())),
    decltype(std::declval<Func>()(std::declval<const int&>()))>::value>;

template <typename Func, EnableIfUnary<Func>* = nullptr>
void do_something(Func func) { ... }

// and use like so
template <typename Type>
void foo(Type) { cout << "foo(Type)" << endl; }
template <typename Type>
void bar(Type) { typename Type::something{}; }

int main() {
    do_something(foo);
    return 0;
}
</code>```

Is there a better way to check if a function is unary?  My current approach doesn't work when the function pass in (foo() in my example) uses the type in a way that would not work with ints.

In the above case foo is legal and bar isn't, since there is no type named something in int (which is what the enable if checks for)

答:
```<code>template<typename...>
struct is_unary_function : std::false_type {};

template<typename T, typename R>
struct is_unary_function<R(*)(T)> : std::true_type {};
</code>```

Live Demo

Title: Check if a function template is unary

Body:
I am trying to check if a function argument passed is unary or not, something like so

template <typename Func>
using EnableIfUnary = std::enable_if_t<std::is_same<
    decltype(std::declval<Func>()(std::declval<const int&>())),
    decltype(std::declval<Func>()(std::declval<const int&>()))>::value>;

template <typename Func, EnableIfUnary<Func>* = nullptr>
void do_something(Func func) { ... }

// and use like so
template <typename Type>
void foo(Type) { cout << "foo(Type)" << endl; }
template <typename Type>
void bar(Type) { typename Type::something{}; }

int main() {
    do_something(foo);
    return 0;
}

Is there a better way to check if a function is unary?  My current approach doesn't work when the function pass in (foo() in my example) uses the type in a way that would not work with ints.

In the above case foo is legal and bar isn't, since there is no type named something in int (which is what the enable if checks for)

Body:
template<typename...>
struct is_unary_function : std::false_type {};

template<typename T, typename R>
struct is_unary_function<R(*)(T)> : std::true_type {};

Live Demo


问:
Calculating frequency present in Fast Fourier Transform
I have signal output values recorded by a Software-defined radio whose center frequency was 162.550 MHz & sample rate of 1,000,000. Now to analyse the data in frequency domain I calculated FFT which was straight forward.

```<code>#Calculating FFT of signal
fourier=np.fft.fft(RadioData)
</code>```

Since for Amplitude vs Frequency plot I need to calculate frequencies present in the signal too. I used Numpy fftfreq for that.

```<code>freq=np.fft.fftfreq(fourier.shape[0])
</code>```

The output was in the range of [-0.5 0.4999995]. I am confused how to interpret this result or alternatively how to calculate frequencies present in the data ?

答:
When SDR samples are baseband IQ (or complex, or cosine/sine), then the bandwidth is equal to the IQ sample rate.  This is because baseband IQ samples (unlike single_channel strictly real samples) can contain both positive and negative frequency spectrum, independently, half the bandwidth above and half the bandwidth below an RTL-SDR's (et.al.) tuned RF frequency setting (unless a frequency offset is selected).

Thus, the frequency range of the FFT of IQ data will be from Fcenter - (indicated_bandwidth/2) to almost Fcenter + (indicated_bandwidth/2).  Or for your example: 162.050 to (a bit below) 163.050 MHz. (the "bit below" value depends on the FFT size.)  The step size, dF, with be the IQ sample rate divided by the FFT length.

(Note that the data rate in scalar samples is twice the IQ sample rate because each IQ sample contains two samples (real and imaginary components, or cosine and sine mixer outputs).  Thus, because each IQ sample contains more information, the information bandwidth can be greater.  But SDR apps usually indicate the IQ sample rate, not the higher raw data rate.)

Body:
I have signal output values recorded by a Software-defined radio whose center frequency was 162.550 MHz & sample rate of 1,000,000. Now to analyse the data in frequency domain I calculated FFT which was straight forward.

#Calculating FFT of signal
fourier=np.fft.fft(RadioData)

Since for Amplitude vs Frequency plot I need to calculate frequencies present in the signal too. I used Numpy fftfreq for that.

freq=np.fft.fftfreq(fourier.shape[0])

The output was in the range of [-0.5 0.4999995]. I am confused how to interpret this result or alternatively how to calculate frequencies present in the data ?


问:
Invert orientation of memory space?
I'm trying to read some bytes from a file.

This is what I've done:

```<code>struct HeaderData {
    char format[2];
    char n_trks[2];
    char division[2];
};

HeaderData* header = new HeaderData;
</code>```

Then, to get the data directly from the file to header I do

```<code>file.read(reinterpret_cast<char*>(header), sizeof(HeaderData))
</code>```

If the first two bytes are00 06, header->format[0] will be 00 and header->format[1] 06. This two numbers combined represent the number 0x0006 which is 6 in decimal, which is the desired value.

When I do something like

```<code>*reinterpret_cast<unsigned*>(header->format) // In this case, the result is 0x0600
</code>```

it erroneously returns the number 0x0600, so it seems that it inverts the reading of bytes.

My question is what is some workaround to correctly read the numbers as unsigned.

答:
This is going to be an endianness mismatch.

When you read in from the file in that fashion, the bytes will be placed into your structure in the exact order they were in the file in.

When you read from the structure with an unsigned, the processor will interpret those bytes in whatever order the architecture requires it to do (most are hardcoded but some can be set to either order).

Or to put it another way

This two numbers combined represent the number 0x0006 which is 6 in decimal.

That's not necessarily remotely true. It's perfectly permissible for the processor of your choice to represent 6 in decimal as 0x06 0x00, this would be the little-endian scheme which is used on very common processors like x86. Representing it as 0x00 0x06 would be big-endian.

As M.M has stated in his comment, if your format explicitly defines the integer to be little-endian, you should explicitly read it as little-endian, e.g. format[0] + format[1] * 256, or if it is defined to be big-endian, you should read it as format[0] * 256 + format[1]. Don't rely on the processor's endianness happening to match the endianness of the data.

Title: Invert orientation of memory space?

Body:
I'm trying to read some bytes from a file.

This is what I've done:

struct HeaderData {
    char format[2];
    char n_trks[2];
    char division[2];
};

HeaderData* header = new HeaderData;

Then, to get the data directly from the file to header I do

file.read(reinterpret_cast<char*>(header), sizeof(HeaderData))

If the first two bytes are00 06, header->format[0] will be 00 and header->format[1] 06. This two numbers combined represent the number 0x0006 which is 6 in decimal, which is the desired value.

When I do something like

*reinterpret_cast<unsigned*>(header->format) // In this case, the result is 0x0600

it erroneously returns the number 0x0600, so it seems that it inverts the reading of bytes.

My question is what is some workaround to correctly read the numbers as unsigned.