问:
Long Numeric to Character in SAS
When I try to convert a 10 digit number which is stored as 8. into a character using put(,8.) it gives me the character value as something like 1.2345e10. I want the character string to be as 1234567890. Can someone please help ?</p>

答:
SAS stores numbers as IEEE 64bit floating point numbers.  So when you see that the LENGTH of the variable is 8 that just means you are storing the full 8 bytes of the floating point representation. If the length is less than 8 then you will lose some of the ability to store more digits of precision, but when it pulls the data from the dataset to be used by a data step or proc it will always convert it back to the full 64 bit IEEE format.

The LENGTH that you use to store the data has little to do with how many characters you should use to display the value for humans to read.  How to display the value is controlled by the FORMAT that you use.  What format to use will depend on the type of values your variable will contain.

So if you know your values are always integers and the maximum value is 9,999,999,999 then you can use the format 10. (also known as F10.).

```<code>charvar= put(numvar,F10.);
</code>```

Title: Long Numeric to Character in SAS

Body:
SAS stores numbers as IEEE 64bit floating point numbers.  So when you see that the LENGTH of the variable is 8 that just means you are storing the full 8 bytes of the floating point representation. If the length is less than 8 then you will lose some of the ability to store more digits of precision, but when it pulls the data from the dataset to be used by a data step or proc it will always convert it back to the full 64 bit IEEE format.

The LENGTH that you use to store the data has little to do with how many characters you should use to display the value for humans to read.  How to display the value is controlled by the FORMAT that you use.  What format to use will depend on the type of values your variable will contain.

So if you know your values are always integers and the maximum value is 9,999,999,999 then you can use the format 10. (also known as F10.).

charvar= put(numvar,F10.);


来源: stackexchange

问:
Accessing function return value through nested object inside IIFE
I'm trying to set an object value to a function call using another value (array) as its parameter, however, for some reason the value comes back as undefined, I'm  then trying access that value right after that. It's inside an IIFE.

I am unsure why this is happening because to the best of my knowledge the scoping is okay and the value should be initialized and executed by that time?

Here's a simplified example:

```<code>(function(){
 var minefield = [1,2,3,'M',4,5,6];

function findMachine(minefieldMachine) {
  return minefieldMachine === 'M';
}

  var terrain = {

    start:{initialMachienLocation:minefield.findIndex(findMachine)},
    currentMutable:{mutableIndex:terrain.start.initialMachineLocation}//Error: "Uncaught type error cannot read property 'start' of undefined"
//Why isn't the above accessing the value declared in terrain.start.initialMachineLocation through the function call?

  }
}());
</code>```

However, doing this works, out of context from above:

```<code>function findMachine(minefield){return minefield === 'M'}
[1,2,3,'M',4,5,6].findIndex(findMachine);
//above returns the proper index value, 3.
</code>```

答:
This has nothing to do with the function.

What you are attempting to do is, essentially, this:

```<code>var foo = {
    a: 1,
    b: foo.a
}
</code>```

You need to consider the order of operations.

The object literal constructs an object which is then assigned to the variable foo.

… except that while the object is being constructed, you are trying to read the value of foo. It doesn't have one yet, so this fails.

You need to do this in two steps.

```<code>var foo = {
    a: 1,
}
foo.b = foo.a;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to set an object value to a function call using another value (array) as its parameter, however, for some reason the value comes back as undefined, I'm  then trying access that value right after that. It's inside an IIFE.

I am unsure why this is happening because to the best of my knowledge the scoping is okay and the value should be initialized and executed by that time?

Here's a simplified example:

(function(){
 var minefield = [1,2,3,'M',4,5,6];

function findMachine(minefieldMachine) {
  return minefieldMachine === 'M';
}

  var terrain = {

    start:{initialMachienLocation:minefield.findIndex(findMachine)},
    currentMutable:{mutableIndex:terrain.start.initialMachineLocation}//Error: "Uncaught type error cannot read property 'start' of undefined"
//Why isn't the above accessing the value declared in terrain.start.initialMachineLocation through the function call?

  }
}());

However, doing this works, out of context from above:

function findMachine(minefield){return minefield === 'M'}
[1,2,3,'M',4,5,6].findIndex(findMachine);
//above returns the proper index value, 3.

Body:
This has nothing to do with the function.

What you are attempting to do is, essentially, this:

var foo = {
    a: 1,
    b: foo.a
}

You need to consider the order of operations.

The object literal constructs an object which is then assigned to the variable foo.

… except that while the object is being constructed, you are trying to read the value of foo. It doesn't have one yet, so this fails.

You need to do this in two steps.

var foo = {
    a: 1,
}
foo.b = foo.a;


问:
jQuery unbind/disable navigation link
Hy,

a really stupid problem, but i cant get it to work:

I have some function that binds the click of my navigation. When a link is clicker it gets the class "active". So my idea was that i just say:

```<code><a id="link1" class="main">link1</a>
<a id="link2" class="main">link2</a>
<a id="link3" class="main">link3</a>

