问:
ValueError: Invalid tensors 'input' were found
I'm not able to convert .pb to tflite

Here is the command that I'm executing to generate .pb I am successful in generating it.

```<code>IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1_1.0_${IMAGE_SIZE}"

python retrain.py
 --bottleneck_dir=tf_files/bottlenecks
 --how_many_training_steps=500
 --model_dir=tf_files/models/
 --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}"
  --output_graph=tf_files/retrained_graph.pb
  --output_labels=tf_files/retrained_labels.txt
  --architecture="${ARCHITECTURE}"
  --image_dir=tf_files/flower_photos
</code>```

Once I am trying to create that .pb to .tflite get fail with same error "ValueError: Invalid tensors 'input' were found."

```<code>tflite_convert \
  --output_file=foo.tflite \
  --graph_def_file=retrained_graph.pb \
  --input_arrays=input \
  --output_arrays=MobilenetV1/Predictions/Reshape_1
</code>```

答:
I got the same error as you with tflite converter python api.

This caused by the params we passed in input_arrays.

input_arrays need tensor_name defined in tf.placeholder(name="input") not proto map key string defined in build_signature_def(inputs={"input": tensor_info_proto},outputs...).

Here is a simple example.

```<code>x = tf.placeholder(tf.float32, [None], name="input_x")
...

builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
input_tensor_info = {"input": tf.saved_model.build_tensor_info(x)}
output_tensor_info = ...
signature_def = tf.saved_model.build_signature_def(inputs=input_tensor_info,
                                                   outputs=...,
                                                   method_name=...)
builder.add_meta_graph_and_variables(...)
builder.save()

# convert saved_model to tflite format.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path,
                                                     input_arrays=["input"],
                                                     ...)
...
...
</code>```

Once you run a code like this will raise an error "ValueError: Invalid tensors 'input' were found."

If we make a small change as bellow, it will succeed.

```<code># a small change when convert
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path,
                                                     input_arrays=["input_x"],
                                                     ...)
</code>```

Body:
I'm not able to convert .pb to tflite

Here is the command that I'm executing to generate .pb I am successful in generating it.

IMAGE_SIZE=224
ARCHITECTURE="mobilenet_1_1.0_${IMAGE_SIZE}"

python retrain.py
 --bottleneck_dir=tf_files/bottlenecks
 --how_many_training_steps=500
 --model_dir=tf_files/models/
 --summaries_dir=tf_files/training_summaries/"${ARCHITECTURE}"
  --output_graph=tf_files/retrained_graph.pb
  --output_labels=tf_files/retrained_labels.txt
  --architecture="${ARCHITECTURE}"
  --image_dir=tf_files/flower_photos

Once I am trying to create that .pb to .tflite get fail with same error "ValueError: Invalid tensors 'input' were found."

tflite_convert \
  --output_file=foo.tflite \
  --graph_def_file=retrained_graph.pb \
  --input_arrays=input \
  --output_arrays=MobilenetV1/Predictions/Reshape_1

Body:
I got the same error as you with tflite converter python api.

This caused by the params we passed in input_arrays.

input_arrays need tensor_name defined in tf.placeholder(name="input") not proto map key string defined in build_signature_def(inputs={"input": tensor_info_proto},outputs...).

Here is a simple example.

x = tf.placeholder(tf.float32, [None], name="input_x")
...

builder = tf.saved_model.builder.SavedModelBuilder(saved_model_path)
input_tensor_info = {"input": tf.saved_model.build_tensor_info(x)}
output_tensor_info = ...
signature_def = tf.saved_model.build_signature_def(inputs=input_tensor_info,
                                                   outputs=...,
                                                   method_name=...)
builder.add_meta_graph_and_variables(...)
builder.save()

# convert saved_model to tflite format.
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path,
                                                     input_arrays=["input"],
                                                     ...)
...
...

Once you run a code like this will raise an error "ValueError: Invalid tensors 'input' were found."

If we make a small change as bellow, it will succeed.

# a small change when convert
converter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path,
                                                     input_arrays=["input_x"],
                                                     ...)


来源: stackexchange

问:
Paypal Sandbox Access Token not Found in Cache
I am having a persisting issue with the Paypal access token for the sandbox environment where I continually get the error,

```<code>Client error: `POST https://api.sandbox.paypal.com/v1/payments/billing-
agreements` resulted in a `401 Unauthorized` response:
{"error":"invalid_token","error_description":"Access Token not found in cache"}
</code>```

I am not sure where to go as this is a new token that is being generated and used just prior to running the API call. Everything was working normal until this began giving me issues a couple of nights ago. It seems to return this error for about 30 minutes or so until the token begins working. My issue is that once I switch to the live version, I do not want there to be this error while the new token is "processing" as the tokens are going to automatically update (or doing whatever the issue is).

Any suggestions?

答:
The issue ended up being with Laravel's configuration caching from the env file. I just ran php artisan config:cache and it fixed itself. I added to the command

Artisan::call('config:cache');
```

and this fixed all of my issues.

ContentLicense: CC BY-SA 4.0

Body:
I am having a persisting issue with the Paypal access token for the sandbox environment where I continually get the error,

Client error: `POST https://api.sandbox.paypal.com/v1/payments/billing-
agreements` resulted in a `401 Unauthorized` response:
{"error":"invalid_token","error_description":"Access Token not found in cache"}

I am not sure where to go as this is a new token that is being generated and used just prior to running the API call. Everything was working normal until this began giving me issues a couple of nights ago. It seems to return this error for about 30 minutes or so until the token begins working. My issue is that once I switch to the live version, I do not want there to be this error while the new token is "processing" as the tokens are going to automatically update (or doing whatever the issue is).

Any suggestions?

Body:
The issue ended up being with Laravel's configuration caching from the env file. I just ran php artisan config:cache and it fixed itself. I added to the command

Artisan::call('config:cache');

and this fixed all of my issues.


问:
Python indentation not clear
Trying to understand how indentation works in Python.

```<code>var = 100
if ( var == 100 ) :
    print ("Value of expression is 100")
    print ("Good bye!")
print("AM I out?")
</code>```

Output:

```<code>Value of expression is 100
Good bye!
AM I out?
</code>```

Isn't it only supposed to print the below output considering the indentation given for the if condition?

```<code>Value of expression is 100
Good bye!
</code>```

Why is the last statement also printed even though it has no indentation like the previous statements?

答:
Python executes your program line by line,

```<code>var = 100                                 # First assign var = 100
if ( var == 100 ) :                       # Executed your if condition
    print ("Value of expression is 100")
    print ("Good bye!")
print("AM I out?")                        # Executed your last line
</code>```

If you don't want to execute your last line when if is used,
keep print("AM I out?")  in else block.

```<code>if ( var == 100 ) :
        print ("Value of expression is 100")
        print ("Good bye!")
else:
        print("AM I out?")
</code>```

About Identation:

It is used to know your program, that specific block statements belong to specific object(class, function, if-conditions, loops)

Title: Python indentation not clear

Body:
Trying to understand how indentation works in Python.

var = 100
if ( var == 100 ) :
    print ("Value of expression is 100")
    print ("Good bye!")
print("AM I out?")

Output:

Value of expression is 100
Good bye!
AM I out?

Isn't it only supposed to print the below output considering the indentation given for the if condition?

Value of expression is 100
Good bye!

Why is the last statement also printed even though it has no indentation like the previous statements?

Body:
Python executes your program line by line,

var = 100                                 # First assign var = 100
if ( var == 100 ) :                       # Executed your if condition
    print ("Value of expression is 100")
    print ("Good bye!")
print("AM I out?")                        # Executed your last line

If you don't want to execute your last line when if is used,
keep print("AM I out?")  in else block.

if ( var == 100 ) :
        print ("Value of expression is 100")
        print ("Good bye!")
else:
        print("AM I out?")

About Identation:

It is used to know your program, that specific block statements belong to specific object(class, function, if-conditions, loops)


问:
Change color of single li on hover
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="tags-list">
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
</ul></code>```

答:
Remove the ul., .tags-list already refered to the ul. It does not contain another ul.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list li a:hover{color:black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="tags-list">
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
</ul></code>```

Title: Change color of single li on hover

Body:
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}

Testing

Testing

Testing

Testing

Testing

Testing

Body:
Remove the ul., .tags-list already refered to the ul. It does not contain another ul.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list li a:hover{color:black;}

<ul class="tags-list">
<li><a href="#">Testing</a></li>
<li><a href="#">Testing</a></li>
<li><a href="#">Testing</a></li>
<li><a href="#">Testing</a></li>
<li><a href="#">Testing</a></li>
<li><a href="#">Testing</a></li>
</ul>


问:
Converting a string pattern of format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date
I am trying to convert a String with format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date

Unable to convert the String format to a Java Date.
It is not identifying the time asAM/PM

```<code>String s = "1/1/2010 3:23:12 PM +00:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a",Locale.ENGLISH);

