问:
UIPageViewController subviewcontroller can't perform segue on viewDidAppear
I have a UIPageController which contains two subviewcontrollers. On start, I'm trying to perform a segue from SubViewControllerOne to LoginViewController when a user isn't authorized. I have a segue in viewDidAppear like so:

```<code>performSegue(withIdentifier: "authorizeSegue", sender: self);
</code>```

This produces an unsuccessful segue and a warning

```<code>Warning: Attempt to present <Volley.LoginViewController: 0x7f98bd801e00> on <Volley.SubViewControllerOne: 0x7f98bd608400> whose view is not in the window hierarchy!
</code>```

I've done this in the past with ViewControllers and TabBarViewControllers successfully.

When I wrap the segue in a timer, or trigger through an IBAction, the segue works perfectly fine. I believe it has something to do with the PageViewController.

```<code>class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate {

    var subViewControllers = [UIViewController]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.dataSource = self
        self.edgesForExtendedLayout = [];
        // Do any additional setup after loading the view.

        let subViewControllerOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerOne") as! SubViewControllerOne
        let subViewControllerTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerTwo") as! SubViewControllerTwo
        subViewControllers = [yourPodcastViewController, appearancesViewController]
        setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
    }

    required init?(coder: NSCoder) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }
</code>```

The navigation controller and PageViewController

The segue from SubViewControllerOne to LoginViewController

答:
Welp, I've had this issue before when running segues via didSelect on tableviews. The solution is to wrap it in the main thread. Not sure why this is necessary, but it solves my problem.</p>

```<code>DispatchQueue.main.async {
  self.performSegue(withIdentifier: "authorizeSegue", sender: self);
}
</code>```

Body:
I have a UIPageController which contains two subviewcontrollers. On start, I'm trying to perform a segue from SubViewControllerOne to LoginViewController when a user isn't authorized. I have a segue in viewDidAppear like so:

performSegue(withIdentifier: "authorizeSegue", sender: self);

This produces an unsuccessful segue and a warning

Warning: Attempt to present <Volley.LoginViewController: 0x7f98bd801e00> on <Volley.SubViewControllerOne: 0x7f98bd608400> whose view is not in the window hierarchy!

I've done this in the past with ViewControllers and TabBarViewControllers successfully.

When I wrap the segue in a timer, or trigger through an IBAction, the segue works perfectly fine. I believe it has something to do with the PageViewController.

class PageViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate, UIScrollViewDelegate {

    var subViewControllers = [UIViewController]()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.dataSource = self
        self.edgesForExtendedLayout = [];
        // Do any additional setup after loading the view.

        let subViewControllerOne = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerOne") as! SubViewControllerOne
        let subViewControllerTwo = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SubViewControllerTwo") as! SubViewControllerTwo
        subViewControllers = [yourPodcastViewController, appearancesViewController]
        setViewControllers([subViewControllers[0]], direction: .forward, animated: true, completion: nil)
    }

    required init?(coder: NSCoder) {
        super.init(transitionStyle: .scroll, navigationOrientation: .horizontal, options: nil)
    }

The navigation controller and PageViewController

The segue from SubViewControllerOne to LoginViewController

Body:
Welp, I've had this issue before when running segues via didSelect on tableviews. The solution is to wrap it in the main thread. Not sure why this is necessary, but it solves my problem.

DispatchQueue.main.async {
  self.performSegue(withIdentifier: "authorizeSegue", sender: self);
}


来源: stackexchange

问:
Javascript .toLocaleString() not honoring '2-digit'
Original Question:
How do I get the hour/month to respect a '2-digit' formatting.

```<code>const event = new Date(2012, 3, 20, 3, 0, 0);
</code>```

Edit...
Apologies all, I don't use this very often

The real issue is depending on which version of chrome you are on, it respects this formatting differently:

For example:

```<code>new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"
</code>```

答:
this is because you forget to add hour12:false

const myDate = new Date(2012, 3, 20, 3, 0, 0)
  ,   dateOpt = { month: '2-digit', hour: '2-digit', hour12:false }

console.log( myDate.toLocaleString(dateOpt) ); // 20/04/2012 à 03:00:00
// or
console.log( myDate.toLocaleString('en-US',dateOpt) ); // 04, 03```

ContentLicense: CC BY-SA 4.0

Body:
Original Question:
How do I get the hour/month to respect a '2-digit' formatting.

const event = new Date(2012, 3, 20, 3, 0, 0);

Edit...
Apologies all, I don't use this very often

The real issue is depending on which version of chrome you are on, it respects this formatting differently:

For example:

new Date(1561984526000).toLocaleString("ja-JP", {hour: "2-digit"})
// Chrome 80 (and other releases): "08時"
// Chrome 79: "8時"


问:
Python 3 PBKDF2HMACBackend default_backend() equivalent in java
I have a task to rewrite some crypto code from python to java. I'm new in Python. Python sample:

```<code>import default_backend
backend = default_backend()

PBKDF2HMAC(hashes.SHA256(), 32, salt, iterations, backend)
</code>```

As I read here 'backend' is an instance of PBKDF2HMACBackend.

I wrote the next code in Java:

```<code>SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factory.generateSecret(new PBEKeySpec(???.toCharArray(), salt, iterations, 256));
</code>```

In constructor of PBEKeySpec first parameter is password which is equivalent of 'backend' in python code. As I inderstand in python code it defined as default via library. But how I should define this parameter in my java code? Can I use some random value or constant? Or maybe some default_backend() equivalent exist?

UPDATED: full python code to get key:

```<code>PBKDF2HMAC(hashes.SHA256(), 32, salt, iterations, backend).derive("somePassword")
</code>```

答:
In the Python code, the password is passed in the derive method whose call is missing in the posted code, here:

```<code>kdf = PBKDF2HMAC(...)
key = kdf.derive(b'MyPassword')
</code>```

The password doesn't correspond to the backend. The backend provides methods to support operations like encryption, hashing etc. and is described in more detail, here.

Also note that in the Python code SHA256 is used and in the Java code SHA1. Since the Python code is the reference, PBKDF2WithHmacSHA256 must be applied in the Java code.

Body:
I have a task to rewrite some crypto code from python to java. I'm new in Python. Python sample:

import default_backend
backend = default_backend()

PBKDF2HMAC(hashes.SHA256(), 32, salt, iterations, backend)

As I read here 'backend' is an instance of PBKDF2HMACBackend.

I wrote the next code in Java:

SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
SecretKey tmp = factory.generateSecret(new PBEKeySpec(???.toCharArray(), salt, iterations, 256));

In constructor of PBEKeySpec first parameter is password which is equivalent of 'backend' in python code. As I inderstand in python code it defined as default via library. But how I should define this parameter in my java code? Can I use some random value or constant? Or maybe some default_backend() equivalent exist?

UPDATED: full python code to get key:

PBKDF2HMAC(hashes.SHA256(), 32, salt, iterations, backend).derive("somePassword")

Body:
In the Python code, the password is passed in the derive method whose call is missing in the posted code, here:

kdf = PBKDF2HMAC(...)
key = kdf.derive(b'MyPassword')

The password doesn't correspond to the backend. The backend provides methods to support operations like encryption, hashing etc. and is described in more detail, here.

Also note that in the Python code SHA256 is used and in the Java code SHA1. Since the Python code is the reference, PBKDF2WithHmacSHA256 must be applied in the Java code.


问:
Find exact substring in cell using excel formula
I have the string "L5+L6+L7+L10" in a cell, and then I have a column with the values L1, L2, ... , L10 on each cell. I need to know which of those values are contained in the main string but with an exact match.

To solve my problem, I tried the formula =IF(ISNUM(SEARCH(B3;$F$2));"Found";"Not found") and the results I get are shown in this image.

However, this results are incorrect because I need only L5, L6, L7 and L10 to be found, and not L1.

Is there a way to do so only using excel formulas?

答:
For anyone viewing question & open to VBA UDF solution

Post code into a worksheet module

Syntax of formula: =Found( Substring, Search String )

So on the excel sheet: C3 = Found(B3, F2) = Not Found

```<code>Public Function Found(SubString As Range, Within As Range) As String

Dim Arr, i As Long
Arr = Split(Within, "+")

Found = "Not Found"

For i = LBound(Arr) To UBound(Arr)
    If SubString = Arr(i) Then
        Found = "Found"
        Exit For
    End If
Next i

End Function
</code>```

Body:
For anyone viewing question & open to VBA UDF solution

Post code into a worksheet module

Syntax of formula: =Found( Substring, Search String )

So on the excel sheet: C3 = Found(B3, F2) = Not Found

Public Function Found(SubString As Range, Within As Range) As String

Dim Arr, i As Long
Arr = Split(Within, "+")

Found = "Not Found"

For i = LBound(Arr) To UBound(Arr)
    If SubString = Arr(i) Then
        Found = "Found"
        Exit For
    End If
Next i

End Function


问:
Efficiently picking combinations of Integers
Let's say we have a 5x5 matrix, filled with 0s.

```<code>myMatrix <- matrix(rep(0, 25), ncol = 5)
</code>```

Now, let's pick a triplet of integers between 1 and 5.

```<code>triplet <- c(1,2,3)
</code>```

For all combinations of this triplet we now add 1 in the matrix,
with this function:

```<code>addCombinationsToMatrix <- function(.matrix, .triplet){
    indexesToChange <- as.matrix(expand.grid(.triplet, .triplet))
    .matrix[indexesToChange] <- .matrix[indexesToChange] + 1
    .matrix
}
</code>```

Using the function, we go from

```<code>myMatrix

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

to

```<code>myMatrix <- addCombinationsToMatrix(myMatrix, triplet)
myMatrix

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

If we pick another triplet we move on to

