问:
Python Script Executes Manually in CMD but Errors in Scheduler
So, I have a python script, that I can run in cmd using python [path to script]

I have it set in scheduler, but it doesn't run through scheduler and finds an error.  Cmd closes out before being able to read the error.  I created a batch file to launch to script, and it shows an error that a package doesn't exist [lxml]. But, the package exists as the script will run when manually executed

Any thoughts?

Script scrapes data from a website, creates a dataframe, posts dataframe to a google sheet, then pulls the full google sheet that it posts to, turns that into a dataframe with all of the data, then creates a plotly graph, turns that plotly into an html file, then sends the html file to a SFTP server

答:
Figured it out...

```<code>import sys
import platform
import imp

print("Python EXE     : " + sys.executable)
print("Architecture   : " + platform.architecture()[0])
#print("Path to arcpy  : " + imp.find_module("arcpy")[1])

#raw_input("\n\nPress ENTER to quit")
</code>```

Run this to get the proper path to your Python.exe, and place this in Program/Script.

Then you need to verify that EVERY directory in your script starts at C:/ and works its way through the full path.

Body:
Figured it out...

import sys
import platform
import imp

print("Python EXE     : " + sys.executable)
print("Architecture   : " + platform.architecture()[0])
#print("Path to arcpy  : " + imp.find_module("arcpy")[1])

#raw_input("\n\nPress ENTER to quit")

Run this to get the proper path to your Python.exe, and place this in Program/Script.

Then you need to verify that EVERY directory in your script starts at C:/ and works its way through the full path.


来源: stackexchange

问:
Regex extract everything except a pattern (string in quotes)
I have a string like input = "I really like "Game of Thrones" (show in quotes) and I only want to extract I really like but I can't get the right regex to do this.
Something like this doesn't work re.search(".*^(?!\".*\")", input).

I can do something like re.sub('".*"','', input) but I'm struggling to find the non-sub, extract using re.search method.

答:
Here you go:

```<code>input = 'I really like "Game of Thrones"'

output = re.sub('"[a-zA-z0-9 _\.]+"','',input)

print(output)
</code>```

output:

```<code>I really like
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Here you go:

input = 'I really like "Game of Thrones"'

output = re.sub('"[a-zA-z0-9 _\.]+"','',input)

print(output)

output:

I really like


问:
How to base the width of the rest of the elements on the width of the title?
I have some centered divs that have a title and text below the title. The title is centered but the text is aligned on the left and starts from where the title starts. I used inline-block to make the div adjust in size based on the content. However, if the text is longer than the title, the container adjusts its width based on the text, not the title, so then the text appears wider than the title. How do I keep the width based on the title, not the text? I've included my code below as well as a badly drawn image to better understand what happens.

HTML and CSS:

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pContent {
  display: inline-block;
  margin-bottom: 10px;
}

.pInfo {
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="projects">
  <h2>My Projects:</h2>
  <div class="pContent">
    <h3 id="p1" class="pTitle">Project Title</h3>
    <div id="p1Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolor</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
  <br>
  <div class="pContent">
    <h3 id="p2" class="pTitle">Another Project Title</h3>
    <div id="p2Info" class="pInfo">
      <p class="desc">This is a project</p>
      <p class="demo">View.</p>
    </div>
  </div>
</div></code>```

Here's an image of what I want and what actually happens.

答:
I hope this should resolve your query :

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pTitle {
  width: 100%;
  display: flex;
  justify-content: center;
}

