问:
How to revalidate the session once it is invalidated Alamofire?
The use of invalidateAndCancel() comes up with another problem which is to reinitialize the session again if u need to use it again. After searching on this problem i got the answer of Cnoon's Alamofire Background Service, Global Manager? Global Authorisation Header?. Tried creating the manager but when it is called it never re-initialize the value, to anticipate this problem i did a small cheat i tried giving my session new name each time.

```<code>    func reset() -> Manager {

            let configuration: NSURLSessionConfiguration = {
                let identifier = "com.footbits.theartgallery2.background-session\(sessionCount)"
                let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
                return configuration
            }()

            return Alamofire.Manager(configuration: configuration)
        }

func cancelAllRequests() {

   manager.session.invalidateAndCancel()
   sessionCount += 1
   manager = reset()

}
</code>```

Now i am curious of what is happening in background like the previous session is still there or has been removed by alamofire because if it is still there how many session can i create and what will be the after affect? because i tried:

```<code>manager.session.resetWithCompletionHandler {

            print("Session reset")
        }
</code>```

it doesnt work.

答:
I know this question is old, but this info will apply to you (the reader) wether or not you are using Alamofire.

You can not revalidate a URLSession, for good reason: The tasks within a session will be told to cancel upon invalidation of the session. However, those tasks may take a while to actually cancel and leave the session. To prove this, cancel a session and retrieve its tasks periodically afterwards. They'll slowly drop towards zero.

What you need to do instead is create a new session with a new identifier. Using the same identifier will cause the old session to be used and crash if new tasks are scheduled to it!

For those seeking to perform background downloads consider using a UUID().uuidString as part of the identifier and storing the id somewhere on the device (Userdefaults come to mind), and generating a new uuid after every call to invalidate your current session. Then create a new session object with a new uuid and reference that instead. Bonus: This new session immediately will have 0 open tasks which proves useful if your logic is based on that.

Example from within my project:

```<code>@UserDefaultOptional(defaultValue: nil, "com.com.company.sessionid")
private var sessionID: String?

// MARK: - Init

private var session: URLSession!

private override init() {
    super.init()
    setupNewSession()
}

private func setupNewSession() {
    let id = sessionID ?? UUID().uuidString
    sessionID = id
    let configuration = URLSessionConfiguration.background(withIdentifier: id)
    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}

private func invalidateSession() {
    session.invalidateAndCancel()
    sessionID = nil
    setupNewSession()
}
</code>```

Body:
The use of invalidateAndCancel() comes up with another problem which is to reinitialize the session again if u need to use it again. After searching on this problem i got the answer of Cnoon's Alamofire Background Service, Global Manager? Global Authorisation Header?. Tried creating the manager but when it is called it never re-initialize the value, to anticipate this problem i did a small cheat i tried giving my session new name each time.

    func reset() -> Manager {

            let configuration: NSURLSessionConfiguration = {
                let identifier = "com.footbits.theartgallery2.background-session\(sessionCount)"
                let configuration = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(identifier)
                return configuration
            }()

            return Alamofire.Manager(configuration: configuration)
        }

func cancelAllRequests() {

   manager.session.invalidateAndCancel()
   sessionCount += 1
   manager = reset()

}

Now i am curious of what is happening in background like the previous session is still there or has been removed by alamofire because if it is still there how many session can i create and what will be the after affect? because i tried:

manager.session.resetWithCompletionHandler {

            print("Session reset")
        }

it doesnt work.

Body:
I know this question is old, but this info will apply to you (the reader) wether or not you are using Alamofire.

You can not revalidate a URLSession, for good reason: The tasks within a session will be told to cancel upon invalidation of the session. However, those tasks may take a while to actually cancel and leave the session. To prove this, cancel a session and retrieve its tasks periodically afterwards. They'll slowly drop towards zero.

What you need to do instead is create a new session with a new identifier. Using the same identifier will cause the old session to be used and crash if new tasks are scheduled to it!

For those seeking to perform background downloads consider using a UUID().uuidString as part of the identifier and storing the id somewhere on the device (Userdefaults come to mind), and generating a new uuid after every call to invalidate your current session. Then create a new session object with a new uuid and reference that instead. Bonus: This new session immediately will have 0 open tasks which proves useful if your logic is based on that.

Example from within my project:

@UserDefaultOptional(defaultValue: nil, "com.com.company.sessionid")
private var sessionID: String?

// MARK: - Init

private var session: URLSession!

private override init() {
    super.init()
    setupNewSession()
}

private func setupNewSession() {
    let id = sessionID ?? UUID().uuidString
    sessionID = id
    let configuration = URLSessionConfiguration.background(withIdentifier: id)
    session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
}

private func invalidateSession() {
    session.invalidateAndCancel()
    sessionID = nil
    setupNewSession()
}


来源: stackexchange

问:
Sum selected records in one2many field odoo12
i Have the following models

```<code>class WorkStation(models.Model):

   _name = 'dlc.workstation'

   _description = 'list of work station'

production_ids = fields.One2many(comodel_name="dlc.pdetails", inverse_name="workstation_id", string="Production", required=False, )

sum_production = fields.Integer(string="Production total",  compute='_dlc_production', required=False,)

@api.one

@api.depends('production_ids.total', )

def _dlc_production(self):

   self.sum_production = sum(production.total for production in self.production_ids)

   """

   @api.depends() should contain all fields that will be used in the calculations.

   """

   pass
</code>```

```<code>class ProductionData(models.Model):

   _name = 'dlc.pdata'

   _rec_name = 'start_date'

   _description = 'New Description'

name = fields.Char()

start_date = fields.Date(string="From", required=False, )

end_date = fields.Date(string="To", required=False,)

production_details_ids = fields.One2many(comodel_name="dlc.pdetails", inverse_name="production_data_id", string="Production Details"
</code>```

```<code>class ProductionDetails(models.Model):

   _name = 'dlc.pdetails'

   _rec_name = 'workstation_id'

   workstation_id = fields.Many2one(comodel_name="dlc.workstation", string="DLC", required=False, )

   production_data_id = fields.Many2one(comodel_name="dlc.pdata", string="Production", required=False, )

   card_type = fields.Selection(string="Card Type",

                                selection=[('Temporary', 'Temporary'), ('Office Total', 'Office Total'),

                                           ('Permanent', 'Permanent')], required=False, )

   date = fields.Date(string="Date", required=False, related='production_data_id.start_date')
   total = fields.Integer(string="TOTAL", required=False, )
</code>```

with this field sum_production gives me the total production figures per workstation but now i want total production for the last 7 days .

答:
Just filter the production_ids list you use to sum.

```<code>from datetime import date

@api.one
@api.depends('production_ids.total', )
def _dlc_production(self):
   production_list = self.production_ids.filter(lambda r: r.date and (date.today() - timedelta(days=7)) <= r.date <= date.today())
   self.sum_production = sum(production.total for production in production_list)
</code>```

Now if you want to have the total of the whole production