```<code>nextTriplet <- 2:4
myMatrix <- addCombinationsToMatrix(myMatrix, nextTriplet)
myMatrix

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

So, row-column combinations represent how often two integers have been shown
together in a triplet: 3 and 4 have been shown together once, 2 and 3 have
been shown together twice.

Question: How can one pick triplets, such that
every combination (1-2, 1-3, 1-4...) was picked at least once
and the number of triplets is minimized.

I'm looking for an algorithm here that picks the next triplet.

Ideally it can be extended to

arbitrarily big matrices (10x10, 100x100 ...)

arbitrarily big vectors (quadruplets, quintuplets, n-tuplets)

an arbitrary number of times a combination must have been picked at least

Example:

```<code>myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 1:3)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 3:5)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(1,4,5))
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(2,4,5))
myMatrix
</code>```

EDIT:
Just to be sure: the answer doesn't have to be R code. It can be some other language as well or even pseudo code.

EDIT 2:
It occured to me now, that there are different ways of measuring efficiency. I actually meant, the algorithm should take as little iterations as possible. The algorithm being fast is also very cool, but not the main goal here.

答:
Great question! This comes up in survey design, where you want a few different versions of the survey that each only contain a subset of the questions, but you want every pair (or t-tuple) of questions to have been asked at least once.

This is called covering design, and is a variant of the classic set cover problem. As you can read in an excellent Mathematics Stack Exchange post on the topic, folks use notation C(v, k, t) indicating the minimum number of k-element subsets you need to draw (k=3 in your case) from a v-element set (v=5 in your case) such that every t-element subset in the entire set (t=2 in your case) is contained within one of your selected subsets. Folks have evaluated this function for many different (v, k, t) tuples; see, for instance, https://ljcr.dmgordon.org/cover/table.html . We can read from that table that C(5, 3, 2) = 4, with the following as one possible design:

```<code>  1  2  3
  1  4  5
  2  3  4
  2  3  5