.p1Info {
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="projects">
  <h2>My Projects:</h2>
  <div class="pContent">
    <h3 id="p1" class="pTitle">Project Titdsdasdsads asdsa asd asd asdsa dasdsad sdsad sadsaa sadsa asdsadsa asdsadasdsale</h3>
    <div id="p1Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolorhis is a project description Loremhis is a project description Lorem</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
  <br>
  <div class="pContent">
    <h3 id="p2" class="pTitle">Another Project Title</h3>
    <div id="p2Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolor</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
</div></code>```

Body:
I have some centered divs that have a title and text below the title. The title is centered but the text is aligned on the left and starts from where the title starts. I used inline-block to make the div adjust in size based on the content. However, if the text is longer than the title, the container adjusts its width based on the text, not the title, so then the text appears wider than the title. How do I keep the width based on the title, not the text? I've included my code below as well as a badly drawn image to better understand what happens.

HTML and CSS:

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pContent {
  display: inline-block;
  margin-bottom: 10px;
}

.pInfo {
  text-align: left;
}

My Projects:

Project Title

This is a project description Lorem Ipsum Dolor

View a demo of the project.

Another Project Title

This is a project

View.

Here's an image of what I want and what actually happens.

Body:
I hope this should resolve your query :

.projects {
  width: 30vw;
  left: 10vw;
  right: 10vw;
  margin: 50px auto 0 auto;
  text-align: center;
}

.pTitle {
  width: 100%;
  display: flex;
  justify-content: center;
}

.p1Info {
  width: 100%;
}

<div class="projects">
  <h2>My Projects:</h2>
  <div class="pContent">
    <h3 id="p1" class="pTitle">Project Titdsdasdsads asdsa asd asd asdsa dasdsad sdsad sadsaa sadsa asdsadsa asdsadasdsale</h3>
    <div id="p1Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolorhis is a project description Loremhis is a project description Lorem</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
  <br>
  <div class="pContent">
    <h3 id="p2" class="pTitle">Another Project Title</h3>
    <div id="p2Info" class="pInfo">
      <p class="desc">This is a project description Lorem Ipsum Dolor</p>
      <p class="demo">View a demo of the project.</p>
    </div>
  </div>
</div>


问:
Change icons based on asc and dsc and retain other column icons to default asc icon which is not active using angular8
i have dynamically binded the icons for sorting the columns, here if i click on other column for sorting previous column icon remains in the state which i had clicked for, but i want that icon to be in default state except the currently sorted column, and here to sort for the new column i want, it must be clicked 2 times to get it the way i want to sort and the current sorted must be highlighted. I have done upto this and struck. Please help

DEMO:
DEMO

TS:

```<code> public sortAgentList(param) {
      this.sorting = (this.sorting === 'asc') ? 'desc' : 'asc';

      // Change the arrow direction
      this.agentListDetails = this.agentListDetails.map(agentListDetail =>
        agentListDetail.param === param ? {
          ...agentListDetail, icon:
            [...agentListDetail.icon.split(' ').filter(i => i !== 'fa-sort' && i !== 'fa-sort-up' && i !== 'fa-sort-down'),
            this.sorting === 'asc' ? 'fa-sort-up' : 'fa-sort-down'].join(' ')
        } : agentListDetail
      );
     this.getMethod()
  }
</code>```

答: I have set icon style for each detail in a foreach loop: https://stackblitz.com/edit/angular-ebcwwd</p>

Body:
i have dynamically binded the icons for sorting the columns, here if i click on other column for sorting previous column icon remains in the state which i had clicked for, but i want that icon to be in default state except the currently sorted column, and here to sort for the new column i want, it must be clicked 2 times to get it the way i want to sort and the current sorted must be highlighted. I have done upto this and struck. Please help

DEMO:
DEMO

TS:

 public sortAgentList(param) {
      this.sorting = (this.sorting === 'asc') ? 'desc' : 'asc';

      // Change the arrow direction
      this.agentListDetails = this.agentListDetails.map(agentListDetail =>
        agentListDetail.param === param ? {
          ...agentListDetail, icon:
            [...agentListDetail.icon.split(' ').filter(i => i !== 'fa-sort' && i !== 'fa-sort-up' && i !== 'fa-sort-down'),
            this.sorting === 'asc' ? 'fa-sort-up' : 'fa-sort-down'].join(' ')
        } : agentListDetail
      );
     this.getMethod()
  }


问:
How can I get the 3rd Friday of a month in Python?
I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this:

```<code>def get_third_fris(how_many):
    # code and stuff
    return list_of_fris
</code>```

So that calling get_third_fris(6) will return a 6-item-long list of 3rd Fridays following the current date. The dates need to be Unix timestamps.

(I have pretty much no experience with time or datetime, so please explain what your code is doing.)

Thanks!

答:
Assuming you use pandas:</p>

```<code>def exp_friday(df):
mask = np.where((df.index.day > 14) &
                (df.index.day < 22) &
                (df.index.dayofweek == 4), True, False)
return df[mask]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to get stock data from Yahoo! Finance using Python 2.7.9, but I only need data for the 3rd Friday of the month. I have a function to get the data, but need a way to get the dates. I want something like this:

def get_third_fris(how_many):
    # code and stuff
    return list_of_fris

So that calling get_third_fris(6) will return a 6-item-long list of 3rd Fridays following the current date. The dates need to be Unix timestamps.

(I have pretty much no experience with time or datetime, so please explain what your code is doing.)

Thanks!

Body:
Assuming you use pandas:

def exp_friday(df):
mask = np.where((df.index.day > 14) &
                (df.index.day < 22) &
                (df.index.dayofweek == 4), True, False)
return df[mask]


问:
How can i take python self class attributes in class's method?
I started with Python's classes and I want to do something like that:

```<code>class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)

second = First()
second.func()
</code>```

But i can't access self.value of the class. Can anybody help me?

答:
IIUC then your class should look like the following:</p>

```<code>class First:
    value = 1

    @classmethod
    def func(cls):
        print(cls.value)
</code>```

Body:
I started with Python's classes and I want to do something like that:

class First:
    def __init__(self):
        self.value = 1

    @classmethod
    def func(cls):
        print(self.value)

second = First()
second.func()

But i can't access self.value of the class. Can anybody help me?

Body:
IIUC then your class should look like the following:

class First:
    value = 1

    @classmethod
    def func(cls):
        print(cls.value)


问:
Open a directory and sort files by date created
I need to open directories and sort the files by the time they were created. I can find some discussion, using tags for Perl, sorting, and files, on sorting files based on date of modification. I assume this is a more common need than sorting by date of creation. I use Perl. There is some previous postings on sorting by creation date in other languages other than Perl, such as php or java.

For example, I need to do the following:

```<code>opendir(DIR, $ARGV[0]);
my @files = "sort-by-date-created" (readdir(DIR));
closedir(DIR);

do things with @files...
</code>```

The CPAN has a page on the sort command, but it's not very accessible to me, and I don't find the words "date" or "creation" on the page.

In response to an edit, I should say I use Mac, OS 10.7. I know that in the Finder, there is a sort by creation date option, so there must be some kind of indication for date of creation somehow attached to files in this system.

In response to an answer, here is another version of the script that attempts to sort the files:

```<code>#!/usr/bin/perl
use strict; use warnings;

use File::stat; # helps with sorting files by ctime, the inode date that hopefully can serve as creation date

my $usage = "usage: enter name of directory to be scanned for SNP containing lines\n";
die $usage unless @ARGV == 1;

opendir(DIR, $ARGV[0]);                             #open directory for getting file list
#my @files = (readdir(DIR));
my @file_list = grep ! /^\./, readdir DIR;
closedir(DIR);

print scalar @file_list."\n";

for my $file (sort {
        my $a_stat = stat($a);
        my $b_stat = stat($b);
        $a_stat->mtime <=> $b_stat->mtime;
    }  @file_list ) {
    say "$file";
}
</code>```

答:
Mojo::File brings some interesting and readable ways to do it.

```<code>#!/usr/bin/env perl
use Mojo::File 'path';

my $files_list = path( '/whatever/dir/path/' )->list;

# Returns an array of Mojo::File
my @files = sort { $a->stat->ctime <=> $b->stat->ctime }
  map { $_ }  $files_list->each;

# Returns an array of paths sorted by modification date (if needed)
my @paths = map { $_->realpath->to_string } @files;
</code>```

Body:
I need to open directories and sort the files by the time they were created. I can find some discussion, using tags for Perl, sorting, and files, on sorting files based on date of modification. I assume this is a more common need than sorting by date of creation. I use Perl. There is some previous postings on sorting by creation date in other languages other than Perl, such as php or java.

For example, I need to do the following:

opendir(DIR, $ARGV[0]);
my @files = "sort-by-date-created" (readdir(DIR));
closedir(DIR);

do things with @files...

The CPAN has a page on the sort command, but it's not very accessible to me, and I don't find the words "date" or "creation" on the page.

In response to an edit, I should say I use Mac, OS 10.7. I know that in the Finder, there is a sort by creation date option, so there must be some kind of indication for date of creation somehow attached to files in this system.

In response to an answer, here is another version of the script that attempts to sort the files:

#!/usr/bin/perl
use strict; use warnings;

use File::stat; # helps with sorting files by ctime, the inode date that hopefully can serve as creation date

my $usage = "usage: enter name of directory to be scanned for SNP containing lines\n";
die $usage unless @ARGV == 1;

opendir(DIR, $ARGV[0]);                             #open directory for getting file list
#my @files = (readdir(DIR));
my @file_list = grep ! /^\./, readdir DIR;
closedir(DIR);

print scalar @file_list."\n";

for my $file (sort {
        my $a_stat = stat($a);
        my $b_stat = stat($b);
        $a_stat->mtime <=> $b_stat->mtime;
    }  @file_list ) {
    say "$file";
}

Body:
Mojo::File brings some interesting and readable ways to do it.

#!/usr/bin/env perl
use Mojo::File 'path';

my $files_list = path( '/whatever/dir/path/' )->list;

# Returns an array of Mojo::File
my @files = sort { $a->stat->ctime <=> $b->stat->ctime }
  map { $_ }  $files_list->each;

# Returns an array of paths sorted by modification date (if needed)
my @paths = map { $_->realpath->to_string } @files;


问:
Using recursive type alias in generic results in error
TypeScript v3.7.5 throws Type instantiation is excessively deep and possibly infinite.(2589) when I'm trying to use recursive type alias in generic function.

```<code>type State = {
    head: {
        title: string;
        description: string;
        metadata: { type: string; value: string }[];
    };
    body: {
        title: string;
    };
};

cons...
</code>```

Playground Link

Why does this happen? Is there a way to fix this without providing maximum depth value(iterator)?

答:
Edit:

Please read the issues mentioned by @jcalz in the comment to make sure you have understand implications of the workaround down under.

If you implement your own custom recursive types, it is also a good idea to safely limit the recursion depth with an iteration counter, like @Maciej Sikora proposed (especially if you publish a public library).

Workaround

With recursive types, this error sometimes cannot be avoided. Fortunately, there is a workaround:

```<code>type Paths<Obj> = Obj extends object
    ? {
        [Key in keyof Obj]: Obj[Key] extends infer I ? Prepend<Paths<I>, Key> : never
        // add this         ^                                                       ^
    }[keyof Obj]
    : [];
</code>```

Above infer declaration will defer type evaluation, so the hard instantiation limit counter is not hit. In consequence that will prevent the Type instantiation is excessively deep compile error. Be sure to test the type thoroughly, as you have disabled a compiler safety check with the escape-hatch.

Alternatively, you can optimize Paths type yourself or use a library like ts-toolbelt, that already has one (the author @pirix-gh discovered above trick and uses this mechanism in his library).

Further links

statements about instantiation limit (1, 2)

commit

Playground

Body:
TypeScript v3.7.5 throws Type instantiation is excessively deep and possibly infinite.(2589) when I'm trying to use recursive type alias in generic function.

type State = {
    head: {
        title: string;
        description: string;
        metadata: { type: string; value: string }[];
    };
    body: {
        title: string;
    };
};

cons...

<a href="https://www.typescriptlang.org/play/#code/C4TwDgpgBAysCGxoF4oG8CwAoKuoAsJ4ATALnWzyqmAEtgAbCcgZ2ACdaA7AcwG5K1XMQgsAxpzB0A9l1Ydu-QUIC2EBMUTxyaGuGZQ2nXnygA3eAwCuBo4qgBfANoBdATjwP3VAEbTiIDrK1HSMtgomwV7Y0VjYYrJshghI5HCIKBQeuIQkQdkh9EzkAOShTCUANMFUIuKSMnJQJXUStFK0slU1eGoaWuROPUK6oJClYOwQDNIkVeaWNqXSYCWO1QVCuKP6E1Mzc5UL1gYlK2sOG1tQLleed7h+AfnX5adPIAAqRRDdBZcxdzYMbQAAKU0gXGIAB5PlYwEwjgBpCAgAB8UFQcIR0AgAA8kFCWFApiRZAwQFB4FwQK5ggB+KAACiZuTIUBRICOADpefB2DwWORsUwAJSYjHUkDi-GE4jEpm87n8wXkbgAMwg7CgAFVxchJTThlBGTrjeQuBAzFrgharVqgVgQVBQYh8CxoQB5HwAKwxqG9PqgsogRKg0l9EDEwAZWWuuCcnKg3CgAGtUdJ1VBAy5yOCIJCYa7gO6vb7E6iXGjkai0d5qM50yBM9nfS5bVBXI7nZ7QZiXW6PekkHXsPFEsBksYeLR1ZTULD+2gHGimWA3XnB7C0aL5NOJXG8FNgFZ2FwoOuS9yfdJuEyStySqLTAB6F9a9jSdiAsdYOy8WcQGhYcIFXJwSjZeYyh+EoXGfIA" rel="nofollow noreferrer">Playground Link

Why does this happen? Is there a way to fix this without providing maximum depth value(iterator)?

Body:
Edit:

Please read the issues mentioned by @jcalz in the comment to make sure you have understand implications of the workaround down under.

If you implement your own custom recursive types, it is also a good idea to safely limit the recursion depth with an iteration counter, like @Maciej Sikora proposed (especially if you publish a public library).

Workaround

With recursive types, this error sometimes cannot be avoided. Fortunately, there is a workaround:

type Paths<Obj> = Obj extends object
    ? {
        [Key in keyof Obj]: Obj[Key] extends infer I ? Prepend<Paths<I>, Key> : never
        // add this         ^                                                       ^
    }[keyof Obj]
    : [];

Above infer declaration will defer type evaluation, so the hard instantiation limit counter is not hit. In consequence that will prevent the Type instantiation is excessively deep compile error. Be sure to test the type thoroughly, as you have disabled a compiler safety check with the escape-hatch.

Alternatively, you can optimize Paths type yourself or use a library like ts-toolbelt, that already has one (the author @pirix-gh discovered above trick and uses this mechanism in his library).

Further links

statements about instantiation limit (1, 2)

commit

<a href="https://www.typescriptlang.org/play/?ssl=36&ssc=10&pln=32&pc=1#code/C4TwDgpgBAysCGxoF4oG8CwAoKuoAsJ4ATALnWzyqmAEtgAbCcgZ2ACdaA7AcwG5K1XMQgsAxpzB0A9l1Ydu-QUIC2EBMUTxyaGuGZQ2nXnygA3eAwCuBo4qgBfANoBdATjwP3VAEbTiIDrK1HSMtgomwV7Y0VjYYrJshghI5HCIKBQeuIQkQdkh9EzkAOShTCUANMFUIuKSMnJQJXUStFK0slU1eGoaWuROPUK6oJClYOwQDNIkVeaWNqXSYCWO1QVCuKP6E1Mzc5UL1gYlK2sOG1tQLleed7h+AfnX5adPIAAqRRDdBZcxdzYMbQAAKU0gXGIAB5PlYwEwjgBpCAgAB8UFQcIR0AgAA8kFCWFApiRZAwQFB4FwQK5ggB+KAACiZuTIUBRICOADpefB2DwWORsUwAJSYjHUkDi-GE4jEpm87n8wXkbgAMwg7CgAFVxchJTSGbrguQuBAzFrTVBzZb2ECsCCoKDEPgWNCAPI+ABWGNQXu9UFlECJUGkPogYmAxswmzwTk5UG4UAA1qjpOqoAGXOQAwnUS4gwSQ-Kk1xNdqAJJQRngiCQmEu4Bu6GVtHI1EYs0Wq3-JxpkAZrM+lzW1wOp0e0GY52u93pJBoh0JLhJOy8WjqymoWEztAONFMsCu8hNlufNGi+TGHgSrJUKbAKzsLhQY-N7ne6TcJklbklUVTAAeiArV2GkdhAWwbB1x4TcQGhBcIEPJwSjZeYyh+EoXEAoA" rel="nofollow noreferrer">Playground


问:
Click event doesn't execute on <object> tag
I have an <object> within an anchor tag which has an Angular click event attached to it like this:

```<code><a (click)="myAction()">
  <object data="/images/icon.svg"></object>
</a>
</code>```

When I click directly on the <object> the click event doesn't work, however, when I click on the padding of the anchor tag (or I remove the object and replace it with text or an  icon), the click event does work. What is causing this?

答:
Looks like I can to add a
  <rect>...</rect>
</svg>
```

<pre class="lang-js prettyprint-override"><code>document.addEventListener('message', event => {
  if (event.data === 'questions-click') {
    // Do something...
  }
});
</code>```

This method isn't ideal, but it does work.

Body:
I have an <object> within an anchor tag which has an Angular click event attached to it like this:

  <object data="/images/icon.svg"></object>

When I click directly on the <object> the click event doesn't work, however, when I click on the padding of the anchor tag (or I remove the object and replace it with text or an  icon), the click event does work. What is causing this?

Body:
Looks like I can to add a <script> tag to the svg that sends a postMessage to the parent:

<svg>
  <script>
    let svg = document.querySelector('svg');
    svg.addEventListener('click', () => {
      window.parent.postMessage('questions-click', '*');
    });
  </script>
  <rect>...</rect>
</svg>

document.addEventListener('message', event => {
  if (event.data === 'questions-click') {
    // Do something...
  }
});

This method isn't ideal, but it does work.


问:
Setting font sizes of a seaborn plot
I'm struggling with setting the font sizes of a seaborn plot correctly. Setting the font size of the title works perfectly fine but unfortunately I didn't have any success yet regarding the font sizes of the axes and the legend. This is my code (using some dummy data):

```<code>import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame()
df['First PCA dimension'] = [1,2,3,4]
df['Second PCA dimension'] = [0,5,5,7]
df['Third PCA dimension'] = [1,2,6,4]
df['Data points'] = [1,2,3,4]

plt.figure(figsize=(42,30))
plt.title('2-D PCA of my data points',fontsize=32)

colors = ["#FF9926", "#2ACD37","#FF9926", "#FF0800"]
sns.scatterplot(x="First PCA dimension", y="Second PCA dimension", hue="Data points", palette=sns.color_palette(colors), data=df, legend="full", alpha=0.3)
sns.set_context("paper", rc={"font.size":48,"axes.titlesize":48,"axes.labelsize":48})
plt.savefig(outputPath+'/PCA/'+'PCA_2D.png',dpi=100,bbox_inches='tight')
</code>```

, which results in the following output:

Changing the numbers in the "set_context" function doesn't have any effect.

答:
BTW, the figure size is too big (42x30):

```<code>import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame()
df['First PCA dimension'] = [1,2,3,4]
df['Second PCA dimension'] = [0,5,5,7]
df['Third PCA dimension'] = [1,2,6,4]
df['Data points'] = [1,2,3,4]

plt.figure(figsize=(42,30))
plt.title('2-D PCA of my data points',fontsize=32)

colors = ["#FF9926", "#2ACD37","#FF9926", "#FF0800"]
b = sns.scatterplot(x="First PCA dimension", y="Second PCA dimension", hue="Data points", palette=sns.color_palette(colors), data=df, legend="full", alpha=0.3)
sns.set_context("paper", rc={"font.size":48,"axes.titlesize":48,"axes.labelsize":48})

b.set_ylabel('mylabely', size=54)
b.set_xlabel('mylabelx', size=54)
b.set_xticklabels([1,2,3,4,5,6,7,8], fontsize = 36)

lgnd = plt.legend(fontsize='22')
for handle in lgnd.legendHandles:
    handle.set_sizes([26.0])

plt.show()
</code>```

Title: Setting font sizes of a seaborn plot

Body:
I'm struggling with setting the font sizes of a seaborn plot correctly. Setting the font size of the title works perfectly fine but unfortunately I didn't have any success yet regarding the font sizes of the axes and the legend. This is my code (using some dummy data):

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame()
df['First PCA dimension'] = [1,2,3,4]
df['Second PCA dimension'] = [0,5,5,7]
df['Third PCA dimension'] = [1,2,6,4]
df['Data points'] = [1,2,3,4]

plt.figure(figsize=(42,30))
plt.title('2-D PCA of my data points',fontsize=32)

colors = ["#FF9926", "#2ACD37","#FF9926", "#FF0800"]
sns.scatterplot(x="First PCA dimension", y="Second PCA dimension", hue="Data points", palette=sns.color_palette(colors), data=df, legend="full", alpha=0.3)
sns.set_context("paper", rc={"font.size":48,"axes.titlesize":48,"axes.labelsize":48})
plt.savefig(outputPath+'/PCA/'+'PCA_2D.png',dpi=100,bbox_inches='tight')

, which results in the following output:

Changing the numbers in the "set_context" function doesn't have any effect.

Body:
BTW, the figure size is too big (42x30):

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

df = pd.DataFrame()
df['First PCA dimension'] = [1,2,3,4]
df['Second PCA dimension'] = [0,5,5,7]
df['Third PCA dimension'] = [1,2,6,4]
df['Data points'] = [1,2,3,4]

plt.figure(figsize=(42,30))
plt.title('2-D PCA of my data points',fontsize=32)

colors = ["#FF9926", "#2ACD37","#FF9926", "#FF0800"]
b = sns.scatterplot(x="First PCA dimension", y="Second PCA dimension", hue="Data points", palette=sns.color_palette(colors), data=df, legend="full", alpha=0.3)
sns.set_context("paper", rc={"font.size":48,"axes.titlesize":48,"axes.labelsize":48})

b.set_ylabel('mylabely', size=54)
b.set_xlabel('mylabelx', size=54)
b.set_xticklabels([1,2,3,4,5,6,7,8], fontsize = 36)

lgnd = plt.legend(fontsize='22')
for handle in lgnd.legendHandles:
    handle.set_sizes([26.0])

plt.show()


答:
Is @classmothod necessary?

If it is eliminated, the class works well.

```<code>class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)

second = First()
second.func()
</code>```

Title: How can i take python self class attributes in class's method?

Body:
Is @classmothod necessary?

If it is eliminated, the class works well.

class First:
    def __init__(self):
        self.value = 1

    def func(self):
        print(self.value)

second = First()
second.func()


问:
How to partially apply `RegExp.test` to a string?
Why doesn't this work:

```<code>var func = /o/.test;
func("hello");
// VM165:1 Uncaught TypeError: Method RegExp.prototype.test called on incompatible receiver undefined
//     at test (<anonymous>)
//     at <anonymous>:1:1
// (anonymous) @ VM165:1
</code>```

But this does:

```<code>/o/.test("hello");
// true
</code>```

答:
EDIT

Use call or bind Method.

```<code>// Call Approach
    var func = /o/.test;
    func.call(/o/, "hello")

//Bind Approach
    var func = /o/.test.bind(/o/);
    func("hello");
</code>```

Body:
Why doesn't this work:

var func = /o/.test;
func("hello");
// VM165:1 Uncaught TypeError: Method RegExp.prototype.test called on incompatible receiver undefined
//     at test (<anonymous>)
//     at <anonymous>:1:1
// (anonymous) @ VM165:1

But this does:

/o/.test("hello");
// true

Body:
EDIT

Use call or bind Method.

// Call Approach
    var func = /o/.test;
    func.call(/o/, "hello")

//Bind Approach
    var func = /o/.test.bind(/o/);
    func("hello");


问:
The AppBarDesign can't be assigned to the parameter type 'PreferredSizeWidget'
Anyone please give some information why this is happening?

When I try to add a class AppBarDesign which implements appBar flutter is giving the below error.

error: The argument type 'AppBarDesign' can't be assigned to the parameter type 'PreferredSizeWidget'. (argument_type_not_assignable at [flutterbyrajath] lib\main.dart:27)

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

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

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Rajath\'s design ',
          debugShowCheckedModeBanner: false,
          theme: new ThemeData(primarySwatch: Colors.amber),
          home: new MyHomePage(key, 'App is Fun'),
        );
      }
    }

    class MyHomePage extends StatelessWidget {
      MyHomePage(Key key, this.title) : super(key: key);

      final title;

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBarDesign(key, title),
        );
      }
    }

    class AppBarDesign extends StatelessWidget {
      AppBarDesign(Key key, this.title) : super(key: key);

      final title;

      @override
      Widget build(BuildContext context) {
        return new AppBar(
          title: new Text(title),
        );
      }
    }