```<code>workstation_list = self.env['dlc.workstation'].search([])
production_list = workstation_list.mapped('production_ids').filter(lambda r: r.date and (date.today() - timedelta(days=7)) <= r.date <= date.today())
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i Have the following models

class WorkStation(models.Model):

   _name = 'dlc.workstation'

   _description = 'list of work station'

production_ids = fields.One2many(comodel_name="dlc.pdetails", inverse_name="workstation_id", string="Production", required=False, )

sum_production = fields.Integer(string="Production total",  compute='_dlc_production', required=False,)

@api.one

@api.depends('production_ids.total', )

def _dlc_production(self):

   self.sum_production = sum(production.total for production in self.production_ids)

   """

   @api.depends() should contain all fields that will be used in the calculations.

   """

   pass

class ProductionData(models.Model):

   _name = 'dlc.pdata'

   _rec_name = 'start_date'

   _description = 'New Description'

name = fields.Char()

start_date = fields.Date(string="From", required=False, )

end_date = fields.Date(string="To", required=False,)

production_details_ids = fields.One2many(comodel_name="dlc.pdetails", inverse_name="production_data_id", string="Production Details"

class ProductionDetails(models.Model):

   _name = 'dlc.pdetails'

   _rec_name = 'workstation_id'

   workstation_id = fields.Many2one(comodel_name="dlc.workstation", string="DLC", required=False, )

   production_data_id = fields.Many2one(comodel_name="dlc.pdata", string="Production", required=False, )

   card_type = fields.Selection(string="Card Type",

                                selection=[('Temporary', 'Temporary'), ('Office Total', 'Office Total'),

                                           ('Permanent', 'Permanent')], required=False, )

   date = fields.Date(string="Date", required=False, related='production_data_id.start_date')
   total = fields.Integer(string="TOTAL", required=False, )

with this field sum_production gives me the total production figures per workstation but now i want total production for the last 7 days .

Body:
Just filter the production_ids list you use to sum.

from datetime import date

@api.one
@api.depends('production_ids.total', )
def _dlc_production(self):
   production_list = self.production_ids.filter(lambda r: r.date and (date.today() - timedelta(days=7)) <= r.date <= date.today())
   self.sum_production = sum(production.total for production in production_list)

Now if you want to have the total of the whole production

workstation_list = self.env['dlc.workstation'].search([])
production_list = workstation_list.mapped('production_ids').filter(lambda r: r.date and (date.today() - timedelta(days=7)) <= r.date <= date.today())


问:
Is .dex file also used when we run android app in physical mobile?
I found that .dex is compiled android application file and it will used by DVM(Dalvik Virtual Machine) and DDMS(Dalvik Debug Monitor Service).
It means, .dex file not required for physical android mobile?</p>

答:
DEX is the file format for the compiled bytecode that goes into an APK file. It will be used on devices and emulators.

Note that DDMS has not been used in years. I recommend that you check the dates on the materials that you are reading and focus on newer items.


问:
What is the correct mimetype for .tex-files?
My webservice generates and returns a .tex-file. I want to give the correct mimetype in the http-header.

I didn't found so much except for here, where I find application/x-tex. Is this an authority to stick to?

答:
For those who came here... i ended up with
"application/x-tex"


问:
Read frame by frame and create video using cv2 in python
I want to read frame by frame from existing video, and create new video from these frames.

In my real project I want to change each frame before making the new video but for simplicity's sake of this question I just want to create new video from the same frames without any change.

答:
This code is working for me:

```<code>import cv2
vidcap = cv2.VideoCapture('input_video.mp4')
vidwrite = cv2.VideoWriter('output_video.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 30, (1920,1080))
success,image = vidcap.read()
while success:
  vidwrite.write(image) # write frame into video
  success,image = vidcap.read() # read frame from video
vidwrite.release()
cv2.destroyAllWindows()
</code>```

The strange thing is that the output video is twice bigger than the input video

Body:
This code is working for me:

import cv2
vidcap = cv2.VideoCapture('input_video.mp4')
vidwrite = cv2.VideoWriter('output_video.mp4', cv2.VideoWriter_fourcc(*'MP4V'), 30, (1920,1080))
success,image = vidcap.read()
while success:
  vidwrite.write(image) # write frame into video
  success,image = vidcap.read() # read frame from video
vidwrite.release()
cv2.destroyAllWindows()

The strange thing is that the output video is twice bigger than the input video


问:
A question about local variable, range, for in Python
I am solving an algorithm problem in https://leetcode.com/problems/two-sum.

Here is my code:

```<code>class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(0, list_length):
            for j in range(i+1, list_length):
                s = i + j
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result

s = Solution()
ts = s.twoSum([2, 7, 11, 15], 9)
print(ts)
</code>```

The output is None.

I want to know why is it None rather than [0,1].

答:
Indentation is important, and both i and j references are to the index within the list of nums example, [0,3,4] so num[0] is 0 etc. etc. And it's a good habit to use a main method at the bottom although not necessary depending on what you are doing. Hope this helps..

```<code>class Solution:

   def twoSum(self, nums, target):
      list_length = len(nums)
      # actually use the list() functionality here not 'list()'but '[]'
      result = []
      for i in range(list_length):
         for j in range(1, list_length):
            s = nums[i] + nums[j]
            if s == target:
              result.append(i)
              result.append(j)
              return result

if __name__ == "__main__":
  #use a main method if possible
  s = Solution()
  ts = s.twoSum([2, 7, 11, 15], 9)
  print(ts)
</code>```

Body:
I am solving an algorithm problem in https://leetcode.com/problems/two-sum.

Here is my code:

class Solution:
    def twoSum(self, nums, target):
        list_length = len(nums)
        result = list()
        for i in range(0, list_length):
            for j in range(i+1, list_length):
                s = i + j
                if s == target:
                    result.append(i)
                    result.append(j)
                    return result

s = Solution()
ts = s.twoSum([2, 7, 11, 15], 9)
print(ts)

The output is None.

I want to know why is it None rather than [0,1].

Body:
Indentation is important, and both i and j references are to the index within the list of nums example, [0,3,4] so num[0] is 0 etc. etc. And it's a good habit to use a main method at the bottom although not necessary depending on what you are doing. Hope this helps..

class Solution:

   def twoSum(self, nums, target):
      list_length = len(nums)
      # actually use the list() functionality here not 'list()'but '[]'
      result = []
      for i in range(list_length):
         for j in range(1, list_length):
            s = nums[i] + nums[j]
            if s == target:
              result.append(i)
              result.append(j)
              return result

if __name__ == "__main__":
  #use a main method if possible
  s = Solution()
  ts = s.twoSum([2, 7, 11, 15], 9)
  print(ts)


问:
Intellij declared multi Java class into one file caused weird UI

```<code>class A {
    A get() {
        return this;
    }
}

public class B1 extends A {
    B1 get() {
        return this;
    }

    void message() {
        System.out.println("Covariant Return type example");
    }

}
</code>```

Pretty annoyed to see this UI. How do I make Intellij show this class as a normal class?

答:
The behavior is expected. If a class has multiple other classes declared inside it, they are shown as child entries for the 'main' class in Project view (and built as separate .class files upon compilation).

If you want to be able to open the 'main' class in the Editor instead of drilling down to the nested ones, you can select it in the Project view and hit F4 ('Jump to Source' action).

Related SO question: Intellij project view: not show multiple classes in same file

Related YouTrack request: https://youtrack.jetbrains.com/issue/IDEA-148825

Body:
class A {
    A get() {
        return this;
    }
}

public class B1 extends A {
    B1 get() {
        return this;
    }

    void message() {
        System.out.println("Covariant Return type example");
    }

}

Pretty annoyed to see this UI. How do I make Intellij show this class as a normal class?


问:
SwipeUp() on UICollectionViewCell in XCUITest triggers unrelated gesture recognizer
I'm trying to create XCUITest scripts for an app that consists mainly of a vertically scrolling UICollectionView.  When recording the automation of scrolling through the collection view, the app behaves as expected in the simulator, and the test records the .swipeUp() gesture applied to the elements that I touched.

But when I execute the recorded automation, that .swipeUp() call triggers a pan gesture recognizer on an unrelated element on screen.  When I experimentally removed the pan gesture recognizer .swipeUp() had no effect at all (i.e., no scrolling).

I am hoping someone could either point me towards the cause of this unexpected behaviour and/or suggest an alternative method of scrolling through a UICollectionView in XCUITest

答:
You can alternatively scroll using this method</p>

```<code>    let startPoint = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
    let endPoint = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 1.0))
    startPoint.press(forDuration:forDuration, thenDragTo:endPoint);
</code>```

Body:
You can alternatively scroll using this method

    let startPoint = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5))
    let endPoint = collectionView.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 1.0))
    startPoint.press(forDuration:forDuration, thenDragTo:endPoint);


问:
Capture std::array in lambda
I was trying to test some  simple C-style sort functions. In the driver program, I wrote something like this:

```<code>int main()
{
    std::array<int, 8> A = { 1, 0, 4, 5, 7, 2, 9, 3 };
    auto lambda = [&A](const std::function<void(int *A, int n)> &sorting_alg) {
        int n = A.size();
        sorting_alg(A.data(), n);
        std::cout << "=> ";
        print(A.data(), n);
        std::cout << std::endl;
    };

    auto do_bubble_sort = std::bind(lambda, bubble_sort);
    auto do_selection_sort  = std::bind(lambda, selection_sort);
    auto do_insertion_sort  = std::bind(lambda, insertion_sort);

    std::cout << "Bubble Sort :" << std::endl;
    do_bubble_sort();
    std::cout << "Selection Sort :" << std::endl;
    do_selection_sort();
    std::cout << "Insertion Sort :" << std::endl;
    do_insertion_sort();

    return 0;
}
</code>```

I had the bind code, to which I could pass A to copy, but it confines my lambda to size=8, which I want to avoid. Is it possible to achieve this without using something like std::vector, etc?
As soon I change capture method of A to value-capture, it doesn't compile anymore. I wanted to use copies for the array, to test all sorting functions. Why can't I capture std::array by value? Why then size-inference works for reference case?

答:
The operator() of a lambda is const by default.  That means you can't modify any members of the lambda (it's captures).  When you capture by reference, this means you can't change the reference to refer to something else, but since you can't do that already it basically means nothing.  When you capture by value it makes that value const, which means you can no longer modify like your sorting method requires (you need data to return a non-const pointer).

To get around this you can use the mutable keyword to make the lambda's operator() not const.  That would look like

```<code>auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    int n = A.size();
    sorting_alg(A.data(), n);
    std::cout << "=> ";
    print(A.data(), n);
    std::cout << std::endl;
};
</code>```

Title: Capture std::array in lambda

Body:
I was trying to test some  simple C-style sort functions. In the driver program, I wrote something like this:

int main()
{
    std::array<int, 8> A = { 1, 0, 4, 5, 7, 2, 9, 3 };
    auto lambda = [&A](const std::function<void(int *A, int n)> &sorting_alg) {
        int n = A.size();
        sorting_alg(A.data(), n);
        std::cout << "=> ";
        print(A.data(), n);
        std::cout << std::endl;
    };

    auto do_bubble_sort = std::bind(lambda, bubble_sort);
    auto do_selection_sort  = std::bind(lambda, selection_sort);
    auto do_insertion_sort  = std::bind(lambda, insertion_sort);

    std::cout << "Bubble Sort :" << std::endl;
    do_bubble_sort();
    std::cout << "Selection Sort :" << std::endl;
    do_selection_sort();
    std::cout << "Insertion Sort :" << std::endl;
    do_insertion_sort();

    return 0;
}

I had the bind code, to which I could pass A to copy, but it confines my lambda to size=8, which I want to avoid. Is it possible to achieve this without using something like std::vector, etc?
As soon I change capture method of A to value-capture, it doesn't compile anymore. I wanted to use copies for the array, to test all sorting functions. Why can't I capture std::array by value? Why then size-inference works for reference case?

Body:
The operator() of a lambda is const by default.  That means you can't modify any members of the lambda (it's captures).  When you capture by reference, this means you can't change the reference to refer to something else, but since you can't do that already it basically means nothing.  When you capture by value it makes that value const, which means you can no longer modify like your sorting method requires (you need data to return a non-const pointer).

To get around this you can use the mutable keyword to make the lambda's operator() not const.  That would look like

auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    int n = A.size();
    sorting_alg(A.data(), n);
    std::cout << "=> ";
    print(A.data(), n);
    std::cout << std::endl;
};


答: I personally find a couple things that your code could do better. First there's nothing in your class as it isn't indented. Second I find the append method to be tedious. You can initialize a list a with a = [""]* length where this will a create a list a with a specified length.

Title: A question about local variable, range, for in Python


答:
You can capture by value, but you have to change the lambda to a mutable one.

When you capture by value, the captures are const by default. You can mark it mutable or make a copy locally:

```<code>auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) {
    auto ALocal = A;
    int n = ALocal.size();
    sorting_alg(ALocal.data(), n);
    std::cout << "=> ";
    print(ALocal.data(), n);
    std::cout << std::endl;
};
</code>```

Live example

This has the advantage of making the lambda callable multiple times.

You can do this with capture by reference too.

You can alternatively make the lambda mutable, but callable only once:

```<code>auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    int n = A.size();
    sorting_alg(A.data(), n);
    std::cout << "=> ";
    print(A.data(), n);
    std::cout << std::endl;
};
</code>```

Title: Capture std::array in lambda

Body:
You can capture by value, but you have to change the lambda to a mutable one.

When you capture by value, the captures are const by default. You can mark it mutable or make a copy locally:

auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) {
    auto ALocal = A;
    int n = ALocal.size();
    sorting_alg(ALocal.data(), n);
    std::cout << "=> ";
    print(ALocal.data(), n);
    std::cout << std::endl;
};

Live example

This has the advantage of making the lambda callable multiple times.

You can do this with capture by reference too.

You can alternatively make the lambda mutable, but callable only once:

auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    int n = A.size();
    sorting_alg(A.data(), n);
    std::cout << "=> ";
    print(A.data(), n);
    std::cout << std::endl;
};


问:
Send data from an array in api and show response in next screen React Native
I want to send my data from textinputs from an array, the reason why I choose array is because the api which I am calling is basically an array, all I want to do is to set those values from textinput to api and show response to next screen.
Here's my screen One which is taking these values and sending it to api, but problem is it is not sending value neither showing me response onto next screen:

```<code> constructor(props){
        super(props);
        this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }
    }
 handleSubmit(){
     fetch("https://jsonplaceholder.typicode.com/todos/1", {
        method: "POST",
       // headers: headers,
        body:  JSON.stringify({
          userId:this.state.ze.userid,
          id:this.state.ze.ID,
          title:this.state.ze.titlex,
          completed:this.state.ze.switchValue,
        })
     })
     .then(function(response){
      return response.json();

     })
     .then(function(z){
     console.log(z)
     });
     this.props.navigation.navigate('Pg',{value:this.state.ze});
    }
