问:
Make SWRevealViewController as rootViewController after Sign In when it has tabbarController as sw_front objC
This is my Storyboards :

Say I have a Sign In viewController above these and from where I want to make SWRevealViewController as my rootViewController, so that It can work perfectly. With the below code, From my leftMenuViewController I can select my tabBar with desired ViewController perfectly.

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITabBarController *tabBarController = (UITabBarController *)self.revealViewController.frontViewController;
    UINavigationController *navController = tabBarController.viewControllers[indexPath.row];
    [navController popToRootViewControllerAnimated:NO];
    tabBarController.selectedIndex = indexPath.row;
    self.revealViewController.rearViewRevealOverdraw = 0.0f;
    [self.revealViewController pushFrontViewController:tabBarController animated:YES];
}
</code>```

But it is not working in App delegate or in SignInViewController.

```<code>- (void)checkIfUserSignedIn
{
    if ([ManagerClass getBOOLTypeUserDefaultForKey:@"isSignedIn"] == YES) {
        UITabBarController *tabBarController = (UITabBarController *)self.revealViewController.frontViewController;
        UINavigationController *navController = tabBarController.viewControllers[0];
        [navController popToRootViewControllerAnimated:NO];
        tabBarController.selectedIndex = 0;
        self.revealViewController.rearViewRevealOverdraw = 0.0f;
        [self.revealViewController pushFrontViewController:tabBarController animated:YES];
        self.window.rootViewController = tabBarController;
    } else {

    }
}
</code>```

It is giving this in log:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application windows are expected to have a root view controller at the end of application launch'
Any help will be highly appreciated. Thanks a lot in advance.

Have a good day.

答:
All I need to do is this:

```<code>UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:mainStoryboard bundle:[NSBundle mainBundle]];
        SWRevealViewController *controller = (SWRevealViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"RevealViewControllerID"];
        [self.window setRootViewController:controller];
</code>```

Just set SWRevealViewController as your rootViewController of the project. :)

Body:
This is my Storyboards :

Say I have a Sign In viewController above these and from where I want to make SWRevealViewController as my rootViewController, so that It can work perfectly. With the below code, From my leftMenuViewController I can select my tabBar with desired ViewController perfectly.

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    UITabBarController *tabBarController = (UITabBarController *)self.revealViewController.frontViewController;
    UINavigationController *navController = tabBarController.viewControllers[indexPath.row];
    [navController popToRootViewControllerAnimated:NO];
    tabBarController.selectedIndex = indexPath.row;
    self.revealViewController.rearViewRevealOverdraw = 0.0f;
    [self.revealViewController pushFrontViewController:tabBarController animated:YES];
}

But it is not working in App delegate or in SignInViewController.

- (void)checkIfUserSignedIn
{
    if ([ManagerClass getBOOLTypeUserDefaultForKey:@"isSignedIn"] == YES) {
        UITabBarController *tabBarController = (UITabBarController *)self.revealViewController.frontViewController;
        UINavigationController *navController = tabBarController.viewControllers[0];
        [navController popToRootViewControllerAnimated:NO];
        tabBarController.selectedIndex = 0;
        self.revealViewController.rearViewRevealOverdraw = 0.0f;
        [self.revealViewController pushFrontViewController:tabBarController animated:YES];
        self.window.rootViewController = tabBarController;
    } else {

    }
}

It is giving this in log:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Application windows are expected to have a root view controller at the end of application launch'
Any help will be highly appreciated. Thanks a lot in advance.

Have a good day.

Body:
All I need to do is this:

UIStoryboard *storyBoard = [UIStoryboard storyboardWithName:mainStoryboard bundle:[NSBundle mainBundle]];
        SWRevealViewController *controller = (SWRevealViewController *)[storyBoard instantiateViewControllerWithIdentifier:@"RevealViewControllerID"];
        [self.window setRootViewController:controller];

Just set SWRevealViewController as your rootViewController of the project. :)


来源: stackexchange

问:
Utalization of classes in python
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

```<code>        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True
</code>```

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.

答:
You can shorten

```<code>def flip(self):
    ''' Sets switch to opposite position.'''
    if self.state == True:
        self.state = False

    elif self.state == False:
        self.state = True
</code>```

to

```<code>def flip(self):
    ''' Sets switch to opposite position.'''
    self.state = not self.state