Date date = sdf.parse(s));
</code>```

Need the date converted with time identified as AM/PM

答:
Unable to convert the String format to a Java Date. It is not
  identifying the time as AM/PM

You are asking the impossible. A Date is a point in time (internally implemented as a count of milliseconds since the so-called epoch), so it “knows” nothing about AM and PM in your time zone.

That’s just the same, though, because the Date class was always poorly designed and is fortunately long outdated. You should not use it at all.

java.time

java.time, the modern Java date and time API that we should use instead of Date, comes closer to fulfilling your requirement. MC Emperor has already shown the basic code you need for parsing your datetime string. The output from his code is:

2010-01-01T15:23:12Z

There’s no AM or PM here. When we print an OffsetDateTime in this way, its toString method is implicitly called. It produces an ISO 8601 formatted string. ISO 8601 prescribes a 24 hour clock (no AM or PM). But! With assistance from the correct TemporalField object the OffsetDateTime is able to calculate and return whether it is in AM or PM. time.get(ChronoField.AMPM_OF_DAY) returns 0 for AM or 1 for PM:

```<code>    System.out.println("AM or PM? 0 for AM. 1 for PM. time: "
            + time.get(ChronoField.AMPM_OF_DAY));
</code>```

AM or PM? 0 for AM. 1 for PM. time: 1

So in this case we got 1 for PM as expected since your original string had PM in it.

I have deliberately not answered all of your question because much of it has been covered in other Stack Overflow questions and their answers already. So it’s better to keep the information there. I include links to a couple of relevant questions below.

What went wrong in your code?

There are at least two bugs in your code that each cause you to get an incorrect result. I tried running your code in America/Los_Angeles time zone and got

Fri Jan 01 03:23:12 PST 2010

The time printed is on a 24 hour clock (Date always does that), so we got 03:23:12 AM instead of PM. And we got the time in the default time zone (PST is for Pacific Standard Time), so the point in time corresponds to 11:23:12 AM at offset +00:00, the offset in the string.

The wrong clock hour comes from conflicting indications in your code: HH in the format pattern string is for hour of day from 00 through 23, so 3 is taken to mean 03 AM and apparently “wins” over the PM marker (for hour within AM or PM, from 1 through 12, you would have needed lowercase h).

The default time zone comes from the fact that you are making no attempt to parse the offset from the string (in conjunction with SimpleDateFormat being satisfied with not parsing all of the string).

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601

Question: want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format

Question: Unable to parse DateTime-string with AM/PM marker

Question: Display current time in 12 hour format with AM/PM

Question: Convert String to java.util.Date

Body:
I am trying to convert a String with format 1/1/2010 3:23:12 PM +00:00 to a Java.util.Date

Unable to convert the String format to a Java Date.
It is not identifying the time asAM/PM

String s = "1/1/2010 3:23:12 PM +00:00";
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss a",Locale.ENGLISH);

Date date = sdf.parse(s));

Need the date converted with time identified as AM/PM

Body:
Unable to convert the String format to a Java Date. It is not
  identifying the time as AM/PM

You are asking the impossible. A Date is a point in time (internally implemented as a count of milliseconds since the so-called epoch), so it “knows” nothing about AM and PM in your time zone.

That’s just the same, though, because the Date class was always poorly designed and is fortunately long outdated. You should not use it at all.

java.time

java.time, the modern Java date and time API that we should use instead of Date, comes closer to fulfilling your requirement. MC Emperor has already shown the basic code you need for parsing your datetime string. The output from his code is:

2010-01-01T15:23:12Z

There’s no AM or PM here. When we print an OffsetDateTime in this way, its toString method is implicitly called. It produces an ISO 8601 formatted string. ISO 8601 prescribes a 24 hour clock (no AM or PM). But! With assistance from the correct TemporalField object the OffsetDateTime is able to calculate and return whether it is in AM or PM. time.get(ChronoField.AMPM_OF_DAY) returns 0 for AM or 1 for PM:

    System.out.println("AM or PM? 0 for AM. 1 for PM. time: "
            + time.get(ChronoField.AMPM_OF_DAY));

AM or PM? 0 for AM. 1 for PM. time: 1

So in this case we got 1 for PM as expected since your original string had PM in it.

I have deliberately not answered all of your question because much of it has been covered in other Stack Overflow questions and their answers already. So it’s better to keep the information there. I include links to a couple of relevant questions below.

What went wrong in your code?

There are at least two bugs in your code that each cause you to get an incorrect result. I tried running your code in America/Los_Angeles time zone and got

Fri Jan 01 03:23:12 PST 2010

The time printed is on a 24 hour clock (Date always does that), so we got 03:23:12 AM instead of PM. And we got the time in the default time zone (PST is for Pacific Standard Time), so the point in time corresponds to 11:23:12 AM at offset +00:00, the offset in the string.

The wrong clock hour comes from conflicting indications in your code: HH in the format pattern string is for hour of day from 00 through 23, so 3 is taken to mean 03 AM and apparently “wins” over the PM marker (for hour within AM or PM, from 1 through 12, you would have needed lowercase h).

The default time zone comes from the fact that you are making no attempt to parse the offset from the string (in conjunction with SimpleDateFormat being satisfied with not parsing all of the string).

Links

Oracle tutorial: Date Time explaining how to use java.time.

Wikipedia article: ISO 8601

Question: want current date and time in “dd/MM/yyyy HH:mm:ss.SS” format

Question: Unable to parse DateTime-string with AM/PM marker

Question: Display current time in 12 hour format with AM/PM

Question: Convert String to java.util.Date


问:
How to install pip with Python 3?
I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2.

How can I install pip with Python 3?

答:
Please follow below steps to install python 3 with pip:

Step 1 : Install Python from download here

Step 2 : you’ll need to download get-pip.py

Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .

Step 4 : Enter command python get-pip.py in cmd.

Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version

ContentLicense: CC BY-SA 3.0

Title: How to install pip with Python 3?


问:
Form submitting with "email already exist" conditon in Php using ajax
I am working with ajax Php, I want to check email availability using ajax(on blur function)
my code is working fine, showing whether email exists or not but my form submitting even " email already exists " message showing
, I just want that form should not submit if I enter existing email, Here is my code, Where I am wrong?</p>

```<code><script type = "text/javascript" >
    $(document).ready(function() {
        /// make loader hidden in start
        $('#loading').hide();
        $('#email').blur(function() {
            var email_val = $("#email").val();

            var filter = /^[a-zA-Z0-9]+[a-zA-Z0-9_.-]+[a-zA-Z0-9_-]+@[a-zA-Z0-9]+[a-zA-Z0-9.-]+[a-zA-Z0-9]+.[a-z]{2,4}$/;
            if (filter.test(email_val)) {
                // show loader
                $('#loading').show();
                $.post("<?php echo site_url()?>/Register/email_check", {
                    email: email_val
                }, function(response) {
                    alert(response);
                    $('#loading').hide();
                    //$('#message').html('').html(response).show().delay(4000).fadeOut();
                    if (response.trim() == '1') {
                        $('#failuremsg').show().delay(4000).fadeOut();

                    } else {

                        $('#successmsg').show().delay(4000).fadeOut();
                    }
                });
                return false;
            }
        });

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

答:
replace the submit button on the form with

```<code><button id="submit-form">Submit</button>
</code>```

set a validated=true variable in your main code when all checks have passed

add some jquery

```<code>$( "#submit-form" ).click(function() {
  if(validated){
     $( "#yourForm" ).submit();
  }else{
   return false;
  }
};
</code>```

Body:
replace the submit button on the form with

<button id="submit-form">Submit</button>

set a validated=true variable in your main code when all checks have passed

add some jquery

$( "#submit-form" ).click(function() {
  if(validated){
     $( "#yourForm" ).submit();
  }else{
   return false;
  }
};


答:
Seems like you added the ul element after your class selector that already is the ul element.

Compare these two lines you wrote:

.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;} <-- .tags-list and ul is the same element and not nested
```

The first one accesses the element correctly, and the second one (which is causing the problem) does not match any elements, because it would need a nested ul element.

Title: Change color of single li on hover

Body:
Seems like you added the ul element after your class selector that already is the ul element.

Compare these two lines you wrote:

.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;} <-- .tags-list and ul is the same element and not nested

The first one accesses the element correctly, and the second one (which is causing the problem) does not match any elements, because it would need a nested ul element.


问:
Problem with the fgetcsv() in php
I have the following piece of code to parse a csv file. After that I am displaying it. The .csv  file is displaying perfectly on my local  machine but on the server after clicking on upload a blank page is displaying.

```<code>function uploadTrainees()
{
    $csv = array();
    $tmpName = $_FILES['csv']['tmp_name'];
    //echo $tmpName;
    //ini_set('auto_detect_line_endings',true);
    $fp = fopen($tmpName,'r');
    $fields = array('delegate_title', 'delegate_firstname', 'delegate_lastname', 'delegate_jobtitle', 'delegate_email', 'delegate_phone', 'is_bringing_own_laptop');
    $records = array();

    while ($record = fgetcsv($fp,1000,','))
    {
        $records[] = array_combine($fields, $record);
    }
    fclose($fp);
}
</code>```

Help me to solve this issue.

答:
What version of PHP is the live server running?

The function array_combine() is only in PHP5

Edit

There is a function here to do this - http://snipplr.com/view/4918/arraycombine-for-php4/

```<code>if (!function_exists('array_combine'))
{
    function array_combine($arr1,$arr2) {
       $out = array();
       foreach ($arr1 as $key1 => $value1) {
        $out[$value1] = $arr2[$key1];
       }
       return $out;
    }
}
</code>```

Title: Problem with the fgetcsv() in php

Body:
I have the following piece of code to parse a csv file. After that I am displaying it. The .csv  file is displaying perfectly on my local  machine but on the server after clicking on upload a blank page is displaying.

function uploadTrainees()
{
    $csv = array();
    $tmpName = $_FILES['csv']['tmp_name'];
    //echo $tmpName;
    //ini_set('auto_detect_line_endings',true);
    $fp = fopen($tmpName,'r');
    $fields = array('delegate_title', 'delegate_firstname', 'delegate_lastname', 'delegate_jobtitle', 'delegate_email', 'delegate_phone', 'is_bringing_own_laptop');
    $records = array();

    while ($record = fgetcsv($fp,1000,','))
    {
        $records[] = array_combine($fields, $record);
    }
    fclose($fp);
}

Help me to solve this issue.

Body:
What version of PHP is the live server running?

The function array_combine() is only in PHP5

Edit

There is a function here to do this - http://snipplr.com/view/4918/arraycombine-for-php4/

if (!function_exists('array_combine'))
{
    function array_combine($arr1,$arr2) {
       $out = array();
       foreach ($arr1 as $key1 => $value1) {
        $out[$value1] = $arr2[$key1];
       }
       return $out;
    }
}


问:
Deleting N matching patterns using sed, awk, perl etc
I have this situation, the file contains

```<code>abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5
</code>```

I would like to delete whenever I find matching 2 lines of

```<code>abcd
vwxyz
</code>```

to be deleted so that it becomes

```<code>abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

答:
With awk, where you define your record separator as the 2 lines and you simply print each line.

```<code>awk -v RS='abcd\nvwxyz\n' '{printf $0}' file.in
abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

A python solution:

```<code>import re

with open('file.in', 'r') as file:
    data = file.read()
    print(re.sub(r'(^|\n)abcd\nvwxyz(?=\n)','',data), end='')
</code>```

output:

```<code>python3 filter_lines.py
abcd
line1
line2
line3
vwxyz
line4
line5
</code>```

Body:
I have this situation, the file contains

abcd
line1
line2
line3
vwxyz
abcd
vwxyz
abcd
vwxyz
abcd
vwxyz
line4
line5

I would like to delete whenever I find matching 2 lines of

abcd
vwxyz

to be deleted so that it becomes

abcd
line1
line2
line3
vwxyz
line4
line5

I have search numerous stackoverflow suggestions of pattern matching but never encountered pattern matching of 2 lines

I have triend sed -i '/abcd|vwxyz/d' file1 but that didn't work as expected...

Any help is appreciated using awk, sed, perl, pyhon etc

Body:
With awk, where you define your record separator as the 2 lines and you simply print each line.

awk -v RS='abcd\nvwxyz\n' '{printf $0}' file.in
abcd
line1
line2
line3
vwxyz
line4
line5

A python solution:

import re

with open('file.in', 'r') as file:
    data = file.read()
    print(re.sub(r'(^|\n)abcd\nvwxyz(?=\n)','',data), end='')

output:

python3 filter_lines.py
abcd
line1
line2
line3
vwxyz
line4
line5


答: The if block contains two indented print statements, which will be executed only if the condition is met. The print('AM I out?') statement which is on the same level as the if, is simply the statement after the block. It is unaffected by the condition. Had that statement been in an else block, it would not have been triggered.

Title: Python indentation not clear


问:
Why am I getting SQLSTATE[42501] error when running php artisan migrate?
I just don't understand for the life of me how this error's happening upon running php artisan migrate after creating a new table.

I've searched the web and SO and tried every single suggestion out there (like php artisan migrate:fresh) but nothing seems to be working.

What can I do to rectify this problem as this is holding me up big time?

```<code>SQLSTATE[42S01]: Base table or view already exists: 1050 Table
'posts' already exists (SQL: create table `posts` (`id` bigint
 unsigned not null auto_increment primary key, `user_id` int
 unsigned not null, `body` varchar(140) not null, `created_at`
 timestamp null, `updated_at` timestamp null) default character set
 utf8mb4 collate 'utf8mb4_unicode_ci')
</code>```

Migration:

```<code><?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->string('body', 140);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}
</code>```

答: Please drop the tables before running the migrate command or try php artisan migrate:fresh command.</p>

Body:
I just don't understand for the life of me how this error's happening upon running php artisan migrate after creating a new table.

I've searched the web and SO and tried every single suggestion out there (like php artisan migrate:fresh) but nothing seems to be working.

What can I do to rectify this problem as this is holding me up big time?

SQLSTATE[42S01]: Base table or view already exists: 1050 Table
'posts' already exists (SQL: create table `posts` (`id` bigint
 unsigned not null auto_increment primary key, `user_id` int
 unsigned not null, `body` varchar(140) not null, `created_at`
 timestamp null, `updated_at` timestamp null) default character set
 utf8mb4 collate 'utf8mb4_unicode_ci')

Migration:

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->integer('user_id')->unsigned();
            $table->string('body', 140);
            $table->timestamps();

            $table->foreign('user_id')->references('id')->on('user')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}


问:
Angular use global interceptor
I want to use 2 interceptor globally (httpInterceptorProviders,
    jwtInterceptorProviders) but it not working in my lazy modules.
I have CoreModule and X lazy load modules. The weird part is that I have an autogenerated code by swagger generator(http services) this calls being intercepted but when I use custom http services interceptor not intercept this requests.

Index.ts where I get the providers

```<code>/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
];

