问:
Firebase - Atomic writes Across Multiple Locations not working
How can I make this function to update the realtime database in Firebase? I managed to make the function work but only to write new ID's for posts when updateChild is triggered. How can I make it to update the current posts by their post ID?

```<code>   var pathToPictures = [Pictures]()
   func updateAllImagesOfCurrentUserInDatabase() {

    //refrences
    let ref = FIRDatabase.database().reference()
    let uid = FIRAuth.auth()?.currentUser?.uid

    //match the user ID value stored into posts with current userID and get all the posts of the user
    let update = ref.child("posts").queryOrdered(byChild: "userID").queryEqual(toValue: uid)
    update.observe(FIRDataEventType.value, with: { (snapshot) in
           // print(snapshot)

        self.pathToPictures.removeAll()

        if snapshot.key != nil {

        let results = snapshot.value as! [String : AnyObject]

        for (_, value) in results {
            let pathToPostPicture = Pictures()

            if let pathToImage = value["pathToImage"] as? String , let postID = value["postID"] as? String {
                pathToPostPicture.postImageUrl = pathToImage
                pathToPostPicture.postID = postID
                self.pathToPictures.append(pathToPostPicture)
                print("Image and POST ID: \(pathToPostPicture.postImageUrl!)")
                print("Post ID is : \(postID)")

                if FIRAuth.auth()?.currentUser?.uid == uid {
                ref.child("Users_Details").child(uid!).child("profileImageUrl").observeSingleEvent(of: .value, with: { (userSnapshot) in
                    print(userSnapshot)

                    let userIMageUrl = userSnapshot.value as! String
                    pathToPostPicture.postImageUrl = userIMageUrl
                    self.pathToPictures.append(pathToPostPicture)
                    print("This is the image path:" + userIMageUrl + String(self.pathToPictures.count))

                    // Generate the path
                    let newPostRef = ref.child("posts").childByAutoId()
                    let newKey = newPostRef.key as String
                    print(newKey)
                    let updatedUserData = ["posts/\(postID)/pathToImage": pathToPostPicture.postImageUrl]
                    print("This is THE DATA:" , updatedUserData)
                    ref.updateChildValues(updatedUserData as Any as! [AnyHashable : Any])

                })

                }

                print(self.pathToPictures.count)

            }

            }
        } else {
            print("snapshot is nill")

        }

        self.collectionView?.reloadData()

    })
}
</code>```

UPDATE: This is how my database looks like

This is my database:

 "Users_Details" : {
    "aR0nRArjWVOhHbBFB8yUfao64z62" : {
      "profileImageUrl" : "url",
      "userID" : "aR0nRArjWVOhHbBFB8yUfao64z62"
    },
    "oGxXznrS2DS4ic1ejcSfKB5UlIQ2" : {
      "profileImageUrl" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    }
  },
  "posts" : {
    "-KlzNLcofTgqJgfTaGN9" : {
      "fullName" : "full name",
      "interval" : 1.496785712879506E9,
      "normalDate" : "Tue, 06 Jun 2017 22:48",
      "pathToImage" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    },
    "-KlzNXfvecIwBatXxmGW" : {
      "fullName" : "full name",
      "interval" : 1.496785761349721E9,
      "normalDate" : "Tue, 06 Jun 2017 22:49",
      "pathToImage" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    },```
</div>
</div>
</p>

<p>Let me tell you what it does: It's looping through the posts and finds all the current user posts. Then it takes the path to image url of every post and assign it to an array. After that it's finding the current user path to image url and updates the whole array with that. Now, I don't know how to update the database with the new values. If anybody knows it will be much appreciate it!</p>

<p>I am looking to make Atomic Writes Across Multiple Locations. Can somebody show me how to fix my code to do that?</p>

<p>It will look something like this:</p>

``` // ATOMIC UPDATE HERE - IF SOMEBODY CAN FIND THE RIGHT WAY OF DOING THAT

                    // Generate a new push ID for the new post
                    let newPostRef = ref.child(byAppendingPath: "posts").childByAutoId()
                    let newPostKey = newPostRef.key
                    // Create the data we want to update
                    let updatedUserData = ["posts/\(newPostKey)": ["pathToImage": self.pathToPictures]] as [String : Any]

                    // Do a deep-path update
                    ref.updateChildValues(updatedUserData)
```

答:
It looks like you're going to be downloading a lot of repetitive data. While denormalization of your database is a good practice, I would argue that in this case, you're better off not including the same download URL in every post. It doesn't make a difference across a handful of posts, but if you have thousands of users and tens or hundreds of thousands of posts, that's a lot of extra data being downloaded. Instead, you could have a dictionary containing uids as keys and the profile imageUrl as the value. You could check the dictionary for the desired uid, and if it's not present, query the database for that user's User_Details, then add them to the dictionary. When you need to display the image, you'd get the url from this dictionary. Someone else may have a better suggestion for this, so I welcome other ideas.

If you'd prefer to keep the profile image in every post, then I recommend using Cloud Functions for Firebase. You can make a function that, when profileImageUrl is updated in the user's User_Details, then updates this entry in the other posts. Currently, Cloud Functions are only available in Node.js. If you don't know JS, please don't let that be a deterrent! It's definitely worth it to learn a bit a JS. And the samples show you about as much JS as you'll have to know to get started.
Check out these resources:

Getting Started with Cloud Functions for Firebase

GitHub samples

Cloud Functions for Firebase documentation

Writing a Database Trigger

Writing a Cloud Storage Trigger: Part 1

Writing a Cloud Storage Trigger: Part 2

Body:
How can I make this function to update the realtime database in Firebase? I managed to make the function work but only to write new ID's for posts when updateChild is triggered. How can I make it to update the current posts by their post ID?

   var pathToPictures = [Pictures]()
   func updateAllImagesOfCurrentUserInDatabase() {

    //refrences
    let ref = FIRDatabase.database().reference()
    let uid = FIRAuth.auth()?.currentUser?.uid

    //match the user ID value stored into posts with current userID and get all the posts of the user
    let update = ref.child("posts").queryOrdered(byChild: "userID").queryEqual(toValue: uid)
    update.observe(FIRDataEventType.value, with: { (snapshot) in
           // print(snapshot)

        self.pathToPictures.removeAll()

        if snapshot.key != nil {

        let results = snapshot.value as! [String : AnyObject]

        for (_, value) in results {
            let pathToPostPicture = Pictures()

            if let pathToImage = value["pathToImage"] as? String , let postID = value["postID"] as? String {
                pathToPostPicture.postImageUrl = pathToImage
                pathToPostPicture.postID = postID
                self.pathToPictures.append(pathToPostPicture)
                print("Image and POST ID: \(pathToPostPicture.postImageUrl!)")
                print("Post ID is : \(postID)")

                if FIRAuth.auth()?.currentUser?.uid == uid {
                ref.child("Users_Details").child(uid!).child("profileImageUrl").observeSingleEvent(of: .value, with: { (userSnapshot) in
                    print(userSnapshot)

                    let userIMageUrl = userSnapshot.value as! String
                    pathToPostPicture.postImageUrl = userIMageUrl
                    self.pathToPictures.append(pathToPostPicture)
                    print("This is the image path:" + userIMageUrl + String(self.pathToPictures.count))

                    // Generate the path
                    let newPostRef = ref.child("posts").childByAutoId()
                    let newKey = newPostRef.key as String
                    print(newKey)
                    let updatedUserData = ["posts/\(postID)/pathToImage": pathToPostPicture.postImageUrl]
                    print("This is THE DATA:" , updatedUserData)
                    ref.updateChildValues(updatedUserData as Any as! [AnyHashable : Any])

                })

                }

                print(self.pathToPictures.count)

            }

            }
        } else {
            print("snapshot is nill")

        }

        self.collectionView?.reloadData()

    })
}

UPDATE: This is how my database looks like

This is my database:

 "Users_Details" : {
    "aR0nRArjWVOhHbBFB8yUfao64z62" : {
      "profileImageUrl" : "url",
      "userID" : "aR0nRArjWVOhHbBFB8yUfao64z62"
    },
    "oGxXznrS2DS4ic1ejcSfKB5UlIQ2" : {
      "profileImageUrl" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    }
  },
  "posts" : {
    "-KlzNLcofTgqJgfTaGN9" : {
      "fullName" : "full name",
      "interval" : 1.496785712879506E9,
      "normalDate" : "Tue, 06 Jun 2017 22:48",
      "pathToImage" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    },
    "-KlzNXfvecIwBatXxmGW" : {
      "fullName" : "full name",
      "interval" : 1.496785761349721E9,
      "normalDate" : "Tue, 06 Jun 2017 22:49",
      "pathToImage" : "url",
      "userID" : "oGxXznrS2DS4ic1ejcSfKB5UlIQ2"
    },

Let me tell you what it does: It's looping through the posts and finds all the current user posts. Then it takes the path to image url of every post and assign it to an array. After that it's finding the current user path to image url and updates the whole array with that. Now, I don't know how to update the database with the new values. If anybody knows it will be much appreciate it!

I am looking to make Atomic Writes Across Multiple Locations. Can somebody show me how to fix my code to do that?

It will look something like this:

 // ATOMIC UPDATE HERE - IF SOMEBODY CAN FIND THE RIGHT WAY OF DOING THAT

                    // Generate a new push ID for the new post
                    let newPostRef = ref.child(byAppendingPath: "posts").childByAutoId()
                    let newPostKey = newPostRef.key
                    // Create the data we want to update
                    let updatedUserData = ["posts/\(newPostKey)": ["pathToImage": self.pathToPictures]] as [String : Any]

                    // Do a deep-path update
                    ref.updateChildValues(updatedUserData)


来源: stackexchange

问:
SWFAddress: adding "/" char at the end of an URL via JavaScript
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

```<code>http://mysite.com/section

// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content
</code>```

I've started with this code to do it:

```<code>$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}
</code>```

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

答:
As already said, you cannot change the URL without forcing a reload of the site. And I don't think you want that. (but it depends on how SWFAddress.setValue() actually works, if it just keeps track of the URLs internally (without changing the browsers URL) then you can do it)

But I wanted to give you an alternative for setTimeout:

```<code>$(".time_dot, .time_year").click (function (event) {
    event.preventDefault();
    event.stopPropagation();
    onClickEvent (this);
});