</code>```

and on your switchboard for

```<code>    def flip_every(self, n):
        for i in range(0, len(self.switchboard), n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True
</code>```

to

```<code>def flip_every(self, n):
    for i in range(0, self.quantity, n):
        self.switchboard[n] = not self.switchboard[n]
        # you could also just use self.flip(n) instead
</code>```

and

```<code>def flip(self, n):
    self.switchboard[n] =  not self.switchboard[n]
</code>```

As a nice touch: you use kind-of the same iteration in which_switch(self) and  __str__(self): that operates on the indexes of switches that are on. I built a small def getOnIndexes(self): ... that returns you an int list of those indexes, and call this in both methods (DRY - dont repeat yourself principle) using a shorthand to create indexes based on a list comprehension.

```<code>    def getOnIndexes(self):
        return [i for i in range(self.quantity) if self.switchboard[i] == True]
</code>```

In total a really nice small OOP example.

What had me stumped though, is why a Switchboard IS_A LightSwitch - I would model it slightly different, saying a SwitchBoard HAS LightSwitch'es, coming to this:

Your base class

```<code>class LightSwitch():
    def __init__(self, default_state):
        '''
        default_state can only be 'on' or 'off'.
        '''
        if default_state == 'on':
            self.state = True
        elif default_state == 'off':
            self.state = False

    def turn_on(self):
        self.state = True

    def turn_off(self):
        self.state = False

    def flip(self):
        self.state = not self.state

    def __str__(self):
        if self.state == True:
            return 'I am on'

        if self.state == False:
            return 'I am off'

    def isOn(self):
        return self.state

    def isOff(self):
        return not self.isOn()
</code>```

My alternative switch board:

```<code>class AlternateSwitchBoard():
    ''' '''
    def __init__(self, quantity, default_state):
        ''' '''
        self.default_state = default_state
        self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
        self.state = False
        self.quantity = quantity

    def __str__(self):
        retVal = ""
        for i in range(self.quantity):
            if self.switchboard[i].isOn():
                retVal += ", On"
            else:
                retVal += ", Off"
        return "Switchboard: " + retVal[1:].strip()

    def which_switch(self):
        print(self.getOnIndexes())

    def flip(self, n):
        self.switchboard[n].flip()

    def flip_every(self,stride):
        for i in range(0, self.quantity, stride):
            self.switchboard[i].flip()

    def reset(self):
        self.switchboard = [LightSwitch(default_state) for x in range(quantity)]

    def getOnIndexes(self):
        return [i for i in range(self.quantity) if self.switchboard[i].isOn()]

s2 = AlternateSwitchBoard(10, "off")
s2.flip(2)
s2.flip(7)
print(str(s2))
s2.flip_every(2)
print(str(s2))
s2.which_switch()
</code>```

Output:

```<code>Switchboard: Off, Off, On, Off, Off, Off, Off, On, Off, Off
Switchboard: On, Off, Off, Off, On, Off, On, On, On, Off
[0, 4, 6, 7, 8]
</code>```

ContentLicense: CC BY-SA 3.0

Title: Utalization of classes in python

Body:
I'm trying to teach myself about OOP in python and am really struggling.

I have the following:

        def __init__(self, quantity):
            ''' '''
            self.switchboard = []
            self.state = False
            self.quantity = quantity
            for i in range(quantity):
                self.switchboard.append(i)

        def __str__(self):
            self.on_list = []
            for i in range(self.quantity):
                if i == True:
                    self.on_list.append(i)
            return("The following switches are on " + str(self.on_list))
        def which_switch(self):
            for i in range(len(self.switchboard)):
                self.on_list = []
                if self.switchboard[i] == True:
                    on_list.append(i)
                print(on_list)

        def flip(self, n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True

When I print it, I get The following switches are on [1]. Even though I put 10 in the parameters. I want it to display all the switches that are on which in this case should be zero since their initial state is 'off'.

Body:
You can shorten

def flip(self):
    ''' Sets switch to opposite position.'''
    if self.state == True:
        self.state = False

    elif self.state == False:
        self.state = True

to

def flip(self):
    ''' Sets switch to opposite position.'''
    self.state = not self.state

and on your switchboard for

    def flip_every(self, n):
        for i in range(0, len(self.switchboard), n):
            if self.switchboard[n] == True:
                self.switchboard[n] = False
            else:
                self.switchboard[n] = True

to

def flip_every(self, n):
    for i in range(0, self.quantity, n):
        self.switchboard[n] = not self.switchboard[n]
        # you could also just use self.flip(n) instead

and

def flip(self, n):
    self.switchboard[n] =  not self.switchboard[n]

As a nice touch: you use kind-of the same iteration in which_switch(self) and  __str__(self): that operates on the indexes of switches that are on. I built a small def getOnIndexes(self): ... that returns you an int list of those indexes, and call this in both methods (DRY - dont repeat yourself principle) using a shorthand to create indexes based on a list comprehension.

    def getOnIndexes(self):
        return [i for i in range(self.quantity) if self.switchboard[i] == True]

In total a really nice small OOP example.

What had me stumped though, is why a Switchboard IS_A LightSwitch - I would model it slightly different, saying a SwitchBoard HAS LightSwitch'es, coming to this:

Your base class

class LightSwitch():
    def __init__(self, default_state):
        '''
        default_state can only be 'on' or 'off'.
        '''
        if default_state == 'on':
            self.state = True
        elif default_state == 'off':
            self.state = False

    def turn_on(self):
        self.state = True

    def turn_off(self):
        self.state = False

    def flip(self):
        self.state = not self.state

    def __str__(self):
        if self.state == True:
            return 'I am on'

        if self.state == False:
            return 'I am off'

    def isOn(self):
        return self.state

    def isOff(self):
        return not self.isOn()

My alternative switch board:

class AlternateSwitchBoard():
    ''' '''
    def __init__(self, quantity, default_state):
        ''' '''
        self.default_state = default_state
        self.switchboard = [LightSwitch(default_state) for x in range(quantity)]
        self.state = False
        self.quantity = quantity

    def __str__(self):
        retVal = ""
        for i in range(self.quantity):
            if self.switchboard[i].isOn():
                retVal += ", On"
            else:
                retVal += ", Off"
        return "Switchboard: " + retVal[1:].strip()

    def which_switch(self):
        print(self.getOnIndexes())

    def flip(self, n):
        self.switchboard[n].flip()

    def flip_every(self,stride):
        for i in range(0, self.quantity, stride):
            self.switchboard[i].flip()

    def reset(self):
        self.switchboard = [LightSwitch(default_state) for x in range(quantity)]

    def getOnIndexes(self):
        return [i for i in range(self.quantity) if self.switchboard[i].isOn()]

s2 = AlternateSwitchBoard(10, "off")
s2.flip(2)
s2.flip(7)
print(str(s2))
s2.flip_every(2)
print(str(s2))
s2.which_switch()

Output:

Switchboard: Off, Off, On, Off, Off, Off, Off, On, Off, Off
Switchboard: On, Off, Off, Off, On, Off, On, On, On, Off
[0, 4, 6, 7, 8]


问:
Javascript - push children to array, appendChild the array to other DOM element effects the childrens list?
So I have a list of children from a DOM element. I take the child list and push it to an empty array. When I appendChild the array elements one by one, why does it change the position of the children elements? Shouldn't it effect only the array?</p>

```<code>var listItemsContainer = document.getElementById("$content_id");
var items = listItemsContainer.children;
var itemsArr = [];
var continentcontainer = document.getElementById('continents');

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

itemsArr.sort(function(a, b) { //sorting itemsArr (array of listItems) A to Z
  return a.innerHTML == b.innerHTML ?
    0 :
    (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (var i = 0; i < itemsArr.length; ++i) {
  continentcontainer.appendChild(itemsArr[i]); //append child moves item from current location into new location
}
</code>```

答:
change

```<code>for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}
</code>```

to

```<code>for (var i = 0; i < items.length; i++) {
  itemsArr.push(items[i].cloneNode(true));
}
</code>```

for...in should not be used to iterate over an Array where the index
  order is important. MDN

Body:
So I have a list of children from a DOM element. I take the child list and push it to an empty array. When I appendChild the array elements one by one, why does it change the position of the children elements? Shouldn't it effect only the array?

var listItemsContainer = document.getElementById("$content_id");
var items = listItemsContainer.children;
var itemsArr = [];
var continentcontainer = document.getElementById('continents');

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

itemsArr.sort(function(a, b) { //sorting itemsArr (array of listItems) A to Z
  return a.innerHTML == b.innerHTML ?
    0 :
    (a.innerHTML > b.innerHTML ? 1 : -1);
});

for (var i = 0; i < itemsArr.length; ++i) {
  continentcontainer.appendChild(itemsArr[i]); //append child moves item from current location into new location
}

Body:
change

for (var i in items) { //for each item in listItemsContainer
  itemsArr.push(items[i]); //add them to the itemsArray (not moving)
}

to

for (var i = 0; i < items.length; i++) {
  itemsArr.push(items[i].cloneNode(true));
}

for...in should not be used to iterate over an Array where the index
  order is important. MDN


问:
Additional firebase database field being added automatically?
I have a book class as

```<code>public class Books {

    public String bookName;
    public String author;
    public String copies;

    public Books() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public Books(String name, String author, String copies) {
        this.bookName = name;
        this.author = author;
        this.copies = copies;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthorName() {
        return author;
    }

    public String getCopies() {
        return copies;
    }

}
</code>```

And i'm adding to firebase realtime cloud database as

```<code>mDatabase = FirebaseDatabase.getInstance("https://cmpe-2b339.firebaseio.com").getReference();

Books book = new Books(bookName,author,copies);
                    mDatabase.push().setValue(book);
</code>```

However in firebase concole, its coming as

```<code>{
  "-KzAt3eHDBtD7gFvLIbn" : {
    "author" : "J",
    "authorName" : "J",
    "bookName" : "Hi",
    "copies" : "5"
  }
}
</code>```

There is added author field, which i dont understand

答: You have a public variable named "author" and a public getter named "getAuthorName". Firebase reflection is using both to create the data in the database. Fix: make your variables private and keep the getters, then add the setters.</p>

Body:
I have a book class as

public class Books {

    public String bookName;
    public String author;
    public String copies;

    public Books() {
        // Default constructor required for calls to DataSnapshot.getValue(User.class)
    }

    public Books(String name, String author, String copies) {
        this.bookName = name;
        this.author = author;
        this.copies = copies;
    }

    public String getBookName() {
        return bookName;
    }

    public String getAuthorName() {
        return author;
    }

    public String getCopies() {
        return copies;
    }

}

And i'm adding to firebase realtime cloud database as

mDatabase = FirebaseDatabase.getInstance("https://cmpe-2b339.firebaseio.com").getReference();

Books book = new Books(bookName,author,copies);
                    mDatabase.push().setValue(book);

However in firebase concole, its coming as

{
  "-KzAt3eHDBtD7gFvLIbn" : {
    "author" : "J",
    "authorName" : "J",
    "bookName" : "Hi",
    "copies" : "5"
  }
}

There is added author field, which i dont understand


问:
Is it good practice in Android to implement our own back button rather than using device's backbutton

Is it good practice in Android to implement our own back button rather than using device's backbutton. May I know what are the disadvantages of using our own back button in Application rather than device provided one.

Thanks in Advance,

答:
Is it good practice in Android to implement our own back button rather than using device's backbutton.

Absolutely not.

May I know what are the disadvantages of using our own back button in Application rather than device provided one.

Waste of screen space

Lack of design consistency with other Android apps

ContentLicense: CC BY-SA 2.5


问:
Can you share parent resource between terraform sub directories?
I'm thinking about breaking up an application into micro-services using this terraform directory structure:

```<code>/staging
  /global
  /service1
  /service2
/prod
  /global
  /service1
  /service2
</code>```

Suppose I would like each microservice to have it's own AWS Apigateway endpoint:

```<code>myurl.com/service1
myurl.com/service2
</code>```

Both services can be part of the same parent AWS apigateway resource:

```<code>#creates the api (a parent of all resources),
resource "aws_api_gateway_rest_api" "api" {
  name        = "API root parent"
  description = "Contains all endpoints"
}
</code>```

My understanding is that each top level AWS REST api would be it's own cloudfront so I only need ONE of them for all my microservices instead of one REST api per microservice.  I would like to put the REST api declaration in the /global folder since that would be shared by all microservices.

Then in service1 subdirectory I would start defining resources that would need to reference the parent:

```<code>resource "aws_api_gateway_resource" "service1" {
  rest_api_id = "${aws_api_gateway_rest_api.api.id}"
  parent_id   = "${aws_api_gateway_rest_api.api.root_resource_id}"
  path_part   = "service1"
}
</code>```

But how would the service1 subdirectory have access to the api resource since it's not defined in the same directory?

I might be able to import the state of an existing resource into the subdirectory, for each microservice subdirectory but that seems like a mess.

UPDATE: It looks like AWS api gateway only charges for usage so I can just create separate rest api resources for each subdirectory after all.  But I might still need to know how to collect the resource variables across the sub-folders in order to add the respective api deployment stages to a common custom domain.  Is there a technique or pattern for being able to separate projects mostly by folders but being able to extract variables and glue them together in /global which is not specific to each subdirectory?

答:
Remote states in terraform is what you are looking for https://www.terraform.io/docs/state/remote.html
https://www.terraform.io/docs/providers/terraform/d/remote_state.html

Since you are in AWS, you could use S3 as storage for the remote states.

```<code>data "terraform_remote_state" "prod_service1" {
  backend = "s3"
  config {
    region = "eu-west-1"
    bucket = "uservices_terraform_bucket_name"
    key    = "/states/prod/service1/terraform.tfstate"

    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    token      = "${var.aws_session_token}"
  }
}
</code>```

Then you would be able to use the outputs of the terraform states in another microservice using

```<code>"${data.terraform_remote_state.prod_service1.api_id}"
</code>```

Body:
I'm thinking about breaking up an application into micro-services using this terraform directory structure:

/staging
  /global
  /service1
  /service2
/prod
  /global
  /service1
  /service2

Suppose I would like each microservice to have it's own AWS Apigateway endpoint:

myurl.com/service1
myurl.com/service2

Both services can be part of the same parent AWS apigateway resource:

#creates the api (a parent of all resources),
resource "aws_api_gateway_rest_api" "api" {
  name        = "API root parent"
  description = "Contains all endpoints"
}

My understanding is that each top level AWS REST api would be it's own cloudfront so I only need ONE of them for all my microservices instead of one REST api per microservice.  I would like to put the REST api declaration in the /global folder since that would be shared by all microservices.

Then in service1 subdirectory I would start defining resources that would need to reference the parent:

resource "aws_api_gateway_resource" "service1" {
  rest_api_id = "${aws_api_gateway_rest_api.api.id}"
  parent_id   = "${aws_api_gateway_rest_api.api.root_resource_id}"
  path_part   = "service1"
}

But how would the service1 subdirectory have access to the api resource since it's not defined in the same directory?

I might be able to import the state of an existing resource into the subdirectory, for each microservice subdirectory but that seems like a mess.

UPDATE: It looks like AWS api gateway only charges for usage so I can just create separate rest api resources for each subdirectory after all.  But I might still need to know how to collect the resource variables across the sub-folders in order to add the respective api deployment stages to a common custom domain.  Is there a technique or pattern for being able to separate projects mostly by folders but being able to extract variables and glue them together in /global which is not specific to each subdirectory?

Body:
Remote states in terraform is what you are looking for https://www.terraform.io/docs/state/remote.html
https://www.terraform.io/docs/providers/terraform/d/remote_state.html

Since you are in AWS, you could use S3 as storage for the remote states.

data "terraform_remote_state" "prod_service1" {
  backend = "s3"
  config {
    region = "eu-west-1"
    bucket = "uservices_terraform_bucket_name"
    key    = "/states/prod/service1/terraform.tfstate"

    access_key = "${var.aws_access_key}"
    secret_key = "${var.aws_secret_key}"
    token      = "${var.aws_session_token}"
  }
}

Then you would be able to use the outputs of the terraform states in another microservice using

"${data.terraform_remote_state.prod_service1.api_id}"


问:
Decimal conversion fails when used in sub-namespace in Microsoft Bond
Following the example here: https://github.com/Microsoft/bond/tree/master/examples/cs/core/decimal

I am trying to use decimal in a struct that is not in the base namespace and get the exception "Expression of type 'System.Decimal' cannot be used for assignment to type 'System.ArraySegment`1[System.Byte]'".

If I keep all structs in the same namespace, everything works great. Is there some type of qualifying I have to do?

I've put together a small project and a couple unit tests to demonstrate: https://github.com/oculuss/BondDecimalExample

TestA has everything in the same namespace. TestB has a few sub-namespaces (and is what breaks).

答:
A BondTypeAliasConverter must be defined "in the same assembly and namespace as the class representing the Bond schema(s) in which the type alias is used or assembly/namespace of one of the types being converted." It cannot be defined in a parent namespace. The search algorithm isn't that smart. :-) Thus, in TestB, you need to put the BondTypeAliasConverter class in the C# namespace "BondExampleB.Global.SecondType.SecondTypeA" (or wherever you've mapped that to in C#).

There are an open design proposal to make this a bit easier. See issue #594 in the Bond GitHub project.

Until something comes from that, if you want to have the same converters for types in different namespaces, you'll need to do something like this:

```<code>namespace Util
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused) { ... }
        public ArraySegment<byte> Convert(decimal d, ArraySegment<byte> unused) { ... }
    }
}

namespace First
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused)
        {
            return Util.BondTypeAliasConverter.Convert(blob, unused);
        }

        ....
    }
}

namespace First.Second
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused)
        {
            return Util.BondTypeAliasConverter.Convert(blob, unused);
        }

        ....
    }
}
</code>```

Body:
A BondTypeAliasConverter must be defined "in the same assembly and namespace as the class representing the Bond schema(s) in which the type alias is used or assembly/namespace of one of the types being converted." It cannot be defined in a parent namespace. The search algorithm isn't that smart. :-) Thus, in TestB, you need to put the BondTypeAliasConverter class in the C# namespace "BondExampleB.Global.SecondType.SecondTypeA" (or wherever you've mapped that to in C#).

There are an open design proposal to make this a bit easier. See issue #594 in the Bond GitHub project.

Until something comes from that, if you want to have the same converters for types in different namespaces, you'll need to do something like this:

namespace Util
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused) { ... }
        public ArraySegment<byte> Convert(decimal d, ArraySegment<byte> unused) { ... }
    }
}

namespace First
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused)
        {
            return Util.BondTypeAliasConverter.Convert(blob, unused);
        }

        ....
    }
}