export const jwtInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
];
</code>```

CoreModule, I import my interceptors in providers

@NgModule({
  imports: [
    // angular
    CommonModule,
    HttpClientModule,
    // ngrx
    StoreModule.forRoot(reducers, { metaReducers }),
    StoreRouterConnectingModule.forRoot(),
    EffectsModule.forRoot([AuthEffects, GoogleAnalyticsEffects]),
    environment.production
      ? []
      : StoreDevtoolsModule.instrument({
          name: "Angular NgRx Material Starter"
        }),

    // 3rd party
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    ApiModule.forRoot(() => {
      return new Configuration({
        basePath: `${environment.HOST}:${environment.PORT}`,
        apiKeys: { Authorization: "" }
      });
    })
  ],
  declarations: [],
  providers: [
    LocalStorageService,
    AuthGuardService,
    AnimationsService,
    TitleService,

    // retryHttpInterceptorProviders,
    { provide: ErrorHandler, useClass: AppErrorHandler },
    httpInterceptorProviders,
    jwtInterceptorProviders,
    { provide: RouterStateSerializer, useClass: CustomSerializer },
    {
      provide: HAMMER_LOADER,
      useValue: () => new Promise(() => {})
    },
    AnalyticsService,
    LayoutService,
    StateService,
    PetsServiceWithUpload
  ],
  exports: [TranslateModule]
})
export class CoreModule {
  constructor(
    @Optional()
    @SkipSelf()
    parentModule: CoreModule
  ) {
    if (parentModule) {
      throw new Error("CoreModule is already loaded. Import only in AppModule");
    }
  }
}

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(
    http,
    `${environment.i18nPrefix}/assets/i18n/`,
    ".json"
  );
}
```

<p>AppModule</p>

```@NgModule({
  declarations: [AppComponent, NavigationComponent, ErrorsComponent],
  imports: [
    BrowserAnimationsModule,
    BrowserModule,
    SharedModule,
    AppRoutingModule,
    AuthModule,
    ThemeModule.forRoot(),
    CoreModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}
```

<p>Interceptor</p>

