问:
Where do I confirm user created with FactoryGirl?
Using rails, devise, rspec & factorygirl:

Trying to create some tests for my site. I'm using the confirmable model for devise so when I create a user using FactoryGirl, the user isn't confirmed.

This is my factories.rb:

```<code>FactoryGirl.define do
  factory :user do
    full_name             "Aren Admin"
    email                 "aren@example.com"
    password              "arenaren"
    password_confirmation "arenaren"
    role_id               ADMIN
  end
end
</code>```

And this is my rspec test file:

```<code>require 'spec_helper'

describe "Admin pages" do

  subject { page }

  describe "home page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit admin_home_path }

    it { should have_content("#{ROLE_TYPES[user.role_id]}") }
  end
end
</code>```

I'm getting an error because the user is not confirmed. By searching around I'm pretty sure I need to use the method 'confirm!' and that it belongs in the factories.rb file, but I'm not sure where to put it.

答:
This is the factory that worked for me</p>

```<code>FactoryGirl.define do
  factory :user do
    sequence :email do |n|
      "address#{n}@example.com"
    end
    sequence :password do |n|
      "password#{n}"
    end

    factory :confirmed_user do
      before(:create) {|user| user.skip_confirmation! }
    end
  end
end
</code>```

Body:
Using rails, devise, rspec & factorygirl:

Trying to create some tests for my site. I'm using the confirmable model for devise so when I create a user using FactoryGirl, the user isn't confirmed.

This is my factories.rb:

FactoryGirl.define do
  factory :user do
    full_name             "Aren Admin"
    email                 "aren@example.com"
    password              "arenaren"
    password_confirmation "arenaren"
    role_id               ADMIN
  end
end

And this is my rspec test file:

require 'spec_helper'

describe "Admin pages" do

  subject { page }

  describe "home page" do
    let(:user) { FactoryGirl.create(:user) }
    before { visit admin_home_path }

    it { should have_content("#{ROLE_TYPES[user.role_id]}") }
  end
end

I'm getting an error because the user is not confirmed. By searching around I'm pretty sure I need to use the method 'confirm!' and that it belongs in the factories.rb file, but I'm not sure where to put it.

Body:
This is the factory that worked for me

FactoryGirl.define do
  factory :user do
    sequence :email do |n|
      "address#{n}@example.com"
    end
    sequence :password do |n|
      "password#{n}"
    end

    factory :confirmed_user do
      before(:create) {|user| user.skip_confirmation! }
    end
  end
end


来源: stackexchange

问:
Simple Pivot Table to Count Unique Values
This seems like a simple Pivot Table to learn with.  I would like to do a count of unique values for a particular value I'm grouping on.

For instance, I have this:

```<code>ABC   123
ABC   123
ABC   123
DEF   456
DEF   567
DEF   456
DEF   456
</code>```

What I want is a pivot table that shows me this:

```<code>ABC   1
DEF   2
</code>```

The simple pivot table that I create just gives me this (a count of how many rows):

```<code>ABC   3
DEF   4
</code>```

But I want the number of unique values instead.

What I'm really trying to do is find out which values in the first column don't have the same value in the second column for all rows.  In other words, "ABC" is "good", "DEF" is "bad"

I'm sure there is an easier way to do it but thought I'd give pivot table a try...

答:
I found the easiest approach is to use the Distinct Count option under Value Field Settings (left click the field in the Values pane). The option for Distinct Count is at the very bottom of the list.

Here are the before (TOP; normal Count) and after (BOTTOM; Distinct Count)

ContentLicense: CC BY-SA 3.0

Body:
This seems like a simple Pivot Table to learn with.  I would like to do a count of unique values for a particular value I'm grouping on.

For instance, I have this:

ABC   123
ABC   123
ABC   123
DEF   456
DEF   567
DEF   456
DEF   456

What I want is a pivot table that shows me this:

ABC   1
DEF   2

The simple pivot table that I create just gives me this (a count of how many rows):

ABC   3
DEF   4

But I want the number of unique values instead.

What I'm really trying to do is find out which values in the first column don't have the same value in the second column for all rows.  In other words, "ABC" is "good", "DEF" is "bad"

I'm sure there is an easier way to do it but thought I'd give pivot table a try...


问:
MySQL AUTO_INCREMENT does not ROLLBACK
I'm using MySQL's AUTO_INCREMENT field and InnoDB to support transactions. I noticed when I rollback the transaction, the AUTO_INCREMENT field is not rollbacked? I found out that it was designed this way but are there any workarounds to this? </p>

答:
If you need to have the ids assigned in numerical order with no gaps, then you can't use an autoincrement column.  You'll need to define a standard integer column and use a stored procedure that calculates the next number in the insert sequence and inserts the record within a transaction.  If the insert fails, then the next time the procedure is called it will recalculate the next id.

Having said that, it is a bad idea to rely on ids being in some particular order with no gaps.  If you need to preserve ordering, you should probably timestamp the row on insert (and potentially on update).

OwnerDisplayName: Gian Paulo

ContentLicense: CC BY-SA 2.5

Title: MySQL AUTO_INCREMENT does not ROLLBACK

OwnerDisplayName: tvanfosson


问:
Unity3D update local assetBundle
In my project, I have a bunch of items stored as assetBundles. In my server, I stored a list of item including their id and version. So ideally, using UnityWebRequest.GetAssetBundle(uri, versionId)I just get the item lists every time I open the app, if first opened, it will download every item; if secondly open, it will only download the one I have updated the version number on the server. Everything is very easy.

But now, I want to store those assetBundles at local first so that people don't need to download with cellular data.Is there an easy way to manage those assetBundles?

答:
You can place the AssetBundles in the StreamingAssets folder. This is what the folder should look like:

```<code>Assets/StreamingAssets/
</code>```

When you build the project, Unity will include the AssetBundles in the build. Of-course, you can use the Resources API but the StreamingAssets folder seems to be more appropriate here.

Once you place the AssetBundles there, you can use Application.streamingAssetsPath and AssetBundle.LoadFromFile to load the AssetBundle.

You can also use the WWW API with Application.streamingAssetsPath to load the AssetBundle.

Title: Unity3D update local assetBundle

Body:
You can place the AssetBundles in the StreamingAssets folder. This is what the folder should look like:

Assets/StreamingAssets/

When you build the project, Unity will include the AssetBundles in the build. Of-course, you can use the Resources API but the StreamingAssets folder seems to be more appropriate here.

Once you place the AssetBundles there, you can use Application.streamingAssetsPath and AssetBundle.LoadFromFile to load the AssetBundle.

You can also use the WWW API with Application.streamingAssetsPath to load the AssetBundle.


问:
C - How do I use realloc with pointers
I'm having trouble using realloc in this case. My compiler, devC++, keeps telling me it's an invalid application of 'sizeof' to incomplete type 'struct WaitlistEntry'. I'm basically trying to malloc a struct using the given structs, and then store the data in it.

Here is the entire function:

```<code>void attemptEnrollment( Course* pCourse, int iStudentID, int iPriority ){

    if (pCourse->iNumEnrolled < pCourse->iMaxEnrolled)
        enrollStudent(pCourse, iStudentID);
    else {
        WaitlistEntry w1;
        w1 = (struct WaitlistEntry*)malloc(sizeof(struct WaitlistEntry));
        w1.iStudentID = iStudentID;
        w1.iPriority = iPriority;
        waitlistStudent(pCourse,w1);
    }
}
</code>```

Here are the structs:

```<code>typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;
</code>```

答:
You are confused and need to read a book about C programming. Your trouble is first to declare your types and structures correctly and consistently. I would suggest:

```<code>typedef struct WaitlistEntry_st {
  int iPriority;          /* Priority of the student to be enrolled */
  int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode_st {
  WaitlistEntry info;     /* WaitlistEntry stored in the node
                             (sorted with largest priority first) */
  struct PQNode_st* pNext;   /* Pointer to next node in the LL */
  struct PQNode_st* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct Course_st {
  int iCourseNumber;      /* Course number of the course */
  int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
  int iNumEnrolled;       /* Number of Students currently enrolled in course */
  int iMaxEnrolled;       /* Max number of Students that can enroll
                              in the course */
  PQNode* pFront;         /* Priority queue representing the waitlist
                             for the course */
} Course;
</code>```

Notice the consistency above: the tags of structs (the name following immediately struct) is suffixed with _st (and in C - but not in C++ - names of struct tags are in a different namespace than names of typedef).

Then you would code

```<code>    WaitlistEntry* w1 = malloc(sizeof(WaitlistEntry));
    if (!w1) { perror("malloc WaitlistEntry"); exit(EXIT_FAILURE); };
    w1->iStudentID = iStudentID;
    w1->iPriority = iPriority;
</code>```