namespace First.Second
{
    public static class BondTypeAliasConverter
    {
        public decimal Convert(ArraySegment<byte> blob, decimal unused)
        {
            return Util.BondTypeAliasConverter.Convert(blob, unused);
        }

        ....
    }
}


问:
C language-> Read a file to a dynamic array
So I have a file that as some text and I want my function to read that file and store it on an array. I did some code and when I print my dynamic array it prints crap values :< help.</p>

```<code>char* read_message(char *filename)
{   //gets the PATH of the txt file
    char *file_contents;
    long input_file_size;
    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)
    {
         return NULL;
    }
    fseek(input_file, 0, SEEK_END);
    input_file_size = ftell(input_file);
    rewind(input_file);
    file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
    fread(file_contents, input_file_size, 1, input_file);
    printf("%s",file_contents);//----Prints crap--------
    fclose(input_file);
                                                  // returns the address to the array of strings
    return file_contents;
}
</code>```

答:
The problem is immediately before the offending printf().

```<code>file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
fread(file_contents, input_file_size, 1, input_file);
printf("%s",file_contents);//----Prints crap--------
</code>```

fread() does a binary read.   It does not add a zero terminator to file_contents.    If there is no character with value zero in the data read from file, then the printf() call has undefined behaviour.

Not also that fread() generally presumes that the file is opened for binary reading as well.   Your open() statement does not open the file in binary mode.

Body:
So I have a file that as some text and I want my function to read that file and store it on an array. I did some code and when I print my dynamic array it prints crap values :< help.

char* read_message(char *filename)
{   //gets the PATH of the txt file
    char *file_contents;
    long input_file_size;
    FILE *input_file = fopen(filename, "r");
    if(input_file == NULL)
    {
         return NULL;
    }
    fseek(input_file, 0, SEEK_END);
    input_file_size = ftell(input_file);
    rewind(input_file);
    file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
    fread(file_contents, input_file_size, 1, input_file);
    printf("%s",file_contents);//----Prints crap--------
    fclose(input_file);
                                                  // returns the address to the array of strings
    return file_contents;
}

Body:
The problem is immediately before the offending printf().

file_contents = (char*)malloc(input_file_size+1 * (sizeof(char)));
fread(file_contents, input_file_size, 1, input_file);
printf("%s",file_contents);//----Prints crap--------

fread() does a binary read.   It does not add a zero terminator to file_contents.    If there is no character with value zero in the data read from file, then the printf() call has undefined behaviour.

Not also that fread() generally presumes that the file is opened for binary reading as well.   Your open() statement does not open the file in binary mode.


问:
(jQuery) A click event is sometimes not attached to its element - seems tied to Developer Tools being open
I have been trying to locate the source of a problem for a few hours now, and I am beginning to think my bug suffers from the observer effect!

In summary:

There are checkboxes on my page

Once the entire page has finished loading, attach a listener to each checkbox

```<code>var myModule = (function() {
    var myFunction = function() {
        console.log("Do something");
     }

    var setUpTogglers = function() {
        var dict = {
          "#checkbox1": "div.div1",
          "#checkbox2": "div.div2"
        };

        $.each(dict, function(i, elem) {
           var toggler = $(i);
           var fader = $(dict[i]);
           toggler.on('click', function() {
               myFunction(fader);
           });
        });
    };

    return {
        init: function() {
            setUpTogglers();
         }
    };
})();

$(window).on("load", function() {
    myModule.init();
});
</code>```

This is a pretty straight forward task (or so I thought, anyways.) My problem arises from the click event being listened for only SOME of the time.

Here is a case where it does not work:

Navigate through the site to the page with the checkboxes

Inspect the checkbox element with the Developer Tools

Examine the 'Event Listeners' tab

My element does not appear under click root

Here is a case where it does work

Open Developer Tools

Navigate through the site to the page with the checkboxes

Examine the 'Event Listeners' tab

My element does appear under click root

I've tested it a number of times in various ways. I've loaded/refreshed the page with Developer Tools open and not had a listener; I've refreshed the page with CTRL-F5 (and Developer Tools not open) and HAD a listener; I've set a breakpoint where the listener gets attached and sometimes the listener gets attached, sometimes it does not.

In all the testing that I've been doing for the last hour, however, the listener has gotten attached when the page has been loaded or refreshed with the Developer Tools window open. This leads me to believe it's some sort of load order issue? I really have no idea where to even start debugging this. If anyone has any suggestions, it would very much be appreciated.

tldr:
Event listener getting attached to checkbox when developer tools is open, but not always getting attached otherwise. What could be some reasons for this happening?

Note: I am using Google Chrome

答:
based on the code provided i would suggest refactoring this as the hard coded dictionary and the each loop seems dodgy and strange to me.

Why not have something like this? This also makes your code testable and easier to debug using the console sinse you are tagging google dev tools etc in your question.

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

    function BindEventLister(jquerySelector, fader){

           $(''+jquerySelector+'').on('click', function() {
               myFunction(fader);
           });
     }

    var myFunction = function() {
        console.log("Do something");
     }

    var setUpTogglers = function() {

         BindEventLister("#checkbox1","div.div1");

         BindEventLister("#checkbox2","div.div2");
    };

    return {
        init: function() {
            setUpTogglers();
         }
    };
})();

$(window).on("load", function() {
    myModule.init();
});
</code>```

Im not testing/running this code im just typing out a rough idea quickly to help.

Body:
I have been trying to locate the source of a problem for a few hours now, and I am beginning to think my bug suffers from the observer effect!

In summary:

There are checkboxes on my page

Once the entire page has finished loading, attach a listener to each checkbox

var myModule = (function() {
    var myFunction = function() {
        console.log("Do something");
     }

    var setUpTogglers = function() {
        var dict = {
          "#checkbox1": "div.div1",
          "#checkbox2": "div.div2"
        };

        $.each(dict, function(i, elem) {
           var toggler = $(i);
           var fader = $(dict[i]);
           toggler.on('click', function() {
               myFunction(fader);
           });
        });
    };

    return {
        init: function() {
            setUpTogglers();
         }
    };
})();

$(window).on("load", function() {
    myModule.init();
});

This is a pretty straight forward task (or so I thought, anyways.) My problem arises from the click event being listened for only SOME of the time.

Here is a case where it does not work:

Navigate through the site to the page with the checkboxes

Inspect the checkbox element with the Developer Tools

Examine the 'Event Listeners' tab

My element does not appear under click root

Here is a case where it does work

Open Developer Tools

Navigate through the site to the page with the checkboxes

Examine the 'Event Listeners' tab

My element does appear under click root

I've tested it a number of times in various ways. I've loaded/refreshed the page with Developer Tools open and not had a listener; I've refreshed the page with CTRL-F5 (and Developer Tools not open) and HAD a listener; I've set a breakpoint where the listener gets attached and sometimes the listener gets attached, sometimes it does not.

In all the testing that I've been doing for the last hour, however, the listener has gotten attached when the page has been loaded or refreshed with the Developer Tools window open. This leads me to believe it's some sort of load order issue? I really have no idea where to even start debugging this. If anyone has any suggestions, it would very much be appreciated.

tldr:
Event listener getting attached to checkbox when developer tools is open, but not always getting attached otherwise. What could be some reasons for this happening?

Note: I am using Google Chrome

Body:
based on the code provided i would suggest refactoring this as the hard coded dictionary and the each loop seems dodgy and strange to me.

Why not have something like this? This also makes your code testable and easier to debug using the console sinse you are tagging google dev tools etc in your question.

var myModule = (function() {

    function BindEventLister(jquerySelector, fader){

           $(''+jquerySelector+'').on('click', function() {
               myFunction(fader);
           });
     }

    var myFunction = function() {
        console.log("Do something");
     }

    var setUpTogglers = function() {

         BindEventLister("#checkbox1","div.div1");

         BindEventLister("#checkbox2","div.div2");
    };

    return {
        init: function() {
            setUpTogglers();
         }
    };
})();

$(window).on("load", function() {
    myModule.init();
});

Im not testing/running this code im just typing out a rough idea quickly to help.


问:
Set Value to a dynamically created Ion-Input
I have a dynamically created Ion-Input control.

Below that there is a button on click on that button i will open the scanner and read the bar code. I want this bar code to appear on the Ion-Input that i created dynamically.

```<code><input *ngSwitchCase="'textbox'" [formControlName]="question.key"
        [id]="question.key" [type]="question.type">

