问:
How to push onto Promise.all(Array)
I don't think this is possible with the native promise implementation, but here's the basic idea of what I want:

```<code>const promises = [
    getSomething(),
    getSomethingElse(),
];

// combine promises
const alldone = Promise.all(promises);

// Add a promise after the previous ones have started
promises.push(getAThirdThing());

// everything, including `getAThirdThing` is done
await allDone;
</code>```

In reality Promise.all() doesn't care that I pushed something onto the promises array.

Is there a similar pattern which accomplishes the same thing? Specifically, adding other promises to wait for, as they become known to a list of currently unresolved promises, arbitrarily, and without any requirement that any be added later.

I could do something like this instead:

```<code>const promises = [
    getSomething(),
    getSomethingElse(),
];
const alldone = Promise.all(promises);
await Promise.all([alldone, getAThirdThing()]);
</code>```

But I want to call .then() on allDone prior to adding getAThirdThing().

答:
To add promises to a set of promises and wait on a promise for them all to be fulfilled, with the ability to add additional promises to the set, there are at least two choices:

Create an onFulfilled handler, called by then that checks if more promises are waiting to be added, and if so returns a promise for them (all) to be settled chained to another promise using the same then handler. More or less akin to a recursive asynchronous method that adds promises if they are available. Keeping track of fulfilled results and matching them with promise operations, and avoiding uncaught rejection errors would still need attention.

Write a custom Promise static method or constructor that does what you want instead without using Promise.all.

As an example of 2., the PromiseGroup constructor below returns an object with

a promise` property that is settled with an array of values in the order promises were added to the group, and

an add method that adds promises to be settled in order of presentation.

function PromiseGroup() {
    var resolve;
    var reject;
    this.promise = new Promise( (r, j) => { resolve = r, reject = j});
    this.settled = false;

    const group = this;
    var numAdded = 0;
    var numSettled = 0;
    const values = [];
    const quickReject = reason => reject(reason);
    const fulfill = ( i, value) => {
        values[i] =  value;
        if( ++numSettled === numAdded) {
            resolve( values);
            group.settled = true;
        }
    };
    this.add = function() {
        if( group.settled) {
            console.trace();
            throw new Error("Can't add promises to a settled group");
        }
        for( var j = 0; j < arguments.length; ++j) {
            let i = numAdded + j;
            Promise.resolve( arguments[j])
            .then( value => fulfill( i, value), quickReject);
        }
        numAdded += j;
    };
}

//********************************************     and test:

async function test() {
  var group = new PromiseGroup();
  group.add( new Promise(resolve=> setTimeout( resolve=>resolve(1), 500, resolve)),
             new Promise(resolve=> setTimeout( resolve=>resolve(2), 600, resolve)));
  setTimeout( test2, 100, group);
  var values = await group.promise;
  // some more code
  return values
}

function test2( group) { // add more after await
  group.add( new Promise(resolve=> setTimeout( resolve=>resolve(3), 700, resolve)),
             new Promise(resolve=> setTimeout( resolve=>resolve(4), 400, resolve)));
}

test().then( values=>console.log(JSON.stringify(values)));```

The reasoning behind this answer is that Promise.all, and Promise.race are a minimal and low level set of promise aggregation methods and their presence need not preclude the development of new ones.

The wisdom of using PromiseGroup or similar is a separate consideration. Personally I would review overall asynchronous design of the application to see if optional promises could be combined with promise operations that determine their need, if possible, before ever reaching the Promise.all or group stage.

Title: How to push onto Promise.all(Array)

Body:
I don't think this is possible with the native promise implementation, but here's the basic idea of what I want:

const promises = [
    getSomething(),
    getSomethingElse(),
];

// combine promises
const alldone = Promise.all(promises);

// Add a promise after the previous ones have started
promises.push(getAThirdThing());

// everything, including `getAThirdThing` is done
await allDone;

In reality Promise.all() doesn't care that I pushed something onto the promises array.

Is there a similar pattern which accomplishes the same thing? Specifically, adding other promises to wait for, as they become known to a list of currently unresolved promises, arbitrarily, and without any requirement that any be added later.

I could do something like this instead:

const promises = [
    getSomething(),
    getSomethingElse(),
];
const alldone = Promise.all(promises);
await Promise.all([alldone, getAThirdThing()]);

But I want to call .then() on allDone prior to adding getAThirdThing().

Body:
To add promises to a set of promises and wait on a promise for them all to be fulfilled, with the ability to add additional promises to the set, there are at least two choices:

Create an onFulfilled handler, called by then that checks if more promises are waiting to be added, and if so returns a promise for them (all) to be settled chained to another promise using the same then handler. More or less akin to a recursive asynchronous method that adds promises if they are available. Keeping track of fulfilled results and matching them with promise operations, and avoiding uncaught rejection errors would still need attention.

Write a custom Promise static method or constructor that does what you want instead without using Promise.all.

As an example of 2., the PromiseGroup constructor below returns an object with

a promise` property that is settled with an array of values in the order promises were added to the group, and

an add method that adds promises to be settled in order of presentation.

function PromiseGroup() {
    var resolve;
    var reject;
    this.promise = new Promise( (r, j) => { resolve = r, reject = j});
    this.settled = false;

    const group = this;
    var numAdded = 0;
    var numSettled = 0;
    const values = [];
    const quickReject = reason => reject(reason);
    const fulfill = ( i, value) => {
        values[i] =  value;
        if( ++numSettled === numAdded) {
            resolve( values);
            group.settled = true;
        }
    };
    this.add = function() {
        if( group.settled) {
            console.trace();
            throw new Error("Can't add promises to a settled group");
        }
        for( var j = 0; j < arguments.length; ++j) {
            let i = numAdded + j;
            Promise.resolve( arguments[j])
            .then( value => fulfill( i, value), quickReject);
        }
        numAdded += j;
    };
}

//********************************************     and test:

async function test() {
  var group = new PromiseGroup();
  group.add( new Promise(resolve=> setTimeout( resolve=>resolve(1), 500, resolve)),
             new Promise(resolve=> setTimeout( resolve=>resolve(2), 600, resolve)));
  setTimeout( test2, 100, group);
  var values = await group.promise;
  // some more code
  return values
}

function test2( group) { // add more after await
  group.add( new Promise(resolve=> setTimeout( resolve=>resolve(3), 700, resolve)),
             new Promise(resolve=> setTimeout( resolve=>resolve(4), 400, resolve)));
}

test().then( values=>console.log(JSON.stringify(values)));

The reasoning behind this answer is that Promise.all, and Promise.race are a minimal and low level set of promise aggregation methods and their presence need not preclude the development of new ones.

The wisdom of using PromiseGroup or similar is a separate consideration. Personally I would review overall asynchronous design of the application to see if optional promises could be combined with promise operations that determine their need, if possible, before ever reaching the Promise.all or group stage.


来源: stackexchange

问:
$_FILES array only stores one file PHP
I am trying to allow my users to upload multiple files at one time. I have set up my form to allow multiples I believe; here is the code for that, so someone can help me to make sure that it is correct:

```<code><form class="well" action="" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="file">Add Documents Such As (Certifications, Degrees, Prior Job Offers, Etc) Here:</label><br>
        <label for="file">Select a file to upload</label>
        <input type="file" name="filesToUpload" id="filesToUpload" multiple>
    </div>
    <button class="glyphicon glyphicon-open-file" type="submit" name="submit"/>Submit
</form>
</code>```

Here is the code that I am attempting to use to get the selected files uploaded to my server:

```<code>if (isset($_POST['submit'])) {
    $file = $_FILES['filesToUpload'];
    foreach ($_FILES['filesToUpload'] as $file) {
        $fileName = $file['name'];
        echo $fileName;
        $fileTmpName = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];
        $fileType = $file['type'];

        $fileExt = explode('.', $fileName);
        $fileActualExt = strtolower(end($fileExt));

        $allowed = array('pdf', 'docx', 'doc', 'jpg', 'jpeg', 'txt', 'png');
        if (in_array($fileActualExt, $allowed)) {
            if ($fileError === 0) {
                if ($fileSize < 1000000) {
                    $fileNameNew = uniqid('', true).".".$fileActualExt;
                    $fileDestination = 'uploads/'.$fileNameNew;
                    move_uploaded_file($fileTmpName, $fileDestination);
                } else {
                    echo "Your file is too big!";
                  }
            } else {
                echo "There was an error uploading your file!";
              }
        } else {
            echo "You cannot upload files of this type!";
          }
    }
    header("Location: developer");
}
</code>```

The thing I have noticed, when I echo $file after I have selected multiple files it only shows the name of one of the files. I am not sure, but I have the feeling that is why I can only get one file to upload to the server when trying to upload multiple files.

Can someone confirm if this is the issue? If it is, what would be the best way to go about getting this working.

Edit: I have tried all the other suggestions that have been made around the site here. When I use <input type="file" name="filesToUpload[]" id="filesToUpload" multiple> it just breaks it. I get all these notices about undefined index for the I guess you call them extensions (based on what someone said below) when trying to break out the different parts of the file. I also get a notice about Array to String conversion. Using the brackets in the input also just jumps to the else statement about not being able to upload files of a certain type.

Here they are:

```<code>Notice: Array to string conversion in /var/www/html/dev/my-documents/upload-document.php on line 47
Array
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
</code>```

答:
```<code> You should
 <input type="file" name="filesToUpload" id="filesToUpload" multiple> instead of
<input type="file" name="filesToUpload[]" id="filesToUpload" multiple>
Array format