$('a.main').bind('click', function(){
$(this).removeClass('active');
//some code
$(this).addClass('active');
}
</code>```

So far thats working. My element gets the active class when it´s hit and removes when another has been clicked. My idea now was just simple unbind all active links (otherwise some double reloading happends by paranoid 10000 clicks on my navigation =)

```<code>§('a.active').unbind('click');
</code>```

I also specify for each element in my navigation a special event:

```<code>$('a#link1').bind('click', function() {
$img.fadeOut('slow', function() {
      $('#bg div table tr td').addClass('loading');
        $img.attr('src', 'images/image.jpg');
     });
});
</code>```

Now what happends is, that if i click an element in my navigation (accordion), the thing slides down, gets the active class (still keeps the main class):

```<code><a id="link1" class="main active">link1</a>
</code>```

When i click another element in the navigation, this one closes and the active class is removed.

BUT when i go back to that link before, it´s nnot clickable anymore? So, i guess jQuery unbinds the click event for ever from an element that has been active. Sounds a bit stupid and unlogic to me...

Maybe is there a way to enable/disabel these. So a function that checks if the element has an active class it should be disabled. Or is the problem the "main" class beside the "active" class...

Any idea?

答:
I think you're not understand how jQuery event binding works. Your question isn't very clear and there are some wrong assertions/assumptions in there. Or maybe I'm just not understand the question :)

Anyway, if you're just trying to stop repeat clicks, I'd go for something like

```<code>$('a:not(.active)').live('click', function(){
    $(this).siblings().removeClass('active');
    $(this).addClass('active');

    // ...do whatever here
});
</code>```

Demo here.

ContentLicense: CC BY-SA 2.5

Title: jQuery unbind/disable navigation link

Body:
Hy,

a really stupid problem, but i cant get it to work:

I have some function that binds the click of my navigation. When a link is clicker it gets the class "active". So my idea was that i just say:

link1
link2
link3

$('a.main').bind('click', function(){
$(this).removeClass('active');
//some code
$(this).addClass('active');
}

So far thats working. My element gets the active class when it´s hit and removes when another has been clicked. My idea now was just simple unbind all active links (otherwise some double reloading happends by paranoid 10000 clicks on my navigation =)

§('a.active').unbind('click');

I also specify for each element in my navigation a special event:

$('a#link1').bind('click', function() {
$img.fadeOut('slow', function() {
      $('#bg div table tr td').addClass('loading');
        $img.attr('src', 'images/image.jpg');
     });
});

Now what happends is, that if i click an element in my navigation (accordion), the thing slides down, gets the active class (still keeps the main class):

link1

When i click another element in the navigation, this one closes and the active class is removed.

BUT when i go back to that link before, it´s nnot clickable anymore? So, i guess jQuery unbinds the click event for ever from an element that has been active. Sounds a bit stupid and unlogic to me...

Maybe is there a way to enable/disabel these. So a function that checks if the element has an active class it should be disabled. Or is the problem the "main" class beside the "active" class...

Any idea?

Body:
I think you're not understand how jQuery event binding works. Your question isn't very clear and there are some wrong assertions/assumptions in there. Or maybe I'm just not understand the question :)

Anyway, if you're just trying to stop repeat clicks, I'd go for something like

$('a:not(.active)').live('click', function(){
    $(this).siblings().removeClass('active');
    $(this).addClass('active');

    // ...do whatever here
});

Demo here.


问:
How to pass a parameter to the child window from parent window using window.open
How to pass a parameter to the child window from parent window in Java Script by using window.open.

Please give me any idea.

答:
I originally tried this:

parent window:

```<code> var parms = {arg1: "arg1", arg2:"arg2"};
 var handle = window.open(url);
 // stringifyed to make sure the child window does
 //not try to access object by reference from child to parent.
 handle.window.parameters = JSON.stringify(parms);
</code>```

child window:

```<code>$(document).ready(function(){
    var args = JSON.parse( window.parameters);
    // and so on.
});
</code>```

The problem was that the value was occasionally being set before the child window was ready so when the child window was ready, it would be undefined.

So Instead, I used sessionStorage (note: this will not work cross domain.)

Parent:

```<code>// the user can cause more than one child window so I give storage a unique id.
var parms = JSON.stringify({arg1: "arg1", arg2:"arg2"});
var storageId = "parms" + String(Date.now());
sessionStorage.setItem(storageId, parms);
window.open(url + "?sid=" + storageId);
</code>```

This on the child:

```<code>$(document).ready(function(){
    var prmstr = window.location.search.split("=");
    var sid = prmstr[1];
    var args = JSON.parse(sessionStorage.getItem(sid));
    sessionStorage.removeItem(sid);
    // and so on
});
</code>```

Body:
I originally tried this:

parent window:

 var parms = {arg1: "arg1", arg2:"arg2"};
 var handle = window.open(url);
 // stringifyed to make sure the child window does
 //not try to access object by reference from child to parent.
 handle.window.parameters = JSON.stringify(parms);

child window:

$(document).ready(function(){
    var args = JSON.parse( window.parameters);
    // and so on.
});

The problem was that the value was occasionally being set before the child window was ready so when the child window was ready, it would be undefined.

So Instead, I used sessionStorage (note: this will not work cross domain.)

Parent:

// the user can cause more than one child window so I give storage a unique id.
var parms = JSON.stringify({arg1: "arg1", arg2:"arg2"});
var storageId = "parms" + String(Date.now());
sessionStorage.setItem(storageId, parms);
window.open(url + "?sid=" + storageId);

This on the child:

$(document).ready(function(){
    var prmstr = window.location.search.split("=");
    var sid = prmstr[1];
    var args = JSON.parse(sessionStorage.getItem(sid));
    sessionStorage.removeItem(sid);
    // and so on
});


问:
Error on javascript queryselector
I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.

Here the main javascript

```<code>function getParameterByName(name)
 {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
     return "";
  else
 return decodeURIComponent(results[1].replace(/\+/g, " "));
 }
</code>```

my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.

```<code><input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">
</code>```

I tried 2 functions call.

```<code>document.getElementByName("satisfaction_case_number").value = getParameterByName("case")
</code>```

and

```<code>document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")
</code>```

I have to say I'm kinda blind here. Any flag would be appreciated.

Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.

I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks

答:
```<code>setTimeout(function () {
  var input = document.querySelector('[id^="satisfaction_case_number"]');
  input.value = getParameterByName('case');
  input.dispatchEvent(new Event('change'));
}, 1000);
</code>```

or try to modify the code that creates HubSpot form:

```<code>hbspt.forms.create({
  // ...
  onFormReady: function () {
    var input = document.querySelector('[id^="satisfaction_case_number"]');
    input.value = getParameterByName('case');
    input.dispatchEvent(new Event('change'));
  }
});
</code>```

Title: Error on javascript queryselector

Body:
I'm trying to input an URL Parameter into a form input. When I'm trying to do it via the inspect console, everything seems fine. But when I load the page I got an error: Uncaught TypeError: Cannot set property 'value' of null.

Here the main javascript

function getParameterByName(name)
 {
  name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
  var regexS = "[\\?&]" + name + "=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
     return "";
  else
 return decodeURIComponent(results[1].replace(/\+/g, " "));
 }

my input looks like this... There is a part of the ID that randomly changes on reload, only satisfaction_case_number stay the same.

<input id="satisfaction_case_number-da4e00e8-dcf6-4efa-9f92-d9564432f979_2621" class="hs-input" type="text" name="satisfaction_case_number" value="" placeholder="" data-reactid=".hbspt-forms-0.0:$0.$satisfaction_case_number.0">

I tried 2 functions call.

document.getElementByName("satisfaction_case_number").value = getParameterByName("case")

and

document.querySelector('[id^="satisfaction_case_number"]').value = getParameterByName("case")

I have to say I'm kinda blind here. Any flag would be appreciated.

Here is the URL of my page : http://info.techo-bloc.com/customer-service-0?case=CAS-00745-Z0G5F8.

I'm trying to get : CAS-00745-Z0G5F8 into the input.
Thanks

Body:
setTimeout(function () {
  var input = document.querySelector('[id^="satisfaction_case_number"]');
  input.value = getParameterByName('case');
  input.dispatchEvent(new Event('change'));
}, 1000);

or try to modify the code that creates HubSpot form:

hbspt.forms.create({
  // ...
  onFormReady: function () {
    var input = document.querySelector('[id^="satisfaction_case_number"]');
    input.value = getParameterByName('case');
    input.dispatchEvent(new Event('change'));
  }
});


问:
converting a nested data frame containing multiple lists into a useable dataframe/tibble
I'm working with a package in R that spits out weather variables for a list of sites that I provide in a csv file. The data comes as a dataframe containing multiple lists, so one for each site. In each list for each site there is info on the site name, lat, long, altitude, and tile, the data for that site, which is a data frame containing 9 variables. It's probably best to just take a look at the output by running the code here:

```<code>library(tidyverse)
if(!require(devtools)){install.package(devtools)}
devtools::install_github("khufkens/daymetr")
library(daymetr)
</code>```

the 'my_sites.csv' below looks like this, where this is no column headings, just the site name and lat long (3 columns total):

```<code>Alpha 43.29515  -89.29077
Delta  44.14667 -121.34722

weather_by_site<-download_daymet_batch(file_location = '/Users/Jay/Desktop/my_sites.csv',
                      start = 2012,
                      end = 2016,
                      internal = TRUE)
</code>```

This gives you a better idea of what the output looks like:

```<code>str(weather_by_site)
</code>```

I'm looking to combine the output with the 9 weather variables with the site name and tile for each site. The goal is to run this same code but for >600 sites, and to be able to analyze the data in a neater looking data frame or tibble format. So basically I would have a data from 2012-2016 for one site, and all the sites would be binded together.

答:
Using purrr, we can loop through each result, grab the dataframe from the results, then push the other variables onto the end of that dataframe:</p>

```<code>library(dplyr)
library(purrr)

# write a function to do pull out the data frame
# then append the other values
tidyweather  <- function(x) {

    datadf  <- pluck(x, "data")
    datadf$site       <- x[[1]]
    datadf$lattitude  <- x[[2]]
    datadf$longitude  <- x[[3]]
    datadf$altitude   <- x[[4]]
    datadf$tile       <- x[[5]]

    return(datadf)
}

weather_df  <- weather_by_site %>%
    # run tidyweather() on each result and return one big data frame
    map_df(tidyweather)
</code>```

Body:
I'm working with a package in R that spits out weather variables for a list of sites that I provide in a csv file. The data comes as a dataframe containing multiple lists, so one for each site. In each list for each site there is info on the site name, lat, long, altitude, and tile, the data for that site, which is a data frame containing 9 variables. It's probably best to just take a look at the output by running the code here:

library(tidyverse)
if(!require(devtools)){install.package(devtools)}
devtools::install_github("khufkens/daymetr")
library(daymetr)

the 'my_sites.csv' below looks like this, where this is no column headings, just the site name and lat long (3 columns total):

Alpha 43.29515  -89.29077
Delta  44.14667 -121.34722

weather_by_site<-download_daymet_batch(file_location = '/Users/Jay/Desktop/my_sites.csv',
                      start = 2012,
                      end = 2016,
                      internal = TRUE)

This gives you a better idea of what the output looks like:

str(weather_by_site)

I'm looking to combine the output with the 9 weather variables with the site name and tile for each site. The goal is to run this same code but for >600 sites, and to be able to analyze the data in a neater looking data frame or tibble format. So basically I would have a data from 2012-2016 for one site, and all the sites would be binded together.

Body:
Using purrr, we can loop through each result, grab the dataframe from the results, then push the other variables onto the end of that dataframe:

library(dplyr)
library(purrr)

# write a function to do pull out the data frame
# then append the other values
tidyweather  <- function(x) {

    datadf  <- pluck(x, "data")
    datadf$site       <- x[[1]]
    datadf$lattitude  <- x[[2]]
    datadf$longitude  <- x[[3]]
    datadf$altitude   <- x[[4]]
    datadf$tile       <- x[[5]]

    return(datadf)
}

weather_df  <- weather_by_site %>%
    # run tidyweather() on each result and return one big data frame
    map_df(tidyweather)


问:
Calling javascript function inside jquery ajax response file code
I am trying to call date_cal() javascript function inside ajax response (wall_list.php).Every thing is fine am getting correct response. But its not calling date_cal() function.

main file:

$.ajax({

```<code>  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {

if(resp)
{
 //alert(resp);
  document.getElementById('wall_listdiv').innerHTML=resp;

}
</code>```

Wall_list.php

Some code...................

```<code>>   <td id="<?php print $key; ?>" class="tm_td" valign="top" colspan=2>
>

    <script language="JavaScript">
                                date_cal('<?php print $commentcreatetimearr[$key]; ?>','<?php print $key; ?>');
                                </script>

>       </td>
</code>```

Some code......................

it's not calling javascript there.

Can anyone explain how to all this function in response.

答:
for example

php:

```<code><?php echo $commentcreatetimearr[$key]; ?>
</code>```

js:

```<code>$.ajax({
  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {
  if(resp){
     $('#wall_listdiv').html(date_cal(resp));
  }
</code>```

Body:
I am trying to call date_cal() javascript function inside ajax response (wall_list.php).Every thing is fine am getting correct response. But its not calling date_cal() function.

main file:

$.ajax({

  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {

if(resp)
{
 //alert(resp);
  document.getElementById('wall_listdiv').innerHTML=resp;

}

Wall_list.php

Some code...................

>   <td id="<?php print $key; ?>" class="tm_td" valign="top" colspan=2>
>

>

Some code......................

it's not calling javascript there.

Can anyone explain how to all this function in response.

Body:
for example

php:

<?php echo $commentcreatetimearr[$key]; ?>

js:

$.ajax({
  url: 'wall_list.php',
  data:"dt_from="+dt_from+"&dt_to="+dt_to+"&week="+week+"&month="+month+"&dt_filter="+dt_filter+"&fan="+fan+"&gender="+gender+"&pageNumber="+pagenumber,
  type: 'POST',
success: function (resp) {
  if(resp){
     $('#wall_listdiv').html(date_cal(resp));
  }


问:
Excel formula quotation symbol meaning
what do the quotation symbols mean in this equation? I cant find a simple straight answer. </p>

```<code>=IF(K25="","",L24+K25)
</code>```

答: Quotes with nothing in them, "", indicates nothing, or a blank cell. The formula says that if cell k25 is empty, then return no value. If k25 is not empty, then perform the calcuation l24+l25.</p>

Title: Excel formula quotation symbol meaning

Body:
what do the quotation symbols mean in this equation? I cant find a simple straight answer.

=IF(K25="","",L24+K25)


问:
GET friendships/show with rtweet
I tried to find a way to use the rtweet package to perform a request to GET friendships/show from the Twitter REST API, in order to analyse the relationship between two users. However, I could not make it work (I did find lookup_friendships(), but it does not do what I want). Is it possible to do that with rtweet, and if so, how?

答:
This feature has been added to rtweet, so there should be at least somewhat reasonable access to the "friendships/show" API via lookup_friendships()–and, bonus, it just got accepted in version 0.6.0 now on CRAN now!

Required inputs are source and target (can be screen names or user IDs). If only one user is provided to either source or target, then any number of users–save Twitter API rate limits–can be passed in the other parameter.

```<code>fds <- lookup_friendships(
  source = "realDonaldTrump",
  target = c("DRUDGE_REPORT", "seanhannity", "HuffPost", "maddow", "cnn")
)
> fds
# A tibble: 60 x 4
   relationship            user       variable           value
          <chr>           <chr>          <chr>           <chr>
 1       source   DRUDGE_REPORT             id        25073877
 2       source   DRUDGE_REPORT         id_str        25073877
 3       source   DRUDGE_REPORT    screen_name realDonaldTrump
 4       source   DRUDGE_REPORT      following            TRUE
 5       source   DRUDGE_REPORT    followed_by           FALSE
 6       source   DRUDGE_REPORT live_following           FALSE
 7       source   DRUDGE_REPORT         can_dm           FALSE
 8       target realDonaldTrump             id        14669951
 9       target realDonaldTrump         id_str        14669951
10       target realDonaldTrump    screen_name   DRUDGE_REPORT
# ... with 50 more rows
>
</code>```

It's also possible to specify more than one user in both source and target parameters. However, if the length of both parameters is greater than 1, then the vectors must be of equal length.

```<code>## vector of multiple users
usrs <- c(
  "realDonaldTrump", "DRUDGE_REPORT", "seanhannity", "HuffPost", "maddow", "cnn"
)
fds <- lookup_friendships(
  source = usrs,
  target = usrs
)
> fds
# A tibble: 72 x 4
   relationship            user       variable           value
          <chr>           <chr>          <chr>           <chr>
 1       source realDonaldTrump             id        25073877
 2       source realDonaldTrump         id_str        25073877
 3       source realDonaldTrump    screen_name realDonaldTrump
 4       source realDonaldTrump      following           FALSE
 5       source realDonaldTrump    followed_by           FALSE
 6       source realDonaldTrump live_following           FALSE
 7       source realDonaldTrump         can_dm            TRUE
 8       target realDonaldTrump             id        25073877
 9       target realDonaldTrump         id_str        25073877
10       target realDonaldTrump    screen_name realDonaldTrump
# ... with 62 more rows
</code>```

There hasn't been a lot of time to test this yet. If you run into problems, try setting parse = FALSE. You'll be left to wrangling the returned data by yourself, but it might help avoid errors in internal parsing.

```<code>fds <- lookup_friendships(
      source = usrs,
      target = usrs,
      parse = FALSE
    )
> str(fds, 3)
List of 6
 $ realDonaldTrump:List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ DRUDGE_REPORT  :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ seanhannity    :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ HuffPost       :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ maddow         :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ cnn            :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
</code>```

Title: GET friendships/show with rtweet

Body:
This feature has been added to rtweet, so there should be at least somewhat reasonable access to the "friendships/show" API via lookup_friendships()–and, bonus, it just got accepted in version 0.6.0 now on CRAN now!

Required inputs are source and target (can be screen names or user IDs). If only one user is provided to either source or target, then any number of users–save Twitter API rate limits–can be passed in the other parameter.

fds <- lookup_friendships(
  source = "realDonaldTrump",
  target = c("DRUDGE_REPORT", "seanhannity", "HuffPost", "maddow", "cnn")
)
> fds
# A tibble: 60 x 4
   relationship            user       variable           value
          <chr>           <chr>          <chr>           <chr>
 1       source   DRUDGE_REPORT             id        25073877
 2       source   DRUDGE_REPORT         id_str        25073877
 3       source   DRUDGE_REPORT    screen_name realDonaldTrump
 4       source   DRUDGE_REPORT      following            TRUE
 5       source   DRUDGE_REPORT    followed_by           FALSE
 6       source   DRUDGE_REPORT live_following           FALSE
 7       source   DRUDGE_REPORT         can_dm           FALSE
 8       target realDonaldTrump             id        14669951
 9       target realDonaldTrump         id_str        14669951
10       target realDonaldTrump    screen_name   DRUDGE_REPORT
# ... with 50 more rows
>

It's also possible to specify more than one user in both source and target parameters. However, if the length of both parameters is greater than 1, then the vectors must be of equal length.

## vector of multiple users
usrs <- c(
  "realDonaldTrump", "DRUDGE_REPORT", "seanhannity", "HuffPost", "maddow", "cnn"
)
fds <- lookup_friendships(
  source = usrs,
  target = usrs
)
> fds
# A tibble: 72 x 4
   relationship            user       variable           value
          <chr>           <chr>          <chr>           <chr>
 1       source realDonaldTrump             id        25073877
 2       source realDonaldTrump         id_str        25073877
 3       source realDonaldTrump    screen_name realDonaldTrump
 4       source realDonaldTrump      following           FALSE
 5       source realDonaldTrump    followed_by           FALSE
 6       source realDonaldTrump live_following           FALSE
 7       source realDonaldTrump         can_dm            TRUE
 8       target realDonaldTrump             id        25073877
 9       target realDonaldTrump         id_str        25073877
10       target realDonaldTrump    screen_name realDonaldTrump
# ... with 62 more rows

There hasn't been a lot of time to test this yet. If you run into problems, try setting parse = FALSE. You'll be left to wrangling the returned data by yourself, but it might help avoid errors in internal parsing.

fds <- lookup_friendships(
      source = usrs,
      target = usrs,
      parse = FALSE
    )
> str(fds, 3)
List of 6
 $ realDonaldTrump:List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ DRUDGE_REPORT  :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ seanhannity    :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ HuffPost       :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ maddow         :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7
 $ cnn            :List of 1
  ..$ relationship:List of 2
  .. ..$ source:List of 16
  .. ..$ target:List of 7


问:
What is the proper way to perform multiple insert queries in multiple table in a relational mysql database?
I have a scenario, that how will I ensure if all of my insert queries works properly. I am using PHP for the backend coding and mysql for my database. Below I am describing my problem briefly.

I have two tables. One table is for login_details and other table is for personal_details. My table structure is here.

Table login_details here user_id is the unique primary key and sl_num is auto incremental:

th{
  padding: 3px;
  border: 1px solid black;
}

td{
  padding: 3px;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
   <thead>
      <th>sl_num</th>
      <th>user_id</th>
      <th>email</th>
      <th>password</th>
   </thead>
   <tbody>
      <tr>
        <td>1</td>
        <td>123</td>
        <td>daniel@gmail.com</td>
        <td>5567</td>
      </tr>
      <tr>
        <td>2</td>
        <td>246</td>
        <td>lucy@yahoo.com</td>
        <td>9908</td>
      </tr>
   </tbody>
</table>
    </code>```

and my second table is personal_details. Here also the user_id is the primary key and this key also maintain relation among the two tables and sl_num is auto incremental:

th{
  padding: 3px;
  border: 1px solid black;
}

td{
  padding: 3px;
  border: 1px solid black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table>
   <thead>
      <th>sl_num</th>
      <th>user_id</th>
      <th>name</th>
      <th>address</th>
      <th>age</th>
   </thead>
   <tbody>
      <tr>
        <td>1</td>
        <td>123</td>
        <td>Daniel</td>
        <td>San Francisco</td>
        <td>23</td>
      </tr>
      <tr>
        <td>2</td>
        <td>246</td>
        <td>Lucy</td>
        <td>London</td>
        <td>27</td>
      </tr>
   </tbody>
</table></code>```

And, I use this code to insert values in these tables.

```<code><?php
   $user_id = uniqid();
   $email = $_POST['email'];
   $password = $_POST['password'];
   $name = $_POST['name'];
   $address = $_POST['address'];
   $age = $_POST['age'];

   $con = mysqli_connect('localhost', 'username', 'password',
                         'user_db');

   $query = "INSERT INTO `login_details` (`user_id`, `email`,
             `password`) VALUES ('$user_id', '$email', '$password')";
   mysqli_query($con,$query);

   $query2 = "INSERT INTO `personal_details` (`user_id`, `name`,
             `address`, `age`) VALUES ('$user_id', '$name', '$address',
             '$age')";
   mysqli_query($con,$query);

   echo 'User created successfully';?>
</code>```

But a wired problem happened once. A third user name 'John Doe' trying to create his account. The details of the personal_details table inserted successfully but the for some reasons the details of the login_details is not inserted. So, the user 'John Doe' has personal information on the table but as he doesn't have any login information so, he can't login.

So, what is the best solution of these kinds of multi insert situation. How can I prevent this situation. It means, if one row inserted into login_details then the system has to ensure that the relative row is also inserted into personal_details table. If two are inserted successfully then the transaction happened or if one row inserted and other not then the system will automatically discarded the inserted row and show a fail message.

答:
The reason the query failed is probably because you're not escaping any of the variables in an SQL context. That means that if there's a ' somewhere in one of the strings, the SQL statement becomes invalid. This is known as an SQL injection attack and can quickly leave your application vulnerable to attacks.

A common way of mitigating these attacks is to use a prepared statement instead.

That would at least allow you to cancel the second query if the first one fails. But what if the second one fails (for some reason when you've used a proper .. this shouldn't really happen if you've escaped your variables properly, but disks can run full, etc.).

You can wrap both statements in an SQL transaction, and then either commit or roll back the transaction if any of the queries fail. This assumes that your table / database type in MySQL supports transactions and that auto commit is disabled.

You can start a transaction with mysqli by calling mysqli_begin_transaction($con).

You can then commit or rollback back the transaction by calling either mysqli_commit or mysqli_rollback.

To detect if the previous statement failed, you can call mysqli_error.

Body:
I have a scenario, that how will I ensure if all of my insert queries works properly. I am using PHP for the backend coding and mysql for my database. Below I am describing my problem briefly.

I have two tables. One table is for login_details and other table is for personal_details. My table structure is here.

Table login_details here user_id is the unique primary key and sl_num is auto incremental:

th{
  padding: 3px;
  border: 1px solid black;
}

td{
  padding: 3px;
  border: 1px solid black;
}

      sl_num
      user_id
      email
      password

        1
        123
        daniel@gmail.com
        5567

        2
        246
        lucy@yahoo.com
        9908

and my second table is personal_details. Here also the user_id is the primary key and this key also maintain relation among the two tables and sl_num is auto incremental:

th{
  padding: 3px;
  border: 1px solid black;
}

td{
  padding: 3px;
  border: 1px solid black;
}

      sl_num
      user_id
      name
      address
      age

        1
        123
        Daniel
        San Francisco
        23

        2
        246
        Lucy
        London
        27

And, I use this code to insert values in these tables.

<?php
   $user_id = uniqid();
   $email = $_POST['email'];
   $password = $_POST['password'];
   $name = $_POST['name'];
   $address = $_POST['address'];
   $age = $_POST['age'];

   $con = mysqli_connect('localhost', 'username', 'password',
                         'user_db');

   $query = "INSERT INTO `login_details` (`user_id`, `email`,
             `password`) VALUES ('$user_id', '$email', '$password')";
   mysqli_query($con,$query);

   $query2 = "INSERT INTO `personal_details` (`user_id`, `name`,
             `address`, `age`) VALUES ('$user_id', '$name', '$address',
             '$age')";
   mysqli_query($con,$query);

   echo 'User created successfully';?>

But a wired problem happened once. A third user name 'John Doe' trying to create his account. The details of the personal_details table inserted successfully but the for some reasons the details of the login_details is not inserted. So, the user 'John Doe' has personal information on the table but as he doesn't have any login information so, he can't login.

So, what is the best solution of these kinds of multi insert situation. How can I prevent this situation. It means, if one row inserted into login_details then the system has to ensure that the relative row is also inserted into personal_details table. If two are inserted successfully then the transaction happened or if one row inserted and other not then the system will automatically discarded the inserted row and show a fail message.


问:
Calculate Time Remaining
What's a good algorithm for determining the remaining time for something to complete?  I know how many total lines there are, and how many have completed already, how should I estimate the time remaining?</p>

答:
It depends greatly on what the "something" is.  If you can assume that the amount of time to process each line is similar, you can do a simple calculation:</p>

```<code>TimePerLine = Elapsed / LinesProcessed
TotalTime = TimePerLine * TotalLines
TimeRemaining = TotalTime - LinesRemaining * TimePerLine
</code>```

OwnerDisplayName: Aaron Smith

Title: Calculate Time Remaining

Body:
It depends greatly on what the "something" is.  If you can assume that the amount of time to process each line is similar, you can do a simple calculation:

TimePerLine = Elapsed / LinesProcessed
TotalTime = TimePerLine * TotalLines
TimeRemaining = TotalTime - LinesRemaining * TimePerLine

OwnerDisplayName: Michael Meadows


问:
How does str.replace() method work?
I have this input:

```<code>'0472/91.39.17'
</code>```

I want to replace my input with '1234567890' one by one like this:

```<code>'1234/56.78.90'
</code>```

But my outcome is

```<code>0472/91.09.17
</code>```

Here's my code

```<code>phone = '0472/91.39.17'
repl = 1234567890

for i in phone:
    if i.isdigit():
        for j in str(repl):
            x = phone.replace(i, j)
        print(x)
</code>```

What is the proper way to do this?

答:
I was thinking you could use itertools count with modulus for numbers higher than 10.</p>

```<code>from itertools import count

c = count(0) # start number
phone = '0472/91.39.17'

''.join(str(next(c) % 10) if item.isdigit() else item for item in phone)
</code>```

Title: How does str.replace() method work?

Body:
I have this input:

'0472/91.39.17'

I want to replace my input with '1234567890' one by one like this:

'1234/56.78.90'

But my outcome is

0472/91.09.17

Here's my code

phone = '0472/91.39.17'
repl = 1234567890

for i in phone:
    if i.isdigit():
        for j in str(repl):
            x = phone.replace(i, j)
        print(x)

What is the proper way to do this?

Body:
I was thinking you could use itertools count with modulus for numbers higher than 10.

from itertools import count

c = count(0) # start number
phone = '0472/91.39.17'

''.join(str(next(c) % 10) if item.isdigit() else item for item in phone)


问:
How to create alert rule for all DBs in a resource group via powershell using foreach loop
I am looking to create DTU alert rules that will monitor for the DTU going above 90 % for the last 15min.I want to do this for all databases within a resource group.
The idea is to automate the work and save the manual creation of dozens of rules in the GUI and also to avoid running one script for each alert.It must basically create the same alert for for as many databases that you have in the resource group but provide a unique name, see "THAT MUST BE UNIQUE" part in the script

The script I wrote is:

```<code>#define variable for resource group name by requesting keynoard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

<#create the array containing databases where alerts are required. The value of v12.0,user corresponds to the kind of resource as to include only the SQL DBs and not the SQL servers#>

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select -expandpropert resourceid

#loop through the array and create the alert rule for each DB

foreach($resource in $resources){Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "Central US" -targetresourceid $resource -Name "THAT MUST BE UNIQUE" -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "putemail@here.com")}
</code>```

The problem is that IT CREATES ONLY ONE ALERT and then errors out with the following (which persumably points to an issue with the -name value not being unique):

```<code>Add-AzureRMMetricAlertRule : Exception type: ErrorResponseException, Message: Can not update target resource id during
update., Code: BadRequest, Status code:BadRequest, Reason phrase: Bad Request
At C:\Users\CreateDTUalertsFORallDBv2.ps1:11 char:34
+ ... $resources){Add-AzureRMMetricAlertRule -ResourceGroup $rg -location " ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Add-AzureRmMetricAlertRule], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetricAlertRuleCommand
</code>```

Can you please advise what is going wrong and how can I make it work as to create a DTU metric for each DB in the resource group following the parameters form the script ?I am also curious how can I populate the "-name" parameter from the above script with something unique to the DB where the alert will be working (ideally with the resource name value that can be fed from the Get-AzureRmResource commandlet which is right before the foreach loop in the script).

If I try to populate the -name parameter with the RESOURCENAME of the DB using the below script :

```<code>#define variable for resource group name by requesting keynoard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

#create the array containing databases where alerts are required

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select -expandpropert resourceid

#loop through the array and create the alert rule for each DB

foreach($resource in $resources){$resourcename = (Get-AzureRmResource -ResourceGroupName $rg -Resourceid $resource).resourcename;Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "Central US" -targetresourceid $resource -Name $resourcename -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-DestinationHotels@hhogdev.com")}
</code>```

It errors about the name not being unique, see error below :

```<code>    Add-AzureRmMetricAlertRule : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\ttest.ps1:11 char:234
+ ...  "Central US" -targetresourceid $resource -Name $resourcename -Metric ...
+                                                     ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Add-AzureRmMetricAlertRule], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetr
   icAlertRuleCommand

Get-AzureRmResource : Parameter set cannot be resolved using the specified named parameters.
At C:\Users\ttest.ps1:11 char:51
+ ... urcename = (Get-AzureRmResource -ResourceGroupName $rg -Resourceid $r ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-AzureRmResource], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.Ge
</code>```

答: The exact DTU alert you are trying to create has been created step-by-step on this article.</p>

Body:
I am looking to create DTU alert rules that will monitor for the DTU going above 90 % for the last 15min.I want to do this for all databases within a resource group.
The idea is to automate the work and save the manual creation of dozens of rules in the GUI and also to avoid running one script for each alert.It must basically create the same alert for for as many databases that you have in the resource group but provide a unique name, see "THAT MUST BE UNIQUE" part in the script

The script I wrote is:

#define variable for resource group name by requesting keynoard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

<#create the array containing databases where alerts are required. The value of v12.0,user corresponds to the kind of resource as to include only the SQL DBs and not the SQL servers#>

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select -expandpropert resourceid

#loop through the array and create the alert rule for each DB

foreach($resource in $resources){Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "Central US" -targetresourceid $resource -Name "THAT MUST BE UNIQUE" -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "putemail@here.com")}

The problem is that IT CREATES ONLY ONE ALERT and then errors out with the following (which persumably points to an issue with the -name value not being unique):

Add-AzureRMMetricAlertRule : Exception type: ErrorResponseException, Message: Can not update target resource id during
update., Code: BadRequest, Status code:BadRequest, Reason phrase: Bad Request
At C:\Users\CreateDTUalertsFORallDBv2.ps1:11 char:34
+ ... $resources){Add-AzureRMMetricAlertRule -ResourceGroup $rg -location " ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : CloseError: (:) [Add-AzureRmMetricAlertRule], PSInvalidOperationException
    + FullyQualifiedErrorId : Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetricAlertRuleCommand

Can you please advise what is going wrong and how can I make it work as to create a DTU metric for each DB in the resource group following the parameters form the script ?I am also curious how can I populate the "-name" parameter from the above script with something unique to the DB where the alert will be working (ideally with the resource name value that can be fed from the Get-AzureRmResource commandlet which is right before the foreach loop in the script).

If I try to populate the -name parameter with the RESOURCENAME of the DB using the below script :

#define variable for resource group name by requesting keynoard input

$rg = Read-Host 'Please, input resource group name here (exactly as it is in Azure)'

#create the array containing databases where alerts are required

$resources = Get-AzureRmResource | ?{ $_.ResourceGroupName -eq $rg -and $_.kind -eq "v12.0,user"  } | select -expandpropert resourceid

#loop through the array and create the alert rule for each DB

foreach($resource in $resources){$resourcename = (Get-AzureRmResource -ResourceGroupName $rg -Resourceid $resource).resourcename;Add-AzureRMMetricAlertRule -ResourceGroup $rg -location "Central US" -targetresourceid $resource -Name $resourcename -MetricName "dtu_consumption_percent" -Operator "GreaterThan" -Threshold 90 -WindowSize $([TimeSpan]::Parse("00:15:00")) -TimeAggregationOperator "Average" -verbose -Actions $(New-AzureRmAlertRuleEmail -SendToServiceOwners -CustomEmails "Client-DestinationHotels@hhogdev.com")}

It errors about the name not being unique, see error below :

    Add-AzureRmMetricAlertRule : Cannot validate argument on parameter 'Name'. The argument is null or empty. Provide an
argument that is not null or empty, and then try the command again.
At C:\Users\ttest.ps1:11 char:234
+ ...  "Central US" -targetresourceid $resource -Name $resourcename -Metric ...
+                                                     ~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Add-AzureRmMetricAlertRule], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.Azure.Commands.Insights.Alerts.AddAzureRmMetr
   icAlertRuleCommand

Get-AzureRmResource : Parameter set cannot be resolved using the specified named parameters.
At C:\Users\ttest.ps1:11 char:51
+ ... urcename = (Get-AzureRmResource -ResourceGroupName $rg -Resourceid $r ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-AzureRmResource], ParameterBindingException
    + FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.Ge


问:
VBA Data validation list not working (Formula1:=)
The following code is a loop that takes the value of a cell (string), and inserts it into another sheet. it then separates the values of the string by a comma delimiter. It all works fine until I try to create a list data validation, where the Formula1:= does not seem to be working properly, however the code looks fine.

It is supposed to copy the current row of the loop all the way to the last column and create a data validation list out of it.

Please help, what am I doing wrong?

```<code>Sub dataVal()

    Dim lrow As Long
    Dim lcol As Long
    Dim i As Long
    Dim counter As Integer
    counter = 1
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.count, "H").End(xlUp).Row
    lcol = Sheets("Sheet7").Cells(counter, Columns.count).End(xlToLeft).Column

    For i = 4 To lrow
      Range("I" & i).Select
      Selection.Copy
      Sheets("Sheet7").Select
      Range("A" & counter).Select
      ActiveSheet.Paste
      Application.CutCopyMode = False
      Selection.TextToColumns Destination:=Range("A" & counter), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), _
        TrailingMinusNumbers:=True
      Sheets("LVL & Mapping").Select
      Range("J" & i).Select
        With Selection.Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))
           .IgnoreBlank = True
           .InCellDropdown = True
           .InputTitle = ""
           .ErrorTitle = ""
           .InputMessage = ""
           .ErrorMessage = ""
           .ShowInput = True
           .ShowError = True
        End With
      counter = counter + 1
    Next i