<button type="button" ion-button (click)="Scan"></button>

Scan(){
 return barcodeasString;
}
</code>```

I want the barcode to appear on the ion-input. I tried to pass the this object and question object and set its value but it didnt work.

Any hints would be helpful!!

https://plnkr.co/edit/ZmzmANTP3bpFmSX7lle0?p=preview

答:
In your app/dynamic-form-question.component.html file, you can change it to either of these:

One-way Binding:

<input #scannerInput [ngModel]="question.value"
[formControlName]="question.key" [id]="question.key" >

Two-way Binding:

<input #scannerInput [(ngModel)]="question.value"
 [formControlName]="question.key" [id]="question.key" >

Basically, one way binding will update the view when the controller updates the value. Two way binding does the same as one-way but also works in reverse (updates the controller when the view is updated.

Body:
I have a dynamically created Ion-Input control.

Below that there is a button on click on that button i will open the scanner and read the bar code. I want this bar code to appear on the Ion-Input that i created dynamically.

<input *ngSwitchCase="'textbox'" [formControlName]="question.key"
        [id]="question.key" [type]="question.type">

<button type="button" ion-button (click)="Scan"></button>

Scan(){
 return barcodeasString;
}

I want the barcode to appear on the ion-input. I tried to pass the this object and question object and set its value but it didnt work.

Any hints would be helpful!!

https://plnkr.co/edit/ZmzmANTP3bpFmSX7lle0?p=preview


问:
Can I file_put_contents to send to an http web address?
I'm trying to have an event trigger that once it does it sends the content to a text file from another web address that I should have access to. I've tried the code below but it will not allow me to do so, the error report reads,

"failed to open stream: HTTP wrapper does not support writeable
  connections in /data/custom/test-alarm-upload.php on line 36"

Is this even possible to do in php?

```<code><?php

if (file_exists($myFile))
{
    $fh = fopen($myFile, 'r');
    $Gas_Seperator = fread($fh, 12);
    fclose($fh);
    $Gas_Seperator = ereg_replace("[^0-9.-]", "", $Gas_Seperator);
    $Gas_Seperator = ($Gas_Seperator * 25) - 12.5;
}

$theday = date (j);
$themonth = date (F);
$theyear = date (Y);
$thetime = date (g);
$theAMPM = date (A);
$thest = date (S);

$entry ="\n" . $themonth . " " . $theday . "" . $thest . " " . $thetime . "" . $theAMPM . "," . $Gas_Seperator;

file_put_contents('http://XXX.XXX.XXX.XXX/data/custom/alarm.txt' , $entry, FILE_APPEND);
?>
</code>```

答:
As per PHP.net

A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.

Body:
I'm trying to have an event trigger that once it does it sends the content to a text file from another web address that I should have access to. I've tried the code below but it will not allow me to do so, the error report reads,

"failed to open stream: HTTP wrapper does not support writeable
  connections in /data/custom/test-alarm-upload.php on line 36"

Is this even possible to do in php?

<?php

if (file_exists($myFile))
{
    $fh = fopen($myFile, 'r');
    $Gas_Seperator = fread($fh, 12);
    fclose($fh);
    $Gas_Seperator = ereg_replace("[^0-9.-]", "", $Gas_Seperator);
    $Gas_Seperator = ($Gas_Seperator * 25) - 12.5;
}

$theday = date (j);
$themonth = date (F);
$theyear = date (Y);
$thetime = date (g);
$theAMPM = date (A);
$thest = date (S);

$entry ="\n" . $themonth . " " . $theday . "" . $thest . " " . $thetime . "" . $theAMPM . "," . $Gas_Seperator;

file_put_contents('http://XXX.XXX.XXX.XXX/data/custom/alarm.txt' , $entry, FILE_APPEND);
?>


问:
PCA difference between python numpy and sklearn
I am trying to implement the PCA using numpy.linalg.eig with two differents methods(with the covariance and the pca method used in eigenface) and I compare my results with the PCA from sklearn. But I observe that my results are differents so I was wondering which mistake I am doing. I have 3 samples, and each sample have 4 features. I am trying to reduce then the dimension of the samples to 3.
EDIT : add with the SVD method.  IThe results I get using the covariance PCA , the SVD and the PCA from sklearn are pretty close. But with the "eigenface" method it is totally different why ?
    import numpy as np
    from sklearn.decomposition import PCA</p>

```<code>x = np.array([[0.5, 0.8, 1.5, -2.4], [-1.9, -8.7, 0.02, 4.9], [5.5,6.1, -8.1,3.0]])
print(x)
K = 3

# -- sklearn -- #
pca = PCA(n_components=K).fit(x)
res = pca.transform(x)
print('sklearn :', res)

# -- numpy covariance -- #
X = x - np.mean(x, axis = 0)

cov = np.cov(X.T)
print("covariance :", cov.shape)

evals , evecs = np.linalg.eig(cov)

idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

res2 = X.dot(evecs[:,:K])
print("numpy with cov:", res2)

# -- numpy scatter matrix -- #
X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

v = np.dot(evecs, X)
print("v :", v.shape)
res3= X[:, :K].dot(v)
print('numpy with scatter matrix : ', res3)

# -- numpy svd -- #
X = x - np.mean(x, axis = 0)
U, S, V = np.linalg.svd(X, full_matrices=False)
U, V = svd_flip(U, V)
res2 = X.dot(V.T)
print("numpy with svd:", res2)
</code>```

答:
First of all: what does any of this mean? You have three points in a 4-dimensional space. They span a 2-dimensional plane. PCA finds a basis for this plane, and the coefficients of your points in that basis. Using Matlab's [C, S] = pca(x) for comparison: we get

```<code>C =
    0.4028    0.1082
    0.7895   -0.3198
   -0.4560   -0.5881
   -0.0806    0.7349
</code>```

and

```<code>S =
   -0.5865   -5.8249
   -8.9674    3.1891
    9.5539    2.6357
</code>```

which are matrices with the property that S*C' recovers centered data (which is X in your notation). The columns of C are basis vectors for the 2D subspace, the rows of S are the coordinates of your three points in that subset.

Sklearn returns

```<code>[[ -5.86525831e-01   5.82485371e+00  -2.65147201e-16]
 [ -8.96738194e+00  -3.18911605e+00   1.41061647e-16]
 [  9.55390777e+00  -2.63573766e+00  -5.28988843e-16]]
</code>```

where the third column is noise (essentially zeros), reflecting that the points lie in a 2D plane; there is no 3rd principal component to be found. The first two columns match S from Matlab, except for sign choices.

Your computation of "NumPy with cov" does the same as sklearn, except the random noise in the 3rd column is different. By the way, for this computation you don't need to center the data; cov does it on its own. cov = np.cov(x.T) would work just as well.

```<code>[[ -5.86525831e-01  -5.82485371e+00   5.26721273e-16]
 [ -8.96738194e+00   3.18911605e+00   3.83725073e-15]
 [  9.55390777e+00   2.63573766e+00  -3.35763132e-15]]
</code>```

"Eigenface" approach

The main idea here is that instead of computing np.dot(X.T, X) (essentially the covariance, up to a constant factor), we will work with the C = np.dot(X, X.T) which is smaller. The basis vectors we need will be obtained by multiplying the eigenvectors of C with X.T (if you are following Wikipedia's article, notice their T has different orientation from your X). However, these vectors are not normalized, unlike the vectors returned by np.linalg.eig. We'll have to normalize them before using:

```<code>X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]
v = np.dot(X.T, evecs)
v /= np.linalg.norm(v, axis=0)
res3 = X.dot(v)
</code>```

This returns

```<code>[[-0.58652583 -5.82485371  5.05711518]
 [-8.96738194  3.18911605  1.72266002]
 [ 9.55390777  2.63573766 -6.7797752 ]]