notice that every call to malloc should be tested against failure.

BTW, I recommend reading some existing code for inspiration. You'll find a lot of free software code (e.g. on github or sourceforge) and reading some of it is inspirational and instructive.

Don't forget to enable all warnings and debug info. So pass -Wall -Wextra -g to your gcc compiler (perhaps a MINGW variant) used by your Dev-C++ IDE.

Title: C - How do I use realloc with pointers

Body:
I'm having trouble using realloc in this case. My compiler, devC++, keeps telling me it's an invalid application of 'sizeof' to incomplete type 'struct WaitlistEntry'. I'm basically trying to malloc a struct using the given structs, and then store the data in it.

Here is the entire function:

void attemptEnrollment( Course* pCourse, int iStudentID, int iPriority ){

    if (pCourse->iNumEnrolled < pCourse->iMaxEnrolled)
        enrollStudent(pCourse, iStudentID);
    else {
        WaitlistEntry w1;
        w1 = (struct WaitlistEntry*)malloc(sizeof(struct WaitlistEntry));
        w1.iStudentID = iStudentID;
        w1.iPriority = iPriority;
        waitlistStudent(pCourse,w1);
    }
}

Here are the structs:

typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;

Body:
You are confused and need to read a book about C programming. Your trouble is first to declare your types and structures correctly and consistently. I would suggest:

typedef struct WaitlistEntry_st {
  int iPriority;          /* Priority of the student to be enrolled */
  int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode_st {
  WaitlistEntry info;     /* WaitlistEntry stored in the node
                             (sorted with largest priority first) */
  struct PQNode_st* pNext;   /* Pointer to next node in the LL */
  struct PQNode_st* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct Course_st {
  int iCourseNumber;      /* Course number of the course */
  int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
  int iNumEnrolled;       /* Number of Students currently enrolled in course */
  int iMaxEnrolled;       /* Max number of Students that can enroll
                              in the course */
  PQNode* pFront;         /* Priority queue representing the waitlist
                             for the course */
} Course;

Notice the consistency above: the tags of structs (the name following immediately struct) is suffixed with _st (and in C - but not in C++ - names of struct tags are in a different namespace than names of typedef).

Then you would code

    WaitlistEntry* w1 = malloc(sizeof(WaitlistEntry));
    if (!w1) { perror("malloc WaitlistEntry"); exit(EXIT_FAILURE); };
    w1->iStudentID = iStudentID;
    w1->iPriority = iPriority;

notice that every call to malloc should be tested against failure.

BTW, I recommend reading some existing code for inspiration. You'll find a lot of free software code (e.g. on github or sourceforge) and reading some of it is inspirational and instructive.

Don't forget to enable all warnings and debug info. So pass -Wall -Wextra -g to your gcc compiler (perhaps a MINGW variant) used by your Dev-C++ IDE.


问:
Swift - Use of unresolved identifier 'self' - from Closure in a Class
I am trying to reference a property in my class from a closure declared in my class. I cannot access self from inside my closure, and I'm assuming self would refer to the Class API from within my closure.

I want to declare a closure that I use later as a parameter to pass to a URLSession dataTask (It works without the one error line). I get the error listed in the title.

Use of unresolved identifier 'self'

I've been writing swift for an entire day now and am just trying things out as a sandbox, so I fully expect some criticism.

```<code>class Api {

    struct Location {
        var name = String()
        var author = String()
        var averageRating: String?
        var id = Int()
        var lat = Double()
        var lon = Double()
        var type = String()
    }

    var locations = [Location]()

    var doSomething = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
        if error != nil {
            print(error!.localizedDescription)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                    let myResult = json["results"] as! [[String: Any]]
                    var location : Location! = Location()
                    for jsonLocation in myResult {
                        if let name = jsonLocation["name"]{location.name = name as! String}
                        if let author = jsonLocation["author"]{location.author = author as! String}
                        if let id = jsonLocation["id"]{location.id = id as! Int}
                        if let lat = jsonLocation["lat"]{location.lat = lat as! Double}
                        if let lon = jsonLocation["lon"]{location.lon = lon as! Double}
                        if let type = jsonLocation["type"]{location.type = type as! String}

                        //ERROR IS HERE, Why does self not reference class API?
                        self.locations.append(location)
                    }
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    }
}
</code>```

I have found this, but this example is different so I wasn't sure if it was the same bug or me not understanding swift.

答:
I have the same questions as you and I solve it using lazy var

Here is a quick example

My originally code is:

```<code>class MyClass {
    let callback:()->() = {
        self.foo()   // Compile error: Use of unresolved identifier "self"
    }

    func foo() {
        print("bar")
    }
}
</code>```

It compile error at that line I use self

But I change it to

```<code>class MyClass {
    lazy var callback:()->() = {
        [unowned self] in
        self.foo()
    }

    func foo() {
        print("bar")
    }
}

let c = MyClass()
c.callback()
</code>```

that solved the problem

References:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

http://mikebuss.com/2014/06/22/lazy-initialization-swift/

Shall we always use [unowned self] inside closure in Swift

Body:
I am trying to reference a property in my class from a closure declared in my class. I cannot access self from inside my closure, and I'm assuming self would refer to the Class API from within my closure.

I want to declare a closure that I use later as a parameter to pass to a URLSession dataTask (It works without the one error line). I get the error listed in the title.

Use of unresolved identifier 'self'

I've been writing swift for an entire day now and am just trying things out as a sandbox, so I fully expect some criticism.

class Api {

    struct Location {
        var name = String()
        var author = String()
        var averageRating: String?
        var id = Int()
        var lat = Double()
        var lon = Double()
        var type = String()
    }

    var locations = [Location]()

    var doSomething = {(data: Data?, response: URLResponse?, error: Error?) -> Void in
        if error != nil {
            print(error!.localizedDescription)
        } else {
            do {
                if let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? [String: Any] {
                    let myResult = json["results"] as! [[String: Any]]
                    var location : Location! = Location()
                    for jsonLocation in myResult {
                        if let name = jsonLocation["name"]{location.name = name as! String}
                        if let author = jsonLocation["author"]{location.author = author as! String}
                        if let id = jsonLocation["id"]{location.id = id as! Int}
                        if let lat = jsonLocation["lat"]{location.lat = lat as! Double}
                        if let lon = jsonLocation["lon"]{location.lon = lon as! Double}
                        if let type = jsonLocation["type"]{location.type = type as! String}

                        //ERROR IS HERE, Why does self not reference class API?
                        self.locations.append(location)
                    }
                }
            } catch {
                print("error in JSONSerialization")
            }
        }
    }
}

I have found this, but this example is different so I wasn't sure if it was the same bug or me not understanding swift.

Body:
I have the same questions as you and I solve it using lazy var

Here is a quick example

My originally code is:

class MyClass {
    let callback:()->() = {
        self.foo()   // Compile error: Use of unresolved identifier "self"
    }

    func foo() {
        print("bar")
    }
}

It compile error at that line I use self

But I change it to

class MyClass {
    lazy var callback:()->() = {
        [unowned self] in
        self.foo()
    }

    func foo() {
        print("bar")
    }
}

let c = MyClass()
c.callback()

that solved the problem

References:
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html

http://mikebuss.com/2014/06/22/lazy-initialization-swift/

Shall we always use [unowned self] inside closure in Swift


问:
How iOS's coordinate system works?
nice to meet you. I am studying "Coordinate System" of UIView of iOS.
Frame is easy to understand, but Bounds isn't.

For example, Frame works as expected when you change origin.

Bounds does not change its position even if we change origin.

```<code>import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let rect = CGRect(x: 20, y: 30, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 5, animations: {
            self.childView.bounds = CGRect(x: 100, y: 150, width: 200, height: 200)
        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

"Why do we need Bounds?" I thought.
And I searched hard on the internet. So, there are some facts I found out.

----First----

Bounds literally means borderline. iOS can draw a picture only within that boundary line. As you can see in the figure above, the UIButton also has Bounds, and when it exceeds the Bounds, the picture is cut and drawn.

---- Second ----
Size of Bounds and Size of Frame are the same.

It's not important, but I tried to test it out.

---- Thirds ----
bounds.origin is also useful in View Hierarchy. But it works differently from Frame.

Frame is easy to understand.
The ViewController's RootView will be 700 from top to button.

```<code>import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 100, y: 100, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
        self.view.backgroundColor = UIColor.cyan
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 10, animations: {

        self.view.frame = CGRect(x: 0, y: 700, width: self.view.frame.size.width, height: self.view.frame.size.height)

        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

If you look at the Coordinate System in iOS, you can see that Frame should work like that.

However, Bounds does not move itself, but only the Subview below it. I do not understand this part.

```<code>import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 100, y: 100, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
        self.view.backgroundColor = UIColor.cyan
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 10, animations: {

        self.view.bounds = CGRect(x: 0, y: 700, width: self.view.frame.size.width, height: self.view.frame.size.height)

        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

So, I searched it in google.
Eventually, I found a mathematical formula for "SubView" to reposition when SuperView.origin.bounds was changed.
( 출처 : article )

```<code>CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;
</code>```

By the way, why did Apple use these formulas? Basically, based on the "Coordinate System" we think,

```<code>CompositedPosition.x = View.frame.origin.x + Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y + Superview.bounds.origin.y;
</code>```

Is not this formula more intuitive?

So, My Question are these.

When I increase SuperView.bounds.origin.y by 700 in its original state, why does SubView move up not moving down ???

Should I just accept the formula and memorize it?

---------------------------------------------------------------

----------------------------Edit--1----------------------------

Now I Got the concept of bounds by studying UIScrollView!

```<code>CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;
</code>```

This is right.

This is a picture what I understand.

yes, I agree this picture looks dizzy sorry!

If I scroll UP the scrollview, and bounds.origin.y will increase and offset.y will increase and the subviews attached in scrollview's frame.origin.y will not change but, iOS calculate where the subviews to draw(CompositedPosition) by using that formula so! It looks like that the subviews goes UP!.

In brief, bounds change -> iOS calculate by using that formula -> draw!

答:
First, please post in English or another supported language.

Second I think I might have understand what you are going for and here is the general simple answer.

First there is a coordinate system for everything, but each view also has its own coordinated system. Each subview of a view is defined inside of the superviews coordinate system.

I would try and say more but I am purely going of the pictures. And also even in the post was in English, I have trouble believing this post is a minimal example of the presented problem

Title: How iOS's coordinate system works?

Body:
nice to meet you. I am studying "Coordinate System" of UIView of iOS.
Frame is easy to understand, but Bounds isn't.

For example, Frame works as expected when you change origin.

Bounds does not change its position even if we change origin.

import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let rect = CGRect(x: 20, y: 30, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 5, animations: {
            self.childView.bounds = CGRect(x: 100, y: 150, width: 200, height: 200)
        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

"Why do we need Bounds?" I thought.
And I searched hard on the internet. So, there are some facts I found out.

----First----

Bounds literally means borderline. iOS can draw a picture only within that boundary line. As you can see in the figure above, the UIButton also has Bounds, and when it exceeds the Bounds, the picture is cut and drawn.

---- Second ----
Size of Bounds and Size of Frame are the same.

It's not important, but I tried to test it out.

---- Thirds ----
bounds.origin is also useful in View Hierarchy. But it works differently from Frame.

Frame is easy to understand.
The ViewController's RootView will be 700 from top to button.

import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 100, y: 100, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
        self.view.backgroundColor = UIColor.cyan
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 10, animations: {

        self.view.frame = CGRect(x: 0, y: 700, width: self.view.frame.size.width, height: self.view.frame.size.height)

        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

If you look at the Coordinate System in iOS, you can see that Frame should work like that.

However, Bounds does not move itself, but only the Subview below it. I do not understand this part.

import UIKit

class ViewController: UIViewController {

    var childView : UIView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let rect = CGRect(x: 100, y: 100, width: 200, height: 200)
        childView = UIView(frame: rect)
        childView.backgroundColor = UIColor.red
        self.view.addSubview(childView)
        self.view.backgroundColor = UIColor.cyan
    }

    override func viewDidAppear(_ animated: Bool) {
        UIView.animate(withDuration: 10, animations: {

        self.view.bounds = CGRect(x: 0, y: 700, width: self.view.frame.size.width, height: self.view.frame.size.height)

        })
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

So, I searched it in google.
Eventually, I found a mathematical formula for "SubView" to reposition when SuperView.origin.bounds was changed.
( 출처 : article )

CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;

By the way, why did Apple use these formulas? Basically, based on the "Coordinate System" we think,

CompositedPosition.x = View.frame.origin.x + Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y + Superview.bounds.origin.y;

Is not this formula more intuitive?

So, My Question are these.

When I increase SuperView.bounds.origin.y by 700 in its original state, why does SubView move up not moving down ???

Should I just accept the formula and memorize it?

---------------------------------------------------------------

----------------------------Edit--1----------------------------

Now I Got the concept of bounds by studying UIScrollView!

CompositedPosition.x = View.frame.origin.x - Superview.bounds.origin.x;
CompositedPosition.y = View.frame.origin.y - Superview.bounds.origin.y;

This is right.

This is a picture what I understand.

yes, I agree this picture looks dizzy sorry!

If I scroll UP the scrollview, and bounds.origin.y will increase and offset.y will increase and the subviews attached in scrollview's frame.origin.y will not change but, iOS calculate where the subviews to draw(CompositedPosition) by using that formula so! It looks like that the subviews goes UP!.

In brief, bounds change -> iOS calculate by using that formula -> draw!


问:
Document.ready or run after certain time?
i have preloader , which hides after document.ready .

```<code>angular.element(document).ready(function () {
    var el =  document.getElementById('preloader');
    fadeOut(el);
});
</code>```

Sometimes document loads so slowly , because of 1 or 2 big size photos , so i don't need to wait for this photos and need to hide preloader after 5000ms.

How can i do that ?
Thanks in advance .

答:
That "document ready" process you're using is simply wrapping jQuery's (now deprecated) .ready() method. It does not wait for all images to load, it only waits for the DOM to be parsed. The window.onload event is the event that only fires after all images have loaded.

Instead, Angular has a directive called ng-cloak to prevent a "flash of unstyled content" (FOUC). The cloak works by putting a class on a top level element, which you can then style to hide part, or all, of the page while you wait for a "ready" state. You can use CSS transitions, rather than the jQuery .fadeOut() effect, to do a slow fade out on your preloader once the cloak is removed.

Body:
i have preloader , which hides after document.ready .

angular.element(document).ready(function () {
    var el =  document.getElementById('preloader');
    fadeOut(el);
});

Sometimes document loads so slowly , because of 1 or 2 big size photos , so i don't need to wait for this photos and need to hide preloader after 5000ms.

How can i do that ?
Thanks in advance .


问:
Does JSSE implement a fallback if the server does not support the used protocol?
I'm just gathering some information about SSL/TSL within java, as we are using netty without even knowing what TLS protocol we are using currently. Our application runs on Java7, so a SSLSocket will run with TLS1 by default and SSL3 is not even activated. That I know now.

Assuming my client runs on Java8 (that uses by default TLS1.2) the target server only supports TLS1.1, is JSSE now using an automatic fallback routing to negotiate a connection with TLS1.1? Or do I have to implement this specifically? If yes, where would I have to do that?

I couldn't find a clear point for that in the JSSE documentation.

答:
is JSSE now using an automatic fallback ...?

It doesn't have to.

A TLS client sends the highest version of the TLS protocol it can support. The server replies with the TLS version it wants to use, which is the lower of the highest version the server supports and the version sent by the client. If the client supports that version, the handshake proceeds. So it is actually the server that does the fallback.

This is all specified in RFC 2246. It is not peculiar to Java.


问:
Regex matching beginning AND end strings where the two strings are same
I have the following code:

```<code><?php
    $subject="something";
    $pattern="something";
    If(preg_match($pattern,$subject)){
        echo "Match is found";
    }else{
        echo "Match is not found";
    }
?>
</code>```

If I have

```<code>$subject="apple is fruit and I love apple";
</code>```

The main point being the string beginning with apple and ending with apple

Then what should be the pattern so that

match is found

is the output.

I know the pattern can be

```<code>"/^apple.*apple$/"
</code>```

But I don't want to repeat the same word apple.

答:
You just need a backreference. Try:

```<code>/^(\w+).*(\1)$/
</code>```

The (\w+) captures the first word, no matter what it is, without having to specify "apple" as the word. The backreference, \1 tells the regex parser to substitute in whatever was captured in the first capture group. Using the magic of backtracking, the regex parser will figure out how to fit match the input symbols correctly to satisfy the backreference.

Body:
I have the following code:

<?php
    $subject="something";
    $pattern="something";
    If(preg_match($pattern,$subject)){
        echo "Match is found";
    }else{
        echo "Match is not found";
    }
?>

If I have

$subject="apple is fruit and I love apple";

The main point being the string beginning with apple and ending with apple

Then what should be the pattern so that

match is found

is the output.

I know the pattern can be

"/^apple.*apple$/"

But I don't want to repeat the same word apple.

Body:
You just need a backreference. Try:

/^(\w+).*(\1)$/

The (\w+) captures the first word, no matter what it is, without having to specify "apple" as the word. The backreference, \1 tells the regex parser to substitute in whatever was captured in the first capture group. Using the magic of backtracking, the regex parser will figure out how to fit match the input symbols correctly to satisfy the backreference.


问:
Fastest primality test
Could you suggest a fast, deterministic method that is usable in practice, for testing if a large number is prime or not?

Also, I would like to know how to use non-deterministic primality tests correctly. For example, if I'm using such a method, I can be sure that a number is not prime if the output is "no", but what about the other case, when the output is "probably"? Do I have to test for primality manually in this case?

Thanks in advance.

答:
"Probably" actually means 1-ε, and ε gets as small as you need.

Most applications have some small yet nonzero probability of failing that is not connected to primality testing, for example

in cryptographic applications, an attacker luckily guessing the secret with, for example,
a probability of 2^(-100)

a hardware failure (radiation-induced) randomly flipping some bit of your computer memory (maybe one that holds the output of your "deterministic" primality test

bugs (indeed, more probable than the other type of failures)

So pressing the ε to that order of magnitude will suffice in practice.

For example, OpenSSL, GnuPG of use non-deterministic primality test only. ``Probably'' you don't really want no deterministic test. But check what is available to you: If you have any libraries at hand, and they perform enough - go on and use them.

Title: Fastest primality test


问:
Do jQuery's val() and prop() methods html-escape values?
I can't find anything in the documentation about val() and prop() and escaping.

Are they intended to escape values when used as setters?

答: I just want to add that you DO have to worry when inserting values inside attributes with side effects which can cause code execution. These include image src attribute which can be used for xss. See: https://www.owasp.org/index.php/Script_in_IMG_tags</p>


问:
Calculate an Average from user input of five to ten numbers using Methods
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

```<code>public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());

        double count = 0;
        double average = 0.0;
        double sum =0;

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput);
        }

        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}