</code>```

答:
You can also use following way to design your appbar in separate file and then use it in your whole app.

```<code>Widget Custom_Appbar(){
  return AppBar(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(20))),
        title: Text(
          'Decimal to Binary & Vice Versa',
          style: TextStyle(fontWeight: FontWeight.w400, fontSize: 19),
        ));
}
</code>```

And then use it like this

```<code>return Scaffold(
      appBar: Custom_Appbar(),
)
</code>```

Body:
Anyone please give some information why this is happening?

When I try to add a class AppBarDesign which implements appBar flutter is giving the below error.

error: The argument type 'AppBarDesign' can't be assigned to the parameter type 'PreferredSizeWidget'. (argument_type_not_assignable at [flutterbyrajath] lib\main.dart:27)

    import 'package:flutter/material.dart';

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

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Rajath\'s design ',
          debugShowCheckedModeBanner: false,
          theme: new ThemeData(primarySwatch: Colors.amber),
          home: new MyHomePage(key, 'App is Fun'),
        );
      }
    }

    class MyHomePage extends StatelessWidget {
      MyHomePage(Key key, this.title) : super(key: key);

      final title;

      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBarDesign(key, title),
        );
      }
    }

    class AppBarDesign extends StatelessWidget {
      AppBarDesign(Key key, this.title) : super(key: key);

      final title;

      @override
      Widget build(BuildContext context) {
        return new AppBar(
          title: new Text(title),
        );
      }
    }

Body:
You can also use following way to design your appbar in separate file and then use it in your whole app.

Widget Custom_Appbar(){
  return AppBar(
        shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.vertical(bottom: Radius.circular(20))),
        title: Text(
          'Decimal to Binary & Vice Versa',
          style: TextStyle(fontWeight: FontWeight.w400, fontSize: 19),
        ));
}

And then use it like this

return Scaffold(
      appBar: Custom_Appbar(),
)


答:
When you take a method from an Object and assign it to a variable, you need to supply a binding for this because the context( the Object ) is not passed along with the method.

var func = /o/.test.bind(/o/);
console.log( func("hello") );```

