问:
'No such token' error upon submitting payment request to Stripe
I'm setting up payments using the Stripe API to allow a user to log into their Stripe account on an iPad and accept payments from anyone. To do this, I'm using Stripe Connect to log them in and save their account id, then I'm using the STPPaymentCardTextField to obtain credit card details, then using the Stripe iOS SDK I'm submitting a card (with the test card info - 4242...) and getting back a token via createTokenWithCard. This successfully returns a token. At this point I need to submit that token along with the destination account id (provided to the app after the user logged in) and other info (currency, amount, etc) to my own server to submit the payment to Stripe. I have verified that information is being submitted and forwarded onto Stripe, but Stripe is returning an error:

```<code>{ type: 'invalid_request_error',
app[web.1]:      message: 'No such token: tok_13vxes2eZkKYli2C9bHY1YfX',
app[web.1]:      param: 'source',
app[web.1]:      statusCode: 400,
app[web.1]:      requestId: 'req_7AIT8cEasnzEaq' },
app[web.1]:   requestId: 'req_7AIT8cEasnzEaq',
app[web.1]:   statusCode: 400 }
</code>```

If we submit the credit card info directly, avoiding the token altogether, the payment succeeds. Something is wrong with this token, and we are not sure why it is failing. What could be going wrong here?

```<code>[[STPAPIClient sharedClient] createTokenWithCard:card completion:^(STPToken *token, NSError *error) {
    //submit tokenId and other info to 'charge' endpoint below
}
</code>```

NodeJS:

```<code>app.post('/charge', (req, res, next) => {
  stripe.charges.create({
    amount: req.body.amount,
    currency: req.body.currency,
    source: req.body.token,
    description: req.body.description,
    destination: req.body.destination
  }, (err, charge) => {
    if (err) return next(err)
    res.json(charge)
  })
})
</code>```

答:
The accepted answer does not work for me. I am using correct key for client and server, but still the issue is still there. I am sending source from iOS to the server as well, based on stripe example RocketRides, it is sending source ID of the credit card, which is "card_xxx", and that is not gonna work. You will have to add "customer" attribute for the call on your server side.

For example: (python)

```<code>stripe.Charge.create(amount=1000, currency='usd', source="card_xxxxx", **customer**='cus_xxxx', application_fee=600,destination={'account': 'acct_xxxx'})
</code>```

Body:
I'm setting up payments using the Stripe API to allow a user to log into their Stripe account on an iPad and accept payments from anyone. To do this, I'm using Stripe Connect to log them in and save their account id, then I'm using the STPPaymentCardTextField to obtain credit card details, then using the Stripe iOS SDK I'm submitting a card (with the test card info - 4242...) and getting back a token via createTokenWithCard. This successfully returns a token. At this point I need to submit that token along with the destination account id (provided to the app after the user logged in) and other info (currency, amount, etc) to my own server to submit the payment to Stripe. I have verified that information is being submitted and forwarded onto Stripe, but Stripe is returning an error:

{ type: 'invalid_request_error',
app[web.1]:      message: 'No such token: tok_13vxes2eZkKYli2C9bHY1YfX',
app[web.1]:      param: 'source',
app[web.1]:      statusCode: 400,
app[web.1]:      requestId: 'req_7AIT8cEasnzEaq' },
app[web.1]:   requestId: 'req_7AIT8cEasnzEaq',
app[web.1]:   statusCode: 400 }

If we submit the credit card info directly, avoiding the token altogether, the payment succeeds. Something is wrong with this token, and we are not sure why it is failing. What could be going wrong here?

[[STPAPIClient sharedClient] createTokenWithCard:card completion:^(STPToken *token, NSError *error) {
    //submit tokenId and other info to 'charge' endpoint below
}

NodeJS:

app.post('/charge', (req, res, next) => {
  stripe.charges.create({
    amount: req.body.amount,
    currency: req.body.currency,
    source: req.body.token,
    description: req.body.description,
    destination: req.body.destination
  }, (err, charge) => {
    if (err) return next(err)
    res.json(charge)
  })
})

Body:
The accepted answer does not work for me. I am using correct key for client and server, but still the issue is still there. I am sending source from iOS to the server as well, based on stripe example RocketRides, it is sending source ID of the credit card, which is "card_xxx", and that is not gonna work. You will have to add "customer" attribute for the call on your server side.

For example: (python)

stripe.Charge.create(amount=1000, currency='usd', source="card_xxxxx", **customer**='cus_xxxx', application_fee=600,destination={'account': 'acct_xxxx'})


来源: stackexchange

问:
Python OOP: how to use a flag parameter to access methods?
It's unclear to me how one accomplishes this in Python, though I am confused about the fundamentals of OOP:

Let's say I create a Shape class, and use this as an example.

```<code>class Shape:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale
</code>```

In my case, I must create a Class which inputs a file whereby there are only two types, file_typeA and file_typeB. For the user, it would be exceptionally cumbersome to use a Class for Type A and a Class for Type B.

```<code>## use case for an a "read in file name" class `filename`
foo = filename(path = "path/to/file.txt", file_type = "TypeA")
</code>```

My question is, how do I restrict the "Type A" methods for a file initialized with flag file_type="TypeA", and restrict the methods for a file initialized with flag file_type = "TypeB"?

Let's try the Shape class again, whereby the two types are Square and Triangle. The wrong way to code this is something like this:

```<code>class Shape:
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

    if type == "Square":

        def area(self):
            return self.x * self.y

        def perimeter(self):
            return 2 * self.x + 2 * self.y

        def scaleSize(self,scale):
            self.x = self.x * scale
            self.y = self.y * scale

    elif type == "Triangle":

        def hooray(self):
            print("HOORAY! It's hip to be a triangle!")

    else:
        print("'type' must be either Circle or Triangle")

 ## example Class instantiation
 bar = Shape(2, 3, type="Square")
</code>```

For such a class, how do I create it such that the method area cannot be used for a Shape of type=="TypeB"?

答:
That's not how you OOP! OOP helps to eliminate those kinds of conditionals. You should create a Shape base class, then use that to define subclasses for each individual kind of shape. The subclasses should include the methods needed for that kind of shape.

If you want the caller to be able to specify a shape using a string, for example because they are using data from a file or the user, you can write a factory method to do that. You can actually ask Python for the subclasses of your class; no need to list them out! DRY

```<code>class Shape(object):
     __subs = {}

     @classmethod
     def of_type(cls, name, *args, **kwargs):
         """Factory method that instantiates Shape subclasses given their name as a string"""
         lname = name.lower()
         subs = cls._Shape__subs
         if cls is Shape:
             if not subs:        # build subclass dictionary
                 subs.update({c.__name__.lower(): c for c in cls.__subclasses__()})
             if lname in subs:   # instantiate the named subclass
                 return subs[lname](*args, **kwargs)
             raise NameError("invalid shape name: %s" % name)
         raise TypeError("of_type() may be called only on Shape base class")

class Square(Shape):
     pass

class Triangle(Shape):
     pass

# set tri to an instance of type Triangle
tri = Shape.of_type("Triangle")
</code>```

Note that the factory method passes through any arguments given after the name. Class names are case-insensitive.

ContentLicense: CC BY-SA 3.0

Body:
It's unclear to me how one accomplishes this in Python, though I am confused about the fundamentals of OOP:

Let's say I create a Shape class, and use this as an example.

class Shape:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def area(self):
        return self.x * self.y

    def perimeter(self):
        return 2 * self.x + 2 * self.y

    def scaleSize(self,scale):
        self.x = self.x * scale
        self.y = self.y * scale

In my case, I must create a Class which inputs a file whereby there are only two types, file_typeA and file_typeB. For the user, it would be exceptionally cumbersome to use a Class for Type A and a Class for Type B.

## use case for an a "read in file name" class `filename`
foo = filename(path = "path/to/file.txt", file_type = "TypeA")

My question is, how do I restrict the "Type A" methods for a file initialized with flag file_type="TypeA", and restrict the methods for a file initialized with flag file_type = "TypeB"?

Let's try the Shape class again, whereby the two types are Square and Triangle. The wrong way to code this is something like this:

class Shape:
    def __init__(self, x, y, type):
        self.x = x
        self.y = y
        self.type = type

    if type == "Square":

        def area(self):
            return self.x * self.y

        def perimeter(self):
            return 2 * self.x + 2 * self.y

        def scaleSize(self,scale):
            self.x = self.x * scale
            self.y = self.y * scale

    elif type == "Triangle":

        def hooray(self):
            print("HOORAY! It's hip to be a triangle!")

    else:
        print("'type' must be either Circle or Triangle")

 ## example Class instantiation
 bar = Shape(2, 3, type="Square")

For such a class, how do I create it such that the method area cannot be used for a Shape of type=="TypeB"?

Body:
That's not how you OOP! OOP helps to eliminate those kinds of conditionals. You should create a Shape base class, then use that to define subclasses for each individual kind of shape. The subclasses should include the methods needed for that kind of shape.

If you want the caller to be able to specify a shape using a string, for example because they are using data from a file or the user, you can write a factory method to do that. You can actually ask Python for the subclasses of your class; no need to list them out! DRY

class Shape(object):
     __subs = {}

     @classmethod
     def of_type(cls, name, *args, **kwargs):
         """Factory method that instantiates Shape subclasses given their name as a string"""
         lname = name.lower()
         subs = cls._Shape__subs
         if cls is Shape:
             if not subs:        # build subclass dictionary
                 subs.update({c.__name__.lower(): c for c in cls.__subclasses__()})
             if lname in subs:   # instantiate the named subclass
                 return subs[lname](*args, **kwargs)
             raise NameError("invalid shape name: %s" % name)
         raise TypeError("of_type() may be called only on Shape base class")

class Square(Shape):
     pass

class Triangle(Shape):
     pass

# set tri to an instance of type Triangle
tri = Shape.of_type("Triangle")

Note that the factory method passes through any arguments given after the name. Class names are case-insensitive.

ContentLicense: CC BY-SA 4.0


问:
Angular onreadystatechange
Angular newbie here. I was wondering if it's possible to use the $http service to call a function upon any ready state/status change and not only upon success/failure.
In terms of code, it would be the equivalent angular code to the following JS code:

```<code>var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function() {
    if (xhr.readyState < 4 && xhr.status != 200)
        alert('Loading');
}
xhr.open...
xhr.send...
</code>```

答:
Another alternative that I've used successfully is to call $scope.$apply() after what would otherwise be the $http call:</p>

```<code>// using $http
var promise = $http.get(url).then(success, ...);

// without $http
$.ajax({
     url: url,
     success: function() {
         success();
         $scope.$apply(); // if you'd used $http, this would be unnecessary
     },
     ...
});
</code>```

Title: Angular onreadystatechange

Body:
Angular newbie here. I was wondering if it's possible to use the $http service to call a function upon any ready state/status change and not only upon success/failure.
In terms of code, it would be the equivalent angular code to the following JS code:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange=function() {
    if (xhr.readyState < 4 && xhr.status != 200)
        alert('Loading');
}
xhr.open...
xhr.send...

Body:
Another alternative that I've used successfully is to call $scope.$apply() after what would otherwise be the $http call:

// using $http
var promise = $http.get(url).then(success, ...);

// without $http
$.ajax({
     url: url,
     success: function() {
         success();
         $scope.$apply(); // if you'd used $http, this would be unnecessary
     },
     ...
});


问:
p5 resize window without clearing the background
The following code makes use of the p5dom add-on to position the canvas in the centre of the window. To dynamically resize the canvas I'm using the windowResized() function. I want to keep the background function in setup. How do I prevent the background colour from clearing when I resize the window? Many thanks.

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){

}