</code>```

答:
count how many spaces there are in your string.  You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String

e.g.

```<code>    String fiveNums = "1 2 3 4 5";
    String noSpaces = fiveNums.replace(" ", "");
    System.out.println(fiveNums.length() - noSpaces.length());
</code>```

ContentLicense: CC BY-SA 4.0

Body:
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());

        double count = 0;
        double average = 0.0;
        double sum =0;

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput);
        }

        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}

Body:
count how many spaces there are in your string.  You can do this either by looping and checking the char value or you can do a replace on the string and compare the size of the new String

e.g.

    String fiveNums = "1 2 3 4 5";
    String noSpaces = fiveNums.replace(" ", "");
    System.out.println(fiveNums.length() - noSpaces.length());


问:
spray Collection ToResponseMarshallable
I am trying to return a List from my complete directive in spray-routing.

```<code>complete {
  List("hello")
}
</code>```

However, I am getting an error -

```<code>Expression of type List[String] doesn't conform to expected type ToResponseMarshallable
</code>```

I am getting the same error with Seq. I see that marshallers for List and Seq are not provided by default in spray-httpx documentation. However, spray-json provides marshalling support in its DefaultJsonProtocol. I have imported spray.httpx.SprayJsonSupport._ and spray.json.DefaultJsonProtocol._ in my code, but that too hasn't helped.

Any idea how can I marshal a List/Seq using spray-json? Or will I have to write my own Marshaller?

(My scala version is 2.11.4)

答:
API for marshalling seems to have changed since akka 2.3.5. For akka-2.4.11.2, SprayJsonSupport needs import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

1) Following is working sbt,

```<code>name := "some-project"

version := "1.0"

scalaVersion := "2.11.5"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

val akkaVersion = "2.4.5"

libraryDependencies ++= {
  Seq(
    "com.typesafe.akka" %% "akka-http-experimental" % akkaVersion,
    "com.typesafe.akka" % "akka-http-spray-json-experimental_2.11" % akkaVersion,
    "com.typesafe.akka" %% "akka-slf4j" % akkaVersion,

    "org.mongodb" % "mongo-java-driver" % "3.4.1",
    "org.apache.kafka" %% "kafka" % "0.10.1.1",
    "org.apache.kafka" % "kafka-clients" % "0.10.1.1",

    //test
    "org.scalatest" %% "scalatest" % "2.2.5" % "test",
    "com.typesafe.akka" %% "akka-http-testkit" % "10.0.9" % "test",
    "de.flapdoodle.embed" % "de.flapdoodle.embed.mongo" % "2.0.0" % "test"
  )
}

parallelExecution in Test := false
</code>```

2) And imports are,

```<code>import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

object GetMusicResources {

  val music_get_api =
    path("music") {
      get {
        complete {
          List("my data1")
        }
      }
    }
}
</code>```

3) Tests

```<code>  Get("/music") ~> GetMusicResources.music_get_api ~> check {
    val response1: Future[ByteString] = response.entity.toStrict(300.millis).map {_.data }

    response1.map(_.utf8String).map { responseString =>
      responseString shouldBe """["my data1"]"""
    }

  }
</code>```

Title: spray Collection ToResponseMarshallable

Body:
I am trying to return a List from my complete directive in spray-routing.

complete {
  List("hello")
}

However, I am getting an error -

Expression of type List[String] doesn't conform to expected type ToResponseMarshallable

I am getting the same error with Seq. I see that marshallers for List and Seq are not provided by default in spray-httpx documentation. However, spray-json provides marshalling support in its DefaultJsonProtocol. I have imported spray.httpx.SprayJsonSupport._ and spray.json.DefaultJsonProtocol._ in my code, but that too hasn't helped.

Any idea how can I marshal a List/Seq using spray-json? Or will I have to write my own Marshaller?

(My scala version is 2.11.4)

Body:
API for marshalling seems to have changed since akka 2.3.5. For akka-2.4.11.2, SprayJsonSupport needs import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._

1) Following is working sbt,

name := "some-project"

version := "1.0"

scalaVersion := "2.11.5"

scalacOptions := Seq("-unchecked", "-deprecation", "-encoding", "utf8")

val akkaVersion = "2.4.5"

libraryDependencies ++= {
  Seq(
    "com.typesafe.akka" %% "akka-http-experimental" % akkaVersion,
    "com.typesafe.akka" % "akka-http-spray-json-experimental_2.11" % akkaVersion,
    "com.typesafe.akka" %% "akka-slf4j" % akkaVersion,

    "org.mongodb" % "mongo-java-driver" % "3.4.1",
    "org.apache.kafka" %% "kafka" % "0.10.1.1",
    "org.apache.kafka" % "kafka-clients" % "0.10.1.1",

    //test
    "org.scalatest" %% "scalatest" % "2.2.5" % "test",
    "com.typesafe.akka" %% "akka-http-testkit" % "10.0.9" % "test",
    "de.flapdoodle.embed" % "de.flapdoodle.embed.mongo" % "2.0.0" % "test"
  )
}

parallelExecution in Test := false

2) And imports are,

import akka.http.scaladsl.marshallers.sprayjson.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

object GetMusicResources {

  val music_get_api =
    path("music") {
      get {
        complete {
          List("my data1")
        }
      }
    }
}

3) Tests

  Get("/music") ~> GetMusicResources.music_get_api ~> check {
    val response1: Future[ByteString] = response.entity.toStrict(300.millis).map {_.data }

    response1.map(_.utf8String).map { responseString =>
      responseString shouldBe """["my data1"]"""
    }

  }


问:
VS2017 Intellisense is slow and sometimes it crashes, any suggestions?
I'm working with the community edition of VS2017.
Version 15.2(26430.14) which is the latest update as of 07/Jul/2017.
Intellisense is sporadically slow, and stops normal progress of my coding effort.  It seems to "wake up" after about a 10 to 20 second wait.  But today, it crashed, and the activity log showed this information.

```<code> <entry>
<record>1709</record>
<time>2017/07/06 00:17:33.497</time>
<type>Error</type>
<source>Editor or Editor Extension</source>
<description>System.InvalidOperationException: Cannot Match.  The session is dismissed.

at Microsoft.VisualStudio.Language.Intellisense.Implementation.CompletionSession.Match()

at Microsoft.VisualStudio.Language.Intellisense.Implementation.CompletionSession.OnViewBuffer_Changed(Object sender, TextContentChangedEventArgs e)