Title: How to partially apply `RegExp.test` to a string?


问:
how do you fix this while loop?
EDIT: i have another problem but it won't let me post again

the code is this:

```<code>print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')
choice = int(input())

while choice > 6:
  if choice == 1:
    contestants = ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"]
  elif choice == 2:
    contestants = ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"]
  elif choice == 3:
    contestants = ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"]
  elif choice == 4:
    contestants = ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"]
  elif choice == 5:
    contestants = ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"]
  elif choice == 6:
    contestants = ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
  else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())
</code>```

the section that doesn't work is this:

```<code>else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())
</code>```

the loop keeps going on and on no mater what i enter (unless i enter anything other than an integer where it'll show an error message). how do i stop this when i enter an integer between 1 and 6?

答:
EDIT: As I see you added more code. You are checking if your choice is greater than 6, then compare to values less than 6. You never hit that while loop.

No need to loop through the indexes. Loop through the list directly.

```<code>for x in contestants:
    print(x)
    time.sleep(0.5)
</code>```

Title: how do you fix this while loop?

Body:
EDIT: i have another problem but it won't let me post again

the code is this:

print('''Which group of queens do you want to compete against?
1. Winners
2. Runner-ups
3. Lip sync assassins
4. Miss Congenialities
5. First Eliminated
6. Returning queens''')
choice = int(input())

while choice > 6:
  if choice == 1:
    contestants = ["BeBe Zahara Benet", "Tyra Sanchez", "Raja", "Sharon Needles", "Jinkx Monsoon", "Bianca Del Rio", "Violet Chachki", "Bob the Drag Queen", "Sasha Velour", "Aquaria", "Yvie Oddly", "Chad Michaels", "Alaska", "Trixie Mattel", "Trinity the Tuck", "Monét X Change"]
  elif choice == 2:
    contestants = ["Nina Flowers", "Raven", "Manila Luzon", "Chad Micheals", "Alaska", "Courtney Act", "Ginger Minj", "Kim Chi", "Peppermint", "Eureka", "Brooke Lynn Hytes", "Katya", "Kennedy Davenport", "Monique Heart"]
  elif choice == 3:
    contestants = ["Akashia", "Jujubee", "Alexis Mateo", "Latrice Royale", "Coco Montrese", "Trinity K. Bonet", "Kennedy Davenport", "Chi Chi DeVayne", "Peppermint", "Kameron Michaels", "Ra'Jah O'Hara", "Raven", "Alaska", "BenDeLaCreme", "Trinity the Tuck"]
  elif choice == 4:
    contestants = ["Nina Flowers", "Pandora Boxx", "Yara Sofia", "Latrice Royale", "Ivy Winters", "BenDeLaCreme", "Katya", "Cynthia Lee Fontaine", "Valentina", "Monét X Change", "Nina West"]
  elif choice == 5:
    contestants = ["Victoria Parker", "Shangela", "Venus D-Lite", "Alisa Summers", "Penny Tration", "Kelly Mantle", "Tempest DuJour", "Laila McQueen", "Jaymes Mansfield", "Vanessa Vanjie Mateo", "Soju", "Mimi Imfurst", "Coco Montrese", "Thorgy Thor", "Jasmine Masters"]
  elif choice == 6:
    contestants = ["Carmen Carrera", "Shangela", "Kenya Michaels", "Trixie Mattel", "Naysha Lopez", "Cynthia Lee Fontaine", "Eureka", "Vanessa Vanjie Mateo", "Alyssa Edwards", "Tatianna", "Morgan McMichaels", "Latrice Royale", "Manila Luzon"]
  else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())

the section that doesn't work is this:

else:
    while choice > 6 or choice < 1:
        print("Please choose one of the 6 groups")
        choice = int(input())

the loop keeps going on and on no mater what i enter (unless i enter anything other than an integer where it'll show an error message). how do i stop this when i enter an integer between 1 and 6?

Body:
EDIT: As I see you added more code. You are checking if your choice is greater than 6, then compare to values less than 6. You never hit that while loop.

No need to loop through the indexes. Loop through the list directly.

for x in contestants:
    print(x)
    time.sleep(0.5)


问:
Error generating QR code in ASP.net + Report viewer with QrCoder
I am trying to generate a report with Qr codes I am using this video as a guide
https://www.youtube.com/watch?v=BW99WK6SQKI
I did tests before and it worked and then it stopped working and it just shows me that error nothing more.

I am working with ASP.net MVC + Report Viewer

I looked for the error in the forums and I can't find a solution...

```<code>Error while loading code module: ‘QRCoder, Version=1.3.6.0, Culture=neutral, PublicKeyToken=null’. Details: Could not load file or assembly 'QRCoder, Version=1.3.6.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. C:\DevOps\Project\Report\Qr.rdlc
</code>```

IDE

IMAGEN PROPERTIES

**REPORT PROPERTIES

答:
PublicKeyToken value should not be null. You need to get the PublicKeyToken from QrCoder dll and use it.

To find the Public key token.

Open visual studio developer command prompt.

Run sn -Tp <AssemblyName>

 e.g. sn -Tp c:\libraries\QRCoder.dll

Use Public key value in PublicKeyToken=<Value>

Body:
I am trying to generate a report with Qr codes I am using this video as a guide
https://www.youtube.com/watch?v=BW99WK6SQKI
I did tests before and it worked and then it stopped working and it just shows me that error nothing more.

I am working with ASP.net MVC + Report Viewer

I looked for the error in the forums and I can't find a solution...

Error while loading code module: ‘QRCoder, Version=1.3.6.0, Culture=neutral, PublicKeyToken=null’. Details: Could not load file or assembly 'QRCoder, Version=1.3.6.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified. C:\DevOps\Project\Report\Qr.rdlc

IDE

IMAGEN PROPERTIES

**REPORT PROPERTIES


问:
Is there any way to use configMaps in K8s with nested values to be used as environment variable in the pod?
I have the sample cm.yml for configMap with nested json like data.

```<code>kind: ConfigMap
metadata:
 name: sample-cm
data:
 spring: |-
  rabbitmq: |-
   host: "sample.com"
  datasource: |-
   url: "jdbc:postgresql:sampleDb"
</code>```

I have to set environment variables, spring-rabbitmq-host=sample.com and spring-datasource-url= jdbc:postgresql:sampleDb in the following pod.

```<code>kind: Pod
metadata:
 name: pod-sample
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
     - name: sping-rabbitmq-host
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>
     - name: spring-datasource-url
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>
</code>```

答:
Unfortunately it won't be possible to pass values from the configmap you created as separate environment variables because it is read as a single string.

You can check it using kubectl describe cm sample-cm

```<code>Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"spring":"rabbitmq: |-\n host: \"sample.com\"\ndatasource: |-\n url: \"jdbc:postgresql:sampleDb\""},"kind":"Con...

Data
====
spring:
----
rabbitmq: |-
 host: "sample.com"
datasource: |-
 url: "jdbc:postgresql:sampleDb"
Events:  <none>
</code>```

ConfigMap needs key-value pairs so you have to modify it to represent separate values.

Simplest approach would be:

```<code>apiVersion: v1
kind: ConfigMap
metadata:
 name: sample-cm
data:
   host: "sample.com"
   url: "jdbc:postgresql:sampleDb"
</code>```

so the values will look like this:

```<code>kubectl describe cm sample-cm
Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"host":"sample.com","url":"jdbc:postgresql:sampleDb"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"s...

Data
====
host:
----
sample.com
url:
----
jdbc:postgresql:sampleDb
Events:  <none>
</code>```

and pass it to a pod:

```<code>apiVersion: v1
kind: Pod
metadata:
 name: pod
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
    - name: sping-rabbitmq-host
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: host
    - name: spring-datasource-url
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: url
</code>```

Body:
I have the sample cm.yml for configMap with nested json like data.

kind: ConfigMap
metadata:
 name: sample-cm
data:
 spring: |-
  rabbitmq: |-
   host: "sample.com"
  datasource: |-
   url: "jdbc:postgresql:sampleDb"

I have to set environment variables, spring-rabbitmq-host=sample.com and spring-datasource-url= jdbc:postgresql:sampleDb in the following pod.

kind: Pod
metadata:
 name: pod-sample
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
     - name: sping-rabbitmq-host
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>
     - name: spring-datasource-url
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>

Body:
Unfortunately it won't be possible to pass values from the configmap you created as separate environment variables because it is read as a single string.

You can check it using kubectl describe cm sample-cm

Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"spring":"rabbitmq: |-\n host: \"sample.com\"\ndatasource: |-\n url: \"jdbc:postgresql:sampleDb\""},"kind":"Con...

Data
====
spring:
----
rabbitmq: |-
 host: "sample.com"
datasource: |-
 url: "jdbc:postgresql:sampleDb"
Events:  <none>

ConfigMap needs key-value pairs so you have to modify it to represent separate values.

Simplest approach would be:

apiVersion: v1
kind: ConfigMap
metadata:
 name: sample-cm
data:
   host: "sample.com"
   url: "jdbc:postgresql:sampleDb"

so the values will look like this:

kubectl describe cm sample-cm
Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"host":"sample.com","url":"jdbc:postgresql:sampleDb"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"s...

Data
====
host:
----
sample.com
url:
----
jdbc:postgresql:sampleDb
Events:  <none>

and pass it to a pod:

apiVersion: v1
kind: Pod
metadata:
 name: pod
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
    - name: sping-rabbitmq-host
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: host
    - name: spring-datasource-url
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: url