</code>```

This is my next screen on which it will show me response this is what I've done so far and I dont know how to show response from an array to next screen:

```<code> componentDidMount = () => {
      const item = JSON.stringify(this.props.navigation.getParam('value'));
       Alert.alert(item.id);
     }
     render() {
        return (
           <View>
              <Text>
               {/* Name:{this.state.} */}
              </Text>
           </View>
        )
     }
</code>```

答:
You are using

```<code>this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }
</code>```

Which is in the form of Array, So you have to access it like

```<code>item[index].id
</code>```

or use the

```<code>array.map((item, index){
return (
  item.ID
)
})
</code>```

Body:
I want to send my data from textinputs from an array, the reason why I choose array is because the api which I am calling is basically an array, all I want to do is to set those values from textinput to api and show response to next screen.
Here's my screen One which is taking these values and sending it to api, but problem is it is not sending value neither showing me response onto next screen:

 constructor(props){
        super(props);
        this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }
    }
 handleSubmit(){
     fetch("https://jsonplaceholder.typicode.com/todos/1", {
        method: "POST",
       // headers: headers,
        body:  JSON.stringify({
          userId:this.state.ze.userid,
          id:this.state.ze.ID,
          title:this.state.ze.titlex,
          completed:this.state.ze.switchValue,
        })
     })
     .then(function(response){
      return response.json();

     })
     .then(function(z){
     console.log(z)
     });
     this.props.navigation.navigate('Pg',{value:this.state.ze});
    }

This is my next screen on which it will show me response this is what I've done so far and I dont know how to show response from an array to next screen:

 componentDidMount = () => {
      const item = JSON.stringify(this.props.navigation.getParam('value'));
       Alert.alert(item.id);
     }
     render() {
        return (
           <View>
              <Text>
               {/* Name:{this.state.} */}
              </Text>
           </View>
        )
     }

Body:
You are using

this.state={
            ze:[userid="",
            ID="",
            titlex="",
            switchValue=false,]
        }

Which is in the form of Array, So you have to access it like

item[index].id

or use the

array.map((item, index){
return (
  item.ID
)
})


问:
Override <ALT> to toggle menu bar on VS CODE
What I want to achieve is as follows:

Disable ALT to show menu bar by toggle-menu-bar completely.

-> Potentially map ALT to a NULL action?

Use a different shortcut to toggle-menu-bar.

Is there a way to achieve this?

答:
On Ubuntu I needed this two settings in settings.json :

```<code>"window.titleBarStyle": "custom",
"window.customMenuBarAltFocus": false
</code>```

(VS Code restart might be required)

Related:

https://github.com/microsoft/vscode/issues/84227

https://code.visualstudio.com/updates/v1_36#_disable-alt-key-focus-of-the-custom-menu-bar

ContentLicense: CC BY-SA 3.0

Body:
On Ubuntu I needed this two settings in settings.json :

"window.titleBarStyle": "custom",
"window.customMenuBarAltFocus": false

(VS Code restart might be required)

Related:

https://github.com/microsoft/vscode/issues/84227

https://code.visualstudio.com/updates/v1_36#_disable-alt-key-focus-of-the-custom-menu-bar


问:
How to get auto width for SVG icon inside a sprite?
I've a problem in setting automatic width for SVG icons, preserving aspect ratio, having a fixed height for Firefox, Chrome and IE11.
I know this is a common problem and I've read examples reported in this very good article, but I cannot find a working snippet of code to make it work.
Here's my code:

```<code><div class="icon-container">
  <svg class="icon">
    <use xlink:href="mySvgSpritePath/icons.svg#myIcon"></use>
  </svg>
</div>

<style type="text/css">
  .icon-container {
    background-color: pink;
    width: 230px;
    height: 75px;
  }
  .icon {
    background-color: lightgreen;
  }
</style>
</code>```

As expected, I get the following, the icon takes the 100% width of its container:

The viewBox of my icon (viewBox="0 0 26.81 45") is not visible in my markup because it's defined inside my SVG sprite, inside a <symbol> element.
This way I cannot use the padding hack described in the article, because I do not have access to viewBox values in my template producing the final html: if I could, I would set a dynamic padding for every different icon I can get from my sprite.

Of course, my desired output would be the following:

Have you got any suggestions, advices or even better snippets to reach this goal?

Thank you

答:
In  add attribute preserveAspectRatio="xMinYMin meet"

Use em

scss template:

```<code>.icon-{{base}} {
    font-size: 1em;
    width: ({{width.inner}} / {{height.inner}})*1em;
    height: 1em;
}
</code>```

Output:

```<code>.icon-medal {
    font-size: 1em;
    width: 1.32em;
    height: 1em;
}
</code>```

Usage:

```<code>.icon-medal {
    font-size: 75px;
}
</code>```

Body:
I've a problem in setting automatic width for SVG icons, preserving aspect ratio, having a fixed height for Firefox, Chrome and IE11.
I know this is a common problem and I've read examples reported in this very good article, but I cannot find a working snippet of code to make it work.
Here's my code:

  <svg class="icon">
    <use xlink:href="mySvgSpritePath/icons.svg#myIcon"></use>
  </svg>

As expected, I get the following, the icon takes the 100% width of its container:

The viewBox of my icon (viewBox="0 0 26.81 45") is not visible in my markup because it's defined inside my SVG sprite, inside a <symbol> element.
This way I cannot use the padding hack described in the article, because I do not have access to viewBox values in my template producing the final html: if I could, I would set a dynamic padding for every different icon I can get from my sprite.

Of course, my desired output would be the following:

Have you got any suggestions, advices or even better snippets to reach this goal?

Thank you

Body:
In  add attribute preserveAspectRatio="xMinYMin meet"

Use em

scss template:

.icon-{{base}} {
    font-size: 1em;
    width: ({{width.inner}} / {{height.inner}})*1em;
    height: 1em;
}

Output:

.icon-medal {
    font-size: 1em;
    width: 1.32em;
    height: 1em;
}

Usage:

.icon-medal {
    font-size: 75px;
}


问:
NOT NULL constraint failed: new__PFNews_pfnews.Auther_id
I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried null=True and blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much! The error I'm getting is this:
1- when i am creating new post from (frontend) it gives empty post (no title, no content and no author)
2- when i am creating from backend it works fine.
3- when i tried to remove any of null=True or blank=True or both it gives the following error :

NOT NULL constraint failed: new__PFNews_pfnews.Auther_id

models.py

```<code>class PFNews (models.Model):
Title = models.CharField(max_length=200)
Content = models.TextField()
Post_Date = models.DateTimeField(default=timezone.now)
Post_Update = models.DateTimeField(auto_now=True)
Auther = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
    return self.Title

def get_absolute_url(self):
    # return '/detail/{}'.format(self.pk)
    return reverse('pfnewsdetails', args=[self.pk])
class Meta:
    ordering = ('-Post_Date',)
</code>```

views.py

```<code>class PostCreateView(LoginRequiredMixin, CreateView):
model = PFNews
# fields = ['title', 'content']
template_name = 'PFNews/new_post.html'
form_class = PostCreateForm

def form_valid(self, form_class):
    form_class.instance.author = self.request.user
    return super().form_valid(form_class)