function windowResized() {
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight)
}
```

答:
Simply by adding the background function to the draw one too.

Try this:

```<code>var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){
  //HERE:
  background(255, 0, 200);
}

function windowResized() {
  //(you can add it here too...)
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight);
}
</code>```

Body:
Simply by adding the background function to the draw one too.

Try this:

var cnv;

function centerCanvas() {
  var x = (windowWidth - width) / 2;
  var y = (windowHeight - height) / 2;
  cnv.position(x, y);
}

function setup() {
  cnv = createCanvas(windowWidth,windowHeight);
  centerCanvas();
  background(255, 0, 200);
}

function draw(){
  //HERE:
  background(255, 0, 200);
}

function windowResized() {
  //(you can add it here too...)
  centerCanvas();
  resizeCanvas(windowWidth,windowHeight);
}


问:
Why does not out-of bound access to an allocatable array cause an error?
I do not understand why this code does not produce any segmentation fault. I was expecting some errors while compiling the code or in run-time, but it runs apparently correctly.

```<code>program alloc

implicit none

real, dimension(:,:), allocatable :: myVec

allocate(myVec(3,2))

myVec=1.

myVec(100,3)=10.

write(*,*) myVec(1,1)

return
end
</code>```

Could somebody shed some light on this behaviour?

答:
With gfortran, you can use the -fbounds-check compiler flag (or -C with ifort) in order to look for this kind of errors. When you compile your example with this option, the program produces:

```<code>Fortran runtime error: Index '3' of dimension 2 of array 'myvec' above upper bound of 2
</code>```

As to why the program does not crash immediately, this question contains more details.

Body:
I do not understand why this code does not produce any segmentation fault. I was expecting some errors while compiling the code or in run-time, but it runs apparently correctly.

program alloc

implicit none

real, dimension(:,:), allocatable :: myVec

allocate(myVec(3,2))

myVec=1.

myVec(100,3)=10.

write(*,*) myVec(1,1)

return
end

Could somebody shed some light on this behaviour?

Body:
With gfortran, you can use the -fbounds-check compiler flag (or -C with ifort) in order to look for this kind of errors. When you compile your example with this option, the program produces:

Fortran runtime error: Index '3' of dimension 2 of array 'myvec' above upper bound of 2

As to why the program does not crash immediately, this question contains more details.


问:
Azure AD Consent from a different Tenant
I am trying to use our multi tenant AD application to access the user's Onedrive for Business. But I keep getting an error when consenting regarding some permissions when the user belongs from a different Tenant. I am not sure which permissions i need to set so that any 365 users can.

I am using the graph API permissions and AD that read the directory. This is what the permissions look like.

Application permissions

Read files in all site collection

Read and write files in all site collections

Read and write devices

Read and Write directory data
-Read directory data

Delegated permissions

Have full access to all files user can access

Read all files that user can access

Have full access to user files

Read user files Access directory as the signed in user

Read and write directory data

Read directory data Sign in and read user profile

Read and write files that the user selects (preview)

Read files that the user selects (preview)

答:
An administrator in the other tenant must consent for the app for the first time.

This is because you are using some scopes that require administrative consent.  If you restrict yourself to only scopes that do not require admin consent, then regular users should normally be able to consent directly to your app.

One thing to note, an administrator in the other tenant can always disable end-user consent in which case they would always require admin consent for every app.


问:
How (and where) to register a custom query method in Laravel
In my application I needed to retrieve the users who were registered in last 7 days. Later I realized I also need to check for 30 days and 365 days and so on. So I wrote a query scope in my User.php:

```<code>public function scopeCreatedWithinDays($query,$day){
    $str = $day.' days ago';
    $carbon = new Carbon($str);
    $query->where('created_at', '>=', $carbon);
}
</code>```

And I suddenly realized that this method is a good candidate for repeated use across all models. So I need to define this method in a common place so that I can easily get the rows created within last x days by simply calling $anyModel->createdWithinDays(30). But I don't know where to put it and how...

答:
There is also the option of macroing a method on the Query Builder:

```<code>\Illuminate\Database\Query\Builder::macro('createdWithinDays', function ($day) {
    return $this->where('created_at', '>=', new \Carbon\Carbon($day .' days ago'));
});
</code>```

Now you should have that method available for any queries involving Query Builder, which includes all Eloquent queries.

No inheritance, no traits, no changes to any models and you have this method to use from DB:: as well.

```<code>AnyModel::createdWithinDays(4)->get();
DB::table('blah')->createdWithinDays(4)->get();
</code>```

Sorry .. the 'and where' part:  Add the macro to a Service Provider boot method.

Body:
In my application I needed to retrieve the users who were registered in last 7 days. Later I realized I also need to check for 30 days and 365 days and so on. So I wrote a query scope in my User.php:

public function scopeCreatedWithinDays($query,$day){
    $str = $day.' days ago';
    $carbon = new Carbon($str);
    $query->where('created_at', '>=', $carbon);
}

And I suddenly realized that this method is a good candidate for repeated use across all models. So I need to define this method in a common place so that I can easily get the rows created within last x days by simply calling $anyModel->createdWithinDays(30). But I don't know where to put it and how...

Body:
There is also the option of macroing a method on the Query Builder:

\Illuminate\Database\Query\Builder::macro('createdWithinDays', function ($day) {
    return $this->where('created_at', '>=', new \Carbon\Carbon($day .' days ago'));
});

Now you should have that method available for any queries involving Query Builder, which includes all Eloquent queries.

No inheritance, no traits, no changes to any models and you have this method to use from DB:: as well.

AnyModel::createdWithinDays(4)->get();
DB::table('blah')->createdWithinDays(4)->get();

Sorry .. the 'and where' part:  Add the macro to a Service Provider boot method.


问:
Using sudo with Python script
I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.

The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.

I already know that it is not safe to write your password into a .py file, but we are talking about a virtual machine that is not critical at all: I just want to click the .py script and get it working.

This is my attempt:

```<code>#!/usr/bin/env python
import subprocess

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'