for more info visit [https://stackoverflow.com/questions/2704314/multiple-file-upload-in-php]
</code>```

ContentLicense: CC BY-SA 3.0

Title: $_FILES array only stores one file PHP

Body:
I am trying to allow my users to upload multiple files at one time. I have set up my form to allow multiples I believe; here is the code for that, so someone can help me to make sure that it is correct:

<form class="well" action="" method="post" enctype="multipart/form-data">

        Add Documents Such As (Certifications, Degrees, Prior Job Offers, Etc) Here:

        Select a file to upload
        <input type="file" name="filesToUpload" id="filesToUpload" multiple>

    <button class="glyphicon glyphicon-open-file" type="submit" name="submit"/>Submit
</form>

Here is the code that I am attempting to use to get the selected files uploaded to my server:

if (isset($_POST['submit'])) {
    $file = $_FILES['filesToUpload'];
    foreach ($_FILES['filesToUpload'] as $file) {
        $fileName = $file['name'];
        echo $fileName;
        $fileTmpName = $file['tmp_name'];
        $fileSize = $file['size'];
        $fileError = $file['error'];
        $fileType = $file['type'];

        $fileExt = explode('.', $fileName);
        $fileActualExt = strtolower(end($fileExt));

        $allowed = array('pdf', 'docx', 'doc', 'jpg', 'jpeg', 'txt', 'png');
        if (in_array($fileActualExt, $allowed)) {
            if ($fileError === 0) {
                if ($fileSize < 1000000) {
                    $fileNameNew = uniqid('', true).".".$fileActualExt;
                    $fileDestination = 'uploads/'.$fileNameNew;
                    move_uploaded_file($fileTmpName, $fileDestination);
                } else {
                    echo "Your file is too big!";
                  }
            } else {
                echo "There was an error uploading your file!";
              }
        } else {
            echo "You cannot upload files of this type!";
          }
    }
    header("Location: developer");
}

The thing I have noticed, when I echo $file after I have selected multiple files it only shows the name of one of the files. I am not sure, but I have the feeling that is why I can only get one file to upload to the server when trying to upload multiple files.

Can someone confirm if this is the issue? If it is, what would be the best way to go about getting this working.

Edit: I have tried all the other suggestions that have been made around the site here. When I use <input type="file" name="filesToUpload[]" id="filesToUpload" multiple> it just breaks it. I get all these notices about undefined index for the I guess you call them extensions (based on what someone said below) when trying to break out the different parts of the file. I also get a notice about Array to String conversion. Using the brackets in the input also just jumps to the else statement about not being able to upload files of a certain type.

Here they are:

Notice: Array to string conversion in /var/www/html/dev/my-documents/upload-document.php on line 47
Array
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54
You cannot upload files of this type!
Notice: Undefined index: name in /var/www/html/dev/my-documents/upload-document.php on line 49

Notice: Undefined index: tmp_name in /var/www/html/dev/my-documents/upload-document.php on line 51

Notice: Undefined index: size in /var/www/html/dev/my-documents/upload-document.php on line 52

Notice: Undefined index: error in /var/www/html/dev/my-documents/upload-document.php on line 53

Notice: Undefined index: type in /var/www/html/dev/my-documents/upload-document.php on line 54


问:
Amazon RDS manual snapshot conjunction with automated backup?
I've read through the Amazon doc, and searched through countless of posts in SO but still I've not been able to answer 2 questions.

Situation: As I understand, Amazon RDS snapshots are incremental. But how can manual snapshots play nice with automated snapshots feature ? Imagine I have created a script to snapshot the DB every day at 1 A.M. and copy the snapshot to another region. Then the snapshots will be:

```<code>+ Day 1 - 1 A.M.: snapshot 1 (manual) => copy to the other region (first time, full copy)
+ Day 1 - 6 A.M: snapshot 2 (automatic backup), in current region, not copy.
+ Day 2 - 1 A.M.: snapshot 3 (manual) => copy to the other region (incremental)
+ Day 2 - 6 A.M: snapshot 4 (automatic backup), in current region, not copy (incremental)
</code>```

Question 1:

snapshot 3 = changes since snapshot 1 or snapshot 3 = changes since snapshot 2 ?

Question 2:

If I just copy snapshot 1 and snapshot 3 (manual snapshots) to another region, is it enough to restore the database ?

In storage world, snapshot 3 = changes since snapshot 2, and we must have all the incremental snapshots (1+2+3+4) to reconstruct the original volume. But for AWS, there're implications and I'm not so sure.

Thank you.

答:
Question 1: snapshot 3 = changes since snapshot 2

Question 2: If you copy a snapshot to another region, the first copy will become a full snapshot and not an incremental and yes you would be able to restore the database from a copied snapshot. Subsequent snapshot copies will be incremental based upon the last copied snapshot.

Once a DB Snapshot is copied to a specific AWS Region, any subsequent
  copy operations of the DB Snapshots of the same DB Instance to that
  Region will only transfer the data that has changed since the last
  copy. Thus the subsequent copy operations transfer fewer amounts of
  data and complete faster.

copy of Amazon RDS DB Snapshots across AWS Regions

Body:
I've read through the Amazon doc, and searched through countless of posts in SO but still I've not been able to answer 2 questions.

Situation: As I understand, Amazon RDS snapshots are incremental. But how can manual snapshots play nice with automated snapshots feature ? Imagine I have created a script to snapshot the DB every day at 1 A.M. and copy the snapshot to another region. Then the snapshots will be:

+ Day 1 - 1 A.M.: snapshot 1 (manual) => copy to the other region (first time, full copy)
+ Day 1 - 6 A.M: snapshot 2 (automatic backup), in current region, not copy.
+ Day 2 - 1 A.M.: snapshot 3 (manual) => copy to the other region (incremental)
+ Day 2 - 6 A.M: snapshot 4 (automatic backup), in current region, not copy (incremental)

Question 1:

snapshot 3 = changes since snapshot 1 or snapshot 3 = changes since snapshot 2 ?

Question 2:

If I just copy snapshot 1 and snapshot 3 (manual snapshots) to another region, is it enough to restore the database ?

In storage world, snapshot 3 = changes since snapshot 2, and we must have all the incremental snapshots (1+2+3+4) to reconstruct the original volume. But for AWS, there're implications and I'm not so sure.

Thank you.


答:
```<code><input type="file" name="filesToUpload" id="filesToUpload" multiple>
</code>```

Its should be array. change the above code as below

```<code><input type="file" name="filesToUpload[]" id="filesToUpload" multiple>
</code>```

Title: $_FILES array only stores one file PHP

Body:
<input type="file" name="filesToUpload" id="filesToUpload" multiple>

Its should be array. change the above code as below

<input type="file" name="filesToUpload[]" id="filesToUpload" multiple>


问:
Question about Hibernate Mapping (One-TO-Many)
while in my path to learn Hibernate i am struck at a point so need you suggestion.
I have Three class A,B,C and there parent Class.
These Three class are only represnting three aspect only but in the underlying Database being mapped to same Table.

In My parent class i have refrences to these three classes as

```<code>private Set<A> airTransport =new HashSet<A>();
    private Set<B> roadTransport=new HashSet<B>();
    private Set<C> trainTransport=new HashSet<C>();
</code>```

and in the parent hbm file i have mapped them as

```<code> <set name="A" table="Test" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="A" />
        </set>
        <set name="B" table="TEST" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="B" />
        </set>
        <set name="C" table="TEST" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="C" />
        </set>
</code>```

i also have one more class which i have mapped as composite-element inside the three classes A,B and C

in my database i have three entries in Test table one for class  A, one for class B and last one is for class C
my table structure is

```<code>UUID
PARENTID
Other Fields
</code>```

when i retrived my ParentClass Object it and checked the size of Set it gives me the following figures
set for class A  has 3 elements
while B and C class's set have 1 element each and this is giving me problem while deleting the object.

i am clueless why this is behaving like the way.
any idea/suggestion in this regard will be helpfull

答:
You can use the 'where' attribute in the set xml element.  You will need some way of discriminating which rows should be in each set. See
http://docs.jboss.org/hibernate/core/3.6/reference/en-US/html/collections.html

example 7.6

ContentLicense: CC BY-SA 2.5

Body:
while in my path to learn Hibernate i am struck at a point so need you suggestion.
I have Three class A,B,C and there parent Class.
These Three class are only represnting three aspect only but in the underlying Database being mapped to same Table.

In My parent class i have refrences to these three classes as

private Set airTransport =new HashSet();
    private Set roadTransport=new HashSet();
    private Set<C> trainTransport=new HashSet<C>();

and in the parent hbm file i have mapped them as

 <set name="A" table="Test" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="A" />
        </set>
        <set name="B" table="TEST" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="B" />
        </set>
        <set name="C" table="TEST" inverse="true" lazy="true" cascade="save-update, delete">
            <key>
                <column name="PARENTID" />
            </key>
            <one-to-many class="C" />
        </set>

i also have one more class which i have mapped as composite-element inside the three classes A,B and C

in my database i have three entries in Test table one for class  A, one for class B and last one is for class C
my table structure is

UUID
PARENTID
Other Fields

when i retrived my ParentClass Object it and checked the size of Set it gives me the following figures
set for class A  has 3 elements
while B and C class's set have 1 element each and this is giving me problem while deleting the object.

i am clueless why this is behaving like the way.
any idea/suggestion in this regard will be helpfull


问:
Efficiently sum up values received from cherrypy web form using python
How can i sum up all the kwarg value i get from cherrypy, noting that the

number of kwarg values is unknown,
kwarg values are submitted from a webform
kwarg values look like kwargs['asset_cost_1'] where the number incrementally starts from 1 and could go 100 or above.

the following is an example but will definitly not work and i don't think is efficient

```<code>#first determine kwargs.get('asset_cost_1') has been received
asset_cost = 0
if kwargs.get('asset_cost_1'):
                for x in range(100):
                    kwarg = "kwargs['asset_cost_" + x + "']"
                    asset_cost = kwarg + asset_cost
</code>```

答:
This should do the trick:

```<code>sum(value for key, value in kwargs.items() if key.startswith('asset_cost_'))
</code>```

If you want it to be ugly, you can do this:

```<code>total = 0
for key, value in kwargs.items():
    if key.startswith('asset_cost_'):
        total += value
</code>```

And if your example was accurate, here it is as a rather dirty one liner:

```<code>sum(value for key, value in kwargs.items() if key.startswith('asset_cost_') and kwargs["asset_allocation_opex_" + key.split('_')[-1]] == "on")
</code>```

Body:
How can i sum up all the kwarg value i get from cherrypy, noting that the

number of kwarg values is unknown,
kwarg values are submitted from a webform
kwarg values look like kwargs['asset_cost_1'] where the number incrementally starts from 1 and could go 100 or above.

the following is an example but will definitly not work and i don't think is efficient

#first determine kwargs.get('asset_cost_1') has been received
asset_cost = 0
if kwargs.get('asset_cost_1'):
                for x in range(100):
                    kwarg = "kwargs['asset_cost_" + x + "']"
                    asset_cost = kwarg + asset_cost

Body:
This should do the trick:

sum(value for key, value in kwargs.items() if key.startswith('asset_cost_'))

If you want it to be ugly, you can do this:

total = 0
for key, value in kwargs.items():
    if key.startswith('asset_cost_'):
        total += value

And if your example was accurate, here it is as a rather dirty one liner:

sum(value for key, value in kwargs.items() if key.startswith('asset_cost_') and kwargs["asset_allocation_opex_" + key.split('_')[-1]] == "on")


问:
UWP Caliburn.Micro 2 x ActiveItem, How to do activate for 2 screens at same time?
in Caliburn.Micro, We can "active" a view in Parent-View.

To activate a screen in Parent-View,
It's easy.

```<code>ActivateItem(new Child1ViewModel());
</code>```

just it. but How to activate 2 view in same parent ?

答:
The comment answers are correct here, having ParentViewModel inherit from Conductor<T>.Collection.AllActive should get you the result you need.

If you really don't need all the collection functionality provided by the class above you can just use something like the following in the constructor of ParentViewModel.

```<code>ActiveItem.ConductWith(this);
</code>```

This will just wire the Activate event from ParentViewModel to activate the child. Ditto with deactivate.

Body:
in Caliburn.Micro, We can "active" a view in Parent-View.

To activate a screen in Parent-View,
It's easy.

ActivateItem(new Child1ViewModel());

just it. but How to activate 2 view in same parent ?

Body:
The comment answers are correct here, having ParentViewModel inherit from Conductor<T>.Collection.AllActive should get you the result you need.

If you really don't need all the collection functionality provided by the class above you can just use something like the following in the constructor of ParentViewModel.

ActiveItem.ConductWith(this);

This will just wire the Activate event from ParentViewModel to activate the child. Ditto with deactivate.


问:
Send parameters to IT Hit WebDAV Server
we would like to know if it is possible to send parameters to Webdav server (for example as query string path: http://server:8080/WebDavItHit/Notes.txt?param=value...") using IT Hit WebDAV Server Library for Java + JS Client.

We are looking forward to validate individual users using other application, and sending some parameters could be really useful.

We appreciate any way or alternative for doing this with your library.

答:
Some WebDAV clients, such as MS Office will truncate query string when saving a document. So to pass parameters, you will typically do this in file path, for example:</p>

```<code>https://server/[SessionID1234567890]/path/file.ext
</code>```

Title: Send parameters to IT Hit WebDAV Server

Body:
Some WebDAV clients, such as MS Office will truncate query string when saving a document. So to pass parameters, you will typically do this in file path, for example:

https://server/[SessionID1234567890]/path/file.ext


问:
Is it possible to deploy oracle forms application(.fmb and .fmx) into jBoss AS?
I am looking for a solution to migrate oracle forms applications from weblogic AS to jBoss AS. Is it possible? I googled it and went through a number of articles, but did not find a solution.

Any help  would be appreciated.

答:
Finally i reached at a conclusion!

The simple answer is NO.

Oracle forms apps are running using native compiler in fusion middleware AS. So if we want
to deploy the oracle forms into jBoss, we need to write compiler for each oracle forms depending on the app and its complexity.


问:
Java BlockingQueue take() vs poll()
When consuming values from a Queue in an infinite loop -- what would be more efficient:

Blocking on the Queue until a value is available via take()

```<code>while (value = queue.take()) { doSomething(value); }
</code>```

Sleeping for n milliseconds and checking if an item is available

```<code>while (true) {
    if ((value = queue.poll()) != null) { doSomething(value); }
    Thread.sleep(1000);
}
</code>```

答:
Be careful when you use take(). If you are using take() from a service and service has db connection.

If take() is returned after stale connection time out period then it will throw Stale connection exception.

Use poll for predefined waiting time and add null check for returned object.

ContentLicense: CC BY-SA 4.0

Title: Java BlockingQueue take() vs poll()

Body:
When consuming values from a Queue in an infinite loop -- what would be more efficient:

Blocking on the Queue until a value is available via take()

while (value = queue.take()) { doSomething(value); }

Sleeping for n milliseconds and checking if an item is available

while (true) {
    if ((value = queue.poll()) != null) { doSomething(value); }
    Thread.sleep(1000);
}


问:
How can I get the name of a form in my directive?
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

```<code>.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }
</code>```

答:
inside link function you can get form name like this way.</p>

```<code>var formName = element.find("ng-form").attr("name");
</code>```

Body:
I'm getting the ngModel name, but I also want to get the name of the form to which the element with the "validacion" directive belongs.

I strictly need to get the name of the form to which the HTML element belongs. I can have several forms so I need a dynamic solution. thank you very much

.directive('validacion', function ($timeout,$rootScope,validacionCampos,$compile) {

      return {
          restrict: 'AE',
          require: 'ngModel',

          link: function (scope, element, attrs, ngModel) {
                  if (!ngModel){
                          console.log("no hay modal")
                  return;
          }

Body:
inside link function you can get form name like this way.

var formName = element.find("ng-form").attr("name");


问:
How to enable a directory listing in Apache web server
I am not able to enable directory listing in my Apache web server. I have tried various solutions posted, but it is not working. I just freshly installed httpd 2.4.6 and enabled HTTPS using ssl.conf under the /etc/httpd/conf.d/ssl.conf directory and trying to access https://server.example.com/, but this is not listing the directory. These are the configuration in file ssl.conf:

```<code>DocumentRoot "/home/userx/Downloads/"
ServerName server.example.com:443
</code>```

Below is what it has in ssl.conf under the VirtualHost element. Files and the first Directory elements were already there when I installed, and I just added Directory for "/home/userx/Downloads". I want to browse the contents of /home/userx/Downloads when I access the URL https://server.example.com/. What am I missing here?

```<code><Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>
<Directory "/home/userx/Downloads">
  Options +Indexes
  AllowOverride all