</code>```

urls.py

```<code>urlpatterns = [
path('', home, name='home'),
path('about/', aboutus, name='about'),
path('newsdetail/<int:pfnews_id>/', pfnews_detail, name='pfnewsdetails'),
path('new_post/', PostCreateView.as_view(), name='new_post'),
path('detail/<slug:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('detail/<slug:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),]
</code>```

答:
In views.py

form_class.instance.author=self.request.user

There is no instance author as in lower case in you models.py ... check your spellings

Body:
I looked at a ton of these issues on stack overflow, but none of the solutions seemed to help me. I've tried null=True and blank=True as well as default=None and they all give errors. Anyone have any ideas? Thanks so much! The error I'm getting is this:
1- when i am creating new post from (frontend) it gives empty post (no title, no content and no author)
2- when i am creating from backend it works fine.
3- when i tried to remove any of null=True or blank=True or both it gives the following error :

NOT NULL constraint failed: new__PFNews_pfnews.Auther_id

models.py

class PFNews (models.Model):
Title = models.CharField(max_length=200)
Content = models.TextField()
Post_Date = models.DateTimeField(default=timezone.now)
Post_Update = models.DateTimeField(auto_now=True)
Auther = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True)

def __str__(self):
    return self.Title

def get_absolute_url(self):
    # return '/detail/{}'.format(self.pk)
    return reverse('pfnewsdetails', args=[self.pk])
class Meta:
    ordering = ('-Post_Date',)

views.py

class PostCreateView(LoginRequiredMixin, CreateView):
model = PFNews
# fields = ['title', 'content']
template_name = 'PFNews/new_post.html'
form_class = PostCreateForm

def form_valid(self, form_class):
    form_class.instance.author = self.request.user
    return super().form_valid(form_class)

urls.py

urlpatterns = [
path('', home, name='home'),
path('about/', aboutus, name='about'),
path('newsdetail/<int:pfnews_id>/', pfnews_detail, name='pfnewsdetails'),
path('new_post/', PostCreateView.as_view(), name='new_post'),
path('detail/<slug:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('detail/<slug:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),]


问:
Swift 5 | didSelectRowAt is selecting two cells at the same time
I am doing a screen where there a list o cells with a switch, like an image below;
I have a struct where a save the label of the cell and the switch state value. This struct is loaded at: var source: [StructName] = [] and then source values are attributed to the UITableView cells.

The problem is that when a touch a cell the function: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) change multiples cells switches states at the same time.
I try to work around the problem by implementing the following function:

```<code>    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    for n in 0..<source.count{ // This loop search for the right cell by looking at the cell label text and the struct where the state of the switch is saved
        if cell.label.text! == source[n].Label{
            // If the label text is equal to the position where the values is saved (is the same order that the cells are loaded in the UITableView) then a change the state of the switch
            let indexLabel = IndexPath(row: n, section: 0)
            let cellValues = tableView.cellForRow(at: indexLabel) as! CustomTableViewCell
            if cellValues.switchButton.isOn {
                cellValues.switchButton.setOn(false, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            } else {
                cellValues.switchButton.setOn(true, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            }
            break
        }
    }
</code>```

although is saved the right values to the switch state array(source) the visual state of multiples switches also changes even though the cells where never touch.

How could I change my code to select and change only the touched cell?

答:
You should not store / read the state of anything in a cell.
But first things first:

Why do loop through all the values? You should be able to access the row in the data model directly by indexPath.row

You should only modify the model data, not the cell

You then tell the table view to reload the cell, which will then ask the model for the correct data to be displayed.

I would suggest the following:

```<code>func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let row = indexPath.row
    source[row].valor.toggle()
    tableView.reloadRows(at:[indexPath], with:.automatic)
}
</code>```

Body:
I am doing a screen where there a list o cells with a switch, like an image below;
I have a struct where a save the label of the cell and the switch state value. This struct is loaded at: var source: [StructName] = [] and then source values are attributed to the UITableView cells.

The problem is that when a touch a cell the function: func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) change multiples cells switches states at the same time.
I try to work around the problem by implementing the following function:

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let cell = tableView.cellForRow(at: indexPath) as! CustomTableViewCell
    for n in 0..<source.count{ // This loop search for the right cell by looking at the cell label text and the struct where the state of the switch is saved
        if cell.label.text! == source[n].Label{
            // If the label text is equal to the position where the values is saved (is the same order that the cells are loaded in the UITableView) then a change the state of the switch
            let indexLabel = IndexPath(row: n, section: 0)
            let cellValues = tableView.cellForRow(at: indexLabel) as! CustomTableViewCell
            if cellValues.switchButton.isOn {
                cellValues.switchButton.setOn(false, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            } else {
                cellValues.switchButton.setOn(true, animated: true)
                source[n].valor = cellValues.switchButton.isOn
            }
            break
        }
    }

although is saved the right values to the switch state array(source) the visual state of multiples switches also changes even though the cells where never touch.

How could I change my code to select and change only the touched cell?

Body:
You should not store / read the state of anything in a cell.
But first things first:

Why do loop through all the values? You should be able to access the row in the data model directly by indexPath.row

You should only modify the model data, not the cell

You then tell the table view to reload the cell, which will then ask the model for the correct data to be displayed.

I would suggest the following:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)

    let row = indexPath.row
    source[row].valor.toggle()
    tableView.reloadRows(at:[indexPath], with:.automatic)
}


问:
What will the code below output to the console and what is the reason?
This is an interview question and I'm very curious about the answer.</p>

```<code>var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();
</code>```

答:
Answer:

```<code>"outer func:  this.foo = bar"
"outer func:  self.foo = bar"
"inner func:  this.foo = undefined"
"inner func:  self.foo = bar"
</code>```

Reason: This references the object that is executing the current function.

If that function is a regular function which means it's not part of
an object This reference's the global object which is the window
object in browsers and global in node

If that function is a part of an object we call that function, a
method. So if that function is a method in an object this
references that object itself.

Body:
This is an interview question and I'm very curious about the answer.

var myObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func:  this.foo = " + this.foo);
        console.log("outer func:  self.foo = " + self.foo);
        (function() {
            console.log("inner func:  this.foo = " + this.foo);
            console.log("inner func:  self.foo = " + self.foo);
        }());
    }
};
myObject.func();

Body:
Answer:

"outer func:  this.foo = bar"
"outer func:  self.foo = bar"
"inner func:  this.foo = undefined"
"inner func:  self.foo = bar"

Reason: This references the object that is executing the current function.

If that function is a regular function which means it's not part of
an object This reference's the global object which is the window
object in browsers and global in node

If that function is a part of an object we call that function, a
method. So if that function is a method in an object this
references that object itself.


问:
Conditionally edit column values for n number of rows
I would like to change the values of a given column for the first 4 rows that appear for a specific boxer in my dataset

This is a sample of my data

```<code>name               clean_outcome
Tyson Fury             an
Other Boxer            win
Tyson Fury             an
Other Boxer            win
Tyson Fury
Tyson Fury
Tyson Fury
Other Boxer
Tyson Fury
</code>```

...

This is what I have tried:

```<code>fully_merged[fully_merged.name == 'Tyson Fury'].iloc[0:4]['clean_outcome'] = 'Win Other'
</code>```

The ideal output would be this:

```<code>name               clean_outcome
Tyson Fury             Win Other
Tyson Fury             Win Other
Tyson Fury             Win Other
Tyson Fury             Win Other
</code>```

答:
IIUC, use .loc with boolean indexing and column filtering,

```<code>df.loc[((df['name'] == 'Tyson Fury').cumsum() <= 4) &
        (df['name'] == 'Tyson Fury'),
       'clean_outcome'] = 'Win Other'
</code>```

Output:

```<code>          name clean_outcome
0   Tyson Fury     Win Other
1  Other Boxer           win
2   Tyson Fury     Win Other
3  Other Boxer           win
4   Tyson Fury     Win Other
5   Tyson Fury     Win Other
6   Tyson Fury          None
7  Other Boxer          None
8   Tyson Fury          None
</code>```

Body:
I would like to change the values of a given column for the first 4 rows that appear for a specific boxer in my dataset

This is a sample of my data

name               clean_outcome
Tyson Fury             an
Other Boxer            win
Tyson Fury             an
Other Boxer            win
Tyson Fury
Tyson Fury
Tyson Fury
Other Boxer
Tyson Fury

...

This is what I have tried:

fully_merged[fully_merged.name == 'Tyson Fury'].iloc[0:4]['clean_outcome'] = 'Win Other'

The ideal output would be this:

name               clean_outcome
Tyson Fury             Win Other
Tyson Fury             Win Other
Tyson Fury             Win Other
Tyson Fury             Win Other

Body:
IIUC, use .loc with boolean indexing and column filtering,

df.loc[((df['name'] == 'Tyson Fury').cumsum() <= 4) &
        (df['name'] == 'Tyson Fury'),
       'clean_outcome'] = 'Win Other'

Output:

          name clean_outcome
0   Tyson Fury     Win Other
1  Other Boxer           win
2   Tyson Fury     Win Other
3  Other Boxer           win
4   Tyson Fury     Win Other
5   Tyson Fury     Win Other
6   Tyson Fury          None
7  Other Boxer          None
8   Tyson Fury          None


问:
How to fix map offset of the tales? on Yandex MAP API
I used vue-yandex-maps this plugin! And i have some problem with offset of tales on Map!

You can see this:

You can see my code, i cannot understand and fix this issues:

```<code><template>
  <yandex-map :settings="settings" :coords="coords" zoom="10">
    <ymap-marker :coords="coords" marker-id="123123" marker-type="placemark" />
  </yandex-map>
</template>

<script>
import { yandexMap, loadYmap, ymapMarker } from "vue-yandex-maps";

export default {
  components: { yandexMap, ymapMarker },
  data() {
    return {
      coords: [54.82896654088406, 39.831893822753904],
      settings: {
        apiKey: "AIzaSyBgLAe7N_MdFpuVofMkcQLGwwhUu5tuxls",
        lang: "ru_RU",
        // coordorder: "latlong",
        version: "2.1",
        type: "yandex#map",
        behaviors: ["default", "scrollZoom"]
      },
      place: null // optional
    };
  },
  mounted() {
    let { settings } = this;
    loadYmap({ settings, debug: true });
  }
};
</script>
</code>```

答:
I found my mistake! In a global scc i have a code for all tags padding and margin:

```<code>* {
  margin: 0;
  padding: 0;
  /* ... */
}
</code>```

And i changed this:

```<code>body,
html,
ul {
  margin: 0;
  padding: 0;
  /* ... */
}
</code>```

It works for me!

Body:
I used vue-yandex-maps this plugin! And i have some problem with offset of tales on Map!

You can see this:

You can see my code, i cannot understand and fix this issues:

<template>
  <yandex-map :settings="settings" :coords="coords" zoom="10">
    <ymap-marker :coords="coords" marker-id="123123" marker-type="placemark" />
  </yandex-map>
</template>

Body:
I found my mistake! In a global scc i have a code for all tags padding and margin:

* {
  margin: 0;
  padding: 0;
  /* ... */
}

And i changed this:

body,
html,
ul {
  margin: 0;
  padding: 0;
  /* ... */
}

It works for me!


问:
How to analyze (very incomplete) round-robin data
I have a design in which I have pairs of individuals that compete against each other. Each pair thus has one winner.

A vs B B wins

B vs C C wins

...

I have also measured a continuous variable (X) of each individual and I expect that X predicts wins. Normally I would thus calculate a difference score for each pair and then predict the win
E.g.,

model <- glm(data$Winner ~ data$diff, family = "binomial" )
summary(model)

However, I do have a few individuals in the dataset who appear in multiple pairs (hence an "incomplete round-robin"):

A vs B

C vs D

A vs E

F vs G

...

I don't know how to account for these "overlapping" pairs in the analyses.

Thanks a lot for any input.

答: You could also select a discrete choice model, where you model "A vs B" as a situation where A and B are possible choices and if A wins against B you model A as the chosen alternative. In R I know the package mlogit that can calculate such models.


问:
how to round up a double value in dart/flutter
Is there anyway to round up a double value?

I want result always rounded up.

```<code>int offSet = (totalRecords / 10).round();
</code>```

答:
It's ceil:

Returns the least integer no smaller than this.

```<code>int offSet = (totalRecords / 10).ceil();
</code>```

Body:
Is there anyway to round up a double value?

I want result always rounded up.

int offSet = (totalRecords / 10).round();

Body:
It's ceil:

Returns the least integer no smaller than this.

int offSet = (totalRecords / 10).ceil();


问:
React-router-dom: Clicking on Link adds the route to the Url Link indefinitely
After several attempts, I have managed to implement basic nested-routing with React-router-dom.

Here's the simple project structure:

Here are the relevant files:

App.js

```<code>import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";
function App() {
  return (
    <div className="App">
      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>
    </div>
  );
}

export default App;
</code>```

NavBar.js

```<code>import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (
    <div>
      <Link to={`home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`home/nestedComponentTwo`}> Nested Component Two </Link>
    </div>
  );
}
</code>```

ParentComponent.js

```<code>import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (
    <div>
      <Switch>
        <Route path="/home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>
    </div>
  );
}
</code>```

nestedComponentOne.js

```<code>import React from "react";

export default function nestedComponentOne() {
  return <div>NESTED COMPONENT 1</div>;
}
</code>```

nestedComponentTwo.js

```<code>import React from "react";

export default function nestedComponentTwo() {
  return <div>NESTED COMPONENT 2</div>;
}
</code>```

So here's the Result:

If I click on nestedComponentOne:

If I click on nestedComponentTwo:

The problem is when I click again on nestedComponentOne (or Two) after the I have clicked it the first time, the route gets added to the url string instead of replacing it:

答:
Some update need for your code.
Working Demo

NavBar.js

Here you forget to add slash / at front to link from root.

```<code>      <Link to={`/home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`/home/nestedComponentTwo`}> Nested Component Two </Link>
</code>```

ParentComponent.js

As we removed the Switch from this component, so we need to get the matching information from parent router and pass the path to navigate the corresponding your nested component

```<code>     export default function ParentComponent({ match }) {
      return (
        <div>
          <Route path={`${match.path}/nestedComponentOne`} component={nestedComponentOne} />
          <Route path={`${match.path}/nestedComponentTwo`} component={nestedComponentTwo} />
        </div>
      );
    }
</code>```

Body:
After several attempts, I have managed to implement basic nested-routing with React-router-dom.

Here's the simple project structure:

Here are the relevant files:

App.js

import React from "react";
import logo from "./logo.svg";
import "./App.css";
import { BrowserRouter, Switch, Route } from "react-router-dom";

import ParentComponent from "./Components/nestedComponents/ParentComponent";
import NavBar from "./Components/Shared/NavBar";
function App() {
  return (

      <BrowserRouter>
        <NavBar />
        <Switch>
          <Route path="/home" name="Home" component={ParentComponent} />
        </Switch>
      </BrowserRouter>

  );
}

export default App;

NavBar.js

import React from "react";
import { Link } from "react-router-dom";

export default function NavBar() {
  return (

      <Link to={`home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`home/nestedComponentTwo`}> Nested Component Two </Link>

  );
}