End Sub
</code>```

答:
```<code>Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))
</code>```

Classic mistake: unqualified Cells member call is implicitly referring to whatever the ActiveSheet is; if that isn't Sheet7, the validation is silently throwing an internal error and you don't get your list.

Range, Cells, Columns, Rows, and Names should always be explicitly qualified with a proper Worksheet instance.

That's what you did here:

```<code>Sheets("Sheet7").Range(...)
</code>```

This Range member belongs to whatever worksheet the Sheets call (which is itself implicitly working off whatever the ActiveWorkbook is) is returning.

The macro recorder generates clumsy code that mimicks user interactions. It's good for exploring the object model and learn what members to use to do what, but it's inherently frail and bug-prone.

Don't use .Select and .Activate; work off object references instead. See this post for more info.

```<code>Dim validationSource As worksheet
Set validationSource = ThisWorkbook.Worksheets("Sheet7")

...

With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=" & validationSource.Range(validationSource.Cells(counter, 1), validationSource.Cells(counter, lcol)).Address
    '...
</code>```

Give it the .Address of the range, not the range itself. And since this is a formula, prefix with an = sign.

Body:
The following code is a loop that takes the value of a cell (string), and inserts it into another sheet. it then separates the values of the string by a comma delimiter. It all works fine until I try to create a list data validation, where the Formula1:= does not seem to be working properly, however the code looks fine.

It is supposed to copy the current row of the loop all the way to the last column and create a data validation list out of it.

Please help, what am I doing wrong?

Sub dataVal()

    Dim lrow As Long
    Dim lcol As Long
    Dim i As Long
    Dim counter As Integer
    counter = 1
    lrow = Sheets("LVL & Mapping").Cells(Sheets("LVL & Mapping").Rows.count, "H").End(xlUp).Row
    lcol = Sheets("Sheet7").Cells(counter, Columns.count).End(xlToLeft).Column

    For i = 4 To lrow
      Range("I" & i).Select
      Selection.Copy
      Sheets("Sheet7").Select
      Range("A" & counter).Select
      ActiveSheet.Paste
      Application.CutCopyMode = False
      Selection.TextToColumns Destination:=Range("A" & counter), DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=False, _
        Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
        :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1)), _
        TrailingMinusNumbers:=True
      Sheets("LVL & Mapping").Select
      Range("J" & i).Select
        With Selection.Validation
           .Delete
           .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))
           .IgnoreBlank = True
           .InCellDropdown = True
           .InputTitle = ""
           .ErrorTitle = ""
           .InputMessage = ""
           .ErrorMessage = ""
           .ShowInput = True
           .ShowError = True
        End With
      counter = counter + 1
    Next i
End Sub

Body:
Formula1:=Sheets("Sheet7").Range(Cells(counter, 1), Cells(counter, lcol))

Classic mistake: unqualified Cells member call is implicitly referring to whatever the ActiveSheet is; if that isn't Sheet7, the validation is silently throwing an internal error and you don't get your list.

Range, Cells, Columns, Rows, and Names should always be explicitly qualified with a proper Worksheet instance.

That's what you did here:

Sheets("Sheet7").Range(...)

This Range member belongs to whatever worksheet the Sheets call (which is itself implicitly working off whatever the ActiveWorkbook is) is returning.

The macro recorder generates clumsy code that mimicks user interactions. It's good for exploring the object model and learn what members to use to do what, but it's inherently frail and bug-prone.

Don't use .Select and .Activate; work off object references instead. See this post for more info.

Dim validationSource As worksheet
Set validationSource = ThisWorkbook.Worksheets("Sheet7")

...

With Selection.Validation
    .Delete
    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="=" & validationSource.Range(validationSource.Cells(counter, 1), validationSource.Cells(counter, lcol)).Address
    '...

Give it the .Address of the range, not the range itself. And since this is a formula, prefix with an = sign.


问:
New Entry Template button is disabled
I have configured the ICN to use the entry templates using the following procedure

Open the administration tool in the web client. Click Repositories
and open the repository on which you want to enable entry template
management.

Connect to the repository as a library server administrator (IBM® Content Manager) or a Content Platform Engine administrator (IBM FileNet® P8).

In the Optional Features section of
the Configuration Parameters tab, select Enable for the entry
template management feature.

I have been able to see the entry template feature on the ICN, however I am unable to create any new entry template as the "New Entry Template" button is disabled.

答:
Check your Access. Are you member of the group for Entry Template Management?
I suggest to clear browser cache and cookies, restart browser.
If that doesn't help try to restart back-end and ICN. </p>

Title: New Entry Template button is disabled


问:
NServiceBus limitations consumers (endpoints)
I am currently looking at NServiceBus as a candidate within my architecture and have a pretty good idea what it is and can do. I do have trouble finding a direct answer to one question that I still have.
I know that it is build in .NET. It is unclear to me if .NET is a limitation to the publishers & consumers (endpoint?) as well.

Simply put, using (for example) Azure ServiceBus I can post a message on a queue with a nodejs application, and a consumer could be an Azure Function (triggered) written in say Java. Or an application/service written in Python.
Does using NServiceBus put a limit on the technology in which publisher/consumer is written ? (so far, to me, it seems so).

Thanks for clarifying this cloud in my brain ;-)

Cheers!

答:
Does using NServiceBus put a limit on the technology in which publisher/consumer is written?

Short answer - it is not. You can use NServiceBus in part of your systems where other parts are running on different platforms and created in other languages. NServiceBus treats this kind of integrations as "native" integrations.

As you have mentioned Azure Service Bus as your underlying communication technology, you could look at the Native Integration with Azure Service Bus Transport sample that demostrates how to connect non-NServiceBus code with NServiceBus endpoint. While the sender in the sample is a .NET code, it could be swapped out with Java or any other language you're using to send/receive messages.


问:
Immutable list not adding data
I am using an ImmutableList as follows:

Referenced the package using Nuget and following is the usage code:

```<code>using System.Collections.Immutable;

