问:
Waiting for loop to execute and getting a value in Node Js
I am new to Node Js programming. I know that javascript is not sequential and executes the code synchronously. I have been having a hard time getting my head around async calls.
Here is my problem:

in my app.get('/send_friend_request', isLoggedIn, function (req, res) {}

I am trying to run a loop and get the value of counter, it will use this value to further choose if the person has already sent the request or not. I am basically checking if the user_id and from_id combinations already exist in FriendReq Collection in MongoDB:

```<code>var counter = 0;
    Profile.findOne({user_id: add_id}).exec(function (err, result) {
        if (err) res.send(err);

            for (var i = 0; i < result.friends_req.length; i++) {
                 FriendReq.findOne({_id: result.friends_req[i]}, function (err, res) {

                     if (res.user_id == add_id && res.from_id == id.toString()) {
                         counter = counter + 1
                     }
                     console.log("this is inside");
                     console.log(counter);  <---- this prints 1 but executes later
                 });
             }
console.log("this is outside");console.log(counter); <---- this prints 0
</code>```

the problem is "this is outside" gets executed first. I have tried using async library but could not get it right:

```<code> async.forEach(result.friends_req, function(item, callback){
            // call this callback when any asynchronous processing is done and
            // this iteration of the loop can be considered complete
            FriendReq.findOne({_id: item}, function (err, res) {
                console.log(res);
                console.log(res.user_id + "===" + add_id + "," + res.from_id + "===" + id);
                if (res.user_id == add_id && res.from_id == id.toString()) {
                    counter = counter + 1
                }
                console.log("this is inside");

                console.log(counter);
            });
            callback();
            // function to run after loop has completed
        }, function(err) {
            if ( !err) console.log("final"+counter);
        });
</code>```

Using this also "final" counter gets printed first. Can someone help me to get this right. My brain hurts.

答:
You could keep a count pending results, and when that count reaches zero you'll know your data retrieval is complete:

```<code>var counter = 0;
Profile.findOne({user_id: add_id}).exec(function (err, result) {
    if (err) res.send(err);
    var pending = result.friends_req.length;
    for (var i = 0; i < result.friends_req.length; i++) {
        FriendReq.findOne({_id: result.friends_req[i]}, function (err, res) {
            if (res.user_id == add_id && res.from_id == id.toString()) {
                counter = counter + 1
            }
            console.log("this is inside");
            console.log(counter);
            if (!--pending) {
                // all done. Do what you want here: e.g. invoke a callback
            }
        });
    }
}
</code>```

Alternatively you could look into promises. With mongoose exec you get a promise:

```<code>var counter = 0, promises;
Profile.findOne({user_id: add_id}).exec(function (err, result) {
    if (err) res.send(err);
    promises = result.friends_req.map(function (friends_req) {
        return FriendReq.findOne({_id: friends_req}, function (err, res) {
            if (res.user_id == add_id && res.from_id == id.toString()) {
                counter = counter + 1
            }
        }).exec();
    };
}).then(function () {
    Promise.all(promises).then(function () {
            console.log("all done");
            console.log(counter);
    });
}
</code>```

Body:
I am new to Node Js programming. I know that javascript is not sequential and executes the code synchronously. I have been having a hard time getting my head around async calls.
Here is my problem:

in my app.get('/send_friend_request', isLoggedIn, function (req, res) {}

I am trying to run a loop and get the value of counter, it will use this value to further choose if the person has already sent the request or not. I am basically checking if the user_id and from_id combinations already exist in FriendReq Collection in MongoDB:

var counter = 0;
    Profile.findOne({user_id: add_id}).exec(function (err, result) {
        if (err) res.send(err);

            for (var i = 0; i < result.friends_req.length; i++) {
                 FriendReq.findOne({_id: result.friends_req[i]}, function (err, res) {

                     if (res.user_id == add_id && res.from_id == id.toString()) {
                         counter = counter + 1
                     }
                     console.log("this is inside");
                     console.log(counter);  <---- this prints 1 but executes later
                 });
             }
console.log("this is outside");console.log(counter); <---- this prints 0

the problem is "this is outside" gets executed first. I have tried using async library but could not get it right:

 async.forEach(result.friends_req, function(item, callback){
            // call this callback when any asynchronous processing is done and
            // this iteration of the loop can be considered complete
            FriendReq.findOne({_id: item}, function (err, res) {
                console.log(res);
                console.log(res.user_id + "===" + add_id + "," + res.from_id + "===" + id);
                if (res.user_id == add_id && res.from_id == id.toString()) {
                    counter = counter + 1
                }
                console.log("this is inside");

                console.log(counter);
            });
            callback();
            // function to run after loop has completed
        }, function(err) {
            if ( !err) console.log("final"+counter);
        });

Using this also "final" counter gets printed first. Can someone help me to get this right. My brain hurts.

Body:
You could keep a count pending results, and when that count reaches zero you'll know your data retrieval is complete:

var counter = 0;
Profile.findOne({user_id: add_id}).exec(function (err, result) {
    if (err) res.send(err);
    var pending = result.friends_req.length;
    for (var i = 0; i < result.friends_req.length; i++) {
        FriendReq.findOne({_id: result.friends_req[i]}, function (err, res) {
            if (res.user_id == add_id && res.from_id == id.toString()) {
                counter = counter + 1
            }
            console.log("this is inside");
            console.log(counter);
            if (!--pending) {
                // all done. Do what you want here: e.g. invoke a callback
            }
        });
    }
}

Alternatively you could look into promises. With mongoose exec you get a promise:

var counter = 0, promises;
Profile.findOne({user_id: add_id}).exec(function (err, result) {
    if (err) res.send(err);
    promises = result.friends_req.map(function (friends_req) {
        return FriendReq.findOne({_id: friends_req}, function (err, res) {
            if (res.user_id == add_id && res.from_id == id.toString()) {
                counter = counter + 1
            }
        }).exec();
    };
}).then(function () {
    Promise.all(promises).then(function () {
            console.log("all done");
            console.log(counter);
    });
}


来源: stackexchange

问:
How to write a function f("123")=123+12+23+1+2+3 as a recurrence relationship
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

```<code>        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5
</code>```

答:
One way to look at this problem is to consider the contribution of each digit to the final sum.

For example, consider the digit Di at position i (from the end) in the number xn-1…xi+1Diyi-1…y0. (I used x, D, and y just to be able to talk about the digit positions.) If we look at all the substrings which contain D and sort them by the position of D from the end of the number, we'll see the following:

```<code>       D
      xD
     xxD
       …
   xx…xD
      Dy
     xDy
    xxDy
      …
  xx…xDy
     Dyy
    xDyy
   xxDyy
     …
 xx…xDyy
</code>```

and so on.

In other words, D appears in every position from 0 to i once for each prefix length from 0 to n-i-1 (inclusive), or a total of n-i times in each digit position. That means that its total contribution to the sum is D*(n-i) times the sum of the powers of 10 from 100 to 10i. (As it happens, that sum is exactly (10i+1−1)⁄9.)

That leads to a slightly simpler version of the iteration proposed by Paul Hankin:

def solve(n):
    ones = 0
    accum = 0
    for m in range(len(n),0,-1):
        ones = 10 * ones + 1
        accum += m * ones * int(n[m-1])
    return accum
```

<p>By rearranging the sums in a different way, you can come up with this simple recursion, if you really really want a recursive solution:</p>

<pre class="lang-python prettyprint-override"><code># Find the sum of the digits in a number represented as a string
digitSum = lambda n: sum(map(int, n))

# Recursive solution by summing suffixes:
solve2 = lambda n: solve2(n[1:]) + (10 * int(n) - digitSum(n))/9 if n else 0
</code>```

In case it's not obvious, 10*n-digitSum(n) is always divisible by 9, because:

10*n == n + 9*n == (mod 9) n mod 9 + 0

digitSum(n) mod 9 == n mod 9. (Because 10k == 1 mod n for any k.)

Therefore (10*n - digitSum(n)) mod 9 == (n - n) mod 9 == 0.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if someone can help me try to figure this out.

I want f(str) to take a string str of digits and return the sum of all substrings as numbers, and I want to write f as a function of itself so that I can try to solve this with memoization.

It's not jumping out at me as I stare at

        Solve("1") = 1
        Solve("2") = 2
        Solve("12") = 12 + 1 + 2
        Solve("29") = 29 + 2 + 9
        Solve("129") = 129 + 12 + 29 + 1 + 2 + 9
        Solve("293") = 293 + 29 + 93 + 2 + 9 + 3
        Solve("1293") = 1293 + 129 + 293 + 12 + 29 + 93 + 1 + 2 + 9 + 3
        Solve("2395") = 2395 + 239 + 395 + 23 + 39 + 95 + 2 + 3 + 9 + 5
        Solve("12395") = 12395 + 1239 + 2395 + 123 + 239 + 395 + 12 + 23 + 39 + 95 + 1 + 2 + 3 + 9 + 5

Body:
One way to look at this problem is to consider the contribution of each digit to the final sum.

For example, consider the digit Di at position i (from the end) in the number xn-1…xi+1Diyi-1…y0. (I used x, D, and y just to be able to talk about the digit positions.) If we look at all the substrings which contain D and sort them by the position of D from the end of the number, we'll see the following:

       D
      xD
     xxD
       …
   xx…xD
      Dy
     xDy
    xxDy
      …
  xx…xDy
     Dyy
    xDyy
   xxDyy
     …
 xx…xDyy

and so on.

In other words, D appears in every position from 0 to i once for each prefix length from 0 to n-i-1 (inclusive), or a total of n-i times in each digit position. That means that its total contribution to the sum is D*(n-i) times the sum of the powers of 10 from 100 to 10i. (As it happens, that sum is exactly (10i+1−1)⁄9.)

That leads to a slightly simpler version of the iteration proposed by Paul Hankin:

def solve(n):
    ones = 0
    accum = 0
    for m in range(len(n),0,-1):
        ones = 10 * ones + 1
        accum += m * ones * int(n[m-1])
    return accum

By rearranging the sums in a different way, you can come up with this simple recursion, if you really really want a recursive solution:

# Find the sum of the digits in a number represented as a string
digitSum = lambda n: sum(map(int, n))

# Recursive solution by summing suffixes:
solve2 = lambda n: solve2(n[1:]) + (10 * int(n) - digitSum(n))/9 if n else 0

In case it's not obvious, 10*n-digitSum(n) is always divisible by 9, because:

10*n == n + 9*n == (mod 9) n mod 9 + 0

digitSum(n) mod 9 == n mod 9. (Because 10k == 1 mod n for any k.)

Therefore (10*n - digitSum(n)) mod 9 == (n - n) mod 9 == 0.


问:
Change cell color based on value faster
I have vba code to change the color of cells based on the content of it currently I am looping through 13000 cells individually using row and column indexed for loops and a select case statement but it takes around 30 secs. Does anyone know a quicker way ?</p>

答: Perhaps sorting by the criteria you color code by, then changing ranges, and finally flipping back to original sequence perhaps. Sort it in such a way as the ones that would not need changing color appear at the end.. Then you can quit faster...</p>

Title: Change cell color based on value faster


问:
Angular 2 - Reactive form Validation messages

My objective is to put all my validation messages in component instead of html file

I have a sign up page and below is the fields:

```<code>public buildRegisterForm() {
this.userForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
    retypeEmail: ['', Validators.required],
  }, { validator: formMatcherValidator('email', 'retypeEmail') }),
  passwordGroup: this.fb.group({
    password: ['', [Validators.required, strongPasswordValidator()]],
    retypePassword: ['', Validators.required],
  }, { validator: formMatcherValidator('password', 'retypePassword')}),
});
}
</code>```

I'm following this tutorial link to achieve what I want which is
to put all my validation messages in component file instead of html file.

```<code>export const validationMessages = {
'firstName': {
'required': 'Your first name is required.',
'minlength': 'Your first name must be at least 3 characters long.'
},
'lastName': {
'required': 'Your last name is required.',
'minlength': 'Your last name must be less than 50 characters long.'
},
'emailGroup': {
  'email': {
      'required': 'Your email is required',
      'pattern': 'Your login email does not seem to be a valid email address.'
     },
 'retypeEmail': {
      'required': 'Your retype email is required',
      'match': 'The email provided do not match.'
   },
},
'passwordGroup':{
     'password': {
         'required': 'Your password is required',
         'strongPassword': 'Your password must be between 8 - 15 characters and must contain at least three of the following: upper case letter, lower case letter, number, symbol.'
     },
   'retypePassword': {
       'required': 'Your retype password is required',
        'match': 'The password provided do not match.'
  }
}
</code>```

onValueChanged  method

```<code>private onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;

// tslint:disable-next-line:forin
for (const field in this.formErrors) {
  // clear previous error message (if any)
  this.formErrors[field] = '';
  let control = form.get(field);
  // console.log("control", control.dirty);

  console.log("controlEmail", control);
  if (control && (control.dirty || control.touched) && control.invalid) {
    let messages = validationMessages[field];
    // tslint:disable-next-line:forin
    for (const key in control.errors) {
      this.formErrors[field] += messages[key] + ' ';
    }
  }
 }
}
</code>```

And this method is not working when I have multi formBuider Group or nested Object. Any tips for this 1?

similar to this How to validate reactive forms with nested form groups?

答:
You can also use the following alongside the original onValueChanged method:

```<code>formErrors = {
  'name': '',
  'power': '',
  'group.child':''
};

validationMessages = {
  'name': {
    'required': 'Name is required.',
  },
  'power': {
    'required': 'Power is required.'
  },
  'group.child': {
    'required': 'Child is required.',
  }
};

onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }
</code>```

Body:
My objective is to put all my validation messages in component instead of html file

I have a sign up page and below is the fields:

public buildRegisterForm() {
this.userForm = this.fb.group({
  firstName: ['', [Validators.required, Validators.minLength(3)]],
  lastName: ['', [Validators.required, Validators.maxLength(50)]],
  emailGroup: this.fb.group({
    email: ['', [Validators.required, Validators.pattern(this.emailPattern)]],
    retypeEmail: ['', Validators.required],
  }, { validator: formMatcherValidator('email', 'retypeEmail') }),
  passwordGroup: this.fb.group({
    password: ['', [Validators.required, strongPasswordValidator()]],
    retypePassword: ['', Validators.required],
  }, { validator: formMatcherValidator('password', 'retypePassword')}),
});
}

I'm following this tutorial link to achieve what I want which is
to put all my validation messages in component file instead of html file.

export const validationMessages = {
'firstName': {
'required': 'Your first name is required.',
'minlength': 'Your first name must be at least 3 characters long.'
},
'lastName': {
'required': 'Your last name is required.',
'minlength': 'Your last name must be less than 50 characters long.'
},
'emailGroup': {
  'email': {
      'required': 'Your email is required',
      'pattern': 'Your login email does not seem to be a valid email address.'
     },
 'retypeEmail': {
      'required': 'Your retype email is required',
      'match': 'The email provided do not match.'
   },
},
'passwordGroup':{
     'password': {
         'required': 'Your password is required',
         'strongPassword': 'Your password must be between 8 - 15 characters and must contain at least three of the following: upper case letter, lower case letter, number, symbol.'
     },
   'retypePassword': {
       'required': 'Your retype password is required',
        'match': 'The password provided do not match.'
  }
}

onValueChanged  method

private onValueChanged(data?: any) {
if (!this.userForm) { return; }
const form = this.userForm;

// tslint:disable-next-line:forin
for (const field in this.formErrors) {
  // clear previous error message (if any)
  this.formErrors[field] = '';
  let control = form.get(field);
  // console.log("control", control.dirty);

  console.log("controlEmail", control);
  if (control && (control.dirty || control.touched) && control.invalid) {
    let messages = validationMessages[field];
    // tslint:disable-next-line:forin
    for (const key in control.errors) {
      this.formErrors[field] += messages[key] + ' ';
    }
  }
 }
}

And this method is not working when I have multi formBuider Group or nested Object. Any tips for this 1?

similar to this How to validate reactive forms with nested form groups?

Body:
You can also use the following alongside the original onValueChanged method:

formErrors = {
  'name': '',
  'power': '',
  'group.child':''
};

validationMessages = {
  'name': {
    'required': 'Name is required.',
  },
  'power': {
    'required': 'Power is required.'
  },
  'group.child': {
    'required': 'Child is required.',
  }
};

onValueChanged(data?: any) {
    if (!this.heroForm) { return; }
    const form = this.heroForm;

    for (const field in this.formErrors) {
      // clear previous error message (if any)
      this.formErrors[field] = '';
      const control = form.get(field);

      if (control && control.dirty && !control.valid) {
        const messages = this.validationMessages[field];
        for (const key in control.errors) {
          this.formErrors[field] += messages[key] + ' ';
        }
      }
    }
  }


问:
How do you solve this problem regarding aligning divs next to each other?

Possible Duplicate:

  Aligning divs next to each other?

I want this design:

```<code>DIV1: auto-size DIV2: 160px
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
</code>```

How do I solve this problem? I've tried stuff like floating left & right, but I just can't get them on the same line.

I want the div 2 to always be there, and the div1 to have a max-width of 40em, but resize to allow the div 2 to show at all times if its necessary.

My CSS code:

```<code>#mainbulk {
 padding: 1.5em 2% 1.5em .5em;
}
#ads {
 width: 7.5em;
 float: left;
 display: table-cell;
 padding: 0 0 0 2em;
}
#textcontent {
 width: 70%;
 float: left;
 display: table-cell;
}
</code>```

and HTML

```<code><div id="mainbulk">
 <div id="textcontent">
  <p>This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.</p>
    </div>
    <div id="ads" align="right">
    ads would, hypothetically, be placed here if this were actually an actual website.
    </div>
</div>
</code>```

I'm encountering this problem:

http://www.screencast-o-matic.com/watch/c6lrXsXyQ

Full source code:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Frotly</title>
<style type="text/css">
body, html {
    font-size: 100%;
    text-align: center;
    padding: 0;
    border: 0;
    margin: 0;
}

#intro {
    border: 0;
    text-align: inherit;
    width: inherit;
}

#content {
    max-width: 50em;
    margin: 0 0 0 .7em;
}
#header {
    background-image: url(images/frotly.gif);
    background-repeat: no-repeat;
    height: 6.25em;
}
#menu {
    text-align: left;
}
#mainbulk {
    text-align: left;
}
#menu a {
    height: 1em;
    text-transform: uppercase;
    padding: 0.15em .6em;
    font-size: 0.9em;
    margin: 0 .5em;
    border-color: #000;
    border-radius: 4px;
    -moz-border-radius: 4px; /*Mozilla*/
    color: #FFF;
    font-weight: bold;
    text-decoration: none;

}
#menu a:link{
    border: px solid black;
    background: url(images/menubg2.gif) repeat-x;
}
#menu a:hover {
    background: url(images/menubginv.gif) repeat-x;
}
#mainbulk {
    padding: 1.5em 2% 1.5em .5em;
}
#ads {
    width: 7.5em;
    float: left;
    display: table-cell;
    padding: 0 0 0 2em;
}
#textcontent {
    width: 70%;
    float: left;
    display: table-cell;
}
</style>
</head>

