问:
Python - Replace Multiple Indices With One in For Loop
I'm trying to find a way to replace multiple indices with a single one.

Original list:

```<code>a[100] = "-277/480V RATED:"
a[101] = "Model L-N:"
a[102] = "B3 Ring Wave: 600"
a[103] = "C3 Combined Wave: 1300"
a[104] = "6kV-3Ka UL VPR: 1200"
a[105] = "Model L-G:"
a[106] = "B3 Ring Wave: 875"
a[107] = "C3 Combined Wave: 1300"
a[108] = "6kV-3Ka UL VPR: 1200"
a[109] = "Some other string"
</code>```

The output I want is:

```<code>a[100] = "-277/480V RATED:"
a[101] = "Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[102] = "Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[103] = "Some other string"
</code>```

I think I know how I'm going to concat everything. I'm going to a.startswith("B3 Ring Wave:) because that appears to be a constant and then join the indices above and below it with "\n" for new line.

Th issue is I don't know how I can replace the indices and if I can have this run in a for loop. My thought is that if I could replace them it would check a[101] which wouldn't match. It would move onto a[102] which would match so it would replace a[101-104]. It would then go into the for loop for a[102] which used to be a[105]. Is that correct?

```<code>original = ["Some Other Sting","-277/480V RATED:","Model L-N:","B3 Ring Wave: 600","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Model L-G:","B3 Ring Wave: 875","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Some other string"]

joinedList = []

for i, str in enumerate(original):
    if str.startswith("B3 Ring Wave:"):
        joinedList.append("\n".join(original[i - 1: i + 2]))
    else:
        "Do Nothing"
</code>```

答:
Removing elements from the list you're iterating over usually causes a lot of headaches. I strongly suggest creating a new list. Assuming that the sublist you want to replace always starts with "Model …" and contains three next lines, this could be done like this:</p>

```<code>new_list = []
j = 0
for i in range(0, len(a)):
    if a[i].startswith('Model '):
         j=3                              # countdown from 3
    elif j>0:
         j -= 1
         if j==0:                         # countdown reached 0 - the final line
             conc = '\n'.join(a[i-3:i+1])  # concatenate 3 preceding lines and the current one
             new_list.append(conc)
    else:
         new_list.append(a[i])
</code>```

Body:
I'm trying to find a way to replace multiple indices with a single one.

Original list:

a[100] = "-277/480V RATED:"
a[101] = "Model L-N:"
a[102] = "B3 Ring Wave: 600"
a[103] = "C3 Combined Wave: 1300"
a[104] = "6kV-3Ka UL VPR: 1200"
a[105] = "Model L-G:"
a[106] = "B3 Ring Wave: 875"
a[107] = "C3 Combined Wave: 1300"
a[108] = "6kV-3Ka UL VPR: 1200"
a[109] = "Some other string"

The output I want is:

a[100] = "-277/480V RATED:"
a[101] = "Model L-N:\nB3 Ring Wave: 600\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[102] = "Model L-G:\nB3 Ring Wave: 875\nC3 Combined Wave: 1300\n6kV-3Ka UL VPR: 1200"
a[103] = "Some other string"

I think I know how I'm going to concat everything. I'm going to a.startswith("B3 Ring Wave:) because that appears to be a constant and then join the indices above and below it with "\n" for new line.

Th issue is I don't know how I can replace the indices and if I can have this run in a for loop. My thought is that if I could replace them it would check a[101] which wouldn't match. It would move onto a[102] which would match so it would replace a[101-104]. It would then go into the for loop for a[102] which used to be a[105]. Is that correct?

original = ["Some Other Sting","-277/480V RATED:","Model L-N:","B3 Ring Wave: 600","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Model L-G:","B3 Ring Wave: 875","C3 Combined Wave: 1300","6kV-3Ka UL VPR: 1200","Some other string"]

joinedList = []

for i, str in enumerate(original):
    if str.startswith("B3 Ring Wave:"):
        joinedList.append("\n".join(original[i - 1: i + 2]))
    else:
        "Do Nothing"

Body:
Removing elements from the list you're iterating over usually causes a lot of headaches. I strongly suggest creating a new list. Assuming that the sublist you want to replace always starts with "Model …" and contains three next lines, this could be done like this:

new_list = []
j = 0
for i in range(0, len(a)):
    if a[i].startswith('Model '):
         j=3                              # countdown from 3
    elif j>0:
         j -= 1
         if j==0:                         # countdown reached 0 - the final line
             conc = '\n'.join(a[i-3:i+1])  # concatenate 3 preceding lines and the current one
             new_list.append(conc)
    else:
         new_list.append(a[i])


来源: stackexchange

问:
java 8 stream - how to get original object reference after map
Is at all possible to simply the below code using Java 8 stream?

Code:-

```<code>private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}
</code>```

I tried something like below

```<code>    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);
</code>```

But after this, I won't have any reference to the original 'smm' object to do further checks.

答:
This is really not readable, but here it is</p>

```<code>public double streamWay(Long startingMaterialId) {

    return Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .map(Stream::of)
            .flatMapToDouble(smmStream ->
                    DoubleStream.concat(
                            smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
                                    .mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f),
                            smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
                                    .mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId() * smm.getBlending2MatrixConcentration()) / 1000000f)
                    )).sum();

}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Is at all possible to simply the below code using Java 8 stream?

Code:-

private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}

I tried something like below

    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);

But after this, I won't have any reference to the original 'smm' object to do further checks.

Body:
This is really not readable, but here it is

public double streamWay(Long startingMaterialId) {

    return Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .map(Stream::of)
            .flatMapToDouble(smmStream ->
                    DoubleStream.concat(
                            smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
                                    .mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f),
                            smmStream.filter(smm -> smm.getBlending1MatrixConcentration() != null)
                                    .mapToDouble(smm -> priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId() * smm.getBlending2MatrixConcentration()) / 1000000f)
                    )).sum();

}


问:
PHP Get Site URL Protocol - http vs https
I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. Can you tell me if this is correct?

```<code>function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code>```

Is it necessary to do it like above or can I just do it like?:

```<code>function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );
</code>```

Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?

Thank you!

答:
I think the complete func should look like :

```<code>function siteURL()
{
    $protocol =  "http://";
    if (
        //straight
        isset($_SERVER['HTTPS']) && in_array($_SERVER['HTTPS'], ['on', 1])
        ||
        //proxy forwarding
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
    ) {
        $protocol = 'https://';
    }

    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
}
</code>```

Notes:

you should look also for HTTP_X_FORWARDED_PROTO (e.g. if proxy
server)

relying on 443 port is not safe (https could be served on
different port)

REQUEST_SCHEME not reliable

ContentLicense: CC BY-SA 2.5

Body:
I've written a little function to establish the current site url protocol but I don't have SSL and don't know how to test if it works under https. Can you tell me if this is correct?

function siteURL()
{
    $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
    $domainName = $_SERVER['HTTP_HOST'].'/';
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

Is it necessary to do it like above or can I just do it like?:

function siteURL()
{
    $protocol = 'http://';
    $domainName = $_SERVER['HTTP_HOST'].'/'
    return $protocol.$domainName;
}
define( 'SITE_URL', siteURL() );

Under SSL, doesn't the server automatically convert the url to https even if the anchor tag url is using http? Is it necessary to check for the protocol?

Thank you!

Body:
I think the complete func should look like :

function siteURL()
{
    $protocol =  "http://";
    if (
        //straight
        isset($_SERVER['HTTPS']) && in_array($_SERVER['HTTPS'], ['on', 1])
        ||
        //proxy forwarding
        isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https'
    ) {
        $protocol = 'https://';
    }

    $domainName = $_SERVER['HTTP_HOST'];
    return $protocol . $domainName;
}

Notes:

you should look also for HTTP_X_FORWARDED_PROTO (e.g. if proxy
server)

relying on 443 port is not safe (https could be served on
different port)

REQUEST_SCHEME not reliable


问:
HTTP request JWT
I am a little bit confused about how HTTP works.
My question is that when the server assigns a JWT token to a client after providing credentials, the server assigns token in HTTP header['Authorization']. Now the user is logged in and can make a request.
So please tell me if when the user makes an API call again, will the HTTP header['Authorization'] remain same or be changed?</p>

答:
Yes client has to do every request with authorisation request (protected routes )
so you have to set up a axios configuration (https://github.com/axios/axios#axioscreateconfig)

```<code>const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'TOKEN'}
});
</code>```

And you have to know how this authentication and authorisation tokens works for this please go through this (https://blog.restcase.com/4-most-used-rest-api-authentication-methods/)

Title: HTTP request JWT

Body:
Yes client has to do every request with authorisation request (protected routes )
so you have to set up a axios configuration (https://github.com/axios/axios#axioscreateconfig)

const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'TOKEN'}
});

And you have to know how this authentication and authorisation tokens works for this please go through this (https://blog.restcase.com/4-most-used-rest-api-authentication-methods/)


问:
Visual Studio 2010 - Debug Breakpoint
Ive just created a new web site project , added a few lines of code in my .cs file set a break point, and nada, website works, but debug point is not hit.
Any ideas?

Im starting the project with Debugging, running on windows 7 64bit

thanks

答:
Have you enabled debug in the web.config? If so you have to have debug true as below. Normally VS asks to enable debug at the first time if you are trying to run in debug mode.

```<code><system.web>
    <compilation debug="true">