</Directory>
</code>```

答:
According to the Apache documentation, found here, the DirectoryIndex directive needs to be specified in the site .conf file (typically found in /etc/apache2/sites-available on Linux).

Quoting from the documentation, it reads:

If no file from the DirectoryIndex directive can be located in the
directory, then mod_autoindex can generate a listing of the directory
contents. This is turned on and off using the Options directive. For
example, to turn on directory listings for a particular directory, you
can use:

```<code><Directory /usr/local/apache2/htdocs/listme>
  Options +Indexes
</Directory>
</code>```

To prevent directory listings (for security purposes, for example),
you should remove the Indexes keyword from every Options directive in
your configuration file. Or to prevent them only for a single
directory, you can use:

```<code><Directory /usr/local/apache2/htdocs/dontlistme>
  Options -Indexes
</Directory>
</code>```

Body:
I am not able to enable directory listing in my Apache web server. I have tried various solutions posted, but it is not working. I just freshly installed httpd 2.4.6 and enabled HTTPS using ssl.conf under the /etc/httpd/conf.d/ssl.conf directory and trying to access https://server.example.com/, but this is not listing the directory. These are the configuration in file ssl.conf:

DocumentRoot "/home/userx/Downloads/"
ServerName server.example.com:443

Below is what it has in ssl.conf under the VirtualHost element. Files and the first Directory elements were already there when I installed, and I just added Directory for "/home/userx/Downloads". I want to browse the contents of /home/userx/Downloads when I access the URL https://server.example.com/. What am I missing here?

<Files ~ "\.(cgi|shtml|phtml|php3?)$">
    SSLOptions +StdEnvVars
</Files>
<Directory "/var/www/cgi-bin">
    SSLOptions +StdEnvVars
</Directory>
<Directory "/home/userx/Downloads">
  Options +Indexes
  AllowOverride all
</Directory>

Body:
According to the Apache documentation, found here, the DirectoryIndex directive needs to be specified in the site .conf file (typically found in /etc/apache2/sites-available on Linux).

Quoting from the documentation, it reads:

If no file from the DirectoryIndex directive can be located in the
directory, then mod_autoindex can generate a listing of the directory
contents. This is turned on and off using the Options directive. For
example, to turn on directory listings for a particular directory, you
can use:

<Directory /usr/local/apache2/htdocs/listme>
  Options +Indexes
</Directory>

To prevent directory listings (for security purposes, for example),
you should remove the Indexes keyword from every Options directive in
your configuration file. Or to prevent them only for a single
directory, you can use:

<Directory /usr/local/apache2/htdocs/dontlistme>
  Options -Indexes
</Directory>


问:
How can I make TextBox Change Event filter GridView pointed to SQL Server?
I have the code below which works for MS Access.

```<code>Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click

    Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Excel\Desktop\Northwind_2012.mdb"
    Dim selectCommand As String
    Dim connection As New OleDbConnection(connectionString)

    selectCommand = "Select * From MyExcelTable where Fname Like '%" & TextBox1.Text & "%'"
    Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)

    With DataGridView1
        .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    End With

    Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
    Dim table As New DataTable()

    table.Locale = System.Globalization.CultureInfo.InvariantCulture

    Me.dataAdapter.Fill(table)
    Me.bindingSource1.DataSource = table

    Dim data As New DataSet()

    data.Locale = System.Globalization.CultureInfo.InvariantCulture

    DataGridView1.DataSource = Me.bindingSource1
    Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
    Me.DataGridView1.AutoResizeColumns( _
        DataGridViewAutoSizeColumnsMode.AllCells)