<pre class="lang-js prettyprint-override"><code>@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    private isRefreshing = false;
    private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    constructor(private injector: Injector,
        private localstorage: LocalStorageService,
        private authService: AuthService,
        private store: Store<AppState>, ) { }

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const tokenInfo = this.localstorage.getItem(AUTH_KEY);
        if (tokenInfo) {
            request = this.addToken(request, tokenInfo.token);
        }
        console.log('TCL: JwtInterceptor -> request', request);
        return next.handle(request).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse && error.status === 401) {
                return this.handle401Error(request, next);
            } else {
                return throwError(error);
            }
        }));
    }

    private addToken(request: HttpRequest<any>, token: string): HttpRequest<any> {
        return request.clone({
            setHeaders: {
                'Authorization': `Bearer ${token}`
            }
        });
    }

    private handle401Error(request: HttpRequest<any>, next: HttpHandler) {

        if (!this.isRefreshing) {
            this.isRefreshing = true;
            this.refreshTokenSubject.next(null);
            const tokenInfo = this.localstorage.getItem(AUTH_KEY);
            return this.authService.authRefreshtokenPost({ refreshToken: tokenInfo.refreshToken }).pipe(
                switchMap((tokenRes: any) => {
                    this.isRefreshing = false;
                    this.refreshTokenSubject.next(tokenRes.token);
                    this.localstorage.setItem(AUTH_KEY,
                        { token: tokenRes.token, refreshToken: tokenRes.refreshToken, isAuthenticated: true });
                    return next.handle(this.addToken(request, tokenRes.token));
                }), catchError((error) => {
                    console.log('TCL: JwtInterceptor -> privatehandle401Error -> error', error);
                    this.store.dispatch(new AuthActions.Logout({ refreshToken: tokenInfo.refreshToken }));
                    return next.handle(request);
                }));

        } else {
            return this.refreshTokenSubject.pipe(
                filter(token => token != null),
                take(1),
                switchMap(jwt => {
                    return next.handle(this.addToken(request, jwt));
                }));
        }
    }
}
</code>```

Lazy load module

@NgModule({
  imports: [
    ThemeModule,
    PetsRoutingModule,
    StoreModule.forFeature("pets", petsReducer),
    TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      isolate: true
    }),
    EffectsModule.forFeature([PetsEffects]),
    InfiniteScrollModule,
    SharedModule
  ],
  declarations: [
    PetsComponent,
    CreatePetComponent,
    ViewPetComponent,
    FormPetComponent,
    EditPetComponent,
    PetListVirtualComponent
  ],
  providers: []
})
export class PetsModule {}
```

If I export my 2 interceptors in petsModule its intercept the request but I want to import it once only in core module. I checkout this stackblitz https://stackblitz.com/edit/angular-http-interceptor-working-for-lazy-loaded-module?file=src/app/core/token-interceptor.service.ts and I ensure that I only import HttpClientModule in my core module.

答:
For use interceptor globally and the providers are in core module should add @Injectable({
  providedIn: 'root'
}) in the top of interceptors like here
https://stackblitz.com/edit/angular-http-interceptor-working-for-lazy-loaded-module?file=src/app/core/token-interceptor.service.ts</p>

Title: Angular use global interceptor

Body:
I want to use 2 interceptor globally (httpInterceptorProviders,
    jwtInterceptorProviders) but it not working in my lazy modules.
I have CoreModule and X lazy load modules. The weird part is that I have an autogenerated code by swagger generator(http services) this calls being intercepted but when I use custom http services interceptor not intercept this requests.

Index.ts where I get the providers

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
];

export const jwtInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
];

CoreModule, I import my interceptors in providers

@NgModule({
  imports: [
    // angular
    CommonModule,
    HttpClientModule,
    // ngrx
    StoreModule.forRoot(reducers, { metaReducers }),
    StoreRouterConnectingModule.forRoot(),
    EffectsModule.forRoot([AuthEffects, GoogleAnalyticsEffects]),
    environment.production
      ? []
      : StoreDevtoolsModule.instrument({
          name: "Angular NgRx Material Starter"
        }),

    // 3rd party
    TranslateModule.forRoot({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      }
    }),
    ApiModule.forRoot(() => {
      return new Configuration({
        basePath: `${environment.HOST}:${environment.PORT}`,
        apiKeys: { Authorization: "" }
      });
    })
  ],
  declarations: [],
  providers: [
    LocalStorageService,
    AuthGuardService,
    AnimationsService,
    TitleService,

    // retryHttpInterceptorProviders,
    { provide: ErrorHandler, useClass: AppErrorHandler },
    httpInterceptorProviders,
    jwtInterceptorProviders,
    { provide: RouterStateSerializer, useClass: CustomSerializer },
    {
      provide: HAMMER_LOADER,
      useValue: () => new Promise(() => {})
    },
    AnalyticsService,
    LayoutService,
    StateService,
    PetsServiceWithUpload
  ],
  exports: [TranslateModule]
})
export class CoreModule {
  constructor(
    @Optional()
    @SkipSelf()
    parentModule: CoreModule
  ) {
    if (parentModule) {
      throw new Error("CoreModule is already loaded. Import only in AppModule");
    }
  }
}

export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(
    http,
    `${environment.i18nPrefix}/assets/i18n/`,
    ".json"
  );
}

AppModule

@NgModule({
  declarations: [AppComponent, NavigationComponent, ErrorsComponent],
  imports: [
    BrowserAnimationsModule,
    BrowserModule,
    SharedModule,
    AppRoutingModule,
    AuthModule,
    ThemeModule.forRoot(),
    CoreModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule {}

Interceptor

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    private isRefreshing = false;
    private refreshTokenSubject: BehaviorSubject<any> = new BehaviorSubject<any>(null);
    constructor(private injector: Injector,
        private localstorage: LocalStorageService,
        private authService: AuthService,
        private store: Store<AppState>, ) { }

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        const tokenInfo = this.localstorage.getItem(AUTH_KEY);
        if (tokenInfo) {
            request = this.addToken(request, tokenInfo.token);
        }
        console.log('TCL: JwtInterceptor -> request', request);
        return next.handle(request).pipe(catchError(error => {
            if (error instanceof HttpErrorResponse && error.status === 401) {
                return this.handle401Error(request, next);
            } else {
                return throwError(error);
            }
        }));
    }

    private addToken(request: HttpRequest<any>, token: string): HttpRequest<any> {
        return request.clone({
            setHeaders: {
                'Authorization': `Bearer ${token}`
            }
        });
    }

    private handle401Error(request: HttpRequest<any>, next: HttpHandler) {

        if (!this.isRefreshing) {
            this.isRefreshing = true;
            this.refreshTokenSubject.next(null);
            const tokenInfo = this.localstorage.getItem(AUTH_KEY);
            return this.authService.authRefreshtokenPost({ refreshToken: tokenInfo.refreshToken }).pipe(
                switchMap((tokenRes: any) => {
                    this.isRefreshing = false;
                    this.refreshTokenSubject.next(tokenRes.token);
                    this.localstorage.setItem(AUTH_KEY,
                        { token: tokenRes.token, refreshToken: tokenRes.refreshToken, isAuthenticated: true });
                    return next.handle(this.addToken(request, tokenRes.token));
                }), catchError((error) => {
                    console.log('TCL: JwtInterceptor -> privatehandle401Error -> error', error);
                    this.store.dispatch(new AuthActions.Logout({ refreshToken: tokenInfo.refreshToken }));
                    return next.handle(request);
                }));

        } else {
            return this.refreshTokenSubject.pipe(
                filter(token => token != null),
                take(1),
                switchMap(jwt => {
                    return next.handle(this.addToken(request, jwt));
                }));
        }
    }
}

Lazy load module

@NgModule({
  imports: [
    ThemeModule,
    PetsRoutingModule,
    StoreModule.forFeature("pets", petsReducer),
    TranslateModule.forChild({
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        deps: [HttpClient]
      },
      isolate: true
    }),
    EffectsModule.forFeature([PetsEffects]),
    InfiniteScrollModule,
    SharedModule
  ],
  declarations: [
    PetsComponent,
    CreatePetComponent,
    ViewPetComponent,
    FormPetComponent,
    EditPetComponent,
    PetListVirtualComponent
  ],
  providers: []
})
export class PetsModule {}

If I export my 2 interceptors in petsModule its intercept the request but I want to import it once only in core module. I checkout this stackblitz https://stackblitz.com/edit/angular-http-interceptor-working-for-lazy-loaded-module?file=src/app/core/token-interceptor.service.ts and I ensure that I only import HttpClientModule in my core module.


问:
Getting error "variable veryFar might not have been initialized" with BigInteger
I am making a converter which will convert numbers to text. I did everything as said in this website and edited for using big Integers but it is then showing a variable is not initialized.

I edited some things to make it compatible with big integers for bigger numbers, but it just shows variable veryFar maybe not initialized. (I edited the variable name to try fix it!).