at Microsoft.VisualStudio.Text.Utilities.GuardedOperations.RaiseEvent[TArgs](Object sender, EventHandler`1 eventHandlers, TArgs args)
</code>```

At the time I was editing XAML and adding a Binding to the IsOpen property of a ContextMenu. After closing the editor and reopening, it worked fine...

I've removed all Plug-ins but Code Maid, which I'll try next.  However, I'm looking for suggestions to this hiccup.

答: I had a similar problem. I closed Visual Studio and deleted the .vs (hidden) folder and restarted. It automatically regenerated the folder.</p>

Body:
I'm working with the community edition of VS2017.
Version 15.2(26430.14) which is the latest update as of 07/Jul/2017.
Intellisense is sporadically slow, and stops normal progress of my coding effort.  It seems to "wake up" after about a 10 to 20 second wait.  But today, it crashed, and the activity log showed this information.

 <entry>
<record>1709</record>
<time>2017/07/06 00:17:33.497</time>
<type>Error</type>
<source>Editor or Editor Extension</source>
<description>System.InvalidOperationException: Cannot Match.  The session is dismissed.

at Microsoft.VisualStudio.Language.Intellisense.Implementation.CompletionSession.Match()

at Microsoft.VisualStudio.Language.Intellisense.Implementation.CompletionSession.OnViewBuffer_Changed(Object sender, TextContentChangedEventArgs e)

at Microsoft.VisualStudio.Text.Utilities.GuardedOperations.RaiseEvent[TArgs](Object sender, EventHandler`1 eventHandlers, TArgs args)

At the time I was editing XAML and adding a Binding to the IsOpen property of a ContextMenu. After closing the editor and reopening, it worked fine...

I've removed all Plug-ins but Code Maid, which I'll try next.  However, I'm looking for suggestions to this hiccup.


问:
multiplication for lists in python
I know there is something obvious that I am missing but I would rather clear my confusion than to mug it up.
why does the following code:
[1]*5
return
[1,1,1,1,1]

and not
[5]

or

[[1],[1],[1],[1],[1]]

答:
Multiplication is defined for sequences in general, not just lists, regardless of the type of the contained values. Sure, [1] * 5 -> [5] makes sense for a list of int, but it's nonsensical for a list of str, or a str by itself.

They wanted a generic sequence handler that worked for sequences of all types, so they defined it as repeated concatenation, rather than element-wise arithmetic. As juanpa mentions in the comments, this makes for a consistent definition: seq + seq is concatenation, so seq * int is just seq + seq repeated int times (well, seq is repeated int times, with four virtual concatenations), the same way inta * intb is just inta + inta repeated intb times.

If you want element-wise arithmetic, take a look at numpy arrays.

Title: multiplication for lists in python


问:
What is the fastest checksumming algorithm for a buffer of size 4096?
I'm looking for a hash/checksum algorithm that is as fast as possible while still being able to detect changes to a 4096 byte memory page. Because the size is fixed I hope it should be possible to attain an optimized algorithm exactly for this purpose, since the size is guaranteed to not change.

What I'm doing is checksumming some memory pages, doing an operation, then checksumming the pages again to see if they've changed. Due to space reasons it is not feasible to simply compare bytewise with a copy of the old bytes. I don't need know where within the page the change occurred, just if a change happened, so comparing the checksums is enough.

I've tried CRC32 in hardware and xxHash, both with good results. Still, as far as I know they are not tailored for a fixed size buffer.

Edit: Here is the code I'm using for CRC32 in hardware. For some reason it's slower than xxHash.

```<code>// Warning! Not padding, so don't use if length isn't dividable by sizeof(uint32_t).
uint32_t sse42_crc32_32bit(const uint32_t* buffer, const uint32_t length)
{
    uint32_t crc = 0;
    const uint32_t numRounds = length / sizeof(uint32_t);

    for (uint32_t i = 0; i < numRounds; ++i)
    {
        crc = _mm_crc32_u32(crc, buffer[i]);
    }

    return crc;
}
</code>```

答:
There is farmHash128, which is faster than xxHash64. I'm not sure about its quality, though.

If you use xxHash64, I think that you can unroll it a little bit (for example, 8 times), and it will be a little bit faster. And if the page is not in cache, prefetching may help.

Note, however, this

"If I miss one bit of change it's game over."

is a risky game to play. xxHash64's 64-bit of output is surely inadequate for this. You will surely have hash collisions. I'd say that you'll need to use a 256-bit hash at least for this purpose. It won't detect changes 100%, but close. The usual wisdom is to use hash size which has a lower collision probability than the probability of system failure (multiplied by 10^-X, where X is a "smallish" positive number, like 5).

Body:
I'm looking for a hash/checksum algorithm that is as fast as possible while still being able to detect changes to a 4096 byte memory page. Because the size is fixed I hope it should be possible to attain an optimized algorithm exactly for this purpose, since the size is guaranteed to not change.

What I'm doing is checksumming some memory pages, doing an operation, then checksumming the pages again to see if they've changed. Due to space reasons it is not feasible to simply compare bytewise with a copy of the old bytes. I don't need know where within the page the change occurred, just if a change happened, so comparing the checksums is enough.

I've tried CRC32 in hardware and xxHash, both with good results. Still, as far as I know they are not tailored for a fixed size buffer.

Edit: Here is the code I'm using for CRC32 in hardware. For some reason it's slower than xxHash.

// Warning! Not padding, so don't use if length isn't dividable by sizeof(uint32_t).
uint32_t sse42_crc32_32bit(const uint32_t* buffer, const uint32_t length)
{
    uint32_t crc = 0;
    const uint32_t numRounds = length / sizeof(uint32_t);

    for (uint32_t i = 0; i < numRounds; ++i)
    {
        crc = _mm_crc32_u32(crc, buffer[i]);
    }

    return crc;
}


问:
How to hide mouse cursor with jquery
How to hide mouse cursor with jquery in entire webpage.
 I tried this

```<code>$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});
</code>```

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.

答: What about using a transparent div overlay (div with an absolute position, 100% width and height, and positive z-index) with cursor set to none. Then use jQuery to toggle it on/off?</p>

Title: How to hide mouse cursor with jquery

Body:
How to hide mouse cursor with jquery in entire webpage.
 I tried this

$(document).ready(function(){
        $(body).css({
           'cursor' : 'none'
        });
});

But this is not working in all the browsers. Is there any plugin to implement this.

Thanks in Advance.


问:
Run CMD as admin in PowerShell
I hope this is simple.

```<code>$cred = Get-Credential $env:USERDOMAIN\$env:USERNAME
$credUser = $cred.UserName
$credPW = $cred.Password

$Col1Row2 = New-Object System.Windows.Forms.Button
$Col1Row2.Location = New-Object System.Drawing.Size(5,80)
$Col1Row2.Size = New-Object System.Drawing.Size(150,25)
$Col1Row2.Text = "CMD as Admin"
$Col1Row2.Add_Click({Write-Host "Started Command Prompt.";$x= RunAs /user:$credUser C:\Windows\System32\cmd.exe })
$objForm.Controls.Add($Col1Row2)
</code>```

There's a button to start command prompt inside my form, but I want it to start as admin by catching the user credentials at the beginning and using them to run.  The problem is I can't seem to figure out how to get this to work.

If I run it in the script, it doesn't seem to work at all (in ISE).  If I run the line in PowerShell as RunAs /user:$credUser C:\Windows\System32\cmd.exe it asks for the password.  If I run it with the password at the end it doesn't seem to care.  Any assistance is appreciated.

答:
$params=@("/C";"$x";" >d:\temp\result.txt")

Parameters go here, change it to your parameters that you want to pass to Command Prompt.

Start Process takes Credential Object hence suggesting this approach.

```<code>$params=@("/C";"$x";" >d:\temp\result.txt")
$prog="cmd.exe"
Start-Process -Credential $cred  -Verb runas $prog +$params
</code>```

Title: Run CMD as admin in PowerShell

Body:
I hope this is simple.

$cred = Get-Credential $env:USERDOMAIN\$env:USERNAME
$credUser = $cred.UserName
$credPW = $cred.Password

$Col1Row2 = New-Object System.Windows.Forms.Button
$Col1Row2.Location = New-Object System.Drawing.Size(5,80)
$Col1Row2.Size = New-Object System.Drawing.Size(150,25)
$Col1Row2.Text = "CMD as Admin"
$Col1Row2.Add_Click({Write-Host "Started Command Prompt.";$x= RunAs /user:$credUser C:\Windows\System32\cmd.exe })
$objForm.Controls.Add($Col1Row2)

There's a button to start command prompt inside my form, but I want it to start as admin by catching the user credentials at the beginning and using them to run.  The problem is I can't seem to figure out how to get this to work.

If I run it in the script, it doesn't seem to work at all (in ISE).  If I run the line in PowerShell as RunAs /user:$credUser C:\Windows\System32\cmd.exe it asks for the password.  If I run it with the password at the end it doesn't seem to care.  Any assistance is appreciated.

Body:
$params=@("/C";"$x";" >d:\temp\result.txt")

Parameters go here, change it to your parameters that you want to pass to Command Prompt.

Start Process takes Credential Object hence suggesting this approach.

$params=@("/C";"$x";" >d:\temp\result.txt")
$prog="cmd.exe"
Start-Process -Credential $cred  -Verb runas $prog +$params


问:
Error:Failed to open zip file
Error:Failed to open zip file.
Gradle 's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)
Re-download dependencies and sync project (requires network)
Re-download dependencies and sync project (requires network)

答:
Manually download

Open your android studio root directory, and extract the zip to the
gradle folder

File->Settings->Build, Exectution, Deployment->Gradle and set "Gradle
home" to point your new gradle-3.3 folder and Sync

Title: Error:Failed to open zip file


问:
C# ASP MVC pulling data from the web config file is not working
I'm trying to pull data from the web config file as outlined by this msdn resource.

Here is my code:

```<code>System.Configuration.Configuration activeCampaignApiSetting1 =
  System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
    System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
    if (activeCampaignApiKeySetting != null) {
        activeCampaignApiKey = activeCampaignApiKeySetting.Value;
    }

    System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
    if (activeCamapignApiUrlSetting != null) {
        activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
    }
}
</code>```

When I try to instantiate this class:

```<code>var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);
</code>```

it throws an exception telling me that the values are blank.

The values in the web config file are there:

```<code><add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />
</code>```

Anyone know where I may be going wrong?
Cheers

答:
If they are appSetting inside web.config, you can access them via ConfigurationManager.AppSettings.

```<code><?xml version="1.0"?>
<configuration>
   <configSections>
      <appSettings>
         <add key="ActiveCampaignApiKey" value="apikey_removed" />
         <add key="ActiveCampaignApiUrl" value="apiurl_removed" />
      </appSettings>
   </configSections>