function onClickEvent (dom) {
    SWFAddress.setValue($(dom).parent().attr("id"));
    // do something else
}
</code>```

With this you prevent the click event from bubbling up and also prevent the change the default action (which would be following the link).

See jQuery event object.

ContentLicense: CC BY-SA 2.5

Body:
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

http://mysite.com/section

// and after click to a specific button get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content

I've started with this code to do it:

$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

Body:
As already said, you cannot change the URL without forcing a reload of the site. And I don't think you want that. (but it depends on how SWFAddress.setValue() actually works, if it just keeps track of the URLs internally (without changing the browsers URL) then you can do it)

But I wanted to give you an alternative for setTimeout:

$(".time_dot, .time_year").click (function (event) {
    event.preventDefault();
    event.stopPropagation();
    onClickEvent (this);
});

function onClickEvent (dom) {
    SWFAddress.setValue($(dom).parent().attr("id"));
    // do something else
}

With this you prevent the click event from bubbling up and also prevent the change the default action (which would be following the link).

See jQuery event object.


问:
Correct Flow types when iterating over HTMLFormElement elements?
I have a function that takes a form element as input, filters its child elements (removing those without serializable values), then returns an object of the form {name: value}.

The typechecking seems to be failing because Flow is telling me that each element passed to the filter function is just a basic HTMLElement. I am filtering by checking element.type, element.name etc, and as HTMLElements do not have these properties, there is an error.

The two filtering functions use a union type containing the relevant elements I expect to be there (HTMLInputElement, HTMLTextAreaElement etc) to typecheck. On their own these work. It is only when they are called in the filter that I get the errors.

Full code for the module is:

```<code>/* @flow
 * Returns form data as a javascript object. Requires each
 * form element to have a name that corresponds to its value.
 */
type FormChild =
  | HTMLInputElement
  | HTMLSelectElement
  | HTMLTextAreaElement
  | HTMLButtonElement
  | HTMLFieldSetElement;

const isValidTarget = (el: FormChild): boolean => {
  return !(el instanceof HTMLFieldSetElement) &&
         !(el instanceof HTMLButtonElement) &&
         el.name !== '';
};

const isSerializable = (el: FormChild): boolean => {
  return (el.type === 'radio' && el.checked === true) ||
         (el.type === 'checkbox' && el.checked === true) ||
         (el.type !== 'radio' && el.type !== 'checkbox');
};

export default (form: HTMLFormElement): { [elementName: string]: string } => {
  return [...form.elements].filter((el) => isValidTarget(el) && isSerializable(el))
                           .reduce((data, el) => ({ [el.name]: el.value, ...data }), {});
};
</code>```

And the errors I am getting all refer to the call in the filter:

HTMLElement This type is incompatible with union: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement | HTMLFieldSetElement

and relating to the reduce:

property 'name' Property not found in HTMLElement

property 'value' Property not found in HTMLElement

答:
There are two steps:

cast type from HTMLElement to FormChild,

remove HTMLFieldSetElement from FormChild type as it cannot have value attribute and will be filtered with isValidTarget().

```<code>/* @flow
 * Returns form data as a javascript object. Requires each
 * form element to have a name that corresponds to its value.
 */
type FormChild =
  | HTMLInputElement
  | HTMLSelectElement
  | HTMLTextAreaElement;
//| HTMLButtonElement         <— removed, will be filtered by isValidTarget()
//| HTMLFieldSetElement;      <— removed, will be filtered by isValidTarget()

    const isValidTarget = (el: FormChild): boolean => {
      return !(el instanceof HTMLFieldSetElement) &&
             !(el instanceof HTMLButtonElement) &&
             el.name !== '';
    };

    const isSerializable = (el: FormChild): boolean => {
      return (el.type === 'radio' && el.checked === true) ||
             (el.type === 'checkbox' && el.checked === true) ||
             (el.type !== 'radio' && el.type !== 'checkbox');
    };

    export default (form: HTMLFormElement): { [elementName: string]: string } => {
//                                     `el: any` — prepare to cast
      return [...form.elements].filter((el: any) => isValidTarget(el) && isSerializable(el))
                               .reduce((data, el: FormChild) => ({ [el.name]: el.value, ...data }), {});
//                                           `el: FormChild` — type was casted
    };
</code>```

Tested with flow:4.0.5

ContentLicense: CC BY-SA 3.0

Body:
I have a function that takes a form element as input, filters its child elements (removing those without serializable values), then returns an object of the form {name: value}.

The typechecking seems to be failing because Flow is telling me that each element passed to the filter function is just a basic HTMLElement. I am filtering by checking element.type, element.name etc, and as HTMLElements do not have these properties, there is an error.

The two filtering functions use a union type containing the relevant elements I expect to be there (HTMLInputElement, HTMLTextAreaElement etc) to typecheck. On their own these work. It is only when they are called in the filter that I get the errors.

Full code for the module is:

/* @flow
 * Returns form data as a javascript object. Requires each
 * form element to have a name that corresponds to its value.
 */
type FormChild =
  | HTMLInputElement
  | HTMLSelectElement
  | HTMLTextAreaElement
  | HTMLButtonElement
  | HTMLFieldSetElement;

const isValidTarget = (el: FormChild): boolean => {
  return !(el instanceof HTMLFieldSetElement) &&
         !(el instanceof HTMLButtonElement) &&
         el.name !== '';
};

const isSerializable = (el: FormChild): boolean => {
  return (el.type === 'radio' && el.checked === true) ||
         (el.type === 'checkbox' && el.checked === true) ||
         (el.type !== 'radio' && el.type !== 'checkbox');
};

export default (form: HTMLFormElement): { [elementName: string]: string } => {
  return [...form.elements].filter((el) => isValidTarget(el) && isSerializable(el))
                           .reduce((data, el) => ({ [el.name]: el.value, ...data }), {});
};

And the errors I am getting all refer to the call in the filter:

HTMLElement This type is incompatible with union: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement | HTMLFieldSetElement

and relating to the reduce:

property 'name' Property not found in HTMLElement

property 'value' Property not found in HTMLElement

Body:
There are two steps:

cast type from HTMLElement to FormChild,

remove HTMLFieldSetElement from FormChild type as it cannot have value attribute and will be filtered with isValidTarget().

/* @flow
 * Returns form data as a javascript object. Requires each
 * form element to have a name that corresponds to its value.
 */
type FormChild =
  | HTMLInputElement
  | HTMLSelectElement
  | HTMLTextAreaElement;
//| HTMLButtonElement         <— removed, will be filtered by isValidTarget()
//| HTMLFieldSetElement;      <— removed, will be filtered by isValidTarget()

    const isValidTarget = (el: FormChild): boolean => {
      return !(el instanceof HTMLFieldSetElement) &&
             !(el instanceof HTMLButtonElement) &&
             el.name !== '';
    };

    const isSerializable = (el: FormChild): boolean => {
      return (el.type === 'radio' && el.checked === true) ||
             (el.type === 'checkbox' && el.checked === true) ||
             (el.type !== 'radio' && el.type !== 'checkbox');
    };

    export default (form: HTMLFormElement): { [elementName: string]: string } => {
//                                     `el: any` — prepare to cast
      return [...form.elements].filter((el: any) => isValidTarget(el) && isSerializable(el))
                               .reduce((data, el: FormChild) => ({ [el.name]: el.value, ...data }), {});
//                                           `el: FormChild` — type was casted
    };

Tested with flow:4.0.5


问:
startIndex cannot be larger then length of string. Parameter name: startIndex MVC4
I am running into an error only on my production while I am adding my weights that are on my receiving reports checked as received.

On my local machine this issue isn't exist. but on the production get the error below.

my controller:

```<code>public int ReceivingReportWeight
{
    get
    {
        if (_ReceivingReportWeight == null && ReceivingReportCount > 0 && ReceivingReportWeight == 0)
        {
            dynamic receivingReportDbView = Database.Open().vw_ReceivingReports;
            List<int> receivedReceivingReports = receivingReportDbView.Select(receivingReportDbView.Id).Where(receivingReportDbView.ProjectId == Id && receivingReportDbView.Received == true).ToScalarList<int>();
            dynamic vwItemsDbView = Database.Open().vw_Items;
            int receivingReportWeight = vwItemsDbView.Select(vwItemsDbView.Weight.Sum()).Where(vwItemsDbView.ModuleId == MODULE_IDS.RECEIVING_REPORT && vwItemsDbView.TransactionId == receivedReceivingReports).ToScalar<int>();
            _ReceivingReportWeight = receivingReportWeight;
        }

        return _ReceivingReportWeight.GetValueOrDefault();
    }
}
</code>```

my view

```<code>   @if (Model.ReceivingReportWeight > 0) {
        <div class="actions" style="width: 50%; text-align: right;">
            Total Received Weight: @Model.ReceivingReportWeight lbs.
        </div>
   }