package com.example.convertnumbertotext;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class EnglishNumberToWords {

    private static BigInteger bi = new BigInteger("100");
    private static BigInteger bi2 = new BigInteger("20");
    private static BigInteger bi3 = new BigInteger("10");
    private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty",
            " fifty", " sixty", " seventy", " eighty", " ninety" };

    private static final String[] numNames = { "", " one", " two", " three", " four", " five",
            " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen",
            " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

    private static String convertLessThanOneThousand(BigInteger number) {
        String veryFar;
        BigInteger[] bii = number.divideAndRemainder(bi);
        BigInteger[] bii2 = number.divideAndRemainder(bi3);
        int resut = bii[1].compareTo(bi2);

        if (resut == -1) {
            veryFar = numNames[bii[1].intValue()];

            number = number.divide(bi);
        } else if (resut == 1 || resut == 0) {
            veryFar = numNames[bii2[1].intValue()];
            number = number.divide(bi3);

            veryFar = tensNames[bii2[1].intValue()] + veryFar;
            number = number.divide(bi3);
        }
        if (number.compareTo(BigInteger.valueOf(0)) == 0)
            return veryFar;
            return numNames[number.intValue()] + " hundred" + veryFar;
    }

}
```

It shows 2 same error messages-
error: variable veryFar might not have been initialized
error: variable veryFar might not have been initialized

答:
Note that the contract of compareTo is that it returns <0, 0 or >0, not -1, 0 or 1.

Comparing to -1 and 1 exactly may work sometimes, but it wouldn't work in general (e.g. it wouldn't work for comparing Strings), and is brittle to changes in internal implementation details of the class.

As such, change your conditions to:

```<code>if (resut < 0) { // instead of == -1
  // ...
} else { // instead of == 0 || == 1
  // ...
}
</code>```

Then your variable will always be initialized.

Body:
I am making a converter which will convert numbers to text. I did everything as said in this website and edited for using big Integers but it is then showing a variable is not initialized.

I edited some things to make it compatible with big integers for bigger numbers, but it just shows variable veryFar maybe not initialized. (I edited the variable name to try fix it!).

package com.example.convertnumbertotext;

import java.math.BigInteger;
import java.text.DecimalFormat;

public class EnglishNumberToWords {

    private static BigInteger bi = new BigInteger("100");
    private static BigInteger bi2 = new BigInteger("20");
    private static BigInteger bi3 = new BigInteger("10");
    private static final String[] tensNames = { "", " ten", " twenty", " thirty", " forty",
            " fifty", " sixty", " seventy", " eighty", " ninety" };

    private static final String[] numNames = { "", " one", " two", " three", " four", " five",
            " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen",
            " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" };

    private static String convertLessThanOneThousand(BigInteger number) {
        String veryFar;
        BigInteger[] bii = number.divideAndRemainder(bi);
        BigInteger[] bii2 = number.divideAndRemainder(bi3);
        int resut = bii[1].compareTo(bi2);

        if (resut == -1) {
            veryFar = numNames[bii[1].intValue()];

            number = number.divide(bi);
        } else if (resut == 1 || resut == 0) {
            veryFar = numNames[bii2[1].intValue()];
            number = number.divide(bi3);

            veryFar = tensNames[bii2[1].intValue()] + veryFar;
            number = number.divide(bi3);
        }
        if (number.compareTo(BigInteger.valueOf(0)) == 0)
            return veryFar;
            return numNames[number.intValue()] + " hundred" + veryFar;
    }

}

It shows 2 same error messages-
error: variable veryFar might not have been initialized
error: variable veryFar might not have been initialized

Body:
Note that the contract of compareTo is that it returns <0, 0 or >0, not -1, 0 or 1.

Comparing to -1 and 1 exactly may work sometimes, but it wouldn't work in general (e.g. it wouldn't work for comparing Strings), and is brittle to changes in internal implementation details of the class.

As such, change your conditions to:

if (resut < 0) { // instead of == -1
  // ...
} else { // instead of == 0 || == 1
  // ...
}

Then your variable will always be initialized.


答:
Everything on the same indent level is a sequence. It executes one after the other.

Everything that is indented is dependent on the line before the indent.

In your case, you have a sequence of three things: an assignment, then a conditional (which may or may not execute its own sequence of two things), then a print.

In order to make sure something doesn't execute as a part of the conditional, you need to introduce an else branch:

```<code>var = 100
if var == 100:
    print ("Value of expression is 100")
    print ("Good bye!")
else:
    print("AM I out?")
</code>```

Here you have a sequence of two things: one assignment and one conditional. The conditional has a sequence of two prints in the positive branch, and one print in the negative branch.

Title: Python indentation not clear

Body:
Everything on the same indent level is a sequence. It executes one after the other.

Everything that is indented is dependent on the line before the indent.

In your case, you have a sequence of three things: an assignment, then a conditional (which may or may not execute its own sequence of two things), then a print.

In order to make sure something doesn't execute as a part of the conditional, you need to introduce an else branch:

var = 100
if var == 100:
    print ("Value of expression is 100")
    print ("Good bye!")
else:
    print("AM I out?")

Here you have a sequence of two things: one assignment and one conditional. The conditional has a sequence of two prints in the positive branch, and one print in the negative branch.


问:
Commit pushed with 2 authors
I have my work ssh keys set on my local system. Now I also, tried to push a project to my personal github account.

I changed the author of the commit while committing.
On git log I can see the new author.

```<code>commit 73344e555da22600723a8302b7d476787f2668e3 (HEAD -> master)
Author: A G <laun.biz@gmail.com>
Date:   Wed May 29 00:35:41 2019 +0530

    First Commit
</code>```

I pushed it using username and password.

```<code>git push https://username:password@github.com/Laun/laun-api.git master
</code>```

Now when I go and check on Github , I see,

```<code>Laun and agupta-at-wellthie First Commit
</code>```

Laun is my personal username and
agupta-at-wellthie is my work account username. What did I do wrong?

答:
I changed the author of the commit while committing.

That's fine—but you didn't change the committer.

Every commit has not one but two "who made this commit, and when" stamps on it: the author, which you can override with --author in git commit, and the committer, which has no obvious command-line option to override it.

It's possible to override all six parts individually, through six environment variables:

GIT_AUTHOR_NAME sets the name part of the author line

GIT_AUTHOR_EMAIL sets the email-address part of the author line

GIT_AUTHOR_DATE sets the date-and-time-stamp part of the author line

GIT_COMMITTER_NAME sets the name part of the committer line

GIT_COMMITTER_EMAIL sets the email address part of the committer line

GIT_COMMITTER_DATE sets the date-and-time-stamp part of the committer line

If you don't override individual parts with environment variables, they default to:

author: you, or from --author, or from the author in a commit you referenced with -c or -C.

committer: you.

In this case, "you" means:

the setting from user.name, plus

the setting from user.email, plus

the current date-and-time as reported by your computer's clock.

Hence one way to override everything in a new commit (one without information copied from some existing commit) is to set your user.name and user.email, either through git config or through the command line:

```<code>git -c user.name='A U Thor' -c user.email='thor@example.com' commit
</code>```

If you add --author='Someone Else <else@example.com>', the --author part here will override the author line, while the committer line will come from the two -c parts (and the current time stamp).

If you want to override the committer time stamp, the only mechanism is to use GIT_COMMITTER_DATE, or change your computer's clock (either suffices, and of course the environment variable is easier and safer as it won't disturb the rest of your computer).

Title: Commit pushed with 2 authors

Body:
I have my work ssh keys set on my local system. Now I also, tried to push a project to my personal github account.

I changed the author of the commit while committing.
On git log I can see the new author.

commit 73344e555da22600723a8302b7d476787f2668e3 (HEAD -> master)
Author: A G <laun.biz@gmail.com>
Date:   Wed May 29 00:35:41 2019 +0530

    First Commit

I pushed it using username and password.

git push https://username:password@github.com/Laun/laun-api.git master

Now when I go and check on Github , I see,

Laun and agupta-at-wellthie First Commit

Laun is my personal username and
agupta-at-wellthie is my work account username. What did I do wrong?

Body:
I changed the author of the commit while committing.

That's fine—but you didn't change the committer.

Every commit has not one but two "who made this commit, and when" stamps on it: the author, which you can override with --author in git commit, and the committer, which has no obvious command-line option to override it.

It's possible to override all six parts individually, through six environment variables:

GIT_AUTHOR_NAME sets the name part of the author line

GIT_AUTHOR_EMAIL sets the email-address part of the author line

GIT_AUTHOR_DATE sets the date-and-time-stamp part of the author line

GIT_COMMITTER_NAME sets the name part of the committer line

GIT_COMMITTER_EMAIL sets the email address part of the committer line

GIT_COMMITTER_DATE sets the date-and-time-stamp part of the committer line

If you don't override individual parts with environment variables, they default to:

author: you, or from --author, or from the author in a commit you referenced with -c or -C.

committer: you.

In this case, "you" means:

the setting from user.name, plus

the setting from user.email, plus

the current date-and-time as reported by your computer's clock.

Hence one way to override everything in a new commit (one without information copied from some existing commit) is to set your user.name and user.email, either through git config or through the command line:

git -c user.name='A U Thor' -c user.email='thor@example.com' commit

If you add --author='Someone Else <else@example.com>', the --author part here will override the author line, while the committer line will come from the two -c parts (and the current time stamp).

If you want to override the committer time stamp, the only mechanism is to use GIT_COMMITTER_DATE, or change your computer's clock (either suffices, and of course the environment variable is easier and safer as it won't disturb the rest of your computer).


问:
Is there a way to inherit parameters from a parent class's constructor?
The problem I'm having is that I have some base (generic) classes whose properties are initialized via the class's constructor. When I then go to extend this class to create a more specific class, I must re-type the same parameters that the base class's constructor has, just so I can pass them to super. If you imagine a very generic class that has many properties that are initialized via a constructor , and that is extended quite often, having to constantly re-type all these properties just to pass them to super each time seems inefficient. I am likely missing some common way of preventing this. Any ideas how to make this more efficient? Perhaps by somehow "inheriting" the parent class's constructor parameters?

Here's a code example, and, as you can see, in Programmer's constructor, I have to re-type name, age, and height again just to pass it to super:

class Person {
    name: string;
    age: number;
    height: number;

    constructor(name: string, age: number, height: number) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

class Programmer extends Person {
    languages: string[];

    constructor(name: string, age: number, height: number, languages: string[]) {
        super(name, age, height);

        this.languages = languages;
    }
}
```