</code>```

which is correct in the first two columns. Again, the third column is noise, but now it's noise that went through normalization, so it's not small at all. One has to understand that the third column is meaningless.

Body:
I am trying to implement the PCA using numpy.linalg.eig with two differents methods(with the covariance and the pca method used in eigenface) and I compare my results with the PCA from sklearn. But I observe that my results are differents so I was wondering which mistake I am doing. I have 3 samples, and each sample have 4 features. I am trying to reduce then the dimension of the samples to 3.
EDIT : add with the SVD method.  IThe results I get using the covariance PCA , the SVD and the PCA from sklearn are pretty close. But with the "eigenface" method it is totally different why ?
    import numpy as np
    from sklearn.decomposition import PCA

x = np.array([[0.5, 0.8, 1.5, -2.4], [-1.9, -8.7, 0.02, 4.9], [5.5,6.1, -8.1,3.0]])
print(x)
K = 3

# -- sklearn -- #
pca = PCA(n_components=K).fit(x)
res = pca.transform(x)
print('sklearn :', res)

# -- numpy covariance -- #
X = x - np.mean(x, axis = 0)

cov = np.cov(X.T)
print("covariance :", cov.shape)

evals , evecs = np.linalg.eig(cov)

idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

res2 = X.dot(evecs[:,:K])
print("numpy with cov:", res2)

# -- numpy scatter matrix -- #
X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]

v = np.dot(evecs, X)
print("v :", v.shape)
res3= X[:, :K].dot(v)
print('numpy with scatter matrix : ', res3)

# -- numpy svd -- #
X = x - np.mean(x, axis = 0)
U, S, V = np.linalg.svd(X, full_matrices=False)
U, V = svd_flip(U, V)
res2 = X.dot(V.T)
print("numpy with svd:", res2)

Body:
First of all: what does any of this mean? You have three points in a 4-dimensional space. They span a 2-dimensional plane. PCA finds a basis for this plane, and the coefficients of your points in that basis. Using Matlab's [C, S] = pca(x) for comparison: we get

C =
    0.4028    0.1082
    0.7895   -0.3198
   -0.4560   -0.5881
   -0.0806    0.7349

and

S =
   -0.5865   -5.8249
   -8.9674    3.1891
    9.5539    2.6357

which are matrices with the property that S*C' recovers centered data (which is X in your notation). The columns of C are basis vectors for the 2D subspace, the rows of S are the coordinates of your three points in that subset.

Sklearn returns

[[ -5.86525831e-01   5.82485371e+00  -2.65147201e-16]
 [ -8.96738194e+00  -3.18911605e+00   1.41061647e-16]
 [  9.55390777e+00  -2.63573766e+00  -5.28988843e-16]]

where the third column is noise (essentially zeros), reflecting that the points lie in a 2D plane; there is no 3rd principal component to be found. The first two columns match S from Matlab, except for sign choices.

Your computation of "NumPy with cov" does the same as sklearn, except the random noise in the 3rd column is different. By the way, for this computation you don't need to center the data; cov does it on its own. cov = np.cov(x.T) would work just as well.

[[ -5.86525831e-01  -5.82485371e+00   5.26721273e-16]
 [ -8.96738194e+00   3.18911605e+00   3.83725073e-15]
 [  9.55390777e+00   2.63573766e+00  -3.35763132e-15]]

"Eigenface" approach

The main idea here is that instead of computing np.dot(X.T, X) (essentially the covariance, up to a constant factor), we will work with the C = np.dot(X, X.T) which is smaller. The basis vectors we need will be obtained by multiplying the eigenvectors of C with X.T (if you are following Wikipedia's article, notice their T has different orientation from your X). However, these vectors are not normalized, unlike the vectors returned by np.linalg.eig. We'll have to normalize them before using:

X = x - np.mean(x, axis = 0)
C = np.dot(X, X.T)
evals , evecs = np.linalg.eig(C)
idx = np.argsort(evals)[::-1]
evecs = evecs[:,idx]
evals = evals[idx]
v = np.dot(X.T, evecs)
v /= np.linalg.norm(v, axis=0)
res3 = X.dot(v)

This returns

[[-0.58652583 -5.82485371  5.05711518]
 [-8.96738194  3.18911605  1.72266002]
 [ 9.55390777  2.63573766 -6.7797752 ]]

which is correct in the first two columns. Again, the third column is noise, but now it's noise that went through normalization, so it's not small at all. One has to understand that the third column is meaningless.


问:
what is the default access modifier for controls created on .aspx page. Private or something else?
What is the default access modifier for controls created on .aspx page. Private or something else?</p>

答:
its 'protected'.

N

Body:
its 'protected'.

N


答:
Another problem is :

You wrote :

```<code>malloc(input_file_size + 1 * (sizeof(char));
</code>```

The priority goes to multiplication, so it is equivalent to :

```<code>malloc(input_file_size + (sizeof(char));
</code>```

You should add parentheses.

Title: C language-> Read a file to a dynamic array

Body:
Another problem is :

You wrote :

malloc(input_file_size + 1 * (sizeof(char));

The priority goes to multiplication, so it is equivalent to :

malloc(input_file_size + (sizeof(char));

You should add parentheses.


问:
All Material Angular directives come up as 'is not a known element'
I am on an Angular 5 project (5.0.0-rc0) with Angular 5 material (5.0.0-rc0) and for the life of me I can not debug while every single angular 5 material directive is coming up with

mat-xyz is not a known element

Here is what my app.module looks like

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Component } from '@angular/core';
// Import the Http Module and our Data Service
import { DataService } from './data.service';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import 'hammerjs';

import {
  MatAutocompleteModule,
  ...
  MatStepperModule
} from '@angular/material';
import { HttpModule } from '@angular/http';
import { CdkTableModule } from '@angular/cdk/table';
import { LandingComponent } from './sandbox/landing/landing.component';

@NgModule({
  declarations: [
    AppComponent,
    LandingComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

The Landing component has HTML like so

```<code><form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>
</code>```

and it's .ts is the following

```<code>import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}
</code>```

I know its probably something small or stupid, but for the life of me I can not find it

Thanks in advance!

答:
Move them to the imports. You currently have them in exports:</p>

```<code>imports: [
    BrowserModule,
    HttpModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  exports: [
    CdkTableModule
  ],
</code>```

Body:
I am on an Angular 5 project (5.0.0-rc0) with Angular 5 material (5.0.0-rc0) and for the life of me I can not debug while every single angular 5 material directive is coming up with

mat-xyz is not a known element

Here is what my app.module looks like

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { Component } from '@angular/core';
// Import the Http Module and our Data Service
import { DataService } from './data.service';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import 'hammerjs';

import {
  MatAutocompleteModule,
  ...
  MatStepperModule
} from '@angular/material';
import { HttpModule } from '@angular/http';
import { CdkTableModule } from '@angular/cdk/table';
import { LandingComponent } from './sandbox/landing/landing.component';

@NgModule({
  declarations: [
    AppComponent,
    LandingComponent
  ],
  imports: [
    BrowserModule,
    HttpModule
  ],
  exports: [
    CdkTableModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  providers: [DataService],
  bootstrap: [AppComponent]
})
export class AppModule { }

The Landing component has HTML like so

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input matInput placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>

and it's .ts is the following

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }

}

I know its probably something small or stupid, but for the life of me I can not find it

Thanks in advance!

Body:
Move them to the imports. You currently have them in exports:

imports: [
    BrowserModule,
    HttpModule,
    MatAutocompleteModule,
    ...
    MatTooltipModule,
  ],
  exports: [
    CdkTableModule
  ],


问:
Partitioning an arraylist into Map buckets
I have two ArrayLists of type String ArrayList<String> xList and ArrayList<String> yList and I want to partition one list into buckets, according to someAttribute (for the below example lets say it uses .contains().

```<code>   Map<String, List<String>> yBuckets = new HashMap<>();
             yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
                     (v == null ? new ArrayList<>() : v).add(y)));
</code>```

However I'm getting an incompatible types error (String can't be converted to Boolean). I've never really used Java 8 to date but it seems to be useful for what I want so I'm wondering if anyone would be able to tell me how i'd go about fixing this code.
Thanks

答:
If you want to use lambda, you could use one of the toMap Collectors:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#mapping-java.util.function.Function-java.util.stream.Collector-

For Example, partitioning a list of names into buckets by last name:

```<code>    List<String> names = Arrays.asList("Steve Ray", "Bobby Ray", "Billy Bob", "Timmy Bob");
    Map<String, List<String>> nameBuckets = names.stream().collect(
            Collectors.groupingBy(str -> {return str.split(" ")[1];}, Collectors.toList()));
</code>```

Body:
I have two ArrayLists of type String ArrayList<String> xList and ArrayList<String> yList and I want to partition one list into buckets, according to someAttribute (for the below example lets say it uses .contains().

   Map<String, List<String>> yBuckets = new HashMap<>();
             yList.forEach(y -> yBuckets.compute(y.contains("I'm here"), (k,v) ->
                     (v == null ? new ArrayList<>() : v).add(y)));

However I'm getting an incompatible types error (String can't be converted to Boolean). I've never really used Java 8 to date but it seems to be useful for what I want so I'm wondering if anyone would be able to tell me how i'd go about fixing this code.
Thanks

Body:
If you want to use lambda, you could use one of the toMap Collectors:

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#mapping-java.util.function.Function-java.util.stream.Collector-

For Example, partitioning a list of names into buckets by last name:

    List<String> names = Arrays.asList("Steve Ray", "Bobby Ray", "Billy Bob", "Timmy Bob");
    Map<String, List<String>> nameBuckets = names.stream().collect(
            Collectors.groupingBy(str -> {return str.split(" ")[1];}, Collectors.toList()));


问:
JavaScript numbers to Words
I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".

My Tactic goes like this:

Separate the digits to three and put them on Array (finlOutPut), from right to left.

Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter
        }
    }

        //convert The output Arry to , more printable string
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}   ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/
    onkeydown="return (event.ctrlKey || event.altKey
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9)
                    || (event.keyCode>34 && event.keyCode<40)
                    || (event.keyCode==46) )"/>
                    <br/>
<div id="container">Here The Numbers Printed</div></code>```

答:
This is a simple ES6+ number to words function. You can simply add 'illions' array to extend digits. American English version.
 (no 'and' before the end)</p>