</code>```

First and foremost, this problem is NP-hard, so all known exact algorithms will scale exponentially in inputs v, k, and t. So while you may be able to solve small instances exactly by enumeration or some more clever exact method (e.g. integer programming), you will likely need to resort to heuristic methods as the problem size gets very large.

One possibility in this direction is lexicographic covering, as proposed in https://arxiv.org/pdf/math/9502238.pdf (you will note that many of the solutions on the site linked above list "lex covering" as the method of construction). Basically you list out all possible k-tuples in lexicographic order:

```<code>123
124
125
134
135
145
234
235
245
345
</code>```

Then you greedily add the k-tuple that covers the most previously uncovered t-tuples, breaking ties using the lexicographic ordering.

Here's how the algorithm works in our case:

At the beginning every 3-tuple covers 3 different 2-tuples, so we add 123 since it is lexicographically earliest.

After doing this, the 2-tuples of 12, 13, and 23 have been covered, while all remaining 2-tuples are not covered. A number of 3-tuples cover 3 more 2-tuples, e.g. 145 and 245. We pick 145, since it is lexicographically first, covering 14, 45, and 15.

Now we have 4 remaining uncovered 2-tuples -- 24, 25, 34, and 35. No 3-tuple covers 3 of these, but several cover 2, e.g. 234 and 345. We select 234 as the lexicographically earliest.

We have two remaining uncovered 2-tuples -- 25 and 35. We select 235 as the only 3-tuple that covers both.

We end up with the exact solution shown above. Importantly, this is just a heuristic method -- it doesn't give any guarantee that 4 is the smallest number of 3-tuples needed to cover all pairs in a set with 5 elements. In this case, a lower bound by Schönheim (a reference is provided in the linked article above) convinces us that, in fact, C(5, 3, 2) cannot be smaller than 4. We conclude that the solution from lexicographic covering is in fact optimal.

You would need a tweak to cover each t-tuple a certain number of times r. One obvious one would just be to repeat each tuple to be covered "r" times, and then run lex covering as usual (so for instance in the first step above each 3-tuple would cover 9 2-tuples with r=3). Of course this remains a heuristic for your overall problem due to the use of lex covering.

Body:
Let's say we have a 5x5 matrix, filled with 0s.

myMatrix <- matrix(rep(0, 25), ncol = 5)

Now, let's pick a triplet of integers between 1 and 5.

triplet <- c(1,2,3)

For all combinations of this triplet we now add 1 in the matrix,
with this function:

addCombinationsToMatrix <- function(.matrix, .triplet){
    indexesToChange <- as.matrix(expand.grid(.triplet, .triplet))
    .matrix[indexesToChange] <- .matrix[indexesToChange] + 1
    .matrix
}

Using the function, we go from

myMatrix

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

to

myMatrix <- addCombinationsToMatrix(myMatrix, triplet)
myMatrix

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

If we pick another triplet we move on to

nextTriplet <- 2:4
myMatrix <- addCombinationsToMatrix(myMatrix, nextTriplet)
myMatrix

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

So, row-column combinations represent how often two integers have been shown
together in a triplet: 3 and 4 have been shown together once, 2 and 3 have
been shown together twice.

Question: How can one pick triplets, such that
every combination (1-2, 1-3, 1-4...) was picked at least once
and the number of triplets is minimized.

I'm looking for an algorithm here that picks the next triplet.

Ideally it can be extended to

arbitrarily big matrices (10x10, 100x100 ...)

arbitrarily big vectors (quadruplets, quintuplets, n-tuplets)

an arbitrary number of times a combination must have been picked at least

Example:

myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 1:3)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, 3:5)
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(1,4,5))
myMatrix
myMatrix <- addCombinationsToMatrix(myMatrix, c(2,4,5))
myMatrix

EDIT:
Just to be sure: the answer doesn't have to be R code. It can be some other language as well or even pseudo code.

EDIT 2:
It occured to me now, that there are different ways of measuring efficiency. I actually meant, the algorithm should take as little iterations as possible. The algorithm being fast is also very cool, but not the main goal here.

Body:
Great question! This comes up in survey design, where you want a few different versions of the survey that each only contain a subset of the questions, but you want every pair (or t-tuple) of questions to have been asked at least once.

This is called covering design, and is a variant of the classic set cover problem. As you can read in an excellent Mathematics Stack Exchange post on the topic, folks use notation C(v, k, t) indicating the minimum number of k-element subsets you need to draw (k=3 in your case) from a v-element set (v=5 in your case) such that every t-element subset in the entire set (t=2 in your case) is contained within one of your selected subsets. Folks have evaluated this function for many different (v, k, t) tuples; see, for instance, https://ljcr.dmgordon.org/cover/table.html . We can read from that table that C(5, 3, 2) = 4, with the following as one possible design:

  1  2  3
  1  4  5
  2  3  4
  2  3  5

First and foremost, this problem is NP-hard, so all known exact algorithms will scale exponentially in inputs v, k, and t. So while you may be able to solve small instances exactly by enumeration or some more clever exact method (e.g. integer programming), you will likely need to resort to heuristic methods as the problem size gets very large.

One possibility in this direction is lexicographic covering, as proposed in https://arxiv.org/pdf/math/9502238.pdf (you will note that many of the solutions on the site linked above list "lex covering" as the method of construction). Basically you list out all possible k-tuples in lexicographic order:

123
124
125
134
135
145
234
235
245
345

Then you greedily add the k-tuple that covers the most previously uncovered t-tuples, breaking ties using the lexicographic ordering.

Here's how the algorithm works in our case:

At the beginning every 3-tuple covers 3 different 2-tuples, so we add 123 since it is lexicographically earliest.

After doing this, the 2-tuples of 12, 13, and 23 have been covered, while all remaining 2-tuples are not covered. A number of 3-tuples cover 3 more 2-tuples, e.g. 145 and 245. We pick 145, since it is lexicographically first, covering 14, 45, and 15.

Now we have 4 remaining uncovered 2-tuples -- 24, 25, 34, and 35. No 3-tuple covers 3 of these, but several cover 2, e.g. 234 and 345. We select 234 as the lexicographically earliest.

We have two remaining uncovered 2-tuples -- 25 and 35. We select 235 as the only 3-tuple that covers both.

We end up with the exact solution shown above. Importantly, this is just a heuristic method -- it doesn't give any guarantee that 4 is the smallest number of 3-tuples needed to cover all pairs in a set with 5 elements. In this case, a lower bound by Schönheim (a reference is provided in the linked article above) convinces us that, in fact, C(5, 3, 2) cannot be smaller than 4. We conclude that the solution from lexicographic covering is in fact optimal.

You would need a tweak to cover each t-tuple a certain number of times r. One obvious one would just be to repeat each tuple to be covered "r" times, and then run lex covering as usual (so for instance in the first step above each 3-tuple would cover 9 2-tuples with r=3). Of course this remains a heuristic for your overall problem due to the use of lex covering.


问:
matlab: how to fill one side of the plot with one color, the remainder with another
Inspired by the old age of empires (picture from here), I would like to create a plot with that splits the pane into two colors at the plotted line. How can this be achieved?

Code:

```<code>separator=randi(100,1,20);
figure; hold on; plot(separator);
%below the separator it should be blue, above red
</code>```

答:
Thank you to @Wolfie who helped me figure it out

```<code>y_max = 100;
separator=randi(y_max,1,20);
figure; hold on; area([separator;y_max-separator]');
</code>```

Body:
Inspired by the old age of empires (picture from here), I would like to create a plot with that splits the pane into two colors at the plotted line. How can this be achieved?

Code:

separator=randi(100,1,20);
figure; hold on; plot(separator);
%below the separator it should be blue, above red

Body:
Thank you to @Wolfie who helped me figure it out

y_max = 100;
separator=randi(y_max,1,20);
figure; hold on; area([separator;y_max-separator]');


问:
Group Table View - loading data
Looking for help on how to properly load the data for a Grouped Table View.  I am using following code to load the data which I think should prepare an array "details" for "cellForRowAtIndexPath". However when I run the program I get the same data for all groups and it happens to be the last row in my data (which is in an NSArray called "Users").  Obviously I am doing something wrong but not sure what... please help.

```<code>// Customize the number of rows in the table view.
</code>```

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

```<code>NSRange aRange;
aRange.length = 9; aRange.location = 16;
NSString *users = [self.Users objectAtIndex: section];
NSString *subtitle = [NSString stringWithString:[users substringWithRange:aRange]];
details = [[NSArray arrayWithObjects:subtitle, subtitle, subtitle, nil] retain];

return [details count];
</code>```

}

The data loading routine is as follows:

```<code>- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
UIImage *cellImage = [UIImage imageNamed:@"world.png"];
cell.imageView.image = cellImage;
cell.textLabel.text = [details objectAtIndex:indexPath.row];
return cell;
</code>```

}

答:
From what you've posted, details array is being reset every time the table views asks its data sources for the number of rows in a section. details is last set when -tableView:numberOfRowsInSection: is last called i.e. for the last section. Once set, the same array provides the data for cell.textLabel.text for all the sections. So you are getting incorrect data.

It would be appropriate to calculate and store all the details arrays in a different array, say detailsArray.

The data can then be accessed them like

    [[detailsArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row]

Another problem with your code is that every time numberOfRowsInSection is called, data is being leaked as details is being reset without the earlier object being released.

ContentLicense: CC BY-SA 3.0

Title: Group Table View - loading data

Body:
Looking for help on how to properly load the data for a Grouped Table View.  I am using following code to load the data which I think should prepare an array "details" for "cellForRowAtIndexPath". However when I run the program I get the same data for all groups and it happens to be the last row in my data (which is in an NSArray called "Users").  Obviously I am doing something wrong but not sure what... please help.

// Customize the number of rows in the table view.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

NSRange aRange;
aRange.length = 9; aRange.location = 16;
NSString *users = [self.Users objectAtIndex: section];
NSString *subtitle = [NSString stringWithString:[users substringWithRange:aRange]];
details = [[NSArray arrayWithObjects:subtitle, subtitle, subtitle, nil] retain];

return [details count];

}

The data loading routine is as follows:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}

// Configure the cell.
UIImage *cellImage = [UIImage imageNamed:@"world.png"];
cell.imageView.image = cellImage;
cell.textLabel.text = [details objectAtIndex:indexPath.row];
return cell;

}


问:
Fastest way to reference a relative file
Assume that you have a relative file reference (using JS for example):

```<code>const db = require('../../models/index');
</code>```

In large projects, it's cumbersome to locate the relative paths of necessary dependencies. Is there either a sublime text plugin or a preferred way to reference relative dependencies without manually figuring out the path?

答:
Since you're not using babel, I'd probably go with something like this:

```<code>const $path = require('path');
const rxTilde = /^~\/?/;
const rxDollar = /^\$(\w+)\/(.*)/;

global.requirex = path => {
  let finalPath = path; // default to entered path
  const rpath = $path.dirname(require.main.filename); // get path of main/root module
  if (rxTilde.test(path)) finalPath = $path.join(rpath, path.replace(rxTilde, '')); // use ~ tilde as "rooted" path
  else if (rxDollar.test(path)) { // use $name for special aliases
    const [, dpath, endPath] = rxDollar.exec(path);
    if (dpath === 'asdf') finalPath = $path.join(rpath, 'my/special/path', endPath);
  }
  // console.log(finalPath);
  return require(finalPath);
};

// run from directory: /home/user/www/test/
const a1 = requirex('~/my/path/to/module');
//>> /home/user/www/test/my/path/to/module
const a2 = requirex('$asdf/other-module');
//>> /home/user/www/test/my/special/path/other-module
</code>```

Regular paths that don't have specially handled aliases should just "fall through" to the regular require without modification.

Also I wouldn't want to override the built in require, which is why I created a global requirex instead. In theory you could probably override, but...yikes.

Body:
Assume that you have a relative file reference (using JS for example):

const db = require('../../models/index');

In large projects, it's cumbersome to locate the relative paths of necessary dependencies. Is there either a sublime text plugin or a preferred way to reference relative dependencies without manually figuring out the path?

Body:
Since you're not using babel, I'd probably go with something like this:

const $path = require('path');
const rxTilde = /^~\/?/;
const rxDollar = /^\$(\w+)\/(.*)/;

global.requirex = path => {
  let finalPath = path; // default to entered path
  const rpath = $path.dirname(require.main.filename); // get path of main/root module
  if (rxTilde.test(path)) finalPath = $path.join(rpath, path.replace(rxTilde, '')); // use ~ tilde as "rooted" path
  else if (rxDollar.test(path)) { // use $name for special aliases
    const [, dpath, endPath] = rxDollar.exec(path);
    if (dpath === 'asdf') finalPath = $path.join(rpath, 'my/special/path', endPath);
  }
  // console.log(finalPath);
  return require(finalPath);
};

// run from directory: /home/user/www/test/
const a1 = requirex('~/my/path/to/module');
//>> /home/user/www/test/my/path/to/module
const a2 = requirex('$asdf/other-module');
//>> /home/user/www/test/my/special/path/other-module

Regular paths that don't have specially handled aliases should just "fall through" to the regular require without modification.

Also I wouldn't want to override the built in require, which is why I created a global requirex instead. In theory you could probably override, but...yikes.


问:
Kotlin - Array of object (no null)
I'm coding in kotlin, and i have a problem with the Arrays

I would make a function that return an Array of Car (for example), but that array is build by data from file

Exemple :

```<code>fun buildAllCar(data:string) : Array<Car> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array.requireNoNulls()
}
</code>```

Without the requireNoNulls() , the type of object returned is Array of Car?
Use this method is the only way to get an Array of Car or there is a other way?

Thanks for your help

答:
You can initialize an array in Kotlin using a mapper function like so

```<code>val array = Array(size, mapper function)
</code>```

So to construct an Array of non-nullable Car

```<code>fun buildAllCar(data: String): Array<Car> = Array(5) { buildACarByData(data) }
</code>```

Title: Kotlin - Array of object (no null)

Body:
I'm coding in kotlin, and i have a problem with the Arrays

I would make a function that return an Array of Car (for example), but that array is build by data from file

Exemple :

fun buildAllCar(data:string) : Array<Car> {
    val array = arrayOfNulls<Location>(5) //In the real code, the size is retrieved by an other item

    for(i in array.indices){
        array[i] = buildACarByData(data); //Just so you could see a sample usage
    }

    return array.requireNoNulls()
}

Without the requireNoNulls() , the type of object returned is Array of Car?
Use this method is the only way to get an Array of Car or there is a other way?

Thanks for your help

Body:
You can initialize an array in Kotlin using a mapper function like so

val array = Array(size, mapper function)

So to construct an Array of non-nullable Car

fun buildAllCar(data: String): Array<Car> = Array(5) { buildACarByData(data) }


问:
awk is only matching the first line when matching against first column
With the following file debug.txt:

```<code>a,b,1
a,b,2
a,b,3
a,b,4
a,b,5
</code>```

This prints the third column of only the first row:

```<code>$ awk -F ',' '$1 == "a" {print($3)}' debug.txt
1
</code>```

while this prints the third column of all 5 rows:

```<code>$ awk -F ',' '$2 == "b" {print($3)}' debug.txt
1
2
3
4
5
</code>```

Why is this? And how would I select all rows where the first column matches a?

EDIT:
Here is the binary output of debug.txt:

```<code>$ cat -v debug.txt
a,b,1
^Ma,b,2
^Ma,b,3
^Ma,b,4
^Ma,b,5
</code>```

```<code>$ hexdump -Cv debug.txt
00000000  61 2c 62 2c 31 0a 0d 61  2c 62 2c 32 0a 0d 61 2c  |a,b,1..a,b,2..a,|
00000010  62 2c 33 0a 0d 61 2c 62  2c 34 0a 0d 61 2c 62 2c  |b,3..a,b,4..a,b,|
00000020  35                                                |5|
00000021
</code>```

```<code>$ file debug.txt
debug.txt: ASCII text, with CR, LF line terminators
</code>```

Note that 5 is the last character in the file (no trailing newline).

答:
TL;DR:

A trailing carriage return character (CR or \r) is causing awk to match ^Ma for the first column, causing $1 == "a" to be false on all but the first line.

Explanation

What is happening is that debug.txt has some bizarre newlines. At the end of each line is this sequence: 0x0a0d (which shows as a newline and then a ^M with cat -v debug.txt).

The Wikipedia article for newline indicates that Unix/Linux newlines are just 0xa (\n or LF), while Windows newlines are 0x0d0a (\r\n or CRLF). Somehow, debug.txt has 'backwards' Windows newlines - 0x0a0d (\n\r or LFCR). This is the cause of all the trouble.

awk is smart enough to handle a regular Windows newline when it sees CRLF. However, when it sees LFCR at the end of the first line, it assumes it's a regular Unix newline followed by a stand-alone carriage return.

Since the CR is now on the next line, when awk delimits the first column of the next line, it correctly sees it as ^Ma instead of a. So $1 == "a" evaluates to "^Ma" == "a", which is false. So all the lines except the first line get ignored.

Examples

The following files have the same contents as debug.txt except that the lines end with 0x0a0d (LF + CR), 0x0d0a (CR + LF), and 0xa (LF), respectively (debug.txt and debug-lfcr.txt are the same):

```<code>$ cat -v debug-lfcr.txt
a,b,1
^Ma,b,2
^Ma,b,3
^Ma,b,4
^Ma,b,5
</code>```
```<code>$ awk -F ',' '($1 == "a") {print($3)}' debug-lfcr.txt
1
</code>```
```<code>$ cat -v debug-crlf.txt
a,b,1^M
a,b,2^M
a,b,3^M
a,b,4^M
a,b,5
</code>```
```<code>$ awk -F ',' '($1 == "a") {print($3)}' debug-crlf.txt
1
2
3
4
5
</code>```
```<code>$ cat -v debug-lf.txt
a,b,1
a,b,2
a,b,3
a,b,4
a,b,5
</code>```
```<code>$ awk -F ',' '($1 == "a") {print($3)}' debug-lf.txt
1
2
3
4
5
</code>```

How to fix the files

So the solution is to replace all LFCR sequences with either CRLF or LF.

To convert to just LF from LFCR, strip away all the CRs:

```<code>tr -d '\r' < debug.txt > debug-cured.txt
</code>```

To convert to CRLF from LFCR, strip away the CRs and add them back in to the end of each line:

```<code>tr -d '\r' < debug.txt | sed -e '$a\' | sed 's/$/\r/' > debug-cured.txt