</code>```

ContentLicense: CC BY-SA 3.0

Title: Visual Studio 2010 - Debug Breakpoint

Body:
Have you enabled debug in the web.config? If so you have to have debug true as below. Normally VS asks to enable debug at the first time if you are trying to run in debug mode.

<system.web>
    <compilation debug="true">


问:
Scheme/"The Seasoned Schemer": Question about the syntax of the definition of "try" function
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

```<code>(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))
</code>```

where letcc is defined as

```<code>(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))
</code>```

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

```<code>(letcc success
       (letcc var (success a)) . b)
</code>```

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

```<code>(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4
</code>```

答:
Syntax rules is pattern matching. A dot indicates the car and cdr of a pair just like rest arguments in lambda / define:

```<code>(define (my-list . args)
  args)
</code>```

A list is just nested pairs. eg. (1 2 3) is just fancy way of displaying (1 . (2 . (3 . ()))).

So (this is random symbols in a list) will match (try var a . b) by try matching this, is matches var, random matches a, and (symbols in a list) matches b.

When you see the same in the expansion it means the code should splice the match after the dot. Eg (var . b) with the previous example becomes (is symbols in a list). It is similar to having b ... but cheaper for the system.

Body:
In their book "The Seasoned Schemer", Felleisen and Friedman introduce the try function. According to http://community.schemewiki.org/?seasoned-schemer, this function can be defined as

(define-syntax try
  (syntax-rules ()
    ((try var a . b)
     (letcc success
       (letcc var (success a)) . b))))

where letcc is defined as

(define-syntax letcc
  (syntax-rules ()
    ((letcc var body ...)
     (call-with-current-continuation
       (lambda (var)  body ... )))))

Now, while I understand what try does and how it can be used, I am having trouble to follow the formal definition of it. What exactly is the meaning of the dot in the application of letcc to success and (letcc var (success a)) . b in the lines

(letcc success
       (letcc var (success a)) . b)

of try? Or maybe asked differently: Which part of the definition of try establishes that try is evaluated to b if var is called in a?

Edit 1: Sorry, the definition of letcc was incomplete. Added the missing first line.

Edit 2: The following code can be run in Racket.

(define-syntax letcc
   (syntax-rules ()
                 ((letcc var body ...)
                  (call-with-current-continuation
                    (lambda (var)  body ... )))))

 (define-syntax try
   (syntax-rules ()
                 ((try var a . b)
                  (letcc success
                         (letcc var (success a)) . b))))

(try var (+ 1 1) 4)
; output: 2

(try var (var '(2)) 4)
; output: 4

Body:
Syntax rules is pattern matching. A dot indicates the car and cdr of a pair just like rest arguments in lambda / define:

(define (my-list . args)
  args)

A list is just nested pairs. eg. (1 2 3) is just fancy way of displaying (1 . (2 . (3 . ()))).

So (this is random symbols in a list) will match (try var a . b) by try matching this, is matches var, random matches a, and (symbols in a list) matches b.

When you see the same in the expansion it means the code should splice the match after the dot. Eg (var . b) with the previous example becomes (is symbols in a list). It is similar to having b ... but cheaper for the system.


问:
remove dynamic ID at the click event
I have a form that generates several input fields, colors for a filter.
With JQuery, I generate a dynamic ID for all the fields and during a "Click" event, I ask it to create a DIV to display my filter if my field is not checked, so far everything works.

Where I can't find the correct code writing is when:
during a "Click" event, if my field is checked I want to dynamically delete the DIV created $newDivCouleur

```<code>var couleurUnique = 1;

$("[id^=branche_search_form_couleurs_").on("click", function() {
  if (!$(this).is(":not(:checked)")) {
    var $newDivCouleur = $('<div class="poPupFiltre"><div class="sousBlockPoPup"><a href="#" class="aPoPup"><img class="img-fluid imgPoPup" src="{{ asset ('../build/images/supprimer.svg') }}" alt=""></a><p class="textPopUp"></p></div></div>');
    $newDivCouleur.attr("id", "PopUpCouleur_" + couleurUnique++);
    $($newDivCouleur).appendTo(".maxWidthPoPup").find(".textPopUp").html($(this).val());
  } else {
    console.log("TEST");
    $(this).closest($newDivCouleur).remove();
  }
});
</code>```

答:
var couleurUnique = 1;

$("[id^=branche_search_form_couleurs_]").on("click", function() {
  if (!$(this).is(":not(:checked)")) {
      var $newDivCouleur = $('

');
      $newDivCouleur.attr("id", "PopUpCouleur_" + couleurUnique++);

   $($newDivCouleur).appendTo(".maxWidthPoPup").find(".textPopUp").html($(this).val());
  } else {
      console.log("TEST");
      $(document).find(".poPupFiltre."+$(this).attr('id')).remove();
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="branche_search_form_couleurs_1" />

<input type="checkbox" id="branche_search_form_couleurs_2" />

<div class="maxWidthPoPup">
    <div class="textPopUp"></div>
</div></code>```

I think you need something like this,

What I have done is just add a class with the reference id of checkbox when it's unchecked the class matches with the selected checkbox id will be removed.

Title: remove dynamic ID at the click event

Body:
I have a form that generates several input fields, colors for a filter.
With JQuery, I generate a dynamic ID for all the fields and during a "Click" event, I ask it to create a DIV to display my filter if my field is not checked, so far everything works.

Where I can't find the correct code writing is when:
during a "Click" event, if my field is checked I want to dynamically delete the DIV created $newDivCouleur

var couleurUnique = 1;

$("[id^=branche_search_form_couleurs_").on("click", function() {
  if (!$(this).is(":not(:checked)")) {
    var $newDivCouleur = $('

');
    $newDivCouleur.attr("id", "PopUpCouleur_" + couleurUnique++);
    $($newDivCouleur).appendTo(".maxWidthPoPup").find(".textPopUp").html($(this).val());
  } else {
    console.log("TEST");
    $(this).closest($newDivCouleur).remove();
  }
});

Body:
var couleurUnique = 1;

$("[id^=branche_search_form_couleurs_]").on("click", function() {
  if (!$(this).is(":not(:checked)")) {
      var $newDivCouleur = $('<div class="poPupFiltre '+$(this).attr('id')+'"><div class="sousBlockPoPup"><a href="#" class="aPoPup"><img class="img-fluid imgPoPup" src="#" alt=""></a><p class="textPopUp"></p></div></div>');
      $newDivCouleur.attr("id", "PopUpCouleur_" + couleurUnique++);

   $($newDivCouleur).appendTo(".maxWidthPoPup").find(".textPopUp").html($(this).val());
  } else {
      console.log("TEST");
      $(document).find(".poPupFiltre."+$(this).attr('id')).remove();
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="branche_search_form_couleurs_1" />

<input type="checkbox" id="branche_search_form_couleurs_2" />

<div class="maxWidthPoPup">
    <div class="textPopUp"></div>
</div>

I think you need something like this,

What I have done is just add a class with the reference id of checkbox when it's unchecked the class matches with the selected checkbox id will be removed.


问:
Error on script linked to getlastrow - i think
I can see that this has been asked elsewhere however the solutions have not worked for me or I have not understood them.

I have been using this bit of code for some time in multiple google sheets without issue. Suddenly this one sheet is throwing up the error "The coordinates of the target range are outside the dimensions of the sheet."

Can anyone help me resolve?

The code I have is as follows:

```<code>function submit() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet1 = ss.getSheetByName("Check Sheet");
   var sheet2 = ss.getSheetByName("Data");
   sheet1.getRange("A1:AA1").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
}
</code>```

Thank you in advance for your time and help.

答:
Most probably you are getting this error because the last row with content in sheet Data (that is, sheet2.getLastRow()) is also the last row of the sheet, regardless of content. That is, you are trying to copy a range to a row (sheet2.getLastRow() + 1) that does not exist.

To avoid this error, you should insert a new blank row before copying the range if the last row with content is the absolute last row of the sheet. You can use getMaxRows to check that.

So you could add this just before using copyTo, to insert a row if the last row with content is the absolute last row in the sheet:

if (sheet2.getLastRow() === sheet2.getMaxRows()) {
  sheet2.insertRowAfter(sheet2.getLastRow());
}
```

Reference:

Sheet.getMaxRows()

Sheet.insertRowAfter(afterPosition)

Body:
I can see that this has been asked elsewhere however the solutions have not worked for me or I have not understood them.

I have been using this bit of code for some time in multiple google sheets without issue. Suddenly this one sheet is throwing up the error "The coordinates of the target range are outside the dimensions of the sheet."

Can anyone help me resolve?

The code I have is as follows:

function submit() {
   var ss = SpreadsheetApp.getActiveSpreadsheet();
   var sheet1 = ss.getSheetByName("Check Sheet");
   var sheet2 = ss.getSheetByName("Data");
   sheet1.getRange("A1:AA1").copyTo(sheet2.getRange(sheet2.getLastRow()+1,1,1,7), {contentsOnly:true});
}

Thank you in advance for your time and help.

Body:
Most probably you are getting this error because the last row with content in sheet Data (that is, sheet2.getLastRow()) is also the last row of the sheet, regardless of content. That is, you are trying to copy a range to a row (sheet2.getLastRow() + 1) that does not exist.

To avoid this error, you should insert a new blank row before copying the range if the last row with content is the absolute last row of the sheet. You can use getMaxRows to check that.

So you could add this just before using copyTo, to insert a row if the last row with content is the absolute last row in the sheet:

if (sheet2.getLastRow() === sheet2.getMaxRows()) {
  sheet2.insertRowAfter(sheet2.getLastRow());
}

Reference:

Sheet.getMaxRows()

Sheet.insertRowAfter(afterPosition)


问:
Ceiling date (Similar to R's ceiling_date) in Python
Suppose I have the following pandas dataframe,

```<code>import pandas as pd
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

df = pd.DataFrame([[201901, 'Value1'], [201902, 'Value2'], [201707, 'Value3], columns=['Col1', 'Col2'])
╔════════╦═════════╗
║  Col1  ║  Col2   ║
╠════════╬═════════╣
║ 201901 ║ Value 1 ║
║ 201902 ║ Value 2 ║
║ 201707 ║ Value 3 ║
╚════════╩═════════╝
</code>```

And I want the first column to be like this (I want the last day of every month):

```<code>╔════════════╦═════════╗
║    Col1    ║  Col2   ║
╠════════════╬═════════╣
║ 2019-01-31 ║ Value 1 ║
║ 2019-02-28 ║ Value 2 ║
║ 2017-07-31 ║ Value 3 ║
╚════════════╩═════════╝
</code>```

So, to acchieve that I've tried the following:

```<code>next_month = {'01':'02', '02':'03',
              '03':'04', '04':'05',
              '05':'06', '06':'07',
              '07':'08', '08':'09',
              '09':'10', '10':'11',
              '11':'12', '12':'01'}

df = df['Col1'].apply(lambda x: str(int(str(x)[:4])+1) + next_month[str(x)[-2:]
                      if str(x)[-2:] else str(x)[:4] + next_month[str(x)[-2:]])

df['Col1'] = pd.to_datetime(df['Col1'], format='%Y%m') - timedelta(days=1)
</code>```

In that last part of the code, I'm replacing the row month for the following month, and checking if it's december adding one a year.

Is there a way to acchieve this effiently? I've tried also this but it took SO MUCH time, even more than the previous code showed.

```<code>df['Col1'] = df['Col1'].apply(lambda x: (x + relativedelta(months=1)) - relativedelta(days=1))
</code>```

答:
I think tseries.offsets.MonthEnd is what you need?

```<code>pd.to_datetime(df['Col1'], format='%Y%m') + pd.tseries.offsets.MonthEnd(1)
</code>```

Output:

```<code>0   2019-01-31
1   2019-02-28
2   2017-07-31
Name: Col1, dtype: datetime64[ns]
</code>```

Body:
Suppose I have the following pandas dataframe,

import pandas as pd
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

df = pd.DataFrame([[201901, 'Value1'], [201902, 'Value2'], [201707, 'Value3], columns=['Col1', 'Col2'])
╔════════╦═════════╗
║  Col1  ║  Col2   ║
╠════════╬═════════╣
║ 201901 ║ Value 1 ║
║ 201902 ║ Value 2 ║
║ 201707 ║ Value 3 ║
╚════════╩═════════╝

And I want the first column to be like this (I want the last day of every month):

╔════════════╦═════════╗
║    Col1    ║  Col2   ║
╠════════════╬═════════╣
║ 2019-01-31 ║ Value 1 ║
║ 2019-02-28 ║ Value 2 ║
║ 2017-07-31 ║ Value 3 ║
╚════════════╩═════════╝

So, to acchieve that I've tried the following:

next_month = {'01':'02', '02':'03',
              '03':'04', '04':'05',
              '05':'06', '06':'07',
              '07':'08', '08':'09',
              '09':'10', '10':'11',
              '11':'12', '12':'01'}

df = df['Col1'].apply(lambda x: str(int(str(x)[:4])+1) + next_month[str(x)[-2:]
                      if str(x)[-2:] else str(x)[:4] + next_month[str(x)[-2:]])

df['Col1'] = pd.to_datetime(df['Col1'], format='%Y%m') - timedelta(days=1)

In that last part of the code, I'm replacing the row month for the following month, and checking if it's december adding one a year.

Is there a way to acchieve this effiently? I've tried also this but it took SO MUCH time, even more than the previous code showed.

df['Col1'] = df['Col1'].apply(lambda x: (x + relativedelta(months=1)) - relativedelta(days=1))

Body:
I think tseries.offsets.MonthEnd is what you need?

pd.to_datetime(df['Col1'], format='%Y%m') + pd.tseries.offsets.MonthEnd(1)

Output:

0   2019-01-31
1   2019-02-28
2   2017-07-31
Name: Col1, dtype: datetime64[ns]


问:
Get current language in Portable Object Localization using javascript
I have a ASP.NET CORE 3.1 c# Web Application with multilanguage support.
The multilanguage support uses Portable Object Localization.
I'm in need to get the current language via Javascript.
It is stored in a cookie setted using the following method :

```<code>    //GET /SetLanguage
    [HttpGet]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential= true }
        );
        return LocalRedirect(returnUrl);
    }
</code>```

Hoe can I do it?
Thanks,

答:
I think you can use the following code.</p>

```<code>var current = document.cookie.split('; ').reduce((r, v) => {
                 const parts = v.split('=')
                 return parts[0] === '.AspNetCore.Culture'? decodeURIComponent(parts[1]) : r
                      }, '').split('|')[0].split('=')[1]
</code>```

Body:
I have a ASP.NET CORE 3.1 c# Web Application with multilanguage support.
The multilanguage support uses Portable Object Localization.
I'm in need to get the current language via Javascript.
It is stored in a cookie setted using the following method :

    //GET /SetLanguage
    [HttpGet]
    public IActionResult SetLanguage(string culture, string returnUrl)
    {
        Response.Cookies.Append(
            CookieRequestCultureProvider.DefaultCookieName,
            CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
        new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1), IsEssential= true }
        );
        return LocalRedirect(returnUrl);
    }

Hoe can I do it?
Thanks,

Body:
I think you can use the following code.

var current = document.cookie.split('; ').reduce((r, v) => {
                 const parts = v.split('=')
                 return parts[0] === '.AspNetCore.Culture'? decodeURIComponent(parts[1]) : r
                      }, '').split('|')[0].split('=')[1]


问:
Scapy - Add field with type dependant on other field
I am trying to add a field to a packet with a type that is dependant on another field value.
One of these "types" is a var length string, with an additional "len" attribute if applicable.

Consider the following example:

from scapy.all import *

class TestPacket(Packet):
        fields_desc=[
                  ShortField("index", 0),
                  ByteEnumField("type", 0 , { 1: "String", 2: "Integer" }),
                  ConditionalField(FieldLenField("len", None, length_of="data"), lambda x: x.type==1),
                  ConditionalField(StrLenField("data", "", length_from=lambda pkt:pkt.len), lambda x: x.type==7 or x.type==11),
                  ConditionalField(IntField("data", 1), lambda pkt: pkt.type==2)]

p = TestPacket(index=12, type=1, data="My Sample String")
p.show2()

p = TestPacket(index=13, type=2, data=5)
p.show2()

```

The problem is that the "len" is always set to 4 (the length of the IntField, as it is the last "data" conditional field).

What is the best way to achieve this functionality? Conditional fields with different names? Storing the raw bytes as a var length string, no matter the type?

答:
You can use MultipleTypeField. See
https://scapy.readthedocs.io/en/latest/api/scapy.fields.html#scapy.fields.MultipleTypeField

For instance:

```<code>class DebugPacket(Packet):
    fields_desc = [
        ByteEnumField("atyp", 0x1, {0x1: "IPv4", 0x3: "DNS", 0x4: "IPv6"}),
        MultipleTypeField(
            [
                # IPv4
                (IPField("addr", "0.0.0.0"), lambda pkt: pkt.atyp == 0x1),
                # DNS
                (DNSStrField("addr", ""), lambda pkt: pkt.atyp == 0x3),
                # IPv6
                (IP6Field("addr", "::"), lambda pkt: pkt.atyp == 0x4),
            ],
            StrField("addr", "")  # By default
        ),
    ]
</code>```

It allows you to have the same field having multiple types depending on a condition

Body:
I am trying to add a field to a packet with a type that is dependant on another field value.
One of these "types" is a var length string, with an additional "len" attribute if applicable.

Consider the following example:

from scapy.all import *

class TestPacket(Packet):
        fields_desc=[
                  ShortField("index", 0),
                  ByteEnumField("type", 0 , { 1: "String", 2: "Integer" }),
                  ConditionalField(FieldLenField("len", None, length_of="data"), lambda x: x.type==1),
                  ConditionalField(StrLenField("data", "", length_from=lambda pkt:pkt.len), lambda x: x.type==7 or x.type==11),
                  ConditionalField(IntField("data", 1), lambda pkt: pkt.type==2)]

p = TestPacket(index=12, type=1, data="My Sample String")
p.show2()

p = TestPacket(index=13, type=2, data=5)
p.show2()

The problem is that the "len" is always set to 4 (the length of the IntField, as it is the last "data" conditional field).

What is the best way to achieve this functionality? Conditional fields with different names? Storing the raw bytes as a var length string, no matter the type?

Body:
You can use MultipleTypeField. See
https://scapy.readthedocs.io/en/latest/api/scapy.fields.html#scapy.fields.MultipleTypeField

For instance:

class DebugPacket(Packet):
    fields_desc = [
        ByteEnumField("atyp", 0x1, {0x1: "IPv4", 0x3: "DNS", 0x4: "IPv6"}),
        MultipleTypeField(
            [
                # IPv4
                (IPField("addr", "0.0.0.0"), lambda pkt: pkt.atyp == 0x1),
                # DNS
                (DNSStrField("addr", ""), lambda pkt: pkt.atyp == 0x3),
                # IPv6
                (IP6Field("addr", "::"), lambda pkt: pkt.atyp == 0x4),
            ],
            StrField("addr", "")  # By default
        ),
    ]

It allows you to have the same field having multiple types depending on a condition


问:
Need Studies, Proof or Research That Show Image Copy Protection Is Not Worth It
I am trying to convince someone that image copy protection such as watermarks, javascript no right clicks, blank image overlays etc is not worth the effort since they are easily bypassed by even non-technical users.

I am also trying to convince them that these measures annoys customers as it impedes the user experience and does nothing to prevent image theft. At the end of the day if its on the internet, its public and people can take it if they want.

So what I'm looking for is a good study, proof, research, anything which has numbers to back up a fall in sales, user experience etc before and after these measures.

Any ideas?

答:
You could present the following:

PrtScrn - even if the right click is prevented the user can still do a print screen of the print screen and cutout the image in Paint

Retouching - even if the watermarek was on the picture it can be easly removed by any user who has read a basic photoshop/other graphic editing software tutorial on retouching photos.

But in the end I think that the best protection against theft is to actually have the image licensed and if you spot or get notified that someone used it without your premission I think you have all the arguments to go against him. You can't blame if the user saves it in his Documents folder - it same as if you hand out 1000 flyers and than sue people for having them in the drawer at home since it uses your picture.


问:
How to add quotes to a specific place in a vector in R?
I have a data frame in R to which I would like to add quotation marks at some specific place. One line of this data frame looks like this:

```<code>> df
    V1       V2       V3   V4 V5 V6         V7         V8 V9
1 chr9 17025523 17026706 SOX2  .  - ncbiRefSeq transcript  .
                                                        V10
1 gene_id SOX2; transcript_id NM_205188.2;  gene_name SOX2;
</code>```

I'm interested in the last column (df$V10):

```<code>> df$V10
gene_id SOX10; transcript_id NM_205188.2;  gene_name SOX10;
</code>```

And I would like to add quotations marks around each word in front of the ";". The output would be:

```<code>> new_df$V10
gene_id "SOX10"; transcript_id "NM_205188.2";  gene_name "SOX10";
</code>```

Thanks !

答:
You can use a regular expression to replace each word preceding a ; with the word in quotes.

```<code>s = 'gene_id SOX10; transcript_id NM_205188.2;  gene_name SOX10;'
str_replace_all(s, '([^[:blank:]]+);', '"\\1";')
# "gene_id \"SOX10\"; transcript_id \"NM_205188.2\";  gene_name \"SOX10\";"
</code>```

Body:
I have a data frame in R to which I would like to add quotation marks at some specific place. One line of this data frame looks like this:

> df
    V1       V2       V3   V4 V5 V6         V7         V8 V9
1 chr9 17025523 17026706 SOX2  .  - ncbiRefSeq transcript  .
                                                        V10
1 gene_id SOX2; transcript_id NM_205188.2;  gene_name SOX2;

I'm interested in the last column (df$V10):

> df$V10
gene_id SOX10; transcript_id NM_205188.2;  gene_name SOX10;

And I would like to add quotations marks around each word in front of the ";". The output would be:

> new_df$V10
gene_id "SOX10"; transcript_id "NM_205188.2";  gene_name "SOX10";

Thanks !

Body:
You can use a regular expression to replace each word preceding a ; with the word in quotes.

s = 'gene_id SOX10; transcript_id NM_205188.2;  gene_name SOX10;'
str_replace_all(s, '([^[:blank:]]+);', '"\\1";')
# "gene_id \"SOX10\"; transcript_id \"NM_205188.2\";  gene_name \"SOX10\";"


问:
Words generating in Python
Let's consider we have an alphabet {'0','1'} and want to create a list of all words of length n, so they don't contain two zeros in a row. My idea of this implementation goes around:

```<code>def words(n):
    if n == 0:
        return ['']
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or b != '0']
</code>```

The output of words(3) is the following:

```<code>['010', '110', '001', '101', '011', '111']
                 ^is the wrong one
</code>```

Can you see my mistake or where my idea of generator goes wrong?

答:
The problem with your implementation is that once b grows to more than one character, it can never evaluate as equal to '0'. As you actually ask about the first letter of b, python has a string method ready for you:

```<code>def words(n):
    if n == 0:
        return ['']
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or not b.startswith('0')]
</code>```

The interface is kept, so you can e.g.:

```<code>words(3)  # ['010', '110', '101', '011', '111']
</code>```

Title: Words generating in Python

Body:
Let's consider we have an alphabet {'0','1'} and want to create a list of all words of length n, so they don't contain two zeros in a row. My idea of this implementation goes around:

def words(n):
    if n == 0:
        return ['']
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or b != '0']

The output of words(3) is the following:

['010', '110', '001', '101', '011', '111']
                 ^is the wrong one

Can you see my mistake or where my idea of generator goes wrong?

Body:
The problem with your implementation is that once b grows to more than one character, it can never evaluate as equal to '0'. As you actually ask about the first letter of b, python has a string method ready for you:

def words(n):
    if n == 0:
        return ['']
    return [a+b for b in words(n-1) for a in ['0','1'] if a != '0' or not b.startswith('0')]

The interface is kept, so you can e.g.:

words(3)  # ['010', '110', '101', '011', '111']


答:
Not sure if this is the think you need

```<code>r <- gsub("(.*?\\s)(\\w+)(;)","\\1\"\\2\"\\3",v)
</code>```

such that

```<code>> r
[1] "gene_id \"SOX10\"; transcript_id NM_205188.2; gene_name \"SOX10\";"
</code>```

DATA

```<code>v <- 'gene_id SOX10; transcript_id NM_205188.2; gene_name SOX10;'
</code>```

Title: How to add quotes to a specific place in a vector in R?

Body:
Not sure if this is the think you need

r <- gsub("(.*?\\s)(\\w+)(;)","\\1\"\\2\"\\3",v)

such that

> r
[1] "gene_id \"SOX10\"; transcript_id NM_205188.2; gene_name \"SOX10\";"

DATA

v <- 'gene_id SOX10; transcript_id NM_205188.2; gene_name SOX10;'


问:
Delete node in binary search tree
I have implemented the following methods for deleting a node in a BST for following the example that is posted here:

class NodeT

```<code>public class NodeT {
    int elem;
    NodeT left;
    NodeT right;
    public NodeT(int elem){
        this.elem=elem;
    }
}
</code>```

class BinaryTree

```<code>public class BinaryTree {
    NodoT root;
    public void insertElem(int n){
        root=addRec(root,n);
    }
    public NodoT addRec(NodeT n, int elem){
        if (n==null){
            n=new NodeT(elem);
        }
        else{
            if (elem<n.elem){
                n.left=addRec(n.left,elem);
            }
            else{
                n.right=addRec(n.right,elem);
            }
        }
        return n;
    }
    public void inorder(NodeT n){
        if (n!=null){
            inorder(n.left);
            System.out.println(n.elem);
            inorden(n.right);
        }
    }

    public NodeT search(NodeT root, int n){
        if (root.elem==n) return root;
        else{
            if (n<root.elem){
                if (root.left!=null){
                    return search(root.left,n);
                }
                else return null;
            }
            else{
                if (root.right!=null){
                    return search(root.right,n);
                }
                else return null;
            }
        }
    }

    public void delete(int n){
       root=deleteNode(root,n);
    }

    public NodeT deleteNode(NodeT curr, int n){
        NodoT answ;
        answ=search(curr,n);
        if (answ==null){
            System.out.println("not found");
            return curr;
        }
        else{

            if (curr.left==null)return curr.right;
            else if (curr.right==null) return curr.left;
            curr.elem=minValue(curr.right);
            curr.right=deleteNode(curr.right,curr.elem);
        }
        return curr;
    }

    int minValue(NodoT curr){

        int min=curr.elem;
        while (curr.left!=null){
            menor=curr.left.elem;
            curr=curr.left;
        }
        return min;
    }

//main program

BinaryTree bt=new BinaryTree();
   int data[]={50,30,70,20,40,60,80};

    for (int i=0;i<data.length;i++){
        bt.insertElem(data[i]);
    }
    bt.inorder(bt.root);

    bt.delete(20);
    bt.inorder(bt.root);

    bt.delete(30);
    bt.inorder(bt.root);

    bt.delete(50);
    bt.inorder(bt.root);
</code>```

However, when I tested,  it prints "not found" on line bt.delete(50);, what am I doing wrong?

答:
There are plenty of mistakes in the code, I think your converted from you language and missed some variable names. However, I corrected the names and tested the code.

Problem: In your deleteNode(), you are not recurring down the tree i.e. checking If element is less than or greater than the value of curr. You need to add few more IF checks.

Solution: Replace your deleteNode() with this one.

```<code>public NodeT deleteNode(NodeT curr, int n){
    NodeT answ;
    answ=search(curr,n);
    if (answ==null){
        System.out.println("not found");
        return curr;
    }
    // need to check whether value is small or greater
    if (n < curr.elem)
        curr.left = deleteNode(curr.left, n);
    else if (n > curr.elem)
        curr.right = deleteNode(curr.right, n);

    // if value is same, means this is the node to be deleted
    else{

        if (curr.left==null)
            return curr.right;
        else if (curr.right==null)
            return curr.left;
        curr.elem=minValue(curr.right);
        curr.right=deleteNode(curr.right,curr.elem);
    }
    return curr;
}
</code>```

Title: Delete node in binary search tree

Body:
I have implemented the following methods for deleting a node in a BST for following the example that is posted here:

class NodeT

public class NodeT {
    int elem;
    NodeT left;
    NodeT right;
    public NodeT(int elem){
        this.elem=elem;
    }
}

class BinaryTree

public class BinaryTree {
    NodoT root;
    public void insertElem(int n){
        root=addRec(root,n);
    }
    public NodoT addRec(NodeT n, int elem){
        if (n==null){
            n=new NodeT(elem);
        }
        else{
            if (elem<n.elem){
                n.left=addRec(n.left,elem);
            }
            else{
                n.right=addRec(n.right,elem);
            }
        }
        return n;
    }
    public void inorder(NodeT n){
        if (n!=null){
            inorder(n.left);
            System.out.println(n.elem);
            inorden(n.right);
        }
    }

    public NodeT search(NodeT root, int n){
        if (root.elem==n) return root;
        else{
            if (n<root.elem){
                if (root.left!=null){
                    return search(root.left,n);
                }
                else return null;
            }
            else{
                if (root.right!=null){
                    return search(root.right,n);
                }
                else return null;
            }
        }
    }

    public void delete(int n){
       root=deleteNode(root,n);
    }

    public NodeT deleteNode(NodeT curr, int n){
        NodoT answ;
        answ=search(curr,n);
        if (answ==null){
            System.out.println("not found");
            return curr;
        }
        else{

            if (curr.left==null)return curr.right;
            else if (curr.right==null) return curr.left;
            curr.elem=minValue(curr.right);
            curr.right=deleteNode(curr.right,curr.elem);
        }
        return curr;
    }

    int minValue(NodoT curr){

        int min=curr.elem;
        while (curr.left!=null){
            menor=curr.left.elem;
            curr=curr.left;
        }
        return min;
    }

//main program

BinaryTree bt=new BinaryTree();
   int data[]={50,30,70,20,40,60,80};

    for (int i=0;i<data.length;i++){
        bt.insertElem(data[i]);
    }
    bt.inorder(bt.root);

    bt.delete(20);
    bt.inorder(bt.root);

    bt.delete(30);
    bt.inorder(bt.root);

    bt.delete(50);
    bt.inorder(bt.root);

However, when I tested,  it prints "not found" on line bt.delete(50);, what am I doing wrong?

Body:
There are plenty of mistakes in the code, I think your converted from you language and missed some variable names. However, I corrected the names and tested the code.

Problem: In your deleteNode(), you are not recurring down the tree i.e. checking If element is less than or greater than the value of curr. You need to add few more IF checks.

Solution: Replace your deleteNode() with this one.

public NodeT deleteNode(NodeT curr, int n){
    NodeT answ;
    answ=search(curr,n);
    if (answ==null){
        System.out.println("not found");
        return curr;
    }
    // need to check whether value is small or greater
    if (n < curr.elem)
        curr.left = deleteNode(curr.left, n);
    else if (n > curr.elem)
        curr.right = deleteNode(curr.right, n);

    // if value is same, means this is the node to be deleted
    else{

        if (curr.left==null)
            return curr.right;
        else if (curr.right==null)
            return curr.left;
        curr.elem=minValue(curr.right);
        curr.right=deleteNode(curr.right,curr.elem);
    }
    return curr;
}


问:
Use of function inside a for loop
I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?

Here is the code I tried but I do not get any output.

```<code>def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)
</code>```

答:
Yes, it is possible but your code would not work because x inside the loop will be unknown:

```<code>for i in test_rng:
    my_fun1(i)
    print(x)
    my_fun2(x)
</code>```

Possibly, you want to do something like:

```<code>for i in test_rng:
    x = my_fun1(i)
    print(x)
    my_fun2(x)
</code>```

You may also want to double-check the code in my_fun1():

```<code>def my_fun1(i):
    x=+i
    return x
</code>```

as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i

Title: Use of function inside a for loop

Body:
I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?

Here is the code I tried but I do not get any output.

def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

Body:
Yes, it is possible but your code would not work because x inside the loop will be unknown:

for i in test_rng:
    my_fun1(i)
    print(x)
    my_fun2(x)

Possibly, you want to do something like:

for i in test_rng:
    x = my_fun1(i)
    print(x)
    my_fun2(x)

You may also want to double-check the code in my_fun1():

def my_fun1(i):
    x=+i
    return x

as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i


问:
Create a custom View with an enum
I am creating a custom view that has an enum to create a custom shape wherever it's called.
I want to control this enum from Init, I am not sure this is the best way

```<code>class ReadOnlyView: UIView {

   public enum Corner {
      case half
      case quarter
   }

   public var corner = Corner.half

   public init(corner: Corner) {
      self.corner = corner
   }

   var textView = UITextView().autolayoutView()
</code>```

It shows this error in the init

```<code>'super.init' isn't called on all paths before returning from initializer
</code>```

Anyone can help me that what is the best way to implement this enum, I want when this view is called, it also require to set the Corner

Many thanks

答:
This code should work for you:

```<code>class ReadOnlyView: UIView {

    public enum Corner {
        case half
        case quarter
    }

    public var corner: Corner

    public init(corner: Corner) {

        self.corner = corner
        super.init(frame: .zero)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
</code>```

In order to create an object from ReadOnlyView you should do:

```<code>let view = ReadOnlyView(corner: .half)
</code>```

Title: Create a custom View with an enum

Body:
I am creating a custom view that has an enum to create a custom shape wherever it's called.
I want to control this enum from Init, I am not sure this is the best way

class ReadOnlyView: UIView {

   public enum Corner {
      case half
      case quarter
   }

   public var corner = Corner.half

   public init(corner: Corner) {
      self.corner = corner
   }

   var textView = UITextView().autolayoutView()

It shows this error in the init

'super.init' isn't called on all paths before returning from initializer

Anyone can help me that what is the best way to implement this enum, I want when this view is called, it also require to set the Corner

Many thanks

Body:
This code should work for you:

class ReadOnlyView: UIView {

    public enum Corner {
        case half
        case quarter
    }

    public var corner: Corner

    public init(corner: Corner) {

        self.corner = corner
        super.init(frame: .zero)
    }

    @available(*, unavailable)
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}

In order to create an object from ReadOnlyView you should do:

let view = ReadOnlyView(corner: .half)


问:
How to remove decimals on whole numbers
In Excel for Mac, I need to remove the zeros and decimal point from whole numbers generated by a formula. The VBA code basically takes any fraction typed and applies the formula =FRACTION+1, so 5/2 becomes 3.50, 15/8 is 2.88 and so on.

But when the fractions entered are going to be whole numbers, like 7/1, 10/1 etc, the whole numbers have .00 at the end.

How is it possible for that not to happen?

I am unsure if it something to be done post the VBA code doing its job, or whether it could be incorporated into the original code.

Just to let you know, if I format the cell to Custom and General after it has been converted, this solves the problem, but this cannot be done beforehand, as if the cell is Custom and General, when a fraction is entered, it becomes a date.

So here is the code I have. It works perfectly except for the fact that whole numbers have 2 decimal places.

```<code>Private Sub Worksheet_Change(ByVal Target As Range)
  On Error GoTo err_handler

  Application.EnableEvents = False

  If Target.CountLarge > 1 Then GoTo exit_handler
  If Target = Empty Then GoTo exit_handler

  If Not Intersect(Target, Columns("P")) Is Nothing Then
    With Target
      .NumberFormat = "@"
      .Value = CDbl(Evaluate(.Value & "+1"))
      .NumberFormat = "0.00"
    End With
  End If

exit_handler:
  Application.EnableEvents = True
Exit Sub

err_handler:
  MsgBox Err.Number & ": " & Err.Description
  Resume exit_handler
End Sub
</code>```

cheers

答:
A quick if statement can sort this. Just change your line .NumberFormat = "0.00" to the following:

```<code>      If (.value - Fix(.value)) = 0 Then
        .NumberFormat = "0"
      Else
        .NumberFormat = "0.00"
      End If
</code>```

The Fix() function removes the decimal part of the fraction so by deducting this from the original value, you're left with the decimal portion only. If what remains is zero then the number is a whole number and can be formatted accordingly.

Title: How to remove decimals on whole numbers

Body:
In Excel for Mac, I need to remove the zeros and decimal point from whole numbers generated by a formula. The VBA code basically takes any fraction typed and applies the formula =FRACTION+1, so 5/2 becomes 3.50, 15/8 is 2.88 and so on.

But when the fractions entered are going to be whole numbers, like 7/1, 10/1 etc, the whole numbers have .00 at the end.

How is it possible for that not to happen?

I am unsure if it something to be done post the VBA code doing its job, or whether it could be incorporated into the original code.

Just to let you know, if I format the cell to Custom and General after it has been converted, this solves the problem, but this cannot be done beforehand, as if the cell is Custom and General, when a fraction is entered, it becomes a date.

So here is the code I have. It works perfectly except for the fact that whole numbers have 2 decimal places.

Private Sub Worksheet_Change(ByVal Target As Range)
  On Error GoTo err_handler

  Application.EnableEvents = False

  If Target.CountLarge > 1 Then GoTo exit_handler
  If Target = Empty Then GoTo exit_handler

  If Not Intersect(Target, Columns("P")) Is Nothing Then
    With Target
      .NumberFormat = "@"
      .Value = CDbl(Evaluate(.Value & "+1"))
      .NumberFormat = "0.00"
    End With
  End If

exit_handler:
  Application.EnableEvents = True
Exit Sub

err_handler:
  MsgBox Err.Number & ": " & Err.Description
  Resume exit_handler
End Sub

cheers

Body:
A quick if statement can sort this. Just change your line .NumberFormat = "0.00" to the following:

      If (.value - Fix(.value)) = 0 Then
        .NumberFormat = "0"
      Else
        .NumberFormat = "0.00"
      End If

The Fix() function removes the decimal part of the fraction so by deducting this from the original value, you're left with the decimal portion only. If what remains is zero then the number is a whole number and can be formatted accordingly.


答:
Have you tried datetime.datetime.strptime()?

So you would take a time (ex. 25.02.2019):
datetime.datetime.strptime('25.02.2019', '%d.%m.%Y')

and it reutrn s datetime format. If your date is in a different starting format, just change the '%d.%m.%Y' to be in the correct format.

Title: How to convert date from string format in python

Body:
I have below table. I want to count timedelta between first and second date, second and third and so on in a for loop…
I really do not want to convert my dates in table to integer set to use timedelta() function. Is there any function in python which can convert str like: ’30.06.2019’ or 30/06/2019 to date ?
Perfect would be convert all tab[i][2] to date and then count time date between them in a loop.

tab = [ [21091705,  0,'30.06.2019'],
        [21091705,  653777,'29.06.2019'],
        [21091705,  653842,'29.06.2019'],
        [21091705,  641701,'28.06.2019'],
        [21091705,  642000,'27.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  642030,'25.06.2019'],
        [21091705,  637030,'25.06.2019'],
        [21091705,  0,'25.06.2019'],
        [21091705,  0,'17.05.2019'],
        [21091705,  0,'25.06.2019']
        ]


问:
Is getc() and getchar() well-defined function?
```<code>printf("%c %c", getc(stdin), getc(stdin));
rewind(stdin); printf("\n");
printf("%c %c", getchar(), getchar());

output
s

 s
s

 s
</code>```

I wrote the source code like that and I pressed s, enter, s, enter sequentially on windows console application using vs2017. Console shows me what I put and print output when I press the  key. The result's appearance is like s, enter, enter, space, s, s, enter, enter, space, s. Did I use the function in wrong way?

Q1. I pressed s, enter sequentially, but why output is reversed?

Q2. At output's third line and sixth line, why is there exist whitespace like 　s not s?.

答:
Explaining the output

The arguments to a function can be evaluated in any order that the compiler chooses.

The original code looked like this (missing printf("\n"); compared to the revised code):

```<code>printf("%c %c", getc(stdin), getc(stdin));
rewind(stdin);
printf("%c %c", getchar(), getchar());
</code>```

Your 'output' in the question is extremely difficult to read and interpret.  However, I'm reasonably sure that what you show consists of both your input and the program's output.
You say you type s enter twice.  The output you get, copied from the question, is:

```<code>s

 s
s

 s
</code>```

The first s and the newline that follows are what you typed. The blank line is there because the newline was read by the getc(stdin) that appears first in the argument list, then there's the blank from the format string, and the s which was read by the getc(stdin) that appears second in the argument list.  Your compiler, it seems, evaluates the arguments right to left — but you should not rely on that.

Now we run into a problem; there's a newline after the second s that isn't accounted for by the code you showed when I wrote this answer.  Since then, you've added the printf("\n"); which explains the output you saw.

Putting that aside, the third s is followed by a newline and is what you typed.  And again, the blank line is from the newline and then space and s is the rest of the output, and there's probably a newline after that too.

JFTR, when I run your code (program getc73 compiled from getc73.c), I see:

```<code>$ getc73
s

 ss

 s$
$
</code>```

The $ is my prompt; the first s is what I type; then the newline, blank and s are printed (with no newline at the end); then the second s on the third line is my next s and return, followed by the newline and blank s.  Since there's no newline at the end, my prompt appears immediately after the fourth s.  I hit return to print another prompt at the start of the line.

Why rewind(stdin) is a no-op

You can't successfully execute an fseek() call on a terminal device.  They don't have any storage so you can't move around like that.  The rewind() function is effectively:

```<code>void rewind(FILE *fp)
{
    fseek(fp, 0, SEEK_SET);
}
</code>```

So, the rewind(stdin) call fails to rewind, but it has no way to report that to you because it returns no value.  It does no good; it doesn't do any harm either.  If it had worked, you would not have needed to enter the information twice.

If the standard input had been a file instead of a terminal, then the rewind would succeed — disks are seekable.

Improved formatting

If you were on a POSIX system, I'd suggest you used a feature of POSIX printf() that allows you to print the same argument more than once:

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

int main(void)
{
    printf("[%1$c] %1$d [%2$c] %2$d\n", getc(stdin), getc(stdin));
    printf("[%1$c] %1$d [%2$c] %2$d\n", getchar(), getchar());
    return 0;
}
</code>```

When I run that on my terminal (it's a Mac running macOS Mojave 10.14.6 using GCC 9.2.0), I get:

```<code>s
[
] 10 [s] 115
s
[
] 10 [s] 115
</code>```

The lines with just the s on them are what I typed; the other lines show that the newline is printed before the letter s.

This probably won't work for you in VS2017 — the manual for printf() formats on Windows strongly suggests it won't work.  Your best bet, probably, is to use:

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

int main(void)
{
    printf("%d %d\n", getc(stdin), getc(stdin));
    printf("%d %d\n", getchar(), getchar());
    return 0;
}
</code>```

That generates:

```<code>s
10 115
s
10 115
</code>```

Choosing a good format to show what you're seeing is an art form.  Don't forget to include newlines at the end of (most) printf() format strings.  Obviously, if you're building up a line of output piecemeal, you don't want newlines at the end of intermediate formats, but the majority of printf() statements should have a newline at the end of the format.

Body:
printf("%c %c", getc(stdin), getc(stdin));
rewind(stdin); printf("\n");
printf("%c %c", getchar(), getchar());

output
s

 s
s

 s

I wrote the source code like that and I pressed s, enter, s, enter sequentially on windows console application using vs2017. Console shows me what I put and print output when I press the  key. The result's appearance is like s, enter, enter, space, s, s, enter, enter, space, s. Did I use the function in wrong way?

Q1. I pressed s, enter sequentially, but why output is reversed?

Q2. At output's third line and sixth line, why is there exist whitespace like 　s not s?.

Body:
Explaining the output

The arguments to a function can be evaluated in any order that the compiler chooses.

The original code looked like this (missing printf("\n"); compared to the revised code):

printf("%c %c", getc(stdin), getc(stdin));
rewind(stdin);
printf("%c %c", getchar(), getchar());

Your 'output' in the question is extremely difficult to read and interpret.  However, I'm reasonably sure that what you show consists of both your input and the program's output.
You say you type s enter twice.  The output you get, copied from the question, is:

s

 s
s

 s

The first s and the newline that follows are what you typed. The blank line is there because the newline was read by the getc(stdin) that appears first in the argument list, then there's the blank from the format string, and the s which was read by the getc(stdin) that appears second in the argument list.  Your compiler, it seems, evaluates the arguments right to left — but you should not rely on that.

Now we run into a problem; there's a newline after the second s that isn't accounted for by the code you showed when I wrote this answer.  Since then, you've added the printf("\n"); which explains the output you saw.

Putting that aside, the third s is followed by a newline and is what you typed.  And again, the blank line is from the newline and then space and s is the rest of the output, and there's probably a newline after that too.

JFTR, when I run your code (program getc73 compiled from getc73.c), I see:

$ getc73
s

 ss

 s$
$

The $ is my prompt; the first s is what I type; then the newline, blank and s are printed (with no newline at the end); then the second s on the third line is my next s and return, followed by the newline and blank s.  Since there's no newline at the end, my prompt appears immediately after the fourth s.  I hit return to print another prompt at the start of the line.

Why rewind(stdin) is a no-op

You can't successfully execute an fseek() call on a terminal device.  They don't have any storage so you can't move around like that.  The rewind() function is effectively:

void rewind(FILE *fp)
{
    fseek(fp, 0, SEEK_SET);
}

So, the rewind(stdin) call fails to rewind, but it has no way to report that to you because it returns no value.  It does no good; it doesn't do any harm either.  If it had worked, you would not have needed to enter the information twice.

If the standard input had been a file instead of a terminal, then the rewind would succeed — disks are seekable.

Improved formatting

If you were on a POSIX system, I'd suggest you used a feature of POSIX printf() that allows you to print the same argument more than once:

#include <stdio.h>

int main(void)
{
    printf("[%1$c] %1$d [%2$c] %2$d\n", getc(stdin), getc(stdin));
    printf("[%1$c] %1$d [%2$c] %2$d\n", getchar(), getchar());
    return 0;
}

When I run that on my terminal (it's a Mac running macOS Mojave 10.14.6 using GCC 9.2.0), I get:

s
[
] 10 [s] 115
s
[
] 10 [s] 115

The lines with just the s on them are what I typed; the other lines show that the newline is printed before the letter s.

This probably won't work for you in VS2017 — the manual for printf() formats on Windows strongly suggests it won't work.  Your best bet, probably, is to use:

#include <stdio.h>

int main(void)
{
    printf("%d %d\n", getc(stdin), getc(stdin));
    printf("%d %d\n", getchar(), getchar());
    return 0;
}

That generates:

s
10 115
s
10 115

Choosing a good format to show what you're seeing is an art form.  Don't forget to include newlines at the end of (most) printf() format strings.  Obviously, if you're building up a line of output piecemeal, you don't want newlines at the end of intermediate formats, but the majority of printf() statements should have a newline at the end of the format.


问:
boolean values, run time error if not 0 or 1

boolean values, run time error if not 0 or 1

I wanted to hear how you understand this question. Would I be - if using this C variant - allowed to write a codeblock like this:

```<code>int b = 2;
if (b == 2) {
    return 3;
}
</code>```

Is it the return value that cannot be 3? I don't understand the sentence correctly I believe. Could someone give me an example of how an invalid conditional statement would look like in this C variant? Learning about Boolean values.

答:
if(condition) { a(); } else { b(); } executes a(); if condition is non-zero and b(); if condition is zero.

That means that setting condition to other values like 2 or 3 would have the same effect as setting it to 1. The way I understand your idea, these other values would now lead to runtime errors.

That would be irrelevant for operators like == or != because they only ever evaluate to 0 or 1 anyway, but it would make a difference for something like char* pointer = malloc(10); if(pointer) or if(strcmp(a, b)) (because the latter could also evaluate to -1).

Body:
boolean values, run time error if not 0 or 1

I wanted to hear how you understand this question. Would I be - if using this C variant - allowed to write a codeblock like this:

int b = 2;
if (b == 2) {
    return 3;
}

Is it the return value that cannot be 3? I don't understand the sentence correctly I believe. Could someone give me an example of how an invalid conditional statement would look like in this C variant? Learning about Boolean values.


问:
Googlemaps Api weird behavior
I decided to have a play around with googlemaps and the ISS api to build a basic tracker. I plan on adding a bunch of stuff to this but for now this is kept simple.

The problem i am having is, i can set dummy values in the asp:Labels for Latitude & Longitude then populate a string with them that i can use with google maps.

```<code>var ISS = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };
</code>```

This works, when i then try use the values i get from the json callback even though i can see these when i use console.log(), they do not work.

```<code>ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };
</code>```

I have tried instead of reading directly adding back to the asp:Label's then reading however it does not work either.

What am i doing wrong? I have tried not to add any complexity to this while i toy with googlemaps api but this not working is confusing me as i dont see whats different with dummy values vs what i get from an api.

Below is all my code for this page.

```<code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ISS.aspx.cs" Inherits="WebApps.IIS" %>

<!DOCTYPE html>
<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <head runat="server">
        <title>ISS Tracker</title>
        <style>
          #map {
            height: 400px;  /* The height is 400 pixels */
            width: 100%;  /* The width is the width of the web page */
           }
          #pageTitle{
              margin: auto;
              padding: 10px;
          }
        </style>
    </head>
    <body>
        <div id="pageTitle">
            <h3>ISS Tracker</h3>
            <h4>International Space Station</h4>
        </div>
        <form runat="server">
            <label>Latitude: </label><asp:Label runat="server" ID="lblLat"/><br />
            <label>Longitude: </label><asp:Label runat="server" ID="lblLong"/><br />
            <label>Time: </label><asp:Label runat="server" ID="lblTime" Text="13/02/2020 15:45:00" /><br />
            <asp:Button runat="server" ID="btnRefresh" Text="Refresh" onClick="btnRefresh_Click" style="height: 26px" />
            <div id="map"></div>
        </form>
        <script>

            //globals
            var map;
            var ISS;// = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };
            var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png'

            // Initialize and add the map
            function initMap() {
                // The location of ISS
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };
                    console.log("latitude: " + data['iss_position']['latitude'] + " & longitude: " + data['iss_position']['longitude']);
                    document.getElementById('lblLat').innerText = data['iss_position']['latitude'];
                    document.getElementById('lblLong').innerText = data['iss_position']['longitude'];
                });
                // The map, centered at ISS
                map = new google.maps.Map(
                    document.getElementById('map'), { zoom: 10, center: ISS });
                // The marker, positioned at ISS
                var marker = new google.maps.Marker({
                    position: ISS,
                    map: map,
                    icon: {
                        url: image,
                        scaledSize: new google.maps.Size(128, 128),
                        size: new google.maps.Size(128, 128)
                    }
                });
                marker.position = ISS;

            }

            //Will use later when i want to update
            function moveISS() {
                $.getJSON('http://api.open-notify.org/iss-now.json?callback=?', function (data) {
                    var lat = data['iss_position']['latitude'];
                    var lon = data['iss_position']['longitude'];
                    ISS = { lat: lat, lng: lon };
                    document.getElementById('lblLat').innerText = lat;
                    document.getElementById('lblLong').innerText = lon;
                });
                setTimeout(moveISS, 5000);
            }
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=*****api key *****&callback=initMap">
        </script>
    </body>
</html>
</code>```

答:
Your problem is due to when things happen

Your getJSON call launches and then will return with a data response at some point in the future, however the rest of your code (with an invalid value for ISS) will execute immediately

var map;
var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png';

// ISS start position
var ISS  = { lat: 0.0, lng: 0.0 };

function initMap() {
  // create the map and marker before you know where ISS is
  // The map, centered at ISS
   map = new google.maps.Map(
     document.getElementById('map'), { zoom: 10, center: ISS });
   // The marker, positioned at ISS
   var marker = new google.maps.Marker({
     position: ISS,
     map: map,
     icon: {
       url: image,
       scaledSize: new google.maps.Size(128, 128),
       size: new google.maps.Size(128, 128)
     }
   });

}

function updateISS() {
  // The location of ISS
  $.getJSON('http://api.open-notify.org/iss-now.json?callback=?',
     function (data) {
       ISS = {
         lat: data['iss_position']['latitude'],
         lng: data['iss_position']['longitude']
       };

       // update the Marker position here
       marker.setPosition(ISS);

       console.log("latitude: " + ISS['lat'] + " & longitude: " + ISS['lng']);
       document.getElementById('lblLat').innerText = ISS['lat'];
       document.getElementById('lblLong').innerText = ISS['lng'];
     });

}

// update ISS position every 5 seconds.
var repeat = setInterval( updateISS, 5000)
```

The above is a first pass at a solution, creating the map and the marker before the getJSON call and updating the marker position when the JSON response is obtained.

Also I would note you're using a mixture of JavaScript and JQuery which ain't pretty

Title: Googlemaps Api weird behavior

Body:
I decided to have a play around with googlemaps and the ISS api to build a basic tracker. I plan on adding a bunch of stuff to this but for now this is kept simple.

The problem i am having is, i can set dummy values in the asp:Labels for Latitude & Longitude then populate a string with them that i can use with google maps.

var ISS = { lat: parseFloat(document.getElementById('lblLat').innerText), lng: parseFloat(document.getElementById('lblLong').innerText) };

This works, when i then try use the values i get from the json callback even though i can see these when i use console.log(), they do not work.

ISS = { lat: data['iss_position']['latitude'], lng: data['iss_position']['longitude'] };

I have tried instead of reading directly adding back to the asp:Label's then reading however it does not work either.

What am i doing wrong? I have tried not to add any complexity to this while i toy with googlemaps api but this not working is confusing me as i dont see whats different with dummy values vs what i get from an api.

Below is all my code for this page.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ISS.aspx.cs" Inherits="WebApps.IIS" %>

<!DOCTYPE html>

        <title>ISS Tracker</title>

ISS Tracker

International Space Station

        <form runat="server">
            Latitude: <asp:Label runat="server" ID="lblLat"/>

            Longitude: <asp:Label runat="server" ID="lblLong"/>

            Time: <asp:Label runat="server" ID="lblTime" Text="13/02/2020 15:45:00" />

            <asp:Button runat="server" ID="btnRefresh" Text="Refresh" onClick="btnRefresh_Click" style="height: 26px" />

        </form>

Body:
Your problem is due to when things happen

Your getJSON call launches and then will return with a data response at some point in the future, however the rest of your code (with an invalid value for ISS) will execute immediately

var map;
var image = 'http://icons.iconarchive.com/icons/goodstuff-no-nonsense/free-space/256/international-space-station-icon.png';

// ISS start position
var ISS  = { lat: 0.0, lng: 0.0 };

function initMap() {
  // create the map and marker before you know where ISS is
  // The map, centered at ISS
   map = new google.maps.Map(
     document.getElementById('map'), { zoom: 10, center: ISS });
   // The marker, positioned at ISS
   var marker = new google.maps.Marker({
     position: ISS,
     map: map,
     icon: {
       url: image,
       scaledSize: new google.maps.Size(128, 128),
       size: new google.maps.Size(128, 128)
     }
   });

}

function updateISS() {
  // The location of ISS
  $.getJSON('http://api.open-notify.org/iss-now.json?callback=?',
     function (data) {
       ISS = {
         lat: data['iss_position']['latitude'],
         lng: data['iss_position']['longitude']
       };

       // update the Marker position here
       marker.setPosition(ISS);

       console.log("latitude: " + ISS['lat'] + " & longitude: " + ISS['lng']);
       document.getElementById('lblLat').innerText = ISS['lat'];
       document.getElementById('lblLong').innerText = ISS['lng'];
     });

}

// update ISS position every 5 seconds.
var repeat = setInterval( updateISS, 5000)

The above is a first pass at a solution, creating the map and the marker before the getJSON call and updating the marker position when the JSON response is obtained.

Also I would note you're using a mixture of JavaScript and JQuery which ain't pretty


问:
How to place an Imageview on top of anothe Layout as shown in the figure?
I would like to create a layout which could make the UI look like as shown in figure.

All comments and pointers welcome.

Adding my current Layout :

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical"
    android:id="@+id/video_panel">

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/top_panel" android:gravity="top"
        android:orientation="horizontal" android:alwaysDrawnWithCache="true"
        android:layout_height="fill_parent" android:layout_gravity="top"
        android:layout_weight="14" android:background="@drawable/top_bg1">

        <TextView android:layout_width="wrap_content"
            android:layout_height="fill_parent" android:id="@+id/date"
            android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
            android:text="@string/space" />

        <RelativeLayout android:layout_centerHorizontal="true"
            android:id="@+id/button_panel" android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:gravity="center_horizontal"
            android:layout_centerInParent="true">
        </RelativeLayout>

        <TextView android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:layout_alignParentRight="true"
            android:layout_alignParentTop="true" android:id="@+id/time"
            android:text="@string/space" />
    </RelativeLayout>

    <LinearLayout android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent" android:layout_gravity="center_horizontal"
        android:layout_weight="4" android:id="@+id/screen">
    </LinearLayout>

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/bottom_panel" android:layout_height="fill_parent"
        android:layout_gravity="bottom" android:layout_weight="13"
        android:orientation="vertical" android:background="@drawable/bottom_bg1"
        android:duplicateParentState="true" android:alwaysDrawnWithCache="true">

        <LinearLayout android:foregroundGravity="center"
            android:id="@+id/album_art" android:layout_alignParentLeft="true"
            android:layout_width="256dip" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:layout_gravity="center"
                android:id="@+id/thumbnail"></ImageView>
        </LinearLayout>

        <LinearLayout android:layout_toRightOf="@+id/album_art"
            android:layout_height="fill_parent" android:orientation="vertical"
            android:paddingTop="10dip" android:layout_width="wrap_content"
            android:layout_centerHorizontal="true" android:layout_toLeftOf="@+id/status_frame"
            android:id="@+id/info_panel">
        </LinearLayout>

        <FrameLayout android:layout_width="wrap_content"
            android:id="@+id/status_frame" android:layout_height="fill_parent"
            android:visibility="visible" android:foregroundGravity="center"
            android:layout_alignParentRight="true" android:paddingTop="50dip">
            <ImageView android:id="@+id/status" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:scaleType="fitCenter"
                android:layout_gravity="center" />
        </FrameLayout>
    </RelativeLayout>
</LinearLayout>
</code>```

How Should i change this layout to make it look like in my picture?

答:
There is several possibilities but I guess I would go for a simple negative top margin on the imageview. Put the image view in your blue linearview and android:layout_marginTop="-20dip".

This should work

Body:
I would like to create a layout which could make the UI look like as shown in figure.

All comments and pointers welcome.

Adding my current Layout :

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:orientation="vertical"
    android:id="@+id/video_panel">

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/top_panel" android:gravity="top"
        android:orientation="horizontal" android:alwaysDrawnWithCache="true"
        android:layout_height="fill_parent" android:layout_gravity="top"
        android:layout_weight="14" android:background="@drawable/top_bg1">

        <TextView android:layout_width="wrap_content"
            android:layout_height="fill_parent" android:id="@+id/date"
            android:layout_alignParentLeft="true" android:layout_alignParentTop="true"
            android:text="@string/space" />

        <RelativeLayout android:layout_centerHorizontal="true"
            android:id="@+id/button_panel" android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:gravity="center_horizontal"
            android:layout_centerInParent="true">
        </RelativeLayout>

        <TextView android:layout_height="fill_parent"
            android:layout_width="wrap_content" android:layout_alignParentRight="true"
            android:layout_alignParentTop="true" android:id="@+id/time"
            android:text="@string/space" />
    </RelativeLayout>

    <LinearLayout android:layout_width="fill_parent"
        xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_height="fill_parent" android:layout_gravity="center_horizontal"
        android:layout_weight="4" android:id="@+id/screen">
    </LinearLayout>

    <RelativeLayout android:layout_width="fill_parent"
        android:id="@+id/bottom_panel" android:layout_height="fill_parent"
        android:layout_gravity="bottom" android:layout_weight="13"
        android:orientation="vertical" android:background="@drawable/bottom_bg1"
        android:duplicateParentState="true" android:alwaysDrawnWithCache="true">

        <LinearLayout android:foregroundGravity="center"
            android:id="@+id/album_art" android:layout_alignParentLeft="true"
            android:layout_width="256dip" android:layout_height="fill_parent">
            <ImageView android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:layout_gravity="center"
                android:id="@+id/thumbnail"></ImageView>
        </LinearLayout>

        <LinearLayout android:layout_toRightOf="@+id/album_art"
            android:layout_height="fill_parent" android:orientation="vertical"
            android:paddingTop="10dip" android:layout_width="wrap_content"
            android:layout_centerHorizontal="true" android:layout_toLeftOf="@+id/status_frame"
            android:id="@+id/info_panel">
        </LinearLayout>

        <FrameLayout android:layout_width="wrap_content"
            android:id="@+id/status_frame" android:layout_height="fill_parent"
            android:visibility="visible" android:foregroundGravity="center"
            android:layout_alignParentRight="true" android:paddingTop="50dip">
            <ImageView android:id="@+id/status" android:layout_width="fill_parent"
                android:layout_height="fill_parent" android:scaleType="fitCenter"
                android:layout_gravity="center" />
        </FrameLayout>
    </RelativeLayout>
</LinearLayout>

How Should i change this layout to make it look like in my picture?


答:
Standard C allows any scalar expression (any arithmetic or pointer expression) for the controlling expression of if and while statements, and the expression is taken as “true” if it is not zero (or, for a pointer, null). This means we can write statements such as if (p) { … }, where p is a pointer, and it will execute the { … } if and only if p is not a null pointer. That is convenient in various ways.

However, it also means errors can occur. A programmer might accidentally write x & 3 | y where they intend x & 3 || y. The latter always has a value of 0 or 1, because the || operator returns 1 if either operand is not zero and 0 if both are zero. But x & 3 | y may have a value other than 0 or 1. So a variant of C which gave a run-time error for this could help catch this error during testing.

Effectively, the proposed change requires controlling expressions to evaluate to only the Boolean values 0 or 1, thus inducing programmers to write more strictly Boolean expressions rather than the free-form expressions standard C allows. It is not a perfect change, as some arithmetic expressions may evaluate only to 0 or 1 even though they are not proper Boolean expressions (for example, we generally consider x & 1 to be doing some bit manipulation rather than being a Boolean test like x == 13, but it evaluates to only 0 or 1), so the change will not completely restrict controlling expressions to being Boolean expressions. A better change to accomplish this goal would further modify the grammar or constraints so that controlling expressions had to be Boolean expressions.

Title: boolean values, run time error if not 0 or 1