```<code>// generic number to words

let digits  = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties    = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()

let join = (a, s) => a.filter(v => v).join(s || ' ')

let tens = s =>
    digits[s] ||
    join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one

let hundreds = s =>
    join(
        (s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
            .concat( tens(s.substr(1,2)) )  )

let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'

let numberToWords = n =>
    // to filter non number or '', null, undefined, false, NaN
    isNaN(Number(n)) || !n && n !== 0
        ? 'not a number'
        : Number(n) === 0
            ? 'zero'
            : Number(n) >= 10 ** (illions.length * 3)
                ? 'too big'
                : String(n)
                    .padStart(illions.length * 3, '0')
                    .match(new RegExp(re))
                    .slice(1, illions.length + 1)
                    .reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')

// just for this question.

let update = () => {
    let value = document.getElementById('number').value
    document.getElementById('container').innerHTML = numberToWords(value)
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: JavaScript numbers to Words

Body:
I'm trying to convert numbers into english words, for example 1234 would become: "one thousand two hundred thirty four".

My Tactic goes like this:

Separate the digits to three and put them on Array (finlOutPut), from right to left.

Convert each group (each cell in the finlOutPut array) of three digits to a word (this what the triConvert function does). If all the three digits are zero convert them to "dontAddBigSuffix"

From Right to left, add thousand, million, billion, etc. If the finlOutPut cell equals "dontAddBigSufix" (because it was only zeroes), don't add the word and set the cell to " " (nothing).

It seems to work pretty well, but I've got some problems with numbers like 190000009, converted to: "one hundred ninety million". Somehow it "forgets" the last numbers when there are a few zeros.

What did I do wrong? Where is the bug? Why does it not work perfectly?

function update(){
    var bigNumArry = new Array('', ' thousand', ' million', ' billion', ' trillion', ' quadrillion', ' quintillion');

    var output = '';
    var numString =   document.getElementById('number').value;
    var finlOutPut = new Array();

    if (numString == '0') {
        document.getElementById('container').innerHTML = 'Zero';
        return;
    }

    if (numString == 0) {
        document.getElementById('container').innerHTML = 'messeg tell to enter numbers';
        return;
    }

    var i = numString.length;
    i = i - 1;

    //cut the number to grups of three digits and add them to the Arry
    while (numString.length > 3) {
        var triDig = new Array(3);
        triDig[2] = numString.charAt(numString.length - 1);
        triDig[1] = numString.charAt(numString.length - 2);
        triDig[0] = numString.charAt(numString.length - 3);

        var varToAdd = triDig[0] + triDig[1] + triDig[2];
        finlOutPut.push(varToAdd);
        i--;
        numString = numString.substring(0, numString.length - 3);
    }
    finlOutPut.push(numString);
    finlOutPut.reverse();

    //conver each grup of three digits to english word
    //if all digits are zero the triConvert
    //function return the string "dontAddBigSufix"
    for (j = 0; j < finlOutPut.length; j++) {
        finlOutPut[j] = triConvert(parseInt(finlOutPut[j]));
    }

    var bigScalCntr = 0; //this int mark the million billion trillion... Arry

    for (b = finlOutPut.length - 1; b >= 0; b--) {
        if (finlOutPut[b] != "dontAddBigSufix") {
            finlOutPut[b] = finlOutPut[b] + bigNumArry[bigScalCntr] + ' , ';
            bigScalCntr++;
        }
        else {
            //replace the string at finlOP[b] from "dontAddBigSufix" to empty String.
            finlOutPut[b] = ' ';
            bigScalCntr++; //advance the counter
        }
    }

        //convert The output Arry to , more printable string
        for(n = 0; n<finlOutPut.length; n++){
            output +=finlOutPut[n];
        }

    document.getElementById('container').innerHTML = output;//print the output
}

//simple function to convert from numbers to words from 1 to 999
function triConvert(num){
    var ones = new Array('', ' one', ' two', ' three', ' four', ' five', ' six', ' seven', ' eight', ' nine', ' ten', ' eleven', ' twelve', ' thirteen', ' fourteen', ' fifteen', ' sixteen', ' seventeen', ' eighteen', ' nineteen');
    var tens = new Array('', '', ' twenty', ' thirty', ' forty', ' fifty', ' sixty', ' seventy', ' eighty', ' ninety');
    var hundred = ' hundred';
    var output = '';
    var numString = num.toString();

    if (num == 0) {
        return 'dontAddBigSufix';
    }
    //the case of 10, 11, 12 ,13, .... 19
    if (num < 20) {
        output = ones[num];
        return output;
    }

    //100 and more
    if (numString.length == 3) {
        output = ones[parseInt(numString.charAt(0))] + hundred;
        output += tens[parseInt(numString.charAt(1))];
        output += ones[parseInt(numString.charAt(2))];
        return output;
    }

    output += tens[parseInt(numString.charAt(0))];
    output += ones[parseInt(numString.charAt(1))];

    return output;
}

<input type="text"
    id="number"
    size="70"
    onkeyup="update();"
    /*this code prevent non numeric letters*/
    onkeydown="return (event.ctrlKey || event.altKey
                    || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)
                    || (95<event.keyCode && event.keyCode<106)
                    || (event.keyCode==8) || (event.keyCode==9)
                    || (event.keyCode>34 && event.keyCode<40)
                    || (event.keyCode==46) )"/>

Here The Numbers Printed

Body:
This is a simple ES6+ number to words function. You can simply add 'illions' array to extend digits. American English version.
 (no 'and' before the end)

// generic number to words

let digits  = ['','one','two','three','four', 'five','six','seven','eight','nine','ten','eleven','twelve','thirteen','fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'];
let ties    = ['', '', 'twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];
let illions = ['', 'thousand', 'million', 'billion', 'trillion'].reverse()

let join = (a, s) => a.filter(v => v).join(s || ' ')

let tens = s =>
    digits[s] ||
    join([ties[s[0]], digits[s[1]]], '-') // 21 -> twenty-one

let hundreds = s =>
    join(
        (s[0] !== '0' ? [digits[s[0]], 'hundred'] : [])
            .concat( tens(s.substr(1,2)) )  )

let re = '^' + '(\\d{3})'.repeat(illions.length) + '$'

let numberToWords = n =>
    // to filter non number or '', null, undefined, false, NaN
    isNaN(Number(n)) || !n && n !== 0
        ? 'not a number'
        : Number(n) === 0
            ? 'zero'
            : Number(n) >= 10 ** (illions.length * 3)
                ? 'too big'
                : String(n)
                    .padStart(illions.length * 3, '0')
                    .match(new RegExp(re))
                    .slice(1, illions.length + 1)
                    .reduce( (a, v, i) => v === '000' ? a : join([a, hundreds(v), illions[i]]), '')

// just for this question.

let update = () => {
    let value = document.getElementById('number').value
    document.getElementById('container').innerHTML = numberToWords(value)
}


答:
No. The http:// and https:// wrappers only support read operations:

Description: Allows read-only access to files/resources via HTTP 1.0, using the HTTP GET method.

While the wrappers could conceivably implement write operations via the PUT method, most web applications do not implement that method, so it wouldn't do anything useful.

Title: Can I file_put_contents to send to an http web address?


答:
For the example that you provided there is Collectors.partitioningBy but this will partition in two parts only - based on a Predicate.

```<code>yList.stream()
            .collect(Collectors.partitioningBy(y -> y.contains("I'm here")));