private ImmutableList<Data> immutableList = ImmutableList.Create<Data>();

// Write Action

Action writeAction = (() =>
        {
            Data writeData = new Data();

            // Fill Data type with valid values

            immutableList.Add(writeData);

        });
</code>```

This code above is not adding any data to the Immutable list. It remains empty, I cannot figure out the reason when all the data is valid. Similar code is used to fill other data structures like ConcurrentQueue and ConcurrentBag and it works fine.

Am I missing something in the usage of the immutable list, does it requires correction?
Please note this is a multi-threaded operation, but that can't be an issue, since this data structure is thread safe.

答:
ImmutableList immutableList = ImmutableList.Create<string>("data1", "data2");

This works perfectly for me.

Title: Immutable list not adding data

Body:
I am using an ImmutableList as follows:

Referenced the package using Nuget and following is the usage code:

using System.Collections.Immutable;

private ImmutableList<Data> immutableList = ImmutableList.Create<Data>();

// Write Action

Action writeAction = (() =>
        {
            Data writeData = new Data();

            // Fill Data type with valid values

            immutableList.Add(writeData);

        });

This code above is not adding any data to the Immutable list. It remains empty, I cannot figure out the reason when all the data is valid. Similar code is used to fill other data structures like ConcurrentQueue and ConcurrentBag and it works fine.

Am I missing something in the usage of the immutable list, does it requires correction?
Please note this is a multi-threaded operation, but that can't be an issue, since this data structure is thread safe.


问:
Regex to get a list of strings within a pattern
I have a load of strings like this:

.ls-resourceIcon .icon_xls_gif,
  .ls-resourceIcon .icon_xlt_gif,
  .ls-resourceIcon .icon_xlw_gif

I want to get the strings between icon_ and _gif into a comma separated list, so in this case "xls,xlt,xlw," (I can trim the trailing comma).

I have so far got this:

```<code>var regex = new RegExp("^.*icon_(.*)_gif.*$", "g");
var result = input.replace(regex, "$1,");
</code>```

but that gives me

xlw,

as a result, not all the matches.

What am I missing? Is there an easier way to do this that I haven't noticed?

答:
Your regex is greedy, so the leading .* will grab everything up until the final icon_xlw_gif.  You need to make both sides non-greedy.  This might work:

```<code>var regex = new RegExp("icon_([A-Za-z]*)_gif", "g");
</code>```

Remove the leading and trailing .*

Also replaced the (.*) with I think also now wouldn't work the way you intended it.

Body:
I have a load of strings like this:

.ls-resourceIcon .icon_xls_gif,
  .ls-resourceIcon .icon_xlt_gif,
  .ls-resourceIcon .icon_xlw_gif

I want to get the strings between icon_ and _gif into a comma separated list, so in this case "xls,xlt,xlw," (I can trim the trailing comma).

I have so far got this:

var regex = new RegExp("^.*icon_(.*)_gif.*$", "g");
var result = input.replace(regex, "$1,");

but that gives me

xlw,

as a result, not all the matches.

What am I missing? Is there an easier way to do this that I haven't noticed?

Body:
Your regex is greedy, so the leading .* will grab everything up until the final icon_xlw_gif.  You need to make both sides non-greedy.  This might work:

var regex = new RegExp("icon_([A-Za-z]*)_gif", "g");

Remove the leading and trailing .*

Also replaced the (.*) with I think also now wouldn't work the way you intended it.


问:
How to map user defined table valued function to EF 6 database first entity collection?
I am trying to solve a problem with mapping original entity on UDF execution.
I have this scenario:

```<code>    CREATE FUNCTION [dbo].[GetUsers]
    (
        @password nvarchar(50) NULL
    )
    RETURNS TABLE
    AS
    RETURN
    (
     SELECT UserID, Username FROM User
    )