问:
XLL is "not a valid add-in" compilation with Platform Toolset Visual Studio 2019
An XLL add-in for Excel was developed in C++ (by someone else) some time ago (originally late 1990s, with some modifications in 2013).  While I can compile the addin with no reported errors using VS2019 and the Platform Toolset "vs142" (associated with VS2019), when the xll is added to Excel with the Add-In Manager, Excel complains that "...xll is not a valid add-in."  If I revise the project, in VS2019, solely such that the configuration property Platform Toolset is "vs100 (Visual Studio 10)" then the add-in compiles and can be registered as a correctly working add-in in Excel.

The main difference I see in the list of warnings after the solution is rebuilt with Platform Toolset vs142 (there are no errors) is that everywhere there is a directive in the code "#pragma EXPORT" there is a warning
"expected 'string'; found 'user-defined string literal'.
this is not a warning when the solution is rebuilt using Toolset vs100.

The EXPORT is defined in the project as follows (boilerplate following some example in the Dalton book about C/C++ and financial add-ins for Excel, I think.)

```<code>// to the world without having to maintain a .def file. Look in any exported
// function for how to use it.
#define EXPORT comment(linker, "/EXPORT:"__FUNCTION__"="__FUNCDNAME__)
</code>```

I'm not really sure where to begin to reconcile this difference due to the Platform Toolset (and version of C++?)  To maintain this project going forward I would like to be able to use the latest versions of VS and the latest toolset, so help in understanding what and why modifications must be made would be greatly appreciated.

答:
This warning/error appears to be related to the different ways various versions of the MSVC compiler's pre-processor handle string-literal concatenations in #pragma comment() lines (see note below). By adding spaces between the (quoted) literals and the __FUNCxxx__ macros, the warning disappears (and this would most likely fix the linker issue causing the "not a valid add-in" problem).

Assuming the 'problem' appeared in the VS-2015 release, one can get round this using the following code:

#if (_MSC_VER >= 1900) // This is for VS-2015 - see link below for others versions
#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
#else
#define EXPORT comment(linker, "/EXPORT:"__FUNCTION__"="__FUNCDNAME__)
#endif
```

<p>You <em>may</em> be able to use the 'space-added' version with earlier compilers but, I've added the conditional following the philosophy, "If it ain't broke, don't fix it!"</p>

<p>Values of the <code>_MSC_VER</code> macro to use for other versions are listed here.</p>

<p>NOTE: The example given on this Microsoft web-page includes spaces between string literals and pre-defined macros:</p>

<blockquote>
  <p>For comments that take a comment-string parameter, you can use a macro
  in any place where you would use a string literal, provided that the
  macro expands to a string literal. You can also concatenate any
  combination of string literals and macros that expand to string
  literals. For example, the following statement is acceptable:</p>

```    #pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )
```

Body:
An XLL add-in for Excel was developed in C++ (by someone else) some time ago (originally late 1990s, with some modifications in 2013).  While I can compile the addin with no reported errors using VS2019 and the Platform Toolset "vs142" (associated with VS2019), when the xll is added to Excel with the Add-In Manager, Excel complains that "...xll is not a valid add-in."  If I revise the project, in VS2019, solely such that the configuration property Platform Toolset is "vs100 (Visual Studio 10)" then the add-in compiles and can be registered as a correctly working add-in in Excel.

The main difference I see in the list of warnings after the solution is rebuilt with Platform Toolset vs142 (there are no errors) is that everywhere there is a directive in the code "#pragma EXPORT" there is a warning
"expected 'string'; found 'user-defined string literal'.
this is not a warning when the solution is rebuilt using Toolset vs100.

The EXPORT is defined in the project as follows (boilerplate following some example in the Dalton book about C/C++ and financial add-ins for Excel, I think.)

// to the world without having to maintain a .def file. Look in any exported
// function for how to use it.
#define EXPORT comment(linker, "/EXPORT:"__FUNCTION__"="__FUNCDNAME__)

I'm not really sure where to begin to reconcile this difference due to the Platform Toolset (and version of C++?)  To maintain this project going forward I would like to be able to use the latest versions of VS and the latest toolset, so help in understanding what and why modifications must be made would be greatly appreciated.

Body:
This warning/error appears to be related to the different ways various versions of the MSVC compiler's pre-processor handle string-literal concatenations in #pragma comment() lines (see note below). By adding spaces between the (quoted) literals and the __FUNCxxx__ macros, the warning disappears (and this would most likely fix the linker issue causing the "not a valid add-in" problem).

Assuming the 'problem' appeared in the VS-2015 release, one can get round this using the following code:

#if (_MSC_VER >= 1900) // This is for VS-2015 - see link below for others versions
#define EXPORT comment(linker, "/EXPORT:" __FUNCTION__ "=" __FUNCDNAME__)
#else
#define EXPORT comment(linker, "/EXPORT:"__FUNCTION__"="__FUNCDNAME__)
#endif

You may be able to use the 'space-added' version with earlier compilers but, I've added the conditional following the philosophy, "If it ain't broke, don't fix it!"

Values of the _MSC_VER macro to use for other versions are listed here.

NOTE: The example given on this Microsoft web-page includes spaces between string literals and pre-defined macros:

For comments that take a comment-string parameter, you can use a macro
  in any place where you would use a string literal, provided that the
  macro expands to a string literal. You can also concatenate any
  combination of string literals and macros that expand to string
  literals. For example, the following statement is acceptable:

    #pragma comment( user, "Compiled on " __DATE__ " at " __TIME__ )


问:
Generate unique ascending numerical id in django model field
```<code>Class Car(models.Model):
     type = models.CharField('Type', max_length=100)
     code = models.CharField('Code', max_length=10, blank=True, null=True)
</code>```

Considering I want to make a list of cars depending on their types. I have a model and fields like the above code,
I want to make the code uniquely increment based on the type of the car. For instance, if an instance of a car was created with type field as 'HD', then the code would be 'HD-0000001'. The next model created with the type HD as well would be HD-0000002, so on, so forth. If another type is given, it will save as 'type' + 'the last saved number + 1'.

I know I have to do something in the save() function, but I can't figure out how to make it unique based on different types.

Any suggestions will be truly appreciated.
Thank you!

答:
maybe you could write your class as follows:

```<code>Class Car(models.Model):
    type = models.CharField('Type', max_length=100)
    code = models.IntegerField('Code', default=-1)

    def save(self, *args, **kw):
        if self.code == -1:
            max_code=Car.objects.filter(type=self.type).aggregate(max_code=Max('code'))
            self.code = max_code.get('max_code',0)+1 if max_code else 1
        return super(Car, self).save(*args, **kw)

    class Meta:
        unique_together = ('type', 'code')
</code>```

So, you should never save the attribute code, because before first save the object get the last code number for it's type and set self 'code' with de next value.

Body:
Class Car(models.Model):
     type = models.CharField('Type', max_length=100)
     code = models.CharField('Code', max_length=10, blank=True, null=True)

Considering I want to make a list of cars depending on their types. I have a model and fields like the above code,
I want to make the code uniquely increment based on the type of the car. For instance, if an instance of a car was created with type field as 'HD', then the code would be 'HD-0000001'. The next model created with the type HD as well would be HD-0000002, so on, so forth. If another type is given, it will save as 'type' + 'the last saved number + 1'.

I know I have to do something in the save() function, but I can't figure out how to make it unique based on different types.

Any suggestions will be truly appreciated.
Thank you!

Body:
maybe you could write your class as follows:

Class Car(models.Model):
    type = models.CharField('Type', max_length=100)
    code = models.IntegerField('Code', default=-1)

    def save(self, *args, **kw):
        if self.code == -1:
            max_code=Car.objects.filter(type=self.type).aggregate(max_code=Max('code'))
            self.code = max_code.get('max_code',0)+1 if max_code else 1
        return super(Car, self).save(*args, **kw)

    class Meta:
        unique_together = ('type', 'code')

So, you should never save the attribute code, because before first save the object get the last code number for it's type and set self 'code' with de next value.


问:
Splitting a string that is converted to a list with a single item into multiple items
I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.

Here's my code:

```<code>string = "ABCDEFG"
x = string.split()
print(x)
</code>```

Thank you for your time!:D

答:
Use the for loop :

```<code># Driver code
string = "ABCDEFG"
print(split([char for char in string]))
</code>```

Or the list:

```<code>string = "ABCDEFG"
print(list(string))
</code>```

Body:
I have a string that is converted to a list using the split() function, and I want to split my single item into multiple items each containing one character.

Here's my code:

string = "ABCDEFG"
x = string.split()
print(x)

Thank you for your time!:D

Body:
Use the for loop :

# Driver code
string = "ABCDEFG"
print(split([char for char in string]))

Or the list:

string = "ABCDEFG"
print(list(string))


问:
Mutable str class extension
I've written the following extension of the class str (built-in) in order to do the following operation: Suppose I have the string "Ciao", by doing "Ciao" - "a" I want as a result the string "Cio". Here it is the code that do this and it works fine:

```<code>class my_str(str):
   def __sub__(self, other):
       p = list(other)
       l = ""
       for el in self:
           if (el in p) == False:
               l += el

       return my_str(l)

if __name__ == "__main__":
    s = my_str("Ciao")
    p = my_str("a")
    t = s - p
    print(t) # 'Cio'
    print(s) # 'Ciao'
</code>```

Now, suppose that I'd like the function __sub__ to directly update the object s, in such a way that when I type print(s) after having execute s - p the output would be "Cio". How do I have to modify the class my_str?

答:
You can use

```<code>from collections import UserString
class Test(UserString):
    def __add__(self, other):
        self.data = self.data + other