<body>
<div id="content">
<div id="intro">
    <div id="header">

    </div>
    <div id="menu">
        <a href="#">Page 2</a><a href="#">Page 3</a><a href="#">Page 4</a><a href="#">Page 5</a><a href="#">Page 6</a>
    </div>
</div>
<div id="mainbulk">
    <div id="textcontent">
        <p>Frotly is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that Frotly can't do, then nothing can do it, but I'd suggest to try all of Frotly's features before complaining.</p>
    </div>
    <div id="ads">
    sdjafjhdj fg dfg sdf sadf asdf asdf asdf asdf asdfa sd hgilehri hergiuesrh iofdshoiers f vpaeirg 9owaej waeoioje raoaednae dnirefn oeh råo hwog heirhg oesnr ieharg eanr poaergo neriuhg neiarginea rer gr.
    </div>
</div>
</div>
</body>
</html>
</code>```

答:
```<code>#mainbulk { width: 960px; }
</code>```

Set the width of the main container, or use min-width

ContentLicense: CC BY-SA 2.5

Body:
Possible Duplicate:

  Aligning divs next to each other?

I want this design:

DIV1: auto-size DIV2: 160px
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo
divnumberonediv divtwo

How do I solve this problem? I've tried stuff like floating left & right, but I just can't get them on the same line.

I want the div 2 to always be there, and the div1 to have a max-width of 40em, but resize to allow the div 2 to show at all times if its necessary.

My CSS code:

#mainbulk {
 padding: 1.5em 2% 1.5em .5em;
}
#ads {
 width: 7.5em;
 float: left;
 display: table-cell;
 padding: 0 0 0 2em;
}
#textcontent {
 width: 70%;
 float: left;
 display: table-cell;
}

and HTML

This is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that this site can't do, then nothing can do it, but I'd suggest to try all of this site's features before complaining.

    ads would, hypothetically, be placed here if this were actually an actual website.

I'm encountering this problem:

http://www.screencast-o-matic.com/watch/c6lrXsXyQ

Full source code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Frotly</title>

        Page 2Page 3Page 4Page 5Page 6

Frotly is the most amazing site in the world. It has a very nice design, and is perfect for everything. If there's something that Frotly can't do, then nothing can do it, but I'd suggest to try all of Frotly's features before complaining.

    sdjafjhdj fg dfg sdf sadf asdf asdf asdf asdf asdfa sd hgilehri hergiuesrh iofdshoiers f vpaeirg 9owaej waeoioje raoaednae dnirefn oeh råo hwog heirhg oesnr ieharg eanr poaergo neriuhg neiarginea rer gr.

Body:
#mainbulk { width: 960px; }

Set the width of the main container, or use min-width


问:
How to split a number into its digits in APL
In APL, how can I split an integer or number into a vector containing its digits? What is the most concise (shortest) way of doing this?</p>

答:
You can use the inverse of Decode with base 10:

```<code>10⊥⍣¯1⊢
</code>```

since Decode would take in as many digits as needed and decode them, its inverse would take a number and encode it to as many digits as needed,

or, with ⎕IO←0, you can try to find the indexes of the formatted number inside the digits vector:

```<code>⎕D⍳⍕
</code>```

Demo for both solutions.

This is better than the uglier use of Encode with custom length derived by shaping an array of 10 to the length of the log10 of the input:

```<code>{⍵⊤⍨10⍴⍨⌈10⍟1+⍵}
</code>```

Body:
You can use the inverse of Decode with base 10:

10⊥⍣¯1⊢

since Decode would take in as many digits as needed and decode them, its inverse would take a number and encode it to as many digits as needed,

or, with ⎕IO←0, you can try to find the indexes of the formatted number inside the digits vector:

⎕D⍳⍕

Demo for both solutions.

This is better than the uglier use of Encode with custom length derived by shaping an array of 10 to the length of the log10 of the input:

{⍵⊤⍨10⍴⍨⌈10⍟1+⍵}


问:
Typescript class: Why does this compile?
I want to write a class like this:

```<code>class Foo {
    public someProp = '123';
}
</code>```

but I mistyped and wrote this:

```<code>class Foo{
    public someProp: '123'; // not "="
}
</code>```

I expect getting a compilation error but nothing happens. Why is it so?

答:
Because TypeScript supports constatnts as type when you need to list allowed values in the field. It is not a bug. It is feature. :)

```<code>var x: '123';
var y: '123' | '456';