</code>```

Assume table users has only those two columns(int and nvarchar).For obvious reasons I skipped any logic from this procedure. It simply returns all rows and columns from table User now.

I have mapped table User as entity User and is accessible from dbcontext. And now I want it to be returned from this procedure as IQueryable. I specifically dont want to use result set of "Complex" type but the original entity User.

When I do the function import and set "Returns collection of" to entities - User , it is not working, throws an exception.

Code it generates in dbcontext class looks like this:

```<code>    [DbFunction("Entities", "GetUsers")]
    public virtual IQueryable<User> GetUsers(string password)
    {
        var passwordParameter = password != null ?
            new ObjectParameter("password", password) :
            new ObjectParameter("password", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<User>("[Entities].[GetUsers](@password)", passwordParameter);
    }
</code>```

so when I call the function using:

```<code>   var result = dbcontext.GetUsers("pass");
</code>```

it throws and exception: 'Entities.GetUsers' cannot be resolved into a valid type or function. Near member access expression, line 1, column 11.

"Entities" is indeed correct name of my dbcontext class.

Do I have my function wrong or what can be done about it to make this scenario work?

Thanks a lot

答:
The only problem consisted in bug of entity framework where it cant obviously work with different name/type of connection strings than "Entities" (its the default one what ADO.NET model creates). I modified the T4 template a long time ago. Till moment i wanted to call UDF i never had any problem. It was using different name and kind of connection string which I am sharing across multiple libraries and not all of them support that weird type of connection string looking like:

connectionString="metadata=res:///DataModel.csdl|res:///DataModel.ssdl|res://*/..."
  one.

```<code>public partial class Entities : DbContext
{
    public Entities() : base("name=Entities")
    {
    }

    ...
}
</code>```

When I put it back like above, it started working.

Body:
I am trying to solve a problem with mapping original entity on UDF execution.
I have this scenario:

    CREATE FUNCTION [dbo].[GetUsers]
    (
        @password nvarchar(50) NULL
    )
    RETURNS TABLE
    AS
    RETURN
    (
     SELECT UserID, Username FROM User
    )

Assume table users has only those two columns(int and nvarchar).For obvious reasons I skipped any logic from this procedure. It simply returns all rows and columns from table User now.

I have mapped table User as entity User and is accessible from dbcontext. And now I want it to be returned from this procedure as IQueryable. I specifically dont want to use result set of "Complex" type but the original entity User.

When I do the function import and set "Returns collection of" to entities - User , it is not working, throws an exception.

Code it generates in dbcontext class looks like this:

    [DbFunction("Entities", "GetUsers")]
    public virtual IQueryable<User> GetUsers(string password)
    {
        var passwordParameter = password != null ?
            new ObjectParameter("password", password) :
            new ObjectParameter("password", typeof(string));

        return ((IObjectContextAdapter)this).ObjectContext.CreateQuery<User>("[Entities].[GetUsers](@password)", passwordParameter);
    }

so when I call the function using:

   var result = dbcontext.GetUsers("pass");

it throws and exception: 'Entities.GetUsers' cannot be resolved into a valid type or function. Near member access expression, line 1, column 11.

"Entities" is indeed correct name of my dbcontext class.

Do I have my function wrong or what can be done about it to make this scenario work?

Thanks a lot

Body:
The only problem consisted in bug of entity framework where it cant obviously work with different name/type of connection strings than "Entities" (its the default one what ADO.NET model creates). I modified the T4 template a long time ago. Till moment i wanted to call UDF i never had any problem. It was using different name and kind of connection string which I am sharing across multiple libraries and not all of them support that weird type of connection string looking like:

connectionString="metadata=res:///DataModel.csdl|res:///DataModel.ssdl|res://*/..."
  one.

public partial class Entities : DbContext
{
    public Entities() : base("name=Entities")
    {
    }

    ...
}

When I put it back like above, it started working.


问:
i am getting zero values of longitude and latitude in google maps in android studio
Here is my MapsActivity.java code, I am getting zero values for longitude and latitude after placing a marker on map and after calling getCurrentlocation(). What is going wrong?

```<code>public class MapsActivity extends FragmentActivity implements
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener,
        View.OnClickListener {

    //Our Map
    private GoogleMap mMap;

    //To store longitude and latitude from map
    private double longitude;
    private double latitude;

    //Buttons
    private ImageButton buttonSave;
    private ImageButton buttonCurrent;
    private ImageButton buttonView;

    //Google ApiClient
    private GoogleApiClient googleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //Initializing googleapi client
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        //Initializing views and adding onclick listeners
        buttonSave = (ImageButton) findViewById(R.id.buttonSave);
        buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
        buttonView = (ImageButton) findViewById(R.id.buttonView);
        buttonSave.setOnClickListener(this);
        buttonCurrent.setOnClickListener(this);
        buttonView.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    //Getting current location
    private void getCurrentLocation() {
        mMap.clear();
        //Creating a location object
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            //moving the map to location
            moveMap();
        }
    }

    //Function to move the map
    private void moveMap() {
        //String to display current latitude and longitude
        String msg = latitude + ", "+longitude;

        //Creating a LatLng Object to store Coordinates
        LatLng latLng = new LatLng(latitude, longitude);

        //Adding marker to map
        mMap.addMarker(new MarkerOptions()
                .position(latLng) //setting position
                .draggable(true) //Making the marker draggable
                .title("Current Location")); //Adding a title

        //Moving the camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        //Animating the camera
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        //Displaying current coordinates in toast
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng latLng = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        getCurrentLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        //Clearing all the markers
        mMap.clear();

        //Adding a new marker to the current pressed position
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
        String msg = latitude + ", "+longitude;
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();

    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        //Getting the coordinates
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        //Moving the map
        moveMap();
    }

    @Override
    public void onClick(View v) {
        if(v == buttonCurrent){
            getCurrentLocation();
            moveMap();
        }
    }
}
</code>```

答:
Use Request Location Updates better </p>

```<code> protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(15 * 1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setSmallestDisplacement(0);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
        }

    }

 LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
                mLastLocation = location;
                //do whatever you want here
            }
        }
    };