End Sub
</code>```

I want to do the same thing, but point to a SQL Server query, and not an Access query.  Does anyone know how to do that?  If so, please do share.

答:
With some light testing, the script below seems to work as desired.

```<code>Imports System.Data.SqlClient

Public Class Form1
    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim con As SqlConnection = New SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS; Integrated Security=true; Initial Catalog=NORTHWND")
        con.Open()
        Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Categories", con)
        da.Fill(ds, "Cat")
        DataGridView1.DataSource = ds.Tables("Cat")

    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        ds.Tables("Cat").DefaultView.RowFilter = "[CategoryName] LIKE '*" & TextBox1.Text & "*'"
    End Sub

End Class
</code>```

I'll look into that timer option tomorrow.  That's very clever!  Thanks for the tip!!

Body:
I have the code below which works for MS Access.

Private Sub TextBox1_TextChanged(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged, TextBox1.Click

    Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Excel\Desktop\Northwind_2012.mdb"
    Dim selectCommand As String
    Dim connection As New OleDbConnection(connectionString)

    selectCommand = "Select * From MyExcelTable where Fname Like '%" & TextBox1.Text & "%'"
    Me.dataAdapter = New OleDbDataAdapter(selectCommand, connection)

    With DataGridView1
        .AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
        .AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.ColumnHeader
    End With

    Dim commandBuilder As New OleDbCommandBuilder(Me.dataAdapter)
    Dim table As New DataTable()

    table.Locale = System.Globalization.CultureInfo.InvariantCulture

    Me.dataAdapter.Fill(table)
    Me.bindingSource1.DataSource = table

    Dim data As New DataSet()

    data.Locale = System.Globalization.CultureInfo.InvariantCulture

    DataGridView1.DataSource = Me.bindingSource1
    Me.DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.Aqua
    Me.DataGridView1.AutoResizeColumns( _
        DataGridViewAutoSizeColumnsMode.AllCells)

End Sub

I want to do the same thing, but point to a SQL Server query, and not an Access query.  Does anyone know how to do that?  If so, please do share.

Body:
With some light testing, the script below seems to work as desired.

Imports System.Data.SqlClient

Public Class Form1
    Dim ds As New DataSet

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Dim con As SqlConnection = New SqlConnection("Data Source=EXCEL-PC\SQLEXPRESS; Integrated Security=true; Initial Catalog=NORTHWND")
        con.Open()
        Dim da As SqlDataAdapter = New SqlDataAdapter("SELECT * FROM Categories", con)
        da.Fill(ds, "Cat")
        DataGridView1.DataSource = ds.Tables("Cat")

    End Sub

    Private Sub TextBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
        ds.Tables("Cat").DefaultView.RowFilter = "[CategoryName] LIKE '*" & TextBox1.Text & "*'"
    End Sub

End Class

I'll look into that timer option tomorrow.  That's very clever!  Thanks for the tip!!


问:
Flask render_template() & **locals() arg not working... Won't display python variables in HTML text
so I am very new to flask and am tinkering around with the CTypes module aswell - playing around with C & C++ files compiled in .so files to utilize in Python...
I have a simple function imported into python using CTypes and then display the return value of the function (A random number to the power of two; x^2) using Flask into an html file along with a little sample introduction in case I were to stumble on this file a year from now - I would clearly know why I made this random sample.
Now, that's all fine and dandy but, I heard on the street of the internets I can import multiple(all) my python variables into my HTML template using **locals().
I have seen others get this to work, but alas - I cannot...
I'll whip up a Python function to replace the C++ file so you all don't have to mess with it... That works fine and is simply a part of this file and not inherently apart of the problem. I am naive enough to were I am overlooking something completely and the CTypes module is the root of this dilemma possibly.

```<code>from flask import Flask, render_template
# disabled the CTypes module for your convenience...
# from ctypes import *
def c_plus_plus_replacement(x):
    return pow(x, 2)

# libpy = CDLL("./libpy.so")
# value = libpy.main(10)

value = c_plus_plus_replacement(5)
name = "Michael"

app = Flask(__name__)

@app.route("/")
def index():
    # ---- The problem is at this return statement to render the HTML template...
    # render_template("base.html", value=value, name=name) works fine, but I would like this statement to work...
    return render_template("base.html", value=value)

if __name__ == '__main__':
    app.run(debug=False)
</code>```

Let me know if you can help! :)

答:
As it appears in your code, name and value are defined globally, therefore are not local to the function index, so they wouldn't appear in locals() when you call locals from within the index function.

This would work if you moved these inside the function...

```<code>def index():
    value = c_plus_plus_replacement(5)
    name = "Michael"
    return render_template('base.html', **locals())
</code>```

This would make the names value and name available in the template being rendered.

Body:
so I am very new to flask and am tinkering around with the CTypes module aswell - playing around with C & C++ files compiled in .so files to utilize in Python...
I have a simple function imported into python using CTypes and then display the return value of the function (A random number to the power of two; x^2) using Flask into an html file along with a little sample introduction in case I were to stumble on this file a year from now - I would clearly know why I made this random sample.
Now, that's all fine and dandy but, I heard on the street of the internets I can import multiple(all) my python variables into my HTML template using **locals().
I have seen others get this to work, but alas - I cannot...
I'll whip up a Python function to replace the C++ file so you all don't have to mess with it... That works fine and is simply a part of this file and not inherently apart of the problem. I am naive enough to were I am overlooking something completely and the CTypes module is the root of this dilemma possibly.

from flask import Flask, render_template
# disabled the CTypes module for your convenience...
# from ctypes import *
def c_plus_plus_replacement(x):
    return pow(x, 2)

# libpy = CDLL("./libpy.so")
# value = libpy.main(10)

value = c_plus_plus_replacement(5)
name = "Michael"

app = Flask(__name__)

@app.route("/")
def index():
    # ---- The problem is at this return statement to render the HTML template...
    # render_template("base.html", value=value, name=name) works fine, but I would like this statement to work...
    return render_template("base.html", value=value)

if __name__ == '__main__':
    app.run(debug=False)

Let me know if you can help! :)

Body:
As it appears in your code, name and value are defined globally, therefore are not local to the function index, so they wouldn't appear in locals() when you call locals from within the index function.

This would work if you moved these inside the function...

def index():
    value = c_plus_plus_replacement(5)
    name = "Michael"
    return render_template('base.html', **locals())

This would make the names value and name available in the template being rendered.


问:
CSSMERR_TP_NOT_TRUSTED error
I did everything according to documentation.i marked both the Apple WorldWide Developer certificate as always trusted..

and the iPhone Distribution one as Always trusted, but i faced following error message.

```<code>/Users/keyss/Desktop/Deep/Free_Version/######/build/Release-iphoneos/####.app: replacing invalid existing  signature.
/Users/keyss/Desktop/Deep/Free_Version/######/build/Release-iphoneos/####.app: CSSMERR_TP_NOT_TRUSTED
</code>```

One thing more, I run the release that made it fine work on iphone.(with this error)

答:
You need to download the Apple WWDR intermediate certificate from the Provisioning Portal.  You can find the certificate in the "Certificates" tab in the portal.  After downloading, just drag the certificate to the Keychain Access application.

This should resolve your issue.

Title: CSSMERR_TP_NOT_TRUSTED error

Body:
I did everything according to documentation.i marked both the Apple WorldWide Developer certificate as always trusted..

and the iPhone Distribution one as Always trusted, but i faced following error message.

/Users/keyss/Desktop/Deep/Free_Version/######/build/Release-iphoneos/####.app: replacing invalid existing  signature.
/Users/keyss/Desktop/Deep/Free_Version/######/build/Release-iphoneos/####.app: CSSMERR_TP_NOT_TRUSTED

One thing more, I run the release that made it fine work on iphone.(with this error)


问:
Format Exception - Catch and Try
I want to test catching format exceptions, but the program crashes if I try to enter any words. How can I make my program catch Exceptions without crashing?

```<code>string words;
int[] number;
int i = 0;