ParentComponent.js

import React from "react";
import nestedComponentOne from "./nestedComponentOne";
import nestedComponentTwo from "./nestedComponentTwo";
import { Switch, Route } from "react-router-dom";

export default function ParentComponent() {
  return (

      <Switch>
        <Route path="/home/nestedComponentOne" component={nestedComponentOne} />
        <Route path="/home/nestedComponentTwo" component={nestedComponentTwo} />
      </Switch>

  );
}

nestedComponentOne.js

import React from "react";

export default function nestedComponentOne() {
  return
NESTED COMPONENT 1
;
}

nestedComponentTwo.js

import React from "react";

export default function nestedComponentTwo() {
  return
NESTED COMPONENT 2
;
}

So here's the Result:

If I click on nestedComponentOne:

If I click on nestedComponentTwo:

The problem is when I click again on nestedComponentOne (or Two) after the I have clicked it the first time, the route gets added to the url string instead of replacing it:

Body:
Some update need for your code.
Working Demo

NavBar.js

Here you forget to add slash / at front to link from root.

      <Link to={`/home/nestedComponentOne`}> Nested Component One </Link>
      <Link to={`/home/nestedComponentTwo`}> Nested Component Two </Link>

ParentComponent.js

As we removed the Switch from this component, so we need to get the matching information from parent router and pass the path to navigate the corresponding your nested component

     export default function ParentComponent({ match }) {
      return (
        <div>
          <Route path={`${match.path}/nestedComponentOne`} component={nestedComponentOne} />
          <Route path={`${match.path}/nestedComponentTwo`} component={nestedComponentTwo} />
        </div>
      );
    }


问:
mdf file is work correctly under App_data folder but after attaching to sql server give following error
mdf file is working correctly under App_data folder but after attaching it to sql server give following error when running asp.net page.

Cannot open user default database. Login failed.
Login failed for user 'Domain\myUserName'.

[edit]
More information; SQL data source and connection string.

```<code><asp:SqlDataSource
        id="srcFiles"
        ConnectionString="Server=.\SQLExpress;Integrated Security=True;
            AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True"
        SelectCommand="SELECT Id,FileName FROM Files"
        InsertCommand="INSERT Files (FileName,FileBytes) VALUES (@FileName,@FileBytes)"
        Runat="server">
        <InsertParameters>
            <asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
            <asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
        </InsertParameters>
    </asp:SqlDataSource>
</code>```

答:
If you are using visual studio and you have created a local database that way, and want to know what the 'correct' connection string is:

1) Open the Server Explorer

2) Under 'data connections' select your database and choose 'properties'

3) Look at the 'connection string' property.

That is what you must use.

In your case, it is possibly incorrect because you have not specified a 'Data Source' param. Here is an example of a valid connection string:

Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True

ContentLicense: CC BY-SA 2.5

Body:
mdf file is working correctly under App_data folder but after attaching it to sql server give following error when running asp.net page.

Cannot open user default database. Login failed.
Login failed for user 'Domain\myUserName'.

[edit]
More information; SQL data source and connection string.

<asp:SqlDataSource
        id="srcFiles"
        ConnectionString="Server=.\SQLExpress;Integrated Security=True;
            AttachDbFileName=|DataDirectory|FilesDB.mdf;User Instance=True"
        SelectCommand="SELECT Id,FileName FROM Files"
        InsertCommand="INSERT Files (FileName,FileBytes) VALUES (@FileName,@FileBytes)"
        Runat="server">
        <InsertParameters>
            <asp:ControlParameter Name="FileName" ControlID="upFile" PropertyName="FileName" />
            <asp:ControlParameter Name="FileBytes" ControlID="upFile" PropertyName="FileBytes" />
        </InsertParameters>
    </asp:SqlDataSource>


问:
How to customize the Gantt chart using matplotlib and display the vertical line indicating current time on a graph?
Here is my Python code which basically plots a Gantt chart:

```<code>import pandas as pd
import random
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
%matplotlib inline
import math
plt.style.use('ggplot')

df = pd.read_csv('zpp00141_new.csv')

def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))

df.rename(columns={"Earl. start / time": "start", "Latest finish / time": "finish"}, inplace = True)

df['Operation/Activity'] = df['Operation/Activity'].astype(str)

fig, ax = plt.subplots(figsize=(10, 5))
operations = pd.unique(df['Operation/Activity'])
#df.assign(start=df['Earl. start / time'])
colors = plt.cm.tab10.colors  # get a list of 10 colors
colors *= math.ceil(len(operations) / (len(colors)))  # repeat the list as many times as needed
for operation, color in zip(operations, colors):
    for row in df[df['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=3, color=color)
ax.set_xlim(timestr_to_num('07:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
ax.set_xlabel('Time')
ax.set_ylabel('Operation')
plt.tight_layout()
plt.show()
</code>```

You can see the output on the attached picture:

I would like to plot a vertical straight line that would correspond with a current time on the x-axis. I tried to add this to my code to plot it but I can't figure out how to make it work. I assume there might an issue with my time formatting or something like that:

```<code>plt.axvline(pd.Timestamp.now(),color='r')
</code>```

I would really appreciate any assistance in this matter.
Here is a picture of the desired output, I want my plot to be alike:

Also, I would like to add/append another category to my y-axis "Operation short text" along with the "Operation/Activity"# so it would not only show the operation number, but would also reflect the description of the operation next to it.
To have a grasp of what my data looks like,see below (first row is a header):