</configuration>

string activeCampaignApiKeySetting
 = ConfigurationManager.AppSettings["ActiveCampaignApiKey"];

string activeCamapignApiUrlSetting
 = ConfigurationManager.AppSettings["ActiveCampaignApiUrl"];
</code>```

Please make sure you reference System.Configuration, and include using System.Configuration; directive.

FYI: They return string value (not key value pair).

Body:
I'm trying to pull data from the web config file as outlined by this msdn resource.

Here is my code:

System.Configuration.Configuration activeCampaignApiSetting1 =
  System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);
if (activeCampaignApiSetting1.AppSettings.Settings.Count > 0) {
    System.Configuration.KeyValueConfigurationElement activeCampaignApiKeySetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiKey"];
    if (activeCampaignApiKeySetting != null) {
        activeCampaignApiKey = activeCampaignApiKeySetting.Value;
    }

    System.Configuration.KeyValueConfigurationElement activeCamapignApiUrlSetting =
      activeCampaignApiSetting1.AppSettings.Settings["ActiveCampaignApiUrl"];
    if (activeCamapignApiUrlSetting != null) {
        activeCampaignApiUrl = activeCamapignApiUrlSetting.Value;
    }
}

When I try to instantiate this class:

var acs = new Acs(activeCampaignApiKey, activeCampaignApiUrl);

it throws an exception telling me that the values are blank.

The values in the web config file are there:

<add key="ActiveCampaignApiKey" value="apikey_removed" />
<add key="ActiveCampaignApiUrl" value="apiurl_removed" />

Anyone know where I may be going wrong?
Cheers

Body:
If they are appSetting inside web.config, you can access them via ConfigurationManager.AppSettings.

<?xml version="1.0"?>
<configuration>
   <configSections>
      <appSettings>
         <add key="ActiveCampaignApiKey" value="apikey_removed" />
         <add key="ActiveCampaignApiUrl" value="apiurl_removed" />
      </appSettings>
   </configSections>
</configuration>

string activeCampaignApiKeySetting
 = ConfigurationManager.AppSettings["ActiveCampaignApiKey"];

string activeCamapignApiUrlSetting
 = ConfigurationManager.AppSettings["ActiveCampaignApiUrl"];

Please make sure you reference System.Configuration, and include using System.Configuration; directive.

FYI: They return string value (not key value pair).


问:
Format exception unhandled: input string was not in a correct format
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

```<code>public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }
</code>```

and

```<code>private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }
</code>```

答:
int.Parse will throw the exception in question if the input string can't be converted to a number.

Instead you should use int.TryParse

```<code>int parsed = 0;
if (int.TryParse(checkerBox.Text, out parsed))
{
    pali = new Palindrome() { number = parsed};
} else {
    // show an error and exit the method.
    return;
}
</code>```

Body:
when ever i try to run my program the compiler brings me an error  Input string was not in a correct format.

my code:

public int number;
public int evenOrOdd()
        {
            if(number % 2 == 0)
            {
                return int.Parse(number+" is a even number");
            }
            else
            {
                return int.Parse(number + " is a oddnumber");
            }
        }

and

private void checkerButton_Click(object sender, EventArgs e)
        {
            pali = new Palindrome() { number = int.Parse(checkerBox.Text) };
            checkerLabel.Text = pali.evenOrOdd().ToString();
        }

Body:
int.Parse will throw the exception in question if the input string can't be converted to a number.

Instead you should use int.TryParse

int parsed = 0;
if (int.TryParse(checkerBox.Text, out parsed))
{
    pali = new Palindrome() { number = parsed};
} else {
    // show an error and exit the method.
    return;
}


问:
Session issue with unset() and the browser back button
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

```<code>// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);
</code>```

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.

答: Just bypass the insert all together if $_SESSION['next_id'] comes up NULL, even if it means calling die() before you reach that legacy code you don't want to touch.</p>

Body:
I'm using a SESSION variable to set the pre-allocated record id from Postgres (getting the record id sequence) using PEAR's DB nextId(). I set the I id to a session variable because of scoping issues in the legacy code I'm working with. After the INSERT happens I use the unset() to remove the SESSION variable (This is to clear the used record id). There is more information in the session as well that remains intact, it's just the next_id element that is being removed.

Pseudo code:

// Get the next Id and set to SESSION
$_SESSION['next_id'] = $db->nextId();

... more code here

// After insert
unset($_SESSION['next_id']);

My question is, Would clicking the back button on the browser somehow reset the SESSION variable $_SESSION['next_id']? Maybe causing it to be NULL? How does CACHE handle the SESSION after an element has been removed but the user has returned to a previous state?

EDIT:
the reason for the question is that the code in production is randomly (by any user) trying to INSERT with a NULL record id (Which is the next_id from SESSION). Just trying to debug the process as the code is very minimal, reviewed by my peers and has just stumped us???

EDIT 2:
Wow I guess there is an issue with how I'm using the SESSION variable.
Well I'll explain as much as I can as to why I chose this method.
First the code is in the process on being rewritten from PHP 4, but the current production version is mostly PHP 4 with a ton a newly added module code in PHP 5.
The reason I chose the SESSION variable is because of a scoping issue that would need to be hard coded on several hundred pages of legacy code or on one page and cast the value into the SESSION which all pages have access to. (well my boss who pays my salary like the option I chose).
The original problem is they (my boss) wanted to display the id to the end user before the insertion of the information. Hence the PEAR DB call nextId(). We use PostgreSQL and I'm using the record id sequence to ensure that the next id will be unique and allocated to the end user only (No duplicates as Postgres handles locking this in the sequence).
So the end user can also navigate to multiple pages during the process, this also is another scoping issue.
Now using the SESSION and retrieving the next Id with some validation and checks is about 50 lines of code for the whole process instead of the thousands of lines of code that would have been written to do this the correct way.
Again NOT MY CODE in the first place, just making the best solution at the least possible cost.

If you have another, better, greater, easier, cheaper solution feel free to post away. But if you're going to piss on my decision about how to code, then please pay my bills and I will fully agree with following better coding standard,practices,solution.


问:
remove virtual directory in IIS Express created in error
I clicked on create virtual directory of the web tab of the properties menu.
My application now isn't running (the published version is)
It just hangs when any of my controllers code is executed
I think I've messed up the IIS config
Can anyone help me out?</p>

答: None of this worked for me - possibly because I'm working with a later version of the tools (VS 2017). I finally found the correct appplicationhost.config file in the .vs directory for the solution, edited it, rebooted, and it worked.</p>


问:
Apply function to each cell in DataFrame that depends on the column name in pandas
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

```<code>import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)
</code>```

returns:

```<code>               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06
</code>```

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

```<code>def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)
</code>```

Returns:

```<code>              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06
</code>```

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

Body:
How can I apply function to each cell in a DataFrame that depends on the column name?

I'm aware of pandas.DataFrame.applymap but it doesn't seem to allow depending on the column name:

import numpy as np
import pandas as pd
np.random.seed(1)
frame = pd.DataFrame(np.random.randn(4, 3), columns=list('bde'),
                     index=['Utah', 'Ohio', 'Texas', 'Oregon'])
print(frame)
format = lambda x: '%.2f' % x
frame = frame.applymap(format)
print(frame)

returns:

               b         d         e
Utah    1.624345 -0.611756 -0.528172
Ohio   -1.072969  0.865408 -2.301539
Texas   1.744812 -0.761207  0.319039
Oregon -0.249370  1.462108 -2.060141

            b      d      e
Utah     1.62  -0.61  -0.53
Ohio    -1.07   0.87  -2.30
Texas    1.74  -0.76   0.32
Oregon  -0.25   1.46  -2.06

Instead, I want the function that I applied to each cell to use the column name of the current cell as an argument.

I don't want to have to loop myself over each column, like:

def format2(cell_value, column_name):
    return '{0}_{1:.2f}'.format(column_name, cell_value)

for column_name in frame.columns.values:
    print('column_name: {0}'.format(column_name))
    frame[column_name]=frame[column_name].apply(format2, args=(column_name))
print(frame)

Returns:

              b        d        e
Utah     b_1.62  d_-0.61  e_-0.53
Ohio    b_-1.07   d_0.87  e_-2.30
Texas    b_1.74  d_-0.76   e_0.32
Oregon  b_-0.25   d_1.46  e_-2.06

(This is just one example. The functions I want to apply on the cells may do more than just appending the column name)

Body:
why not:

>>> frame
               b         d         e
Utah   -0.579869  0.101039 -0.225319
Ohio   -1.791191 -0.026241 -0.531509
Texas   0.785618 -1.422460 -0.740677
Oregon  1.302074  0.241523  0.860346

>>> frame['e'] = ['%.2f' % val for val in frame['e'].values]
>>> frame
               b         d      e
Utah   -0.579869  0.101039  -0.23
Ohio   -1.791191 -0.026241  -0.53
Texas   0.785618 -1.422460  -0.74
Oregon  1.302074  0.241523   0.86


问:
C - How do I use realloc with pointers
I'm having trouble using realloc in this case. My compiler, devC++, keeps telling me it's an invalid application of 'sizeof' to incomplete type 'struct WaitlistEntry'. I'm basically trying to malloc a struct using the given structs, and then store the data in it.

Here is the entire function:

```<code>void attemptEnrollment( Course* pCourse, int iStudentID, int iPriority ){

    if (pCourse->iNumEnrolled < pCourse->iMaxEnrolled)
        enrollStudent(pCourse, iStudentID);
    else {
        WaitlistEntry w1;
        w1 = (struct WaitlistEntry*)malloc(sizeof(struct WaitlistEntry));
        w1.iStudentID = iStudentID;
        w1.iPriority = iPriority;
        waitlistStudent(pCourse,w1);
    }
}
</code>```

Here are the structs:

```<code>typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;
</code>```

答:
Either change:

```<code>typedef struct {
  // ...
} WaitlistEntry;
</code>```

to

```<code>typedef struct WaitlistEntry {
  // ...
} WaitlistEntry;
</code>```

I'd use this style if you choose to do that: (minus the comments)

```<code>// typedef's "struct WaitlistEntry" as "WaitlistEntry"
typedef struct WaitlistEntry WaitlistEntry;
// declares the contents of "struct WaitlistEntry"
struct WaitlistEntry {
  // ...
};
</code>```

Which makes the meaning of the typedef more obvious. Mixing typedef and struct declarations can be a little confusing. (It also allows you to use WaitlistEntry * inside WaitlistEntry.)

Or you can change the malloc call to:

```<code>w1 = (WaitlistEntry *) malloc(sizeof(WaitlistEntry));
</code>```

You should try be consistent with your usage: (If you use WaitlistEntry always use WaitlistEntry, if you use struct WaitlistEntry always use struct WaitlistEntry).

Title: C - How do I use realloc with pointers

Body:
I'm having trouble using realloc in this case. My compiler, devC++, keeps telling me it's an invalid application of 'sizeof' to incomplete type 'struct WaitlistEntry'. I'm basically trying to malloc a struct using the given structs, and then store the data in it.

Here is the entire function:

void attemptEnrollment( Course* pCourse, int iStudentID, int iPriority ){

    if (pCourse->iNumEnrolled < pCourse->iMaxEnrolled)
        enrollStudent(pCourse, iStudentID);
    else {
        WaitlistEntry w1;
        w1 = (struct WaitlistEntry*)malloc(sizeof(struct WaitlistEntry));
        w1.iStudentID = iStudentID;
        w1.iPriority = iPriority;
        waitlistStudent(pCourse,w1);
    }
}

Here are the structs:

typedef struct{
    int iPriority;          /* Priority of the student to be enrolled */
    int iStudentID;         /* ID of the student */
} WaitlistEntry;

typedef struct PQNode {
    WaitlistEntry info;     /* WaitlistEntry stored in the node (sorted with largest priority first) */
    struct PQNode* pNext;   /* Pointer to next node in the LL */
    struct PQNode* pPrev;   /* Pointer to previous node in the LL */
} PQNode;

typedef struct{
    int iCourseNumber;      /* Course number of the course */
    int* iStudentIDs;       /* Array of IDs of students enrolled in the course */
    int iNumEnrolled;       /* Number of Students currently enrolled in course */
    int iMaxEnrolled;       /* Max number of Students that can enroll in the course */
    PQNode* pFront;         /* Priority queue representing the waitlist for the course */
} Course;

Body:
Either change:

typedef struct {
  // ...
} WaitlistEntry;

to

typedef struct WaitlistEntry {
  // ...
} WaitlistEntry;

I'd use this style if you choose to do that: (minus the comments)

// typedef's "struct WaitlistEntry" as "WaitlistEntry"
typedef struct WaitlistEntry WaitlistEntry;
// declares the contents of "struct WaitlistEntry"
struct WaitlistEntry {
  // ...
};

Which makes the meaning of the typedef more obvious. Mixing typedef and struct declarations can be a little confusing. (It also allows you to use WaitlistEntry * inside WaitlistEntry.)

Or you can change the malloc call to:

w1 = (WaitlistEntry *) malloc(sizeof(WaitlistEntry));

You should try be consistent with your usage: (If you use WaitlistEntry always use WaitlistEntry, if you use struct WaitlistEntry always use struct WaitlistEntry).


问:
Beginner at programming. C++ colon on line 9 included in this example code from textbook. I understand up to line 8 but what does the colon do?
Colon on line 9 is throwing me off. I'm not sure what its purpose is.</p>

```<code>    #include <iostream>
    using namespace std;

    const int TOTALYEARS = 100;

    int main()
    {
        int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
        :
        return 0;
    }