while (true)
{
    Console.WriteLine("How many numbers would you like to enter? ");
    words = Console.ReadLine();

    if (isInteger(words))
    {
        number = new int[Convert.ToInt32(words)];
        Console.WriteLine("Please enter your numbers: ");

        for (i = 0; i < number.Length; ++i)
        {
            number[i] = Convert.ToInt32(Console.ReadLine());
            isInteger(words);
        }
    }
}
</code>```

isInteger method:

```<code>private static bool isInteger(string words)
{
    try
    {
         return true;
    }
    catch (FormatException)
    {
        return false;
    }
}
</code>```

答:
If you want to catch the exceptions thrown by the calls to Convert Convert.ToInt32(words) or Convert.ToInt32(Console.ReadLine()) they need to be wrapped in the try catch block.  Any catch only handles the exceptions that occur inside the preceding try. So, for example

```<code>try
{
  number = new int[Convert.ToInt32(words);
}
catch (FormatException ex)
{
  // Do something here ex is needed if you want to look at the exception
}
</code>```

Or you could wrap it all in one try catch

```<code>try
{
  number = new int[Convert.ToInt32(words);
  Console.WriteLine("Please enter your numbers: ");

  for (i = 0; i < number.Length; ++i)
  {
    number[i] = Convert.ToInt32(Console.ReadLine());
    isInteger(words);
  }
}
catch (FormatException ex)
{
  // Do something here ex is needed if you want to look at the exception
}
</code>```

isInteger will never have an exception to handle because all it does is return true which will never except.  If you want to handle an exception in a function, either the function has to make the call that will except, or be called in the catch block.

Title: Format Exception - Catch and Try

Body:
I want to test catching format exceptions, but the program crashes if I try to enter any words. How can I make my program catch Exceptions without crashing?

string words;
int[] number;
int i = 0;

while (true)
{
    Console.WriteLine("How many numbers would you like to enter? ");
    words = Console.ReadLine();

    if (isInteger(words))
    {
        number = new int[Convert.ToInt32(words)];
        Console.WriteLine("Please enter your numbers: ");

        for (i = 0; i < number.Length; ++i)
        {
            number[i] = Convert.ToInt32(Console.ReadLine());
            isInteger(words);
        }
    }
}

isInteger method:

private static bool isInteger(string words)
{
    try
    {
         return true;
    }
    catch (FormatException)
    {
        return false;
    }
}

Body:
If you want to catch the exceptions thrown by the calls to Convert Convert.ToInt32(words) or Convert.ToInt32(Console.ReadLine()) they need to be wrapped in the try catch block.  Any catch only handles the exceptions that occur inside the preceding try. So, for example

try
{
  number = new int[Convert.ToInt32(words);
}
catch (FormatException ex)
{
  // Do something here ex is needed if you want to look at the exception
}

Or you could wrap it all in one try catch

try
{
  number = new int[Convert.ToInt32(words);
  Console.WriteLine("Please enter your numbers: ");

  for (i = 0; i < number.Length; ++i)
  {
    number[i] = Convert.ToInt32(Console.ReadLine());
    isInteger(words);
  }
}
catch (FormatException ex)
{
  // Do something here ex is needed if you want to look at the exception
}

isInteger will never have an exception to handle because all it does is return true which will never except.  If you want to handle an exception in a function, either the function has to make the call that will except, or be called in the catch block.


问:
Cannot import module from Powershell script using Jenkins
I am trying to use Psake to build my Asp.Net MVC Solution on Jenkins Server. I have the Powershell scripts and Psake scripts checked in to source code. I have created a bootstrapper file build.ps1 that imports and invokes Psake.

Import-Module .\Psake.4.5.0\psake.psm1

```<code>    Invoke-Psake -buildFile .\default.ps1 `
        -taskList Default `
        -framework '4.6' `
        -parameters @{'solutionFilePath'='..\Application.sln'}
</code>```

All my tasks are defined in the default.ps1 file which I am trying to invoke. Locally when I run the script, the Psake module is imported and everything works. On Jenkins server however I get the following error:

```<code>Import-Module : The specified module '.\Psake.4.5.0\psake.psm1' was not loaded
because no valid module file was found in any module directory.At C:\Program
Files (x86)\Jenkins\workspace\Atmosphere\Build\Build.ps1:9 char:1
+ Import-Module .\Psake.4.5.0\psake.psm1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (.\Psake.4.5.0\psake.psm1:S
   tring) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm
   ands.ImportModuleCommand
</code>```

I am new to Jenkins, having used Team City previously and I have double checked that the Psake module is indeed being copied to the Jenkins Workspace.

This is how I am invoking the Build.ps1 from Jenkins

Powershell.exe -noprofile -executionpolicy Bypass -file .\Build\Build.ps1

Can someone please point me to what I am doing wrong?

答:
Ok I was finally able to resolve the problem and wanted to share the solution in case someone else runs into it. When running Powershell Script .\ is automatically resolved to current directory. However when we are executing our Script from Jenkins, we need to reference path of our Jenkins Workspace and use full path. To do that, Jenkins provides variable $ENV:WORKSPACE

Everywhere I was using .\ I changed it to use $ENV:WORKSPACE

so

Import-Module .\Psake.4.5.0\psake.psm1 became

Import-Module $ENV:WORKSPACE\Build\Psake.4.5.0\psake.psm1

And it started working!

Body:
I am trying to use Psake to build my Asp.Net MVC Solution on Jenkins Server. I have the Powershell scripts and Psake scripts checked in to source code. I have created a bootstrapper file build.ps1 that imports and invokes Psake.

Import-Module .\Psake.4.5.0\psake.psm1

    Invoke-Psake -buildFile .\default.ps1 `
        -taskList Default `
        -framework '4.6' `
        -parameters @{'solutionFilePath'='..\Application.sln'}

All my tasks are defined in the default.ps1 file which I am trying to invoke. Locally when I run the script, the Psake module is imported and everything works. On Jenkins server however I get the following error:

Import-Module : The specified module '.\Psake.4.5.0\psake.psm1' was not loaded
because no valid module file was found in any module directory.At C:\Program
Files (x86)\Jenkins\workspace\Atmosphere\Build\Build.ps1:9 char:1
+ Import-Module .\Psake.4.5.0\psake.psm1
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ResourceUnavailable: (.\Psake.4.5.0\psake.psm1:S
   tring) [Import-Module], FileNotFoundException
    + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Comm
   ands.ImportModuleCommand

I am new to Jenkins, having used Team City previously and I have double checked that the Psake module is indeed being copied to the Jenkins Workspace.

This is how I am invoking the Build.ps1 from Jenkins

Powershell.exe -noprofile -executionpolicy Bypass -file .\Build\Build.ps1

Can someone please point me to what I am doing wrong?


问:
How to show a dynamic content in the same page using Angularjs 1.6?
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

```<code>   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}
</code>```

Script.js

```<code>app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);
</code>```

News.html

```<code><div class="container-fluid">

    <div class="row">

        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="NewsRendering">
                <div ng-repeat="NewsData in News.Articles">
                    <h3>{{NewsData.Title}}</h3>
                    <p>{{NewsData.Abstract}}</p>
                    <a data-ng-href="/AngularTask/NewsViewer.html">more</a>
                </div>
            </div>
        </div>

        <div class="col-md-4 questionnaire">
            <h3>Questionnaire of the day</h3>
        </div>

    </div>

</div>
</code>```

NewsViewer.html

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Articles[0].Title}}</h3>
                    <p>{{News.Articles[0].Abstract}}</p>
                    <p>{{News.Articles[0].Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Articles[0].Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

答:
I think what you need is using 'ng-repeat' to show the Array Articles and '$http.get()' to load the json.file "dynamically" as you want.

ng-repeat : angularjs docs

load JSON :  #1 see this link, loading a json file
            #2 see this link, loading a json file

Body:
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}

Script.js

app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);

News.html

{{NewsData.Title}}

{{NewsData.Abstract}}

                    more

Questionnaire of the day

NewsViewer.html

{{News.Articles[0].Title}}

{{News.Articles[0].Abstract}}

{{News.Articles[0].Body}}

Comments

{{News.Articles[0].Comments[0]}}

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.


问:
How do I center a row of images?
English major here; I know practically nothing about coding, so please use VERY BASIC language. I need to know for my book publishing class website. I'm trying to align rows of images for our "Team Members" page. How do I do that? Below is the first row of images. Right now, they're shifted to the left.

 Publishers

 Mike
Course Director

 Mackenzie
Publisher

 Liz
Associate Publisher

 Mia
Publishing Assistant

```

答:
Use  tag to center anything...
Hope this helps...

 Publishers

 Mike
Course Director

 Mackenzie
Publisher

 Liz
Associate Publisher

 Mia
Publishing Assistant

        ```

Title: How do I center a row of images?

Body:
Use <center> tag to center anything...
Hope this helps...

<h3> Publishers </h3>
<center>
        <div class="box alt">
            <div class="row"> <!-- % changes space between pictures -->
                <div class="2u"><span class="image fit"><img src="images/headshots/mike.JPG" alt="" /><p> Mike<br>Course Director</p></span></div>
                <div class="2u"><span class="image fit"><img src="images/headshots/mackenzie.JPG" alt="" /><p> Mackenzie<br>Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="images/headshots/liz.JPG" alt="" /><p> Liz<br>Associate Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="images/headshots/mia.JPG" alt="" /><p> Mia<br>Publishing Assistant</p></span></div>
            </div>

        </div>
        </center>


问:
Caliburn.Micro binding parent property in Child View. ( UWP )
in Caliburn.Micro, I want to bind Parent property in Child View(ViewModel).

First is simple example.

This is Child View(XAML).

```<code><UserControl
x:Class="Bg7Uwp1.Views.App.DerLayout.Der2View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:micro="using:Caliburn.Micro"
xmlns:local="using:Bg7Uwp1.Controls"
mc:Ignorable="d"
x:Name="RootDer2">

<TextBlock Text="{Binding DataContext.hello, ElementName=RootDer2}"/>
</code>```

This is Child ViewModel.

```<code>public class Der2ViewModel : Conductor<Screen>
{
    public Der2ViewModel()
    {
    }
}
</code>```

This is parent View Model.

```<code>public string _hello = "HELLOWORLD!";
    public string hello
    {
        get { return _hello; }
        set
        {
            this.Set(ref _hello, value);
        }
    }