</code>```

<p>Don't Forget to add onDestory Method </p>

```<code> @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener);
            mGoogleApiClient.disconnect();
        }
    }
</code>```

Body:
Here is my MapsActivity.java code, I am getting zero values for longitude and latitude after placing a marker on map and after calling getCurrentlocation(). What is going wrong?

public class MapsActivity extends FragmentActivity implements
        OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        GoogleMap.OnMarkerDragListener,
        GoogleMap.OnMapLongClickListener,
        View.OnClickListener {

    //Our Map
    private GoogleMap mMap;

    //To store longitude and latitude from map
    private double longitude;
    private double latitude;

    //Buttons
    private ImageButton buttonSave;
    private ImageButton buttonCurrent;
    private ImageButton buttonView;

    //Google ApiClient
    private GoogleApiClient googleApiClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        //Initializing googleapi client
        googleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        //Initializing views and adding onclick listeners
        buttonSave = (ImageButton) findViewById(R.id.buttonSave);
        buttonCurrent = (ImageButton) findViewById(R.id.buttonCurrent);
        buttonView = (ImageButton) findViewById(R.id.buttonView);
        buttonSave.setOnClickListener(this);
        buttonCurrent.setOnClickListener(this);
        buttonView.setOnClickListener(this);
    }

    @Override
    protected void onStart() {
        googleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onStop() {
        googleApiClient.disconnect();
        super.onStop();
    }

    //Getting current location
    private void getCurrentLocation() {
        mMap.clear();
        //Creating a location object
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
        if (location != null) {
            //Getting longitude and latitude
            longitude = location.getLongitude();
            latitude = location.getLatitude();

            //moving the map to location
            moveMap();
        }
    }

    //Function to move the map
    private void moveMap() {
        //String to display current latitude and longitude
        String msg = latitude + ", "+longitude;

        //Creating a LatLng Object to store Coordinates
        LatLng latLng = new LatLng(latitude, longitude);

        //Adding marker to map
        mMap.addMarker(new MarkerOptions()
                .position(latLng) //setting position
                .draggable(true) //Making the marker draggable
                .title("Current Location")); //Adding a title

        //Moving the camera
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));

        //Animating the camera
        mMap.animateCamera(CameraUpdateFactory.zoomTo(15));

        //Displaying current coordinates in toast
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        LatLng latLng = new LatLng(-34, 151);
        mMap.addMarker(new MarkerOptions().position(latLng).draggable(true));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        mMap.setOnMarkerDragListener(this);
        mMap.setOnMapLongClickListener(this);
    }

    @Override
    public void onConnected(Bundle bundle) {
        getCurrentLocation();
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onMapLongClick(LatLng latLng) {
        //Clearing all the markers
        mMap.clear();

        //Adding a new marker to the current pressed position
        mMap.addMarker(new MarkerOptions()
                .position(latLng)
                .draggable(true));
        String msg = latitude + ", "+longitude;
        Toast.makeText(this, msg, Toast.LENGTH_LONG).show();

    }

    @Override
    public void onMarkerDragStart(Marker marker) {

    }

    @Override
    public void onMarkerDrag(Marker marker) {

    }

    @Override
    public void onMarkerDragEnd(Marker marker) {
        //Getting the coordinates
        latitude = marker.getPosition().latitude;
        longitude = marker.getPosition().longitude;

        //Moving the map
        moveMap();
    }

    @Override
    public void onClick(View v) {
        if(v == buttonCurrent){
            getCurrentLocation();
            moveMap();
        }
    }
}

Body:
Use Request Location Updates better

 protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(15 * 1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setSmallestDisplacement(0);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        if (ContextCompat.checkSelfPermission(this,
                android.Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, locationListener);
        }

    }

 LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
                mLastLocation = location;
                //do whatever you want here
            }
        }
    };

Don't Forget to add onDestory Method

 @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, locationListener);
            mGoogleApiClient.disconnect();
        }
    }


问:
Macro increment
I have table lookup values as below

```<code>sno date
1   200101
2   200102
3   200103
4   200104
</code>```

I wrote below macro

```<code>%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;
</code>```

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

答:
Build a lookup table dynamically and create a macro variable for each row in the table.  The macro variables will be named date_200101,date_200102,...and so on.  They will contain a value equal to the corresponding sno value:

```<code>data lookup;
  length var_name $20;
  do sno = 1 to intck('month','01jan2001'd,date())+1;
    date = input(put(intnx('month','01jan2001'd, sno-1, 'beginning'),yymmn6.),best.);
    var_name = cats('date_',date);
    call symput(var_name, cats(sno));
    output;
  end;