答:
You can't inherit, but you can refer to the parameter using ContructorParameters and you can spread them back in your derived constructor, as long as you don't mind adding any new parameters at the front:

```<code>class Person {
    name: string;
    age: number;
    height: number;

    constructor(name: string, age: number, height: number) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

class Programmer extends Person {
    languages: string[];

    constructor(languages: string[], ...p: ConstructorParameters<typeof Person>) {
        super(...p);

        this.languages = languages;
    }
}

new Programmer(["A"], "", 1, 1) // Since 3.4 you will get actual parameter names in intelisense not just ...p
</code>```

Not sure it's the best design though, and if you have a lot of parameters you might be better off defining an interface and passing that in instead. Or using some sort of mapped type to extract relevant fields.

Body:
You can't inherit, but you can refer to the parameter using ContructorParameters and you can spread them back in your derived constructor, as long as you don't mind adding any new parameters at the front:

class Person {
    name: string;
    age: number;
    height: number;

    constructor(name: string, age: number, height: number) {
        this.name = name;
        this.age = age;
        this.height = height;
    }
}

class Programmer extends Person {
    languages: string[];

    constructor(languages: string[], ...p: ConstructorParameters<typeof Person>) {
        super(...p);

        this.languages = languages;
    }
}

new Programmer(["A"], "", 1, 1) // Since 3.4 you will get actual parameter names in intelisense not just ...p

Not sure it's the best design though, and if you have a lot of parameters you might be better off defining an interface and passing that in instead. Or using some sort of mapped type to extract relevant fields.


问:
Using downgradeModule in conjunction with downgradeInjectable in an angular / angularjs hybrid application results in error
With angular 5.0 the upgrade module now has the option of using downgradeModule which runs angularjs outside of the angular zone. While experimenting with this I have run into a problem with using downgradeInjectable.

I am receiving the error:

Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.

Bootstrapping angular in angular js works fine

```<code>import 'zone.js/dist/zone.js';
import * as angular from 'angular';
/**
 * Angular bootstrapping
 */
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { decorateModuleRef } from 'src/environment';
import { AppModule } from 'src/app/app.module';
import { downgradeModule } from '@angular/upgrade/static';

export const bootstrapFn = ( extraProviders ) => {
    const platformRef = platformBrowserDynamic( extraProviders );
    return platformRef
        .bootstrapModule( AppModule )
        .then( decorateModuleRef );
};

angular.module( 'app.bootstrap', [
    downgradeModule( bootstrapFn ),
] );
</code>```

However...

Since the bootstrapping takes place after angularjs has been initialized I can no longer get the downgrade injectable working.

Service to be downgraded

```<code>import { Injectable, Inject, OnInit } from '@angular/core';

@Injectable()
export class MobileService implements OnInit{
    constructor(
        @Inject( 'angularjsDependency1' ) public angularjsDependency1 : any,
        @Inject( 'angularjsDependency2' ) public angularjsDependency2 : any,
    ) {}

}
</code>```

Downgrade injectable attempt

```<code>import * as angular from 'angular';
import { downgradeInjectable } from '@angular/upgrade/static';
import { MyService } from 'src/services/myService/myService';

export const myServiceDowngraded = angular.module( 'services.mobileService', [
    angularjsDependency1,
    angularjsDependency2,
] )

.factory(
    'mobileService',
    downgradeInjectable( MyService ),
).name;
</code>```

When "downgradeInjectable( MyService ) runs the angular injector is not available yet since angular hasn't been bootstrapped. Hence the error:

Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.

Does anyone have an idea how I might fix this?

答:
I had the same issue, and the reasons are explained in the above answer.

I fixed this by dynamically injecting the downgraded angular service using $injector.

Steps

Register your downgraded service to angularjs module

```<code> angular.module('moduleName', dependencies)
 angular.factory('service', downgradeInjectable(Service));
</code>```

Inject $injector to your controller and use this to get the downgraded service

```<code>const service = this.$injector.get('service');
service.method();
</code>```

Body:
With angular 5.0 the upgrade module now has the option of using downgradeModule which runs angularjs outside of the angular zone. While experimenting with this I have run into a problem with using downgradeInjectable.

I am receiving the error:

Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.

Bootstrapping angular in angular js works fine

import 'zone.js/dist/zone.js';
import * as angular from 'angular';
/**
 * Angular bootstrapping
 */
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { decorateModuleRef } from 'src/environment';
import { AppModule } from 'src/app/app.module';
import { downgradeModule } from '@angular/upgrade/static';

export const bootstrapFn = ( extraProviders ) => {
    const platformRef = platformBrowserDynamic( extraProviders );
    return platformRef
        .bootstrapModule( AppModule )
        .then( decorateModuleRef );
};

angular.module( 'app.bootstrap', [
    downgradeModule( bootstrapFn ),
] );

However...

Since the bootstrapping takes place after angularjs has been initialized I can no longer get the downgrade injectable working.

Service to be downgraded

import { Injectable, Inject, OnInit } from '@angular/core';

@Injectable()
export class MobileService implements OnInit{
    constructor(
        @Inject( 'angularjsDependency1' ) public angularjsDependency1 : any,
        @Inject( 'angularjsDependency2' ) public angularjsDependency2 : any,
    ) {}

}

Downgrade injectable attempt

import * as angular from 'angular';
import { downgradeInjectable } from '@angular/upgrade/static';
import { MyService } from 'src/services/myService/myService';

export const myServiceDowngraded = angular.module( 'services.mobileService', [
    angularjsDependency1,
    angularjsDependency2,
] )

.factory(
    'mobileService',
    downgradeInjectable( MyService ),
).name;

When "downgradeInjectable( MyService ) runs the angular injector is not available yet since angular hasn't been bootstrapped. Hence the error:

Uncaught Error: Trying to get the Angular injector before bootstrapping an Angular module.

Does anyone have an idea how I might fix this?

Body:
I had the same issue, and the reasons are explained in the above answer.

I fixed this by dynamically injecting the downgraded angular service using $injector.

Steps

Register your downgraded service to angularjs module

 angular.module('moduleName', dependencies)
 angular.factory('service', downgradeInjectable(Service));

Inject $injector to your controller and use this to get the downgraded service

const service = this.$injector.get('service');
service.method();


问:
How to Calculate difference between hours when the cells contain date in date format? And there are some conditions too
Need difference between Created & Closed In Hours along with below

The TAT hour to be calculated between 9:00 am to 09:00 pm which is working hours, if created time us 09 pm then it should be considered from next day 9 am.

Sunday is Holiday

I have tried:- =Created-Closed Date, but don't know how to exclude Sunday and  calculate only shift hours.

Body:
Yes! Finally Self Got Answer For it.

Here is that

=(NETWORKDAYS(A2,B2)-1)*("21:00:00"-"09:00:00")
+IF(NETWORKDAYS(B2,B2),MEDIAN(MOD(B2,1),"21:00:00","09:00:00"),"21:00:00")
-MEDIAN(NETWORKDAYS(A2,A2)*MOD(A2,1),"21:00:00","09:00:00")


问:
Getting workitems link using TFS C# API
i am new to TFS API and i am using C# code as described in:
https://learn.microsoft.com/en-us/azure/devops/integrate/get-started/client-libraries/samples?view=azure-devops

I was managed to run the code on my TFS test server and to get the querty result quite easily. However, when i am tryin to get work items links details, i can't find the right way to do it.
When i zom into 1 object during the code executuon, i see that the Links attribute is set to null while the 'real' workitem in TFS as linked WI as parent. Any idea how can I loop thru WI links ang get the linked WI details?
Many thanks in advance :-)

答:
You have to set the expand attribute in GetWorkItemAsync:

GetWorkItemAsync(Id, expand: WorkItemExpand.Relations).Result

You can find all links in Relations list. Link does not contain an id, but you can extract it from link URL. Parent type is System.LinkTypes.Hierarchy-Reverse value in Rel member. Example of the relations list:

```<code>var wi = GetWorkItemWithRelations(wiId);

if (wi.Relations != null)
    {
        foreach (var wiLink in wi.Relations)
        Console.WriteLine("{0,-40}: {1}", wiLink.Rel, ExtractWiIdFromUrl(wiLink.Url));
    }

static int ExtractWiIdFromUrl(string Url)
{
    int id = -1;

    string splitStr = "_apis/wit/workItems/";

    if (Url.Contains(splitStr))
    {
        string [] strarr = Url.Split(new string[] { splitStr }, StringSplitOptions.RemoveEmptyEntries);

        if (strarr.Length == 2 && int.TryParse(strarr[1], out id))
                return id;
    }

    return id;
}
</code>```

Additional link types you can find here: https://learn.microsoft.com/en-us/azure/devops/boards/queries/link-type-reference?view=azure-devops&viewFallbackFrom=vsts

Title: Getting workitems link using TFS C# API