</code>```

and this is parent View.

```<code><UserControl
x:Class="Bg7Uwp1.Views.App.SpectrumView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:micro="using:Caliburn.Micro"
xmlns:local="using:Bg7Uwp1.Controls"
mc:Ignorable="d"
x:Name="Root"
d:DesignHeight="800"
d:DesignWidth="1000">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <ContentControl x:Name="ActiveItem"
                    Grid.Row="0"
                    HorizontalContentAlignment="Stretch"
                    VerticalContentAlignment="Stretch"/>

</Grid>
</UserControl>
</code>```

Above is just example. I used simple. and I want to bind without "x:Name". because "TextBlock" is final target to bind. I want to bind a custom control in ChildView.

This is my current CustomControl in Child View.

```<code>     <local:SensorMeter

        x:Name="DerRMeter"
        HorizontalAlignment="Center"
        DerThreashold1Svh="{Binding DerMeters[1].DerThreashold1Svh, ElementName=RootDer2}"
        DerThreashold2Svh="{Binding DerMeters[1].DerThreashold2Svh, ElementName=RootDer2}"
        DerSvh="{Binding DerMeters[1].DerSvh, ElementName=RootDer2}"
        Title="{Binding DataContext.DerMeters[1].Title, ElementName=RootDer2}"
        connectionDeviceStatusEnum="{Binding DerMeters[1].connectionDeviceStatusEnum, ElementName=RootDer2}"
        ticketThresholdType="{Binding DerMeters[1].ticketThresholdType, ElementName=RootDer2}"
        device="{Binding DerMeters[1].device, ElementName=RootDer2}"
        micro:Message.Attach="[Event DoubleTapped]=[Action Click_DoubleTapped(1)];[Event Tapped]=[Action Click_Tapped(1)]"

        />
</code>```

This is my current Parent View Model.

```<code>public ObservableCollection<DerMeter> DerMeters
    {
        get { return _derMeters; }
        set
        {
            this.Set(ref _derMeters, value);
        }
    }
</code>```

Question

How to bind "Parent property" to Child View ??

I found some helpful links.. but I can not make yet...

link

link

link

link

答: I've posted an answer on GitHub, but the gist of it is that if you're using the out of the box Screen and Conductor classes then the view model will have a Parent property which you can use to create bindings to a view models parent conductor's properties.

Body:
in Caliburn.Micro, I want to bind Parent property in Child View(ViewModel).

First is simple example.

This is Child View(XAML).

<UserControl
x:Class="Bg7Uwp1.Views.App.DerLayout.Der2View"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:micro="using:Caliburn.Micro"
xmlns:local="using:Bg7Uwp1.Controls"
mc:Ignorable="d"
x:Name="RootDer2">

<TextBlock Text="{Binding DataContext.hello, ElementName=RootDer2}"/>

This is Child ViewModel.

public class Der2ViewModel : Conductor<Screen>
{
    public Der2ViewModel()
    {
    }
}

This is parent View Model.

public string _hello = "HELLOWORLD!";
    public string hello
    {
        get { return _hello; }
        set
        {
            this.Set(ref _hello, value);
        }
    }

and this is parent View.

<UserControl
x:Class="Bg7Uwp1.Views.App.SpectrumView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:controls="using:Microsoft.Toolkit.Uwp.UI.Controls"
xmlns:micro="using:Caliburn.Micro"
xmlns:local="using:Bg7Uwp1.Controls"
mc:Ignorable="d"
x:Name="Root"
d:DesignHeight="800"
d:DesignWidth="1000">

<Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">

    <ContentControl x:Name="ActiveItem"
                    Grid.Row="0"
                    HorizontalContentAlignment="Stretch"
                    VerticalContentAlignment="Stretch"/>

</Grid>
</UserControl>

Above is just example. I used simple. and I want to bind without "x:Name". because "TextBlock" is final target to bind. I want to bind a custom control in ChildView.

This is my current CustomControl in Child View.

     <local:SensorMeter

        x:Name="DerRMeter"
        HorizontalAlignment="Center"
        DerThreashold1Svh="{Binding DerMeters[1].DerThreashold1Svh, ElementName=RootDer2}"
        DerThreashold2Svh="{Binding DerMeters[1].DerThreashold2Svh, ElementName=RootDer2}"
        DerSvh="{Binding DerMeters[1].DerSvh, ElementName=RootDer2}"
        Title="{Binding DataContext.DerMeters[1].Title, ElementName=RootDer2}"
        connectionDeviceStatusEnum="{Binding DerMeters[1].connectionDeviceStatusEnum, ElementName=RootDer2}"
        ticketThresholdType="{Binding DerMeters[1].ticketThresholdType, ElementName=RootDer2}"
        device="{Binding DerMeters[1].device, ElementName=RootDer2}"
        micro:Message.Attach="[Event DoubleTapped]=[Action Click_DoubleTapped(1)];[Event Tapped]=[Action Click_Tapped(1)]"

        />

This is my current Parent View Model.

public ObservableCollection<DerMeter> DerMeters
    {
        get { return _derMeters; }
        set
        {
            this.Set(ref _derMeters, value);
        }
    }

Question

How to bind "Parent property" to Child View ??

I found some helpful links.. but I can not make yet...

link

link

link

link


问:
JWTGenerateCommand::handle() does not exist
I am using Laravel 5.4 and JWT Auth Library for user authentication in API development. After installation while i am running php artisan jwt:generate then it throws me error of

```<code>Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist
</code>```

Any idea what i am missing ?

答:
Change fire() function to handle() in this path
vendor/tymon/jwt-auth/src/commands/JWTGenerateCommand.php</p>

Body:
I am using Laravel 5.4 and JWT Auth Library for user authentication in API development. After installation while i am running php artisan jwt:generate then it throws me error of

Method Tymon\JWTAuth\Commands\JWTGenerateCommand::handle() does not exist

Any idea what i am missing ?


答:
```<code><head>
    <link rel="stylesheet" href="styles.css" type="text/css"/>
</head>
</code>```

This is a severe problem with css that is resolved with flex

styles.css

```<code>.row {
    display: flex;
    align-items: center;     /* vertical centering   */
    justify-content: center; /* horizontal centering */
}
</code>```

Title: How do I center a row of images?

Body:
English major here; I know practically nothing about coding, so please use VERY BASIC language. I need to know for my book publishing class website. I'm trying to align rows of images for our "Team Members" page. How do I do that? Below is the first row of images. Right now, they're shifted to the left.

 Publishers

 Mike
Course Director

 Mackenzie
Publisher

 Liz
Associate Publisher

 Mia
Publishing Assistant

Body:
<head>
    <link rel="stylesheet" href="styles.css" type="text/css"/>
</head>

This is a severe problem with css that is resolved with flex

styles.css

.row {
    display: flex;
    align-items: center;     /* vertical centering   */
    justify-content: center; /* horizontal centering */
}


问:
Update Component State (And UI) With Random Word From Array At Set Interval
I'd like to update a word in a React component every second with a random value from an array. The state seems to update at the interval just fine in DevTools, but there is a weird bug in the browser that I can't seem to pinpoint:
 the text flashes, almost as if it's "scrolling" through the old strings to the new one. Any advice on how to smooth this out would be much appreciated!

import React, { Component } from 'react';

class App extends Component {
  state = {
    name: ""
  }
  getWord = () => {
    let randomWords = ["Friend", "Enemy", "Santa"];
    const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)];

    this.setState({
      name: randomWord
    });
  }

  render() {
    setInterval(this.getWord, 1000);
    return (

{this.state.name}

    );
  }
}

export default App;```

答:
The problem is the setInterval in render(). Every second you get another ine, so by the tenth flash, it's rerendering 10 times, hence the flicker. Render methods should have no side effects, as this is adding another interval every time it renders. Try it in componentDidMount:

```<code>import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: ""
    }
  }

  componentDidMount = () => {
    setInterval(this.getWord, 1000);
  }

  getWord = () => {
    let randomWords = ["Friend", "Enemy", "Santa"];
    const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)];

    console.log('new word', randomWord)
    this.setState({
      name: randomWord
    });
  }

  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
}

export default App
</code>```

Body:
The problem is the setInterval in render(). Every second you get another ine, so by the tenth flash, it's rerendering 10 times, hence the flicker. Render methods should have no side effects, as this is adding another interval every time it renders. Try it in componentDidMount:

import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props)
    this.state = {
      name: ""
    }
  }

  componentDidMount = () => {
    setInterval(this.getWord, 1000);
  }

  getWord = () => {
    let randomWords = ["Friend", "Enemy", "Santa"];
    const randomWord = randomWords[Math.floor(Math.random() * randomWords.length)];

    console.log('new word', randomWord)
    this.setState({
      name: randomWord
    });
  }

  render() {
    return (
      <div>
        <h1>{this.state.name}</h1>
      </div>
    );
  }
}

export default App


问:
JS: Posting form directly
If on document.ready, I want my form to auto post itself, is this possible?

So when the document has loaded, then it posts itself and takes to the action="" (in this case is ?upload=true).

I heard about $.post() jquery, but this is just for posting in the background?

答:
$.post() is an AJAX call and will not force the entire page to postback.

you may want to try

```<code>$(document).ready(function(){
     var form = $("#yourformid");
     form.submit();
});
</code>```

Title: JS: Posting form directly

Body:
$.post() is an AJAX call and will not force the entire page to postback.

you may want to try

$(document).ready(function(){
     var form = $("#yourformid");
     form.submit();
});


答:
You can also use this to learn css.