</code>```

答:
I just wanted to share that I received this EXACT same error from incorrectly specifying a property on a control (Captcha control).

```<code> Width="204px" BorderStyle="Solid" BorderColor="Black" BorderWidth="1">
</code>```

I actually had entered

```<code> Border="1"
</code>```

Which fired the error indicated above. When I corrected the property name, code worked perfectly.

Body:
I am running into an error only on my production while I am adding my weights that are on my receiving reports checked as received.

On my local machine this issue isn't exist. but on the production get the error below.

my controller:

public int ReceivingReportWeight
{
    get
    {
        if (_ReceivingReportWeight == null && ReceivingReportCount > 0 && ReceivingReportWeight == 0)
        {
            dynamic receivingReportDbView = Database.Open().vw_ReceivingReports;
            List<int> receivedReceivingReports = receivingReportDbView.Select(receivingReportDbView.Id).Where(receivingReportDbView.ProjectId == Id && receivingReportDbView.Received == true).ToScalarList<int>();
            dynamic vwItemsDbView = Database.Open().vw_Items;
            int receivingReportWeight = vwItemsDbView.Select(vwItemsDbView.Weight.Sum()).Where(vwItemsDbView.ModuleId == MODULE_IDS.RECEIVING_REPORT && vwItemsDbView.TransactionId == receivedReceivingReports).ToScalar<int>();
            _ReceivingReportWeight = receivingReportWeight;
        }

        return _ReceivingReportWeight.GetValueOrDefault();
    }
}

my view

   @if (Model.ReceivingReportWeight > 0) {

            Total Received Weight: @Model.ReceivingReportWeight lbs.

   }

Body:
I just wanted to share that I received this EXACT same error from incorrectly specifying a property on a control (Captcha control).

 Width="204px" BorderStyle="Solid" BorderColor="Black" BorderWidth="1">

I actually had entered

 Border="1"

Which fired the error indicated above. When I corrected the property name, code worked perfectly.


问:
get admin_creator of a post Facebook api
I need to get the userid of the person who creates the post, and based on the documentation: https://developers.facebook.com/docs/graph-api/reference/v2.9/post#read

This information is in the admin_creator field. Example:  {post-id}?fields=admin_creator I am already the admin of the page and manage_pages permission, so I dont understand what is going on... Thanks!

答:
```<code>https://graph.facebook.com/v2.9/{page_id}/posts?fields=admin_creator&access_token={page_access_token}
</code>```

PS: This endpoint requires an access_token from the page

Body:
https://graph.facebook.com/v2.9/{page_id}/posts?fields=admin_creator&access_token={page_access_token}

PS: This endpoint requires an access_token from the page


问:
Is it possible to iterate through an array list with elements of different data types and put them out?
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

答:
As far as I know, yes.

You can make ArrayList which contains Objects (see Java class Object), because each class you define in Java at least extends class Object which is a top class.

Now let me answer your questions:

yes, it is. Each object in the list knows which class it is instance of and has method toString(). When you swipe through ArrayList and call toString() for every object, the most specific method toString() will be called. For example, if it's instance of Integer (let's say it's called number) and you casted it to Object, call number.toString();, although compiler now looks at that number as the Object, it will call toString() method from Integer class. That's called dynamic polymorphism

yes, you can check which class is the Object instance of. Each of these objects has that info; casting it to Object class is just like saying to compiler "here is some object, I want you to look at it as an instance of class Object" - just like putting glasses to a compiler.
And object knows which class it is, so you can just ask, for example:

```<code>if(myObject instanceof String){
     //do something;
}
</code>```

Hope it helped, I tried to explain it the best way I could so you understand what's going on "under the hood" :)

Body:
As far as I know, yes.

You can make ArrayList which contains Objects (see Java class Object), because each class you define in Java at least extends class Object which is a top class.

Now let me answer your questions:

yes, it is. Each object in the list knows which class it is instance of and has method toString(). When you swipe through ArrayList and call toString() for every object, the most specific method toString() will be called. For example, if it's instance of Integer (let's say it's called number) and you casted it to Object, call number.toString();, although compiler now looks at that number as the Object, it will call toString() method from Integer class. That's called dynamic polymorphism

yes, you can check which class is the Object instance of. Each of these objects has that info; casting it to Object class is just like saying to compiler "here is some object, I want you to look at it as an instance of class Object" - just like putting glasses to a compiler.
And object knows which class it is, so you can just ask, for example:

if(myObject instanceof String){
     //do something;
}

Hope it helped, I tried to explain it the best way I could so you understand what's going on "under the hood" :)


问:
Angular CLI route
When executing command:

```<code>ng generate route someName
</code>```

I am getting error like this:

Could not start watchman; falling back to NodeWatcher for file system
  events. Visit http://ember-cli.com/user-guide/#watchman for more info.
  Due to changes in the router, route generation has been temporarily
  disabled. You can find more information about the new router here:
  http://victorsavkin.com/post/145672529346/angular-router

Provided links are not helpful

答:
use :

```<code>ng g m route --routing
</code>```

g-> generate

m-> module

route-> Your route Module Name(You can use any name).

Title: Angular CLI route

Body:
When executing command:

ng generate route someName

I am getting error like this:

Could not start watchman; falling back to NodeWatcher for file system
  events. Visit http://ember-cli.com/user-guide/#watchman for more info.
  Due to changes in the router, route generation has been temporarily
  disabled. You can find more information about the new router here:
  http://victorsavkin.com/post/145672529346/angular-router

Provided links are not helpful

Body:
use :

ng g m route --routing

g-> generate

m-> module

route-> Your route Module Name(You can use any name).


问:
React Redux action payload not in componentDidMount
I have an action creator that I'm calling in componentWillMount, the return of that action payload is being assigned to state using setState. However, in componentDidMount I cannot access that property as the async call hasn't completed yet. What is the correct way to access this data in compoentDidMount?</p>

```<code>//component
class Dashboard extends Component {

componentWillMount() {
    this.setState(this.props.getUser());
  }

componentDidMount() {
    // this.state.user isn't available yet
}

render(){
  return(...);
}
}

//action
export function getUser() {
  return async function (dispatch) {
     const user = await axios.get(`${API_URL}user?token=${token}`);
     return dispatch({
      type: USER,
      payload: user,
     });
    }
  };
}
</code>```

答:
Axios returns a promise and you have to wait until it resolves. Then dispatch the success action like this,

```<code>export function getUser() {
  return function (dispatch) {
     axios.get(`${API_URL}user?token=${token}`)
        .then(user => {
             return dispatch(getUserSuccess(user));
        }).catch(error => {
            throw error;
        });
    }
  };

  export function getUserSuccess(user) {
    return {type: USER, payload: user};
  }
</code>```

Also note that you need to have mapStateToProps so it brings the user to your component. Then you can access it using this.props.user within your component. It should be like this.

```<code>UserPage.propTypes = {
  user: PropTypes.object.isRequired
};