x = '123';
x = '456'; // Error
x = '789'; // Error

y = '123';
y = '456';
y = '789'; // Error
</code>```

see TypeScript Playground

Body:
I want to write a class like this:

class Foo {
    public someProp = '123';
}

but I mistyped and wrote this:

class Foo{
    public someProp: '123'; // not "="
}

I expect getting a compilation error but nothing happens. Why is it so?

Body:
Because TypeScript supports constatnts as type when you need to list allowed values in the field. It is not a bug. It is feature. :)

var x: '123';
var y: '123' | '456';

x = '123';
x = '456'; // Error
x = '789'; // Error

y = '123';
y = '456';
y = '789'; // Error

see TypeScript Playground


问:
Display badge number in Android/Ios using cordova
I am developing an hybrid application with  cordova .I want to display notifications count in the application icon same as below image after recieving a notification from the APNS/FCM. I am using cordova-plugin-fcm and cordova-plugin-badge plugins.

code :

```<code>onDeviceReady: function() {
cordova.plugins.notification.badge.hasPermission(function (granted) {
    });

    cordova.plugins.notification.badge.registerPermission(function (hasPermission) {
    });

    // switch on 'auto clear'
    cordova.plugins.notification.badge.configure({
    autoClear: true
    });
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
    //Keep in mind the function will return null if the token has not been established yet.
    FCMPlugin.getToken(
    function(token){
        console.log("token "+token);
    },
    function(err){
        console.log('error retrieving token: ' + err);
    }
    )

    //FCMPlugin.subscribeToTopic( topic, successCallback(msg), errorCallback(err) );
    //All devices are subscribed automatically to 'all' and 'ios' or 'android' topic respectively.
    //Must match the following regular expression: "[a-zA-Z0-9-_.~%]{1,900}".
    FCMPlugin.subscribeToTopic('all');

    //FCMPlugin.onNotification( onNotificationCallback(data), successCallback(msg), errorCallback(err) )
    //Here you define your application behaviour based on the notification data.

    FCMPlugin.onNotification(
    function(data){
        //increase the badge
        cordova.plugins.notification.badge.increase();
        if(data.wasTapped){
        //Notification was received on device tray and tapped by the user.

        }else{
        //Notification was received in foreground. Maybe the user needs to be notified.
        }
    },
    function(msg){
    console.log('onNotification callback successfully registered: ' + msg);
    },
    function(err){
        console.log('Error registering onNotification callback: ' + err);
    }
    );}
</code>```

Image with badge !!

答:
The solution is to send 2 distinct FCM messages.

First one without notification, with a payload like this:

```<code>{
  "data":{
    "badge":"true",
  },
    "to":"/topics/all",
    "priority":"high"
}
</code>```

This will trigger onMessageReceived in MyFirebaseMessagingService.java, then pushes the payload to FCMPlugin.onNotification() callback.

```<code>FCMPlugin.onNotification(function(data){
    if(data.badge == "true"){
        cordova.plugins.notification.badge.increase();
    }
});
</code>```

By doing this, you will increase the badge number.
Then, you send the notification with a payload like this:

```<code>{
  "notification":{
    "title":"Notification title",
    "body":"Notification body",
    "sound":"default",
    "click_action":"FCM_PLUGIN_ACTIVITY",
    "icon":"fcm_push_icon"
  },
    "to":"/topics/all",
    "priority":"high"
}
</code>```

This way you will get the message in the notifications tray. I also recommend setting cordova.plugins.notification.badge.set(0) onDeviceReady and onResume events so that the badge number is cleared after app comes to foreground.

Body:
I am developing an hybrid application with  cordova .I want to display notifications count in the application icon same as below image after recieving a notification from the APNS/FCM. I am using cordova-plugin-fcm and cordova-plugin-badge plugins.

code :

onDeviceReady: function() {
cordova.plugins.notification.badge.hasPermission(function (granted) {
    });

    cordova.plugins.notification.badge.registerPermission(function (hasPermission) {
    });

    // switch on 'auto clear'
    cordova.plugins.notification.badge.configure({
    autoClear: true
    });
//FCMPlugin.getToken( successCallback(token), errorCallback(err) );
    //Keep in mind the function will return null if the token has not been established yet.
    FCMPlugin.getToken(
    function(token){
        console.log("token "+token);
    },
    function(err){
        console.log('error retrieving token: ' + err);
    }
    )

    //FCMPlugin.subscribeToTopic( topic, successCallback(msg), errorCallback(err) );
    //All devices are subscribed automatically to 'all' and 'ios' or 'android' topic respectively.
    //Must match the following regular expression: "[a-zA-Z0-9-_.~%]{1,900}".
    FCMPlugin.subscribeToTopic('all');

    //FCMPlugin.onNotification( onNotificationCallback(data), successCallback(msg), errorCallback(err) )
    //Here you define your application behaviour based on the notification data.

    FCMPlugin.onNotification(
    function(data){
        //increase the badge
        cordova.plugins.notification.badge.increase();
        if(data.wasTapped){
        //Notification was received on device tray and tapped by the user.

        }else{
        //Notification was received in foreground. Maybe the user needs to be notified.
        }
    },
    function(msg){
    console.log('onNotification callback successfully registered: ' + msg);
    },
    function(err){
        console.log('Error registering onNotification callback: ' + err);
    }
    );}

Image with badge !!

Body:
The solution is to send 2 distinct FCM messages.

First one without notification, with a payload like this:

{
  "data":{
    "badge":"true",
  },
    "to":"/topics/all",
    "priority":"high"
}

This will trigger onMessageReceived in MyFirebaseMessagingService.java, then pushes the payload to FCMPlugin.onNotification() callback.

FCMPlugin.onNotification(function(data){
    if(data.badge == "true"){
        cordova.plugins.notification.badge.increase();
    }
});

By doing this, you will increase the badge number.
Then, you send the notification with a payload like this:

{
  "notification":{
    "title":"Notification title",
    "body":"Notification body",
    "sound":"default",
    "click_action":"FCM_PLUGIN_ACTIVITY",
    "icon":"fcm_push_icon"
  },
    "to":"/topics/all",
    "priority":"high"
}

This way you will get the message in the notifications tray. I also recommend setting cordova.plugins.notification.badge.set(0) onDeviceReady and onResume events so that the badge number is cleared after app comes to foreground.


问:
Check if an array is descending, ascending or not sorted?
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

```<code>        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }
</code>```

答:
You could use a copy from the second element and check the predecessor for the wanted sort order.

function checkArray(array) {
    var aa = array.slice(1);
    if (!aa.length) {
        return "Just one element";
    }
    if (aa.every((a, i) => array[i] > a)) {
        return "Ascending";
    }
    if (aa.every((a, i) => array[i] < a)) {
        return "Descending";
    }
    return "Unsorted";
}

console.log(checkArray([1, 2, 3, 4, 5]));
console.log(checkArray([5, 4, 3, 2, 1]));
console.log(checkArray([3, 1, 4, 2, 5]));
console.log(checkArray([42]));```