.row {
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h3> Publishers </h3>
        <div class="box alt">
            <div class="row"> <!-- % changes space between pictures -->
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mike<br>Course Director</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mackenzie<br>Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Liz<br>Associate Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mia<br>Publishing Assistant</p></span></div>
            </div>
        </div></code>```

Title: How do I center a row of images?

Body:
You can also use this to learn css.

.row {
  text-align: center;
}

<h3> Publishers </h3>
        <div class="box alt">
            <div class="row"> <!-- % changes space between pictures -->
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mike<br>Course Director</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mackenzie<br>Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Liz<br>Associate Publisher</p></span></div>
                <div class="2u"><span class="image fit"><img src="https://cdn.sstatic.net/Sites/stackoverflow/img/apple-touch-icon@2.png?v=73d79a89bded" alt="" /><p> Mia<br>Publishing Assistant</p></span></div>
            </div>
        </div>


问:
How do I distribute updates to a Access database front end?
I've got an Access 2007 database that I developed which connects to SQL Server for the actual data storage.  I used the Package Solution Wizard to create a distributable installer which included access runtime (with an ACCDE file) which I went around and installed on 15 or so PCs.  Anyway, my question is, what is the best way to distribute updates to this database?  Right now I'd need to go around and remove and reinstall.  That's not a problem... I was just wondering if there was another way.

I've tried leaving the front end on a network share but it seems that most people suggest storing the front-end on the local machine, which makes sense.  The problems I've run into when I leave it on a network share (at least with Access 2003 mdbs) is that I find myself needing to compact and repair often and I also have to kill the open sessions (user's who have the file open) when upgrading.  I would imagine it could also hypothetically create an unnecessary bottleneck if the user was not on the local network.

答:
After trying all of the solutions above (not exactly these solutions but these are the common suggestions in the Access community), I developed a system entirely within Access using VBA that allows an admin DB to create and publish objects to client DBs without the need for user intervention or management of multiple DB files.

This approach has several benefits:
1. It simplifies the development process by having a dedicated environment (admin DB) for development and testing totally separate from the client DBs.
2. It simplifies the update/distribution process by allowing a developer to push out updates in real time that client DBs can implement in the background, without involving users. Can also allow devs to roll back to previous versions if desired.
3. It could be used as a kind of change management system within Access for developers who want to commit multiple changes to objects and modules and retain past changes.
4. It allows for easier user access control by allowing an admin to easily assign certain objects to specific users/roles without needing to maintain multiple versions of the DB.

I will hopefully post the code to GitHub soon, I just have to get clearance from my workplace to release it. I will edit this post to include the link when I have.


问:
Xcode scrollview not working
I'm making a game and need users to sign an End User License Agreement (EULA). The EULA is long and requires a scroll view. I want the screen itself to stay still, so the buttons and header are always present:

Here is a screenshot of my viewController storyboard:

here's my code:

```<code>@IBOutlet var eulaView: UIView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let width = eulaView.frame.width
    let height = eulaView.frame.height

    self.scrollView.frame = CGRect(x: 0, y: 0, width: width, height: height)

    self.label.frame = CGRect(x: 0, y: 0, width: width , height: 2000)
    self.label.text = "Lots of stuff"

}
</code>```

Strangely, if I set self.label.frame's width to 100, it shows up. If I have it at 300, or "width", the label disappears.

No matter what, the scroll view doesn't scroll.

PS: I had it working earlier, but then I tried it on an iPhone X simulator and it was blank.

答:
You need to set  self.scrollView.contentSize = CGSize(width: width,height: 2000)

Sometimes When you change device in storyboard at that time screen was blank may be its bug of xcode.

To find the Dynamic Height Of label Depends on String Of label.

```<code>func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height
}
</code>```

Title: Xcode scrollview not working

Body:
I'm making a game and need users to sign an End User License Agreement (EULA). The EULA is long and requires a scroll view. I want the screen itself to stay still, so the buttons and header are always present:

Here is a screenshot of my viewController storyboard:

here's my code:

@IBOutlet var eulaView: UIView!
@IBOutlet var scrollView: UIScrollView!
@IBOutlet var label: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    let width = eulaView.frame.width
    let height = eulaView.frame.height

    self.scrollView.frame = CGRect(x: 0, y: 0, width: width, height: height)

    self.label.frame = CGRect(x: 0, y: 0, width: width , height: 2000)
    self.label.text = "Lots of stuff"

}

Strangely, if I set self.label.frame's width to 100, it shows up. If I have it at 300, or "width", the label disappears.

No matter what, the scroll view doesn't scroll.

PS: I had it working earlier, but then I tried it on an iPhone X simulator and it was blank.

Body:
You need to set  self.scrollView.contentSize = CGSize(width: width,height: 2000)

Sometimes When you change device in storyboard at that time screen was blank may be its bug of xcode.

To find the Dynamic Height Of label Depends on String Of label.

func heightForView(text:String, font:UIFont, width:CGFloat) -> CGFloat{
    let label:UILabel = UILabel(frame: CGRect(x: 0, y: 0, width: width, height: CGFloat.greatestFiniteMagnitude))
    label.numberOfLines = 0
    label.lineBreakMode = NSLineBreakMode.byWordWrapping
    label.font = font
    label.text = text
    label.sizeToFit()

    return label.frame.height
}


问:
Enums and With in Kotlin
Either my syntax is wrong, or you can't use with to apply to enum constants.  IntelliJ says it's because RegexOption doesn't have a companion object, and that RegexOption needs to be initialized here.  I didn't think you could instantiate an enum.

```<code>// this works:
val RX_OPTIONS = mapOf(
  'c' to RegexOption.COMMENTS,
  'd' to RegexOption.DOT_MATCHES_ALL,
  'e' to RegexOption.CANON_EQ,
  'i' to RegexOption.IGNORE_CASE,
  'l' to RegexOption.LITERAL,
  'm' to RegexOption.MULTILINE,
  'u' to RegexOption.UNIX_LINES
)

// this doesn't work:
val RX_OPTIONS2 = with(RegexOption) { mapOf(
  'c' to COMMENTS,
  'd' to DOT_MATCHES_ALL,
  'e' to CANON_EQ,
  'i' to IGNORE_CASE,
  'l' to LITERAL,
  'm' to MULTILINE,
  'u' to UNIX_LINES
) }
</code>```

Why doesn't the second example work?  If they're not in the companion object, it doesn't seem like they'd be in an instance.  Does with have a counterpart that could work in this situation?  If not, is it easy to write one (since with is just a one-liner)?

EDIT (Refining the question):

In a block (not necessarily even this one) where I'm typing 20 references to the same long enum names like Class.Inner.VeryInner.YouGetTheIdea.SOMEOPTION is it possible to factor out all but the SOMEOPTION name using a with-statement-like construct just for a block -- even one that I must write myself as a higher order function?  I've considered typealias, but I really want this to apply only to the block.  The answer below tells me the with higher-order function doesn't work for this, but is there a way to do it?

答:
The one-liner implementation of with is:

```<code>public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
</code>```

The T.() is a function literal with a receiver, and the receiver is an object. You're passing a class.

The documentation for Kotlin function literals with receiver can be found here.

Title: Enums and With in Kotlin

Body:
Either my syntax is wrong, or you can't use with to apply to enum constants.  IntelliJ says it's because RegexOption doesn't have a companion object, and that RegexOption needs to be initialized here.  I didn't think you could instantiate an enum.

// this works:
val RX_OPTIONS = mapOf(
  'c' to RegexOption.COMMENTS,
  'd' to RegexOption.DOT_MATCHES_ALL,
  'e' to RegexOption.CANON_EQ,
  'i' to RegexOption.IGNORE_CASE,
  'l' to RegexOption.LITERAL,
  'm' to RegexOption.MULTILINE,
  'u' to RegexOption.UNIX_LINES
)

// this doesn't work:
val RX_OPTIONS2 = with(RegexOption) { mapOf(
  'c' to COMMENTS,
  'd' to DOT_MATCHES_ALL,
  'e' to CANON_EQ,
  'i' to IGNORE_CASE,
  'l' to LITERAL,
  'm' to MULTILINE,
  'u' to UNIX_LINES
) }

Why doesn't the second example work?  If they're not in the companion object, it doesn't seem like they'd be in an instance.  Does with have a counterpart that could work in this situation?  If not, is it easy to write one (since with is just a one-liner)?

EDIT (Refining the question):

In a block (not necessarily even this one) where I'm typing 20 references to the same long enum names like Class.Inner.VeryInner.YouGetTheIdea.SOMEOPTION is it possible to factor out all but the SOMEOPTION name using a with-statement-like construct just for a block -- even one that I must write myself as a higher order function?  I've considered typealias, but I really want this to apply only to the block.  The answer below tells me the with higher-order function doesn't work for this, but is there a way to do it?

Body:
The one-liner implementation of with is:

public inline fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()

The T.() is a function literal with a receiver, and the receiver is an object. You're passing a class.

The documentation for Kotlin function literals with receiver can be found here.


问:
Adding HTML content to angular material $mdDialog
I have written the following piece of code to display some contents in angular material dialog box. it works fine when i add plain text to textContent . when i add HTML its displays HTML as text. how do i bind HTML to textContent

This Works

```<code>  <a href="#" ng-click="$scope.Modal()">Sample Link</a>

  $scope.Modal = function () {
      $mdDialog.show(
          $mdDialog.alert()
              .parent(angular.element(document.querySelector('body')))
              .clickOutsideToClose(true)
              .textContent('sample text')
              .ok('Ok')
      );
  }