</code>```

The UserString class is meant for subclassing the built-in string, and gives you the actual content as a self.data field.

Title: Mutable str class extension

Body:
I've written the following extension of the class str (built-in) in order to do the following operation: Suppose I have the string "Ciao", by doing "Ciao" - "a" I want as a result the string "Cio". Here it is the code that do this and it works fine:

class my_str(str):
   def __sub__(self, other):
       p = list(other)
       l = ""
       for el in self:
           if (el in p) == False:
               l += el

       return my_str(l)

if __name__ == "__main__":
    s = my_str("Ciao")
    p = my_str("a")
    t = s - p
    print(t) # 'Cio'
    print(s) # 'Ciao'

Now, suppose that I'd like the function __sub__ to directly update the object s, in such a way that when I type print(s) after having execute s - p the output would be "Cio". How do I have to modify the class my_str?

Body:
You can use

from collections import UserString
class Test(UserString):
    def __add__(self, other):
        self.data = self.data + other

The UserString class is meant for subclassing the built-in string, and gives you the actual content as a self.data field.


问:
What is the advantage/point of using Interfaces in Java?
I'm very new into Java and I've reached the chapter in my textbook that talks about interfaces. However, I am failing to see their use/point. I'm sure that they're not useless though and that it's just me not understanding the subject.

So, interfaces are like abstract classes and they only name methods, not their implementations. The first example provided in the book talks about having a class Shape, an extended class rectangle and the idea is to allow for a method to stretch the rectangle by its biggest side. So the code starts:

```<code>public interface Stretchable {
    void stretch( double factor );
{
</code>```

Then they describe the "point" of using it

```<code>public class Rectangle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      if( factor <0 )
      throw new IllegalArgumentException();

      if( length > width )
          length *= factor;
      else
          width*= factor;
   }
}
</code>```

However, I fail to see what did I win there, by defining and implementing an interface. the interface was just void stretch( double factor); and I still had to define the same thing in the Rectangle class. What is the advantage in doing this, when I still have to define from scratch what the method of the interface is going to do in the class it's being implemented on?

答:
Because you define a common behavior for all classes, that can be stretched (Stretchable). Say you have a Circle:

```<code>public class Circle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      this.radius = this.radius * factor;
   }
}
</code>```

Now if you can have a collection of all the things, that can be stretched, because there is a common interface:

```<code>List<Stretchable> stretchables = List.of(new Circle(1), new Rectangle(1, 2));
</code>```

Since they are all Stretchable, you can invoke the method on all of the objects:

```<code>stretchables.forEach(stretchable -> stretchable.stretch(2));
</code>```

Body:
I'm very new into Java and I've reached the chapter in my textbook that talks about interfaces. However, I am failing to see their use/point. I'm sure that they're not useless though and that it's just me not understanding the subject.

So, interfaces are like abstract classes and they only name methods, not their implementations. The first example provided in the book talks about having a class Shape, an extended class rectangle and the idea is to allow for a method to stretch the rectangle by its biggest side. So the code starts:

public interface Stretchable {
    void stretch( double factor );
{

Then they describe the "point" of using it

public class Rectangle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      if( factor <0 )
      throw new IllegalArgumentException();

      if( length > width )
          length *= factor;
      else
          width*= factor;
   }
}

However, I fail to see what did I win there, by defining and implementing an interface. the interface was just void stretch( double factor); and I still had to define the same thing in the Rectangle class. What is the advantage in doing this, when I still have to define from scratch what the method of the interface is going to do in the class it's being implemented on?

Body:
Because you define a common behavior for all classes, that can be stretched (Stretchable). Say you have a Circle:

public class Circle extends Shape implements Stretchable
{
   public void stretch( double factor )
   {
      this.radius = this.radius * factor;
   }
}

Now if you can have a collection of all the things, that can be stretched, because there is a common interface:

List<Stretchable> stretchables = List.of(new Circle(1), new Rectangle(1, 2));

Since they are all Stretchable, you can invoke the method on all of the objects:

stretchables.forEach(stretchable -> stretchable.stretch(2));


问:
Golang run on Windows without deal with the Firewall
I'm working on a Rest API with Go, but everytime I try to run my application with

```<code>go run main.go
</code>```

the Windows Firewall tells me that has blocked some features of my app. I would like to know if there's some way to make my executions without have to Accept everytime.

答:
I think @apxp's answer is the complete explanation of the situation; some time after ask this question I found a way to run my application with:</p>

```<code>go build -o ejecutable.exe ; if($?)  { .\ejecutable.exe }
</code>```

Body:
I'm working on a Rest API with Go, but everytime I try to run my application with

go run main.go

the Windows Firewall tells me that has blocked some features of my app. I would like to know if there's some way to make my executions without have to Accept everytime.

Body:
I think @apxp's answer is the complete explanation of the situation; some time after ask this question I found a way to run my application with:

go build -o ejecutable.exe ; if($?)  { .\ejecutable.exe }


问:
How to use something like Try-Catch inside CUDA device code
Is there a way to execute a statement inside the device code without raising CUDA error?
Something looks like the following:

```<code>__global__ void myKernel(float* X1, float* X2, float* Y){
try{
    Y[0] = X1[0] / X2[0];
   }catch(){
    Y[0] = 0.0f;
    }
}
</code>```

I know that we can check the value of X2[0] before division, but what If I want to execute the statement without checking for valid inputs, and execute it safely?

答:
currently, CUDA device code does not support exception handling.

try/catch cannot be used in CUDA device code.

If a statement would cause a device side error (e.g. out-of-bounds access, for example), there is no way to execute that statement in device code without triggering the device side error.

To avoid the error, you would need to modify the statement, or conditionally not execute it, to avoid triggering the device side error.

Body:
Is there a way to execute a statement inside the device code without raising CUDA error?
Something looks like the following:

__global__ void myKernel(float* X1, float* X2, float* Y){
try{
    Y[0] = X1[0] / X2[0];
   }catch(){
    Y[0] = 0.0f;
    }
}

I know that we can check the value of X2[0] before division, but what If I want to execute the statement without checking for valid inputs, and execute it safely?


问:
git p4 sync operation failure
I am using "git-p4" script for migration from p4 to GIT. clone operation is failing due to large number of change list (about 5 million). So I am trying to perform incremental import operation:
I tried to clone for first run then sync operation. I tested with small changes list.

First run:

```<code>git p4 clone //depot/f1/f2/f3/ere@17888479,17918050 -v
</code>```

Second run:

```<code>git p4 sync //depot/f1/f2/f3/ere@17918051,17918064 -v
</code>```

Error:

```<code>Traceback (most recent call last):
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3677, in <module>
    main()
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3671, in main
    if not cmd.run(args):
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3429, in run
    die("fast-import failed: %s" % self.gitError.read())
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 122, in die
    raise Exception(msg)
Exception: fast-import failed: warning: Not updating refs/remotes/p4/master (new tip 85c94d84335bb1441a7f959b384729b2a4d633f4 does not contain 3222bdc29799d1fe5fff91c36524481b1469f1d9)
</code>```

答:
There is a similar case described recently during a git-fast-import process

With Git 2.26 (Q1 2020), git-p4 should be more robust around that edge-case.

See commit 43f33e4 (30 Jan 2020), and commit 19fa5ac, commit 6026aff, commit ca5b5cc, commit 4c1d586, commit 5c3d502, commit 837b3a6 (29 Jan 2020) by Luke Diamand (ldiamand42).

(Merged by Junio C Hamano -- gitster -- in commit 4a77434, 14 Feb 2020)

git-p4: cleanup better on error exit

Signed-off-by: Luke Diamand

After an error, git-p4 calls die(). This just exits, and leaves child processes still running.

Instead of calling die(), raise an exception and catch it where the child process(es) (git-fastimport) are created.

This change does not address the particular issue of p4CmdList() invoking a subchild and not waiting for it on error.

Title: git p4 sync operation failure

Body:
I am using "git-p4" script for migration from p4 to GIT. clone operation is failing due to large number of change list (about 5 million). So I am trying to perform incremental import operation:
I tried to clone for first run then sync operation. I tested with small changes list.

First run:

git p4 clone //depot/f1/f2/f3/ere@17888479,17918050 -v

Second run:

git p4 sync //depot/f1/f2/f3/ere@17918051,17918064 -v

Error:

Traceback (most recent call last):
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3677, in <module>
    main()
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3671, in main
    if not cmd.run(args):
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 3429, in run
    die("fast-import failed: %s" % self.gitError.read())
  File "C:\Program Files\Git\mingw64/libexec/git-core\git-p4", line 122, in die
    raise Exception(msg)
Exception: fast-import failed: warning: Not updating refs/remotes/p4/master (new tip 85c94d84335bb1441a7f959b384729b2a4d633f4 does not contain 3222bdc29799d1fe5fff91c36524481b1469f1d9)


问:
How to proxy a HTTP video stream to any amount of clients through a Spring Webserver
Provided that I have a video HTTP stream broadcasted on a server that is on the same network as my Spring Webserver is, for instance in some url such as:

http://localhost:9090/httpstream

How can I proxy this video stream to any amount of clients, using Spring?
The following example demonstrates the wanted flow:

Spring webserver can be found at http://localhost:9091/spring

A client wants to access a video stream, so he connects his video-stream-player to http://localhost:9091/spring (the spring webserver)

The Spring WebServer should redirect the stream found on http://localhost:9090/httpstream to the client, with the latter never knowing that he accessed the httpstream host. The connection is made by Spring, not by the client

This is needed because the HTTPStream is an unsecured and not authenticated host, and I wanted to wrap it around a Spring Webserver, so that I could use some form of Security, such as a Basic Auth.

I tried requesting some form of mapping, but I couldn't find what kind of object to return, nor how to make the connection, but the expected behaviour should be something like this:

```<code>@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring") {
    public /*Stream Object?*/ getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

       return   //What should be returned?
       }
   }
}
</code>```

答:
I struggled with this same problem for days, attempting to migrate my node app to Spring/React. I'm using a raspberry pi running Motion, which acts as a remote stream server that I was previously able to use the node module mjpeg-proxy to easily proxy the way OP wishes. This thread was the most useful set of examples in my search to do this in Java, however none of the examples quite worked for me. I'm hoping my controller class and component will help others attempting the same.

Please take note of response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString"); as the boundary=BoundaryString portion was the last critical piece. I opened the chrome debugger while connecting directly to the stream and this was in the response headers -- when I copied it, suddenly everything worked!

```<code>
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.net.URI;