Body:
I'm just beginning with programming using javascript and I need to practice some questions to get EXP with the logic of code build.
I got this question for homework but I can't make it work for some reason, even though it seems "logic" to me.
Check if an array is descending, ascending or not sorted using loops.

I'm just a noob so please try and help me figure this out as I only got to loops in my studies (:
 this is the code I wrote:

        var array = [1, 2, 3, 7 ];
        var d = 0;
        var c =0 ;
        var b = 1;
        var a = 0;
        for (var i = 1; i <= array.length; i++)
            {
                if (array[c]<array[b] && a!== -1  ){
                   d = -1;
                   c =c+1;
                   b = b+1;
                   if(c==array.length){
                    console.log("asc");
                     break;
                   }else{
                     continue;
                }

                } else if (array[c]>array[b] && d!==-1 ){
                           a = -1;
                           d= d+1;
                           b = b+1;
                    if(i=array.length){
                    console.log("dsc");
                    break;
               }else{continue;}

               } else{

                    console.log("unsorted array");
                    break;
                }

            }


问:
Can I 'drop' a PHP request without replying?
I am not completely sure that this is possible from within PHP or even the HTTP protocol in depth. Is it possible to receive PHP script to run when it is requested but then the script drops the connection? Without replying?

Hopefully my question makes sense.

(I am using Apache)

答: Why would you want to do this? Surely you should be sending some kind of HTTP error code instead?</p>


问:
Flutter - Effect of flip card
I'm trying to make a flip card, what would be the best way to get the effect