</code>```

答:
Just checked the "texbook" contents (which are some review notes actually). That's not a colon, that's the academic way of saying "other miscellaneous non-important code goes here". Something like:

```<code>int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
.
.
.
return 0;
</code>```

Here's a screenshot for confirmation:

You're expected to ignore those symbols.

Body:
Colon on line 9 is throwing me off. I'm not sure what its purpose is.

    #include <iostream>
    using namespace std;

    const int TOTALYEARS = 100;

    int main()
    {
        int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
        :
        return 0;
    }

Body:
Just checked the "texbook" contents (which are some review notes actually). That's not a colon, that's the academic way of saying "other miscellaneous non-important code goes here". Something like:

int ageFrequency[TOTALYEARS]; // reserves memory for 100 ints
.
.
.
return 0;

Here's a screenshot for confirmation:

You're expected to ignore those symbols.


问:
How I reference hash inside of subroutine?
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

```<code>use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}
</code>```

I am sure it is something simple, but I am stumped.

答:
First off, the tie function returns the internal hidden object that represents the tie, and not the tied variable itself.  Secondly, you can not return a plural tied value (hash or array) from a subroutine and have it work the way you are expecting.  You need to return a reference to the plural value, and then dereference it when you need to use it.

```<code>use Config::IniFiles;

sub config_file {
    tie my %cfg, 'Config::IniFiles', -file => 'settings.ini';  # tie variable
    return \%cfg;  # return a reference to the tied variable
}