</code>```

As such that is going to be a result in the form of Map<Boolean, List<String>>.

If you have more groups, you would want to use Collectors.groupingBy that will partition your List base on a Function

Title: Partitioning an arraylist into Map buckets

Body:
For the example that you provided there is Collectors.partitioningBy but this will partition in two parts only - based on a Predicate.

yList.stream()
            .collect(Collectors.partitioningBy(y -> y.contains("I'm here")));

As such that is going to be a result in the form of Map<Boolean, List<String>>.

If you have more groups, you would want to use Collectors.groupingBy that will partition your List base on a Function


问:
Scale values of a particular column of python dataframe between 1-10
I have a dataframe which contains youtube videos views, I want to scale these values in the range of 1-10.
Below is the sample of how values look like? How do i normalize it in the range of 1-10 or is there any more efficient way to do this thing?</p>

```<code>rating
4394029
274358
473691
282858
703750
255967
3298456
136643
796896
2932
220661
48688
4661584
2526119
332176
7189818
322896
188162
157437
1153128
788310
1307902
</code>```

Body:
I have a dataframe which contains youtube videos views, I want to scale these values in the range of 1-10.
Below is the sample of how values look like? How do i normalize it in the range of 1-10 or is there any more efficient way to do this thing?

rating
4394029
274358
473691
282858
703750
255967
3298456
136643
796896
2932
220661
48688
4661584
2526119
332176
7189818
322896
188162
157437
1153128
788310
1307902

Body:
One possibility is performing a scaling with max.

1 + df / df.max() * 9

       rating
0    6.500315
1    1.343433
2    1.592952
3    1.354073
4    1.880933
5    1.320412
6    5.128909
7    1.171046
8    1.997531
9    1.003670
10   1.276217
11   1.060946
12   6.835232
13   4.162121
14   1.415808
15  10.000000
16   1.404192
17   1.235536
18   1.197075
19   2.443451
20   1.986783
21   2.637193

Similar solution by Wen (now deleted):

1 + (df - df.min()) * 9 / (df.max() - df.min())

       rating
0    6.498887
1    1.339902
2    1.589522
3    1.350546
4    1.877621
5    1.316871
6    5.126922
7    1.167444
8    1.994266
9    1.000000
10   1.272658
11   1.057299
12   6.833941
13   4.159739
14   1.412306
15  10.000000
16   1.400685
17   1.231960
18   1.193484
19   2.440368
20   1.983514
21   2.634189


问:
Where can I find UX documentation for Xamarin's TableView Intent?
The Xamarin TableView has an Intent property that allows me to define between

Data

Form

Menu

Settings

However it's not clear what the UX difference will be on each platform.

Is there any elaboration for this enumeration?

答:
It's found at https://developer.xamarin.com/api/type/Xamarin.Forms.TableIntent/

Data    A table intended to contain an arbitrary number of similar data entries.

Form    A table which is used to contain information that would normally be contained in a form.

Menu    A table intended to be used as a menu for selections.

Settings    A table containing a set of switches, toggles, or other modifiable configuration settings.

As for specifically showing the difference between them on platforms visually, I think you'd just have to play around with them and see. Xamarin Forms Previewer does a great job at this without having to re-deploy your project to a simulator or device. (View - Other Windows - Xamarin Forms Previewer)


问:
MDB starts to consume messages before fully initialization of JNDI names
AS: Websphere 8.5.5

MQ impl: SIB

During application startup MDB starts to invoke onMessage method, which in turn invokes initialContext.lookup in order to find specific bean.
Sometimes (during variety of startup iterations) it returns null instead of reference to bean object.

This behavior is nondeterministic: in some startup iterations bean's context has time for all JNDI names initialization due to more longer MDB initialization and respectively a pause in message consumption.

Is there any workaround or magic IBM key to resolve issue ?

答:
So, as everyone "love's" Websphere, it was without a doubt an IBM bug. Sorry, i lied.... it was TWO bugs at the same time.

First :
http://www-01.ibm.com/support/docview.wss?uid=swg1PI28099.
Yep, you need to fix this bug yourself !!!
Just add this jvm custom property to your server:
com.ibm.ejs.j2c.J2CServerListener.activateEndpointsOnCRAStarted = true

Second:
http://www-01.ibm.com/support/docview.wss?uid=swg1PM62774
Yep, this one you need to fix ... drumroll  ... by yourself too !!!
Just add the second custom property to your server:
com.ibm.ws.cdi.immediate.ejb.start = true


问:
std::conditional_variable::wait_for, std::thread::sleep_for on Windows are affected by adjusting clock
Well. I have Win10 x64 and this pretty simple code:

```<code>int main() {
    std::conditional_variable cv;
    std::mutex m;
    std::unique_lock<std::mutex> lock(m);
    while(1) {
        cv.wait_for(lock, 1000ms, [](){return false;});
        std::cout << "!" << std::endl;
    }
}
</code>```

Yes. The code works just like I expect; It shows '!' every second.
But If I change my local time (minus 1 hour/minute e.g.) it holds forever.
If I replace cv.wait_for(...) with WinAPI Sleep(1000) it works fine. Also WinAPI SleepConditionVariableCS works fine.

I have tried this:

```<code>cv.wait_until(lock, std::chrono::steady_clock::now() + 1000ms, [](){return false;});
</code>```

And it gives me the same result.

BTW: The behavior of the calls like std::this_thread::sleep_for, std::this_thread::sleep_until is the same.

So the question is: Is it possible to use std::condition_variable with expected behavior? Or I just have to replace it with my own CONDITION_VARIABLE wrapper?

答:
This was a known bug with VS2015's condition_variable which unfortunately is ABI-breaking to fix. I fixed it in our next major release (I completely rewrote the condition variable implementation from scratch), but I don't know when that will happen next. Note that VS2017 was a minor release as far as the standard libraries are concerned.

The problem is that the API contract exposed by msvcp140.dll expects an absolute time against the system clock, so if the system clock changes the effective wait length changes. The standard permits implementing an unsteady clock out of a steady clock but not the reverse; my predecessors apparently didn't get that memo :)

Body:
Well. I have Win10 x64 and this pretty simple code:

int main() {
    std::conditional_variable cv;
    std::mutex m;
    std::unique_lock<std::mutex> lock(m);
    while(1) {
        cv.wait_for(lock, 1000ms, [](){return false;});
        std::cout << "!" << std::endl;
    }
}

Yes. The code works just like I expect; It shows '!' every second.
But If I change my local time (minus 1 hour/minute e.g.) it holds forever.
If I replace cv.wait_for(...) with WinAPI Sleep(1000) it works fine. Also WinAPI SleepConditionVariableCS works fine.

I have tried this:

cv.wait_until(lock, std::chrono::steady_clock::now() + 1000ms, [](){return false;});

And it gives me the same result.

BTW: The behavior of the calls like std::this_thread::sleep_for, std::this_thread::sleep_until is the same.

So the question is: Is it possible to use std::condition_variable with expected behavior? Or I just have to replace it with my own CONDITION_VARIABLE wrapper?


问:
How to use x:Object and when?
When passing arguments by the markup extension x:Arguments to non default constructors as specified by the docs, I can see the use of concrete data types such as x:Int32 or x:String, but what's the use case of x:Object? And what's more, to use it, what should be put between the tag? <x:Object> ??? </x:Object>

In the case of integer or string, it is natural to think them as an variable assignment and the variables then get passed to the constructors. But in the case of Object, such an variable normally is constructed by another user defined class, so how to specify what class you want to create?

答:
Data Templates that define their data type as x:Object are excellent fallback data templates when dealing with data of an unsupported type.

Lets say you have a screen that shows up and informs the user that if the data they import is unsupported, they will see the result as follows: and then you show the data template for x:Object. An easy way to do this would be like this:

```<code><ContentControl>
  <ContentControl.Content>
    <x:Object/>
  </ContentControl.Content>
</ContentControl>
</code>```

so that the most specific data template available is the x:Object one, and that is what is shown.

the Object class contains no meaningful data, so there is not really any reason to write

```<code><x:Object></x:Object>
</code>```

because there is no content for the type.

Title: How to use x:Object and when?

Body:
Data Templates that define their data type as x:Object are excellent fallback data templates when dealing with data of an unsupported type.

Lets say you have a screen that shows up and informs the user that if the data they import is unsupported, they will see the result as follows: and then you show the data template for x:Object. An easy way to do this would be like this:

<ContentControl>
  <ContentControl.Content>
    <x:Object/>
  </ContentControl.Content>
</ContentControl>

so that the most specific data template available is the x:Object one, and that is what is shown.

the Object class contains no meaningful data, so there is not really any reason to write

<x:Object></x:Object>

because there is no content for the type.


问:
Print external HTML file with Javascript
I have a "print" button on index.html. What code do I need to print the print.html file? I mean, when I press the button from index.html, print the page print.html.

答:
function closePrint () {
  document.body.removeChild(this.__container__);
}

function setPrint () {
  this.contentWindow.__container__ = this;
  this.contentWindow.onbeforeunload = closePrint;
  this.contentWindow.onafterprint = closePrint;
  this.contentWindow.focus(); // Required for IE
  this.contentWindow.print();
}

function printPage (sURL) {
  var oHiddFrame = document.createElement("iframe");
  oHiddFrame.onload = setPrint;
  oHiddFrame.style.visibility = "hidden";
  oHiddFrame.style.position = "fixed";
  oHiddFrame.style.right = "0";
  oHiddFrame.style.bottom = "0";
  oHiddFrame.src = sURL;
  document.body.appendChild(oHiddFrame);
}
```

<p>Then use </p>

<pre class="lang-html prettyprint-override"><code>onclick="printPage('print_url');"
</code>```

Body:
function closePrint () {
  document.body.removeChild(this.__container__);
}

function setPrint () {
  this.contentWindow.__container__ = this;
  this.contentWindow.onbeforeunload = closePrint;
  this.contentWindow.onafterprint = closePrint;
  this.contentWindow.focus(); // Required for IE
  this.contentWindow.print();
}

function printPage (sURL) {
  var oHiddFrame = document.createElement("iframe");
  oHiddFrame.onload = setPrint;
  oHiddFrame.style.visibility = "hidden";
  oHiddFrame.style.position = "fixed";
  oHiddFrame.style.right = "0";
  oHiddFrame.style.bottom = "0";
  oHiddFrame.src = sURL;
  document.body.appendChild(oHiddFrame);
}

Then use

onclick="printPage('print_url');"


问:
How to prevent duplicating DB insertions when refreshing?
I am very new to PHP. I've tried to find an answer here that will fit my code, but I didn't find any.

When I press F5, the last insertion from the form duplicates itself in the database. How do I prevent it without redirecting to another page?

I saw a few answers about $_SESSION, but I did not understand how to use it.
I would love to have some explanation with the correction code, thank you.

PS, the db connection is in another file, if you need it to answer me, I'll put it.

Here's my code:

addToMembersList.php

```<code><DOCTYPE html5>
<html>
  <head>
    <?php
      include_once "db_connect.php";

      $member=mysqli_query($mysqli,"select * from members");
    ?>
    <style>
      table,tr,td{
        border: 1px solid black;
        border-collapse: collapse;
      }
    </style>
  </head>
  <body>
    <table>
      <tr>
        <td><b>First name</b></td>
        <td><b>Last name</b></td>
        <td><b>Email</b></td>
        <td><b>Website</b></td>
        <td><b>Comment</b></td>
        <td><b>Gender</b></td>
      </tr>
      <?php
        if($member){
          while($row = $member->fetch_assoc()){ ?>
            <tr>
              <td><?php echo $row['first_name'];?></td>
              <td><?php echo $row['last_name'];?></td>
              <td><?php echo $row['email'];?></td>
              <td><?php echo '<a href="'.$row['website'].'">'.$row['website'].'</a>';?></td>
              <td><?php echo $row['comment'];?></td>
              <td><?php echo $row['gender'];?></td>
              <td><button type="submit" onclick="deleteMember.php" value="$row['id']">Delete</button></td>
            </tr>
          <?php }
        }?>
    </table>
  </body>
</html>

$query = "insert into members (first_name, last_name, email, website, comment, gender) values ('%s', '%s', '%s', '%s', '%s', '%s')";
      $query = sprintf($query,$_POST['fName'], $_POST['lName'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST[$gender_select]);
      $result = $mysqli ->query($query);
    }
  }

?>
</code>```

index.php

```<code><DOCTYPE html5>
<html>
  <head>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script>
      function loadmembersList(response,textStatus,jqXHR){
        request = $.ajax({
        url:"memberListRequest.php",
        type:"get"
        })
        request.done(function(response,textStatus,jqXHR){
          $("#member_list").html(response);
        });
      }
      $( document ).ready(loadmembersList);
    </script>
  </head>
  <body>
    <form action="", method="POST">
      First name:<input type="text" name="fName">
      <br>
      Last name:<input type="text" name="lName">
      <br>
      Email:<input type="text" name="email">
      <br>
      Website:<input type="text" name="website">
      <br>
      Comment:<input type="textarea" name="comment" placeholder="your text here">
      <br>
      Gender:<input type="radio" name="Male"> Male <input type="radio"
name="Female"> Female <input type="radio" name="Other"> Other
      <br>
      <input type="submit">
    </form>
    <div id="member_list"></div>
  </body>