</code>```

(| sed -e '$a\'  is optional - it merely adds a newline to the end of the file if it doesn't already. This avoids ending the file with a stand-alone CR, which could cause problems later).

See Remove carriage return in Unix, Add text at the end of each line, and https://unix.stackexchange.com/questions/31947/how-to-add-a-newline-to-the-end-of-a-file.

Aside

The reason why there were LFCR newlines is that I was dealing with software that was outputting text to both a virtual console and a hardware UART. This specific software's print function would detect an LF in the text and inject a CR afterwards. A hardware UART needs both LF and CR, but the order doesn't matter. So the software opted for LFCR, since it's a slightly faster implementation than CRLF.

Body:
With the following file debug.txt:

a,b,1
a,b,2
a,b,3
a,b,4
a,b,5

This prints the third column of only the first row:

$ awk -F ',' '$1 == "a" {print($3)}' debug.txt
1

while this prints the third column of all 5 rows:

$ awk -F ',' '$2 == "b" {print($3)}' debug.txt
1
2
3
4
5

Why is this? And how would I select all rows where the first column matches a?

EDIT:
Here is the binary output of debug.txt:

$ cat -v debug.txt
a,b,1
^Ma,b,2
^Ma,b,3
^Ma,b,4
^Ma,b,5

$ hexdump -Cv debug.txt
00000000  61 2c 62 2c 31 0a 0d 61  2c 62 2c 32 0a 0d 61 2c  |a,b,1..a,b,2..a,|
00000010  62 2c 33 0a 0d 61 2c 62  2c 34 0a 0d 61 2c 62 2c  |b,3..a,b,4..a,b,|
00000020  35                                                |5|
00000021

$ file debug.txt
debug.txt: ASCII text, with CR, LF line terminators

Note that 5 is the last character in the file (no trailing newline).

Body:
TL;DR:

A trailing carriage return character (CR or \r) is causing awk to match ^Ma for the first column, causing $1 == "a" to be false on all but the first line.

Explanation

What is happening is that debug.txt has some bizarre newlines. At the end of each line is this sequence: 0x0a0d (which shows as a newline and then a ^M with cat -v debug.txt).

The Wikipedia article for newline indicates that Unix/Linux newlines are just 0xa (\n or LF), while Windows newlines are 0x0d0a (\r\n or CRLF). Somehow, debug.txt has 'backwards' Windows newlines - 0x0a0d (\n\r or LFCR). This is the cause of all the trouble.

awk is smart enough to handle a regular Windows newline when it sees CRLF. However, when it sees LFCR at the end of the first line, it assumes it's a regular Unix newline followed by a stand-alone carriage return.

Since the CR is now on the next line, when awk delimits the first column of the next line, it correctly sees it as ^Ma instead of a. So $1 == "a" evaluates to "^Ma" == "a", which is false. So all the lines except the first line get ignored.

Examples

The following files have the same contents as debug.txt except that the lines end with 0x0a0d (LF + CR), 0x0d0a (CR + LF), and 0xa (LF), respectively (debug.txt and debug-lfcr.txt are the same):

$ cat -v debug-lfcr.txt
a,b,1
^Ma,b,2
^Ma,b,3
^Ma,b,4
^Ma,b,5

$ awk -F ',' '($1 == "a") {print($3)}' debug-lfcr.txt
1

$ cat -v debug-crlf.txt
a,b,1^M
a,b,2^M
a,b,3^M
a,b,4^M
a,b,5

$ awk -F ',' '($1 == "a") {print($3)}' debug-crlf.txt
1
2
3
4
5

$ cat -v debug-lf.txt
a,b,1
a,b,2
a,b,3
a,b,4
a,b,5

$ awk -F ',' '($1 == "a") {print($3)}' debug-lf.txt
1
2
3
4
5

How to fix the files

So the solution is to replace all LFCR sequences with either CRLF or LF.

To convert to just LF from LFCR, strip away all the CRs:

tr -d '\r' < debug.txt > debug-cured.txt

To convert to CRLF from LFCR, strip away the CRs and add them back in to the end of each line:

tr -d '\r' < debug.txt | sed -e '$a\' | sed 's/$/\r/' > debug-cured.txt

(| sed -e '$a\'  is optional - it merely adds a newline to the end of the file if it doesn't already. This avoids ending the file with a stand-alone CR, which could cause problems later).

See Remove carriage return in Unix, Add text at the end of each line, and https://unix.stackexchange.com/questions/31947/how-to-add-a-newline-to-the-end-of-a-file.

Aside

The reason why there were LFCR newlines is that I was dealing with software that was outputting text to both a virtual console and a hardware UART. This specific software's print function would detect an LF in the text and inject a CR afterwards. A hardware UART needs both LF and CR, but the order doesn't matter. So the software opted for LFCR, since it's a slightly faster implementation than CRLF.


问:
Add background image and border image to form
I have a simple form based on jquery -

```<code><center>
    <form id="form1">
    <div id="registerDiv" data-role="fieldcontain" >
     <input type="button" value="Register" id="registerButton" data-inline="true"/>
    </div>
    </form>
  </center>
</code>```

Id like to modify the form so that it has two background images, one background covers the button (number 1 in attachment - layout.png), the second is a background image that act as a border(number 2 in attachment - layout.png). What is the best method of achieving this ?

Thanks

答:
CSS:

```<code><style type="text/css">
  .outer {background:url(layout-outer.png);padding:12px}
  .inner {background:url(layout-inner.png);padding:12px}
</style>
</code>```

HTML:

```<code><div class="outer">
  <form id="form1">
    <div class="inner">
      <!-- other input items as necessary -->
      <input type="button" value="register" id="registerButton" data-inline="true" />
    </div>
  </form>
</div>
</code>```

The key part here is the amount of padding in '.outer'.  This is basically your border width.

Body:
I have a simple form based on jquery -

    <form id="form1">

     <input type="button" value="Register" id="registerButton" data-inline="true"/>

    </form>

Id like to modify the form so that it has two background images, one background covers the button (number 1 in attachment - layout.png), the second is a background image that act as a border(number 2 in attachment - layout.png). What is the best method of achieving this ?

Thanks

Body:
CSS:

<style type="text/css">
  .outer {background:url(layout-outer.png);padding:12px}
  .inner {background:url(layout-inner.png);padding:12px}
</style>

HTML:

<div class="outer">
  <form id="form1">
    <div class="inner">
      <!-- other input items as necessary -->
      <input type="button" value="register" id="registerButton" data-inline="true" />
    </div>
  </form>
</div>

The key part here is the amount of padding in '.outer'.  This is basically your border width.


问:
How do I make my electron app behave like a mobile device
For example, visiting instagram.com/direct/inbox/ gives a 404 error but when you turn on dev tools's "device toolbar" and select a mobile device, instagram shows me the DMs page.

I am trying to do this in a small electron app and I've already tried setting the user agent to an ipad/samsung one but instagram still detects its not a real device and still redirects me to the home page.

This is my code:

const {app, BrowserWindow, session} = require('electron')
const path = require('path')

function createWindow () {

  const mainWindow = new BrowserWindow({
    width: 400,
    height: 850,
  })

  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Mobile Safari/537.36';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });

  mainWindow.loadURL('https://instagram.com/direct/inbox')

}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})
```

Am I missing something?

答:
Read documentation webContents method https://www.electronjs.org/docs/api/web-contents

Try, its worked me

```<code>  mainWindow = new BrowserWindow({width: 412, height: 732, title: 'Instagram Desktop'})

  // and load the index.html of the app.
  mainWindow.webContents.setUserAgent("Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko; googleweblight) Chrome/38.0.1025.166 Mobile Safari/535.19");
  mainWindow.loadURL('https://instagram.com/direct/inbox')
</code>```

Founded from https://github.com/azishapidin/instagram-electron/blob/master/main.js

Body:
For example, visiting instagram.com/direct/inbox/ gives a 404 error but when you turn on dev tools's "device toolbar" and select a mobile device, instagram shows me the DMs page.

I am trying to do this in a small electron app and I've already tried setting the user agent to an ipad/samsung one but instagram still detects its not a real device and still redirects me to the home page.

This is my code:

const {app, BrowserWindow, session} = require('electron')
const path = require('path')

function createWindow () {

  const mainWindow = new BrowserWindow({
    width: 400,
    height: 850,
  })

  session.defaultSession.webRequest.onBeforeSendHeaders((details, callback) => {
    details.requestHeaders['User-Agent'] = 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Mobile Safari/537.36';
    callback({ cancel: false, requestHeaders: details.requestHeaders });
  });

  mainWindow.loadURL('https://instagram.com/direct/inbox')

}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  if (BrowserWindow.getAllWindows().length === 0) createWindow()
})