function mapStateToProps(state, ownProps) {
  return {
    user: state.user
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({getUser}, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(UserPage);
</code>```

Finally you may access the user like this.

```<code>  render() {
    const {user} = this.props;
    return(
      <div>
        <div>user.name</div>
      </div>
    );
  }
</code>```

Body:
I have an action creator that I'm calling in componentWillMount, the return of that action payload is being assigned to state using setState. However, in componentDidMount I cannot access that property as the async call hasn't completed yet. What is the correct way to access this data in compoentDidMount?

//component
class Dashboard extends Component {

componentWillMount() {
    this.setState(this.props.getUser());
  }

componentDidMount() {
    // this.state.user isn't available yet
}

render(){
  return(...);
}
}

//action
export function getUser() {
  return async function (dispatch) {
     const user = await axios.get(`${API_URL}user?token=${token}`);
     return dispatch({
      type: USER,
      payload: user,
     });
    }
  };
}

Body:
Axios returns a promise and you have to wait until it resolves. Then dispatch the success action like this,

export function getUser() {
  return function (dispatch) {
     axios.get(`${API_URL}user?token=${token}`)
        .then(user => {
             return dispatch(getUserSuccess(user));
        }).catch(error => {
            throw error;
        });
    }
  };

  export function getUserSuccess(user) {
    return {type: USER, payload: user};
  }

Also note that you need to have mapStateToProps so it brings the user to your component. Then you can access it using this.props.user within your component. It should be like this.

UserPage.propTypes = {
  user: PropTypes.object.isRequired
};

function mapStateToProps(state, ownProps) {
  return {
    user: state.user
  };
}

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators({getUser}, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(UserPage);

Finally you may access the user like this.

  render() {
    const {user} = this.props;
    return(
      <div>
        <div>user.name</div>
      </div>
    );
  }


问:
How do I get a SELECT date query to run on my SQL database from C# application?
```<code>string dateType = DateFieldDropDown.SelectedItem.ToString();
string DateField1 = DateTextBox.Text;
string DateField2 = dateSelection2Text.Text;
DateField1 = Convert.ToDateTime(DateField1).ToString("yyyy-MM-dd");
DateField2 = Convert.ToDateTime(DateField2).ToString("yyyy-MM-dd");
string DateFiled = "DateFiled";

if (dateType == "DateFiled")
{
  SqlDataSource1.SelectParameters.Add(new Parameter("DateFiled",  TypeCode.String, DateFiled));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE @DateFiled BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();
</code>```

I'm not sure anyone can help without seeing the database behind, but I thought I'd give it a shot.  So I'm querying my database, trying to get records within a certain date range out. No errors thrown, just no results, despite there being associated data behind which should be pulled in.  I've tested the SQL query on the database in a SQL editor using the dates rather than the parameter variables and gotten the correct results. I think it may need a CAST in order to be able to check the date in the string to the datetime in the database?  But when I try putting that in
SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE @DateFiled BETWEEN CAST(@DateField1 AS DATE) AND CAST(@DateField2 AS DATE)";
I get an error saying Conversion failed when converting date and/or time from character string.  Any ideas appreciated.

答:
you are passing a string "column name" to the stored-procedure.  Inside the stored procedure, the resulting SQL would look something like this:

SELECT * FROM tbl_dateCorrection WHERE 'DateFiled' BETWEEN '6/1/2017' AND '6/8/2017'

...Which will not have the effect you are trying for...

You'll need to try something like this:

```<code>if (dateType == "DateFiled")
{
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE DateFiled BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();
}
else {
   //some other Date
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE SomeOtherDate BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();
}
</code>```

Body:
string dateType = DateFieldDropDown.SelectedItem.ToString();
string DateField1 = DateTextBox.Text;
string DateField2 = dateSelection2Text.Text;
DateField1 = Convert.ToDateTime(DateField1).ToString("yyyy-MM-dd");
DateField2 = Convert.ToDateTime(DateField2).ToString("yyyy-MM-dd");
string DateFiled = "DateFiled";

if (dateType == "DateFiled")
{
  SqlDataSource1.SelectParameters.Add(new Parameter("DateFiled",  TypeCode.String, DateFiled));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE @DateFiled BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();

I'm not sure anyone can help without seeing the database behind, but I thought I'd give it a shot.  So I'm querying my database, trying to get records within a certain date range out. No errors thrown, just no results, despite there being associated data behind which should be pulled in.  I've tested the SQL query on the database in a SQL editor using the dates rather than the parameter variables and gotten the correct results. I think it may need a CAST in order to be able to check the date in the string to the datetime in the database?  But when I try putting that in
SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE @DateFiled BETWEEN CAST(@DateField1 AS DATE) AND CAST(@DateField2 AS DATE)";
I get an error saying Conversion failed when converting date and/or time from character string.  Any ideas appreciated.

Body:
you are passing a string "column name" to the stored-procedure.  Inside the stored procedure, the resulting SQL would look something like this:

SELECT * FROM tbl_dateCorrection WHERE 'DateFiled' BETWEEN '6/1/2017' AND '6/8/2017'

...Which will not have the effect you are trying for...

You'll need to try something like this:

if (dateType == "DateFiled")
{
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE DateFiled BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();
}
else {
   //some other Date
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField1", TypeCode.String, DateField1));
  SqlDataSource1.SelectParameters.Add(new Parameter("DateField2", TypeCode.String, DateField2));

  SqlDataSource1.SelectCommand = "SELECT * FROM tbl_dateCorrection WHERE SomeOtherDate BETWEEN @DateField1 AND @DateField2";
   SqlDataSource1.DataBind();
   GridView1.DataBind();
}


问:
SQL and ASP.NET WHERE IN generates wrong
I have this line of code:

```<code>sql += " AND lc.name IN ('" + String.Join(",", id.type.ToArray()) + "')";
</code>```

There are two items in id.type and this code generates this:

```<code>AND lc.name IN ('towns back to back,towns 3 storey')
</code>```

Which will not work because it should be like this:

```<code>AND lc.name IN ('towns back to back' , 'towns 3 storey')
</code>```

How can I fix this?

答:
Use parameter to pass input string like </p>

```<code>sql += " AND lc.name IN (@inputname)";
sqlcommand.parameters.AddWithValue("@inputname", String.Join("','", id.type.ToArray()))
</code>```

Body:
I have this line of code:

sql += " AND lc.name IN ('" + String.Join(",", id.type.ToArray()) + "')";

There are two items in id.type and this code generates this:

AND lc.name IN ('towns back to back,towns 3 storey')

Which will not work because it should be like this:

AND lc.name IN ('towns back to back' , 'towns 3 storey')

How can I fix this?

Body:
Use parameter to pass input string like

sql += " AND lc.name IN (@inputname)";
sqlcommand.parameters.AddWithValue("@inputname", String.Join("','", id.type.ToArray()))


问:
Get checked checkbox MVC5
I have searched some articles but none of them fits with my problem. i have this code in my cshtml

```<code>@model IEnumerable<MonitoreoIntegrado.Models.Sensores>
@using (Html.BeginForm("Graphics", "Datos_extensometro", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()
    <div style="margin:0; padding:0; border:none; position:absolute; bottom:5px; right:25px;"><input type="submit" id="enviar" class="btn btn-primary" value="Consultar"></div>
    <div style="float:left; width:428px; height:105px; padding:5px; overflow-y: scroll;">
        <h4 style="margin-top:0px;">Consultar multiples sensores</h4>
            @foreach (var item in Model)
            {
                @Html.CheckBox("sensoresCB", false, new { value = @item.idSensor.ToString() }) @item.nombre <a class="moverse" objetivo="@(item.idSensor)" href=""><span class="glyphicon glyphicon-map-marker" title="Ir al marcador"></span></a><br />
            }
    </div>
}
</code>```

and this in my controller:

```<code>[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics()
{
    return View();
}
</code>```

I need help to receive that checkboxes in my controller and check which of them are checked

答:
I would like to mention a helpful point here, that is

If a checkbox is checked, then the postback values will contain a
  key-value pair of the form [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no
  reference to the checkbox at all.

So in a controller action method, you can use the name of the checkbox and get the values which is only checked

ex:

```<code>public ActionResult Graphics(bool[] sensoresCB)
{
    return View();
}
</code>```

Hope above  information was helpful

Thanks

Karthik

Title: Get checked checkbox MVC5

Body:
I have searched some articles but none of them fits with my problem. i have this code in my cshtml

@model IEnumerable<MonitoreoIntegrado.Models.Sensores>
@using (Html.BeginForm("Graphics", "Datos_extensometro", FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
    @Html.AntiForgeryToken()

<input type="submit" id="enviar" class="btn btn-primary" value="Consultar">

Consultar multiples sensores

            @foreach (var item in Model)
            {
                @Html.CheckBox("sensoresCB", false, new { value = @item.idSensor.ToString() }) @item.nombre

            }

}

and this in my controller:

[HttpPost]
[ValidateAntiForgeryToken]
[Authorize(Roles = RolesSistema.Administrador + "," + RolesSistema.Lectura)]
public ActionResult Graphics()
{
    return View();
}

I need help to receive that checkboxes in my controller and check which of them are checked

Body:
I would like to mention a helpful point here, that is

If a checkbox is checked, then the postback values will contain a
  key-value pair of the form [InputName]=[InputValue]

If a checkbox is not checked, then the posted form contains no
  reference to the checkbox at all.

So in a controller action method, you can use the name of the checkbox and get the values which is only checked

ex:

public ActionResult Graphics(bool[] sensoresCB)
{
    return View();
}

Hope above  information was helpful

Thanks

Karthik


问:
Change File Names within Subfolders with VBA
I am trying to upload a few hundred folders each with files inside of them into SharePoint, but unfortunately SharePoint doesn't allow any special characters like "%".

I'm trying to use a VBA code that can automatically go into each subfolder and replace any special characters contained within the files such as "%", "#", etc.

So far what I have is:

```<code>Sub ChangeFileName()

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder("C:\Users\Documents\TEST\Subfolder")
'Currently the way I have it requires me to change my path a few hundred times
For Each File In Folder.Files
    sNewFile = File.Name
    sNewFile = Replace(sNewFile, "%", "_")
    sNewFile = Replace(sNewFile, "#", "_")
'^and so on`
    If (sNewFile <> File.Name) Then
        File.Move (File.ParentFolder + "\" + sNewFile)
    End If

Next

End Sub
</code>```

However for the script above, you need the specific sub-folder path. Wondering if there's any way to automatically replace the special characters of files within subfolders. I can also paste all the specific subfolder paths into column A of my Excel worksheet if that helps.

Thank you!

答:
I use this code</p>

```<code>Sub GetFileFromFolder()

    Dim fd As FileDialog
    Dim strFolder As String
    Dim colResult As Collection
    Dim i As Long, k As Long
    Dim vSplit
    Dim strFn As String
    Dim vR() As String
    Dim p As String
    Dim iLevel As Integer, cnt As Long

    'iLevel = InputBox(" Subfolder step : ex) 2 ")
        p = Application.PathSeparator
        Set fd = Application.FileDialog(msoFileDialogFolderPicker)
        With fd
            .Show
            .InitialView = msoFileDialogViewList
            .Title = "Select your Root folder"
            .AllowMultiSelect = False

            If .SelectedItems.Count = 0 Then
            Else
                strFolder = .SelectedItems(1)
                Set colResult = SearchFolder(strFolder)

                i = colResult.Count

                For k = 1 To i

                    vSplit = Split(colResult(k), p)
                    strFn = vSplit(UBound(vSplit))
                    strFn = Replace(strFn, "%", "_")
                    strFn = Replace(strFn, "#", "_")

                    'If UBound(vSplit) - UBound(Split(strFolder, p)) = iLevel Then
                        cnt = cnt + 1
                        ReDim Preserve vR(1 To 3, 1 To cnt)
                        On Error Resume Next
                        Err.Clear
                        Name colResult(k) As strFolder & strFn
                        vR(1, cnt) = colResult(k)

                        If Err.Number = 58 Then
                            strFn = Split(strFn, ".")(0) & "_" & vSplit(UBound(vSplit) - 1) & "_" & Date & "." & Split(strFn, ".")(1)
                            Name colResult(k) As strFolder & strFn
                            vR(2, cnt) = strFolder & strFn
                            vR(3, cnt) = "Changed name " 'When filename is duplicated chage filename
                        Else
                            vR(2, cnt) = strFolder & strFn
                        End If
                   ' End If
                Next k

                ActiveSheet.UsedRange.Offset(1).Clear
                Range("a3").Resize(1, 3) = Array("Old file", "New file", "Ect")
                If cnt > 0 Then
                    Range("a4").Resize(cnt, 3) = WorksheetFunction.Transpose(vR)
                End If
                 With ActiveSheet.UsedRange
                    .Borders.LineStyle = xlContinuous
                    .Columns.AutoFit
                    .Font.Size = 9
                End With
            End If
        End With
        MsgBox cnt & " files moved!! "
End Sub
Function SearchFolder(strRoot As String)
    Dim FS As Object

    Dim fsFD As Object
    Dim f As Object
    Dim colFile As Collection
    Dim p As String

    On Error Resume Next
    p = Application.PathSeparator
    If Right(strRoot, 1) = p Then
    Else
        strRoot = strRoot & p
    End If

    Set FS = CreateObject("Scripting.FileSystemObject")
    Set fsFD = FS.GetFolder(strRoot)
    Set colFile = New Collection
    For Each f In fsFD.Files
        colFile.Add f.Path
    Next f

        SearchSubfolder colFile, fsFD

    Set SearchFolder = colFile
    Set fsFD = Nothing
    Set FS = Nothing
    Set colFile = Nothing

End Function
Sub SearchSubfolder(colFile As Collection, objFolder As Object)
    Dim sbFolder As Object
    Dim f As Object
    For Each sbFolder In objFolder.subfolders
        SearchSubfolder colFile, sbFolder
        For Each f In sbFolder.Files
            colFile.Add f.Path
        Next f
    Next sbFolder

End Sub
</code>```

Body:
I am trying to upload a few hundred folders each with files inside of them into SharePoint, but unfortunately SharePoint doesn't allow any special characters like "%".

I'm trying to use a VBA code that can automatically go into each subfolder and replace any special characters contained within the files such as "%", "#", etc.

So far what I have is:

Sub ChangeFileName()

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Folder = objFSO.GetFolder("C:\Users\Documents\TEST\Subfolder")
'Currently the way I have it requires me to change my path a few hundred times
For Each File In Folder.Files
    sNewFile = File.Name
    sNewFile = Replace(sNewFile, "%", "_")
    sNewFile = Replace(sNewFile, "#", "_")
'^and so on`
    If (sNewFile <> File.Name) Then
        File.Move (File.ParentFolder + "\" + sNewFile)
    End If

Next

End Sub

However for the script above, you need the specific sub-folder path. Wondering if there's any way to automatically replace the special characters of files within subfolders. I can also paste all the specific subfolder paths into column A of my Excel worksheet if that helps.

Thank you!

Body:
I use this code

Sub GetFileFromFolder()

    Dim fd As FileDialog
    Dim strFolder As String
    Dim colResult As Collection
    Dim i As Long, k As Long
    Dim vSplit
    Dim strFn As String
    Dim vR() As String
    Dim p As String
    Dim iLevel As Integer, cnt As Long

    'iLevel = InputBox(" Subfolder step : ex) 2 ")
        p = Application.PathSeparator
        Set fd = Application.FileDialog(msoFileDialogFolderPicker)
        With fd
            .Show
            .InitialView = msoFileDialogViewList
            .Title = "Select your Root folder"
            .AllowMultiSelect = False

            If .SelectedItems.Count = 0 Then
            Else
                strFolder = .SelectedItems(1)
                Set colResult = SearchFolder(strFolder)

                i = colResult.Count

                For k = 1 To i

                    vSplit = Split(colResult(k), p)
                    strFn = vSplit(UBound(vSplit))
                    strFn = Replace(strFn, "%", "_")
                    strFn = Replace(strFn, "#", "_")

                    'If UBound(vSplit) - UBound(Split(strFolder, p)) = iLevel Then
                        cnt = cnt + 1
                        ReDim Preserve vR(1 To 3, 1 To cnt)
                        On Error Resume Next
                        Err.Clear
                        Name colResult(k) As strFolder & strFn
                        vR(1, cnt) = colResult(k)

                        If Err.Number = 58 Then
                            strFn = Split(strFn, ".")(0) & "_" & vSplit(UBound(vSplit) - 1) & "_" & Date & "." & Split(strFn, ".")(1)
                            Name colResult(k) As strFolder & strFn
                            vR(2, cnt) = strFolder & strFn
                            vR(3, cnt) = "Changed name " 'When filename is duplicated chage filename
                        Else
                            vR(2, cnt) = strFolder & strFn
                        End If
                   ' End If
                Next k

                ActiveSheet.UsedRange.Offset(1).Clear
                Range("a3").Resize(1, 3) = Array("Old file", "New file", "Ect")
                If cnt > 0 Then
                    Range("a4").Resize(cnt, 3) = WorksheetFunction.Transpose(vR)
                End If
                 With ActiveSheet.UsedRange
                    .Borders.LineStyle = xlContinuous
                    .Columns.AutoFit
                    .Font.Size = 9
                End With
            End If
        End With
        MsgBox cnt & " files moved!! "
End Sub
Function SearchFolder(strRoot As String)
    Dim FS As Object

    Dim fsFD As Object
    Dim f As Object
    Dim colFile As Collection
    Dim p As String

    On Error Resume Next
    p = Application.PathSeparator
    If Right(strRoot, 1) = p Then
    Else
        strRoot = strRoot & p
    End If

    Set FS = CreateObject("Scripting.FileSystemObject")
    Set fsFD = FS.GetFolder(strRoot)
    Set colFile = New Collection
    For Each f In fsFD.Files
        colFile.Add f.Path
    Next f

        SearchSubfolder colFile, fsFD

    Set SearchFolder = colFile
    Set fsFD = Nothing
    Set FS = Nothing
    Set colFile = Nothing

End Function
Sub SearchSubfolder(colFile As Collection, objFolder As Object)
    Dim sbFolder As Object
    Dim f As Object
    For Each sbFolder In objFolder.subfolders
        SearchSubfolder colFile, sbFolder
        For Each f In sbFolder.Files
            colFile.Add f.Path
        Next f
    Next sbFolder

End Sub


问:
T-SQL Transactions Rollback entire batch or only error records in the batch
I am updating our ERP from our CRM to add a new account. I have a table that has a batch of records to insert. Each record in the batch table will be used to insert into about 20 tables for the new account. I'm using a stored procedure with a cursor. I want to try each insert, If any insert fails all need to be removed. The errors need to be logged to a table and I have a script that does that. The code I have in mind is listed below. How do I know if the transaction is going to post all 15 records in the batch table and if any error rollback the entire batch. Or, if it will post each record from the batch and commit if each of the 20 inserts are successful for that batch table record and only rollback the 20 transactions if the record in the batch table has an error. </p>

```<code>OPEN @cur
fetch next from @cur
WHILE @@fetch_status = 0
BEGIN

BEGIN TRY
BEGIN TRANSACTION
/*INSERT INTO pc.dbo.People --People...*/
END TRY

BEGIN CATCH
error handling sp
set error flag to a yes

END CATCH

BEGIN TRY
BEGIN TRANSACTION
/*INSERT INTO pc.dbo.PersonPhone...*/
END TRY

BEGIN CATCH
error handling sp
set error flag to a yes

END CATCH

etc etc through the entire unit of work
END

If the error flag is No Commit, else Rollback

FETCH NEXT FROM cur INTO @some_variables

CLOSE cur
DEALLOCATE cur
</code>```

答:
Not really sure you need few try catches if you want to rollback entire inserts if error occur. I think it should look like:

```<code>BEGIN TRANSACTION
BEGIN TRY
        OPEN @cur
        fetch next from @cur
        WHILE @@fetch_status = 0
        BEGIN
            /*INSERT INTO pc.dbo.People --People...*/

            /*INSERT INTO pc.dbo.PersonPhone...*/
        FETCH NEXT FROM cur INTO @some_variables
            END
        CLOSE cur
        DEALLOCATE cur

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK
    -- error insert into table here
END CATCH
</code>```

Let me know if further assistance needed.

EDIT:

```<code>DECLARE @ERROR BIT = 0
BEGIN TRANSACTION
    OPEN @cur
    fetch next from @cur
    WHILE @@fetch_status = 0
    BEGIN

        BEGIN TRY
            /*INSERT INTO pc.dbo.People --People...*/
        END TRY
        BEGIN CATCH
            --error handling sp
            --set error flag to a yes
            SET @ERROR = 1
        END CATCH

        BEGIN TRY
            /*INSERT INTO pc.dbo.PersonPhone...*/
        END TRY

        BEGIN CATCH
            --error handling sp
            --set error flag to a yes
            SET @ERROR = 1
        END CATCH

        FETCH NEXT FROM cur INTO @some_variables
    END

    CLOSE cur
    DEALLOCATE cur

IF (@ERROR = 1)
    ROLLBACK
ELSE
    COMMIT TRANSACTION
</code>```

Please test this approach, it should do what you are expecting.

Body:
I am updating our ERP from our CRM to add a new account. I have a table that has a batch of records to insert. Each record in the batch table will be used to insert into about 20 tables for the new account. I'm using a stored procedure with a cursor. I want to try each insert, If any insert fails all need to be removed. The errors need to be logged to a table and I have a script that does that. The code I have in mind is listed below. How do I know if the transaction is going to post all 15 records in the batch table and if any error rollback the entire batch. Or, if it will post each record from the batch and commit if each of the 20 inserts are successful for that batch table record and only rollback the 20 transactions if the record in the batch table has an error.

OPEN @cur
fetch next from @cur
WHILE @@fetch_status = 0
BEGIN

BEGIN TRY
BEGIN TRANSACTION
/*INSERT INTO pc.dbo.People --People...*/
END TRY

BEGIN CATCH
error handling sp
set error flag to a yes

END CATCH

BEGIN TRY
BEGIN TRANSACTION
/*INSERT INTO pc.dbo.PersonPhone...*/
END TRY

BEGIN CATCH
error handling sp
set error flag to a yes

END CATCH

etc etc through the entire unit of work
END

If the error flag is No Commit, else Rollback

FETCH NEXT FROM cur INTO @some_variables

CLOSE cur
DEALLOCATE cur

Body:
Not really sure you need few try catches if you want to rollback entire inserts if error occur. I think it should look like:

BEGIN TRANSACTION
BEGIN TRY
        OPEN @cur
        fetch next from @cur
        WHILE @@fetch_status = 0
        BEGIN
            /*INSERT INTO pc.dbo.People --People...*/

            /*INSERT INTO pc.dbo.PersonPhone...*/
        FETCH NEXT FROM cur INTO @some_variables
            END
        CLOSE cur
        DEALLOCATE cur

    COMMIT TRANSACTION
END TRY
BEGIN CATCH
    ROLLBACK
    -- error insert into table here
END CATCH

Let me know if further assistance needed.

EDIT:

DECLARE @ERROR BIT = 0
BEGIN TRANSACTION
    OPEN @cur
    fetch next from @cur
    WHILE @@fetch_status = 0
    BEGIN

        BEGIN TRY
            /*INSERT INTO pc.dbo.People --People...*/
        END TRY
        BEGIN CATCH
            --error handling sp
            --set error flag to a yes
            SET @ERROR = 1
        END CATCH

        BEGIN TRY
            /*INSERT INTO pc.dbo.PersonPhone...*/
        END TRY

        BEGIN CATCH
            --error handling sp
            --set error flag to a yes
            SET @ERROR = 1
        END CATCH

        FETCH NEXT FROM cur INTO @some_variables
    END

    CLOSE cur
    DEALLOCATE cur

IF (@ERROR = 1)
    ROLLBACK
ELSE
    COMMIT TRANSACTION

Please test this approach, it should do what you are expecting.


问:
condense an if/else if statement using logical operators with javascript
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

```<code>$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };
</code>```

答:
----------------------------UPDATED------------WORKING CODE-------------------

** HTML **

```<code><!DOCTYPE html>
<html lang="en-us" ng-app="calcApp" class="full-height">
<head>
    <title>Hello World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="/Tom-s-Journal/">
    <link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="JournalCSS.css">
</head>

<body class="full-height overflow-hidden" ng-cloak>

    <div class="theCalculator" ng-controller="calcCtrl" id="outsideCalcEdge">
        <div class="calcButtonsrow" id="1stLine">
            <div id="answerScreen">
                <span>{{leftOperand}}</span>
                <span>{{operator}}</span>
                <span>{{rightOperand}}</span>
                <span>{{clear}}</span>
            </div>
        </div>

        <div class="calcButtonsrow" title="brand" id="brand">
            <span id="calcBrand">*Basic Calculator*</span><br>
            <span id="kogoSoftwareLLC">Kogo Software LLC</span>
        </div>
        <div class="calcButtonsrow" id="2ndLine">
            <button class="number" id="7" ng-click="setOperand('7')">7</button>
            <button class="number" id="8" ng-click="setOperand('8')">8</button>
            <button class="number" id="9" ng-click="setOperand('9')">9</button>
            <button id="divideBySign" ng-click="setOperator('/')" class=" operator">/</button>
        </div>
        <div class="calcButtonsrow" id="3rdLine">
            <button class="number" id="4" ng-click="setOperand('4')">4</button>
            <button class="number" id="5" ng-click="setOperand('5')">5</button>
            <button class="number" id="6" ng-click="setOperand('6')">6</button>
            <button id="multiplySign" ng-click="setOperator('*')" class=" operator">*</button>
        </div>
        <div class="calcButtonsrow" id="4thLine">
            <button class="number" id="1" ng-click="setOperand('1')">1</button>
            <button class="number" id="2" ng-click="setOperand('2')">2</button>
            <button class="number" id="3" ng-click="setOperand('3')">3</button>
            <button id="minusSign" ng-click="setOperator('-')" class=" operator">-</button>

        </div>
        <div class="calcButtonsrow" id="5thLine">
            <button id="clear" ng-click="setClear('C')">C</button>
            <button class="number" id="0" ng-click="setOperand('0')">0</button>
            <button id="equalSign" ng-click="getAnswer('=')"
            ng-disabled="!leftOperand || !operator || !rightOperand">=</button>
            <button id="plusSign" ng-click="setOperator('+')" class=" operator">+</button>
        </div>
    </div>

    <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<script src="calculator.js"></script>

</body>
</html>
</code>```

AngularJS

```<code>var calcApp = angular.module('calcApp', []);

calcApp.controller('calcCtrl', function ($scope) {
    $scope.leftOperand = "";
    $scope.operator = "";
    $scope.rightOperand = "";
    $scope.answer = "";

    $scope.setOperand = function (operandEntered) {
        if ($scope.operator){
            $scope.rightOperand += operandEntered;
        }
        else {
            $scope.leftOperand += operandEntered;
        };
    };
    $scope.setOperator = function (operatorEntered) {
        $scope.operator = operatorEntered;
    };

    $scope.getAnswer = function () {
        var result = $scope.leftOperand + $scope.operator + $scope.rightOperand;
        var answer = eval(result);
        if (answer % 2 !== 0){
            $scope.answer = answer.toFixed(2);
        }
        else {$scope.answer = answer;}

        $scope.leftOperand = $scope.answer;
        $scope.operator = "";
        $scope.rightOperand = "";
    };

    $scope.setClear = function (a) {
        $scope.clear = location.reload();
    };

});
    var windowProperties = "width=255,height=367,menubar=yes,location=no,resizable=no,scrollbars=no";
    var windowObjectReference = function openCalc() {
        window.open("/Tom-s-Journal/calculatorHTML.html", "calcWindow", windowProperties);
};
</code>```

CSS

```<code>@font-face {
    font-family: 'sickCalculatorFont';
    src: url('./calcFontFiles/digital-7.ttf');
}
#answerScreen {
    background-color: lightgray;
    border-style: inset;
    border-color: white;
    border-width:5px;
    font-family: 'sickCalculatorFont';
    font-size: 25px;
    font-weight: bold;
    height: 50px;
    padding-left: 3px;
    width: 215px;
}

button {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}

#brand {
    color: #000;
    font-weight: bold;
    font-size: 11px;
    text-align: center;
}

.calcButtonsrow {
    padding: 5px;
}

#calcButtonsBox {
    border-style: groove;
}

#clear {
    background-color: #FFAAAA;
}

.overflow-hidden {
    overflow: hidden;
}
#divideBySign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#divideBySign:hover {
    background-color: #4CAF50;
    color: white;
}

#equalSign{
    color: #FA6800;
}

#kogoSoftwareLLC {
    color: grey;
    font-weight: bold;
}

#minusSign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#minusSign:hover {
    background-color: #4CAF50;
    color: white;
}

#modalCalcButt {
    height: 150px !important;
    width: 150px !important;
}

#multiplySign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#multiplySign:hover {
    background-color: #4CAF50;
    color: white;
}

.number:hover {
    background-color: yellow;
    color: black;
}

#outsideCalcEdge {
    border-style: solid;
    border-width: 3px;
    border-radius: 3px;
    margin-left: 2px;
    margin-bottom: 50px;
    padding: 10px;
    width: 250px;
}

.operator {
    color: white;
    background-color: #0E2F5C;
}

#plusSign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#plusSign:hover {
    background-color: #4CAF50;
    color: white;
}

.theCalculator {
    background-color: lightskyblue;
}

[disabled] {
    color: gray !important;
    /*            the id of #equalSign takes precedence over [disabled], !important over rides that*/
}

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
}
</code>```

Body:
I'm learning AngularJS, trying to make a simple calculator, and I'm trying to condense this if/else if statement to 1-2 lines, using the Javascript logical Operators (&&, ||, !)

Given this example, how could I reduce it?
(if you don't understand $scope, ignore it. Its basically a view. So when someone clicks 9, the calculator will display 9 on the answer screen)

$scope.setOperand = function (operandEntered) {

    if ($scope.leftOperand === null) {
        $scope.leftOperand = operandEntered;
    }
    else if ($scope.operator === null) {
        $scope.leftOperand = $scope.leftOperand + operandEntered;
    }
    else if ($scope.rightOperand === null) {
        $scope.rightOperand = operandEntered;
    }
    else if ($scope.answer === null) {
        $scope.rightOperand = $scope.rightOperand + operandEntered;
    }
 };

Body:
----------------------------UPDATED------------WORKING CODE-------------------

** HTML **

<!DOCTYPE html>
<html lang="en-us" ng-app="calcApp" class="full-height">
<head>
    <title>Hello World</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <base href="/Tom-s-Journal/">
    <link rel='shortcut icon' type='image/x-icon' href='favicon.ico' />
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="JournalCSS.css">
</head>

<body class="full-height overflow-hidden" ng-cloak>

    <div class="theCalculator" ng-controller="calcCtrl" id="outsideCalcEdge">
        <div class="calcButtonsrow" id="1stLine">
            <div id="answerScreen">
                <span>{{leftOperand}}</span>
                <span>{{operator}}</span>
                <span>{{rightOperand}}</span>
                <span>{{clear}}</span>
            </div>
        </div>

        <div class="calcButtonsrow" title="brand" id="brand">
            <span id="calcBrand">*Basic Calculator*</span><br>
            <span id="kogoSoftwareLLC">Kogo Software LLC</span>
        </div>
        <div class="calcButtonsrow" id="2ndLine">
            <button class="number" id="7" ng-click="setOperand('7')">7</button>
            <button class="number" id="8" ng-click="setOperand('8')">8</button>
            <button class="number" id="9" ng-click="setOperand('9')">9</button>
            <button id="divideBySign" ng-click="setOperator('/')" class=" operator">/</button>
        </div>
        <div class="calcButtonsrow" id="3rdLine">
            <button class="number" id="4" ng-click="setOperand('4')">4</button>
            <button class="number" id="5" ng-click="setOperand('5')">5</button>
            <button class="number" id="6" ng-click="setOperand('6')">6</button>
            <button id="multiplySign" ng-click="setOperator('*')" class=" operator">*</button>
        </div>
        <div class="calcButtonsrow" id="4thLine">
            <button class="number" id="1" ng-click="setOperand('1')">1</button>
            <button class="number" id="2" ng-click="setOperand('2')">2</button>
            <button class="number" id="3" ng-click="setOperand('3')">3</button>
            <button id="minusSign" ng-click="setOperator('-')" class=" operator">-</button>

        </div>
        <div class="calcButtonsrow" id="5thLine">
            <button id="clear" ng-click="setClear('C')">C</button>
            <button class="number" id="0" ng-click="setOperand('0')">0</button>
            <button id="equalSign" ng-click="getAnswer('=')"
            ng-disabled="!leftOperand || !operator || !rightOperand">=</button>
            <button id="plusSign" ng-click="setOperator('+')" class=" operator">+</button>
        </div>
    </div>

    <script
    src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js">
</script>

<script src="calculator.js"></script>

</body>
</html>

AngularJS

var calcApp = angular.module('calcApp', []);

calcApp.controller('calcCtrl', function ($scope) {
    $scope.leftOperand = "";
    $scope.operator = "";
    $scope.rightOperand = "";
    $scope.answer = "";

    $scope.setOperand = function (operandEntered) {
        if ($scope.operator){
            $scope.rightOperand += operandEntered;
        }
        else {
            $scope.leftOperand += operandEntered;
        };
    };
    $scope.setOperator = function (operatorEntered) {
        $scope.operator = operatorEntered;
    };

    $scope.getAnswer = function () {
        var result = $scope.leftOperand + $scope.operator + $scope.rightOperand;
        var answer = eval(result);
        if (answer % 2 !== 0){
            $scope.answer = answer.toFixed(2);
        }
        else {$scope.answer = answer;}

        $scope.leftOperand = $scope.answer;
        $scope.operator = "";
        $scope.rightOperand = "";
    };

    $scope.setClear = function (a) {
        $scope.clear = location.reload();
    };

});
    var windowProperties = "width=255,height=367,menubar=yes,location=no,resizable=no,scrollbars=no";
    var windowObjectReference = function openCalc() {
        window.open("/Tom-s-Journal/calculatorHTML.html", "calcWindow", windowProperties);
};

CSS

@font-face {
    font-family: 'sickCalculatorFont';
    src: url('./calcFontFiles/digital-7.ttf');
}
#answerScreen {
    background-color: lightgray;
    border-style: inset;
    border-color: white;
    border-width:5px;
    font-family: 'sickCalculatorFont';
    font-size: 25px;
    font-weight: bold;
    height: 50px;
    padding-left: 3px;
    width: 215px;
}

button {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}

#brand {
    color: #000;
    font-weight: bold;
    font-size: 11px;
    text-align: center;
}

.calcButtonsrow {
    padding: 5px;
}

#calcButtonsBox {
    border-style: groove;
}

#clear {
    background-color: #FFAAAA;
}

.overflow-hidden {
    overflow: hidden;
}
#divideBySign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#divideBySign:hover {
    background-color: #4CAF50;
    color: white;
}

#equalSign{
    color: #FA6800;
}

#kogoSoftwareLLC {
    color: grey;
    font-weight: bold;
}

#minusSign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#minusSign:hover {
    background-color: #4CAF50;
    color: white;
}

#modalCalcButt {
    height: 150px !important;
    width: 150px !important;
}