@RestController
@RequestMapping(value = "/video")
public class VideoController {

    Logger log = LoggerFactory.getLogger(VideoController.class);

    @RequestMapping("/oculus")
    public void oculus(HttpServletResponse response) {
        log.info("Calling /video/oculus...");
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.execute(
                URI.create("http://oculus:8081"),
                HttpMethod.GET,
                (ClientHttpRequest request) -> {},
                responseExtractor -> {
                    response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString");
                    IOUtils.copy(responseExtractor.getBody(), response.getOutputStream());
                    return null;
                }
        );
    }

    @RequestMapping("/door")
    public void door(HttpServletResponse response) {
        log.info("Calling /video/door...");

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.execute(
                URI.create("http://vox:9002"),
                HttpMethod.GET,
                clientHttpRequest -> {
                    clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic blahblahBase64encodedUserAndPass=");
                },
                responseExtractor -> {
                    response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString");
                    IOUtils.copy(responseExtractor.getBody(), response.getOutputStream());
                    return null;
                }
        );
    }

}
</code>```

I have included examples for using Motion's basic auth, as well as an unprotected stream.

Both streams are then available on my app using the following bit of react js

```<code>
class Video extends React.Component{
    render() {
        return (
            <div className="Content">
                <p>
                    <img className="stream" src="/video/oculus"/>
                </p>
                <p>
                    <img className="stream" src="/video/door"/>
                </p>
            </div>
        );
    }
}

export default Video;```
```

Body:
Provided that I have a video HTTP stream broadcasted on a server that is on the same network as my Spring Webserver is, for instance in some url such as:

http://localhost:9090/httpstream

How can I proxy this video stream to any amount of clients, using Spring?
The following example demonstrates the wanted flow:

Spring webserver can be found at http://localhost:9091/spring

A client wants to access a video stream, so he connects his video-stream-player to http://localhost:9091/spring (the spring webserver)

The Spring WebServer should redirect the stream found on http://localhost:9090/httpstream to the client, with the latter never knowing that he accessed the httpstream host. The connection is made by Spring, not by the client

This is needed because the HTTPStream is an unsecured and not authenticated host, and I wanted to wrap it around a Spring Webserver, so that I could use some form of Security, such as a Basic Auth.

I tried requesting some form of mapping, but I couldn't find what kind of object to return, nor how to make the connection, but the expected behaviour should be something like this:

@Controller
public class HttpStreamProxyController {

    @RequestMapping("/spring") {
    public /*Stream Object?*/ getSecuredHttpStream() {
       if (clientIsSecured) {
       //... Security information

       return   //What should be returned?
       }
   }
}

Body:
I struggled with this same problem for days, attempting to migrate my node app to Spring/React. I'm using a raspberry pi running Motion, which acts as a remote stream server that I was previously able to use the node module mjpeg-proxy to easily proxy the way OP wishes. This thread was the most useful set of examples in my search to do this in Java, however none of the examples quite worked for me. I'm hoping my controller class and component will help others attempting the same.

Please take note of response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString"); as the boundary=BoundaryString portion was the last critical piece. I opened the chrome debugger while connecting directly to the stream and this was in the response headers -- when I copied it, suddenly everything worked!

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.net.URI;

@RestController
@RequestMapping(value = "/video")
public class VideoController {

    Logger log = LoggerFactory.getLogger(VideoController.class);

    @RequestMapping("/oculus")
    public void oculus(HttpServletResponse response) {
        log.info("Calling /video/oculus...");
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.execute(
                URI.create("http://oculus:8081"),
                HttpMethod.GET,
                (ClientHttpRequest request) -> {},
                responseExtractor -> {
                    response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString");
                    IOUtils.copy(responseExtractor.getBody(), response.getOutputStream());
                    return null;
                }
        );
    }

    @RequestMapping("/door")
    public void door(HttpServletResponse response) {
        log.info("Calling /video/door...");

        RestTemplate restTemplate = new RestTemplate();
        restTemplate.execute(
                URI.create("http://vox:9002"),
                HttpMethod.GET,
                clientHttpRequest -> {
                    clientHttpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, "Basic blahblahBase64encodedUserAndPass=");
                },
                responseExtractor -> {
                    response.setContentType("multipart/x-mixed-replace; boundary=BoundaryString");
                    IOUtils.copy(responseExtractor.getBody(), response.getOutputStream());
                    return null;
                }
        );
    }

}

I have included examples for using Motion's basic auth, as well as an unprotected stream.

Both streams are then available on my app using the following bit of react js

class Video extends React.Component{
    render() {
        return (
            <div className="Content">
                <p>
                    <img className="stream" src="/video/oculus"/>
                </p>
                <p>
                    <img className="stream" src="/video/door"/>
                </p>
            </div>
        );
    }
}