Am I missing something?

Body:
Read documentation webContents method https://www.electronjs.org/docs/api/web-contents

Try, its worked me

  mainWindow = new BrowserWindow({width: 412, height: 732, title: 'Instagram Desktop'})

  // and load the index.html of the app.
  mainWindow.webContents.setUserAgent("Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 5 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko; googleweblight) Chrome/38.0.1025.166 Mobile Safari/535.19");
  mainWindow.loadURL('https://instagram.com/direct/inbox')

Founded from https://github.com/azishapidin/instagram-electron/blob/master/main.js


问:
How to show javax.faces.context.FacesContext exception message inside an alert
I have a menu item which calls a method. When it fails, I want the ajax call shows a alert with the exception message.

menu.xhtml

```<code><rich:panelMenuItem
    id="test"
    name="test"
    label="Ajax call"
    mode="ajax">
    <a4j:ajax
        event="select"
        onerror="alert('error: #{facesContext.messageList[0]}');"
        oncomplete="alert('Success!');"
        listener="#{menuMB.someMethod()}">
    </a4j:ajax>
</rich:panelMenuItem>
</code>```

MenuMB.java

```<code>public void someMethod() throws IOException {
    try {
        // method call which may fail
    } catch (Exception e) {
        FacesContext context = FacesContext.getCurrentInstance();

        FacesMessage mensagem = new FacesMessage(FacesMessage.SEVERITY_ERROR, null, e.getMessage());
        context.addMessage(null, mensagem);

        context.getExternalContext().responseSendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
        context.responseComplete();
    }
}
</code>```

When clicking the menu option:

1) If method call succeeds, it shows an alert with the message "Success!"

2) If method call fails, it shows an alert only with the message "error:". How to show the exception message?

If I don't handle exceptions on method call, the alert of oncomplete event will always be exibited, even when method call fails.

Based on Makhiel's answer, I noticed I was going in the wrong direction. So I did this:

MenuMB:

```<code>private String resultMessage;

public void someMethod() {
    resultMessage = "Any success message";

    try {
        // method call which may fail
    } catch (Exception e) {
        resultMessage = e.getMessage();
    }
}

public String getResultMessage() {
    return resultMessage;
}
</code>```

menu.xhtml

```<code><a4j:ajax
    event="select"
    oncomplete="alert('#{menuMB.resultMessage}');"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>
</code>```

答:
onerror is intended for handling errors in the AJAX request/response loop; a method failing in some way is generally not a good reason to abort and send an error

If you still want to do it this way onerror has access to a variable named event that contains the response. You will not have access to the FacesMessages.

Otherwise just make a flag for the operation result and use oncomplete to handle it

```<code><a4j:ajax
    event="select"
    data="#{menuMB.operationFailed}"
    oncomplete="handle(event.data)"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>
</code>```

The JS code for the handle method needs to be rerendered to show the message.

Body:
I have a menu item which calls a method. When it fails, I want the ajax call shows a alert with the exception message.

menu.xhtml

<rich:panelMenuItem
    id="test"
    name="test"
    label="Ajax call"
    mode="ajax">
    <a4j:ajax
        event="select"
        onerror="alert('error: #{facesContext.messageList[0]}');"
        oncomplete="alert('Success!');"
        listener="#{menuMB.someMethod()}">
    </a4j:ajax>
</rich:panelMenuItem>

MenuMB.java

public void someMethod() throws IOException {
    try {
        // method call which may fail
    } catch (Exception e) {
        FacesContext context = FacesContext.getCurrentInstance();

        FacesMessage mensagem = new FacesMessage(FacesMessage.SEVERITY_ERROR, null, e.getMessage());
        context.addMessage(null, mensagem);

        context.getExternalContext().responseSendError(HttpServletResponse.SC_PRECONDITION_FAILED, e.getMessage());
        context.responseComplete();
    }
}

When clicking the menu option:

1) If method call succeeds, it shows an alert with the message "Success!"

2) If method call fails, it shows an alert only with the message "error:". How to show the exception message?

If I don't handle exceptions on method call, the alert of oncomplete event will always be exibited, even when method call fails.

Based on Makhiel's answer, I noticed I was going in the wrong direction. So I did this:

MenuMB:

private String resultMessage;

public void someMethod() {
    resultMessage = "Any success message";

    try {
        // method call which may fail
    } catch (Exception e) {
        resultMessage = e.getMessage();
    }
}

public String getResultMessage() {
    return resultMessage;
}

menu.xhtml

<a4j:ajax
    event="select"
    oncomplete="alert('#{menuMB.resultMessage}');"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>

Body:
onerror is intended for handling errors in the AJAX request/response loop; a method failing in some way is generally not a good reason to abort and send an error

If you still want to do it this way onerror has access to a variable named event that contains the response. You will not have access to the FacesMessages.

Otherwise just make a flag for the operation result and use oncomplete to handle it

<a4j:ajax
    event="select"
    data="#{menuMB.operationFailed}"
    oncomplete="handle(event.data)"
    listener="#{menuMB.someMethod()}">
</a4j:ajax>

The JS code for the handle method needs to be rerendered to show the message.


问:
How to store each JSON data with restsharper in c#?
I need to get the values from the JSON response, I've tried to do the following but the messagebox shows empty in the Project class.

I've tried to Google my problem (also restsharp tutorials) but until now I wasn't able to fix the problem that I'm having. I've gotten clues here and there online and this is how far I've gotten over the last few days.

The result I am expecting is that each value from the API goes into the variable, which I can then grab per value. I don't want the plain JSON content.

Api Class

```<code>private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();
    Project output = deserialize.Deserialize<Project>(response);

    Project project = new Project();
    project.check();
}
</code>```

Project Class

```<code>class Project
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Slug { get; set; }
    public string Description { get; set; }
    public string Deadline { get; set; }
    public int User_id { get; set; }
    public string Created_at { get; set; }
    public string Updated_at { get; set; }

    public void check()
    {
        MessageBox.Show(Title);
    }
}
</code>```

JSON Code

```<code>{
    "projects": [
        {
            "id": 29,
            "title": "a_project",
            "slug": "a_project",
            "description": "f",
            "deadline": "2020-04-08 00:00:00",
            "user_id": 19,
            "created_at": "2020-02-11 16:59:45",
            "updated_at": "2020-02-11 16:59:45"
        }
    ]
}
</code>```

Github link: https://github.com/s1129092/n212/blob/master/WpfApp1/MainWindow.xaml.cs

答:
It appears that you're deserializing an object with one property containing an array of Project objects into a Project class object. Your JSON example shows the root object's property projects containing an array of objects, so you'll want to match that in your class design for your deserialization to implicitly work:

```<code>class ProjectList
{
    public Project[] Projects { get; set; }
}
</code>```

Then deserialize your response to the new ProjectList class:

```<code>ProjectList output = deserialize.Deserialize<ProjectList>(response);
</code>```

Then you can iterate through the output.Projects array to find your project objects.

Your Submit_Button_Click method could now work like this:

```<code>private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();

    ProjectList output = deserialize.Deserialize<ProjectList>(response);

    Project firstProjectInResponse = output.Projects[0];
    firstProjectInResponse.check();
}
</code>```

Body:
I need to get the values from the JSON response, I've tried to do the following but the messagebox shows empty in the Project class.

I've tried to Google my problem (also restsharp tutorials) but until now I wasn't able to fix the problem that I'm having. I've gotten clues here and there online and this is how far I've gotten over the last few days.

The result I am expecting is that each value from the API goes into the variable, which I can then grab per value. I don't want the plain JSON content.

Api Class

private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();
    Project output = deserialize.Deserialize<Project>(response);

    Project project = new Project();
    project.check();
}

Project Class

class Project
{
    public int Id { get; set; }
    public string Title { get; set; }
    public string Slug { get; set; }
    public string Description { get; set; }
    public string Deadline { get; set; }
    public int User_id { get; set; }
    public string Created_at { get; set; }
    public string Updated_at { get; set; }

    public void check()
    {
        MessageBox.Show(Title);
    }
}

JSON Code

{
    "projects": [
        {
            "id": 29,
            "title": "a_project",
            "slug": "a_project",
            "description": "f",
            "deadline": "2020-04-08 00:00:00",
            "user_id": 19,
            "created_at": "2020-02-11 16:59:45",
            "updated_at": "2020-02-11 16:59:45"
        }
    ]
}

Github link: https://github.com/s1129092/n212/blob/master/WpfApp1/MainWindow.xaml.cs

Body:
It appears that you're deserializing an object with one property containing an array of Project objects into a Project class object. Your JSON example shows the root object's property projects containing an array of objects, so you'll want to match that in your class design for your deserialization to implicitly work:

class ProjectList
{
    public Project[] Projects { get; set; }
}

Then deserialize your response to the new ProjectList class:

ProjectList output = deserialize.Deserialize<ProjectList>(response);

Then you can iterate through the output.Projects array to find your project objects.

Your Submit_Button_Click method could now work like this:

private async void Submit_Button_Click(object sender, RoutedEventArgs e)
{
    var client = new RestClient("http://apage.com/");
    var request = new RestRequest("api/project");
    request.Method = Method.GET;

    request.AddHeader("Accept", "application/json");

    client.AddDefaultHeader("Authorization",
        string.Format("Bearer {0}", "token goes here"));

    var response = client.Execute(request);

    var deserialize = new JsonDeserializer();

    ProjectList output = deserialize.Deserialize<ProjectList>(response);

    Project firstProjectInResponse = output.Projects[0];
    firstProjectInResponse.check();
}


问:
How to output an array of different elements in a sequence using Angularjs
I have code that generates a description of an HTML table row, like so:

```<code>  [
    {element: 'th', content: 'Header 1'},
    {element: 'td', content: 'data 1'},
    {element: 'td', content: 'data 2'},
  ]
</code>```

I'd like to output these with angularjs, something like

```<code><tr>
  <td ng-repeat="item in row" >{{item.content}}</td>
</tr>
</code>```

Except I can't figure out how this could handle the element(s) that are supposed to be ?

(Vuejs, for example, has {{item.content}}	 but I'm working in an angularjs app, so this example is given in case it helps Vuejs people understand what I need.)

答:
Thanks to Clint's answer, a variation that works with tables is:

Create a directive that deletes itself (!)

angular.module('theapp').directive('repeatSection', function () {
  return { restrict: 'A', replace: true, link(scope, el) { el.remove(); } };
});
```

<h2>Use <code><td></code> elements to wrap the logic:</h2>

<pre class="lang-html prettyprint-override"><code><table>
 ...
 <tbody>
   <tr ng-repeat="row in rows">

     <td repeat-section ng-repeat-start="cells in row"></td>
     <th ng-if="cell.element === 'th'">{{cell.content}}</th>
     <td ng-if="cell.element === 'td'">{{cell.content}}</td>
     <td repeat-section ng-repeat-end></td>

   </tr>
 </tbody>
</table>
</code>```

the repeat-section directive deletes the td elements that are created as part of the ng-repeat-start.

we need to use  here - if you use
 or <repeat-section> even, these elements get emptied (at least in Firefox), since a
 can only contain  or .

this works for my use (table cells), but is not a general solution - as you'll see I've had to include one of each possible element; that would get messy in the general case.

Body:
I have code that generates a description of an HTML table row, like so:

  [
    {element: 'th', content: 'Header 1'},
    {element: 'td', content: 'data 1'},
    {element: 'td', content: 'data 2'},
  ]

I'd like to output these with angularjs, something like

  {{item.content}}

Except I can't figure out how this could handle the element(s) that are supposed to be ?

(Vuejs, for example, has {{item.content}}	 but I'm working in an angularjs app, so this example is given in case it helps Vuejs people understand what I need.)

Body:
Thanks to Clint's answer, a variation that works with tables is:

Create a directive that deletes itself (!)

angular.module('theapp').directive('repeatSection', function () {
  return { restrict: 'A', replace: true, link(scope, el) { el.remove(); } };
});

Use <td> elements to wrap the logic:

<table>
 ...
 <tbody>
   <tr ng-repeat="row in rows">

     <td repeat-section ng-repeat-start="cells in row"></td>
     <th ng-if="cell.element === 'th'">{{cell.content}}</th>
     <td ng-if="cell.element === 'td'">{{cell.content}}</td>
     <td repeat-section ng-repeat-end></td>

   </tr>
 </tbody>
</table>

the repeat-section directive deletes the td elements that are created as part of the ng-repeat-start.

we need to use <td> here - if you use <div> or <repeat-section> even, these elements get emptied (at least in Firefox), since a <tr> can only contain <td> or <th>.

this works for my use (table cells), but is not a general solution - as you'll see I've had to include one of each possible element; that would get messy in the general case.


答:
Just add the "+" to the beginning and end of the strings inside the search:

```<code>=IF(ISNUMBER(SEARCH("+"&B3&"+","+"&$F$3&"+")),"Found","Not found")
</code>```

Title: Find exact substring in cell using excel formula

Body:
I have the string "L5+L6+L7+L10" in a cell, and then I have a column with the values L1, L2, ... , L10 on each cell. I need to know which of those values are contained in the main string but with an exact match.

To solve my problem, I tried the formula =IF(ISNUM(SEARCH(B3;$F$2));"Found";"Not found") and the results I get are shown in this image.

However, this results are incorrect because I need only L5, L6, L7 and L10 to be found, and not L1.

Is there a way to do so only using excel formulas?

Body:
Just add the "+" to the beginning and end of the strings inside the search:

=IF(ISNUMBER(SEARCH("+"&B3&"+","+"&$F$3&"+")),"Found","Not found")


问:
image border not displaying html email
I am trying to send an html email with an image border as

```<code><p align="center">
    <img src="images/pic1.jpg" width="443" height="148" align="middle"
         style="border: 1px solid grey; padding:10px;" border="1"/>
</p>
</code>```

However, the border just does not display in any of the email clients. How can i fix this?

答:
To be honest your in for a hard time using "p" tags. Tables will 100% be the way to go in this situation. I know I know, tables blow, but for email clients that use word as their html render cough outlook cough and ones like hotmail and gmail running html 1 (this might be a little bit of a strech but its somewhere around there), you never really know how things are going to turn out.

As for an answer to your question, try ```display:block``` on your image. Generally you want to put display:block on all your images as well as heights and width to insure there are no weird gaps between image slices.

Title: image border not displaying html email

Body:
I am trying to send an html email with an image border as

However, the border just does not display in any of the email clients. How can i fix this?

Body:
To be honest your in for a hard time using "p" tags. Tables will 100% be the way to go in this situation. I know I know, tables blow, but for email clients that use word as their html render cough outlook cough and ones like hotmail and gmail running html 1 (this might be a little bit of a strech but its somewhere around there), you never really know how things are going to turn out.

As for an answer to your question, try
display:block
 on your image. Generally you want to put display:block on all your images as well as heights and width to insure there are no weird gaps between image slices.


问:
Extracting values
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value1",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
I think you should do a for loop to go through the Array first.

for (let i = 0; i <= array.length; i++{
}
```

<p>and check in every line, doing something like:</p>

<pre class="lang-js prettyprint-override"><code>if (idExample == array.id[i]){
  return idExample
}
</code>```

Title: Extracting values

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value1",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

Body:
I think you should do a for loop to go through the Array first.

for (let i = 0; i <= array.length; i++{
}

and check in every line, doing something like:

if (idExample == array.id[i]){
  return idExample
}


问:
When running an Async/Await Experiment, operations do not occur in expected order
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

```<code>    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }
</code>```

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test
</code>```

The output I get is

```<code>Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test
</code>```

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

答:
Try changing your code like this:

```<code>var t = await RunningAsync();

_testOutput.WriteLine("In outer method, after calling async method");
</code>```

When you are not awaiting an async method, the outer one will continue running, especially when the inner one is waiting.

Adding the await there will fix the issue.

Body:
I have created an experiment (run in XUnit) to test output. I use three methods - the test method, an asynchronous method that calls await, and an inner Task that sleeps for 5 seconds.

    [Fact]
    public void TestAsyncRunning()
    {
        _testOutput.WriteLine("Beginning Test");
        _testOutput.WriteLine("Calling RunningAsync");

        var t = RunningAsync();

        _testOutput.WriteLine("In outer method, after calling async method");

        t.Wait(); //IOW, Thread.Join();

        _testOutput.WriteLine("Exiting Test");
    }

    private async Task RunningAsync()
    {
        _testOutput.WriteLine("RunningAsync: Enter Method");
        _testOutput.WriteLine("RunningAsync: Calling and awaiting inner running");
        await InnerRunning();
        _testOutput.WriteLine("RunningAsync: Returning");
    }

    private Task InnerRunning()
    {
        _testOutput.WriteLine("InnerRunning: Begin method");
        _testOutput.WriteLine("InnerRunning: Sleeping For 5 seconds");
        var t = Task.Run(() => Thread.Sleep(5000));
        _testOutput.WriteLine("InnerRunning: Wake up and exit");
        return t;
    }

In the following output, the lines with the asterisks is where the unexpected order occurs.

The output I expect is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*In outer method, after calling async method
*InnerRunning: Wake up and exit
RunningAsync: Returning
Exiting Test

The output I get is

Beginning Test
Calling RunningAsync
RunningAsync: Enter Method
RunningAsync: Calling and awaiting inner running
InnerRunning: Begin method
InnerRunning: Sleeping For 5 seconds
*InnerRunning: Wake up and exit
*In outer method, after calling async method
RunningAsync: Returning
Exiting Test

It appears that the async method is actually running async but the method it calls is running synchronously. Does this have to do with the TaskScheduler? I am clearly missing something...….

Body:
Try changing your code like this:

var t = await RunningAsync();

_testOutput.WriteLine("In outer method, after calling async method");

When you are not awaiting an async method, the outer one will continue running, especially when the inner one is waiting.

Adding the await there will fix the issue.


问:
How to pass a CheckedChange Listener to a custom view
I made a custom view with 3 toggle buttons. In my custom view class I set

```<code>public void setMyToggleButton1OnCheckedChangedListener(CompoundButton.OnCheckedChangeListener o) {
    myToggleButton1.setOnCheckedChangeListener(o);
}
</code>```

but when I try to handle this even in my main activity, it looks like this event never been triggered. In the main activity I tried

```<code>myCustomView.setMyToggleButton1OnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //TODO something here
            }
            else {
                //TODO something here
            }
        }
    });