Body:
You have to set the expand attribute in GetWorkItemAsync:

GetWorkItemAsync(Id, expand: WorkItemExpand.Relations).Result

You can find all links in Relations list. Link does not contain an id, but you can extract it from link URL. Parent type is System.LinkTypes.Hierarchy-Reverse value in Rel member. Example of the relations list:

var wi = GetWorkItemWithRelations(wiId);

if (wi.Relations != null)
    {
        foreach (var wiLink in wi.Relations)
        Console.WriteLine("{0,-40}: {1}", wiLink.Rel, ExtractWiIdFromUrl(wiLink.Url));
    }

static int ExtractWiIdFromUrl(string Url)
{
    int id = -1;

    string splitStr = "_apis/wit/workItems/";

    if (Url.Contains(splitStr))
    {
        string [] strarr = Url.Split(new string[] { splitStr }, StringSplitOptions.RemoveEmptyEntries);

        if (strarr.Length == 2 && int.TryParse(strarr[1], out id))
                return id;
    }

    return id;
}

Additional link types you can find here: https://learn.microsoft.com/en-us/azure/devops/boards/queries/link-type-reference?view=azure-devops&viewFallbackFrom=vsts


问:
Is this good practice to change build files directly in angular?
I have some scenario to modify build files after deployment. Is this good practice to change manually?</p>

答:
As per the discussion in the comments, what you want to do is to have different configurations for different environments, there are lots of ways to accomplish this. A built in angular cli way is to use different build configurations. Build configurations have a file replacements option that replaces a file you specify with different variants of it.

In the default scaffold project you can see this pattern with the environments/environment.ts file. You will see a production variant of it with the name environment.prod.ts To have a different api url for production all you have to do is to add the production api url to that file and the development api url to environment.ts For staging, you will have to create a build configuration with a file replacement called environment.staging.ts

The configuration in angular.json would look like this,

```<code>"configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": ".../environments/environment.ts",
                  "with": ".../environments/environment.prod.ts"
                }
               ]
              ...
              "staging": {
               "fileReplacements": [
                 {
                   "replace": ".../environments/environment.ts",
                   "with": ".../environments/environment.staging.ts"
                  }
                ],
  }
</code>```

Make sure you always import the api base url from environment.ts and not any of the variants. ng build --configuration staging will do the replacement for you.

Body:
As per the discussion in the comments, what you want to do is to have different configurations for different environments, there are lots of ways to accomplish this. A built in angular cli way is to use different build configurations. Build configurations have a file replacements option that replaces a file you specify with different variants of it.

In the default scaffold project you can see this pattern with the environments/environment.ts file. You will see a production variant of it with the name environment.prod.ts To have a different api url for production all you have to do is to add the production api url to that file and the development api url to environment.ts For staging, you will have to create a build configuration with a file replacement called environment.staging.ts

The configuration in angular.json would look like this,

"configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": ".../environments/environment.ts",
                  "with": ".../environments/environment.prod.ts"
                }
               ]
              ...
              "staging": {
               "fileReplacements": [
                 {
                   "replace": ".../environments/environment.ts",
                   "with": ".../environments/environment.staging.ts"
                  }
                ],
  }

Make sure you always import the api base url from environment.ts and not any of the variants. ng build --configuration staging will do the replacement for you.


问:
Cant clear the value of TextInput in react-native
enter image description herethis problem show in ios,when i use TextInput of react-native,but it  can't type Chinese when using soft keyboard，so i modify the code like picture1,but  a new problem has arisen,when i enter the key to send ,the value of the TextInput cant clear.
what can i do?enter image desenter code herecription here

 <TextareaItem clear={true}  type="text" ref="text" value={this.state.meg}
 editable={true} disabled={false} onChange={(value) => {
                                    if (Platform.OS =='ios'){
                                        this.meg = value
                                    } else {
                                        this.setState({
                                            meg:value
                                        })}}} />

    sendMeg = () => {
        let message = ''
        if (this.meg !== '')
        messahe = this.meg
        }else{message = this.state.meg}
      this.meg = ''
      this.setState({  meg:''})
}```

solve with this answer https://github.com/CHANOMA/react-native/pull/3/files#diff-8eb50d68d87e28556c034717cd58a86e

答:
Add this code where you want to reset  meg field:

```<code>this.setState({meg: ''})
</code>```

Body:
enter image description herethis problem show in ios,when i use TextInput of react-native,but it  can't type Chinese when using soft keyboard，so i modify the code like picture1,but  a new problem has arisen,when i enter the key to send ,the value of the TextInput cant clear.
what can i do?enter image desenter code herecription here

 <TextareaItem clear={true}  type="text" ref="text" value={this.state.meg}
 editable={true} disabled={false} onChange={(value) => {
                                    if (Platform.OS =='ios'){
                                        this.meg = value
                                    } else {
                                        this.setState({
                                            meg:value
                                        })}}} />

    sendMeg = () => {
        let message = ''
        if (this.meg !== '')
        messahe = this.meg
        }else{message = this.state.meg}
      this.meg = ''
      this.setState({  meg:''})
}

solve with this answer https://github.com/CHANOMA/react-native/pull/3/files#diff-8eb50d68d87e28556c034717cd58a86e

Body:
Add this code where you want to reset  meg field:

this.setState({meg: ''})


问:
sfinae on member function defined outside of class body
Kind of a continuation from my previous question. What I've got is a bunch of functions that form a sfinae depencency chain like so (let "A -> B" notation mean that existence of A depends on existence of B):

```<code>S::f_base -> S::f -> ns::f_ -> f -> T::f
</code>```

where T is the template argument. It's implemented like this:

```<code>#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
    {
        ns::f_(*this, t);
    }

    template <typename T>
    auto f_base(T const* t_ptr) -> decltype(f(*t_ptr), void())
    {
        f(*t_ptr);
    }
};

struct pass
{
   void f(S&) const
   {
   }
};

struct fail
{

};

int main()
{
    S s;
    s.f(pass()); // compiles
    //s.f(fail()); // doesn't compile
    return 0;
}
</code>```

and works as intended. The problem arises when I attempt to move definitions of S::f and S::f_base outside the class body, like so:

```<code>#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void());

    template <typename T>
    auto f_base(T const* t_ptr) -> decltype(f(*t_ptr), void());
};

template <typename T>
auto S::f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
{
    ns::f_(*this, t);
}

template <typename T>
auto S::f_base(T const* t_ptr) -> decltype(f(*t_ptr), void()) // <---- HERE ---
{
    f(*t_ptr);
}

int main()
{

    return 0;
}
</code>```

On the line marked by arrow GCC 4.7.1 expresses it's dissatisfaction:

error: prototype for 'decltype ((((S*)0)->S::f((* t_ptr)), void())) S::f_base(const T*)' does not match any in class 'S'

 error: candidate is: template decltype ((((S*)this)->S::f((* t_ptr)), void())) S::f_base(const T*)

I tried to explicitly specify which f I'm using in f_base by prepending it (in both declaration and definition) with std::declval<S&>()., but the error persists.

I know I can modify the dependency graph like so:

```<code>S::f_base ->
          -> ns::f_ -> f -> T::f
S::f      ->
</code>```

to make S::f_base depend on ns::f_ along with S::f, but is there a way to do this with the first dependency graph?

答:
GCC 4.X is not the best for meta programing

I have manage to make it compile in 4.7.3 (live) :

```<code>#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

// some std::void_t like but GCC4.x compatible
template<class T>
struct void_t
{
   using type = typename std::enable_if<std::is_same<T,T>::value >::type;
};

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void());

    template <typename T>
    auto f_base(T const* t_ptr) ->  typename void_t< decltype (::f(*std::declval<T const*>()))>::type ;
};

template <typename T>
auto S::f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
{
    ns::f_(*this, t);
}