</code>```

This Doesn't Works

```<code>  <a href="#" ng-click="$scope.Modal()">Sample Link</a>

  $scope.Modal = function () {
      $mdDialog.show(
          $mdDialog.alert()
              .parent(angular.element(document.querySelector('body')))
              .clickOutsideToClose(true)
              .textContent('<div class="test"><p>Sample text</p></div>')
              .ok('Ok')
      );
  }
</code>```

Thanks in advance

答:
It seems a bit counter intuitive to use a template when you only need to inject one or two things in.  To avoid using a template, you need to include 'ngSanitize' for it to work.

```<code>angular.module('myApp',['ngMaterial', 'ngSanitize'])
.controller('btnTest',function($mdDialog,$scope){
  var someHTML = "<font>This is a test</font>";
    $scope.showConfirm = function(ev) {
      // Appending dialog to document.body to cover sidenav in docs app
      var confirm = $mdDialog.confirm()
        .title('Please confirm the following')
        .htmlContent(someHTML)
        .ariaLabel('Lucky day')
        .targetEvent(ev)
        .ok('Please do it!')
        .cancel('Sounds like a scam');
      //Switch between .htmlContent and .textContent. You will see htmlContent doesn't display dialogbox, textContent does.
      $mdDialog.show(confirm).then(function() {
        $scope.status = 'Saving Data';
      },
      function() {
        $scope.status = 'You decided to keep your debt.';
      });
    };

})
</code>```

Notice the injected HTML:

```<code>var someHTML = "<font>This is a test</font>";
</code>```

I found this example here.

Body:
I have written the following piece of code to display some contents in angular material dialog box. it works fine when i add plain text to textContent . when i add HTML its displays HTML as text. how do i bind HTML to textContent

This Works

  Sample Link

  $scope.Modal = function () {
      $mdDialog.show(
          $mdDialog.alert()
              .parent(angular.element(document.querySelector('body')))
              .clickOutsideToClose(true)
              .textContent('sample text')
              .ok('Ok')
      );
  }

This Doesn't Works

  Sample Link

  $scope.Modal = function () {
      $mdDialog.show(
          $mdDialog.alert()
              .parent(angular.element(document.querySelector('body')))
              .clickOutsideToClose(true)
              .textContent('

Sample text

')
              .ok('Ok')
      );
  }

Thanks in advance

Body:
It seems a bit counter intuitive to use a template when you only need to inject one or two things in.  To avoid using a template, you need to include 'ngSanitize' for it to work.

angular.module('myApp',['ngMaterial', 'ngSanitize'])
.controller('btnTest',function($mdDialog,$scope){
  var someHTML = "<font>This is a test</font>";
    $scope.showConfirm = function(ev) {
      // Appending dialog to document.body to cover sidenav in docs app
      var confirm = $mdDialog.confirm()
        .title('Please confirm the following')
        .htmlContent(someHTML)
        .ariaLabel('Lucky day')
        .targetEvent(ev)
        .ok('Please do it!')
        .cancel('Sounds like a scam');
      //Switch between .htmlContent and .textContent. You will see htmlContent doesn't display dialogbox, textContent does.
      $mdDialog.show(confirm).then(function() {
        $scope.status = 'Saving Data';
      },
      function() {
        $scope.status = 'You decided to keep your debt.';
      });
    };

})

Notice the injected HTML:

var someHTML = "<font>This is a test</font>";

I found this example here.


问:
Aspect method of a parent class of a RestController does not trigger advice logic
I have some construct I'd really love to use an aspect on. I want to let my RestController inherit from a class which yields special logging methods which

log to the standard logback output

fires a http request to a service which does stuff with the log
message as well (done by the aspect)

I created an annotation with which I mark the method I want to aspect so the pointcut cant filter it. Special case is that this method is declared within the parent class of the RestController.

The aspect is not running even tho IntelliJ is marking the method as being used by the aspect, which tells me the pointcut has to be working?

Please see my code and check what I've might missed out to get it to work.

ApplicationClass

```<code>@SpringBootApplication
@ComponentScan("com.xetra.experimental")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopTryoutApplication {

    public static void main(String[] args) {
        SpringApplication.run(AopTryoutApplication.class, args);
    }
}
</code>```

RestController

```<code>@RestController
public class Endpoint extends SimpleLogger {
  @GetMapping("/endpoint")
  public void doStuff(){
    log("foo");
  }
}
</code>```

Parent class for RestController

```<code>public class SimpleLogger implements EndpointLogger{
  @AspectAnnotation
  public void log(String msg) {
    System.out.println(msg);
  }
}
</code>```

Interface for parent class (heard that aspected methods need interfaces)

```<code>public interface EndpointLogger {
  void log(String msg);
}
</code>```

Annotation my aspect should pointcut to

```<code>@Inherited
public @interface AspectAnnotation {
}
</code>```

Spring AOP aspect

```<code>@Component
@Aspect
public class TestAspect {

  @Pointcut("@annotation(com.xetra.experimental.aoptryout.AspectAnnotation)")
  public void methods() {
  }

  @Before("methods()")
  public void beforeMethodExecution(JoinPoint jp) {
    System.out.println("Aspect ran!!!!");
  }

}
</code>```

答:
Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted.

You can find more here.

The call to log method is not intercepted since it's made from the doStuff method belonging to the same target object.

Now, any call to log method will be intercepted as long it's made externally from another object (not the same target object).

Questions

So if I use SimpleLogger as a component and not a parent class within the Endpoint it will work aye?

Yes, you are right!

Is there any way to get this to work anyway? Like using AspectJ and not Spring AOP?

You can use AspectJ's source weaving to make it work. Here, is a working example.

Body:
I have some construct I'd really love to use an aspect on. I want to let my RestController inherit from a class which yields special logging methods which

log to the standard logback output

fires a http request to a service which does stuff with the log
message as well (done by the aspect)

I created an annotation with which I mark the method I want to aspect so the pointcut cant filter it. Special case is that this method is declared within the parent class of the RestController.

The aspect is not running even tho IntelliJ is marking the method as being used by the aspect, which tells me the pointcut has to be working?

Please see my code and check what I've might missed out to get it to work.

ApplicationClass

@SpringBootApplication
@ComponentScan("com.xetra.experimental")
@EnableAspectJAutoProxy(proxyTargetClass = true)
public class AopTryoutApplication {

    public static void main(String[] args) {
        SpringApplication.run(AopTryoutApplication.class, args);
    }
}

RestController

@RestController
public class Endpoint extends SimpleLogger {
  @GetMapping("/endpoint")
  public void doStuff(){
    log("foo");
  }
}

Parent class for RestController

public class SimpleLogger implements EndpointLogger{
  @AspectAnnotation
  public void log(String msg) {
    System.out.println(msg);
  }
}

Interface for parent class (heard that aspected methods need interfaces)

public interface EndpointLogger {
  void log(String msg);
}

Annotation my aspect should pointcut to

@Inherited
public @interface AspectAnnotation {
}

Spring AOP aspect

@Component
@Aspect
public class TestAspect {

  @Pointcut("@annotation(com.xetra.experimental.aoptryout.AspectAnnotation)")
  public void methods() {
  }

  @Before("methods()")
  public void beforeMethodExecution(JoinPoint jp) {
    System.out.println("Aspect ran!!!!");
  }

}


问:
PCACompute on Unity
I try to learn about how pca work. I write a code but I have a problem when I use PCACompute it's no output data.Can someone help me?
Thank.</p>

```<code>Mat mat = new Mat(5, 1, CvType.CV_32FC3);
mat.put(0,0,new float[]{10.0f,5.0f,0.8f});
mat.put(1,0,new float[]{20.9f,9.2f,0.9f});
mat.put(2,0,new float[]{2.7f,4.8f,0.7f});
mat.put(3,0,new float[]{13.0f,7.9f,0.9f});
mat.put(4,0,new float[]{50.9f,1.2f,1.0f});
Mat mean = new Mat();
Mat eigenvectors = new Mat();
Core.PCACompute(mat, mean, eigenvectors);
Debug.Log("eigenvectors dump = " + eigenvectors.dump ()); // Print []
mat1.Dispose ();
mean.Dispose ();
eigenvectors.Dispose ();
</code>```

答:
Do you really need to use 3 channels?

Maybe you can try to increase the columns instead.

```<code>Mat mat = new Mat(5, 3, CvType.CV_32FC1);
</code>```

or you can make an array and change it to Mat using

```<code>    data= np.zeros([[1,2,3] ,[1,2,3]], np.float32)
    Mat mat = cv.fromarray(data)
</code>```

Title: PCACompute on Unity

Body:
I try to learn about how pca work. I write a code but I have a problem when I use PCACompute it's no output data.Can someone help me?
Thank.

Mat mat = new Mat(5, 1, CvType.CV_32FC3);
mat.put(0,0,new float[]{10.0f,5.0f,0.8f});
mat.put(1,0,new float[]{20.9f,9.2f,0.9f});
mat.put(2,0,new float[]{2.7f,4.8f,0.7f});
mat.put(3,0,new float[]{13.0f,7.9f,0.9f});
mat.put(4,0,new float[]{50.9f,1.2f,1.0f});
Mat mean = new Mat();
Mat eigenvectors = new Mat();
Core.PCACompute(mat, mean, eigenvectors);
Debug.Log("eigenvectors dump = " + eigenvectors.dump ()); // Print []
mat1.Dispose ();
mean.Dispose ();
eigenvectors.Dispose ();

Body:
Do you really need to use 3 channels?

Maybe you can try to increase the columns instead.

Mat mat = new Mat(5, 3, CvType.CV_32FC1);

or you can make an array and change it to Mat using

    data= np.zeros([[1,2,3] ,[1,2,3]], np.float32)
    Mat mat = cv.fromarray(data)