run;
</code>```

You can then refer to the macro variables like so:

```<code>%let date =200103;
%put &&date_&date;
</code>```

...or...

```<code>%put &date_200101;
</code>```

The first usage example is using double macro resolution.  Basically the macro processes needs to perform 2 iterations of the macro token &&date_&date in order to fully resolve it.  On the first pass, it gets resolved to &date_200101.  On the second pass, the macro token &date_200101 gets resolved to 1.

Title: Macro increment

Body:
I have table lookup values as below

sno date
1   200101
2   200102
3   200103
4   200104

I wrote below macro

%let date=200102
 proc sql;
 select sno into :no from lookup where date=&date.;
 quit;

I need a help on how to convert the entire table lookup into macro increment by creating first s.no and date as two macro variable then increment. So that i don’t need to update dates in my table lookup every time. So if i look up for date 201304 i need to get its corresponding s.no

Body:
Build a lookup table dynamically and create a macro variable for each row in the table.  The macro variables will be named date_200101,date_200102,...and so on.  They will contain a value equal to the corresponding sno value:

data lookup;
  length var_name $20;
  do sno = 1 to intck('month','01jan2001'd,date())+1;
    date = input(put(intnx('month','01jan2001'd, sno-1, 'beginning'),yymmn6.),best.);
    var_name = cats('date_',date);
    call symput(var_name, cats(sno));
    output;
  end;
run;

You can then refer to the macro variables like so:

%let date =200103;
%put &&date_&date;

...or...

%put &date_200101;

The first usage example is using double macro resolution.  Basically the macro processes needs to perform 2 iterations of the macro token &&date_&date in order to fully resolve it.  On the first pass, it gets resolved to &date_200101.  On the second pass, the macro token &date_200101 gets resolved to 1.


问:
Error (22,0) Could not find method android() for arguments
Today I opened Android Studio and got a Cylic Redundancy Check Error, so I went into the cmd promp as admin and restarted my computer, it booted up and scanned my drive that was corrupted and repaired it, When it finished booting up I reopened Android Studio, and when I opened my project on Android Studio, the build failed and I got an error in my Gradle Sync, how can I go about fixing this so the project completes its build instead of failing?

Gradle Synce Error Messages:

```<code>Error:(22, 0) Could not find method android() for arguments [build_1renfppeqp4po95v257ecguyh$_run_closure3@76bc331d] on root project 'PopularMovies' of type org.gradle.api.Project.
<a href="openFile:C:\Users\apple\Desktop\PopularMovies\build.gradle">Open File</a>
</code>```

Build Gradle

```<code>buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
repositories {
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
}
</code>```

Any help would be appreciated

答:
In my case, I got this error because my module level gradle file was missing the line:

```<code>apply plugin: 'com.android.application'
</code>```

It's usually the first line in the gradle file.  For some unknown reason, probably being a little careless, I accidentally deleted that line, so that's how I ran into this problem.  I notice, I don't see that line in the gradle script above, so that's probably what's happening in this case.

Body:
Today I opened Android Studio and got a Cylic Redundancy Check Error, so I went into the cmd promp as admin and restarted my computer, it booted up and scanned my drive that was corrupted and repaired it, When it finished booting up I reopened Android Studio, and when I opened my project on Android Studio, the build failed and I got an error in my Gradle Sync, how can I go about fixing this so the project completes its build instead of failing?

Gradle Synce Error Messages:

Error:(22, 0) Could not find method android() for arguments [build_1renfppeqp4po95v257ecguyh$_run_closure3@76bc331d] on root project 'PopularMovies' of type org.gradle.api.Project.
Open File

Build Gradle

buildscript {
repositories {
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:2.2.3'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}
}
allprojects {
repositories {
    jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

android {
compileSdkVersion 25
buildToolsVersion '25.0.2'
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
}
}
dependencies {
}

Any help would be appreciated

Body:
In my case, I got this error because my module level gradle file was missing the line:

apply plugin: 'com.android.application'

It's usually the first line in the gradle file.  For some unknown reason, probably being a little careless, I accidentally deleted that line, so that's how I ran into this problem.  I notice, I don't see that line in the gradle script above, so that's probably what's happening in this case.


问:
Split divs diagonally and responsively
I need to build the following screenshot, and I can't figure out how to do the angles responsively:

https://imgur.com/a/e9IJV

I tried using pseudo classes to add diagonal edges to a solid-color div.
But this design requires two images side-by-side so that won't work there. Also, the slants have to stay on the same angle through different sections with variable heights. I can't use clip-path because I need to support IE.

Here is my feeble attempt:
https://codepen.io/lsterling03/pen/zPEgaq

As you can see, I am having trouble! Is this design possible? Do you have any advice on how to approach this? Will it require javascript?

UPDATE

I have made a little progress. Here is an updated pen:
https://codepen.io/lsterling03/pen/GOOqmo

I can't get the slant right on the last section, which needs a variable height and width. I tried using javascript, but I don't have the right calculations:

```<code>        $(".slant").css('width', $('.main').width() * 0.5 - 100);
        $(".slant").css('border-top-width', $('.main').height());