</code>```

I did try my other custom view with regular button and pass the standard button click event to it with the same method. I don't understand what makes it different to pass a standard button click event to custom view and passing a toggle button checkedchange event listener to a custom view.

PS: Here is what I did for regular button and its OnClickListener. This one works as I expected, that's why I try to replicate it to Toggle Button and the OnCheckedChangeListener.

in myCustomView2 (the custom view contains regular buttons)

```<code>public class myCustomView2 extends ConstraintLayout{
    private Button myRegBtn1;
    ...
    public myCustomView2(Context context) {
        this(context, null);
    }

    public myCustomView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
         setAttributes(context, attrs);
    }

    public myCustomView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setAttributes(context, attrs);
        init(context);
    }

    private void init(Context context) {
        myRegBtn = findViewById(R.id.btn1);
        ...
    }

    private void setAttributes(Context context, AttributeSet attrs) {
        ...
    }

    public void setMyRegBtnOnClickListener(OnClickListener o) {
        myRegBtn.setOnClickListener(o);
    }
}
</code>```

In my mainActivity,

```<code>public class myMainActivity extends AppCompatActivity{
    private MyCustomView2 myCustomView2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        myCustomView2.setMyRegBtnOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //TODO: some code execute here when button clicked
            }
        });
    ...
}
</code>```

答:
You need to call your CheckedChangeListener yourself

i.e lister.onCheckedChange(isChecked)

It would work out of the box only if you extend the CheckBox view.

Body:
I made a custom view with 3 toggle buttons. In my custom view class I set

public void setMyToggleButton1OnCheckedChangedListener(CompoundButton.OnCheckedChangeListener o) {
    myToggleButton1.setOnCheckedChangeListener(o);
}

but when I try to handle this even in my main activity, it looks like this event never been triggered. In the main activity I tried

myCustomView.setMyToggleButton1OnCheckedChangedListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                //TODO something here
            }
            else {
                //TODO something here
            }
        }
    });

I did try my other custom view with regular button and pass the standard button click event to it with the same method. I don't understand what makes it different to pass a standard button click event to custom view and passing a toggle button checkedchange event listener to a custom view.

PS: Here is what I did for regular button and its OnClickListener. This one works as I expected, that's why I try to replicate it to Toggle Button and the OnCheckedChangeListener.

in myCustomView2 (the custom view contains regular buttons)

public class myCustomView2 extends ConstraintLayout{
    private Button myRegBtn1;
    ...
    public myCustomView2(Context context) {
        this(context, null);
    }

    public myCustomView2(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
         setAttributes(context, attrs);
    }

    public myCustomView2(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        setAttributes(context, attrs);
        init(context);
    }

    private void init(Context context) {
        myRegBtn = findViewById(R.id.btn1);
        ...
    }

    private void setAttributes(Context context, AttributeSet attrs) {
        ...
    }

    public void setMyRegBtnOnClickListener(OnClickListener o) {
        myRegBtn.setOnClickListener(o);
    }
}

In my mainActivity,

public class myMainActivity extends AppCompatActivity{
    private MyCustomView2 myCustomView2;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        ...
        myCustomView2.setMyRegBtnOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                //TODO: some code execute here when button clicked
            }
        });
    ...
}


问:
I don't understand how Set Date Methods work in JavaScript
I am a newbie, am trying to understand how Set Date Method work in JavaScript. The first code gave me different result than the second, despite they look (similar), i don't know why!

// First example
var a = new Date();
a.setFullYear(2020);
console.log(a); //result = Fri Feb 14 2020 18:29:28 GMT+0100 (West Africa Standard Time).
```

<pre class="lang-js prettyprint-override"><code>// Second example
var a = new Date();
var b = a.setFullYear(2020);
console.log(b); //result = 1581702924396
// I don't know why they gave different value
</code>```

答:
In the first example when you say a.setFullYear(2020); that value is not saved in a variable and the method does not change the value of the variable it is called by , a, on its own. When you log a in the console, it is logging new Date() which will be the current datetime string that you see returned in that example. If you wanted the results of setFullYear logged in the console in this example, you should have saved the result of the method to a (like a = a.setFullYear(2020)), or just logged the method in the console like: console.log(a.setFullYear(2020)) if you did not need to use it again later.

In the second example, you save the return value of a.setFullYear(2020); to a variable, b and then log that variable in the console. The setFullYear method returns the number of milliseconds between Jan 1 1970 and now, which is what you see logged. This millisecond count is very useful for easily comparing and storing dates.

Body:
I am a newbie, am trying to understand how Set Date Method work in JavaScript. The first code gave me different result than the second, despite they look (similar), i don't know why!

// First example
var a = new Date();
a.setFullYear(2020);
console.log(a); //result = Fri Feb 14 2020 18:29:28 GMT+0100 (West Africa Standard Time).

// Second example
var a = new Date();
var b = a.setFullYear(2020);
console.log(b); //result = 1581702924396
// I don't know why they gave different value


问:
odoo.service.server: Failed to load server-wide module `web`
I am getting this error during starting the server after installation of odoo 11.

I am using ubuntu 18.04

my config file is like this

```<code>*
[options]
; This is the password that allows database operations:
;admin_passwd = admin
db_host = 127.0.0.1
db_port = 8069
db_user = odoo
db_password = 123
addons_path = /opt/odoo/addons,/opt/odoo/odoo/addons
logfile = /var/log/odoo/odoo-server.log
*
</code>```

Full error is something like this

```<code>2020-02-07 05:12:33,809 12706 CRITICAL ? odoo.modules.module: Couldn't load module web
2020-02-07 05:12:33,809 12706 CRITICAL ? odoo.modules.module: The 'odoo.addons.web' package was not installed in a way that PackageLoader understands.
2020-02-07 05:12:33,809 12706 ERROR ? odoo.service.server: Failed to load server-wide module `web`.
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration.
Traceback (most recent call last):
  File "/opt/odoo/odoo/service/server.py", line 984, in load_server_wide_modules
    odoo.modules.module.load_openerp_module(m)
  File "/opt/odoo/odoo/modules/module.py", line 368, in load_openerp_module
    __import__('odoo.addons.' + module_name)
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "/opt/odoo/odoo/modules/module.py", line 82, in load_module
    exec(open(modfile, 'rb').read(), new_mod.__dict__)
  File "<string>", line 4, in <module>
  File "/opt/odoo/addons/web/controllers/__init__.py", line 4, in <module>
    from . import main, pivot
  File "/opt/odoo/addons/web/controllers/main.py", line 56, in <module>
    loader = jinja2.PackageLoader('odoo.addons.web', "views")
  File "/home/sandip/.local/lib/python3.6/site-packages/jinja2/loaders.py", line 290, in __init__
    " PackageLoader understands." % package_name
ValueError: The 'odoo.addons.web' package was not installed in a way that PackageLoader understands.
</code>```

答:
You might be blocked by a missing parameter in your config file.

Try to add the following parameter in the file:

```<code>server_wide_modules = web
</code>```

It is a requirement for the installation to go through peacefully.

Hope it helps

Body:
I am getting this error during starting the server after installation of odoo 11.

I am using ubuntu 18.04

my config file is like this

*
[options]
; This is the password that allows database operations:
;admin_passwd = admin
db_host = 127.0.0.1
db_port = 8069
db_user = odoo
db_password = 123
addons_path = /opt/odoo/addons,/opt/odoo/odoo/addons
logfile = /var/log/odoo/odoo-server.log
*

Full error is something like this

2020-02-07 05:12:33,809 12706 CRITICAL ? odoo.modules.module: Couldn't load module web
2020-02-07 05:12:33,809 12706 CRITICAL ? odoo.modules.module: The 'odoo.addons.web' package was not installed in a way that PackageLoader understands.
2020-02-07 05:12:33,809 12706 ERROR ? odoo.service.server: Failed to load server-wide module `web`.
The `web` module is provided by the addons found in the `openerp-web` project.
Maybe you forgot to add those addons in your addons_path configuration.
Traceback (most recent call last):
  File "/opt/odoo/odoo/service/server.py", line 984, in load_server_wide_modules
    odoo.modules.module.load_openerp_module(m)
  File "/opt/odoo/odoo/modules/module.py", line 368, in load_openerp_module
    __import__('odoo.addons.' + module_name)
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 656, in _load_unlocked
  File "<frozen importlib._bootstrap>", line 626, in _load_backward_compatible
  File "/opt/odoo/odoo/modules/module.py", line 82, in load_module
    exec(open(modfile, 'rb').read(), new_mod.__dict__)
  File "<string>", line 4, in <module>
  File "/opt/odoo/addons/web/controllers/__init__.py", line 4, in <module>
    from . import main, pivot
  File "/opt/odoo/addons/web/controllers/main.py", line 56, in <module>
    loader = jinja2.PackageLoader('odoo.addons.web', "views")
  File "/home/sandip/.local/lib/python3.6/site-packages/jinja2/loaders.py", line 290, in __init__
    " PackageLoader understands." % package_name
ValueError: The 'odoo.addons.web' package was not installed in a way that PackageLoader understands.

Body:
You might be blocked by a missing parameter in your config file.

Try to add the following parameter in the file:

server_wide_modules = web

It is a requirement for the installation to go through peacefully.

Hope it helps


问:
Is there a shorter way to write this condition in BigQuery?

SELECT IF(
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY) < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)
) AS days_until_july_4th
```

Specifically, I'm wondering if there is a way to avoid writing this line twice:

TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)

It's written once to compare to 0, and then written again for the else_result.

Can this be avoided?

答:
...  but for the purposes of my question you can just assume any statement could be there