#multiplySign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#multiplySign:hover {
    background-color: #4CAF50;
    color: white;
}

.number:hover {
    background-color: yellow;
    color: black;
}

#outsideCalcEdge {
    border-style: solid;
    border-width: 3px;
    border-radius: 3px;
    margin-left: 2px;
    margin-bottom: 50px;
    padding: 10px;
    width: 250px;
}

.operator {
    color: white;
    background-color: #0E2F5C;
}

#plusSign {
    border-radius: 10px;
    font-weight: bold;
    height: 50px;
    width: 50px;
}
#plusSign:hover {
    background-color: #4CAF50;
    color: white;
}

.theCalculator {
    background-color: lightskyblue;
}

[disabled] {
    color: gray !important;
    /*            the id of #equalSign takes precedence over [disabled], !important over rides that*/
}

[ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
    display: none !important;
}


问:
Tensorflow: What is the difference between declaring a variable with tf.Variable and declaring directly?
I'm writing a small sample program of adding and subtracting two number using Tensorflow. However I have received different result for the case if I declare variable as tf.Variable or when I declare it directly. So I wonder what is the difference between the 2 ways as I sense that there is a fundamental piece of knowledge about TF that I haven't known which drove me toward the bug.
Here are the code:

```<code>x= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
y= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
#declare 2 tf variables with initial value randomly generated.

# A 'case' statement to perform either addition or subtraction
out = tf.case({tf.less(x, y): lambda: tf.add(x, y), tf.greater(x, y): lambda: tf.subtract(x, y)}, default= lambda: tf.zeros([]), exclusive= True)

#Run the graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    x_value = x.eval()
    y_value = y.eval()
    print("{}\n".format(x_value - y_value))
    out_value, sub_value, add_value = sess.run([out, subtf, addtf])

#Example output: x_value = 0.53607559
                 y_value = -0.63836479
                 add_value = -0.1022892
                 sub_value = 1.1744404
                 out_value = 1.1744404
</code>```