subprocess.Popen('sudo -S' , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(sudoPassword , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(command , shell=True,stdout=subprocess.PIPE)
</code>```

My python version is 2.6

答:
To limit what you run as sudo, you could run

```<code>python non_sudo_stuff.py
sudo -E python -c "import os; os.system('sudo echo 1')"
</code>```

without needing to store the password. The -E parameter passes your current user's env to the process. Note that your shell will have sudo priveleges after the second command, so use with caution!

Title: Using sudo with Python script

Body:
I'm trying to write a small script to mount a VirtualBox shared folder each time I execute the script. I want to do it with Python, because I'm trying to learn it for scripting.

The problem is that I need privileges to launch mount command. I could run the script as sudo, but I prefer it to make sudo by its own.

I already know that it is not safe to write your password into a .py file, but we are talking about a virtual machine that is not critical at all: I just want to click the .py script and get it working.

This is my attempt:

#!/usr/bin/env python
import subprocess

sudoPassword = 'mypass'
command = 'mount -t vboxsf myfolder /home/myuser/myfolder'

subprocess.Popen('sudo -S' , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(sudoPassword , shell=True,stdout=subprocess.PIPE)
subprocess.Popen(command , shell=True,stdout=subprocess.PIPE)

My python version is 2.6

Body:
To limit what you run as sudo, you could run

python non_sudo_stuff.py
sudo -E python -c "import os; os.system('sudo echo 1')"

without needing to store the password. The -E parameter passes your current user's env to the process. Note that your shell will have sudo priveleges after the second command, so use with caution!


问:
Fill several parts of NumPy array, given a list of indexes
I want to fill a numpy.ndarray with data (32x32 pixel integer pictures==arrays)

From the name of the file of the picture I know where in my ndarray I want my values to be stored.

I would like to give my ndarray a list but also some slice(0) in it, because the picture is stored in the last two dimensions. How do I do that?

I would like to do something like

Pesudocode:

```<code>data=numpy.ndarray(dim1,dim2,dim3,32,32)
list=function(filename)

data[list,slice(0),slice(0)]=read_image(filename)
</code>```

Is that possible?

My list has entries specifying the positions of the ndarray [int,int,int] and my read image is a 32 times 32 integer array (filling the last two dimension of my ndarray).

答:
To perform this assignment, pass a suitable array in each of the first three dimensions, and : (meaning entire index range) in the last two  dimensions.
If your list is, for example,

```<code>list = [[1, 2, 3], [4, 2, 0], [5, 3, 4], [2, 2, 2]]
</code>```

then the array to pass as the first index is [1, 4, 5, 2],  and similarly for two others: [2, 2, 3, 2] and [3, 0, 4, 2]. Complete example with fake (random) image:

```<code>data = np.zeros((6, 7, 8, 32, 32))
list = [[1, 2, 3], [4, 2, 0], [5, 3, 4], [2, 2, 2]]
image = np.random.uniform(size=(32, 32))
ix = np.array(list)
data[ix[:, 0], ix[:, 1], ix[:, 2], :, :] = image
</code>```

Here ix[:, 0] is [1, 4, 5, 2],  ix[:, 1] is [2, 2, 3, 2], and so on.

Reference: NumPy indexing and broadcasting.

Body:
I want to fill a numpy.ndarray with data (32x32 pixel integer pictures==arrays)

From the name of the file of the picture I know where in my ndarray I want my values to be stored.

I would like to give my ndarray a list but also some slice(0) in it, because the picture is stored in the last two dimensions. How do I do that?

I would like to do something like

Pesudocode:

data=numpy.ndarray(dim1,dim2,dim3,32,32)
list=function(filename)

data[list,slice(0),slice(0)]=read_image(filename)

Is that possible?

My list has entries specifying the positions of the ndarray [int,int,int] and my read image is a 32 times 32 integer array (filling the last two dimension of my ndarray).

Body:
To perform this assignment, pass a suitable array in each of the first three dimensions, and : (meaning entire index range) in the last two  dimensions.
If your list is, for example,

list = [[1, 2, 3], [4, 2, 0], [5, 3, 4], [2, 2, 2]]

then the array to pass as the first index is [1, 4, 5, 2],  and similarly for two others: [2, 2, 3, 2] and [3, 0, 4, 2]. Complete example with fake (random) image:

data = np.zeros((6, 7, 8, 32, 32))
list = [[1, 2, 3], [4, 2, 0], [5, 3, 4], [2, 2, 2]]
image = np.random.uniform(size=(32, 32))
ix = np.array(list)
data[ix[:, 0], ix[:, 1], ix[:, 2], :, :] = image

Here ix[:, 0] is [1, 4, 5, 2],  ix[:, 1] is [2, 2, 3, 2], and so on.

Reference: NumPy indexing and broadcasting.


问:
How to use argparse without passing 'python' in CMD?
I want to run a Python script, which uses argparse, without having to type python at the beginning.

What I do

```<code>$ python file.py --arg value
</code>```

What I want

```<code>$ file --arg value
</code>```

I have done the first part through putting the file in a folder that is added to PATH variable but then argparse is not working correctly as when I type in:

```<code>$ file --arg val
</code>```

It says that arg can't be None even though I passed it in ( it can't read the args I pass it when called like this even though it works well when I use $ python file.py --arg val

I hope this makes sense.

答:
So the solution to the problem was simple but very hard to get to.

The problem was something wrong in the registry.

Executing these 2 commands was the first step:

```<code>assoc .py=py_auto_file
ftype py_auto_file="C:\Anaconda\python.exe" "%1" %*
</code>```

Then editing the registry value default located at key  HKEY_CLASSES_ROOT\py_auto_file\shell\open\command to "C:\Python36\python.exe" "%1" %*

Then Add .PY to PATHEXT

NOTE

Replace Python36 with your version of python ( and the path too if that's different ).

Hope this helps people ;)

Thanks to @Lycopersicum who linked this Question in the comments below which helped me to get the answer.

Also This link helped me.

Body:
I want to run a Python script, which uses argparse, without having to type python at the beginning.

What I do

$ python file.py --arg value

What I want

$ file --arg value

I have done the first part through putting the file in a folder that is added to PATH variable but then argparse is not working correctly as when I type in:

$ file --arg val

It says that arg can't be None even though I passed it in ( it can't read the args I pass it when called like this even though it works well when I use $ python file.py --arg val

I hope this makes sense.

Body:
So the solution to the problem was simple but very hard to get to.

The problem was something wrong in the registry.

Executing these 2 commands was the first step:

assoc .py=py_auto_file
ftype py_auto_file="C:\Anaconda\python.exe" "%1" %*

Then editing the registry value default located at key  HKEY_CLASSES_ROOT\py_auto_file\shell\open\command to "C:\Python36\python.exe" "%1" %*

Then Add .PY to PATHEXT

NOTE

Replace Python36 with your version of python ( and the path too if that's different ).

Hope this helps people ;)

Thanks to @Lycopersicum who linked this Question in the comments below which helped me to get the answer.

Also This link helped me.


问:
Why can't programs be proven?
Why can't a computer program be proven just as a mathematical statement can?  A mathematical proof is built up on other proofs, which are built up from yet more proofs and on down to axioms - those truths truths we hold as self evident.

Computer programs don't seem to have such a structure.  If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program?  You can't since none exist.  Further, what are the axioms of programming?  The very atomic truths of the field?

I don't have good answers to the above.  But it seems software can't be proven because it is art and not science.  How do you prove a Picasso?

答:
First, why are you saying "programs CAN'T be proven"?

What do you mean by "programs" anyway?

If by programs you're meaning algorithms don't you know Kruskal's? Dijkstra's? MST? Prim's? Binary Search? Mergesort? DP? All those things have mathematical models that describe their behaviors.

DESCRIBE. Math doesn't explain the why of things it simply draws a picture of the how. I can't prove to you that the Sun will rise tomorrow on the East but I can show the data where it has been doing that thing on the past.

You said:
"If you write a computer program, how is it that you can take previous proven works and use them to show the truth of your program? You can't since none exist"

Wait? You CAN'T?
http://en.wikipedia.org/wiki/Algorithm#Algorithmic_analysis

I can't show you "truth" I a program as much as I can't show you "truth" on language. Both are representations of our empirical understanding of the world. Not on "truth". Putting all gibberish aside I can demonstrate to you mathematically that a mergesort algorith will sort the elements on a list with O(nlogn) performance, that a Dijkstra will find the shortest path on a weighted graph, or that Euclid's algorithm will find you the greatest common divisor between two numbers. The "truth in my program" in that last case maybe that I'll find you the greatest common divisor between two numbers, don't you think?

With a recurrence equation I can delineate to you how your Fibonacci program works.

Now, is computer programming an art? I sure think it is. As much as mathematics.

ContentLicense: CC BY-SA 2.5

Title: Why can't programs be proven?


问:
Design efficient user interactive event log so that I won't exceed my 10000 user object limit.
I have a problem: in my application I get some event-related information, so for event x I should get a form window in which I do some sort of things (enter some text and click on a button)

My problem is that for my application there is a 10,000 user objects limit (as for all c# apps), and for my existing code there are already 3000 user objects occupied (so that leaves around 7000 user objects free). I receive from 200 clients info about events regarding some stuff going on each of the clients.

When I receive info about an event from a client I would like to somehow display this as a label in an event log window and when I click on the label the specific form window (that I mentioned earlier) should pop-up so that I may enter some text and click on a button.

I need to be able to display this event log window efficiently (because I could receive up to 1000 events from every client and if every label in this log occupies 1 object that means that for every client there will be 1000 objects (max, but possible) so I would exceed very much my 10000 limit).

How can I do something about it efficiently?

Currently for every event I launch a form window in which I enter text and click on a button but this is not efficient (because my form window occupies already 3 user objects and if I have a max 3 * 200 clients * 1000 user object i exceed my 7000 limit by far).

答:
As Hans Passant said - Win32 isn't designed to be used in the way you are trying to use it.

A typical implementation could look like this:

If there are many items (a few thousand, as you expect), a quick search box to filter the items in the list is almost mandatory.

If the details are complex, you can replace the static web browser control with HTML generated on the fly.

If you insist on buttons-per-event (which I wouldn't recommend for your UX) you'd need to render it yourself, which is a PITA in GDI. Or use a web browser control


问:
isnan does not work correctly with `-Ofast` flags
Consider the following test program:

```<code># include <gsl/gsl_statistics_double.h>
# include <iostream>

using namespace std;

int main()
{
  double y = 50.2944, yc = 63.2128;
  double pearson_corr = gsl_stats_correlation(&y, 1, &yc, 1, 1);
  cout << "pearson_corr = " << pearson_corr << endl;
  if (isnan(pearson_corr))
    cout << "It is nan" << endl;
  else
    cout << "Not nan" << endl;
}
</code>```

In some way, this code is some absurd, but its purpose is to show a subtle error that I am experiencing.

The call to gsl_stats_correlation() should give an error because the number of samples is 1 and the pearson coefficient has sense for at least two samples.

When I compile thus:

```<code>c++ test-r2.cc -lgsl -lgslcblas
</code>```

the programs prints out -nan as result and the message "It is nan", which I consider correct because as I said it is not possible to compute the coefficient. The call to isnan()detects correctly that the result is nan. However, when I compile thus:

```<code>c++ -Ofast test-r2.cc -lgsl -lgslcblas
</code>```

The program prints out -nan as result but the message "Not nan", which suggests that the call to isnan() was unable to detect the invalidity of pearson_corr variable.

So, my first question es "Why with the -Ofast flag the call to isnan() is not able to detect that the variable is nan. And my second question would be how to solve this problem in a way independent on the optimizations flags given to the compiler?

I am using gnu c++ version 5.4.0 on ubuntu 16.04 and an Intel i5 run at 64 bits mode

Thanks in advance

答:
You can use this option: -Ofast -fno-finite-math-only, so isnan still works.

Or, if you don't want to use -fno-finithe-math-only, but still want to detect NaN numbers, you can do it in a platform dependent way: implement your own isnan function.

For example, if you're on a IEEE-754 platform with floats 32-bit and  doubles 64-bit, you can do:

```<code>#include <cstdint>
#include <string.h>

bool myIsnan(float v) {
    std::uint32_t i;
    memcpy(&i, &v, 4);
    return ((i&0x7f800000)==0x7f800000)&&(i&0x7fffff);
}

bool myIsnan(double v) {
    std::uint64_t i;
    memcpy(&i, &v, 8);
    return ((i&0x7ff0000000000000)==0x7ff0000000000000)&&(i&0xfffffffffffff);
}
</code>```

Body:
Consider the following test program:

# include <gsl/gsl_statistics_double.h>
# include <iostream>

using namespace std;

int main()
{
  double y = 50.2944, yc = 63.2128;
  double pearson_corr = gsl_stats_correlation(&y, 1, &yc, 1, 1);
  cout << "pearson_corr = " << pearson_corr << endl;
  if (isnan(pearson_corr))
    cout << "It is nan" << endl;
  else
    cout << "Not nan" << endl;
}

In some way, this code is some absurd, but its purpose is to show a subtle error that I am experiencing.

The call to gsl_stats_correlation() should give an error because the number of samples is 1 and the pearson coefficient has sense for at least two samples.

When I compile thus:

c++ test-r2.cc -lgsl -lgslcblas

the programs prints out -nan as result and the message "It is nan", which I consider correct because as I said it is not possible to compute the coefficient. The call to isnan()detects correctly that the result is nan. However, when I compile thus:

c++ -Ofast test-r2.cc -lgsl -lgslcblas

The program prints out -nan as result but the message "Not nan", which suggests that the call to isnan() was unable to detect the invalidity of pearson_corr variable.

So, my first question es "Why with the -Ofast flag the call to isnan() is not able to detect that the variable is nan. And my second question would be how to solve this problem in a way independent on the optimizations flags given to the compiler?

I am using gnu c++ version 5.4.0 on ubuntu 16.04 and an Intel i5 run at 64 bits mode

Thanks in advance

Body:
You can use this option: -Ofast -fno-finite-math-only, so isnan still works.

Or, if you don't want to use -fno-finithe-math-only, but still want to detect NaN numbers, you can do it in a platform dependent way: implement your own isnan function.

For example, if you're on a IEEE-754 platform with floats 32-bit and  doubles 64-bit, you can do:

#include <cstdint>
#include <string.h>

bool myIsnan(float v) {
    std::uint32_t i;
    memcpy(&i, &v, 4);
    return ((i&0x7f800000)==0x7f800000)&&(i&0x7fffff);
}

bool myIsnan(double v) {
    std::uint64_t i;
    memcpy(&i, &v, 8);
    return ((i&0x7ff0000000000000)==0x7ff0000000000000)&&(i&0xfffffffffffff);
}


问:
Return all records from parent table if id = 0
Let's say I have a table that assigns Users as managers for division(s) such as:

UserManagerTable:

```<code>ID      UserId    DivisionId
1       23        1
2       45        0
</code>```

When DivisionId = 0 it is meant to represent that the user is assigned as a manager to All Divisions in the Divisions table.

I would like to know the best possible way to query this table to return DivisionId's and if DivisionId = 0 then return all DivisionIds from the Divisions table.

```<code>SELECT DivisionId FROM UserManagerTable...?

DivisionId
1
1
2
3
...
...
30
</code>```

Initially I thought I could do something like:

```<code>SELECT
CASE
    WHEN DivisionId  = 0 THEN (Select DivisionId FROM Division)
    ELSE DivisionId
END AS DivisionID
FROM PoAppApprovedRequestor
</code>```

But that did not get me what I wanted.

答:
you can use query like below</p>

```<code>;with newUserManagerTable as
(
select ID,UserId,D.DivisionId from
from UserManagerTable U Join Divisions D
  on U.DivisionId=D.DivisionId or U.DivisionId=0
)

--you query here on newUserManagerTable
</code>```

Body:
Let's say I have a table that assigns Users as managers for division(s) such as:

UserManagerTable:

ID      UserId    DivisionId
1       23        1
2       45        0

When DivisionId = 0 it is meant to represent that the user is assigned as a manager to All Divisions in the Divisions table.

I would like to know the best possible way to query this table to return DivisionId's and if DivisionId = 0 then return all DivisionIds from the Divisions table.

SELECT DivisionId FROM UserManagerTable...?

DivisionId
1
1
2
3
...
...
30

Initially I thought I could do something like:

SELECT
CASE
    WHEN DivisionId  = 0 THEN (Select DivisionId FROM Division)
    ELSE DivisionId
END AS DivisionID
FROM PoAppApprovedRequestor

But that did not get me what I wanted.

Body:
you can use query like below

;with newUserManagerTable as
(
select ID,UserId,D.DivisionId from
from UserManagerTable U Join Divisions D
  on U.DivisionId=D.DivisionId or U.DivisionId=0
)

--you query here on newUserManagerTable


问:
Mercurial Changegroup hook varies based on branches
Is there an existing hook in Mercurial which, like changegroup, allows actions to take place on a push, but allows me to do multiple actions (or vary them) based on which branches are affected by the changesets therein?

For example, I need to notify a listener at an url when a push is made but ideally it would notify different urls based on which branch is affected without just blanketing them all.

答:
There are no branch-specfic hooks, but you can do that logic in the hook itself.  For example in your hgrc:

```<code>[hooks]
changeset = actions-by-branch.sh
</code>```

and then in your actions-by-branch.sh you'd do:

```<code>#!/bin/bash
BRANCH=$(hg log --template '{branch}' -r $HG_NODE)
BRANCH=${BRANCH:-default}  # set value to 'default' if it was empty

if [ "$BRANCH" == "default" ] ; then
   do something
elif [ "$BRANCH" == "release" ] ; then
   do something else
else
   do a different thing
fi
</code>```

Notice that I used a changeset rather than changegroup hook.  A single changegroup can have changesets on multiple branches, which would complicate the logic.  If you do decide to go that route you need to loop from $HG_NODE all the way to tip to act on each changeset in the changegroup.

Body:
There are no branch-specfic hooks, but you can do that logic in the hook itself.  For example in your hgrc:

[hooks]
changeset = actions-by-branch.sh

and then in your actions-by-branch.sh you'd do:

#!/bin/bash
BRANCH=$(hg log --template '{branch}' -r $HG_NODE)
BRANCH=${BRANCH:-default}  # set value to 'default' if it was empty

if [ "$BRANCH" == "default" ] ; then
   do something
elif [ "$BRANCH" == "release" ] ; then
   do something else
else
   do a different thing
fi

Notice that I used a changeset rather than changegroup hook.  A single changegroup can have changesets on multiple branches, which would complicate the logic.  If you do decide to go that route you need to loop from $HG_NODE all the way to tip to act on each changeset in the changegroup.


问:
Mirror cells from one sheet to another within the same workbook with special conditions

What are you trying to accomplish?

I'm trying to mirror the contents of a row of respective cells from one sheet to another. However, the caveat here are: I'm restricted to MS Excel not Access - I can use modules, the initials in column B are to be used as the condition to populate the corresponding sheets. Like:  Primary key in MS Access and finally the sheets should be populated in real time; nothing should have to be run.
Said spreadsheet attached here.

What have you tried so far?

a. Well, I tried the =Value(x) and  =Grand Budget!A(x) formulas. I setup the corresponding initials worksheets with the respective initials in the main sheet so for example: on sheet "Grand Budget" all NA initials and data in the corresponding row i.e. Description, Vendor and Amount will be mirrored on worksheet "NA"
It works great until the third caveat is unfulfilled: it doesn't work in real time because I cannot predict what the next initial will be so I can't setup the next cell with a formula.

b. I also tried filtering the "Grand Budget" sheet by initials in column B, selecting the needed row data, named it and imported the named table to the corresponding initial worksheet. Source.

What do you have in mind - conceptually?

I'm thinking, it's time for modules or if someone knows a hidden excel formula, lay it on me.
 all I have right is an if statement in c++ in my mind: if(current_cell == desired_initial) {populate()};

I'm willing to aid in interpreting anything that may have been transposed incorrectly.

答:
@peter
update on progress, I require assistance on how to populate the respective sheets. thank you!</p>

```<code>Option Explicit

' Create a new sheet for new initials.
Sub CreateNewSheet(Initials As String)
    'Checks whether a sheet with the name "Initials" exists
    'Creates a new sheet if it doesn't exist yet.
    If SheetExists("Initials") Then
        MsgBox "Yay! the sheet exists"
    Else
        MsgBox "Boo! the sheet doesn't exist; I shall create a new one!"
         'Creates a new sheet if it doesn't exist yet.
         CreateSheet (Initials)
    End If
End Sub

Function SheetExists(Initials As String)
    On Error GoTo no:
    WorksheetName = Worksheets(Initials).Name
    SheetExists = True
    Exit Function
no:
    SheetExists = False
End Function

Private Sub CreateSheet(Initials)
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = Initials
End Sub

Private Sub sbClearEntireSheetOnlyData()
    Sheets("Initials").Cells.ClearContents
End Sub

Private Sub MatchCase(Initials)
    Dim x As Integer
    Application.ScreenUpdating = False
    ' Set numrows = number of rows of data.
    NumRows = Range("A3", Range("A3").End(xlDown)).Rows.Count
    ' Select cell a3.
    Range("A3").Select
    ' Establish "For" loop to loop "numrows" number of times.
    For x = 1 To NumRows
       ' Insert your code here.
       ' Selects cell down 1 row from active cell.
       ActiveCell.Offset(1, 0).Select
    Next
    Application.ScreenUpdating = True
End Sub
</code>```

Body:
@peter
update on progress, I require assistance on how to populate the respective sheets. thank you!

Option Explicit

' Create a new sheet for new initials.
Sub CreateNewSheet(Initials As String)
    'Checks whether a sheet with the name "Initials" exists
    'Creates a new sheet if it doesn't exist yet.
    If SheetExists("Initials") Then
        MsgBox "Yay! the sheet exists"
    Else
        MsgBox "Boo! the sheet doesn't exist; I shall create a new one!"
         'Creates a new sheet if it doesn't exist yet.
         CreateSheet (Initials)
    End If
End Sub

Function SheetExists(Initials As String)
    On Error GoTo no:
    WorksheetName = Worksheets(Initials).Name
    SheetExists = True
    Exit Function
no:
    SheetExists = False
End Function

Private Sub CreateSheet(Initials)
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets.Add(After:= _
             ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
    ws.Name = Initials
End Sub

Private Sub sbClearEntireSheetOnlyData()
    Sheets("Initials").Cells.ClearContents
End Sub

Private Sub MatchCase(Initials)
    Dim x As Integer
    Application.ScreenUpdating = False
    ' Set numrows = number of rows of data.
    NumRows = Range("A3", Range("A3").End(xlDown)).Rows.Count
    ' Select cell a3.
    Range("A3").Select
    ' Establish "For" loop to loop "numrows" number of times.
    For x = 1 To NumRows
       ' Insert your code here.
       ' Selects cell down 1 row from active cell.
       ActiveCell.Offset(1, 0).Select
    Next
    Application.ScreenUpdating = True
End Sub


问:
Saving model with description in keras
I would like to write out a keras model that contains a description (can be a simple string), so that one can more easily keep track of what a file contains.

Is there any simple way to do this? I can save and load a model with

```<code>model.save(filename)
[...]
model = keras.load_model(filename)
</code>```

what I would like to do, is something to the effect of

```<code>model.save(filename, description=string)
[...]
model, description = keras.load_model(filename)
</code>```

Any ideas on what would be the simplest way of achieving this?

答:
Currently, there is no way to do this with the current version of model.save in the Keras. It just saves the configuration of the model() such as loss function  and metrics and load_model just returns what has been saved.

One nasty solution to this problem is manually adding a description variable to the class models.py in Keras and consequently, add the required lines of code to the save_model and load_model functions. Again, this is just a horrible solution!

Title: Saving model with description in keras

Body:
I would like to write out a keras model that contains a description (can be a simple string), so that one can more easily keep track of what a file contains.

Is there any simple way to do this? I can save and load a model with

model.save(filename)
[...]
model = keras.load_model(filename)

what I would like to do, is something to the effect of

model.save(filename, description=string)
[...]
model, description = keras.load_model(filename)

Any ideas on what would be the simplest way of achieving this?


问:
Closing word when using interop library - VB.net
I have successfully been able to convert a word doc to pdf - but I can't get the winword process to end.

```<code> Dim wordApplication As Object = New Microsoft.Office.Interop.Word.Application
    Dim wordDocument As Object
    wordApplication.displayalerts = Word.WdAlertLevel.wdAlertsNone
    wordDocument = New Microsoft.Office.Interop.Word.Document
    'wordDocument = Nothing
    Dim outputFilename As String
    Dim filename As String

    filename = "c:\TestInvoice.doc"

    Try
        wordDocument = wordApplication.Documents.Open(filename, ReadOnly:=False)
        outputFilename = System.IO.Path.ChangeExtension(filename, "pdf")

        If Not wordDocument Is Nothing Then
            wordDocument.ExportAsFixedFormat(outputFilename, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 0, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, True, True, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, True, True, False)
        End If
        'Threading.Thread.Sleep(3000)

        If File.Exists(System.IO.Path.ChangeExtension(filename, "pdf")) Then
            MessageBox.Show(System.IO.Path.ChangeExtension(filename, "pdf"))
        End If
        'wordDocument = Nothing

        'wordApplication.Documents(filename).Close(Word.WdSaveOptions.wdDoNotSaveChanges)

        'wordDocument.dispose()

        'wordApplication.quit(False)
        wordDocument.close()

        wordApplication.application.quit(False)
        wordApplication = Nothing
</code>```

I've tried pretty much everything and have been scratching my head for the past few days - can you point me in the right direction?

答:
Have you tried a Using statement?

Try wrapping everything in this.

```<code>Using wordApplication As Object = New Microsoft.Office.Interop.Word.Application

End Using
</code>```

Body:
I have successfully been able to convert a word doc to pdf - but I can't get the winword process to end.

 Dim wordApplication As Object = New Microsoft.Office.Interop.Word.Application
    Dim wordDocument As Object
    wordApplication.displayalerts = Word.WdAlertLevel.wdAlertsNone
    wordDocument = New Microsoft.Office.Interop.Word.Document
    'wordDocument = Nothing
    Dim outputFilename As String
    Dim filename As String

    filename = "c:\TestInvoice.doc"

    Try
        wordDocument = wordApplication.Documents.Open(filename, ReadOnly:=False)
        outputFilename = System.IO.Path.ChangeExtension(filename, "pdf")

        If Not wordDocument Is Nothing Then
            wordDocument.ExportAsFixedFormat(outputFilename, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF, False, Microsoft.Office.Interop.Word.WdExportOptimizeFor.wdExportOptimizeForOnScreen, Microsoft.Office.Interop.Word.WdExportRange.wdExportAllDocument, 0, 0, Microsoft.Office.Interop.Word.WdExportItem.wdExportDocumentContent, True, True, Microsoft.Office.Interop.Word.WdExportCreateBookmarks.wdExportCreateNoBookmarks, True, True, False)
        End If
        'Threading.Thread.Sleep(3000)

        If File.Exists(System.IO.Path.ChangeExtension(filename, "pdf")) Then
            MessageBox.Show(System.IO.Path.ChangeExtension(filename, "pdf"))
        End If
        'wordDocument = Nothing

        'wordApplication.Documents(filename).Close(Word.WdSaveOptions.wdDoNotSaveChanges)

        'wordDocument.dispose()

        'wordApplication.quit(False)
        wordDocument.close()

        wordApplication.application.quit(False)
        wordApplication = Nothing

I've tried pretty much everything and have been scratching my head for the past few days - can you point me in the right direction?

Body:
Have you tried a Using statement?

Try wrapping everything in this.

Using wordApplication As Object = New Microsoft.Office.Interop.Word.Application

End Using


问:
Chef is running the wrong recipe
I'm trying to set up Varnish in front of a Wordpress multi-site using Chef.  I am new to the system that was set up by others, and I'm a bit of a beginner in general.

I have created a new recipe and added it to the run list, but when I run chef-client, it executes a different recipe in place of the one I wrote.  Specifically, it runs the only recipe that my recipe includes.

Here is my recipe, which I copied almost verbatim from a pre-existing, working recipe that we use for a different site:

```<code>#
# Cookbook Name:: web_varnish_config
# Recipe:: wordpress
#

include_recipe 'web_varnish_config::default'

all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")
all_wordpress_backends.sort_by!{ |n| n[:fqdn] } # Sort the nodes to prevent config-order thrashing.

# Error state
if all_wordpress_backends.empty?
  Chef::Log.warn("At least one node with recipes:web_wordpress must exist for chef_environment:#{node.chef_environment}. Skipping Varnish configuration.")
  return
end

template "/etc/varnish/default.vcl" do
  source "etc/varnish/wordpress.vcl.erb"
  mode "0644"
  variables(
    :all_wordpress_backends => all_wordpress_backends
  )
  notifies :restart, "service[varnish]", :delayed
end

# Use a share secret for our Varnish instances that is available to our Webservers
# so that Wordpress can clear the Varnish cache.
include_recipe 'chef-vault'
settings = chef_vault_item_for_environment("web_wordpress", "varnish")
if !settings.nil? and settings.key?('secret')
  file "/etc/varnish/secret" do
    content settings['secret']
    mode "0600"
    notifies :restart, "service[varnish]", :delayed
  end
end
</code>```

When I run chef-client, it runs web_varnish_config::default instead of this recipe, web_varnish_config::wordpress.  This is what my chef-client output looks like (tried to copy all of it, but couldn't so here's the beginning and the end, what I think is most relevant):

```<code>Starting Chef Client, version 13.6.4
resolving cookbooks for run list: ["yum-epel::default", "serversetup-midd::cent7", "serversetup-midd::rootpassword", "midd_yum_cron::default", "fw-midd::default", "chef-client::config", "chef-client::default", "chef_client_updater::default", "centrify-midd::default", "centrify-midd::sshd", "midd_spacewalk::client", "commvault-midd::default", "serversetup-midd::webserver", "fw-midd::webserver", "centrify-midd::webserver", "chef-vault::default", "ssl-config-midd::miis", "ssl-config-midd::midd", "php-midd::default", "ssl-config-midd::wordpress", "web_php_config", "web_apache_config", "web_apache_config::ssl_context", "web_wordpress", "cookbook_versions::all", "ssl-config-midd::davisfellowsforpeace", "ssl-config-midd::davisprojectsforpeace", "ssl-config-midd::davisuwcscholars", "varnish-midd::default", "fw-midd::varnishserver", "web_varnish_config::backend", "web_varnish_config::wordpress"]
Synchronizing Cookbooks:
  - smbfs (0.5.0)
  - compat_resource (12.19.0)
  - web_php_config (1.1.0)
  - ohai (5.1.0)
  - midd_spacewalk (0.4.3)
  - windows (3.0.5)
  - yum (5.0.1)
  - firewalld (1.1.5)
  - cookbook_versions (1.0.0)
  - serversetup-midd (2.6.10)
  - commvault-midd (2.3.1)
  - cron (4.1.3)
  - php-midd (2.0.6)
  - ssl-config-midd (2.2.1)
  - chef-vault (3.0.0)
  - logrotate (2.2.0)
  - selinux (2.0.3)
  - ssh_authorized_keys (0.4.0)
  - chef_client_updater (2.0.3)
  - web_wordpress (2.0.10)
  - varnish-midd (2.0.3)
  - chef-client (8.1.6)
  - users (5.1.0)
  - yum-epel (2.1.2)
  - web_apache_config (2.0.10)
  - web_varnish_config (2.3.2)
  - sshd (1.3.1)
  - fw-midd (3.2.5)
  - midd_yum_cron (1.0.0)
  - web_sshkeys (1.0.2)
  - web_git_tracking_branch (1.1.0)
  - centrify-midd (3.1.1)
</code>```

And at the end:

```<code>Recipe: web_varnish_config::backend
   * cookbook_file[/var/www/html/check.html] action create (up to date)
   * web_apache_config_vhost[vhost-7-wwwhealthcheck.conf] action create
   * template[/etc/httpd/conf.d/vhost-7-wwwhealthcheck.conf] action create (up to date)
 (up to date)
 # NOTE: Below is where I'm expecting web_varnish_config:wordpress
 Recipe: web_varnish_config::default
   * service[varnish] action enable (up to date)
   * template[/etc/varnish/varnish.params] action create (up to date)
   * service[varnishncsa] action enable (up to date)
   * service[varnishncsa] action start (up to date)
   * cookbook_file[/etc/systemd/system/varnishncsa.service] action create (up to date)
</code>```

If I take out the include line, chef-client skips this entirely, without errors.

Any ideas?

答: Copying down from comments, the search in the recipe is likely returning no nodes and so the recipe is skipping itself as it was written to do.</p>

Title: Chef is running the wrong recipe

Body:
I'm trying to set up Varnish in front of a Wordpress multi-site using Chef.  I am new to the system that was set up by others, and I'm a bit of a beginner in general.

I have created a new recipe and added it to the run list, but when I run chef-client, it executes a different recipe in place of the one I wrote.  Specifically, it runs the only recipe that my recipe includes.

Here is my recipe, which I copied almost verbatim from a pre-existing, working recipe that we use for a different site:

#
# Cookbook Name:: web_varnish_config
# Recipe:: wordpress
#

include_recipe 'web_varnish_config::default'

all_wordpress_backends = search(:node, "chef_environment:#{node.chef_environment} AND roles:web_wordpress")
all_wordpress_backends.sort_by!{ |n| n[:fqdn] } # Sort the nodes to prevent config-order thrashing.

# Error state
if all_wordpress_backends.empty?
  Chef::Log.warn("At least one node with recipes:web_wordpress must exist for chef_environment:#{node.chef_environment}. Skipping Varnish configuration.")
  return
end

template "/etc/varnish/default.vcl" do
  source "etc/varnish/wordpress.vcl.erb"
  mode "0644"
  variables(
    :all_wordpress_backends => all_wordpress_backends
  )
  notifies :restart, "service[varnish]", :delayed
end

# Use a share secret for our Varnish instances that is available to our Webservers
# so that Wordpress can clear the Varnish cache.
include_recipe 'chef-vault'
settings = chef_vault_item_for_environment("web_wordpress", "varnish")
if !settings.nil? and settings.key?('secret')
  file "/etc/varnish/secret" do
    content settings['secret']
    mode "0600"
    notifies :restart, "service[varnish]", :delayed
  end
end

When I run chef-client, it runs web_varnish_config::default instead of this recipe, web_varnish_config::wordpress.  This is what my chef-client output looks like (tried to copy all of it, but couldn't so here's the beginning and the end, what I think is most relevant):

Starting Chef Client, version 13.6.4
resolving cookbooks for run list: ["yum-epel::default", "serversetup-midd::cent7", "serversetup-midd::rootpassword", "midd_yum_cron::default", "fw-midd::default", "chef-client::config", "chef-client::default", "chef_client_updater::default", "centrify-midd::default", "centrify-midd::sshd", "midd_spacewalk::client", "commvault-midd::default", "serversetup-midd::webserver", "fw-midd::webserver", "centrify-midd::webserver", "chef-vault::default", "ssl-config-midd::miis", "ssl-config-midd::midd", "php-midd::default", "ssl-config-midd::wordpress", "web_php_config", "web_apache_config", "web_apache_config::ssl_context", "web_wordpress", "cookbook_versions::all", "ssl-config-midd::davisfellowsforpeace", "ssl-config-midd::davisprojectsforpeace", "ssl-config-midd::davisuwcscholars", "varnish-midd::default", "fw-midd::varnishserver", "web_varnish_config::backend", "web_varnish_config::wordpress"]
Synchronizing Cookbooks:
  - smbfs (0.5.0)
  - compat_resource (12.19.0)
  - web_php_config (1.1.0)
  - ohai (5.1.0)
  - midd_spacewalk (0.4.3)
  - windows (3.0.5)
  - yum (5.0.1)
  - firewalld (1.1.5)
  - cookbook_versions (1.0.0)
  - serversetup-midd (2.6.10)
  - commvault-midd (2.3.1)
  - cron (4.1.3)
  - php-midd (2.0.6)
  - ssl-config-midd (2.2.1)
  - chef-vault (3.0.0)
  - logrotate (2.2.0)
  - selinux (2.0.3)
  - ssh_authorized_keys (0.4.0)
  - chef_client_updater (2.0.3)
  - web_wordpress (2.0.10)
  - varnish-midd (2.0.3)
  - chef-client (8.1.6)
  - users (5.1.0)
  - yum-epel (2.1.2)
  - web_apache_config (2.0.10)
  - web_varnish_config (2.3.2)
  - sshd (1.3.1)
  - fw-midd (3.2.5)
  - midd_yum_cron (1.0.0)
  - web_sshkeys (1.0.2)
  - web_git_tracking_branch (1.1.0)
  - centrify-midd (3.1.1)

And at the end:

Recipe: web_varnish_config::backend
   * cookbook_file[/var/www/html/check.html] action create (up to date)
   * web_apache_config_vhost[vhost-7-wwwhealthcheck.conf] action create
   * template[/etc/httpd/conf.d/vhost-7-wwwhealthcheck.conf] action create (up to date)
 (up to date)
 # NOTE: Below is where I'm expecting web_varnish_config:wordpress
 Recipe: web_varnish_config::default
   * service[varnish] action enable (up to date)
   * template[/etc/varnish/varnish.params] action create (up to date)
   * service[varnishncsa] action enable (up to date)
   * service[varnishncsa] action start (up to date)
   * cookbook_file[/etc/systemd/system/varnishncsa.service] action create (up to date)

If I take out the include line, chef-client skips this entirely, without errors.

Any ideas?


问:
Laravel - Extending User model
I have a class Seller that extends laravel's User model
as the following

```<code>namespace App;
class Seller extends User{
   public function products(){
       return $this->hasMany(Products::class);
   }
}
</code>```

in the ModelFactory.php I have the following code

```<code>$factory->define(Transaction::class, function (Faker\Generator $faker) {
  $seller = Seller::has('products')->get()->random();
  $buyer = User::all()->except($seller->id)->random();
  return [
    'quantity' => $faker->numberBetween(0, 3),
    'buyer_id' => $buyer->id,
    'product_id' => $seller->products->random()->id
 ];
});
</code>```

I'm getting the following error

Base table or view not found: 1146 Table 'tutorial.sellers' doesn't
  exist (SQL: select * from sellers where exists (select * from
  products where sellers.id = products.seller_id))

the Product class is as the following

```<code>namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model{
     const AVAILABLE_PRODUCT = 'available';
     const UNAVAILABLE_PRODUCT = 'unavailable';

     protected $fillable = [
         'name',
         'description',
         'quantity',
         'status',
         'image',
         'seller_id'
     ];

     public function isAvailable(){

         return $this->status == Product::AVAILABLE_PRODUCT;

     }

    public function seller(){

        return $this->belongsTo(Seller::class);

    }

    public function categories(){

        return $this->belongsToMany(Category::class);

    }

    public function transactions(){
        return $this->hasMany(Transaction::class);
    }

}
</code>```

apparently, the generated query does not take the inheritance into consideration.
I tried changing $seller = Seller::has('products')->get()->random(); into $seller = User::has('products')->get()->random();
but then the line 'product_id' => $seller->products->random()->id causes an error since the products() method is defined in seller class
What's the best way to do this?

Is it a right way to extend User class ?

I have searched for ways to extend the User class.
I found this question: Model Inheritance in Laravel
 didn't help me though.

I'm using Laravel 5.4.36, PHP 7.1.11

答:
To summarize:

Laravel will use the Class Name as the table name if not explicitly declared on the model. This causes Laravel to automatically assume sellers as the table name in the query. To resolve this add the following to the extending Model:

```<code>protected $table = 'users'
</code>```

Finally, you're attempting to use ->random() on a query builder instance, but that's not what you want. You want to use it on the collection. You can do any of the following:

```<code>$seller->products()->get()->random()->id;
</code>```

The above will perform the query and retrieve all products, then get you a random item from the returned collection, then retrieve the ID. The better (more efficient) way, is to let the Query builder handle it:

```<code>$seller->products->inRandomOrder()->first()->id;
</code>```

Title: Laravel - Extending User model

Body:
I have a class Seller that extends laravel's User model
as the following

namespace App;
class Seller extends User{
   public function products(){
       return $this->hasMany(Products::class);
   }
}

in the ModelFactory.php I have the following code

$factory->define(Transaction::class, function (Faker\Generator $faker) {
  $seller = Seller::has('products')->get()->random();
  $buyer = User::all()->except($seller->id)->random();
  return [
    'quantity' => $faker->numberBetween(0, 3),
    'buyer_id' => $buyer->id,
    'product_id' => $seller->products->random()->id
 ];
});

I'm getting the following error

Base table or view not found: 1146 Table 'tutorial.sellers' doesn't
  exist (SQL: select * from sellers where exists (select * from
  products where sellers.id = products.seller_id))

the Product class is as the following

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model{
     const AVAILABLE_PRODUCT = 'available';
     const UNAVAILABLE_PRODUCT = 'unavailable';

     protected $fillable = [
         'name',
         'description',
         'quantity',
         'status',
         'image',
         'seller_id'
     ];

     public function isAvailable(){

         return $this->status == Product::AVAILABLE_PRODUCT;

     }

    public function seller(){

        return $this->belongsTo(Seller::class);

    }

    public function categories(){

        return $this->belongsToMany(Category::class);

    }

    public function transactions(){
        return $this->hasMany(Transaction::class);
    }

}

apparently, the generated query does not take the inheritance into consideration.
I tried changing $seller = Seller::has('products')->get()->random(); into $seller = User::has('products')->get()->random();
but then the line 'product_id' => $seller->products->random()->id causes an error since the products() method is defined in seller class
What's the best way to do this?

Is it a right way to extend User class ?

I have searched for ways to extend the User class.
I found this question: Model Inheritance in Laravel
 didn't help me though.

I'm using Laravel 5.4.36, PHP 7.1.11

Body:
To summarize:

Laravel will use the Class Name as the table name if not explicitly declared on the model. This causes Laravel to automatically assume sellers as the table name in the query. To resolve this add the following to the extending Model:

protected $table = 'users'

Finally, you're attempting to use ->random() on a query builder instance, but that's not what you want. You want to use it on the collection. You can do any of the following:

$seller->products()->get()->random()->id;

The above will perform the query and retrieve all products, then get you a random item from the returned collection, then retrieve the ID. The better (more efficient) way, is to let the Query builder handle it:

$seller->products->inRandomOrder()->first()->id;


问:
Can I run R scripts in AWS Glue?
Is it possible to call an R script from an AWS Glue job? I would need to pass parameters to it as well.</p>

答:
It is not currently possible to run R on AWS Glue. Python is officially supported, but the following quote from the docs suggests that it may be possible using something like SparkR in the future:

Your custom script must be compatible with Apache Spark 2.1.

Title: Can I run R scripts in AWS Glue?


问:
Enable Autosave files plugin on Sublime Startup
How can the AutoSave plugin for Sublime Text be automatically enabled on Sublime Text 3 startup?

link to auto-save is here

答:
This particular package doesn't naively support the idea of enabling itself automatically when Sublime starts, so in order to accomplish this a small plugin is needed to make this happen, which I've posted below.

In order to use this plugin, select Tools > Developer > New Plugin... from the menu, then replace the stub plugin code that is presented to you with the code below and save the file in the location that Sublime will default to (your User package) as a Python file, for example auto_save_on_startup.py

NOTE: See the edit below; this plugin requires that you add a setting in order to control whether it's enabled or not.

import sublime
import sublime_plugin

# Sublime executes this every time it loads the plugin, which includes when
# it first starts, as well as whenever the this file changes on disk.
def plugin_loaded():
    settings = sublime.load_settings("auto_save.sublime-settings")
    # See if auto_save_toggle_at_startup is turned on; default it to
    # not being turned on if the setting is missing, because that is
    # how the package would behave if you didn't add the setting.
    if settings.get("auto_save_toggle_at_startup", False):
        sublime.set_timeout(lambda: sublime.run_command("auto_save"), 1000)
```
<hr />
<p><em><strong>Edit:</strong></em> The original version of this plugin called <code>run_command</code> directly; however Sublime invokes the <code>plugin_loaded</code> endpoint before it has fully added all of the command classes provided by plugins, so it was possible for this to try to run the command before it was available.</p>
<p>The code above has been modified so that there is a delay imposed before the command triggers to give the commands time to become available.</p>
<hr />
<p>As the comment suggests, every time Sublime loads a plugin file, it will execute the <code>plugin_loaded()</code> function inside of that plugin file, if it happens to exist.</p>
<p>Here the code checks the auto save package settings to see if you have set the value <code>auto_save_toggle_at_startup</code> to <code>true</code>, and if you have it will invoke the command from the auto save package that turns it on.</p>
<p>As such, you also need to select <code>Preferences > Package Settings > Auto-save > Settings - User</code> from the menu and add the appropriate setting. Preferences is under <code>Sublime Text</code> in the menu if you're using MacOS.</p>
<p>If that brings up an empty file (because you're using the default settings), then you should enter the following into the file and save it. Otherwise you can just add the setting itself to the existing settings.</p>
<pre class="lang-json prettyprint-override"><code>{
    // Toggle auto save at startup (from User/auto_save_on_startup.py)
    "auto_save_toggle_at_startup": true
}
</code>```

Here the comment is a reminder that this setting is being provided by something outside of the package itself, in case you forget.

Since the plugin command will only toggle the state of the auto save when it's loaded, you either have to add the setting before you add the plugin, save the plugin file to get Sublime to reload it once the setting is in place, or restart Sublime.

Alternatively you can replace the plugin_loaded() function to contain only the run_command line to unconditionally always toggle the state at startup, but you may want to temporarily stop it from doing that at some point in the future, which you could easily do by just toggling the setting.

Body:
This particular package doesn't naively support the idea of enabling itself automatically when Sublime starts, so in order to accomplish this a small plugin is needed to make this happen, which I've posted below.

In order to use this plugin, select Tools > Developer > New Plugin... from the menu, then replace the stub plugin code that is presented to you with the code below and save the file in the location that Sublime will default to (your User package) as a Python file, for example auto_save_on_startup.py

NOTE: See the edit below; this plugin requires that you add a setting in order to control whether it's enabled or not.

import sublime
import sublime_plugin

# Sublime executes this every time it loads the plugin, which includes when
# it first starts, as well as whenever the this file changes on disk.
def plugin_loaded():
    settings = sublime.load_settings("auto_save.sublime-settings")
    # See if auto_save_toggle_at_startup is turned on; default it to
    # not being turned on if the setting is missing, because that is
    # how the package would behave if you didn't add the setting.
    if settings.get("auto_save_toggle_at_startup", False):
        sublime.set_timeout(lambda: sublime.run_command("auto_save"), 1000)

Edit: The original version of this plugin called run_command directly; however Sublime invokes the plugin_loaded endpoint before it has fully added all of the command classes provided by plugins, so it was possible for this to try to run the command before it was available.

The code above has been modified so that there is a delay imposed before the command triggers to give the commands time to become available.

As the comment suggests, every time Sublime loads a plugin file, it will execute the plugin_loaded() function inside of that plugin file, if it happens to exist.

Here the code checks the auto save package settings to see if you have set the value auto_save_toggle_at_startup to true, and if you have it will invoke the command from the auto save package that turns it on.

As such, you also need to select Preferences > Package Settings > Auto-save > Settings - User from the menu and add the appropriate setting. Preferences is under Sublime Text in the menu if you're using MacOS.

If that brings up an empty file (because you're using the default settings), then you should enter the following into the file and save it. Otherwise you can just add the setting itself to the existing settings.

{
    // Toggle auto save at startup (from User/auto_save_on_startup.py)
    "auto_save_toggle_at_startup": true
}

Here the comment is a reminder that this setting is being provided by something outside of the package itself, in case you forget.

Since the plugin command will only toggle the state of the auto save when it's loaded, you either have to add the setting before you add the plugin, save the plugin file to get Sublime to reload it once the setting is in place, or restart Sublime.

Alternatively you can replace the plugin_loaded() function to contain only the run_command line to unconditionally always toggle the state at startup, but you may want to temporarily stop it from doing that at some point in the future, which you could easily do by just toggling the setting.


问:
How to stop and start Jenkins on Mac
I installed Jenkins on my Mac local machine. It is running and working fine. What is the right way to stop and start the server from terminal?</p>

答:
You might be able to use launchctl for starting and stopping Jenkins.

Start

```<code>sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist
</code>```

Stop

```<code>sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist
</code>```

Title: How to stop and start Jenkins on Mac

Body:
You might be able to use launchctl for starting and stopping Jenkins.

Start

sudo launchctl load /Library/LaunchDaemons/org.jenkins-ci.plist

Stop

sudo launchctl unload /Library/LaunchDaemons/org.jenkins-ci.plist


问:
Add "Keyboards" In App Settings
How can you add the Keyboards option in the settings of an app?

Like such:

I know the Siri & Search keys you must enter in your Info.plist, but I wasn't able to find how to directly add the keyboards option.

The purpose is to be able to turn on a custom keyboard from the apps settings rather than going through General > Keyboards > Add Keyboard.

If the answer is "You can not", how can you add a keyboard from within the app's own settings. There are several keyboard applications out there that have this feature, so unless it's a private deal with Apple I'm sure there is a way to do this.

答: Simply removing and adding the keyboard extension to an already existing project added the necessary elements to the info.plist. Not sure if this was a bug, software glitch on my end, or the alignment of the planets... all I know is that it is fixed now. Cheers!

Title: Add "Keyboards" In App Settings


问:
How to not worry about children objects (lists) in nhibernate
i have a parent object called Request and a Child object called RequestDate

A Request has a list of RequestDates

i want to have mappings so when i:

Save Parent, it saves all children

Update list on parent object (remove some items and add some new items) and save parent it updates children

Delete parent will delete all children.

is this possible.  i tried using this syntax but it doesn't seem to work:

```<code> HasMany(x => x.RequestDates)
     .AsBag()
     .Inverse()
     .Cascade.AllDeleteOrphan()
     .Fetch.Select()
     .BatchSize(80);
</code>```

the issue is around #2.  what is the way to update the list of items.  I am calling Remove() to get rid of some and then calling Add() to add new ones

答:
You've configured your collection as Inverse, which means the "other side" (i.e. a  References in RequestDate) is responsible for managing the relationship.

Therefore, you need to set the reference to the Request in the RequestDate.

If you don't have such a property, then remove the Inverse() call. But NH will do an insert with NULL and then an UPDATE, which might not be what you want.

Body:
i have a parent object called Request and a Child object called RequestDate

A Request has a list of RequestDates

i want to have mappings so when i:

Save Parent, it saves all children

Update list on parent object (remove some items and add some new items) and save parent it updates children

Delete parent will delete all children.

is this possible.  i tried using this syntax but it doesn't seem to work:

 HasMany(x => x.RequestDates)
     .AsBag()
     .Inverse()
     .Cascade.AllDeleteOrphan()
     .Fetch.Select()
     .BatchSize(80);

the issue is around #2.  what is the way to update the list of items.  I am calling Remove() to get rid of some and then calling Add() to add new ones


问:
Calculate previous week's start and end date
What is the best way to calculate the previous week's start and end date in C#?  I.e. today 18 March would result in 9 March (Monday last week) and 15 March (Sunday last week).

I have seen this done with DayOfWeek and a switch statement to work out an offset but was wondering whether there is a more elegant way.

答:
The accepted solution is actually not correct.

You have to switch when the week "breaks", i.e. when it considers the week to end or start, and the formula in the accepted solution does not.

This is not so visible on a Monday as week start, but more so if you would consider Thursday the end of the week.

Correct formula is (for a Thursday as ending day):

```<code>DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);
</code>```

For Monday, the -5 would switch to -2.

Example code to print out

```<code>        String s = "";
        DateTime date = new DateTime(2017, 1, 1);
        for (int i = 0; i < 14; i++)
        {
            date = date.AddDays(1);
            DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);
            DateTime mon = date.AddDays(-(int)(date.AddDays(-2).DayOfWeek) -1);
            s += date.ToString() + " - Thu: " + thu.ToString() + " - Mon: " + mon.ToString() + "\r\n";
        }
        Console.WriteLine(s);
</code>```

OwnerDisplayName: Henryk

Body:
The accepted solution is actually not correct.

You have to switch when the week "breaks", i.e. when it considers the week to end or start, and the formula in the accepted solution does not.

This is not so visible on a Monday as week start, but more so if you would consider Thursday the end of the week.

Correct formula is (for a Thursday as ending day):

DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);

For Monday, the -5 would switch to -2.

Example code to print out

        String s = "";
        DateTime date = new DateTime(2017, 1, 1);
        for (int i = 0; i < 14; i++)
        {
            date = date.AddDays(1);
            DateTime thu = date.AddDays(-(int)(date.AddDays(-5).DayOfWeek) -1);
            DateTime mon = date.AddDays(-(int)(date.AddDays(-2).DayOfWeek) -1);
            s += date.ToString() + " - Thu: " + thu.ToString() + " - Mon: " + mon.ToString() + "\r\n";
        }
        Console.WriteLine(s);


问:
Exporting an imported library
I have projectA, into which I'm importing a library with:

```<code>add_library(foo STATIC IMPORTED)
set_property(TARGET foo PROPERTY IMPORTED_LOCATION /path/to/foo.a)
</code>```

I then use foo in several places within the project, and it all works fine.

A couple of directory levels down I want to export a library built within this project for use in yet another project with a completely disconnected CMake config. I've got:

```<code>...
target_link_libraries(thislib foo)
export(TARGETS thislib FILE /path/to/thislib.cmake)
</code>```

The importing projectB also needs foo though (because the imported library needs it), and complains that it cannot find -lfoo. I tried adding it to the export command, but then I get:

```<code>CMake Error at thislib/CMakeLists.txt:37 (export):
  export given target "foo" which is not built by this project.
</code>```

I just want to export the same configuration I use locally to the other (importing) project. I don't want to have to tell projectB about foo explicitly. Is there some way to accomplish this?

答:
I also can't find an ideal way to do this. But here is the workaround I'm using for now. It's extra work, and not DRY, but I think it achieves the right thing.

Imagine lib B depends on third party lib A. A either has a find module defined, or we can implement a custom find module for it. Both are doable. Assume we've already written FindA.cmake and stored in in ${CMAKE_SOURCE_DIR}/cmake. Also, let's assume that when you run cmake to generate B's build system, you provide A_ROOT to help cmake locate A.

Then in B's top-level CMakeLists.txt we need:

```<code># Use FindA.cmake, defined in the cmake/ directory.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
find_package(A REQUIRED)

# ... (define the B target here)...

# Copy the config file to the build dir
configure_file(cmake/BConfig.cmake cmake/BConfig.cmake @ONLY)

# Copy A's find module (skip this step if FindA is not custom).
configure_file(cmake/FindA.cmake cmake/FindA.cmake COPYONLY)

# Create the target export.
export(EXPORT BTargets
    FILE ${CMAKE_BINARY_DIR}/cmake/BTargets.cmake
    NAMESPACE B::
    )

# Register B so cmake can find B's config file.
export(PACKAGE B)
</code>```

Now in cmake/BConfig.cmake:

```<code># Get the exported find module onto the module path.
# This step is unnecessary if the find module is part of cmake.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")

# Store the root so that find_package will work.
# You may have to store other variables here, too, but
# the principle is just more of the same.
set(A_ROOT @A_ROOT@) # **Could optionally cache this.
find_package(A MODULE REQUIRED)

# The usual one-liner for a config file.
include("${CMAKE_CURRENT_LIST_DIR}/BTargets.cmake")
</code>```

Just to drive the solution home, let's look at a second example, Rocket this time using Boost, which already has a find module defined.

CMakeLists.txt:

```<code>option(Boost_USE_MULTITHREADED ON)
option(Boost_USE_STATIC_LIBS OFF)
find_package(Boost REQUIRED COMPONENTS filesystem program_options)

add_library(Rocket rocket.cpp)
target_link_libraries(Rocket
    PUBLIC Boost::filesystem
    PRIVATE Boost::program_options
    )

configure_file(cmake/BConfig.cmake cmake/BConfig.cmake @ONLY)

export(EXPORT RocketTargets
    FILE ${CMAKE_BINARY_DIR}/RocketTargets.cmake
    NAMESPACE Rocket::
    )
export(PACKAGE Rocket)
</code>```

Then cmake/RocketConfig.cmake would have:

```<code>set(BOOST_ROOT @BOOST_ROOT@ CACHE PATH "In case boost was relocated.")
set(Boost_USE_MULTITHREADED @Boost_USE_MULTITHREADED@)
set(Boost_USE_STATIC LIBS @Boost_USE_STATIC_LIBS@)
find_package(Boost REQUIRED COMPONENTS filesystem program_options)

include("${CMAKE_CURRENT_LIST_DIR}/RocketTargets.cmake")
</code>```

So yeah. It seems like too much typing. It seems like cmake should be able to generate all of that code from an export statement in CMakeLists.txt. But this strategy seems to achieve the goal.

Also, I haven't tested yet, but I suspect that, if your transitive dependency uses a CONFIG instead of a MODULE for find_package, it should be very easy just to add to CMAKE_PREFIX_PATH in your config file as well.

Edit (2021): Tsyvarev has pointed out the find_dependency() macro, which can simplify the above approach somewhat. Consider using that instead of find_package().

Title: Exporting an imported library

Body:
I have projectA, into which I'm importing a library with:

add_library(foo STATIC IMPORTED)
set_property(TARGET foo PROPERTY IMPORTED_LOCATION /path/to/foo.a)

I then use foo in several places within the project, and it all works fine.

A couple of directory levels down I want to export a library built within this project for use in yet another project with a completely disconnected CMake config. I've got:

...
target_link_libraries(thislib foo)
export(TARGETS thislib FILE /path/to/thislib.cmake)

The importing projectB also needs foo though (because the imported library needs it), and complains that it cannot find -lfoo. I tried adding it to the export command, but then I get:

CMake Error at thislib/CMakeLists.txt:37 (export):
  export given target "foo" which is not built by this project.

I just want to export the same configuration I use locally to the other (importing) project. I don't want to have to tell projectB about foo explicitly. Is there some way to accomplish this?

Body:
I also can't find an ideal way to do this. But here is the workaround I'm using for now. It's extra work, and not DRY, but I think it achieves the right thing.

Imagine lib B depends on third party lib A. A either has a find module defined, or we can implement a custom find module for it. Both are doable. Assume we've already written FindA.cmake and stored in in ${CMAKE_SOURCE_DIR}/cmake. Also, let's assume that when you run cmake to generate B's build system, you provide A_ROOT to help cmake locate A.

Then in B's top-level CMakeLists.txt we need:

# Use FindA.cmake, defined in the cmake/ directory.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_SOURCE_DIR}/cmake")
find_package(A REQUIRED)

# ... (define the B target here)...

# Copy the config file to the build dir
configure_file(cmake/BConfig.cmake cmake/BConfig.cmake @ONLY)

# Copy A's find module (skip this step if FindA is not custom).
configure_file(cmake/FindA.cmake cmake/FindA.cmake COPYONLY)

# Create the target export.
export(EXPORT BTargets
    FILE ${CMAKE_BINARY_DIR}/cmake/BTargets.cmake
    NAMESPACE B::
    )

# Register B so cmake can find B's config file.
export(PACKAGE B)

Now in cmake/BConfig.cmake:

# Get the exported find module onto the module path.
# This step is unnecessary if the find module is part of cmake.
list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}")

# Store the root so that find_package will work.
# You may have to store other variables here, too, but
# the principle is just more of the same.
set(A_ROOT @A_ROOT@) # **Could optionally cache this.
find_package(A MODULE REQUIRED)

# The usual one-liner for a config file.
include("${CMAKE_CURRENT_LIST_DIR}/BTargets.cmake")

Just to drive the solution home, let's look at a second example, Rocket this time using Boost, which already has a find module defined.

CMakeLists.txt:

option(Boost_USE_MULTITHREADED ON)
option(Boost_USE_STATIC_LIBS OFF)
find_package(Boost REQUIRED COMPONENTS filesystem program_options)

add_library(Rocket rocket.cpp)
target_link_libraries(Rocket
    PUBLIC Boost::filesystem
    PRIVATE Boost::program_options
    )

configure_file(cmake/BConfig.cmake cmake/BConfig.cmake @ONLY)

export(EXPORT RocketTargets
    FILE ${CMAKE_BINARY_DIR}/RocketTargets.cmake
    NAMESPACE Rocket::
    )
export(PACKAGE Rocket)

Then cmake/RocketConfig.cmake would have:

set(BOOST_ROOT @BOOST_ROOT@ CACHE PATH "In case boost was relocated.")
set(Boost_USE_MULTITHREADED @Boost_USE_MULTITHREADED@)
set(Boost_USE_STATIC LIBS @Boost_USE_STATIC_LIBS@)
find_package(Boost REQUIRED COMPONENTS filesystem program_options)

include("${CMAKE_CURRENT_LIST_DIR}/RocketTargets.cmake")

So yeah. It seems like too much typing. It seems like cmake should be able to generate all of that code from an export statement in CMakeLists.txt. But this strategy seems to achieve the goal.

Also, I haven't tested yet, but I suspect that, if your transitive dependency uses a CONFIG instead of a MODULE for find_package, it should be very easy just to add to CMAKE_PREFIX_PATH in your config file as well.

Edit (2021): Tsyvarev has pointed out the find_dependency() macro, which can simplify the above approach somewhat. Consider using that instead of find_package().


问:
wrong python html parsing
My code:

```<code>from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
print(kardiz)
</code>```

my output :

```<code>[<div class="views-row views-row-1 views-row-odd views-row-first">
<span class="views-field views-field-title"> <span class="field-content"><a href="/tr/node/479">Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri</a></span> </span>
<span class="views-field views-field-created"> <span class="field-content"><i class="fa fa-calendar"></i> Salı, Aralık 5, 2017 - 09:58 </span> </span> </div>]
</code>```

But I want to get just " Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri ". How can I achieve that?

答:
You can try like this as well to get the title and link from that page. I used css selector to get them:

```<code>from bs4 import BeautifulSoup
from urllib.parse import urljoin
import requests

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
res = requests.get(url)
soup = BeautifulSoup(res.text,'lxml')
for item in soup.select("#content .field-content a"):
    link = urljoin(url,item['href'])
    print("Title: {}\nLink: {}\n".format(item.text,link))
</code>```

Partial output:

```<code>Title: 2017-2018 Güz Dönemi Final Sınav Programı (TASLAK)
Link: http://yaz.tek.firat.edu.tr/tr/node/481

Title: NETAŞ İşyeri Eğitimi Mülakatları Hakkında Duyuru
Link: http://yaz.tek.firat.edu.tr/tr/node/480
</code>```

Title: wrong python html parsing

Body:
My code:

from bs4 import BeautifulSoup
import urllib.request

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
url_oku = urllib.request.urlopen(url)
soup = BeautifulSoup(url_oku, 'html.parser')
icerik = soup.find_all('div',attrs={'class':'views-row views-row-1 views-row-odd views-row-first'})
print(kardiz)

my output :

[

 Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri
  Salı, Aralık 5, 2017 - 09:58
]

But I want to get just " Grup-1, Grup-2, Grup-3, Grup-4 ve Grup-6 Öğrencileri İçin Staj Sunum Tarihleri ". How can I achieve that?

Body:
You can try like this as well to get the title and link from that page. I used css selector to get them:

from bs4 import BeautifulSoup
from urllib.parse import urljoin
import requests

url = "http://yaz.tek.firat.edu.tr/tr/duyurular"
res = requests.get(url)
soup = BeautifulSoup(res.text,'lxml')
for item in soup.select("#content .field-content a"):
    link = urljoin(url,item['href'])
    print("Title: {}\nLink: {}\n".format(item.text,link))

Partial output:

Title: 2017-2018 Güz Dönemi Final Sınav Programı (TASLAK)
Link: http://yaz.tek.firat.edu.tr/tr/node/481

Title: NETAŞ İşyeri Eğitimi Mülakatları Hakkında Duyuru
Link: http://yaz.tek.firat.edu.tr/tr/node/480


问:
What is the complexity of insertion operation for 1...n keys in BST and Splay tree?
If n keys 1,2,…,n are to be inserted in that order,

(a). to a normal BST (Binary Search Tree)

(b). to a Splay Tree

What would be the complexity in each case (a), b) ?

Is it O(log n) for both the cases? Or is it O(log n) for (a) and O(M log n) for (b) ?

答:
According to the Wikipedia Splay tree article, average insertion time is O(log n), and worst case is amortized O(log n). So your expected time to insert all the items into the Splay tree would be O(n log n).

The Binary search tree case depends on what kind of BST you're using. For a primitive BST, inserting items in order is the worst case because it creates a degenerate tree--a linked list. That's O(n) (where n is the number of items in the tree) per insertion. So insertion of all the items would require O(n^2).

Insertion into a degenerate tree is O(n) because the tree is essentially a linked list. After inserting the numbers [1, 2, 3] in order, your tree looks like this:

```<code>1
 \
  2
   \
    3
</code>```

If you then want to insert 4, the code has to look at each of the existing items, 1, 2, and 3, before adding 4 as the right child of 3. And when you go to insert 5, it again has to look at the previous four items. Each insertion has to look at all of the previous items. The total number of comparisons when inserting n items will be (n*(n-1))/2, which is O(n^2).

If you're using a self balancing binary search tree, then insertion is O(log n), and insertion of all the items will require O(n log n).

Body:
According to the Wikipedia Splay tree article, average insertion time is O(log n), and worst case is amortized O(log n). So your expected time to insert all the items into the Splay tree would be O(n log n).

The Binary search tree case depends on what kind of BST you're using. For a primitive BST, inserting items in order is the worst case because it creates a degenerate tree--a linked list. That's O(n) (where n is the number of items in the tree) per insertion. So insertion of all the items would require O(n^2).

Insertion into a degenerate tree is O(n) because the tree is essentially a linked list. After inserting the numbers [1, 2, 3] in order, your tree looks like this:

1
 \
  2
   \
    3

If you then want to insert 4, the code has to look at each of the existing items, 1, 2, and 3, before adding 4 as the right child of 3. And when you go to insert 5, it again has to look at the previous four items. Each insertion has to look at all of the previous items. The total number of comparisons when inserting n items will be (n*(n-1))/2, which is O(n^2).

If you're using a self balancing binary search tree, then insertion is O(log n), and insertion of all the items will require O(n log n).


问:
Angular injector error on component downgrading from v5 or v4 to angularJS
I've created simple angular5 component HelloComponent:

```<code>var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];
</code>```

Next I tried to use this component in my angularJS directive like:

```<code>angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))
</code>```

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV

答:
The error is telling you that it does not understand which provider you are talking about. I'm no expert in this area but you need to make sure that a system has been explicitly told which files it is using.

The good news is that you are not alone.

The "unknown provider" error appears, according to a Google which came back with lots of SO answers, to be caused by incorrect initialisation or order of including:

AngularJS Error: $injector:unpr Unknown Provider

AngularJS Error: [$injector:unpr] Unknown provider

Simply failing to specify the *.js file seems to be a really common cause.

Error: [$injector:unpr] Unknown provider: $routeProvider

As you are getting a very similar error across multiple different versions, it is safe to assume that the same cause exists in all cases. Version is not, therefore you problem. Look at file inclusion, file order, and object initialization - in that order.

Body:
I've created simple angular5 component HelloComponent:

var HelloComponent = function () {
};

HelloComponent.annotations = [
  new ng.core.Component({
    selector: 'hello-world',
    template: 'Hello World!'
  })
];

Next I tried to use this component in my angularJS directive like:

angular.module("app", [])
.directive("helloWorld", ng.upgrade.static.downgradeComponent(HelloComponent))

But on running this script I getting this error:

Error: [$injector:unpr] Unknown provider: $$angularLazyModuleRefProvider <- $$angularLazyModuleRef
  http://errors.angularjs.org/1.6.5/$injector/unpr?p0=%24%24angularLazyModuleRefProvider%20%3C-%20%24%24angularLazyModuleRef

See simple example with angular 5 and angularJS: http://plnkr.co/edit/dQJ2tgV2MuInT41ucjq1

How to fix this ?

ADDITIONAL INFO

Example for downgrading component from v4 to v1 also exists: https://hackernoon.com/angular-v4-hybrid-upgrade-application-73d5afba1e01

But when I trying to remake my app with this post, im getting another error:

Unknown provider: $$angularInjectorProvider

See example for v4: http://plnkr.co/edit/9Oxy0QeSg1FYve0cjGYw

Same example for v5 returns old error:

Unknown provider: $$angularLazyModuleRefProvider

See example for v5: http://plnkr.co/edit/eZScm8U41mGuuHJMjApV