export default Video;```


问:
How to access current_user with devise-token_authenticatable gem?
I’m working on a small project that is using devise and devise-token_authenticatable in a Rails/GraphQL/Apollo/React setup. Project is setup using webpacker, so the front and back ends are both served from the same domain. Sign-in, register, log-out are all handle by the front end (React). I also need to point out this is not an API only app.

It seems, server is not setting the current_user or the proper cookie and I’m getting a network error.

Heroku logs shows the following error:

```<code>NoMethodError (undefined method `authentication_token' for #<User:0x000055ca6c0e4c50>)
</code>```

Is that mean it’s trying ‘authentication_token’ method on a nil class?

At the same time it’s showing this error in the console:

```<code>Network error: Unexpected token < in JSON at position 0 (I have no idea what this is)
</code>```

In my login component’s sign-in mutation, I’m storing the authentication_token of the user in local storage after a successful login and in my Apollo setup I’m retrieving it from storage and attaching it to each request. But Chrome dev tool’s network tab shows I’m not getting the cookie set by devise after a signin in the response header. I’m pretty new to all of this so not sure this is the problem or something else. PS: I’m not using Devise sessions since sign-in is handle in the from end. I have devise_for: users, skip: :sessions in my routes.

Code snippets:

Apollo Provide

Component UserInfo

SignIn mutation

Any assistance is greatly appreciated. Thank you in advance for your help.

UPDATE: issue was fixed: (also see my answer below for additional info)

Issue was fixed by adding current_user private method in application_controller.rb.

Here's the code...

```<code>def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end
</code>```

答:
Marko Kacanski was right I should have elaborate on my findings & how I fixed it. :-(

I was wrong to assume that the current_user is automatically sent by the gem devise-token_authenticatable when it detects a authentication_token in the header. At least the way I have setup my project, I wasn't getting the current_user as expected, instead I get a nil object.

So... I created a current_user private method in application_controller.rb and, it fixed the issue.

Here's the code...

```<code>def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end
</code>```

Body:
I’m working on a small project that is using devise and devise-token_authenticatable in a Rails/GraphQL/Apollo/React setup. Project is setup using webpacker, so the front and back ends are both served from the same domain. Sign-in, register, log-out are all handle by the front end (React). I also need to point out this is not an API only app.

It seems, server is not setting the current_user or the proper cookie and I’m getting a network error.

Heroku logs shows the following error:

NoMethodError (undefined method `authentication_token' for #<User:0x000055ca6c0e4c50>)

Is that mean it’s trying ‘authentication_token’ method on a nil class?

At the same time it’s showing this error in the console:

Network error: Unexpected token < in JSON at position 0 (I have no idea what this is)

In my login component’s sign-in mutation, I’m storing the authentication_token of the user in local storage after a successful login and in my Apollo setup I’m retrieving it from storage and attaching it to each request. But Chrome dev tool’s network tab shows I’m not getting the cookie set by devise after a signin in the response header. I’m pretty new to all of this so not sure this is the problem or something else. PS: I’m not using Devise sessions since sign-in is handle in the from end. I have devise_for: users, skip: :sessions in my routes.

Code snippets:

Apollo Provide

Component UserInfo

SignIn mutation

Any assistance is greatly appreciated. Thank you in advance for your help.

UPDATE: issue was fixed: (also see my answer below for additional info)

Issue was fixed by adding current_user private method in application_controller.rb.

Here's the code...

def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end

Body:
Marko Kacanski was right I should have elaborate on my findings & how I fixed it. :-(

I was wrong to assume that the current_user is automatically sent by the gem devise-token_authenticatable when it detects a authentication_token in the header. At least the way I have setup my project, I wasn't getting the current_user as expected, instead I get a nil object.

So... I created a current_user private method in application_controller.rb and, it fixed the issue.

Here's the code...

def current_user
 token = request.headers["Authorization"].to_s
 User.find_for_database_authentication(authentication_token: token)
end


问:
Why do I have to return Unit.INSTANCE in a void kotlin function, when called from Java, and not NULL?
When having a function, for example:

```<code>fun doSomething(action:() -> Unit) {
   action.invoke()
}
</code>```

if I call this from Java the code needs to be:

```<code>doSomething(() -> {
   //do something
   return Unit.INSTANCE
})
</code>```

I have seen code instead using

```<code>doSomething(() -> {
   //do something
   return null
})
</code>```

Does it affect sending null instead of Unit.INSTANCE? Do Kotlin perform more things by validating that UNIT instance is returned instead?

答:
Any method in Kotlin returns a value. "void" methods always return the one instance of the type Unit which is Unit.INSTANCE. You can obmit the return type unit in the declaration but implicitly it is added and the value is returned at the end of the method.
https://kotlinlang.org/docs/reference/basic-syntax.html

So when calling the Kotlin method from Java code, you need to fullfill the same contract and return something. If you return null is is a null reference to the type Unit. Just because it is better, to avoid null references, in case a caller would like to act on the result of your method, you should avoid returning null and return Unit.INSTANCE instead. Yes, this case is unlikely, but will cause the most annoying error.

Body:
When having a function, for example:

fun doSomething(action:() -> Unit) {
   action.invoke()
}

if I call this from Java the code needs to be:

doSomething(() -> {
   //do something
   return Unit.INSTANCE
})

I have seen code instead using

doSomething(() -> {
   //do something
   return null
})

Does it affect sending null instead of Unit.INSTANCE? Do Kotlin perform more things by validating that UNIT instance is returned instead?


问:
error: no matching function for call to 'getline'
```<code>#include<iostream>
#include<string>
using namespace std;
int main(){
    //initializing two string

     string s2,s1="hello";

     cout<<s2<<s1;

     cout<<endl;
     //transferring(copying) data from s1 to s2
       getline(s1,s2);

     cout<<s2<<s1;
}
</code>```

答:
The error is caused by the fact that there is no getline that would accept two strings as parameters.

To "transfer" or copy data from s1 to s2 you write

```<code>s2 = s1;
</code>```

It is unclear why you think you need getline. The method getline is for different purpose about which you can read eg here.

Body:
The error is caused by the fact that there is no getline that would accept two strings as parameters.

To "transfer" or copy data from s1 to s2 you write

s2 = s1;

It is unclear why you think you need getline. The method getline is for different purpose about which you can read eg here.


问:
Creating a long running branch
Problem: "Updates were rejected because the tip of your current branch is behind its remote counterpart" error while trying to push a (potentially long-running) bugfix/maintenance branch.

Setup: The development is done on the master branch. A commit, which is behind the master's HEAD by a number of commits, is tagged with dev-0.2 tag. I want to create a new (potentially long-running) branch (say, dev-0.2-bugfix) based on dev-0.2 tag and use the new dev-0.2-bugfix branch to track changes related to the dev-0.2 release.

What I did:

```<code>$ git checkout -b dev-0.2-bugfix dev-0.2
Switched to a new branch 'dev-0.2-bugfix

$ ..make changes to dev-0.2-bugfix files

$ ..commit changes to local dev-0.2-bugfix branch and now let's try to push it to remote

$ git push origin dev-0.2-bugfix
To file:////var/lib/git/Test.git
 ! [rejected]        dev-0.2-bugfix -> dev-0.2-bugfix (non-fast-forward)
error: failed to push some refs to 'file:////var/lib/git/Test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

$ git push origin dev-0.2-bugfix:dev-0.2-bugfix
To file:////var/lib/git/Test.git
 ! [rejected]        dev-0.2-bugfix -> dev-0.2-bugfix (non-fast-forward)
error: failed to push some refs to 'file:////var/lib/git/Test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
</code>```

Any ideas how to resolve this? I want dev-0.2-bugfix to be created on the remote, currently dev-0.2-bugfix does not exits on the remote. I don't want to bring the latest changes from master as they were committed after the dev-0.2 tag had been created and are not a part of dev-0.2 release.

Thanks

Update: Tried forcing the push, it kind of worked (see below) but still did not create dev-0.2-bugfix on the remote:

```<code>$ git push -f origin dev-0.2-bugfix:dev-0.2-bugfix
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 2 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 419 bytes | 419.00 KiB/s, done.
Total 4 (delta 2), reused 0 (delta 0)
To file:////var/lib/git/Test.git
 + 337a471...0dd7573 dev-0.2-bugfix -> dev-0.2-bugfix (forced update)

 $ git branch -a
* dev-0.2-bugfix
  master
  remotes/origin/HEAD
  remotes/origin/master
</code>```

答: The problem was that dev-0.2-bugfix branch was created on the remote but did not show in git branch -r or git branch -a and that was causing the confusion. See Remote branch is not showing up in "git branch -r" for more info. Thanks to everyone who responded.

Title: Creating a long running branch

Body:
Problem: "Updates were rejected because the tip of your current branch is behind its remote counterpart" error while trying to push a (potentially long-running) bugfix/maintenance branch.

Setup: The development is done on the master branch. A commit, which is behind the master's HEAD by a number of commits, is tagged with dev-0.2 tag. I want to create a new (potentially long-running) branch (say, dev-0.2-bugfix) based on dev-0.2 tag and use the new dev-0.2-bugfix branch to track changes related to the dev-0.2 release.

What I did:

$ git checkout -b dev-0.2-bugfix dev-0.2
Switched to a new branch 'dev-0.2-bugfix

$ ..make changes to dev-0.2-bugfix files

$ ..commit changes to local dev-0.2-bugfix branch and now let's try to push it to remote

$ git push origin dev-0.2-bugfix
To file:////var/lib/git/Test.git
 ! [rejected]        dev-0.2-bugfix -> dev-0.2-bugfix (non-fast-forward)
error: failed to push some refs to 'file:////var/lib/git/Test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

$ git push origin dev-0.2-bugfix:dev-0.2-bugfix
To file:////var/lib/git/Test.git
 ! [rejected]        dev-0.2-bugfix -> dev-0.2-bugfix (non-fast-forward)
error: failed to push some refs to 'file:////var/lib/git/Test.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Any ideas how to resolve this? I want dev-0.2-bugfix to be created on the remote, currently dev-0.2-bugfix does not exits on the remote. I don't want to bring the latest changes from master as they were committed after the dev-0.2 tag had been created and are not a part of dev-0.2 release.

Thanks

Update: Tried forcing the push, it kind of worked (see below) but still did not create dev-0.2-bugfix on the remote:

$ git push -f origin dev-0.2-bugfix:dev-0.2-bugfix
Enumerating objects: 7, done.
Counting objects: 100% (7/7), done.
Delta compression using up to 2 threads
Compressing objects: 100% (4/4), done.
Writing objects: 100% (4/4), 419 bytes | 419.00 KiB/s, done.
Total 4 (delta 2), reused 0 (delta 0)
To file:////var/lib/git/Test.git
 + 337a471...0dd7573 dev-0.2-bugfix -> dev-0.2-bugfix (forced update)

 $ git branch -a
* dev-0.2-bugfix
  master
  remotes/origin/HEAD
  remotes/origin/master


问:
Swift - Unit testing private variables and methods
I'm trying to test a class but I'm kind of confused as to what to test. Here is the class I want to unit test:

```<code>class CalculatorBrain {

    private var accumulator = 0.0

    func setOperand(operand: Double) {
        accumulator = operand
    }

    var result: Double {
        return accumulator
    }

    private var operations: Dictionary<String, Operation> = [
        "=" : .Equals,

        "π" : .Constant(M_PI),
        "e" : .Constant(M_E),

        "±" : .UnaryOperation({ (op1: Double) -> Double in return -op1 }),
        "√" : .UnaryOperation(sqrt ),
        "cos": .UnaryOperation(cos),

        "+" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 + op2 }),
        "−" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 - op2 }),
        "×" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 * op2 }),
        "÷" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 / op2 })
    ]

    private enum Operation {
        case Constant(Double)
        case UnaryOperation((Double) -> Double)
        case BinaryOperation((Double, Double) -> Double)
        case Equals
    }

    func performOperation(symbol: String) {
        if let operation = operations[symbol] {
            switch operation {
            case .Constant(let value):
                accumulator = value
            case .UnaryOperation(let function):
                accumulator = function(accumulator)
            case .BinaryOperation(let function):
                executePendingBinaryOperation()
                pendingBinaryOperation = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator)
            case .Equals:
                executePendingBinaryOperation()
            }
        }
    }

    private var pendingBinaryOperation: PendingBinaryOperationInfo?

    private struct PendingBinaryOperationInfo {
        var binaryOperation: (Double, Double) -> Double
        var firstOperand: Double
    }

    private func executePendingBinaryOperation() {
        if let pending = pendingBinaryOperation {
            accumulator = pending.binaryOperation(pending.firstOperand, accumulator)
            pendingBinaryOperation = nil
        }
    }
}
</code>```

For the code above, what would be good tests.

Is it worth testing every single operation (+, -, *, /, etc) in the dictionary operations?

Is it worth testing the private methods?

答:
Diego's answer is clever but it is possible to go further.

Go into your project editor and define a new Testing Configuration by duplicating the Debug configuration.

Edit your scheme's Test action so that the build configuration is Testing.

Now edit your test target's build settings to define an additional Active Compilation Conditions value for the Testing configuration, "TESTING".

Now you can say #if TESTING, as distinct from mere DEBUG.

I use this, for example, to declare initializers that only a test can see.

Body:
I'm trying to test a class but I'm kind of confused as to what to test. Here is the class I want to unit test:

class CalculatorBrain {

    private var accumulator = 0.0

    func setOperand(operand: Double) {
        accumulator = operand
    }

    var result: Double {
        return accumulator
    }

    private var operations: Dictionary<String, Operation> = [
        "=" : .Equals,

        "π" : .Constant(M_PI),
        "e" : .Constant(M_E),

        "±" : .UnaryOperation({ (op1: Double) -> Double in return -op1 }),
        "√" : .UnaryOperation(sqrt ),
        "cos": .UnaryOperation(cos),

        "+" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 + op2 }),
        "−" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 - op2 }),
        "×" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 * op2 }),
        "÷" : .BinaryOperation({ (op1: Double, op2: Double) -> Double in return op1 / op2 })
    ]

    private enum Operation {
        case Constant(Double)
        case UnaryOperation((Double) -> Double)
        case BinaryOperation((Double, Double) -> Double)
        case Equals
    }

    func performOperation(symbol: String) {
        if let operation = operations[symbol] {
            switch operation {
            case .Constant(let value):
                accumulator = value
            case .UnaryOperation(let function):
                accumulator = function(accumulator)
            case .BinaryOperation(let function):
                executePendingBinaryOperation()
                pendingBinaryOperation = PendingBinaryOperationInfo(binaryOperation: function, firstOperand: accumulator)
            case .Equals:
                executePendingBinaryOperation()
            }
        }
    }

    private var pendingBinaryOperation: PendingBinaryOperationInfo?

    private struct PendingBinaryOperationInfo {
        var binaryOperation: (Double, Double) -> Double
        var firstOperand: Double
    }

    private func executePendingBinaryOperation() {
        if let pending = pendingBinaryOperation {
            accumulator = pending.binaryOperation(pending.firstOperand, accumulator)
            pendingBinaryOperation = nil
        }
    }
}

For the code above, what would be good tests.

Is it worth testing every single operation (+, -, *, /, etc) in the dictionary operations?

Is it worth testing the private methods?