// ::f is needed, fail if just 'f'
template <typename T>
auto S::f_base(T const* t_ptr) ->  typename void_t< decltype (::f(*std::declval<T const*>()))>::type
{
    f(*t_ptr);
}
int main()
{

    return 0;
}
</code>```

Note:

In GCC4.X I have seen some weird stuff like :

```<code>template<class T>
struct void_t
{
   using type = void;
};
</code>```

Where GCC replace void_t<decltype(expr)>::type by void even if expr is not valid. That why I use this implementation of void_t.

Body:
Kind of a continuation from my previous question. What I've got is a bunch of functions that form a sfinae depencency chain like so (let "A -> B" notation mean that existence of A depends on existence of B):

S::f_base -> S::f -> ns::f_ -> f -> T::f

where T is the template argument. It's implemented like this:

#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
    {
        ns::f_(*this, t);
    }

    template <typename T>
    auto f_base(T const* t_ptr) -> decltype(f(*t_ptr), void())
    {
        f(*t_ptr);
    }
};

struct pass
{
   void f(S&) const
   {
   }
};

struct fail
{

};

int main()
{
    S s;
    s.f(pass()); // compiles
    //s.f(fail()); // doesn't compile
    return 0;
}

and works as intended. The problem arises when I attempt to move definitions of S::f and S::f_base outside the class body, like so:

#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void());

    template <typename T>
    auto f_base(T const* t_ptr) -> decltype(f(*t_ptr), void());
};

template <typename T>
auto S::f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
{
    ns::f_(*this, t);
}

template <typename T>
auto S::f_base(T const* t_ptr) -> decltype(f(*t_ptr), void()) // <---- HERE ---
{
    f(*t_ptr);
}

int main()
{

    return 0;
}

On the line marked by arrow GCC 4.7.1 expresses it's dissatisfaction:

error: prototype for 'decltype ((((S*)0)->S::f((* t_ptr)), void())) S::f_base(const T*)' does not match any in class 'S'

 error: candidate is: template decltype ((((S*)this)->S::f((* t_ptr)), void())) S::f_base(const T*)

I tried to explicitly specify which f I'm using in f_base by prepending it (in both declaration and definition) with std::declval<S&>()., but the error persists.

I know I can modify the dependency graph like so:

S::f_base ->
          -> ns::f_ -> f -> T::f
S::f      ->

to make S::f_base depend on ns::f_ along with S::f, but is there a way to do this with the first dependency graph?

Body:
GCC 4.X is not the best for meta programing

I have manage to make it compile in 4.7.3 (live) :

#include <utility>

struct S;

template <typename T>
auto f(S& s, T const& t) -> decltype(t.f(s), void())
{
    t.f(s);
}

namespace ns
{
    template <typename T>
    auto f_(S& s, T const& t) -> decltype(f(s, t), void())
    {
        f(s, t);
    }
}

// some std::void_t like but GCC4.x compatible
template<class T>
struct void_t
{
   using type = typename std::enable_if<std::is_same<T,T>::value >::type;
};

struct S
{
    template <typename T>
    auto f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void());

    template <typename T>
    auto f_base(T const* t_ptr) ->  typename void_t< decltype (::f(*std::declval<T const*>()))>::type ;
};

template <typename T>
auto S::f(T const& t) -> decltype(ns::f_(std::declval<S&>(), t), void())
{
    ns::f_(*this, t);
}

// ::f is needed, fail if just 'f'
template <typename T>
auto S::f_base(T const* t_ptr) ->  typename void_t< decltype (::f(*std::declval<T const*>()))>::type
{
    f(*t_ptr);
}
int main()
{

    return 0;
}

Note:

In GCC4.X I have seen some weird stuff like :

template<class T>
struct void_t
{
   using type = void;
};

Where GCC replace void_t<decltype(expr)>::type by void even if expr is not valid. That why I use this implementation of void_t.


问:
How to compare the temporary variables in the form of string?
I want to know why the two results are different?

the code is：

```<code>string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;
</code>```

the output is:

1 0

答:
Literal strings in C++ are really arrays of constant characters. As any other array, they decay to pointers to their first element.

With "35">"255" you compare the pointers, and not the contents of the strings themselves.

To compare literal strings you need to use std::strcmp. But note that it doesn't return a boolean value.

What you current do is roughly equivalent to

```<code>char const* a = "35";
char const* b = "255";
std::cout << (&a[0] > &b[0]) << '\n';  // Print the result of comparing the *pointers*
</code>```

With s1>s2 you're invoking the operator> function of std::string. The expression s1 > s2 is equivalent to s1.operator>(s2).

Body:
I want to know why the two results are different?

the code is：

string s1="35",s2="255";
cout<<(s1>s2)<<" "<<("35">"255")<<endl;

the output is:

1 0

Body:
Literal strings in C++ are really arrays of constant characters. As any other array, they decay to pointers to their first element.

With "35">"255" you compare the pointers, and not the contents of the strings themselves.

To compare literal strings you need to use std::strcmp. But note that it doesn't return a boolean value.

What you current do is roughly equivalent to

char const* a = "35";
char const* b = "255";
std::cout << (&a[0] > &b[0]) << '\n';  // Print the result of comparing the *pointers*

With s1>s2 you're invoking the operator> function of std::string. The expression s1 > s2 is equivalent to s1.operator>(s2).


问:
How to Comma separate multiple rows obtained from a SQL Query
```<code>Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
</code>```

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?

答:
Try something like:

```<code>select s.FirstName, GROUP_CONCAT(glTitle.LookupItem Title, ',')
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
GROUP BY s.FirstName
</code>```

Cant really test, so its difficult, trail and error usually works eventually. I would suggest to group by a unique id though.

I hope this helps...

Body:
Select s.FirstName, glTitle.LookupItem Title
    from ClientStaff cs
    left outer join Staff s on s.Id = cs.StaffId
    left outer join StaffTitle st on st.StaffId = s.Id
    left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId

It returns these rows:

As you can see, the first column has all same rows because one employee can have multiple titles.

How can I merge all of the titles for each employee into a comma separated value so that there is only one row per employee?

Body:
Try something like:

select s.FirstName, GROUP_CONCAT(glTitle.LookupItem Title, ',')
from ClientStaff cs
left outer join Staff s on s.Id = cs.StaffId
left outer join StaffTitle st on st.StaffId = s.Id
left outer join GeneralLookup glTitle on glTitle.Id = st.glTitleId
GROUP BY s.FirstName

Cant really test, so its difficult, trail and error usually works eventually. I would suggest to group by a unique id though.

I hope this helps...


问:
How to make an activity background completely transparent (not translucent)?
In my android activity, I need to make the background of the activity transparent. For that, I found solutions online saying to do this in theme.

```<code><item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
</code>```

However this makes the activity background translucent i.e it isn't perfectly transparent, it is slightly grey. Is there a way to get a perfectly transparent background such that the screen below it is perfectly viisible. Thanks!

答:
Try this

```<code><style name="TransparentTheme.Base" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>
</code>```

Usage

```<code><activity
        android:name=".activity"
        android:theme="@style/TransparentTheme.Base" />
</code>```

Body:
In my android activity, I need to make the background of the activity transparent. For that, I found solutions online saying to do this in theme.

<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>

However this makes the activity background translucent i.e it isn't perfectly transparent, it is slightly grey. Is there a way to get a perfectly transparent background such that the screen below it is perfectly viisible. Thanks!

Body:
Try this

<style name="TransparentTheme.Base" parent="Theme.AppCompat.DayNight.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
        <item name="android:windowIsTranslucent">true</item>
        <item name="android:windowBackground">@android:color/transparent</item>
        <item name="android:windowContentOverlay">@null</item>
        <item name="android:backgroundDimEnabled">false</item>
    </style>

Usage

<activity
        android:name=".activity"
        android:theme="@style/TransparentTheme.Base" />


问:
Change color of single li on hover
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="tags-list">
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
<li>Testing</li>
</ul></code>```

答:
Change .tags-list ul li a:hover to .tags-list li:hover a. The repeated ul in the selector was making it not match the links.

On top of that, I'd recommend putting the :hover on the li rather than the a, so the text color will also change if you mouse points to the padding surrounding the a.

.tags-list li {
  display: inline-block;
  background-color: #253b5d;
  padding: 1px 10px !important;
  text-transform: lowercase;
  font-weight: normal;
  font-size: 14px;
  transition: all 1s linear;
}

.tags-list li:hover {
  background-color: #aebdd5;
}

.tags-list li a {
  transition: all 1s linear;
  color: white;
}

.tags-list li:hover a {
  color: black;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul class="tags-list">
  <li>Testing</li>
  <li>Testing</li>
  <li>Testing</li>
  <li>Testing</li>
  <li>Testing</li>
  <li>Testing</li>
</ul></code>```

Title: Change color of single li on hover

Body:
I am struggling to change the font color of that particular li when hover over. My code is not working properly when mouse is pointed to li from white to black color.

.tags-list li{display:inline-block;background-color:#253b5d;    padding: 1px 10px !important;
    text-transform: lowercase;
    font-weight: normal;
    font-size: 14px;
    transition: all 1s linear;
    }
.tags-list li:hover{background-color: #aebdd5;}
.tags-list li a{transition: all 1s linear;color:white;}
.tags-list ul li a:hover{color:black;}

Testing

Testing

Testing

Testing

Testing

Testing

Body:
Change .tags-list ul li a:hover to .tags-list li:hover a. The repeated ul in the selector was making it not match the links.

On top of that, I'd recommend putting the :hover on the li rather than the a, so the text color will also change if you mouse points to the padding surrounding the a.

.tags-list li {
  display: inline-block;
  background-color: #253b5d;
  padding: 1px 10px !important;
  text-transform: lowercase;
  font-weight: normal;
  font-size: 14px;
  transition: all 1s linear;
}

.tags-list li:hover {
  background-color: #aebdd5;
}

.tags-list li a {
  transition: all 1s linear;
  color: white;
}

.tags-list li:hover a {
  color: black;
}

<ul class="tags-list">
  <li><a href="#">Testing</a></li>
  <li><a href="#">Testing</a></li>
  <li><a href="#">Testing</a></li>
  <li><a href="#">Testing</a></li>
  <li><a href="#">Testing</a></li>
  <li><a href="#">Testing</a></li>
</ul>