</code>```

I also haven't figured out how to do two images in a row yet.

Does anyone have suggestions to fix either of the above issues?

答:
Here is something you can work with:

Bootply: https://www.bootply.com/4QuGRXY11d

.container{position:relative;width: 500px; overflow:hidden;}
.flex{display:flex;overflow:hidden;}
.cinq{overflow:hidden;width:50%;height:150px;background:blue;}
.cinq + .cinq{oveflow:hidden;right:-25%;width:75%;height:150px;position:absolute;   transform: skewX(-20deg) translateX(-50px);background:red;}
.flex + .flex .cinq + .cinq{transform: skewX(20deg) translate(-50px)}
.cinq .img{height:100%;background-size:cover; background-image:url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg);    position: absolute;
    width: 100%;
    top: 0;
    left: -50px;transform: skewX(20deg);}

.flex + .flex .cinq + .cinq .img{transform: skewX(-20deg);}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <div class="flex">
     <div class="cinq">1</div>
     <div class="cinq">
       <div class="img"></div>
    </div>
  </div>
  <div class="flex">
     <div class="cinq">3</div>
     <div class="cinq"><div class="img"></div></div>
  </div>
</div></code>```

Title: Split divs diagonally and responsively

Body:
I need to build the following screenshot, and I can't figure out how to do the angles responsively:

https://imgur.com/a/e9IJV

I tried using pseudo classes to add diagonal edges to a solid-color div.
But this design requires two images side-by-side so that won't work there. Also, the slants have to stay on the same angle through different sections with variable heights. I can't use clip-path because I need to support IE.

Here is my feeble attempt:
https://codepen.io/lsterling03/pen/zPEgaq

As you can see, I am having trouble! Is this design possible? Do you have any advice on how to approach this? Will it require javascript?

UPDATE

I have made a little progress. Here is an updated pen:
https://codepen.io/lsterling03/pen/GOOqmo

I can't get the slant right on the last section, which needs a variable height and width. I tried using javascript, but I don't have the right calculations:

        $(".slant").css('width', $('.main').width() * 0.5 - 100);
        $(".slant").css('border-top-width', $('.main').height());

I also haven't figured out how to do two images in a row yet.

Does anyone have suggestions to fix either of the above issues?

Body:
Here is something you can work with:

Bootply: https://www.bootply.com/4QuGRXY11d

.container{position:relative;width: 500px; overflow:hidden;}
.flex{display:flex;overflow:hidden;}
.cinq{overflow:hidden;width:50%;height:150px;background:blue;}
.cinq + .cinq{oveflow:hidden;right:-25%;width:75%;height:150px;position:absolute;   transform: skewX(-20deg) translateX(-50px);background:red;}
.flex + .flex .cinq + .cinq{transform: skewX(20deg) translate(-50px)}
.cinq .img{height:100%;background-size:cover; background-image:url(https://s-media-cache-ak0.pinimg.com/564x/ca/9b/ca/ca9bca4db9afb09158b76641ea09ddb6.jpg);    position: absolute;
    width: 100%;
    top: 0;
    left: -50px;transform: skewX(20deg);}

.flex + .flex .cinq + .cinq .img{transform: skewX(-20deg);}

<div class="container">
  <div class="flex">
     <div class="cinq">1</div>
     <div class="cinq">
       <div class="img"></div>
    </div>
  </div>
  <div class="flex">
     <div class="cinq">3</div>
     <div class="cinq"><div class="img"></div></div>
  </div>
</div>