```<code>Operation short text,Operation/Activity,Earl. start / time,Latest finish / time
Mount right racks,0250,7:00:00 AM,9:22:00 AM
Mount right side motion unit carriage,0251,9:22:00 AM,10:30:00 AM
Mount left side motion unit carriage,0252,10:30:00 AM,11:17:00 AM
Install motion unit complete,0253,11:17:00 AM,1:01:00 PM
Move machine to next step + EPA,0254,1:01:00 PM,3:30:00 PM
Mount Left Racks,0200,7:00:00 AM,9:12:00 AM
Mount cable motor & Lubricate guide carr,0201,9:12:00 AM,9:44:00 AM
Mount suction components,0202,9:44:00 AM,11:04:00 AM
Mount extraction,0203,11:04:00 AM,12:34:00 PM
Mount temporary diamond plates,0204,12:34:00 PM,1:04:00 PM
Mount piping inside,0205,1:04:00 PM,1:44:00 PM
Move Machine to next step + EPA,0206,1:44:00 PM,3:30:00 PM
</code>```

答:
I was able to plot a vertical line using this code:

```<code>now = datetime.now()
now = now.strftime('%I:%M:%S %p')
plt.axvline(x=timestr_to_num(now),color='r')
</code>```

I basically converted the "now" time to the certain format and converted it again using the timestr_to_num that I defined at the beginning.

However, I still need some help with adding a secondary values to my y-axis values (operation short text)

Body:
Here is my Python code which basically plots a Gantt chart:

import pandas as pd
import random
from datetime import datetime
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
%matplotlib inline
import math
plt.style.use('ggplot')

df = pd.read_csv('zpp00141_new.csv')

def timestr_to_num(timestr):
    return mdates.date2num(datetime.strptime('0' + timestr if timestr[1] == ':' else timestr, '%I:%M:%S %p'))

df.rename(columns={"Earl. start / time": "start", "Latest finish / time": "finish"}, inplace = True)

df['Operation/Activity'] = df['Operation/Activity'].astype(str)

fig, ax = plt.subplots(figsize=(10, 5))
operations = pd.unique(df['Operation/Activity'])
#df.assign(start=df['Earl. start / time'])
colors = plt.cm.tab10.colors  # get a list of 10 colors
colors *= math.ceil(len(operations) / (len(colors)))  # repeat the list as many times as needed
for operation, color in zip(operations, colors):
    for row in df[df['Operation/Activity'] == operation].itertuples():
        left = timestr_to_num(row.start)
        right = timestr_to_num(row.finish)
        ax.barh(operation, left=left, width=right - left, height=3, color=color)
ax.set_xlim(timestr_to_num('07:00:00 AM'), timestr_to_num('4:30:00 PM'))
ax.xaxis.set_major_formatter(mdates.DateFormatter('%H:%M'))  # display ticks as hours and minutes
ax.xaxis.set_major_locator(mdates.HourLocator(interval=1))  # set a tick every hour
ax.set_xlabel('Time')
ax.set_ylabel('Operation')
plt.tight_layout()
plt.show()

You can see the output on the attached picture:

I would like to plot a vertical straight line that would correspond with a current time on the x-axis. I tried to add this to my code to plot it but I can't figure out how to make it work. I assume there might an issue with my time formatting or something like that:

plt.axvline(pd.Timestamp.now(),color='r')

I would really appreciate any assistance in this matter.
Here is a picture of the desired output, I want my plot to be alike:

Also, I would like to add/append another category to my y-axis "Operation short text" along with the "Operation/Activity"# so it would not only show the operation number, but would also reflect the description of the operation next to it.
To have a grasp of what my data looks like,see below (first row is a header):

Operation short text,Operation/Activity,Earl. start / time,Latest finish / time
Mount right racks,0250,7:00:00 AM,9:22:00 AM
Mount right side motion unit carriage,0251,9:22:00 AM,10:30:00 AM
Mount left side motion unit carriage,0252,10:30:00 AM,11:17:00 AM
Install motion unit complete,0253,11:17:00 AM,1:01:00 PM
Move machine to next step + EPA,0254,1:01:00 PM,3:30:00 PM
Mount Left Racks,0200,7:00:00 AM,9:12:00 AM
Mount cable motor & Lubricate guide carr,0201,9:12:00 AM,9:44:00 AM
Mount suction components,0202,9:44:00 AM,11:04:00 AM
Mount extraction,0203,11:04:00 AM,12:34:00 PM
Mount temporary diamond plates,0204,12:34:00 PM,1:04:00 PM
Mount piping inside,0205,1:04:00 PM,1:44:00 PM
Move Machine to next step + EPA,0206,1:44:00 PM,3:30:00 PM

Body:
I was able to plot a vertical line using this code:

now = datetime.now()
now = now.strftime('%I:%M:%S %p')
plt.axvline(x=timestr_to_num(now),color='r')

I basically converted the "now" time to the certain format and converted it again using the timestr_to_num that I defined at the beginning.

However, I still need some help with adding a secondary values to my y-axis values (operation short text)


问:
Converting a sequence chart to Python code

```<code>def Input_Numbers():
    global Number1
    global Number2
    Number1 = int(input("please enter a value for Number 1 : "))
    Number2 = int(input("please enter a value for Number 2 : "))

def Calculate_average(Number1,Number2):
    Average = (Number1 + Number2)/2
    return Average

def Output_average(Average):
    print(Average)
    return Average

Input_Numbers()
Calculate_average(Number1,Number2)
Output_average(Average)
</code>```

Here is my attempt of representing the structure chart but I'm not sure if it is correct

答:
I guess it should be as follows:</p>

```<code>def input_Numbers():
    number1 = int(input("Please enter a value for Number 1 : "))
    number2 = int(input("Please enter a value for Number 2 : "))
    return number1,number2

def calculate_Average(number1,number2):
    average = (number1 + number2)/2
    return average

def output_Average(average):
    print(average)

number1, number2 = input_Numbers()
average = calculate_Average(number1,number2)
output_Average(average)
</code>```

Body:
def Input_Numbers():
    global Number1
    global Number2
    Number1 = int(input("please enter a value for Number 1 : "))
    Number2 = int(input("please enter a value for Number 2 : "))

def Calculate_average(Number1,Number2):
    Average = (Number1 + Number2)/2
    return Average

def Output_average(Average):
    print(Average)
    return Average

Input_Numbers()
Calculate_average(Number1,Number2)
Output_average(Average)

Here is my attempt of representing the structure chart but I'm not sure if it is correct

Body:
I guess it should be as follows:

def input_Numbers():
    number1 = int(input("Please enter a value for Number 1 : "))
    number2 = int(input("Please enter a value for Number 2 : "))
    return number1,number2

def calculate_Average(number1,number2):
    average = (number1 + number2)/2
    return average

def output_Average(average):
    print(average)

number1, number2 = input_Numbers()
average = calculate_Average(number1,number2)
output_Average(average)


答:
try with

```<code>num.parse((totalRecords / 10).toStringAsFixed(3))
</code>```

if you want 3 decimal

Title: how to round up a double value in dart/flutter

Body:
try with

num.parse((totalRecords / 10).toStringAsFixed(3))

if you want 3 decimal


问:
OPOS PosExplorer.GetDevice() returns null when executed in Windows Service
The code snippet below makes use of OPOS .NET to open a POS printer for printing. It works fine when executed as part of a standalone application. When executed by a Windows Service the call to GetDevice(...) always returns null.

```<code>explorer = new PosExplorer();
device_info = explorer.GetDevice(DeviceType.PosPrinter, PrinterName);
printer = (PosPrinter)explorer.CreateInstance(device_info);
printer.Open();
printer.Claim(1000);
printer.DeviceEnabled = true;
</code>```

The printer happens to be an Epson TM-U220B. Is there a security issue that needs to be overcome before a service has access to POS devices? Can anyone recommend a good source of information regarding the development of Windows Services that use OPOS .NET?

答:
Your code looks good. I see the variable name PrinterName. This variable should contain the Logical Name assigned to the printer. The Logical Name assignment is a seperate step that may be overlooked. You can confirm the proper existance of the Logical Name using POSDM available from the POS for .Net SDK. The command path would be

C:\Program Files\Microsoft Point Of Service\POSDM LISTNAMES

If the device and assigned Logical Name do not appear then that would explain your current situation.

Body:
The code snippet below makes use of OPOS .NET to open a POS printer for printing. It works fine when executed as part of a standalone application. When executed by a Windows Service the call to GetDevice(...) always returns null.

explorer = new PosExplorer();
device_info = explorer.GetDevice(DeviceType.PosPrinter, PrinterName);
printer = (PosPrinter)explorer.CreateInstance(device_info);
printer.Open();
printer.Claim(1000);
printer.DeviceEnabled = true;

The printer happens to be an Epson TM-U220B. Is there a security issue that needs to be overcome before a service has access to POS devices? Can anyone recommend a good source of information regarding the development of Windows Services that use OPOS .NET?


问:
how can something be bigger than (unsigned long long) > LONG_MAX?
I found this code in an algorithm I need to update:

```<code> if (value > (unsigned long long) LONG_MAX)
</code>```

EDIT: value is the result of a division of two uint64_t numbers.

I understand that (unsigned long long) LONG_MAX is a VERY big number:

```<code>   #include "stdio.h"
   #include "limits.h"

   int main() {
     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);
     return 0;
   }
</code>```

prints 9223372036854775807

So what I am comparing here? In what case this if statement will evaluate to true?

答:
how can something be bigger than (unsigned long long) > LONG_MAX?

Easily.  LONG MAX is the maximum value that can be represented as a long int.  Converting that to unsigned long long does not change its value, only its data type.  The maximum value that can be represented as an unsigned long int is larger on every C implementation you're likely to meet.  The maximum value of long long int is larger on some, and the maximum value of unsigned long long int is, again, larger on every C implementation you're likely to meet (much larger on some).

However, this ...

```<code>     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);
</code>```

... is not a conforming way to investigate the value in question because %lu is a formatting directive for type unsigned long, not unsigned long long.  The printf call presented therefore has undefined behavior.

I found this code in an algorithm I need to update:

```<code> if (value > (unsigned long long) LONG_MAX)
</code>```

EDIT: value is the result of a division of two uint64_t numbers.

[...]

In what case this if statement will
  evaluate to true?

Supposing that value has type uint64_t, which is probably the same as unsigned long long in your implementation, the condition in that if statement will evaluate to true at least when the most-significant bit of value is set.  If your long int is only 32 bits wide, however, then the condition will evaluate to true much more widely than that, because there are many 64-bit integers that are larger than the largest value representable as a signed 32-bit integer.

I would be inclined to guess that the code was indeed written under the assumption that long int is 32 bits wide, so that the if statement asks a very natural question: "can the result of the previous uint64_t division be represented as a long?"  In fact, that's what the if statement is evaluating in any case, but it makes more sense if long is only 32 bits wide, which is typical of 32-bit computers and standard on both 32- and 64-bit Windows.

Body:
I found this code in an algorithm I need to update:

 if (value > (unsigned long long) LONG_MAX)

EDIT: value is the result of a division of two uint64_t numbers.

I understand that (unsigned long long) LONG_MAX is a VERY big number:

   #include "stdio.h"
   #include "limits.h"

   int main() {
     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);
     return 0;
   }

prints 9223372036854775807

So what I am comparing here? In what case this if statement will evaluate to true?

Body:
how can something be bigger than (unsigned long long) > LONG_MAX?

Easily.  LONG MAX is the maximum value that can be represented as a long int.  Converting that to unsigned long long does not change its value, only its data type.  The maximum value that can be represented as an unsigned long int is larger on every C implementation you're likely to meet.  The maximum value of long long int is larger on some, and the maximum value of unsigned long long int is, again, larger on every C implementation you're likely to meet (much larger on some).

However, this ...

     unsigned long long ull = (unsigned long long) LONG_MAX;
     printf("%lu",ull);

... is not a conforming way to investigate the value in question because %lu is a formatting directive for type unsigned long, not unsigned long long.  The printf call presented therefore has undefined behavior.

I found this code in an algorithm I need to update:

 if (value > (unsigned long long) LONG_MAX)

EDIT: value is the result of a division of two uint64_t numbers.

[...]

In what case this if statement will
  evaluate to true?

Supposing that value has type uint64_t, which is probably the same as unsigned long long in your implementation, the condition in that if statement will evaluate to true at least when the most-significant bit of value is set.  If your long int is only 32 bits wide, however, then the condition will evaluate to true much more widely than that, because there are many 64-bit integers that are larger than the largest value representable as a signed 32-bit integer.

I would be inclined to guess that the code was indeed written under the assumption that long int is 32 bits wide, so that the if statement asks a very natural question: "can the result of the previous uint64_t division be represented as a long?"  In fact, that's what the if statement is evaluating in any case, but it makes more sense if long is only 32 bits wide, which is typical of 32-bit computers and standard on both 32- and 64-bit Windows.


问:
could not find class EqualsBuilder, but I've included commons-lang
I am trying to use EqualsBuilder in the apache commons library.  So, I downloaded commons-lang3-3.1.jar from the apache site, and in Eclipse I configured my build path to add it to my  set of libraries.  I see it listed in my libraries, and if I hit cmd+shift+o it automatically adds this import:

```<code>import org.apache.commons.lang3.builder.EqualsBuilder;
</code>```

However, when I run my application and try to use it, I get:

```<code>Could not find class 'org.apache.commons.lang3.builder.EqualsBuilder', referenced from method com.gnychis.awmon.DeviceAbstraction.Interface.equals
</code>```

Is there something simple I'm missing, here?

答:
In case you are using maven, add the following dependency to your pom.xml file:

```<code><dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>
</code>```

Or if you ever need "lang" dependencies rather than "lang3", use this one instead:

```<code>    <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>
</code>```

Body:
I am trying to use EqualsBuilder in the apache commons library.  So, I downloaded commons-lang3-3.1.jar from the apache site, and in Eclipse I configured my build path to add it to my  set of libraries.  I see it listed in my libraries, and if I hit cmd+shift+o it automatically adds this import:

import org.apache.commons.lang3.builder.EqualsBuilder;

However, when I run my application and try to use it, I get:

Could not find class 'org.apache.commons.lang3.builder.EqualsBuilder', referenced from method com.gnychis.awmon.DeviceAbstraction.Interface.equals

Is there something simple I'm missing, here?

Body:
In case you are using maven, add the following dependency to your pom.xml file:

<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.9</version>
</dependency>

Or if you ever need "lang" dependencies rather than "lang3", use this one instead:

    <groupId>commons-lang</groupId>
        <artifactId>commons-lang</artifactId>
        <version>2.6</version>
    </dependency>


问:
Capture std::array in lambda
I was trying to test some  simple C-style sort functions. In the driver program, I wrote something like this:

```<code>int main()
{
    std::array<int, 8> A = { 1, 0, 4, 5, 7, 2, 9, 3 };
    auto lambda = [&A](const std::function<void(int *A, int n)> &sorting_alg) {
        int n = A.size();
        sorting_alg(A.data(), n);
        std::cout << "=> ";
        print(A.data(), n);
        std::cout << std::endl;
    };

    auto do_bubble_sort = std::bind(lambda, bubble_sort);
    auto do_selection_sort  = std::bind(lambda, selection_sort);
    auto do_insertion_sort  = std::bind(lambda, insertion_sort);

    std::cout << "Bubble Sort :" << std::endl;
    do_bubble_sort();
    std::cout << "Selection Sort :" << std::endl;
    do_selection_sort();
    std::cout << "Insertion Sort :" << std::endl;
    do_insertion_sort();

    return 0;
}
</code>```

I had the bind code, to which I could pass A to copy, but it confines my lambda to size=8, which I want to avoid. Is it possible to achieve this without using something like std::vector, etc?
As soon I change capture method of A to value-capture, it doesn't compile anymore. I wanted to use copies for the array, to test all sorting functions. Why can't I capture std::array by value? Why then size-inference works for reference case?

答:
The problem is that the operator() of the lambda function is const-qualified by default. This means that the values captured by value are const-qualified in the lambda body. In your code, you are trying to invoke std::function with a non-const pointer to int initialized from the captured array, which is const.

To fix this you need to mark your lambda as mutable so that the generated operator() is no longer const-qualified:

```<code>auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    ...
}
</code>```

Title: Capture std::array in lambda

Body:
I was trying to test some  simple C-style sort functions. In the driver program, I wrote something like this:

int main()
{
    std::array<int, 8> A = { 1, 0, 4, 5, 7, 2, 9, 3 };
    auto lambda = [&A](const std::function<void(int *A, int n)> &sorting_alg) {
        int n = A.size();
        sorting_alg(A.data(), n);
        std::cout << "=> ";
        print(A.data(), n);
        std::cout << std::endl;
    };

    auto do_bubble_sort = std::bind(lambda, bubble_sort);
    auto do_selection_sort  = std::bind(lambda, selection_sort);
    auto do_insertion_sort  = std::bind(lambda, insertion_sort);

    std::cout << "Bubble Sort :" << std::endl;
    do_bubble_sort();
    std::cout << "Selection Sort :" << std::endl;
    do_selection_sort();
    std::cout << "Insertion Sort :" << std::endl;
    do_insertion_sort();

    return 0;
}

I had the bind code, to which I could pass A to copy, but it confines my lambda to size=8, which I want to avoid. Is it possible to achieve this without using something like std::vector, etc?
As soon I change capture method of A to value-capture, it doesn't compile anymore. I wanted to use copies for the array, to test all sorting functions. Why can't I capture std::array by value? Why then size-inference works for reference case?

Body:
The problem is that the operator() of the lambda function is const-qualified by default. This means that the values captured by value are const-qualified in the lambda body. In your code, you are trying to invoke std::function with a non-const pointer to int initialized from the captured array, which is const.

To fix this you need to mark your lambda as mutable so that the generated operator() is no longer const-qualified:

auto lambda = [A](const std::function<void(int *A, int n)> &sorting_alg) mutable {
    ...
}


问:
Amcharts - Change value axis properties dynamically
I have a StackedBarChart which shows serveral values per day. Now i want to switch the view from absolute values to relative values. Therefore i need to change the valueAxis properties like </p>

```<code>valueAxis.min = 0;
valueAxis.max = 100;
valueAxis.strictMinMax = true;
valueAxis.calculateTotals = true;
valueAxis.renderer.minWidth = 50;
</code>```

<p>But how can i get the valueAxis from an existing chart object? </p>

答:
You can access your axis object by accessing it from the xAxes or yAxes list, depending on where you assigned the object to, and use getIndex or loop through them using each if you have multiple axes you want to update.

```<code>// assuming you have one value axis on the y axis:
var valueAxis = chart.yAxes.getIndex(0);
// make updates to the variable

// if you have multiple value axes:
chart.yAxes.each(function(valueAxis) {
  // make changes to each axis object
});
</code>```

Body:
I have a StackedBarChart which shows serveral values per day. Now i want to switch the view from absolute values to relative values. Therefore i need to change the valueAxis properties like

valueAxis.min = 0;
valueAxis.max = 100;
valueAxis.strictMinMax = true;
valueAxis.calculateTotals = true;
valueAxis.renderer.minWidth = 50;

But how can i get the valueAxis from an existing chart object?

Body:
You can access your axis object by accessing it from the xAxes or yAxes list, depending on where you assigned the object to, and use getIndex or loop through them using each if you have multiple axes you want to update.

// assuming you have one value axis on the y axis:
var valueAxis = chart.yAxes.getIndex(0);
// make updates to the variable

// if you have multiple value axes:
chart.yAxes.each(function(valueAxis) {
  // make changes to each axis object
});


问:
Get Value on a Window with GridPanel using ExtJS
I have a situation here: I have a form field with trigger xtype, what I want to happen on my trigger function is to open a window with a list or grid of data in it. I want to get the value of those data and assign it as the value of my form field with trigger. Can anyone help me solve this problem. Thank you very much.</p>