sub esx_host_check {
    my $esx_host = config_file()->{ESX}{host}; # call sub and dereference value
}
</code>```

If you are going to use the config hash more than a few times, its probably best to build it and then cache the result:

```<code>{my $cfg;
sub config_file {
    tie %$cfg, 'Config::IniFiles', -file => 'settings.ini' unless $cfg;
    return $cfg;
}}
</code>```

This is a little different than above.  First, we setup config_file to be a closure around the private variable $cfg.  Note that it is a scalar and not a hash.  Then in the sub, we check to see if the variable has been initialized, and if not, call tie.  tie is passed a first argument of %$cfg which dereferences the undefined value as a hash, which has the effect of storing the tied hash reference into $cfg.

While a little more complicated, this technique will only need to build the config hash once, potentially saving a lot of time.

Body:
I am trying to use the tie function of the module Config::IniFiles but I cannot figure out how to reference the hash inside of sub routine. If I remove the tie function and related code from the sub routine it works perfectly.

This is the line I thought would work, but tells me that "$cfg" is not initialized.

use Config::IniFiles
sub config_file {
    my $cfg_file = 'settings.ini';
    my %cfg;
    tie %cfg, 'Config::IniFiles', ( -file => "$cfg_file" );

    #my $cfg = Config::IniFiles->new( -file => $cfg_file );

}

sub esx_host_check {
    my $esx_host = config_file()->$cfg{ESX}{host};
}

I am sure it is something simple, but I am stumped.

Body:
First off, the tie function returns the internal hidden object that represents the tie, and not the tied variable itself.  Secondly, you can not return a plural tied value (hash or array) from a subroutine and have it work the way you are expecting.  You need to return a reference to the plural value, and then dereference it when you need to use it.

use Config::IniFiles;

sub config_file {
    tie my %cfg, 'Config::IniFiles', -file => 'settings.ini';  # tie variable
    return \%cfg;  # return a reference to the tied variable
}

sub esx_host_check {
    my $esx_host = config_file()->{ESX}{host}; # call sub and dereference value
}

If you are going to use the config hash more than a few times, its probably best to build it and then cache the result:

{my $cfg;
sub config_file {
    tie %$cfg, 'Config::IniFiles', -file => 'settings.ini' unless $cfg;
    return $cfg;
}}

This is a little different than above.  First, we setup config_file to be a closure around the private variable $cfg.  Note that it is a scalar and not a hash.  Then in the sub, we check to see if the variable has been initialized, and if not, call tie.  tie is passed a first argument of %$cfg which dereferences the undefined value as a hash, which has the effect of storing the tied hash reference into $cfg.

While a little more complicated, this technique will only need to build the config hash once, potentially saving a lot of time.


答:
From your first section of code I am making the assumption all the numbers are entered on a single line all at once.

My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?

The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.

```<code>Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
    numbers++;
    total += line.nextDouble();
}
line.close(); // Good habit
</code>```

You can then compute your average with all this information:

```<code>double avg = total/numbers;
</code>```

Notes:

Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.

I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.

Title: Calculate an Average from user input of five to ten numbers using Methods

Body:
My assignment requires me to prompt a user for 5 to 10 numbers and then calculate the average of those numbers. I also have to use methods to do so. My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers? Below is what I have so far, I'm also having a little trouble understanding how to get the methods to execute in the main method but I think I have the actual method ideas right.

It was suggested that I format as reflected below, but my problem here is that it does not print anything after the user inputs its numbers, can anyone see what I'm missing? I'm thinking maybe I did something wrong in the main method?

public class AverageWithMethods {

    public static void main(String[] args) {
        String userNumbers = getUserNums();
        double average = userNumAvg(userNumbers);
        printAverage(0, userNumbers);

    }

    public static String getUserNums() {
        Scanner in = new Scanner(System.in);
        String userNumInput = "";
        System.out.print("Please enter five to ten numbers separated by spaces: ");
        userNumInput = in.nextLine();
        return userNumInput;
    }

    public static double userNumAvg(String userNumInput) {
        Scanner in = new Scanner(System.in);
        Scanner line = new Scanner(in.nextLine());

        double count = 0;
        double average = 0.0;
        double sum =0;

        while (in.hasNextDouble()) {
            count++;
            sum = line.nextDouble();

        }
        if (count != 0) {
            average = sum / count;
            count = Double.parseDouble(userNumInput);
        }

        return average;
    }

    public static void printAverage(double average, String userNumInput) {
        System.out.printf("The average of the numbers " + userNumInput + " is %.2f", average);

    }
}

Body:
From your first section of code I am making the assumption all the numbers are entered on a single line all at once.

My question is, how do I get the program to calculate the average if exactly if I'm not sure if they will enter 5 or 10 numbers?

The Scanner object you are using has a method hasNextInt() so you can construct a simple while loop to figure out how many numbers there are.

Scanner line = new Scanner(in.nextLine()); // Feed line into scanner
int numbers = 0;
double total = 0.0;
while(in.hasNextInt()) { // read all the numbers
    numbers++;
    total += line.nextDouble();
}
line.close(); // Good habit

You can then compute your average with all this information:

double avg = total/numbers;

Notes:

Making total a double to avoid integer math when computing the average. There are obviously other ways to avoid integer math and I can include more if you would like.

I use a second Scanner with a String parameter of in.nextLine() because if you skip that step, the code won't terminate when reading a continuous input stream such as a console/terminal. This is because there will be a next int possible since the terminal is still accepting input.


问:
Stop Z rotation of gameObject on touch in Unity
Hi am trying to Rotate the gameobject in X-axis and Y-axis on touch, the code works perfectly, but it effects z-rotation also, I don't want Z-Rotation,
My gameObject does not contain Rigid-body so i can't apply Z-rotation constraints. I have searched the problem on internet but can't get any appropriate solution.
Any help would be appreciated. Thankx

Here is my code:

```<code>public class Rot : MonoBehaviour {
    private float RotateSpeed   = 10f;

    void OnMouseDrag () {
        float xRot = Input.GetAxis ("Mouse X") * RotateSpeed * Mathf.Deg2Rad;
        float yRot = Input.GetAxis ("Mouse Y") * RotateSpeed * Mathf.Deg2Rad;

        transform.RotateAround (Vector3.up, -xRot);
        transform.RotateAround (Vector3.right, yRot);
    }
}
</code>```

答:
Try this,

```<code>transform.Rotate(new Vector3(-xRot,yRot,0.0f),Space.Self);
</code>```

If you want to set absolute rotation use transform.localEulerAngles

Body:
Hi am trying to Rotate the gameobject in X-axis and Y-axis on touch, the code works perfectly, but it effects z-rotation also, I don't want Z-Rotation,
My gameObject does not contain Rigid-body so i can't apply Z-rotation constraints. I have searched the problem on internet but can't get any appropriate solution.
Any help would be appreciated. Thankx

Here is my code:

public class Rot : MonoBehaviour {
    private float RotateSpeed   = 10f;

    void OnMouseDrag () {
        float xRot = Input.GetAxis ("Mouse X") * RotateSpeed * Mathf.Deg2Rad;
        float yRot = Input.GetAxis ("Mouse Y") * RotateSpeed * Mathf.Deg2Rad;

        transform.RotateAround (Vector3.up, -xRot);
        transform.RotateAround (Vector3.right, yRot);
    }
}

Body:
Try this,

transform.Rotate(new Vector3(-xRot,yRot,0.0f),Space.Self);

If you want to set absolute rotation use transform.localEulerAngles


问:
VBA (Ms-Access) 2013 Overflow errors
I'm building a set of VBA functions to manipulate IP address strings in an MS-Access database and I am having problems with overflow errors whenever the IP address value exceeds the size of an Integer variable.  I've tried to ensure I am using only Long types, but I am still getting these errors.  Here is a very simple demo that fails with an overflow, and I can't figure out why.

```<code>Public Function BigNumber() As Long
Dim N256 As Long
N256 = 256
BigNumber = N256 * N256 * N256 * N256
End Function
</code>```

I've read other thread that explained VBA may give overflow errors if any of the terms in an expression are too small for the product, but I can't see how that applies in this example.  Can anybody explain?

答:
In VBA, a Long variable can store a value between -2,147,483,648 and 2,147,483,647. The result of your calculation is greater than the max, so it overflows:

256 * 256 * 256 * 256 = 4,294,967,296

Title: VBA (Ms-Access) 2013 Overflow errors

Body:
I'm building a set of VBA functions to manipulate IP address strings in an MS-Access database and I am having problems with overflow errors whenever the IP address value exceeds the size of an Integer variable.  I've tried to ensure I am using only Long types, but I am still getting these errors.  Here is a very simple demo that fails with an overflow, and I can't figure out why.

Public Function BigNumber() As Long
Dim N256 As Long
N256 = 256
BigNumber = N256 * N256 * N256 * N256
End Function

I've read other thread that explained VBA may give overflow errors if any of the terms in an expression are too small for the product, but I can't see how that applies in this example.  Can anybody explain?