</html>
</code>```

答:
The common solution is to use a post-redirect-get pattern. The form collecting data from the user posts to a script which does the db operation then responds with a 302 redirect to a page which shows the outcome. The downside of this is that it requires at least 2 consecutive round trips to the server to navigate to the next page.

As others have noted, your code is subject to sql injection, but given the behaviour you describe, it is also vulnerable to cross site request forgery. A csrf token could be used to detect duplicate submissions.

Setting a suitable primary key /unique index and ignoring duplicate submissions would prevent duplicate records being created.

It is also possible to set a flag inside the form when the users hits the submit button using javascript. Then only carry out the insert if the flag is set in the parameters - but don't forget to plan for cases where javascript is disabled.

Another solution would be to send the data serverside in an ajax request rather than as a page navigation event.

There are probably more solutions.

Body:
I am very new to PHP. I've tried to find an answer here that will fit my code, but I didn't find any.

When I press F5, the last insertion from the form duplicates itself in the database. How do I prevent it without redirecting to another page?

I saw a few answers about $_SESSION, but I did not understand how to use it.
I would love to have some explanation with the correction code, thank you.

PS, the db connection is in another file, if you need it to answer me, I'll put it.

Here's my code:

addToMembersList.php

<DOCTYPE html5>

    <?php
      include_once "db_connect.php";

      $member=mysqli_query($mysqli,"select * from members");
    ?>

        First name
        Last name
        Email
        Website
        Comment
        Gender

      <?php
        if($member){
          while($row = $member->fetch_assoc()){ ?>

              <?php echo $row['first_name'];?>
              <?php echo $row['last_name'];?>
              <?php echo $row['email'];?>
              <?php echo ''.$row['website'].'';?>
              <?php echo $row['comment'];?>
              <?php echo $row['gender'];?>
              <button type="submit" onclick="deleteMember.php" value="$row['id']">Delete</button>

          <?php }
        }?>

$query = "insert into members (first_name, last_name, email, website, comment, gender) values ('%s', '%s', '%s', '%s', '%s', '%s')";
      $query = sprintf($query,$_POST['fName'], $_POST['lName'], $_POST['email'], $_POST['website'], $_POST['comment'], $_POST[$gender_select]);
      $result = $mysqli ->query($query);
    }
  }

?>

index.php

<DOCTYPE html5>

    <form action="", method="POST">
      First name:<input type="text" name="fName">

      Last name:<input type="text" name="lName">

      Email:<input type="text" name="email">

      Website:<input type="text" name="website">

      Comment:<input type="textarea" name="comment" placeholder="your text here">

      Gender:<input type="radio" name="Male"> Male <input type="radio"
name="Female"> Female <input type="radio" name="Other"> Other

      <input type="submit">
    </form>


问:
Queryset in Django if empty field returns all elements
I want to do a filter in Django that uses form method.
If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements.

How can I do that?

I am new in Django

```<code>if request.GET.get('Var'):
    Var = request.GET.get('Var')
else:
    Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW

models.objects.filter(Var=Var)
</code>```

答:
It's not a great idea from a security standpoint to allow users to input data directly into search terms (and should DEFINITELY not be done for raw SQL queries if you're using any of those.)

With that note in mind, you can take advantage of more dynamic filter creation using a dictionary syntax, or revise the queryset as it goes along:

Option 1: Dictionary Syntax

```<code>def my_view(request):
  query = {}
  if request.GET.get('Var'):
     query['Var'] = request.GET.get('Var')
  if request.GET.get('OtherVar'):
    query['OtherVar'] = request.GET.get('OtherVar')
  if request.GET.get('thirdVar'):
    # Say you wanted to add in some further processing
    thirdVar = request.GET.get('thirdVar')
    if int(thirdVar) > 10:
       query['thirdVar'] = 10
    else:
       query['thirdVar'] = int(thirdVar)
  if request.GET.get('lessthan'):
    lessthan = request.GET.get('lessthan')
    query['fieldname__lte'] = int(lessthan)
  results = MyModel.objects.filter(**query)
</code>```

If nothing has been added to the query dictionary and it's empty, that'll be the equivalent of doing MyModel.objects.all()

My security note from above applies if you wanted to try to do something like this (which would be a bad idea):

```<code>MyModel.objects.filter(**request.GET)
</code>```

Django has a good security track record, but this is less safe than anticipating the types of queries that your users will have. This could also be a huge issue if your schema is known to a malicious site user who could adapt their query syntax to make a heavy query along non-indexed fields.

Option 2: Revising the Queryset
Alternatively, you can start off with a queryset for everything and then filter accordingly

```<code>def my_view(request):
  results = MyModel.objects.all()
  if request.GET.get('Var'):
     results = results.filter(Var=request.GET.get('Var'))
  if request.GET.get('OtherVar'):
    results = results.filter(OtherVar=request.GET.get('OtherVar'))
  return results
</code>```

Body:
I want to do a filter in Django that uses form method.
If the user type de var it should query in the dataset that var, if it is left in blank to should bring all the elements.

How can I do that?

I am new in Django

if request.GET.get('Var'):
    Var = request.GET.get('Var')
else:
    Var = WHAT SHOULD I PUT HERE TO FILTER ALL THE ELEMNTS IN THE CODE BELLOW

models.objects.filter(Var=Var)

Body:
It's not a great idea from a security standpoint to allow users to input data directly into search terms (and should DEFINITELY not be done for raw SQL queries if you're using any of those.)

With that note in mind, you can take advantage of more dynamic filter creation using a dictionary syntax, or revise the queryset as it goes along:

Option 1: Dictionary Syntax

def my_view(request):
  query = {}
  if request.GET.get('Var'):
     query['Var'] = request.GET.get('Var')
  if request.GET.get('OtherVar'):
    query['OtherVar'] = request.GET.get('OtherVar')
  if request.GET.get('thirdVar'):
    # Say you wanted to add in some further processing
    thirdVar = request.GET.get('thirdVar')
    if int(thirdVar) > 10:
       query['thirdVar'] = 10
    else:
       query['thirdVar'] = int(thirdVar)
  if request.GET.get('lessthan'):
    lessthan = request.GET.get('lessthan')
    query['fieldname__lte'] = int(lessthan)
  results = MyModel.objects.filter(**query)

If nothing has been added to the query dictionary and it's empty, that'll be the equivalent of doing MyModel.objects.all()

My security note from above applies if you wanted to try to do something like this (which would be a bad idea):

MyModel.objects.filter(**request.GET)

Django has a good security track record, but this is less safe than anticipating the types of queries that your users will have. This could also be a huge issue if your schema is known to a malicious site user who could adapt their query syntax to make a heavy query along non-indexed fields.

Option 2: Revising the Queryset
Alternatively, you can start off with a queryset for everything and then filter accordingly

def my_view(request):
  results = MyModel.objects.all()
  if request.GET.get('Var'):
     results = results.filter(Var=request.GET.get('Var'))
  if request.GET.get('OtherVar'):
    results = results.filter(OtherVar=request.GET.get('OtherVar'))
  return results


问:
Incomplete final line found error when reading url using readLines() in R
I am trying to read the html content of a url using the readLines() function in R. However, I am getting a "incomplete final line found" warning message as shown below? How can I skip the final line in such a case? Any suggestions would be very much appreciated.

```<code>x <- readLines("https://in.finance.yahoo.com/industries/technology")

Warning message:
In readLines("https://in.finance.yahoo.com/industries/technology") :
  incomplete final line found on 'https://in.finance.yahoo.com/industries/technology'
</code>```

答:
Most files are missing an End of Line marker like a new line below, so I would just use warn=FALSE.   </p>

```<code>cat("abc\ndef\nhij", file="test.txt")
readLines( "test.txt")
# [1] "abc" "def" "hij"
# Warning message:
# In readLines("test.txt") : incomplete final line found on 'test.txt'
readLines( "test.txt", warn=FALSE)
# [1] "abc" "def" "hij"
</code>```

Body:
I am trying to read the html content of a url using the readLines() function in R. However, I am getting a "incomplete final line found" warning message as shown below? How can I skip the final line in such a case? Any suggestions would be very much appreciated.

x <- readLines("https://in.finance.yahoo.com/industries/technology")

Warning message:
In readLines("https://in.finance.yahoo.com/industries/technology") :
  incomplete final line found on 'https://in.finance.yahoo.com/industries/technology'

Body:
Most files are missing an End of Line marker like a new line below, so I would just use warn=FALSE.

cat("abc\ndef\nhij", file="test.txt")
readLines( "test.txt")
# [1] "abc" "def" "hij"
# Warning message:
# In readLines("test.txt") : incomplete final line found on 'test.txt'
readLines( "test.txt", warn=FALSE)
# [1] "abc" "def" "hij"


问:
Codeigniter Xero api Library to add Purchase orders
I am using https://github.com/dharyk/codeigniter-xero to integrate Xero to my website. It is very helpful when adding invoices to Xero or adding a contact.

But it cannot add Purchase orders.
I am using
$this->xero->PurchaseOrders($new_po); to add a purchase order. But its giving me the following error:

An uncaught Exception was encountered

Type: XeroException

Message: The selected method does not exist. Please use one of the
  following methods: Accounts, BankTransactions, BrandingThemes,
  Contacts, CreditNotes, Currencies, Employees, ExpenseClaims, Invoices,
  Items, Journals, ManualJournals, Organisation, Payments, Receipts,
  TaxRates, TrackingCategories, Users

Filename:
  /home/path-to-files/application/libraries/Xero.php

Line Number: 167

I think its because this library was written long back and purchase orders came later(just thinking).

Is there any way so that I can add Purchase order method to this library?

Any other suggestions are also welcomed.

Thanks

答: The code is open source so you can do the work yourself. The last commit to that SDK was 4 years ago however so it's probably no longer maintained (purchase orders released maybe 2+ years ago). If you don't want to move away from that SDK to another one that's maintained, you should fork the repository and add the new functionality to your fork. I wouldn't think the original maintainer will be accepting pull requests if the repo is dead but you could always open one once you've got the new functionality you want in there anyway. </p>