答:
You have multiple solutions for this.

You can make use Saki's simple message bus to do the communication between extjs components.

You can create an custom event for your trigger field. When user selects a record in your window, fire the event with the selected record.

Inside your onTriggerClick :

Display your window with grid / view for user selection

Inside your Window (on some submit button):

```<code> onSubmitClick: function(){
    // Get the selected record & fire event
    var selected = grid.getSelectionModel().getSelected();
    triggerFieldObject.fireEvent('recordSelect',selected);
}
</code>```

Inside your event processing (Will be on TriggerField):

```<code>onRecordSelect: function(record) {

    // Now you have access to the selected record.. process it,
    // Set the trigger field value etc
    this.setValue('Your Value for Trigger Field');
}
</code>```

Note: This is a skeleton code and not a complete solution. You will need to add your code according to your requirements.

Body:
You have multiple solutions for this.

You can make use Saki's simple message bus to do the communication between extjs components.

You can create an custom event for your trigger field. When user selects a record in your window, fire the event with the selected record.

Inside your onTriggerClick :

Display your window with grid / view for user selection

Inside your Window (on some submit button):

 onSubmitClick: function(){
    // Get the selected record & fire event
    var selected = grid.getSelectionModel().getSelected();
    triggerFieldObject.fireEvent('recordSelect',selected);
}

Inside your event processing (Will be on TriggerField):

onRecordSelect: function(record) {

    // Now you have access to the selected record.. process it,
    // Set the trigger field value etc
    this.setValue('Your Value for Trigger Field');
}

Note: This is a skeleton code and not a complete solution. You will need to add your code according to your requirements.


问:
Unhandled promise rejection: Zone.js has detected that ZoneAwarePromise : Angular
Application works like a charm with Chrome. But with edge and Firefox its throwing this error

```<code>Error: "Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.
Most likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise
api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)"
</code>```

I found similar questions here but solution was changing the order of core.js and zone.js imports.
I don't have core.js imports in my application.

In polyfill.js I have import 'zone.js/dist/zone' nothing else.

package.json

{
  "name": "DFS_Poc",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@salesforce-ux/design-system": "^2.11.1",
    "angular-in-memory-web-api": "^0.9.0",
    "chart.js": "^2.9.3",
    "core-js": "^3.1.2",
    "dataframe-js": "^1.4.3",
    "hammerjs": "^2.0.8",
    "ng2-charts": "^2.2.3",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.0.0",
    "vis": "^4.21.0-EOL",
    "zone.js": "^0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^6.0.118",
    "@types/vis": "^4.21.19",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.9.1",
    "typescript": "~3.4.5"
  }
}```
</div>
</div>
</p>

<p>tsconfig.json</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "ES6",
    "downlevelIteration": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "ES6",
      "dom",
      "dom.iterable"
    ]
  }
}</code>```

答: Moving import 'zone.js/dist/zone'; statement from polyfill.js to main.js fixed the issue.

Body:
Application works like a charm with Chrome. But with edge and Firefox its throwing this error

Error: "Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.
Most likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise
api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)"

I found similar questions here but solution was changing the order of core.js and zone.js imports.
I don't have core.js imports in my application.

In polyfill.js I have import 'zone.js/dist/zone' nothing else.

package.json

{
  "name": "DFS_Poc",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build --prod",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^8.0.0",
    "@angular/cdk": "^8.0.0",
    "@angular/common": "^8.0.0",
    "@angular/compiler": "^8.0.0",
    "@angular/core": "^8.0.0",
    "@angular/flex-layout": "^8.0.0-beta.26",
    "@angular/forms": "^8.0.0",
    "@angular/material": "^8.0.0",
    "@angular/platform-browser": "^8.0.0",
    "@angular/platform-browser-dynamic": "^8.0.0",
    "@angular/router": "^8.0.0",
    "@salesforce-ux/design-system": "^2.11.1",
    "angular-in-memory-web-api": "^0.9.0",
    "chart.js": "^2.9.3",
    "core-js": "^3.1.2",
    "dataframe-js": "^1.4.3",
    "hammerjs": "^2.0.8",
    "ng2-charts": "^2.2.3",
    "rxjs": "^6.0.0",
    "rxjs-compat": "^6.0.0",
    "vis": "^4.21.0-EOL",
    "zone.js": "^0.9.1"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "~0.800.0",
    "@angular/cli": "^8.0.0",
    "@angular/compiler-cli": "^8.0.0",
    "@angular/language-service": "^8.0.0",
    "@types/jasmine": "~2.8.3",
    "@types/jasminewd2": "~2.0.2",
    "@types/node": "^6.0.118",
    "@types/vis": "^4.21.19",
    "codelyzer": "^4.0.1",
    "jasmine-core": "~2.8.0",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~2.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "~1.0.1",
    "karma-coverage-istanbul-reporter": "^1.2.1",
    "karma-jasmine": "~1.1.0",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.1.2",
    "ts-node": "~3.2.0",
    "tslint": "~5.9.1",
    "typescript": "~3.4.5"
  }
}

tsconfig.json

{
  "compileOnSave": false,
  "compilerOptions": {
    "outDir": "./dist/out-tsc",
    "sourceMap": true,
    "declaration": false,
    "moduleResolution": "node",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "ES6",
    "downlevelIteration": true,
    "typeRoots": [
      "node_modules/@types"
    ],
    "lib": [
      "ES6",
      "dom",
      "dom.iterable"
    ]
  }
}


问:
http status code for an expired link?
guys which is the correct status code for a link that expires in a certain amount of time?

I have thought to send a 404 after the expiration but maybe there is a better http status to send.

Example of link:

mysite/dir/062011/file.exe (<- working only within 06-2011)

Thanks

答:
```<code>410 Gone

The requested resource is no longer available at the server and no forwarding
address is known. This condition is expected to be considered permanent.
</code>```

Title: http status code for an expired link?


问:
an error occur when running a c++ script in cygwin
I tryed to run the following code in my cygwin

#include<iostream>
#include<cstdio>
using namespace std;
const int NR=2005;
int n,m;
bool arr[NR][NR];
int mx_jx(int x){
    int up[NR][NR],lf[NR][NR],rt[NR][NR];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            up[i][j]=1,lf[i][j]=rt[i][j]=j;
    for(int i=1;i<=n;i++)
        for(int j=2;j<=m;j++)
            if(arr[i][j-1]==x)lf[i][j]=lf[i][j-1];
    for(int i=1;i<=n;i++)
        for(int j=m-1;j>=1;j--)
            if(arr[i][j+1]==x)rt[i][j]=rt[i][j+1];
    int ans=0;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            if(arr[i][j]!=x)continue;
            if(i>1 && arr[i-1][j]==x){
                up[i][j]=arr[i][j-1]+1;
                lf[i][j]=max(lf[i][j],lf[i-1][j]);
                rt[i][j]=min(rt[i][j],rt[i-1][j]);
            }
            ans=max(ans,(rt[i][j]-lf[i][j]+1)*up[i][j]);
        }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            int tmp;
            scanf("%d",&tmp);
            arr[i][j]=(int)tmp;
            if((i+j)&1)arr[i][j]=!arr[i][j];
        }

    printf("%d",max(mx_jx(0),mx_jx(1)));
    return 0;
}
```

<p>It passed the compile(0 warning,0 error), but when I tried to run it with the following input</p>

```4 4
0 1 1 1
1 1 1 0
0 1 1 0
1 1 0 1
```

It says "Command terminated"

these code could run correctly on other platform, how can I solve this problem on cygwin? thanks a lot

答:
The mistake is in that line:

```<code>scanf("%d", &arr[i][j]);
</code>```

%d reads ints, but your array is of type bool. This leads to a memory error.

An easy way to fix it would be:

```<code>int read_value;
scanf("%d", &read_value);
arr[i][j] = read_value;
</code>```

As an additional hint: If you enable compiler warnings (-Wall -Wextra -pedantic), the compiler will tell you about those kinds of mistakes.

Body:
I tryed to run the following code in my cygwin

#include<iostream>
#include<cstdio>
using namespace std;
const int NR=2005;
int n,m;
bool arr[NR][NR];
int mx_jx(int x){
    int up[NR][NR],lf[NR][NR],rt[NR][NR];
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            up[i][j]=1,lf[i][j]=rt[i][j]=j;
    for(int i=1;i<=n;i++)
        for(int j=2;j<=m;j++)
            if(arr[i][j-1]==x)lf[i][j]=lf[i][j-1];
    for(int i=1;i<=n;i++)
        for(int j=m-1;j>=1;j--)
            if(arr[i][j+1]==x)rt[i][j]=rt[i][j+1];
    int ans=0;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            if(arr[i][j]!=x)continue;
            if(i>1 && arr[i-1][j]==x){
                up[i][j]=arr[i][j-1]+1;
                lf[i][j]=max(lf[i][j],lf[i-1][j]);
                rt[i][j]=min(rt[i][j],rt[i-1][j]);
            }
            ans=max(ans,(rt[i][j]-lf[i][j]+1)*up[i][j]);
        }
    return ans;
}
int main(){
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++){
            int tmp;
            scanf("%d",&tmp);
            arr[i][j]=(int)tmp;
            if((i+j)&1)arr[i][j]=!arr[i][j];
        }

    printf("%d",max(mx_jx(0),mx_jx(1)));
    return 0;
}

It passed the compile(0 warning,0 error), but when I tried to run it with the following input

4 4
0 1 1 1
1 1 1 0
0 1 1 0
1 1 0 1

It says "Command terminated"

these code could run correctly on other platform, how can I solve this problem on cygwin? thanks a lot

Body:
The mistake is in that line:

scanf("%d", &arr[i][j]);

%d reads ints, but your array is of type bool. This leads to a memory error.

An easy way to fix it would be:

int read_value;
scanf("%d", &read_value);
arr[i][j] = read_value;

As an additional hint: If you enable compiler warnings (-Wall -Wextra -pedantic), the compiler will tell you about those kinds of mistakes.