Ok, so below "verbose" dummy example

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2020-02-14 17:46:33.270196 UTC' order_date,
    STRUCT('2020-02-12 17:46:33.270196 UTC' AS july_4th) next_year_holidays,
    STRUCT('2020-02-13 17:46:33.270196 UTC' AS july_4th) current_year_holidays
)
SELECT IF(
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY) < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)
) AS days_until_july_4th
FROM `project.dataset.table` t1
</code>```

can be re-written as

```<code>#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2020-02-14 17:46:33.270196 UTC' order_date,
    STRUCT('2020-02-12 17:46:33.270196 UTC' AS july_4th) next_year_holidays,
    STRUCT('2020-02-13 17:46:33.270196 UTC' AS july_4th) current_year_holidays
)
SELECT IF(
    diff < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    diff
) AS days_until_july_4th
FROM `project.dataset.table` t1,
UNNEST([TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)]) diff
</code>```

Hope, this gives you an idea

Body:
SELECT IF(
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY) < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)
) AS days_until_july_4th

Specifically, I'm wondering if there is a way to avoid writing this line twice:

TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)

It's written once to compare to 0, and then written again for the else_result.

Can this be avoided?

Body:
...  but for the purposes of my question you can just assume any statement could be there

Ok, so below "verbose" dummy example

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2020-02-14 17:46:33.270196 UTC' order_date,
    STRUCT('2020-02-12 17:46:33.270196 UTC' AS july_4th) next_year_holidays,
    STRUCT('2020-02-13 17:46:33.270196 UTC' AS july_4th) current_year_holidays
)
SELECT IF(
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY) < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)
) AS days_until_july_4th
FROM `project.dataset.table` t1

can be re-written as

#standardSQL
WITH `project.dataset.table` AS (
  SELECT '2020-02-14 17:46:33.270196 UTC' order_date,
    STRUCT('2020-02-12 17:46:33.270196 UTC' AS july_4th) next_year_holidays,
    STRUCT('2020-02-13 17:46:33.270196 UTC' AS july_4th) current_year_holidays
)
SELECT IF(
    diff < 0,
    TIMESTAMP_DIFF(TIMESTAMP(next_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY),
    diff
) AS days_until_july_4th
FROM `project.dataset.table` t1,
UNNEST([TIMESTAMP_DIFF(TIMESTAMP(current_year_holidays.july_4th), TIMESTAMP(t1.order_date), DAY)]) diff

Hope, this gives you an idea


问:
How to zip each element from a 1D array with the elements from each row of a 2D array?
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

```<code>x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]
</code>```

Into:

```<code>r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

答:
I thought of following:

Extend x to be of same size as y

Flatten y

Zip x and y

as follows

```<code>>>> x = [1, 2, 3]
>>> y = [[4, 5], [6, 7], [8, 9]]
>>> x = np.array(x).repeat(2)
>>> y = np.array(y).reshape(-1)
>>> list(zip(x, y))
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]
</code>```

I would love to learn how more efficiently this can be done.

Please comment or answer more efficient approach.

Body:
I am trying to plot a dataset using matplotlib which contains multiple y coordinates per x. To plot them I have to combine these arrays to show them in a single plot. How do I zip each element from a 1D array with the elements from each row of a 2D array (corresponding with the index for the element of the 1D array)? Without using explicit for-loops. Using built-ins (eg. zip/list comprehension) or even better: numpy?

Turning:

x = [1, 2, 3]
y = [[4, 5], [6, 7], [8, 9]]

Into:

r = [(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

Body:
I thought of following:

Extend x to be of same size as y

Flatten y

Zip x and y

as follows

>>> x = [1, 2, 3]
>>> y = [[4, 5], [6, 7], [8, 9]]
>>> x = np.array(x).repeat(2)
>>> y = np.array(y).reshape(-1)
>>> list(zip(x, y))
[(1, 4), (1, 5), (2, 6), (2, 7), (3, 8), (3, 9)]

I would love to learn how more efficiently this can be done.

Please comment or answer more efficient approach.


问:
Why does $(window).load() work but not $(document).ready()?
I'm working with a rails 3 app, and I want to use a sortable list. I'm working with the method shown here. My app uses JQuery, and there's a js file included in my app's layout that calls $(document).ready() to set up some visual stuff. That seems to be working fine.

However, when I attempt to call $(document).ready() in my view template via content_for :javascript to set up the sortable list, that code never fires. I do have the requisite yield :javascript call in my layout file, and if I load the page and look at the source everything looks fine. The code never runs, though – i.e. this instance of $(document).ready() never fires.

I've just found that if I replace $(document).ready() with $(window).load() then my js code runs.

So my question is: Why would $(document).ready() fail and $(window).load() work?

Code

This works:

```<code><% content_for :javascript do %>

<script>
   $(window).load(function(){
     alert('it works!');
   });
</script>
<% end %>
</code>```

This doesn't work

```<code><% content_for :javascript do %>

<script>
   $(document).ready(function(){
            alert('it works!');
   });
</script>
<% end %>
</code>```

Here's the Layout

```<code><!DOCTYPE html>
<html>
  <head>
    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>

    <!-- Reset Stylesheet -->
      <%= stylesheet_link_tag "reset" %>
        <!-- Main Stylesheet -->
      <%= stylesheet_link_tag "style" %>
        <!-- Invalid Stylesheet -->
      <%= stylesheet_link_tag "invalid" %>

        <%= javascript_include_tag :defaults, "nested_form", "DD_belatedPNG_0.0.7a", "simpla.jquery.configuration", "facebox", "jquery-ui.min" %>
        <%= yield :javascript %>

    <%= yield(:head) %>
    <%= csrf_meta_tag %>

  </head>
  <body onload="initialize()"><div id="body-wrapper">
…
</code>```

答:
What about a workaround... Did you know that a SCRIPT tag at the end of the BODY tag, is executed when everything before is loaded in the DOM ?

```<code><body>
  <!-- all your HTML here -->
  <script>
    //your starting Javascript code here
  </script>
</body>
</code>```

Body:
I'm working with a rails 3 app, and I want to use a sortable list. I'm working with the method shown here. My app uses JQuery, and there's a js file included in my app's layout that calls $(document).ready() to set up some visual stuff. That seems to be working fine.

However, when I attempt to call $(document).ready() in my view template via content_for :javascript to set up the sortable list, that code never fires. I do have the requisite yield :javascript call in my layout file, and if I load the page and look at the source everything looks fine. The code never runs, though – i.e. this instance of $(document).ready() never fires.

I've just found that if I replace $(document).ready() with $(window).load() then my js code runs.

So my question is: Why would $(document).ready() fail and $(window).load() work?

Code

This works:

<% content_for :javascript do %>

<% end %>

This doesn't work

<% content_for :javascript do %>

<% end %>

Here's the Layout

<!DOCTYPE html>

    <title><%= content_for?(:title) ? yield(:title) : "Untitled" %></title>

      <%= stylesheet_link_tag "reset" %>

      <%= stylesheet_link_tag "style" %>

      <%= stylesheet_link_tag "invalid" %>

        <%= javascript_include_tag :defaults, "nested_form", "DD_belatedPNG_0.0.7a", "simpla.jquery.configuration", "facebox", "jquery-ui.min" %>
        <%= yield :javascript %>

    <%= yield(:head) %>
    <%= csrf_meta_tag %>

…

Body:
What about a workaround... Did you know that a SCRIPT tag at the end of the BODY tag, is executed when everything before is loaded in the DOM ?

<body>
  <!-- all your HTML here -->
  <script>
    //your starting Javascript code here
  </script>
</body>


问:
How to calculate last day of month per row in dremio?
I have a properly casted date column that I want to create a new column from that is that date of the last day of the month.

Example:

```<code>current_datefield         end_of_month_date
2019-03-01                 2019-03-31
2020-01-29                 2020-01-31
</code>```

I dont know how to do this in dremio, I have tried EXTRACT,Date_PART

Non of the solutions work. Thank you in advance.

答:
Since Dremio is proprietary, and we don't run it where I work, I can't test specific code for you, but I can explain the approach. I'll leave working out the exact syntax to you.

Broadly speaking, the solution is to use the date value that you have to calculate the first day of the next month, then subtract one day. This works because every month has a first of the month, and every SQL engine will get the correct EOM date when subtracting one from the first. In most systems, there are several ways to do that.

The sort of "brute force" way is to take your current date, current_datefield, then EXTRACT the year and the month. Add one to the month. Use those values and a hardcoded 01 to "build" the first of next month. There will probably be a TO_DATE or some such involved there.

Now just wrap that value in a DATE_ADD function to subtract one.

Body:
I have a properly casted date column that I want to create a new column from that is that date of the last day of the month.

Example:

current_datefield         end_of_month_date
2019-03-01                 2019-03-31
2020-01-29                 2020-01-31

I dont know how to do this in dremio, I have tried EXTRACT,Date_PART

Non of the solutions work. Thank you in advance.


问:
What is the ALSA timer interface used for?
I have a hard time to figure out what the ALSA timer interface is actually useful for.

The documentation is quite lean:

Timer interface is designed to use internal timers in sound hardware, but it can be driven with any timer.

答:
"Nowadays, this interface is no longer useful."
I am not sure how valid this statement is. I trying to use the dshare plugin for creating a TDM audio frame with 16 channels and this timer is driving me crazy as you cannot use the plugins without it. infact all plugins use the timer. Atleast Dshare/Dmix/Dsnoop plugins use the timer.
The timer seems like it sets up a counter (unsigned int) at the start of the playback tracks the frames in time. essentially, its a running counter that any playback will sync up with and the difference between the application counter and the Timer (counter) will give you the #of samples that still need to be played.</p>


问:
Attachment size limit to export data?
I'd like to export my data via email everyday from a safesearch, problem is the (I think) limit of 5mb. There's a way to overcome it? Like for example send multiple files.

Thanks

答: It's possible to email a link accessable from the outside? I've Search info about it but got nothing... could you address me? Thanks</p>

Title: Attachment size limit to export data?


问:
Define default values for function arguments
In the Lua wiki I found a way to define default values for missing arguments:

```<code>function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end
</code>```

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.

答: Technically, there's b = b == nil and 7 or b (which should be used in the case where false is a valid value as false or 7 evaluates to 7), but that's probably not what you're looking for.

Body:
In the Lua wiki I found a way to define default values for missing arguments:

function myfunction(a,b,c)
    b = b or 7
    c = c or 5
    print (a,b,c)
end

Is that the only way? The PHP style myfunction (a,b=7,c=5) does not seem to work. Not that the Lua way doesn't work, I am just wondering if this is the only way to do it.