As you see, the case statement works right, the operations are ok.
However, if I omit the tf.Variable from the declaration of x and y , thing go wild:

```<code>x= tf.random_uniform([], minval= -1, maxval= 1)
y= tf.random_uniform([], minval= -1, maxval= 1)
.... All the same as above

#Sample answer run on Spyder: x_value = -0.91663623
                              y_value = -0.80014014
                              add_value = 0.26550484 , should be =-1.71677637
                              sub_value = -0.19451094, should be -0.11649609
                              out_value = 0.26550484, , should be =-1.71677637
</code>```

As you see, the case statement and the operation still perform consistently, but the answer is wrong.
I don't understand why the answers are different?

答:
When you declare a variable as in

```<code>x_var = tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
</code>```

The random values are stored in the variable unless changed by an assignment operation.

Alternatively, declaring

```<code>x_op = tf.random_uniform([], minval= -1, maxval= 1)
</code>```

defines an operation that generates a new random number each time it is called.

For example:

```<code># After calling
sess.run(tf.global_variables_initializer())

sess.run(x_var) # Will return the same randomly generated value every time
sess.run(x_op) # Will return a different random value every time
</code>```

I hope this helps explain why the second version of the code behaves differently.

Body:
I'm writing a small sample program of adding and subtracting two number using Tensorflow. However I have received different result for the case if I declare variable as tf.Variable or when I declare it directly. So I wonder what is the difference between the 2 ways as I sense that there is a fundamental piece of knowledge about TF that I haven't known which drove me toward the bug.
Here are the code:

x= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
y= tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))
#declare 2 tf variables with initial value randomly generated.

# A 'case' statement to perform either addition or subtraction
out = tf.case({tf.less(x, y): lambda: tf.add(x, y), tf.greater(x, y): lambda: tf.subtract(x, y)}, default= lambda: tf.zeros([]), exclusive= True)

#Run the graph
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    x_value = x.eval()
    y_value = y.eval()
    print("{}\n".format(x_value - y_value))
    out_value, sub_value, add_value = sess.run([out, subtf, addtf])

#Example output: x_value = 0.53607559
                 y_value = -0.63836479
                 add_value = -0.1022892
                 sub_value = 1.1744404
                 out_value = 1.1744404

As you see, the case statement works right, the operations are ok.
However, if I omit the tf.Variable from the declaration of x and y , thing go wild:

x= tf.random_uniform([], minval= -1, maxval= 1)
y= tf.random_uniform([], minval= -1, maxval= 1)
.... All the same as above

#Sample answer run on Spyder: x_value = -0.91663623
                              y_value = -0.80014014
                              add_value = 0.26550484 , should be =-1.71677637
                              sub_value = -0.19451094, should be -0.11649609
                              out_value = 0.26550484, , should be =-1.71677637

As you see, the case statement and the operation still perform consistently, but the answer is wrong.
I don't understand why the answers are different?

Body:
When you declare a variable as in

x_var = tf.Variable(tf.random_uniform([], minval= -1, maxval= 1))

The random values are stored in the variable unless changed by an assignment operation.

Alternatively, declaring

x_op = tf.random_uniform([], minval= -1, maxval= 1)

defines an operation that generates a new random number each time it is called.

For example:

# After calling
sess.run(tf.global_variables_initializer())

sess.run(x_var) # Will return the same randomly generated value every time
sess.run(x_op) # Will return a different random value every time

I hope this helps explain why the second version of the code behaves differently.


问:
Conditional Delete in RethinkDB
I would like to delete an object in RethinkDB but only if a condition is met.

I came up with the following function that utilizes replace and null (RethinkDB deletes objects when null is passed in to replace()). However, I cannot get this to work as RethinkDB keeps returning Cannot perform bracket on a non-object non-sequencenull. I am only trying to replace one object. What is wrong?

```<code>r.db('test')
  .table('test')
  .get('123')
  .replace(function(thing) {
    return r.branch(thing('color').ne('green'),
      r.error('Object color must be green to be deleted'),
      null)
  }, { returnChanges: true })
</code>```

答: I think the problem is as Kludge pointed out that you get null from get("123"). You can test for this condition in the branch with thing.eq(null)

Title: Conditional Delete in RethinkDB

Body:
I would like to delete an object in RethinkDB but only if a condition is met.

I came up with the following function that utilizes replace and null (RethinkDB deletes objects when null is passed in to replace()). However, I cannot get this to work as RethinkDB keeps returning Cannot perform bracket on a non-object non-sequencenull. I am only trying to replace one object. What is wrong?

r.db('test')
  .table('test')
  .get('123')
  .replace(function(thing) {
    return r.branch(thing('color').ne('green'),
      r.error('Object color must be green to be deleted'),
      null)
  }, { returnChanges: true })


问:
Problem with an Access 2007 Project connecting to Sql Server 2005
So I've created an Access Project for one of my users so he can connect to a reporting database.  The .adp project connects to the DB and he can query data to his heart's content.  The problem is, no queries can be saved.  Whenever he opens the project, he is presented with the following error:

"This version of Microsoft Access does not support design changes with the version of   Microsoft Sql Server to which your Access project is connected.  See the Microsoft Office Update Web site for the latest information and downloads.  Your design changes will not be saved."

Again, this is Access 2007 and Sql Server 2005.  My googling efforts - which are coming on a day when I seem to be especially stupid - keep bringing up information regarding this error for Access 2002/2003 trying to connect to Sql Server 2005, which is clearly not my problem.

I'm seeing that one can connect to Sql Server with the normal Access databases (.accdb in 2007 or some such), but I'm seeing mixed information regarding whether I want to do this or not.  And since I can't get a copy of Access 2007, I can't really test this (topic for another time).

Before I do down that road, I'd like to get to the bottom of this one.  Anyone have any suggestions, useful links, or useful knowledge?  Or an older developer who knows the answer that is no longer needed, so I can eat him and absorb his knowledge and powers?

答:
I am not sure if I can be of help here.

But you can have a view inside Access which connects to SQL database and use that view.

Alternatively, you can go the other way. Have a DB project with SQL Server & create a linked server to MS-Access DB.

OwnerDisplayName: peacedog

LastEditorDisplayName: CJM

OwnerDisplayName: shahkalpesh


问:
Method overload resolution unexpected behavior
I'm wrestling with a weird, at least for me, method overloading resolution of .net. I've written a small sample to reproduce the issue:

```<code>class Program
{
    static void Main(string[] args)
    {
        var test = new OverloadTest();
        test.Execute(0);
        test.Execute(1);

        Console.ReadLine();
    }
}

public class OverloadTest
{
    public void Execute(object value)
    {
        Console.WriteLine("object overload: {0}", value);
    }

    public void Execute(MyEnum value)
    {
        Console.WriteLine("enum overload: {0}", value);
    }
}

public enum MyEnum
{
    First = 1, Second = 2, Third = 3
}
</code>```

Will print:

```<code>enum overload: 0
object overload: 1
</code>```

Basically the overload called is different depending on the value (0, 1) instead of the given data type.

Could someone explain?

Update

I should have pointed out that there's a different behaviour between C# 2 and C# 3

```<code>Do((long)0) => object overload //C# 2
Do((long)0) => enum overload   //C# 3
</code>```

答:
I agree with Jon Skeet's answer - refer to his post (above) on Jan 11 at 17:32.
To expand further, please refer to C# language specification - page: 110

6.1.3 Implicit enumeration conversions
An implicit enumeration conversion permits the decimal-integer-literal 0 to be converted to any enum-type and to any nullable-type whose underlying type is an enum-type. In the latter case the conversion is evaluated by converting to the underlying enum-type and wrapping the result (§4.1.10).

Still there is a problem:

adding the statement:

test.Execute(-0.0); //object overload: 0

while adding the following:

test.Execute(+0.0); //enum overload: 0

Jacques Colmenero
Enterprise Architect
colmeneroj@videotron.ca

Body:
I'm wrestling with a weird, at least for me, method overloading resolution of .net. I've written a small sample to reproduce the issue:

class Program
{
    static void Main(string[] args)
    {
        var test = new OverloadTest();
        test.Execute(0);
        test.Execute(1);

        Console.ReadLine();
    }
}

public class OverloadTest
{
    public void Execute(object value)
    {
        Console.WriteLine("object overload: {0}", value);
    }

    public void Execute(MyEnum value)
    {
        Console.WriteLine("enum overload: {0}", value);
    }
}

public enum MyEnum
{
    First = 1, Second = 2, Third = 3
}

Will print:

enum overload: 0
object overload: 1

Basically the overload called is different depending on the value (0, 1) instead of the given data type.

Could someone explain?

Update

I should have pointed out that there's a different behaviour between C# 2 and C# 3

Do((long)0) => object overload //C# 2
Do((long)0) => enum overload   //C# 3


问:
JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.ClassNotFoundException: Didn't find class
I am getting the following error:

JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.ClassNotFoundException: Didn't find class "package.name.class" on path: DexPathList[[zip file "/system/framework/sample.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

```<code>JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.ClassNotFoundException: Didn't find class "package.name.class" on path: DexPathList[[zip file "/system/framework/XposedBridge.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56)
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511)
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469)
</code>```

Here is more about the error:

```<code>`jmethodID MethodId;
    JNIEnv * env;
    int nStatus = gVM->GetEnv((void**)&env, JNI_VERSION_1_6);
    int nResult = attachStatus(nStatus, &env);
    LOG_HM("::attach status = %d::\n", nResult);
    if (nResult == ATTACH_FAILED) {
        LOG_HM("Attach failed");
        return ;
    }

jclass classClass = env->GetObjectClass(gTotalUsageClass);
    auto classLoaderClass = env->FindClass("java/lang/ClassLoader");
    auto getClassLoaderMethod = env->GetMethodID(classClass, "getClassLoader",
                                             "()Ljava/lang/ClassLoader;");
    gClassLoader = env->CallObjectMethod(gTotalUsageClass, getClassLoaderMethod);
    gFindClassMethod = env->GetMethodID(classLoaderClass, "findClass",
                                    "(Ljava/lang/String;)Ljava/lang/Class;");

    jclass totalUsage = static_cast<jclass>(env->CallObjectMethod(gClassLoader, gFindClassMethod, env->NewStringUTF("com/a/a/TotalUsageInfo")));

    TotalUsageInfo *info = NULL;
    jobject jUsageInfo = NULL;

        jlong noOfProc = 0;
        jlong memTotal = 0;
        jlong memFree = 0;
        jlong cache = 0;
        jlong buffer = 0;
        jlong cpuUtil = 0;
        //jclass totalUsage = env->FindClass("com/a/a/TotalUsageInfo");
        if (totalUsage == NULL) {
            LOG_HM("Class TotalUsageInfo not Found \n");
            nResult = FAIL;
            detachThread(nResult);
            return;
        }
        else {
             LOG_HM("Class TotalUsageInfo Found \n");
        }

        jmethodID constructor = env->GetMethodID(totalUsage, "<init>", "(JJJJJJ)V");
        if (NULL == constructor) {
            LOG_HM("JNIGetTotalUsageInfo::TotalUsageInfo constructor not found\n");
            nResult = FAIL;
            detachThread(nResult);
            return ;
        }`
</code>```

答:
In order to call GetMethodID, you need to properly attach your C++ thread to the main Java thread.  Like this:

```<code>bool attachThreadToJVM(JNIEnv **env)
{

    bool ret = false;

    if(globalJavaVm != NULL) {
        JavaVMAttachArgs vmAttachArgs;
        vmAttachArgs.version = JNI_VERSION_1_6;
        vmAttachArgs.name = NULL;
        vmAttachArgs.group = NULL;
        jint attachRet = globalJavaVm->AttachCurrentThread(env, &vmAttachArgs);

        if(attachRet == 0)
        {
            ret = true;
        }
    }

    return ret;
}
</code>```

Body:
I am getting the following error:

JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.ClassNotFoundException: Didn't find class "package.name.class" on path: DexPathList[[zip file "/system/framework/sample.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]

JNI DETECTED ERROR IN APPLICATION: JNI GetMethodID called with pending exception java.lang.ClassNotFoundException: Didn't find class "package.name.class" on path: DexPathList[[zip file "/system/framework/XposedBridge.jar"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class dalvik.system.BaseDexClassLoader.findClass(java.lang.String) (BaseDexClassLoader.java:56)
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String, boolean) (ClassLoader.java:511)
26771-26918/package.name.class A/art: art/runtime/java_vm_ext.cc:410]   at java.lang.Class java.lang.ClassLoader.loadClass(java.lang.String) (ClassLoader.java:469)

Here is more about the error:

`jmethodID MethodId;
    JNIEnv * env;
    int nStatus = gVM->GetEnv((void**)&env, JNI_VERSION_1_6);
    int nResult = attachStatus(nStatus, &env);
    LOG_HM("::attach status = %d::\n", nResult);
    if (nResult == ATTACH_FAILED) {
        LOG_HM("Attach failed");
        return ;
    }

jclass classClass = env->GetObjectClass(gTotalUsageClass);
    auto classLoaderClass = env->FindClass("java/lang/ClassLoader");
    auto getClassLoaderMethod = env->GetMethodID(classClass, "getClassLoader",
                                             "()Ljava/lang/ClassLoader;");
    gClassLoader = env->CallObjectMethod(gTotalUsageClass, getClassLoaderMethod);
    gFindClassMethod = env->GetMethodID(classLoaderClass, "findClass",
                                    "(Ljava/lang/String;)Ljava/lang/Class;");

    jclass totalUsage = static_cast<jclass>(env->CallObjectMethod(gClassLoader, gFindClassMethod, env->NewStringUTF("com/a/a/TotalUsageInfo")));

    TotalUsageInfo *info = NULL;
    jobject jUsageInfo = NULL;

        jlong noOfProc = 0;
        jlong memTotal = 0;
        jlong memFree = 0;
        jlong cache = 0;
        jlong buffer = 0;
        jlong cpuUtil = 0;
        //jclass totalUsage = env->FindClass("com/a/a/TotalUsageInfo");
        if (totalUsage == NULL) {
            LOG_HM("Class TotalUsageInfo not Found \n");
            nResult = FAIL;
            detachThread(nResult);
            return;
        }
        else {
             LOG_HM("Class TotalUsageInfo Found \n");
        }

        jmethodID constructor = env->GetMethodID(totalUsage, "<init>", "(JJJJJJ)V");
        if (NULL == constructor) {
            LOG_HM("JNIGetTotalUsageInfo::TotalUsageInfo constructor not found\n");
            nResult = FAIL;
            detachThread(nResult);
            return ;
        }`

Body:
In order to call GetMethodID, you need to properly attach your C++ thread to the main Java thread.  Like this:

bool attachThreadToJVM(JNIEnv **env)
{

    bool ret = false;

    if(globalJavaVm != NULL) {
        JavaVMAttachArgs vmAttachArgs;
        vmAttachArgs.version = JNI_VERSION_1_6;
        vmAttachArgs.name = NULL;
        vmAttachArgs.group = NULL;
        jint attachRet = globalJavaVm->AttachCurrentThread(env, &vmAttachArgs);

        if(attachRet == 0)
        {
            ret = true;
        }
    }

    return ret;
}


问:
how to pollenrich from camel processor
Is it possible to pollenrich from camel processor?

earlier I used camel enpoint:

```<code>.pollEnrich("smb://domain;login:pwd@host/dir?password=pwd&preMove=backup&move=processed&moveFailed=error&charset=UTF-8", 1000)
</code>```

But now I need to call pollEnrich from processor.

答: Yes you can use ConsumerTemplate to poll from endpoints: http://camel.apache.org/polling-consumer.html

Title: how to pollenrich from camel processor

Body:
Is it possible to pollenrich from camel processor?

earlier I used camel enpoint:

.pollEnrich("smb://domain;login:pwd@host/dir?password=pwd&preMove=backup&move=processed&moveFailed=error&charset=UTF-8", 1000)

But now I need to call pollEnrich from processor.


答:
Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which file type they are?

Sure, you can iterate a list (or arraylist) of Objectclass and do what you need.

Is it possible to iterate through an array list and put out only the elements which are of a specific file type (e. g. only the strings)?

Yes, you can use instanceof and do specific actions for specific classes.

Usage example:

```<code>List<Object> genericList = new ArrayList<>();
genericList.add("test");
genericList.add(2);
genericList.add('c');

for (Object object: genericList) {
    // "Put" out object (question 1)
    System.out.println(object);
    // Check object type (question 2)
    if (object instanceof AnyClass) {
        //doSomething()
    }else if (object instanceof AnotherClass){
        //doSomethingElse()
    }
}
</code>```

Title: Is it possible to iterate through an array list with elements of different data types and put them out?

Body:
Without generics it is possible to create an ArrayList with elements of different types. I want to iterate through it and put out the elements. I can not use a for-each-loop, because it wants a specific type. I tried Iterator but wasn't successful.

So I have two questions:

Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which type they are?

Is it possible to iterate through an array list and put out only the elements which are of a specific type (e. g. only the Strings)?

Body:
Is it possible to iterate through an array list and put out (e. g. with System.out.println) all elements no matter of which file type they are?

Sure, you can iterate a list (or arraylist) of Objectclass and do what you need.

Is it possible to iterate through an array list and put out only the elements which are of a specific file type (e. g. only the strings)?

Yes, you can use instanceof and do specific actions for specific classes.

Usage example:

List<Object> genericList = new ArrayList<>();
genericList.add("test");
genericList.add(2);
genericList.add('c');

for (Object object: genericList) {
    // "Put" out object (question 1)
    System.out.println(object);
    // Check object type (question 2)
    if (object instanceof AnyClass) {
        //doSomething()
    }else if (object instanceof AnotherClass){
        //doSomethingElse()
    }
}