答:
I would use an AnimatedBuilder or AnimatedWidget to animate the values of a Transform widget. ScaleTransition almost does this for you, but it scales both directions, and you only want one.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyCustomCard extends StatelessWidget {
  MyCustomCard({ this.colors });

  final MaterialColor colors;

  Widget build(BuildContext context) {
    return new Container(
      alignment: FractionalOffset.center,
      height: 144.0,
      width: 360.0,
      decoration: new BoxDecoration(
        color: colors.shade50,
        border: new Border.all(color: new Color(0xFF9E9E9E)),
      ),
      child: new FlutterLogo(size: 100.0, colors: colors),
    );
  }
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _frontScale;
  Animation<double> _backScale;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
    _frontScale = new Tween(
      begin: 1.0,
      end: 0.0,
    ).animate(new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 0.5, curve: Curves.easeIn),
    ));
    _backScale = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.5, 1.0, curve: Curves.easeOut),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);

    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.flip_to_back),
        onPressed: () {
          setState(() {
            if (_controller.isCompleted || _controller.velocity > 0)
              _controller.reverse();
            else
              _controller.forward();
          });
        },
      ),
      body: new Center(
        child: new Stack(
          children: <Widget>[
            new AnimatedBuilder(
              child: new MyCustomCard(colors: Colors.orange),
              animation: _backScale,
              builder: (BuildContext context, Widget child) {
                final Matrix4 transform = new Matrix4.identity()
                  ..scale(1.0, _backScale.value, 1.0);
                return new Transform(
                  transform: transform,
                  alignment: FractionalOffset.center,
                  child: child,
                );
              },
            ),
            new AnimatedBuilder(
              child: new MyCustomCard(colors: Colors.blue),
              animation: _frontScale,
              builder: (BuildContext context, Widget child) {
                final Matrix4 transform = new Matrix4.identity()
                  ..scale(1.0, _frontScale.value, 1.0);
                return new Transform(
                  transform: transform,
                  alignment: FractionalOffset.center,
                  child: child,
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}
</code>```

Title: Flutter - Effect of flip card

Body:
I would use an AnimatedBuilder or AnimatedWidget to animate the values of a Transform widget. ScaleTransition almost does this for you, but it scales both directions, and you only want one.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePageState createState() => new MyHomePageState();
}

class MyCustomCard extends StatelessWidget {
  MyCustomCard({ this.colors });

  final MaterialColor colors;

  Widget build(BuildContext context) {
    return new Container(
      alignment: FractionalOffset.center,
      height: 144.0,
      width: 360.0,
      decoration: new BoxDecoration(
        color: colors.shade50,
        border: new Border.all(color: new Color(0xFF9E9E9E)),
      ),
      child: new FlutterLogo(size: 100.0, colors: colors),
    );
  }
}

class MyHomePageState extends State<MyHomePage> with TickerProviderStateMixin {
  AnimationController _controller;
  Animation<double> _frontScale;
  Animation<double> _backScale;

  @override
  void initState() {
    super.initState();
    _controller = new AnimationController(
      vsync: this,
      duration: const Duration(seconds: 1),
    );
    _frontScale = new Tween(
      begin: 1.0,
      end: 0.0,
    ).animate(new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.0, 0.5, curve: Curves.easeIn),
    ));
    _backScale = new CurvedAnimation(
      parent: _controller,
      curve: new Interval(0.5, 1.0, curve: Curves.easeOut),
    );
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ThemeData theme = Theme.of(context);

    return new Scaffold(
      appBar: new AppBar(),
      floatingActionButton: new FloatingActionButton(
        child: new Icon(Icons.flip_to_back),
        onPressed: () {
          setState(() {
            if (_controller.isCompleted || _controller.velocity > 0)
              _controller.reverse();
            else
              _controller.forward();
          });
        },
      ),
      body: new Center(
        child: new Stack(
          children: <Widget>[
            new AnimatedBuilder(
              child: new MyCustomCard(colors: Colors.orange),
              animation: _backScale,
              builder: (BuildContext context, Widget child) {
                final Matrix4 transform = new Matrix4.identity()
                  ..scale(1.0, _backScale.value, 1.0);
                return new Transform(
                  transform: transform,
                  alignment: FractionalOffset.center,
                  child: child,
                );
              },
            ),
            new AnimatedBuilder(
              child: new MyCustomCard(colors: Colors.blue),
              animation: _frontScale,
              builder: (BuildContext context, Widget child) {
                final Matrix4 transform = new Matrix4.identity()
                  ..scale(1.0, _frontScale.value, 1.0);
                return new Transform(
                  transform: transform,
                  alignment: FractionalOffset.center,
                  child: child,
                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

ContentLicense: CC BY-SA 4.0


问:
Do I really need to request runtime permissions?
Runtime permissions are essential to ensure that your apps get the required permissions to function, on android 6+ devices, however, it seems like some top developers (gameloft, ea games) do not find the need to implement runtime permissions, and they are rather happy on target SDK 22. So my questions are:

Why do I need take the pain of adding run-time permissions, when I can be stay on api 22. This would also save some lines of code.

Is it possible to upgrade from target SDK 22 to target SDK 23 once the app has been published? If I plan to stay on SDK 22 for now. It seems like downgrading is not possible. " Keep in mind that once you publish an APK targeting API level 23 or higher, you won't be able to submit an update targeting API level 22 or lower on any channel. "

答:
Why do I need take the pain of adding run-time permissions, when I can be stay on api 22

Your "I can be stay on api 22" assumption may not hold up well over time. For example, the user will be told that your app is not compatible with multi-window.

Also, users see that the app is not supporting runtime permissions right away at install time, as they are prompted with the classic install-time permission dialog. Users, over time, will start to think that apps that show that dialog are out of date and not being maintained, and so they may not bother installing your app.

Also, certain third-party libraries that you may want to use may insist upon a higher targetSdkVersion.

So, while technically you can have any targetSdkVersion you want, there are costs.

This would also save some lines of code.

Not necessarily. The user can still revoke these permissions from within Settings, and so you may need more error-handling code than before.

Is it possible to upgrade from target SDK 22 to target SDK 23 once the app has been published?

In general, yes.


问:
I cound not able to install monodevelop in ubuntu 14.04
I want to install Monodevelop in ubuntu for that I follow instruction provided on http://www.mono-project.com/download/#download-lin

After following these following.
I put command sudo apt-get install mono-complete monodevelop

But unmet dependencies are as follows.

Please help me to get resolve the issue..

Thanks very much..

答:
The unmet condition is by design. The monodevelop package is too old, so it does not work with latest Mono (5.x) packages.

You can now use the alternative installer from GitHub,

https://github.com/cra0zy/monodevelop-run-installer

I have a blog post to cover more details,

https://blog.lextudio.com/the-success-of-running-monodevelop-7-on-linux-a55f1469b1d1


问:
How to get a phone's number in React Native?
With React Native, how do you get the number of the current phone?

Along the same lines, can I get the user's name?

答: It looks like the react-native-sim library can do this on Android, though as @xanadont mentions, it's not currently possible on iOS.


问:
IntegrityError: Not Null constraint failed
I have deleted a class from model.py but whenever I run python manage.py migrate, I get this:

intergrityerror : not null constraint failed: appname_modelclassfieldname.user_id

The most challenging thing is that I had already deleted the model class of the related field django is pointing error at.

答: The problem was an error with the server .I had delete the app and create a new one ,and everything is working just fine now</p>


问:
Custom HeaderFooterView Bad Access
In the following code, viewForHeaderInSection last line, I am getting EXC_BAD ACCESS error.

ViewController.m

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    movies = [[NSArray alloc] initWithObjects:
           (NSArray*)[[Section alloc ] init:@"Z" movieNames:@[@"M", @"S"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"M" movieNames:@[@"Y", @"A"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"H" movieNames:@[@"M", @"F"] isExpanded:false], nil
           ];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ExpandableHeaderFoorterView* headerView = [[ExpandableHeaderFoorterView alloc] customInit:((Section*)movies[section]).genre withSection:section withDelegate:self];
    // BAD ACCESS
    return headerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    cell.textLabel.text =  ((Section*)movies[indexPath.section]).movies[indexPath.row];
    return cell;
}
</code>```

ExpandableHeaderFoorterView.m

```<code>- (id)customInit:(NSString*)title withSection: (NSInteger) section withDelegate :(id<ExpandableHeaderFooterViewDelegate>)delegate
{
    self.textLabel.text = title;
    self.headerSection = section;
    self.headerDelegate = delegate;
    return self;
}
</code>```

答:
Your implementation of your custom init method is all wrong. That's not how you write an initializer in Objective-C. Also, since it is an initializer, the name should start with init....

Since you are extending UITableViewHeaderFooterView you need to call the proper super initializer.

```<code>- (id)init:(NSString*)title withSection:(NSInteger)section withDelegate:(id<ExpandableHeaderFooterViewDelegate>)delegate {
    self = [super initWithReuseIdentifier:@"SomeUsefulIdentifier"];
    if (self) {
        self.textLabel.text = title;
        self.headerSection = section;
        self.headerDelegate = delegate;
    }

    return self;
}
</code>```

Title: Custom HeaderFooterView Bad Access

Body:
In the following code, viewForHeaderInSection last line, I am getting EXC_BAD ACCESS error.

ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    movies = [[NSArray alloc] initWithObjects:
           (NSArray*)[[Section alloc ] init:@"Z" movieNames:@[@"M", @"S"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"M" movieNames:@[@"Y", @"A"] isExpanded:false],
           (NSArray*)[[Section alloc ] init:@"H" movieNames:@[@"M", @"F"] isExpanded:false], nil
           ];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    ExpandableHeaderFoorterView* headerView = [[ExpandableHeaderFoorterView alloc] customInit:((Section*)movies[section]).genre withSection:section withDelegate:self];
    // BAD ACCESS
    return headerView;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
    }

    cell.textLabel.text =  ((Section*)movies[indexPath.section]).movies[indexPath.row];
    return cell;
}

ExpandableHeaderFoorterView.m

- (id)customInit:(NSString*)title withSection: (NSInteger) section withDelegate :(id<ExpandableHeaderFooterViewDelegate>)delegate
{
    self.textLabel.text = title;
    self.headerSection = section;
    self.headerDelegate = delegate;
    return self;
}

Body:
Your implementation of your custom init method is all wrong. That's not how you write an initializer in Objective-C. Also, since it is an initializer, the name should start with init....

Since you are extending UITableViewHeaderFooterView you need to call the proper super initializer.

- (id)init:(NSString*)title withSection:(NSInteger)section withDelegate:(id<ExpandableHeaderFooterViewDelegate>)delegate {
    self = [super initWithReuseIdentifier:@"SomeUsefulIdentifier"];
    if (self) {
        self.textLabel.text = title;
        self.headerSection = section;
        self.headerDelegate = delegate;
    }

    return self;
}


问:
Android Out of Memory Error using DrawableAnimation
I´m trying to run an app with several DrawableAnimation.

Structure

MainActivity - ButtonA - ButtonB - ButtonC - ButtonD - ButtonE - Button F

ActivityA - ButtonA1 - ButtonA2 - ButtonA3 - ButtonA4

ActivityB - ButtonB1 - ButtonB2 - ButtonB3 - ButtonB4

ActivityC - ButtonC1 - ButtonC2 - ButtonC3

Settings - Name - Date - Numbers -

So, each button Start a Short DrawableAnimation, each animation has 30 to 50 images. I know it´s a little ambitious, but I´m sure there´s a way to do it.

Each Animation start with this code:

```<code>private void addListenerOnButton() {
view = (ImageView) findViewById(R.id.image);
button = (Button) findViewById(R.id.startanimation);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        frameAnimation.stop(); frameAnimation = null;
        view.setBackgroundResource(R.drawable.animation01);
        frameAnimation = (AnimationDrawable) view.getBackground();
        frameAnimation.start();
</code>```

I tried to clean memory with animation stop or animation null, but it doesn't work.
I tried with bitmap recycle but, If the user wants to run an Animation more than one time it doesn't work cause recycle don't use it anymore.
I know that garbage collector is not the way.

So, how can I run DrawableAnimation and Clean Memory after finish it, to avoid the Out of Memory error?

答:
for me this code works fine

```<code>largeHeap=true
</code>```

you have to put in application tag of manifest

Body:
I´m trying to run an app with several DrawableAnimation.

Structure

MainActivity - ButtonA - ButtonB - ButtonC - ButtonD - ButtonE - Button F

ActivityA - ButtonA1 - ButtonA2 - ButtonA3 - ButtonA4

ActivityB - ButtonB1 - ButtonB2 - ButtonB3 - ButtonB4

ActivityC - ButtonC1 - ButtonC2 - ButtonC3

Settings - Name - Date - Numbers -

So, each button Start a Short DrawableAnimation, each animation has 30 to 50 images. I know it´s a little ambitious, but I´m sure there´s a way to do it.

Each Animation start with this code:

private void addListenerOnButton() {
view = (ImageView) findViewById(R.id.image);
button = (Button) findViewById(R.id.startanimation);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) {
        frameAnimation.stop(); frameAnimation = null;
        view.setBackgroundResource(R.drawable.animation01);
        frameAnimation = (AnimationDrawable) view.getBackground();
        frameAnimation.start();

I tried to clean memory with animation stop or animation null, but it doesn't work.
I tried with bitmap recycle but, If the user wants to run an Animation more than one time it doesn't work cause recycle don't use it anymore.
I know that garbage collector is not the way.

So, how can I run DrawableAnimation and Clean Memory after finish it, to avoid the Out of Memory error?

Body:
for me this code works fine

largeHeap=true

you have to put in application tag of manifest


问:
I have two images that I want to display in a single row next to each other
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div id="umar">
  <div class="card">
    <img src="images/img.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="images/img1.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>
</div></code>```

答:
I would add display: flex for your container #umar. Also you can optionally set CSS property align-items for vertical positioning.

#umar {
  display: flex; /* new */
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h2>Card</h2>

<div id="umar">
  <div class="card">
    <img src="images/img.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="images/img1.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>
</div></code>```

Body:
I am unable to display in one row. I will be looping the images dynamically. So if there are 4 to 5 images, then it should come in one row. But if there are more than 5 images or you can say 9, then it should come in next rows. In the below code, I am using HTML and CSS but unable to get in same row.

#umar {
  display: inline;
  width: 100%;
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}

Card

John Doe

Architect & Engineer

John Doe

Architect & Engineer

Body:
I would add display: flex for your container #umar. Also you can optionally set CSS property align-items for vertical positioning.

#umar {
  display: flex; /* new */
}

.card {
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
  transition: 0.3s;
  width: 20%;
}

.card:hover {
  box-shadow: 0 8px 16px 0 rgba(0, 0, 0, 0.2);
}

.container {
  padding: 2px 16px;
  margin-bottom: 10px;
}

<h2>Card</h2>

<div id="umar">
  <div class="card">
    <img src="images/img.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>

  <div class="card">
    <img src="images/img1.jpg" alt="Avatar" style="width:100%">
    <div class="container">
      <h4><b>John Doe</b></h4>
      <p>Architect & Engineer</p>
    </div>
  </div>
</div>


问:
How do I nest knockoutjs when comming from seperate js files?
I have one html file with several js files included. These js files have knockout videmodels and I need to bind them nested in the html file.

Here's a sample:

HTML

```<code><div id="container1">
   <span data-bind="html: name"></span>
   <div id="container2">
      <span data-bind="html: color"></span>
   </div>
</div>
</code>```

JAVASCRIPT

```<code>// Script comming from myScript1.js....
var person = new function() {
   var viewModel = function() {
      var self = this;
      self.name = ko.observable("John");
      return {
         name: self.name
      };
   };
   var vm = new viewModel();
   ko.applyBindings(vm, document.getElementById("container1"));
}

// Script comming from myScript2.js....
var colors = new function() {
   var viewModel = function() {
      var self = this;
      self.color = ko.observable("Red");
      return {
         color: self.color
      };
   }
   var vm = new viewModel();
   ko.applyBindings(vm, document.getElementById("container2"));
}
</code>```

jsfiddle

I get this error:

Uncaught ReferenceError: Unable to process binding "html: function
  (){return color }" Message: color is not defined

How can I solve this? Thanks!

答:
Hmm, I see 2 ways to solve this problem. However in both solutions sequence of js files is important (not quite sure is it significant for you).

Include Colors into Person

Use with binding for your inner html block:

Markup:

```<code><div id="container1">
    <span data-bind="html: name"></span>
    <!--with binding to set context-->
    <div data-bind="with: colors">
        <span data-bind="html: color"></span>
    </div>
</div>
</code>```

First file:

```<code>// It's important to put this script first to make it available in person
var Colors = function() {
    return {
       color: ko.observable("Red")
    };
}
</code>```

Second file:

```<code>var Person = function() {
    return {
       name: ko.observable("John"),
       // Create new instance of colors inside your person view model.
       colors: new Colors()
    };
};
ko.applyBindings(new Person(), document.getElementById("container1"));
</code>```

Use component for your inner html

You can use components to separate logic of particular blocks on the page. I would prefer this solution to make application more scalable.

Markup:

```<code><div id="container1">
    <span data-bind="html: name"></span>
    <!--separate component as inner element-->
    <colors></colors>
</div>
</code>```

First file (your component):

```<code>ko.components.register("colors", {
    viewModel: function(params) {
        return {
            color: ko.observable("Red")
        };
    },
    template: "<div id='container2'><span data-bind='html: color'></span></div>"
});
</code>```

Second file:

```<code>var Person = function() {
    return {
       name: ko.observable("John")
    };
};
ko.applyBindings(new Person(), document.getElementById("container1"));
</code>```

Body:
I have one html file with several js files included. These js files have knockout videmodels and I need to bind them nested in the html file.

Here's a sample:

HTML

JAVASCRIPT

// Script comming from myScript1.js....
var person = new function() {
   var viewModel = function() {
      var self = this;
      self.name = ko.observable("John");
      return {
         name: self.name
      };
   };
   var vm = new viewModel();
   ko.applyBindings(vm, document.getElementById("container1"));
}

// Script comming from myScript2.js....
var colors = new function() {
   var viewModel = function() {
      var self = this;
      self.color = ko.observable("Red");
      return {
         color: self.color
      };
   }
   var vm = new viewModel();
   ko.applyBindings(vm, document.getElementById("container2"));
}

jsfiddle

I get this error:

Uncaught ReferenceError: Unable to process binding "html: function
  (){return color }" Message: color is not defined

How can I solve this? Thanks!

Body:
Hmm, I see 2 ways to solve this problem. However in both solutions sequence of js files is important (not quite sure is it significant for you).

Include Colors into Person

Use with binding for your inner html block:

Markup:

<div id="container1">
    <span data-bind="html: name"></span>
    <!--with binding to set context-->
    <div data-bind="with: colors">
        <span data-bind="html: color"></span>
    </div>
</div>

First file:

// It's important to put this script first to make it available in person
var Colors = function() {
    return {
       color: ko.observable("Red")
    };
}

Second file:

var Person = function() {
    return {
       name: ko.observable("John"),
       // Create new instance of colors inside your person view model.
       colors: new Colors()
    };
};
ko.applyBindings(new Person(), document.getElementById("container1"));

Use component for your inner html

You can use components to separate logic of particular blocks on the page. I would prefer this solution to make application more scalable.

Markup:

<div id="container1">
    <span data-bind="html: name"></span>
    <!--separate component as inner element-->
    <colors></colors>
</div>

First file (your component):

ko.components.register("colors", {
    viewModel: function(params) {
        return {
            color: ko.observable("Red")
        };
    },
    template: "<div id='container2'><span data-bind='html: color'></span></div>"
});

Second file:

var Person = function() {
    return {
       name: ko.observable("John")
    };
};
ko.applyBindings(new Person(), document.getElementById("container1"));


问:
Pattern match an array of Regex's in Scala
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

```<code>  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}
</code>```

答:
This will tell you if any of the Regex patterns match the 1st element in the massageBody array.

```<code>unsubscribeTriggers.exists(_.findAllIn(messageBody.head).nonEmpty)
</code>```

But I don't think your regex patterns do what you want. What is the /i extension? If you mean for it to ignore case, it won't. It's also not a very efficient or Scala-esque way to do it. Instead of many smaller regex patterns, combine them into a single test.

```<code>val unsubscribeTriggers: Array[String] =
  Array("unsubscribe/i", "stop/i", "stopall/i", "cancel.i", "end/i", "quit/i")
val TriggersRE = unsubscribeTriggers.mkString("(", "|", ")").r

messageBody.head match {
  case TriggersRE(_) => true
  case _ => false
}
</code>```

update

If you just need to compare strings, ignoring case, then try this.

```<code>val unsubscribeTriggers: Array[String] =
  Array("unsubscribe", "stop", "stopall", "cancel", "end", "quit")

unsubscribeTriggers.exists(messageBody.head.equalsIgnoreCase)
</code>```

If you want to test if any element in massageBody matches any element in unsubscribeTriggers then try this.

```<code>unsubscribeTriggers.exists(t => messageBody.exists(t.equalsIgnoreCase))
</code>```

Body:
I have an array of regex's in Scala, and am trying to verify that a message body contains anything in the regex. However, in the messageBody variable I'm getting a Pattern type is incompatible with given type, expected Array[Regex], found Array[String]. How can I pass in a proper case?

A few other posts have suggested using Pattern but that hasn't worked in my case.

  val messageBody: Array[String] = message.body.split(' ')
  val unsubscribeTriggers: Array[Regex] = Array("unsubscribe/i".r, "stop/i".r, "stopall/i".r, "cancel/i".r, "end/i".r, "quit/i".r)\

  if (messageBody.length == 1) {
        unsubscribeTriggers match {
          case `messageBody` => true

          case _ => false

        }
}

Body:
This will tell you if any of the Regex patterns match the 1st element in the massageBody array.

unsubscribeTriggers.exists(_.findAllIn(messageBody.head).nonEmpty)

But I don't think your regex patterns do what you want. What is the /i extension? If you mean for it to ignore case, it won't. It's also not a very efficient or Scala-esque way to do it. Instead of many smaller regex patterns, combine them into a single test.

val unsubscribeTriggers: Array[String] =
  Array("unsubscribe/i", "stop/i", "stopall/i", "cancel.i", "end/i", "quit/i")
val TriggersRE = unsubscribeTriggers.mkString("(", "|", ")").r

messageBody.head match {
  case TriggersRE(_) => true
  case _ => false
}

update

If you just need to compare strings, ignoring case, then try this.

val unsubscribeTriggers: Array[String] =
  Array("unsubscribe", "stop", "stopall", "cancel", "end", "quit")

unsubscribeTriggers.exists(messageBody.head.equalsIgnoreCase)

If you want to test if any element in massageBody matches any element in unsubscribeTriggers then try this.

unsubscribeTriggers.exists(t => messageBody.exists(t.equalsIgnoreCase))


问:
Convert string to array in Java?
I have a string which has the values like this (format is the same):

```<code>name:xxx
occupation:yyy
phone:zzz
</code>```

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?

答: I would recommend using String's split function.</p>

Title: Convert string to array in Java?

Body:
I have a string which has the values like this (format is the same):

name:xxx
occupation:yyy
phone:zzz

I want to convert this into an array and get the occupation value using indexes.

Any suggestions?


问:
Ms Access multi-select listbox mover
I have two list boxes (lfmVocabulary and lfmVocabularyAssign). They are both unbound along with the form and I'm having trouble achieving certain aspects of the code design.

Thus far, I am able to populate the first list form with the values through a query recordset, but I'm unable to transfer the items from one box to the other.

In an attempt to achieve this, I placed the code in a module as follows

```<code>Option Compare Database

Public Sub MoveListBoxItems(lfmVocabularyAssign As ListBox, _
lfmVocabulary As ListBox)

Dim intListX As Integer

For intListX = lfmVocabulary.ListCount = -1 To 0
    If lfmVocabulary.Selected(intListX) Then
     lfmVocabularyAssign.AddItem lfmVocabulary.List(intListX)
     lfmVocabulary.RemoveItem intListX
    End If
Next
End Sub
</code>```

In the form, I have the following code:

```<code>Option Explicit

Dim db As Database
Dim rs As Recordset

Private Sub cmdAdd_Click()

MoveListBoxItems lfmVocabulary, lfmVocabularyAssign

End Sub

Private Sub cmdSelectAll1_Click()

    Dim n As Integer

    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With

End Sub

Private Sub Form_Load()

    Set db = CurrentDb
    Set rs = db.OpenRecordset("qryVocabularyDefinitions")

    Me.lfmVocabulary.RowSource = ""
    Do Until rs.EOF
        Me.lfmVocabulary.AddItem rs!Vocabulary
        rs.MoveNext
    Loop

End Sub
</code>```

I am kinda new to Access and coding in general and I've been scouring the Internet looking for a solution.

I would offer a thousand thanks to anyone that can help me :D

答:
You've made multiple small errors and not accounted for some complexities, here's the correct code:

```<code>Public Sub MoveListBoxItems(lstDestination As ListBox, lstSource As ListBox)
    Dim intListX As Integer
    Dim selectedItems As Collection
    Set selectedItems = New Collection
    For intListX = 0 To lstSource.ListCount - 1 'Start with 0, then iterate through the whole list
        If lstSource.Selected(intListX) Then
            lstDestination.AddItem lstSource.ItemData(intListX) 'Add items first

        End If
    Next intListX 'Increment intListX by 1
    Do While intListX >= 0
        If lstSource.Selected(intListX) Then
            selectedItems.Add intListX 'Add the items to be removed to a collection, in reverse order
        End If
        intListX = intListX - 1
    Loop
    Dim iterator As Variant
    For Each iterator In selectedItems
        lstSource.RemoveItem iterator 'And then remove them
    Next iterator
End Sub
</code>```

Complexities include: removing an item from a list box deselects all items, so you should store the selected items in a collection. Also, you need to remove items in reverse order, since removing one changes the index (number) for each one with a higher index.

Title: Ms Access multi-select listbox mover

Body:
I have two list boxes (lfmVocabulary and lfmVocabularyAssign). They are both unbound along with the form and I'm having trouble achieving certain aspects of the code design.

Thus far, I am able to populate the first list form with the values through a query recordset, but I'm unable to transfer the items from one box to the other.

In an attempt to achieve this, I placed the code in a module as follows

Option Compare Database

Public Sub MoveListBoxItems(lfmVocabularyAssign As ListBox, _
lfmVocabulary As ListBox)

Dim intListX As Integer

For intListX = lfmVocabulary.ListCount = -1 To 0
    If lfmVocabulary.Selected(intListX) Then
     lfmVocabularyAssign.AddItem lfmVocabulary.List(intListX)
     lfmVocabulary.RemoveItem intListX
    End If
Next
End Sub

In the form, I have the following code:

Option Explicit

Dim db As Database
Dim rs As Recordset

Private Sub cmdAdd_Click()

MoveListBoxItems lfmVocabulary, lfmVocabularyAssign

End Sub

Private Sub cmdSelectAll1_Click()

    Dim n As Integer

    With Me.lfmVocabulary
        For n = 0 To .ListCount - 1
            .Selected(n) = True
        Next n
    End With

End Sub

Private Sub Form_Load()

    Set db = CurrentDb
    Set rs = db.OpenRecordset("qryVocabularyDefinitions")

    Me.lfmVocabulary.RowSource = ""
    Do Until rs.EOF
        Me.lfmVocabulary.AddItem rs!Vocabulary
        rs.MoveNext
    Loop

End Sub

I am kinda new to Access and coding in general and I've been scouring the Internet looking for a solution.

I would offer a thousand thanks to anyone that can help me :D

Body:
You've made multiple small errors and not accounted for some complexities, here's the correct code:

Public Sub MoveListBoxItems(lstDestination As ListBox, lstSource As ListBox)
    Dim intListX As Integer
    Dim selectedItems As Collection
    Set selectedItems = New Collection
    For intListX = 0 To lstSource.ListCount - 1 'Start with 0, then iterate through the whole list
        If lstSource.Selected(intListX) Then
            lstDestination.AddItem lstSource.ItemData(intListX) 'Add items first

        End If
    Next intListX 'Increment intListX by 1
    Do While intListX >= 0
        If lstSource.Selected(intListX) Then
            selectedItems.Add intListX 'Add the items to be removed to a collection, in reverse order
        End If
        intListX = intListX - 1
    Loop
    Dim iterator As Variant
    For Each iterator In selectedItems
        lstSource.RemoveItem iterator 'And then remove them
    Next iterator
End Sub

Complexities include: removing an item from a list box deselects all items, so you should store the selected items in a collection. Also, you need to remove items in reverse order, since removing one changes the index (number) for each one with a higher index.


问:
Android NotificationManager Makes Phone Reboot
Description:
Every time my application is ran on Android 4.4.4 the user's phone reboots really fast and no crash data is sent to Crashlytics.

When I say the user's phone reboots - it's like the fastest reboot I've seen.

Application works fine on:

4.1.1

6.0.1

Other Notes:

My friend reproduced the bug on his 4.4.4 device

The background service I create continues after the phone reboots (yes I use a bootReceiver)

Link to App on Google Play Store

When I remove the "addAction" code below, the application works fine:

```<code>public void startNotification(){
        final Intent hideNotificationIntent = new Intent(MainActivity.this, HideWallpaperNotificationService.class);
        final Intent stopIntent = new Intent(MainActivity.this, StopWallpaperService.class);
        final Intent wallpaperCyclerIntent = new Intent(MainActivity.this, MainActivity.class);

        alarmIntent = new Intent(this, SetWallpaperService.class);
        alarmIntent.putStringArrayListExtra(Constants.PREF_WALLPAPERS, mWallpapers);

        PendingIntent nextWallpaperPI = PendingIntent.getService(this.getApplicationContext(), 300, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent stopWallpaperPI = PendingIntent.getService(this.getApplicationContext(), 300, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent showApp = PendingIntent.getActivity(this.getApplicationContext(), 300, wallpaperCyclerIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent hideNotification = PendingIntent.getService(this.getApplicationContext(), 300, hideNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        //Button
        NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(R.drawable.ic_stop_white_18dp, "Stop", stopWallpaperPI).build();
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_arrow_forward_white_24dp, "Next", nextWallpaperPI).build();
        NotificationCompat.Action removeAction = new NotificationCompat.Action.Builder(R.drawable.ic_clear_white_18dp, "Hide", hideNotification).build();

        Bitmap original;
        if(lastSelected == -1)
            original = BitmapFactory.decodeFile(mWallpapers.get(0));
        else
            original = BitmapFactory.decodeFile(mWallpapers.get(lastSelected));

        mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_fit)
                        .setLargeIcon(original)
                        .setWhen(0)
                        .setColor(ContextCompat.getColor(this.getApplicationContext(), R.color.colorPrimary))
                        .setContentTitle("Wallpaper Cycler")
                        .setContentText("Click to open")
                        .setContentIntent(showApp)
                        .addAction(stopAction)
                        .addAction(nextAction)
                        .addAction(removeAction);

        notificationManager = (NotificationManager) getSystemService(MainActivity.this.NOTIFICATION_SERVICE);
        Notification n;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            n = mBuilder.build();
        }else{
            n = mBuilder.getNotification();
        }
        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        try{
            notificationManager.notify(Constants.NOTIFICATION_ID, n);
        }catch(Exception e){Log.e(TAG,"Error notifying");}
    }
</code>```

答:
The problem was the Bitmaps were too large so I used the below function to resize them.</p>

```<code>    Bitmap original;
    if(lastSelected == -1)
        original = BitmapFactory.decodeFile(mWallpapers.get(0));
    else
        original = BitmapFactory.decodeFile(mWallpapers.get(lastSelected));

    original = returnBitmap(original,150,320);

public Bitmap returnBitmap(Bitmap originalImage, int width, int height){
    Bitmap background = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888);

    float originalWidth = originalImage.getWidth();
    float originalHeight = originalImage.getHeight();

    Canvas canvas = new Canvas(background);

    float scale = width / originalWidth;

    float xTranslation = 0.0f;
    float yTranslation = (height - originalHeight * scale) / 2.0f;

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);

    canvas.drawBitmap(originalImage, transformation, paint);

    return background;
}
</code>```

Body:
Description:
Every time my application is ran on Android 4.4.4 the user's phone reboots really fast and no crash data is sent to Crashlytics.

When I say the user's phone reboots - it's like the fastest reboot I've seen.

Application works fine on:

4.1.1

6.0.1

Other Notes:

My friend reproduced the bug on his 4.4.4 device

The background service I create continues after the phone reboots (yes I use a bootReceiver)

Link to App on Google Play Store

When I remove the "addAction" code below, the application works fine:

public void startNotification(){
        final Intent hideNotificationIntent = new Intent(MainActivity.this, HideWallpaperNotificationService.class);
        final Intent stopIntent = new Intent(MainActivity.this, StopWallpaperService.class);
        final Intent wallpaperCyclerIntent = new Intent(MainActivity.this, MainActivity.class);

        alarmIntent = new Intent(this, SetWallpaperService.class);
        alarmIntent.putStringArrayListExtra(Constants.PREF_WALLPAPERS, mWallpapers);

        PendingIntent nextWallpaperPI = PendingIntent.getService(this.getApplicationContext(), 300, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent stopWallpaperPI = PendingIntent.getService(this.getApplicationContext(), 300, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent showApp = PendingIntent.getActivity(this.getApplicationContext(), 300, wallpaperCyclerIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent hideNotification = PendingIntent.getService(this.getApplicationContext(), 300, hideNotificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        //Button
        NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(R.drawable.ic_stop_white_18dp, "Stop", stopWallpaperPI).build();
        NotificationCompat.Action nextAction = new NotificationCompat.Action.Builder(R.drawable.ic_arrow_forward_white_24dp, "Next", nextWallpaperPI).build();
        NotificationCompat.Action removeAction = new NotificationCompat.Action.Builder(R.drawable.ic_clear_white_18dp, "Hide", hideNotification).build();

        Bitmap original;
        if(lastSelected == -1)
            original = BitmapFactory.decodeFile(mWallpapers.get(0));
        else
            original = BitmapFactory.decodeFile(mWallpapers.get(lastSelected));

        mBuilder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.ic_stat_fit)
                        .setLargeIcon(original)
                        .setWhen(0)
                        .setColor(ContextCompat.getColor(this.getApplicationContext(), R.color.colorPrimary))
                        .setContentTitle("Wallpaper Cycler")
                        .setContentText("Click to open")
                        .setContentIntent(showApp)
                        .addAction(stopAction)
                        .addAction(nextAction)
                        .addAction(removeAction);

        notificationManager = (NotificationManager) getSystemService(MainActivity.this.NOTIFICATION_SERVICE);
        Notification n;
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN){
            n = mBuilder.build();
        }else{
            n = mBuilder.getNotification();
        }
        n.flags |= Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
        try{
            notificationManager.notify(Constants.NOTIFICATION_ID, n);
        }catch(Exception e){Log.e(TAG,"Error notifying");}
    }

Body:
The problem was the Bitmaps were too large so I used the below function to resize them.

    Bitmap original;
    if(lastSelected == -1)
        original = BitmapFactory.decodeFile(mWallpapers.get(0));
    else
        original = BitmapFactory.decodeFile(mWallpapers.get(lastSelected));

    original = returnBitmap(original,150,320);

public Bitmap returnBitmap(Bitmap originalImage, int width, int height){
    Bitmap background = Bitmap.createBitmap((int)width, (int)height, Bitmap.Config.ARGB_8888);

    float originalWidth = originalImage.getWidth();
    float originalHeight = originalImage.getHeight();

    Canvas canvas = new Canvas(background);

    float scale = width / originalWidth;

    float xTranslation = 0.0f;
    float yTranslation = (height - originalHeight * scale) / 2.0f;

    Matrix transformation = new Matrix();
    transformation.postTranslate(xTranslation, yTranslation);
    transformation.preScale(scale, scale);

    Paint paint = new Paint();
    paint.setFilterBitmap(true);

    canvas.drawBitmap(originalImage, transformation, paint);

    return background;
}


问:
How to select pdf page using bookmark in pdf box?
Sorry i am new to PDF box and was looking for a solution on how to get a specific pdf page using the bookmark name? Like the below code snippet am trying to loop all the pages but stuck to link the book mark with the page i need. Can any one please help?</p>

```<code>import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;

public class PDFLoader {

    public static void main(String[] args) throws InvalidPasswordException, IOException, PrinterException {

          File file = new File("d:\\pdf\\sample.pdf");
          PDDocument document = PDDocument.load(file);
          PDPage page01 = document.getDocumentCatalog().getPages().get(0);
          PDPage page02 = document.getDocumentCatalog().getPages().get(1);

          PDDocumentOutline outline =  document.getDocumentCatalog().getDocumentOutline();
          printBookmark(outline, "");
          PDDocument doc = new PDDocument();
          doc.addPage(page01);
          doc.addPage(page02);
          doc.save("d:\\pdf\\newSample.pdf");
          doc.close();

    }

public static PDPage getBookmark(PDOutlineNode bookmark, String indentation) throws IOException
    {
        PDOutlineItem current = bookmark.getFirstChild();
        while (current != null)

        {
            System.out.println(indentation + current.getTitle());

            if (current.getAction() instanceof PDActionGoTo)
            {
                PDActionGoTo gta = (PDActionGoTo) current.getAction();
                if (gta.getDestination() instanceof PDPageDestination)
                {

                    if(current.getTitle().equals("MyBookMark")){

                        PDPageDestination pd = (PDPageDestination) current.getDestination();
                        System.out.println("Destination page: " + pd.retrievePageNumber());
                        return pd.getPage();

                        }
                }
            }

            getBookmark(current, indentation + "    ");
            current = current.getNextSibling();

            }

        return null;
    }

//Stack Trace
    Exception in thread "main" java.lang.NullPointerException
    at com.mypackage.PDFLoader.getBookmark(PDFLoader.java:67)
    at com.mypackage.PDFLoader.main(PDFLoader.java:40)
</code>```

答:
It turns out that in your PDF the page destination is not in the bookmark's destination entry, but in the bookmark's action entry (yes, PDF makes it possible to have two ways to do the same thing). Add this to your code:</p>

```<code>if (current.getDestination() instanceof PDPageDestination)
{
    PDPageDestination pd = (PDPageDestination) current.getDestination();
    System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
    return pd.getPage();
}
if (current.getAction() instanceof PDActionGoTo)
{
    PDActionGoTo gta = (PDActionGoTo) current.getAction();
    if (gta.getDestination() instanceof PDPageDestination)
    {
        PDPageDestination pd = (PDPageDestination) gta.getDestination();
        System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
        return pd.getPage();
    }
}
</code>```

Body:
Sorry i am new to PDF box and was looking for a solution on how to get a specific pdf page using the bookmark name? Like the below code snippet am trying to loop all the pages but stuck to link the book mark with the page i need. Can any one please help?

import java.awt.print.PrinterException;
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.cos.COSObject;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem;
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode;

public class PDFLoader {

    public static void main(String[] args) throws InvalidPasswordException, IOException, PrinterException {

          File file = new File("d:\\pdf\\sample.pdf");
          PDDocument document = PDDocument.load(file);
          PDPage page01 = document.getDocumentCatalog().getPages().get(0);
          PDPage page02 = document.getDocumentCatalog().getPages().get(1);

          PDDocumentOutline outline =  document.getDocumentCatalog().getDocumentOutline();
          printBookmark(outline, "");
          PDDocument doc = new PDDocument();
          doc.addPage(page01);
          doc.addPage(page02);
          doc.save("d:\\pdf\\newSample.pdf");
          doc.close();

    }

public static PDPage getBookmark(PDOutlineNode bookmark, String indentation) throws IOException
    {
        PDOutlineItem current = bookmark.getFirstChild();
        while (current != null)

        {
            System.out.println(indentation + current.getTitle());

            if (current.getAction() instanceof PDActionGoTo)
            {
                PDActionGoTo gta = (PDActionGoTo) current.getAction();
                if (gta.getDestination() instanceof PDPageDestination)
                {

                    if(current.getTitle().equals("MyBookMark")){

                        PDPageDestination pd = (PDPageDestination) current.getDestination();
                        System.out.println("Destination page: " + pd.retrievePageNumber());
                        return pd.getPage();

                        }
                }
            }

            getBookmark(current, indentation + "    ");
            current = current.getNextSibling();

            }

        return null;
    }

//Stack Trace
    Exception in thread "main" java.lang.NullPointerException
    at com.mypackage.PDFLoader.getBookmark(PDFLoader.java:67)
    at com.mypackage.PDFLoader.main(PDFLoader.java:40)

Body:
It turns out that in your PDF the page destination is not in the bookmark's destination entry, but in the bookmark's action entry (yes, PDF makes it possible to have two ways to do the same thing). Add this to your code:

if (current.getDestination() instanceof PDPageDestination)
{
    PDPageDestination pd = (PDPageDestination) current.getDestination();
    System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
    return pd.getPage();
}
if (current.getAction() instanceof PDActionGoTo)
{
    PDActionGoTo gta = (PDActionGoTo) current.getAction();
    if (gta.getDestination() instanceof PDPageDestination)
    {
        PDPageDestination pd = (PDPageDestination) gta.getDestination();
        System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
        return pd.getPage();
    }
}


问:
Three.js plane doesn't cast shadow
I'm stacking a plane and a sphere on top of a bigger plane, as seen in the following image

From WebGL inspector, it seems all three object are drawn in the shadowmap, but only the sphere is effectively appearing in the shadowmap, causing the smaller plane to never cast a shadow on the bigger one

Here's the scene construction

```<code>renderer.shadowMap.enabled = true

camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 5000);
camera.position.z = 600;
window.controls = new THREE.OrbitControls(camera, renderer.domElement);

light = new THREE.SpotLight(0xffffff, 1, 0, Math.PI / 2);
light.position.set(1, 1000, 1);
light.castShadow = true;
light.shadow = new THREE.LightShadow(new THREE.PerspectiveCamera(50, 1, 1, 5000));

scene.add(light);

var planeGeometry = new THREE.PlaneGeometry( innerWidth * 0.5, innerHeight * 0.5, 10, 10);
var plane = new THREE.Mesh( planeGeometry, new THREE.MeshPhongMaterial({ color: 0xffcccc }));
plane.rotation.x = -Math.PI / 2;
plane.castShadow = true;
plane.receiveShadow = true;
scene.add(plane);

var sphere = new THREE.SphereGeometry(100, 16, 8);
var spheremesh = new THREE.Mesh(sphere, new THREE.MeshPhongMaterial( ));
spheremesh.position.y = 200;
spheremesh.castShadow = true;
spheremesh.receiveShadow = true;
scene.add(spheremesh);

var planeGeometry1 = new THREE.PlaneGeometry( innerWidth, innerHeight, 10, 10);
var plane1 = new THREE.Mesh( planeGeometry1, new THREE.MeshPhongMaterial( ));
plane1.position.y = -250;
plane1.rotation.x = -Math.PI / 2;
plane1.castShadow = true;
plane1.receiveShadow = true;
scene.add(plane1);
</code>```

答:
By default, three.js culls front faces when generating shadow maps.

That means only back faces (from the point of view of the light) cast shadows. Culling front faces of your plane leaves nothing left to cast a shadow.

So one option is to replace your PlaneGeometry with a thin BoxGeometry, which has depth.

A second option is to set

material.shadowSide = THREE.DoubleSide;
```

In this case, your plane will cast a shadow, but there may be self-shadowing artifacts since you have both plane.castShadow = true and plane.receiveShadow = true.

Typically, the first option is the best option.

three.js r.151

Title: Three.js plane doesn't cast shadow

Body:
I'm stacking a plane and a sphere on top of a bigger plane, as seen in the following image

From WebGL inspector, it seems all three object are drawn in the shadowmap, but only the sphere is effectively appearing in the shadowmap, causing the smaller plane to never cast a shadow on the bigger one

Here's the scene construction

renderer.shadowMap.enabled = true

camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 1, 5000);
camera.position.z = 600;
window.controls = new THREE.OrbitControls(camera, renderer.domElement);

light = new THREE.SpotLight(0xffffff, 1, 0, Math.PI / 2);
light.position.set(1, 1000, 1);
light.castShadow = true;
light.shadow = new THREE.LightShadow(new THREE.PerspectiveCamera(50, 1, 1, 5000));

scene.add(light);

var planeGeometry = new THREE.PlaneGeometry( innerWidth * 0.5, innerHeight * 0.5, 10, 10);
var plane = new THREE.Mesh( planeGeometry, new THREE.MeshPhongMaterial({ color: 0xffcccc }));
plane.rotation.x = -Math.PI / 2;
plane.castShadow = true;
plane.receiveShadow = true;
scene.add(plane);

var sphere = new THREE.SphereGeometry(100, 16, 8);
var spheremesh = new THREE.Mesh(sphere, new THREE.MeshPhongMaterial( ));
spheremesh.position.y = 200;
spheremesh.castShadow = true;
spheremesh.receiveShadow = true;
scene.add(spheremesh);

var planeGeometry1 = new THREE.PlaneGeometry( innerWidth, innerHeight, 10, 10);
var plane1 = new THREE.Mesh( planeGeometry1, new THREE.MeshPhongMaterial( ));
plane1.position.y = -250;
plane1.rotation.x = -Math.PI / 2;
plane1.castShadow = true;
plane1.receiveShadow = true;
scene.add(plane1);

Body:
By default, three.js culls front faces when generating shadow maps.

That means only back faces (from the point of view of the light) cast shadows. Culling front faces of your plane leaves nothing left to cast a shadow.

So one option is to replace your PlaneGeometry with a thin BoxGeometry, which has depth.

A second option is to set

material.shadowSide = THREE.DoubleSide;

In this case, your plane will cast a shadow, but there may be self-shadowing artifacts since you have both plane.castShadow = true and plane.receiveShadow = true.

Typically, the first option is the best option.

three.js r.151


答:
You can query as below:</p>

```<code>;With cte as (
    SELECT distinct clientid, a.releaseid FROM #input x
    cross apply (select distinct releaseid from #input) a
) Select c.*, i.[Status], i.ParentSignature from cte c
    left join #input i
    on c.clientid = i.clientid
    and c.releaseid = i.releaseid
</code>```

Title: How to insert dummy rows for distinct ids in a result set

Body:
I have a result set as follows:

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    5059 |        68 | Yes    | ad              |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+

In the above result set, there are 3 distinct values in ReleaseID column such as 68, 70 and 71.
Only one child id  (5410) has records corresponding to all the releaseids.

My requirement is to get an output result set in which there are records for each child for each release id with blank values for remaining columns.
The number of maximum distinct releaseids can vary. In this example, there are 3 releaseids.

Expected output:-

+---------+-----------+--------+-----------------+
| ChildID | ReleaseID | Status | ParentSignature |
+---------+-----------+--------+-----------------+
|    1152 |        68 | Yes    |                 |
|    1152 |        70 | Yes    |                 |
|    1152 |        71 |        |                 |
|    5059 |        68 | Yes    | ad              |
|    5059 |        70 |        |                 |
|    5059 |        71 |        |                 |
|    5410 |        68 | Yes    | 111             |
|    5410 |        70 | Yes    | 111             |
|    5410 |        71 | Yes    |                 |
+---------+-----------+--------+-----------------+

Body:
You can query as below:

;With cte as (
    SELECT distinct clientid, a.releaseid FROM #input x
    cross apply (select distinct releaseid from #input) a
) Select c.*, i.[Status], i.ParentSignature from cte c
    left join #input i
    on c.clientid = i.clientid
    and c.releaseid = i.releaseid