问:
vim: insert increase numbers on the specified column？
I want to insert increase numbers on the specified column, such as the 8th column, but :r!seq 10 insert on 1st column.
I try

```<code>:set ve=all

8|<C-V>9jA0<ESC>gvlg<C-A>
</code>```

but that's too clumsy.

So，can i use :r!seq 10 on the 8th column if not use visincr plugin? Just like Alt funtcion of notepad++.

答:
Don't see what's wrong with g<C-A>, but as an example of alternative solution:

```<code>:call setreg('', system('seq 10'), 'b2')
</code>```

Then move cursor where you want and press P

With a bit of effort you can develop it into general purpose command/function/mapping by adding support to interactive input(), error checking, auto-computing block width, etc.

Body:
I want to insert increase numbers on the specified column, such as the 8th column, but :r!seq 10 insert on 1st column.
I try

:set ve=all

8|<C-V>9jA0<ESC>gvlg<C-A>

but that's too clumsy.

So，can i use :r!seq 10 on the 8th column if not use visincr plugin? Just like Alt funtcion of notepad++.

Body:
Don't see what's wrong with g<C-A>, but as an example of alternative solution:

:call setreg('', system('seq 10'), 'b2')

Then move cursor where you want and press P

With a bit of effort you can develop it into general purpose command/function/mapping by adding support to interactive input(), error checking, auto-computing block width, etc.


来源: stackexchange

问:
Using httr::GET() on macOS produces certificate error
Trying to access an API with httr on macOS produces a certificate error.

httr::GET("https://unstats.un.org/SDGAPI/v1/sdg/Indicator/List")
#> Error in curl::curl_fetch_memory(url, handle = handle): SSL certificate problem: certificate has expired
```

<p>However, running this on multiple Windows machines is successful, with no additional setup other than installing <code>httr</code> and running the above code (it shouldn't need a certificate). Is it something server-side that is preventing access for some reason or something client-side that I can adjust? I was unable to find anything online about general certificate issues with <code>httr</code> and macOS.</p>

<p>I can successfully access other APIs on this machine using <code>httr</code>, so it leads me to believe this is a server-side issue, but don't have enough experience or knowledge to fully troubleshoot this on my own.</p>

<p>Below is my session info for reference. Thanks for any help you can provide.</p>

<p><strong>Session info:</strong></p>

<pre class="lang-r prettyprint-override"><code>#> R version 4.0.0 (2020-04-24)
#> Platform: x86_64-apple-darwin19.4.0 (64-bit)
#> Running under: macOS Catalina 10.15.4
#>
#> Matrix products: default
#> BLAS/LAPACK: /usr/local/Cellar/openblas/0.3.9/lib/libopenblasp-r0.3.9.dylib
#>
#> locale:
#> [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_1.0.4.6    digest_0.6.25   R6_2.4.1        magrittr_1.5
#>  [5] evaluate_0.14   highr_0.8       httr_1.4.1      rlang_0.4.6
#>  [9] stringi_1.4.6   curl_4.3        rmarkdown_2.1   tools_4.0.0
#> [13] stringr_1.4.0   xfun_0.14       yaml_2.2.1      compiler_4.0.0
#> [17] htmltools_0.4.0 knitr_1.28
</code>```

答:
I have the exact same problem since yesterday. After looking things up, turns out a common root CA certificate expired on 30th May (see this answer). In general, what solved my error is to force Curl (which supports httr functions) to ignore the certificate:

```<code>set_config(config(ssl_verifypeer = FALSE))
options(RCurlOptions = list(ssl_verifypeer = FALSE))
options(rsconnect.check.certificate = FALSE)
</code>```

I knows close to nothing about server issues. But this works for me, so I hope it does for you too!

ContentLicense: CC BY-SA 4.0

Body:
Trying to access an API with httr on macOS produces a certificate error.

httr::GET("https://unstats.un.org/SDGAPI/v1/sdg/Indicator/List")
#> Error in curl::curl_fetch_memory(url, handle = handle): SSL certificate problem: certificate has expired

However, running this on multiple Windows machines is successful, with no additional setup other than installing httr and running the above code (it shouldn't need a certificate). Is it something server-side that is preventing access for some reason or something client-side that I can adjust? I was unable to find anything online about general certificate issues with httr and macOS.

I can successfully access other APIs on this machine using httr, so it leads me to believe this is a server-side issue, but don't have enough experience or knowledge to fully troubleshoot this on my own.

Below is my session info for reference. Thanks for any help you can provide.

Session info:

#> R version 4.0.0 (2020-04-24)
#> Platform: x86_64-apple-darwin19.4.0 (64-bit)
#> Running under: macOS Catalina 10.15.4
#>
#> Matrix products: default
#> BLAS/LAPACK: /usr/local/Cellar/openblas/0.3.9/lib/libopenblasp-r0.3.9.dylib
#>
#> locale:
#> [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8
#>
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base
#>
#> loaded via a namespace (and not attached):
#>  [1] Rcpp_1.0.4.6    digest_0.6.25   R6_2.4.1        magrittr_1.5
#>  [5] evaluate_0.14   highr_0.8       httr_1.4.1      rlang_0.4.6
#>  [9] stringi_1.4.6   curl_4.3        rmarkdown_2.1   tools_4.0.0
#> [13] stringr_1.4.0   xfun_0.14       yaml_2.2.1      compiler_4.0.0
#> [17] htmltools_0.4.0 knitr_1.28

Body:
I have the exact same problem since yesterday. After looking things up, turns out a common root CA certificate expired on 30th May (see this answer). In general, what solved my error is to force Curl (which supports httr functions) to ignore the certificate:

set_config(config(ssl_verifypeer = FALSE))
options(RCurlOptions = list(ssl_verifypeer = FALSE))
options(rsconnect.check.certificate = FALSE)

I knows close to nothing about server issues. But this works for me, so I hope it does for you too!


问:
HTML.TextAreaFor - removing html tags for display only
In an MVC application I have to use @HTML.TextAreaFor to display some text from a database, the trouble is sometimes that text may have HTML tags within it and I can't see a way to remove those for display only.

Is it possible to do this in the view (maybe with CSS?) without having to strip the tags in the controller first?

EDIT

The data coming from the controller contains html tags which I do not want to remove, I just don't want to display them

Normally I would use @HTML.Raw but it has to work in a @HTML.TextAreaFor control.

答:
Sorted this by changing TextAreaFor toTextBoxFor and setting a formatted value.  </p>

<p>@Html.TextBoxFor(x => Model.MyItem,  new { @class = "form-control", @required = "true", Value = Regex.Replace(Model.MyItem, "<.*?>", String.Empty) })</p>

Body:
Sorted this by changing TextAreaFor toTextBoxFor and setting a formatted value.

@Html.TextBoxFor(x => Model.MyItem,  new { @class = "form-control", @required = "true", Value = Regex.Replace(Model.MyItem, "<.*?>", String.Empty) })


问:
Pygame window not opening
I have python 3.8 and pygame installed. I am using Pycharm. On my Windows desktop pc at home, everything works perfectly as intended. However on my mac, when I run my code, the python.app icon starts jumping in my dock indefinitely but no window is opening. There are no errors, and everything else works perfectly fine. Just the window doesn't open.

答: In IDLE make sure you start with pygame.init()

Title: Pygame window not opening


问:
Error in eval(predvars, data, env) : object 'STATE_UT' not found
head(mydata)mydata = Crime
view = (mydata)
str(mydata)
index = sample(2,nrow(mydata),replace = TRUE,prob = c(1,494))
RFM = randomForest (STATE_UT~.,data = Training)I'm new to r programming, this error is shown when creating random forest algo for crime prediction..Can anyone help me out??

ERROR

Error in eval(predvars, data, env) : object 'STATE_UT' not found

答:
Well, the error message is telling you that that there is no column named STATE_UT in Training nor is there a object in the global environment called STATE_UT

```<code>colnames(Training)
</code>```

will tell you what columns are in the Training object and

```<code>ls()
</code>```

will tell you what objects are available in the global environment

Body:
Well, the error message is telling you that that there is no column named STATE_UT in Training nor is there a object in the global environment called STATE_UT

colnames(Training)

will tell you what columns are in the Training object and

ls()

will tell you what objects are available in the global environment


问:
Finding empty directories in Python
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

```<code>dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)
</code>```

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

答:
What if you did checked if the directory exists, and whether there is content in the directory... something like:</p>

```<code>if os.path.isdir(dir) and len(os.listdir(dir)) == 0:
    os.rmdir(dir)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Finding empty directories in Python

Body:
All,

What is the best way to check to see if there is data in a directory before deleting it? I am browsing through a couple pages to find some pics using wget and of course every page does not have an image on it but the directory is still created.

dir = 'Files\\%s' % (directory)
os.mkdir(dir)
cmd = 'wget -r -l1 -nd -np -A.jpg,.png,.gif -P %s %s' %(dir,  i[1])
os.system(cmd)
if not os.path.isdir(dir):
    os.rmdir(dir)

I would like to test to see if a file was dropped in the directory after it was created. If nothing is there...delete it.

Thanks,
Adam

Body:
What if you did checked if the directory exists, and whether there is content in the directory... something like:

if os.path.isdir(dir) and len(os.listdir(dir)) == 0:
    os.rmdir(dir)


问:
How should I handle fetching data from the same route using ngrx effects?
This is simply an architecture question, which I couldn't find the answer to anywhere.

The current scenario is - There is a server that accepts GET requests on one end point. Each request body will have the same structure : requestType (string) and payload (json). The requestType is mapped with a switch case in the backend to essentially just mimic multiple end points.

Now, while creating an Angular/NgRx application that relies on this backend, how should I manage the services? There are about 40 requestTypes, should I make 40 services? Should I create one service that uses httpClient to hit that singular end point and then use a lot of effects to listen to actions and then create the right payload and use the service?

Which approach would be easier to test?

答:
Depends on what the backend returns.

If it returns the same kind of data with different flags you can use one store feature with one action and one effect, the action should have type property.

If it returns different kind of data, for example Users / Companies etc then, unfortunately, you have to create 40 store features, write actions and effects for them. To reduce the boilerplate process you can try to use ngrx/data, I can't call it a very good lib, but in this case it will allow you to specify 40 types and the rest will be done automatically.

Otherwise try to create factory functions and classes.


问:
Whatsapp not working with open graph protocol
I'm working on this website and I'm trying to use the open graph protocol. I've managed to get the thumbnail images and meta-tags for Facebook and Twitter, but it has been impossible to get it done for WhatsApp. I can't get neither the thumbnail image nor the description of the website. I'm working with a small size image, added all op codes as recommended. Can somebody please give me a hand telling what is wrong with my code?

     <meta charset="<?php bloginfo( 'charset' ); ?>"/>
     <meta name="viewport" content="width=device-width, initial-scale=1.0" />
     <link rel="profile" href="http://adanosuna.byethost7.com/wp/"/>

<meta property="og:url" content="http://adanosuna.byethost7.com/wp"/>
<meta property="og:title" content="ADANOSUNA"/>
<meta property="description" content=" ADANOSUNA "/>
<meta property="og:description" content=" ADANOSUNA "/>
<meta property="og:image" content="http://nutriholi.com/wp-content/uploads/2020/05/NutriHoli-Facebook-2.jpg"/>
<meta property="og:image" itemprop="image" content="http://nutriholi.com/wp-content/uploads/2020/05/NutriHoli-Facebook-2.jpg"/>
<meta property="og:image:width" content="299"/>
<meta property="og:image:height" content="200"/>
<meta property="og:site_name" content="ADANOSUNA "/>
<meta content="http://nutriholi.com/wp-content/uploads/2020/05/NutriHoli-Facebook-2.jpg"  property="thumbnail" />
<meta property="og:type" content="website" />
<meta property="og:image:type" content="image/jpeg">

         <link itemprop="thumbnailUrl" href="http://nutriholi.com/wp-content/uploads/2020/05/NutriHoli-Facebook-2.jpg"/>
         <link itemprop="url" href="http://nutriholi.com/wp-content/uploads/2020/05/NutriHoli-  Facebook-2.jpg"/>
         <meta itemprop="width" content="299">
         <meta itemprop="height" content="200">

```

答:
So coming back to my situation, just wanted to tell that I've found a solution. I've installed a SSL Certificate, I used CloudFlare which is free and the installation is really easy, although I had to wait for more than 5 hrs to get it active in my website, I used the flex option and after a while I was able to see the Whatsapp thumbnail image, however, the issue of not showing the preview link image continued on Android phones, so what I did, I went into my code lines on my /header file and put the

```<code><"meta property="og:image" itemprop="image" content="..." />
</code>```

line at the very top of the whole code where I located open graph codes, that solved the issue of not showing my thumbnail image on Android phones, on IOS it worked perfectly.

The only thing I have right now is that Facebook blocked my website, I'm not sure if it was because of the SSL installation since it worked perfectly before I was doing that, I've already sent some messages to the FB staff related to this issue so I hope they will release it very soon.

Hope my comments give a little help to those who are struggling with the same issue.

Best :)

Body:
So coming back to my situation, just wanted to tell that I've found a solution. I've installed a SSL Certificate, I used CloudFlare which is free and the installation is really easy, although I had to wait for more than 5 hrs to get it active in my website, I used the flex option and after a while I was able to see the Whatsapp thumbnail image, however, the issue of not showing the preview link image continued on Android phones, so what I did, I went into my code lines on my /header file and put the

<"meta property="og:image" itemprop="image" content="..." />

line at the very top of the whole code where I located open graph codes, that solved the issue of not showing my thumbnail image on Android phones, on IOS it worked perfectly.

The only thing I have right now is that Facebook blocked my website, I'm not sure if it was because of the SSL installation since it worked perfectly before I was doing that, I've already sent some messages to the FB staff related to this issue so I hope they will release it very soon.

Hope my comments give a little help to those who are struggling with the same issue.

Best :)


问:
Throwing on unwrapping nil optional
Consider the following code:

```<code>enum MyErrorType:ErrorType {
    case BadTimes
}

var mightHaveAValue: String?

do {

    if let value = mightHaveAValue {
        // do stuff with value
    } else {
        throw MyErrorType.BadTimes
    }

    // do stuff with NSFileManager using mightHaveAValue which might throw

} catch {
    // handle error
}
</code>```

...in which I have a large do/try/catch block. In this instance the error handling will be the same, whether mightHaveAValue is empty or something bad happens with NSFileManager later on. So it makes sense to re-use the error handling code.

Is this the cleanest approach going in Swift2, or is there some way I can automatically throw/catch on unwrapping an optional with no value?

答:
Maybe just use an extension like this

extension Optional {

    func throwing() throws -> Wrapped {
        if let wrapped = self {
            return wrapped
        } else {
            throw NSError("Trying to access non existing value")
        }
    }
}
```

Title: Throwing on unwrapping nil optional

Body:
Consider the following code:

enum MyErrorType:ErrorType {
    case BadTimes
}

var mightHaveAValue: String?

do {

    if let value = mightHaveAValue {
        // do stuff with value
    } else {
        throw MyErrorType.BadTimes
    }

    // do stuff with NSFileManager using mightHaveAValue which might throw

} catch {
    // handle error
}

...in which I have a large do/try/catch block. In this instance the error handling will be the same, whether mightHaveAValue is empty or something bad happens with NSFileManager later on. So it makes sense to re-use the error handling code.

Is this the cleanest approach going in Swift2, or is there some way I can automatically throw/catch on unwrapping an optional with no value?


问:
Getting length of video
I am having trouble finding a simple example of how to get the video length of a file programmatically. Many people say, oh use this library/wrapper or whatever, but do not say how. I have downloaded ffmpeg, but have no clue how to actually use it and there does not seem to be any example of how to use it to get the video duration. I see how you can use it to convert videos, but I simply just want to know the duration of a video. All of the other information does not matter.

Is there any way of doing this simply, whether it be in C#, python, java, whatever, that will just return a string that indicates the length of a video file.

Please provide examples if possible. Thanks in advance!

Assume standard file formats, such as wmv, avi, mp4, mpeg. Stuff that has metadata.

答:
Here is an example:</p>

```<code>using DirectShowLib;
using DirectShowLib.DES;
using System.Runtime.InteropServices;

...

var mediaDet = (IMediaDet)new MediaDet();
DsError.ThrowExceptionForHR(mediaDet.put_Filename(FileName));

// find the video stream in the file
int index;
var type = Guid.Empty;
for (index = 0; index < 1000 && type != MediaType.Video; index++)
{
    mediaDet.put_CurrentStream(index);
    mediaDet.get_StreamType(out type);
}

// retrieve some measurements from the video
double frameRate;
mediaDet.get_FrameRate(out frameRate);

var mediaType = new AMMediaType();
mediaDet.get_StreamMediaType(mediaType);
var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
DsUtils.FreeAMMediaType(mediaType);
var width = videoInfo.BmiHeader.Width;
var height = videoInfo.BmiHeader.Height;

double mediaLength;
mediaDet.get_StreamLength(out mediaLength);
var frameCount = (int)(frameRate * mediaLength);
var duration = frameCount / frameRate;
</code>```

Title: Getting length of video

Body:
Here is an example:

using DirectShowLib;
using DirectShowLib.DES;
using System.Runtime.InteropServices;

...

var mediaDet = (IMediaDet)new MediaDet();
DsError.ThrowExceptionForHR(mediaDet.put_Filename(FileName));

// find the video stream in the file
int index;
var type = Guid.Empty;
for (index = 0; index < 1000 && type != MediaType.Video; index++)
{
    mediaDet.put_CurrentStream(index);
    mediaDet.get_StreamType(out type);
}

// retrieve some measurements from the video
double frameRate;
mediaDet.get_FrameRate(out frameRate);

var mediaType = new AMMediaType();
mediaDet.get_StreamMediaType(mediaType);
var videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(mediaType.formatPtr, typeof(VideoInfoHeader));
DsUtils.FreeAMMediaType(mediaType);
var width = videoInfo.BmiHeader.Width;
var height = videoInfo.BmiHeader.Height;

double mediaLength;
mediaDet.get_StreamLength(out mediaLength);
var frameCount = (int)(frameRate * mediaLength);
var duration = frameCount / frameRate;


问:
what's the difference between interface pointer and interface value in golang
when Node is a struct type, it can't compiled.

but when Node is a interface type it's ok.

why?

type Node interface {
}
// test1's parameter are pointer
func test1(b *Node) {
    test2(b)
}
// test2's parameter are not pointer
func test2(c Node) {}
```

答:
Let's look at some variations on the declaration of Node:

Example 1:

```<code>type Node interface {
}
</code>```

The code compiles because all types satisfy the empty interface.

Example 2:

```<code>type Node interface {
   AnyMethod()
}
</code>```

The compiler reports the following error:

cannot use b (type *Node) as type Node in argument to test2: *Node is pointer to interface, not interface

The compilation fails because a *Node does not have the method AnyMethod.

Example 3:

```<code>type Node struct {
}
</code>```

The compiler reports the following error:

cannot use b (type *Node) as type Node in argument to test2

The compilation fails because *Node and Node are different types.

One fix for the compilation error is dereference the pointer:

```<code>func test1(b *Node) {
    test2(*b)
}
</code>```

Body:
Let's look at some variations on the declaration of Node:

Example 1:

type Node interface {
}

The code compiles because all types satisfy the empty interface.

Example 2:

type Node interface {
   AnyMethod()
}

The compiler reports the following error:

cannot use b (type *Node) as type Node in argument to test2: *Node is pointer to interface, not interface

The compilation fails because a *Node does not have the method AnyMethod.

Example 3:

type Node struct {
}

The compiler reports the following error:

cannot use b (type *Node) as type Node in argument to test2

The compilation fails because *Node and Node are different types.

One fix for the compilation error is dereference the pointer:

func test1(b *Node) {
    test2(*b)
}


问:
How to use protected variables in gitlab ci
The documentation on protected variables is pretty obscure. When I make a variable as protected I have to idea how to access it. No matter what I do it is always empty. I have tried base64 encoding it and then base64 encoding it again in the pipeline so I can see what it is and I get an empty string: Cg==. Can someone please explain how to use protected variables?

答:
As @secustor wrote, it is not possible to access protected variables from a branch or tag that is not protected. The variable would be empty if accessed.

From here, two options:

Push to a protected branch or tag (set the branch/tag protected in Settings > Repository)

Mark the variable as not protected (in Settings > CI/CD, under "Variables")

Again, as mentioned by @secustor, there is a good reason behind this logic. You might not want all the developers in your team to be able to access these variables.


问:
Different methods for instantiating an object in C++
What is the difference between this:

```<code>Myclass *object = new Myclass();
</code>```

and

```<code>Myclass object = new Myclass();
</code>```

I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?

答:
Its posible
Myclass name = Myclass();</p>

OwnerDisplayName: RaouL

ContentLicense: CC BY-SA 2.5

Body:
What is the difference between this:

Myclass *object = new Myclass();

and

Myclass object = new Myclass();

I have seen that a lot of C++ libraries like wxWidgets, OGRE etc use the first method... Why?

LastEditorDisplayName: Out Into Space

Body:
Its posible
Myclass name = Myclass();


问:
Paragraph mark of UWP RichEditBox is not resized
With this code (Editor.Document.Selection.CharacterFormat.Size = 20;) I change the font size of a UWP RichEditBox in the Page_Loaded-handle. When I start typing some characters, everything works fine. But when I select the paragraph mark and then type something, this text appears in the wrong font size (10.5).

What I've tried is to expand the selection before setting the font size, but it seems that there is no paragraph mark when there's no text. But when the rich edit box is empty and I press Shift+Right Arrow ⟶ (as I would normally select the paragraph mark), the font size is set back to 10.5.

Is there any workaround to prevent that the font size is set back to 10.5 in any case?

```<code><Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="FontSizeBlock" Grid.Row="0"></TextBlock>
    <RichEditBox x:Name="Editor" Grid.Row="1" SelectionChanged="HandleRichEditBox_SelectionChanged"></RichEditBox>
</Grid>

public sealed partial class MainPage : Page {
    public MainPage() {
        this.InitializeComponent();
        this.Loaded += Page_Loaded;
    }

    private void Page_Loaded(object sender, RoutedEventArgs e) {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }

    private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e) {
        FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    }
}
</code>```

答:
When further investigating my problem, I noted that my issue doesn't occur when there has already been some text in the RichEditBox which was deleted.

Therefore, I have tried to programmatically append, select and remove characters in the Page_Loaded-handle, and this approach worked for me.

```<code>private void Page_Loaded(object sender, RoutedEventArgs e) {
    // set any character
    Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, "a");
    Editor.Document.Selection.Expand(Windows.UI.Text.TextRangeUnit.Paragraph);
    Editor.Document.Selection.CharacterFormat.Size = 20;
    Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, "");

}
</code>```

Body:
With this code (Editor.Document.Selection.CharacterFormat.Size = 20;) I change the font size of a UWP RichEditBox in the Page_Loaded-handle. When I start typing some characters, everything works fine. But when I select the paragraph mark and then type something, this text appears in the wrong font size (10.5).

What I've tried is to expand the selection before setting the font size, but it seems that there is no paragraph mark when there's no text. But when the rich edit box is empty and I press Shift+Right Arrow ⟶ (as I would normally select the paragraph mark), the font size is set back to 10.5.

Is there any workaround to prevent that the font size is set back to 10.5 in any case?

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <TextBlock x:Name="FontSizeBlock" Grid.Row="0"></TextBlock>
    <RichEditBox x:Name="Editor" Grid.Row="1" SelectionChanged="HandleRichEditBox_SelectionChanged"></RichEditBox>
</Grid>

public sealed partial class MainPage : Page {
    public MainPage() {
        this.InitializeComponent();
        this.Loaded += Page_Loaded;
    }

    private void Page_Loaded(object sender, RoutedEventArgs e) {
        Editor.Document.Selection.SetRange(0, 1);
        Editor.Document.Selection.CharacterFormat.Size = 20;
    }

    private void HandleRichEditBox_SelectionChanged(object sender, RoutedEventArgs e) {
        FontSizeBlock.Text = "FontSize: " + Editor.Document.Selection.CharacterFormat.Size;
    }
}

Body:
When further investigating my problem, I noted that my issue doesn't occur when there has already been some text in the RichEditBox which was deleted.

Therefore, I have tried to programmatically append, select and remove characters in the Page_Loaded-handle, and this approach worked for me.

private void Page_Loaded(object sender, RoutedEventArgs e) {
    // set any character
    Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, "a");
    Editor.Document.Selection.Expand(Windows.UI.Text.TextRangeUnit.Paragraph);
    Editor.Document.Selection.CharacterFormat.Size = 20;
    Editor.Document.SetText(Windows.UI.Text.TextSetOptions.None, "");

}


问:
No moduled named google during Kivy to apk with Buildozer
Her my main.py

```<code># -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen,FadeTransition
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
from kivy.core.text import LabelBase
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from kivy.storage.jsonstore import JsonStore

class MainWindow(Screen):
    pass

class SecondWindow(Screen):
    stored_data = ObjectProperty(None)
    def __init__(self,*args,**kwargs):
        super(Screen,self).__init__(*args,**kwargs),
        self.stored_data = JsonStore('data.json')

def gonder(self):
        name = self.ids.name.text

        scope = ["https://spreadsheets.google.com/feeds",
'https://www.googleapis.com/auth/spreadsheets',
                 "https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"]

        creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
        client = gspread.authorize(creds)
        sheet = client.open("verigonder").sheet1
        sheet.append_row([name])

class ThirdWindow(Screen):
    pass
class WindowManager(ScreenManager):
    pass

class mainApp(App):
    def build(self):
        return Builder.load_file("my.kv")

if __name__ == "__main__":
    mainApp().run()
</code>```

and buildozer.spec requirements is here

```<code>requirements = python3,kivy,gspread,oauth2client,google-auth-oauthlib,httplib2,pyasn1,pyasn1-modules,rsa,request,google
</code>```

and log of debug

```<code>06-02 15:25:27.121 25609 25949 I python  :  Traceback (most recent call last):
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/app/main.py", line 8, in <module>
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/__init__.py", line 16, in <module>
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/auth.py", line 12, in <module>
06-02 15:25:27.121 25609 25949 I python  :  ModuleNotFoundError: No module named 'google'
06-02 15:25:27.121 25609 25949 I python  : Python for android ended.
</code>```

it is still giving same error. What I need to do for fix this situation? Its working on laptop, but it doesnt work on android because of this error. I thinks its all about the gspread but where is the problem why is still giving this error ?

答:
TL;DR: Add google-auth to your existing requirements of your buildozer.spec

Long story:

Yes buildozer/p4a can't do automatic package dependency resolution by default yet.

So the way we want to debug this is by finding ourselves which package is missing.
From the stacktrace check this part:

```<code>06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/auth.py", line 12, in <module>
06-02 15:25:27.121 25609 25949 I python  :  ModuleNotFoundError: No module named 'google'
</code>```

And then see for the gspread package and auth module what exactly it's trying to import. Check that from the source code: https://github.com/burnash/gspread/blob/v3.6.0/gspread/auth.py#L12

from google.oauth2.credentials import Credentials
```

<p>So now we need to see on which package the <code>Credentials</code> class is being defined.
There're multiple ways to find that, but since we know it must be a dependency we check the <code>setup.py</code> of that same package.
https://github.com/burnash/gspread/blob/v3.6.0/setup.py#L46-L50</p>

<pre class="lang-py prettyprint-override"><code>    install_requires=[
        'requests>=2.2.1',
        'google-auth>=1.12.0',
        'google-auth-oauthlib>=0.4.1'
    ],
</code>```

Here we see 3 dependencies to look from. We could then search further to see if that class is defined in one of them. But actually there're dependencies we would need no matter what. So we can simply add them to then buildozer.spec and then buildozer android clean and buildozer android debug.
That should be it.

But if we're curious still here's where it's really defined https://github.com/googleapis/google-auth-library-python/blob/v1.16.0/google/oauth2/credentials.py#L50 then checking that project README we see it indeed comes from the google-auth package.

Body:
Her my main.py

# -*- coding: utf-8 -*-
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen,FadeTransition
from kivy.lang import Builder
from kivy.properties import ObjectProperty, StringProperty
from kivy.core.text import LabelBase
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from kivy.storage.jsonstore import JsonStore

class MainWindow(Screen):
    pass

class SecondWindow(Screen):
    stored_data = ObjectProperty(None)
    def __init__(self,*args,**kwargs):
        super(Screen,self).__init__(*args,**kwargs),
        self.stored_data = JsonStore('data.json')

def gonder(self):
        name = self.ids.name.text

        scope = ["https://spreadsheets.google.com/feeds",
'https://www.googleapis.com/auth/spreadsheets',
                 "https://www.googleapis.com/auth/drive.file",
"https://www.googleapis.com/auth/drive"]

        creds = ServiceAccountCredentials.from_json_keyfile_name("creds.json", scope)
        client = gspread.authorize(creds)
        sheet = client.open("verigonder").sheet1
        sheet.append_row([name])

class ThirdWindow(Screen):
    pass
class WindowManager(ScreenManager):
    pass

class mainApp(App):
    def build(self):
        return Builder.load_file("my.kv")

if __name__ == "__main__":
    mainApp().run()

and buildozer.spec requirements is here

requirements = python3,kivy,gspread,oauth2client,google-auth-oauthlib,httplib2,pyasn1,pyasn1-modules,rsa,request,google

and log of debug

06-02 15:25:27.121 25609 25949 I python  :  Traceback (most recent call last):
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/app/main.py", line 8, in <module>
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/__init__.py", line 16, in <module>
06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/auth.py", line 12, in <module>
06-02 15:25:27.121 25609 25949 I python  :  ModuleNotFoundError: No module named 'google'
06-02 15:25:27.121 25609 25949 I python  : Python for android ended.

it is still giving same error. What I need to do for fix this situation? Its working on laptop, but it doesnt work on android because of this error. I thinks its all about the gspread but where is the problem why is still giving this error ?

Body:
TL;DR: Add google-auth to your existing requirements of your buildozer.spec

Long story:

Yes buildozer/p4a can't do automatic package dependency resolution by default yet.

So the way we want to debug this is by finding ourselves which package is missing.
From the stacktrace check this part:

06-02 15:25:27.121 25609 25949 I python  :    File
"/home/ademberkaksoy/sheet/.buildozer/android/platform/build-armeabi-v7a/build/python-
installs/myapp/gspread/auth.py", line 12, in <module>
06-02 15:25:27.121 25609 25949 I python  :  ModuleNotFoundError: No module named 'google'

And then see for the gspread package and auth module what exactly it's trying to import. Check that from the source code: https://github.com/burnash/gspread/blob/v3.6.0/gspread/auth.py#L12

from google.oauth2.credentials import Credentials

So now we need to see on which package the Credentials class is being defined.
There're multiple ways to find that, but since we know it must be a dependency we check the setup.py of that same package.
https://github.com/burnash/gspread/blob/v3.6.0/setup.py#L46-L50

    install_requires=[
        'requests>=2.2.1',
        'google-auth>=1.12.0',
        'google-auth-oauthlib>=0.4.1'
    ],

Here we see 3 dependencies to look from. We could then search further to see if that class is defined in one of them. But actually there're dependencies we would need no matter what. So we can simply add them to then buildozer.spec and then buildozer android clean and buildozer android debug.
That should be it.

But if we're curious still here's where it's really defined https://github.com/googleapis/google-auth-library-python/blob/v1.16.0/google/oauth2/credentials.py#L50 then checking that project README we see it indeed comes from the google-auth package.


问:
How would I keep a map icon in the same position of the map which is a background image? CSS
Map Page

Hi I'm making a map on my website and it needs to have icons on it that can be hovered which means they can't be apart of the actual map image itself.

I'm wondering how I would place the icons on the map and keep them in the same position on the map at different view widths/heights.

This is the CSS for my map background:

```<code>.background {
position:fixed;
padding:0;
margin:0;

top:0;
left:0;

width: 100vw;
height: 100vh;

background: url("../assets/map.png") no-repeat center center fixed;
-webkit-background-size: 100vw 100vh;
-moz-background-size: 100vw 100vh;
-o-background-size: 100vw 100vh;
background-size: 100vw 100vh;
}
</code>```

The map will change size based on the resolution of the screen which makes it tricky for me to keep the icons in the same place through screen changes. Currently I tried using position absolute and putting it in the right place but as you change the screen so does the placement of the icon.

Am I doing it wrong or is there another solution to this? Thanks.

答:
if you wanna position icons on a background then you have to give that background container a position relative and then give the elements inside background container a position absolute

body,
html {
    margin: 0;
    padding: 0;
}

.background {
    position: relative;
    width: 100%;
    min-height: 100vh;
    background-image: url('https://i.stack.imgur.com/KQxKh.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
}

.icon1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon2 {
    position: absolute;
    top: 50px;
    right: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon3 {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 50px;
    height: 50px;
    background-color: #4AC144;
}

.icon4 {
    position: absolute;
    bottom: 50px;
    right: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon5 {
    position: absolute;
    bottom: 50px;
    left: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="background">
    <span class="icon1"></span>
    <span class="icon2"></span>
    <span class="icon3"></span>
    <span class="icon4"></span>
    <span class="icon5"></span>
</div></code>```

Body:
Map Page

Hi I'm making a map on my website and it needs to have icons on it that can be hovered which means they can't be apart of the actual map image itself.

I'm wondering how I would place the icons on the map and keep them in the same position on the map at different view widths/heights.

This is the CSS for my map background:

.background {
position:fixed;
padding:0;
margin:0;

top:0;
left:0;

width: 100vw;
height: 100vh;

background: url("../assets/map.png") no-repeat center center fixed;
-webkit-background-size: 100vw 100vh;
-moz-background-size: 100vw 100vh;
-o-background-size: 100vw 100vh;
background-size: 100vw 100vh;
}

The map will change size based on the resolution of the screen which makes it tricky for me to keep the icons in the same place through screen changes. Currently I tried using position absolute and putting it in the right place but as you change the screen so does the placement of the icon.

Am I doing it wrong or is there another solution to this? Thanks.

Body:
if you wanna position icons on a background then you have to give that background container a position relative and then give the elements inside background container a position absolute

body,
html {
    margin: 0;
    padding: 0;
}

.background {
    position: relative;
    width: 100%;
    min-height: 100vh;
    background-image: url('https://i.stack.imgur.com/KQxKh.jpg');
    background-repeat: no-repeat;
    background-size: cover;
    background-position: center center;
}

.icon1 {
    position: absolute;
    top: 50px;
    left: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon2 {
    position: absolute;
    top: 50px;
    right: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon3 {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    left: 0;
    right: 0;
    margin: 0 auto;
    width: 50px;
    height: 50px;
    background-color: #4AC144;
}

.icon4 {
    position: absolute;
    bottom: 50px;
    right: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

.icon5 {
    position: absolute;
    bottom: 50px;
    left: 50px;
    width: 50px;
    height: 50px;
    background-color: #45619D;
}

<div class="background">
    <span class="icon1"></span>
    <span class="icon2"></span>
    <span class="icon3"></span>
    <span class="icon4"></span>
    <span class="icon5"></span>
</div>


问:
Best way to create Python function with multiple options?
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

```<code>def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...
</code>```

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options
</code>```

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

```<code>def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])
</code>```

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.

答:
At the risk of over-engineering your problem, you may use an abstract class and force child to specialize the parts of your procedure. This is possible using the abc library in Python.

from abc import ABC, abstractmethod

class AbstractProcessor(ABC):

    def process(self):
        some_identical_code
        self.some_similar_code()
        more_identical_code

    @abstractmethod
    def some_similar_code(self):
        pass

class Processor1(AbstractProcessor):

    def some_similar_code(self):
        print("Proc 1")

class Processor2(AbstractProcessor):

    def some_similar_code(self):
        print("Proc 2")

proc1 = Processor1()
proc1.process()
```

Body:
I've defined a bunch of custom functions and find a lot of them include some identical or similar blocks of code (e.g. just including slightly different strings or arguments). So something like:

def func1(a, b, c):
    some_identical_code
    some_similar_code
    more_identical_code
    some_unique_code
    final_similar_code

# similarly for func2, func3...

I would like to try to combine these into a single function that takes an additional 'setting' argument, both because the functions are obviously related and to make the code more compact. The obvious but inelegant flow for this would be something like:

def func(a, b, c, setting):
    # setting = '1', '2', etc.

    some identical code

    if setting == '1':
        similar_code_1
    elif setting == '2':
        similar_code_2
    # etc. for other settings options

    more_identical_code

    if setting == '1':
        unique_code_1
        final_similar_code_1
    elif setting == '2':
        unique_code_2
        final_similar_code_2
    # etc. for other settings options

How can I do something like this more elegantly? Is there a standard way to do it?

One option I'm trying is to use dictionaries built into the function to parse the similar code blocks:

def func(a, b, c, setting):
    # setting = '1', '2', etc.
    simdict = {'1': '_1', '2': '_2' ...}

    some identical code
    similar_code(simdict[setting])
    more_identical_code

    if setting == '1':
        unique_code_1
    elif setting == '2':
        unique_code_2
    # etc. for other settings options

    final_similar_code(simdict[setting])

This helps but 1) I'm not sure if it's good design and 2) it only helps so much when the identical vs. similar vs. unique code is very interspersed.


问:
Where are Google Cloud Vision API calls processed and can we specify it?
when making a call to the Cloud Vision API, where is the request processes (Europe, US...)?
Is there a way to specify that we want the request to be handled in a specific region or location?

Background: as part of the various data protection measures, we need to ensure that we know precisely where data is transferred and processed.

thanks!

答:
There is a way to specify the project and the location where you want to make the call.

If you are using the REST API you have a field called "parent" where you can optionally define the project-id and the location-id. See [this documentation] (https://cloud.google.com/vision/docs/reference/rest/v1/images/annotate#request-body), the supported location-ids are us: USA country only, eu: The European Union. .

If you are using a client library, for example the Python Client for Cloud Vision API, there is an optional parameter also called "parent" where you can specify the project-id and the location-id. The supported location-ids are us: USA country only, asia: East asia areas, like Japan, Taiwan, eu: The European Union.

Take a deep look to the documentation in order to clarify which regions are currently  available and take in consideration that if no parent is specified, a region will be chosen automatically.


问:
How to correctly scale image to fit into maxdim-by-maxdim square area?
I want to create a JS expression to set the scale for an image after being a given original height and width so that it can exactly fit inside a maxdim-by-maxdim square area (touching at least two edges). How would I complete my function? I think I am missing the scaling equation.

function scaleImage(width, height, maxdim) {
  var scale = ?;
  return [scale * width, scale * height];
}```

答:
Fill in the ? with a Javascript expression to set the scale for an image having a given original height and width so that it can exactly fit inside a maxdim-by-maxdim square area (touching at least two edges). *

In a square width === height so:

```<code>const scaleImage = (width, height, maxdim) => {

  const resized_width = (maxdim / width) * width;
  const resized_height = (maxdim / height) * height;

  return {
    resized_width,
    resized_height
  }
}

scaleImage(2, 5, 500);
</code>```

Body:
Fill in the ? with a Javascript expression to set the scale for an image having a given original height and width so that it can exactly fit inside a maxdim-by-maxdim square area (touching at least two edges). *

In a square width === height so:

const scaleImage = (width, height, maxdim) => {

  const resized_width = (maxdim / width) * width;
  const resized_height = (maxdim / height) * height;

  return {
    resized_width,
    resized_height
  }
}

scaleImage(2, 5, 500);


问:
RIA Services: Entities Parent Child relationship
In a project using RIA Services, I've a Customer table and an Address table to store the address of each customer.

On a page in silverlight, I have the Customer data and when I expand a control, the address data for that customer are loaded.

When I create a new Customer with his address, how do I save both separetely? The Address entity contains the CustomerId. It is a required field.

How can I save the address when the customerId doesn't exist? And I can also not save the customer first, because it needs the address.

What can I do?

答:
Let me clarify something. Just because the Entities have Navigational Properties doesn't mean you can't create them. Your perception that you have a catch 22 with "can't create one without the other, but can't create the other without the one" is not quite how EF works.

There is a simple way of doing this. The following example uses an anonymous delegate (lambda exression) to create the Customer first. Once the operation has returned from the server, the delegate/lambda expression handles the completed event and allows you to save the Address for that Customer.

This model assumes you have 1 to many relationship between a Customer and Address... aka: 1 Customer can have many addresses. The Id field of the Customer is a foreign key in the Address (CustomerId).

```<code>private void SaveCustomerAndAddress()
{

    CustomerContext context = new CustomerContext();
    Customer c = new Customer();
    c.Name = "Daniel";

    context.Customers.Add(c);

    context.SubmitChanges( submitChangesComplited =>
    {
         //Lambda expressions. Executes when the Completed event fires for the
         //SubmitChanges. At this point the Customer entity that was created
         //will have its Id assigned by the context, so you can access it
         //from within the lambda expression block.

         Address address = new Address();
         address.CustomerId = c.Id;
         address.Name = "Home Address";
         address.State = "CA";
         address.City = "San Diego";

         context.Addresses.Add(address);
         context.SubmitChanges();

    }, null);
}
</code>```

If however you have a meny-to-meny relationships between customers and addresses you have to get a bit more creative. The opeartions are as follows:
1. Save Customer
2. Save Address
3. Create Record in the joiner table for the CustomerAddress association.

Note: Using lambda expressions makes things is a bit easier because you have the ability to access variables outside the lambda expressions, so long as they are declared in the same method. Otherwise for every operation you have to persist objects into "State" if more than one operations are needed to achieve what you want:

Body:
Let me clarify something. Just because the Entities have Navigational Properties doesn't mean you can't create them. Your perception that you have a catch 22 with "can't create one without the other, but can't create the other without the one" is not quite how EF works.

There is a simple way of doing this. The following example uses an anonymous delegate (lambda exression) to create the Customer first. Once the operation has returned from the server, the delegate/lambda expression handles the completed event and allows you to save the Address for that Customer.

This model assumes you have 1 to many relationship between a Customer and Address... aka: 1 Customer can have many addresses. The Id field of the Customer is a foreign key in the Address (CustomerId).

private void SaveCustomerAndAddress()
{

    CustomerContext context = new CustomerContext();
    Customer c = new Customer();
    c.Name = "Daniel";

    context.Customers.Add(c);

    context.SubmitChanges( submitChangesComplited =>
    {
         //Lambda expressions. Executes when the Completed event fires for the
         //SubmitChanges. At this point the Customer entity that was created
         //will have its Id assigned by the context, so you can access it
         //from within the lambda expression block.

         Address address = new Address();
         address.CustomerId = c.Id;
         address.Name = "Home Address";
         address.State = "CA";
         address.City = "San Diego";

         context.Addresses.Add(address);
         context.SubmitChanges();

    }, null);
}

If however you have a meny-to-meny relationships between customers and addresses you have to get a bit more creative. The opeartions are as follows:
1. Save Customer
2. Save Address
3. Create Record in the joiner table for the CustomerAddress association.

Note: Using lambda expressions makes things is a bit easier because you have the ability to access variables outside the lambda expressions, so long as they are declared in the same method. Otherwise for every operation you have to persist objects into "State" if more than one operations are needed to achieve what you want:


问:
JPannel not having the size setted in the setSize method
In my program I'm adding a JPannel that I'm using as canvas to a JFrame. The problem is that the size of the JPannel#setSize() is not what it is displayed.
I first had a problem more or less like this one and I asked here
Java questions about coordinates with Graphics
They toldme to add the JPannel and use the pack() method and it worked but I can't get it to work now because the JFrame is larger than the JPannel where I am drawing.
I have look at some threads to see if I coud fiand an answer but I wasn't succesfull. Here are the threads I looked:

Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Why the JProgressBar doesn't respect the setSize()?

Component setSize method in FlowLayout object

setSize() not working?

setSize not influencing size of button

Why does the JFrame setSize() method not set the size correctly?

java.AWT - setSize() method

Java JPannel not Visible

I create a JFrame with setSize(600, 400); and I add the pane. Here is the code

```<code>import java.awt.Dimension;

import javax.swing.JFrame;

import me.nemo_64.particlessimulation.util.Canvas;

public class Frame extends JFrame {

    private Frame(String title) {
        super(title);
        setResizable(false);
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(null);
        init();
    }

    private void init() {
        canvas = new Canvas();
        canvas.setSize(400, 400);
        canvas.setLocation(0, 0);
        canvas.setPreferredSize(new Dimension(400, 400));
        canvas.startDrawing();
        add(canvas);
    }

    private Canvas canvas;

    public static Frame getInstance() {
        if (instance == null)
            throw new IllegalAccessError("instanceFrame must be callen at least ones before this method");
        return instance;
    }

    public static Frame instanceFrame(String title) {
        if (instance != null)
            return getInstance();
        instance = new Frame(title);
        return getInstance();
    }

    private static Frame instance;

    private static final long serialVersionUID = 1L;
}

</code>```

And here is the canvas class

```<code>
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;

public class Canvas extends ACanvas {

    Vector p, dir;
    float v;

    public Canvas() {
        p = new Vector(0, getHeight() / 2);
        dir = new Vector(50f, 50f);
        v = 50;
    }

    @Override
    public void update(float delta) {
        if (p.x <= 0 && dir.x < 0)
            dir.x *= -1;
        if (p.y <= 0 && dir.y < 0)
            dir.y *= -1;

        if (p.x + 100 >= getWidth() && dir.x > 0)
            dir.x *= -1;
        if (p.y + 100 >= getWidth() && dir.y > 0)
            dir.y *= -1;

        Vector a = dir.clone().multiply(delta);
        p.add(a);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println(e.getX() + " " + e.getY());
    }

    @Override
    public void draw(Graphics2D g) {
        System.out.println(g);
        fill(255, 0, 0);
        fillRectangle(p.x, p.y, 100, 100);
    }

}
</code>```

And here is the ACanvas class

```<code>package me.nemo_64.particlessimulation.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;

public abstract class ACanvas extends JPanel
        implements KeyListener, MouseInputListener, MouseWheelListener, Drawable, Updateable, FigureDrawer {

    private Graphics2D g;

    private Thread drawThread;

    private Color backgroundColor;
    private Color actualColor;

    private long lastTime = 0;
    private float delta = 0;

    public ACanvas() {
        setFocusable(true);
        addKeyListener(this);
        addMouseListener(this);
        addMouseWheelListener(this);
        lastTime = System.currentTimeMillis();
        drawThread = new Thread(() -> {
            while (true)
                repaint();
        }, "Drawing thread");
    }

    @Override
    /**
     * Used to update all the components to be drawn
     */
    public abstract void update(float delta);

    /**
     * Draws all the comsponents
     */
    public void draw(Graphics2D g) {}

    @Override
    public Graphics2D getGraphics2D() {
        return this.g;
    }

    @Override
    /**
     * Draws all the comsponents
     */
    public void draw(Graphics g) {
        this.g = (Graphics2D) g;
        draw(this.g);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        delta = (System.currentTimeMillis() - lastTime) * 0.001f;
        lastTime = System.currentTimeMillis();
        clearBackground(g);
        update(delta);
        g.setColor(actualColor);
        draw(g);
    }

    public void clearBackground(Graphics g) {
        g.setColor(backgroundColor);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    public void startDrawing() {
        if (!drawThread.isAlive())
            drawThread.start();
    }

    public void stopDrawing() {
        if (drawThread.isAlive())
            drawThread.interrupt();
    }

    public void background(Color c) {
        backgroundColor = c;
    }

    public void background(int c) {
        backgroundColor = new Color(c);
    }

    public void background(int r, int g, int b) {
        backgroundColor = new Color(r, g, b);
    }

    public void background(float r, float g, float b) {
        backgroundColor = new Color(r, g, b);
    }

    public void fill(Color c) {
        actualColor = c;
        g.setColor(c);
    }

    public void fill(int c) {
        fill(new Color(c));
    }

    public void fill(float r, float g, float b) {
        fill(new Color(r, g, b));
    }

    public void fill(int r, int g, int b) {
        fill(new Color(r, g, b));
    }

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseDragged(MouseEvent e) {}

    @Override
    public void mouseMoved(MouseEvent e) {}

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void keyTyped(KeyEvent e) {}

}

</code>```

It doen't seem to work in the height. In the canvas class I have a mouse click event that displays the position of the click. The width I click and the output is a coordenade like (0, ?) for the left and (400, ?) for the right. The problem is the height, at the top I get (?, 0) but at the bottom the highest value I could get is (?, 370) and not (?, 400). My question is: why the bottom doesn't go to (?, 400)?
Thanks for the help, if something is not clear just ask it

EDIT:
Other clases of the program are:
A vector class:

```<code>public class Vector {

    public float x, y, z;

    public Vector(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public Vector(float x, float y) {
        this(x, y, 0);
    }

    public Vector() {
        this(0f, 0f, 0f);
    }

    public Vector multiply(float... values) {
        for (float f : values) {
            x *= f;
            y *= f;
            z *= f;
        }
        return this;
    }

    public Vector divide(float... values) {
        for (float f : values) {
            x /= f;
            y /= f;
            z /= f;
        }
        return this;
    }

    public Vector add(Vector... vectors) {
        for (Vector v : vectors)
            add(v.x, v.y, v.z);
        return this;
    }

    public Vector add(float x, float y, float z) {
        this.x += x;
        this.y += y;
        this.z += z;
        return this;
    }

    public Vector add(float x, float y) {
        return add(x, y, 0);
    }

    public Vector remove(Vector... vectors) {
        for (Vector v : vectors)
            remove(v.x, v.y, v.z);
        return this;
    }

    public Vector remove(float x, float y, float z) {
        this.x -= x;
        this.y -= y;
        this.z -= z;
        return this;
    }

    public Vector remove(float x, float y) {
        return remove(x, y, 0);
    }

    public Vector normalize() {
        double mod = module();
        this.x /= mod;
        this.y /= mod;
        this.z /= mod;
        return this;
    }

    public double module() {
        return Math.sqrt(moduleSquared());
    }

    public double moduleSquared() {
        return (double) (x * x + y * y + z * z);
    }

    public Vector clone() {
        return new Vector(x, y, z);
    }

    @Override
    public String toString() {
        return "[ " + x + ", " + y + ", " + z + "]";
    }

}

</code>```

A drawing interface:

```<code>package me.nemo_64.particlessimulation.util;

import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;

public interface FigureDrawer {

    default public void fillRectangle(float x, float y, float width, float height) {
        getGraphics2D().fill(new Rectangle2D.Float(x, y, width, height));
    }

    default public void drawRectangle(float x, float y, float width, float height) {
        getGraphics2D().draw(new Rectangle2D.Float(x, y, width, height));
    }

    default public void fillCircle(float x, float y, float r) {
        fillCircle(x, y, r, r);
    }

    default public void drawCircle(float x, float y, float r) {
        drawCircle(x, y, r, r);
    }

    default public void fillCircle(float x, float y, float r1, float r2) {
        getGraphics2D().fill(new Ellipse2D.Float(x, y, r1, r2));
    }

    default public void drawCircle(float x, float y, float r1, float r2) {
        getGraphics2D().draw(new Ellipse2D.Float(x, y, r1, r2));
    }

    public Graphics2D getGraphics2D();

}
</code>```

And the Drawable and Updateable interfaces:

```<code>package me.nemo_64.particlessimulation.util;

public interface Updateable {

    /**
     * Called when the component must be updated
     * @param delta The seconds that past between calls
     */
    public void update(float delta);

}
</code>```

```<code>package me.nemo_64.particlessimulation.util;

import java.awt.Graphics;

public interface Drawable {

    /**
     * Called when the component must be drawn
     */
    public void draw(Graphics g);

}
</code>```

答:
I see a lot of comments here (all valid) but the question you're asking is why the canvas is showing something like ~ 370 instead of 400 on the right hand side (if I read this correctly).

Your canvas is probably x,y(400,400) but the parent container is only 400px wide based on your initial call. There's a good chance your window border and other operating system specific elements are adding quite a few pixels (on Windows Vista/7 I seem to remember this was ~30px) so there's a really good chance that's the problem.

As a side note (having written some particle simulations in Java/Processing) I can say you might want to look at the OpenGL style of positioning using floats from -1.0f/1.0f representing your canvas rather than trying to do everything in integers. First, you're going to have a lot of choppy "bounces" working with integers as you're going to want to represent values between pixels. Secondly, this makes resizing your simulation to an arbitrary x/y width very easy.

https://learnopengl.com/Getting-started/Coordinate-Systems

Good luck with it, I stopped writing GUIs in Java five or six years ago so I'm a bit rusty. Null layouts can be problematic, I would recommend picking a layout manager and using setPreferredSize (GridBag was my favorite).

Body:
In my program I'm adding a JPannel that I'm using as canvas to a JFrame. The problem is that the size of the JPannel#setSize() is not what it is displayed.
I first had a problem more or less like this one and I asked here
Java questions about coordinates with Graphics
They toldme to add the JPannel and use the pack() method and it worked but I can't get it to work now because the JFrame is larger than the JPannel where I am drawing.
I have look at some threads to see if I coud fiand an answer but I wasn't succesfull. Here are the threads I looked:

Should I avoid the use of set(Preferred|Maximum|Minimum)Size methods in Java Swing?

Why the JProgressBar doesn't respect the setSize()?

Component setSize method in FlowLayout object

setSize() not working?

setSize not influencing size of button

Why does the JFrame setSize() method not set the size correctly?

java.AWT - setSize() method

Java JPannel not Visible

I create a JFrame with setSize(600, 400); and I add the pane. Here is the code

import java.awt.Dimension;

import javax.swing.JFrame;

import me.nemo_64.particlessimulation.util.Canvas;

public class Frame extends JFrame {

    private Frame(String title) {
        super(title);
        setResizable(false);
        setSize(600, 400);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setLayout(null);
        init();
    }

    private void init() {
        canvas = new Canvas();
        canvas.setSize(400, 400);
        canvas.setLocation(0, 0);
        canvas.setPreferredSize(new Dimension(400, 400));
        canvas.startDrawing();
        add(canvas);
    }

    private Canvas canvas;

    public static Frame getInstance() {
        if (instance == null)
            throw new IllegalAccessError("instanceFrame must be callen at least ones before this method");
        return instance;
    }

    public static Frame instanceFrame(String title) {
        if (instance != null)
            return getInstance();
        instance = new Frame(title);
        return getInstance();
    }

    private static Frame instance;

    private static final long serialVersionUID = 1L;
}

And here is the canvas class

import java.awt.Graphics2D;
import java.awt.event.MouseEvent;

public class Canvas extends ACanvas {

    Vector p, dir;
    float v;

    public Canvas() {
        p = new Vector(0, getHeight() / 2);
        dir = new Vector(50f, 50f);
        v = 50;
    }

    @Override
    public void update(float delta) {
        if (p.x <= 0 && dir.x < 0)
            dir.x *= -1;
        if (p.y <= 0 && dir.y < 0)
            dir.y *= -1;

        if (p.x + 100 >= getWidth() && dir.x > 0)
            dir.x *= -1;
        if (p.y + 100 >= getWidth() && dir.y > 0)
            dir.y *= -1;

        Vector a = dir.clone().multiply(delta);
        p.add(a);
    }

    @Override
    public void mouseClicked(MouseEvent e) {
        System.out.println(e.getX() + " " + e.getY());
    }

    @Override
    public void draw(Graphics2D g) {
        System.out.println(g);
        fill(255, 0, 0);
        fillRectangle(p.x, p.y, 100, 100);
    }

}

And here is the ACanvas class

package me.nemo_64.particlessimulation.util;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;

import javax.swing.JPanel;
import javax.swing.event.MouseInputListener;

public abstract class ACanvas extends JPanel
        implements KeyListener, MouseInputListener, MouseWheelListener, Drawable, Updateable, FigureDrawer {

    private Graphics2D g;

    private Thread drawThread;

    private Color backgroundColor;
    private Color actualColor;

    private long lastTime = 0;
    private float delta = 0;

    public ACanvas() {
        setFocusable(true);
        addKeyListener(this);
        addMouseListener(this);
        addMouseWheelListener(this);
        lastTime = System.currentTimeMillis();
        drawThread = new Thread(() -> {
            while (true)
                repaint();
        }, "Drawing thread");
    }

    @Override
    /**
     * Used to update all the components to be drawn
     */
    public abstract void update(float delta);

    /**
     * Draws all the comsponents
     */
    public void draw(Graphics2D g) {}

    @Override
    public Graphics2D getGraphics2D() {
        return this.g;
    }

    @Override
    /**
     * Draws all the comsponents
     */
    public void draw(Graphics g) {
        this.g = (Graphics2D) g;
        draw(this.g);
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        delta = (System.currentTimeMillis() - lastTime) * 0.001f;
        lastTime = System.currentTimeMillis();
        clearBackground(g);
        update(delta);
        g.setColor(actualColor);
        draw(g);
    }

    public void clearBackground(Graphics g) {
        g.setColor(backgroundColor);
        g.fillRect(0, 0, getWidth(), getHeight());
    }

    public void startDrawing() {
        if (!drawThread.isAlive())
            drawThread.start();
    }

    public void stopDrawing() {
        if (drawThread.isAlive())
            drawThread.interrupt();
    }

    public void background(Color c) {
        backgroundColor = c;
    }

    public void background(int c) {
        backgroundColor = new Color(c);
    }

    public void background(int r, int g, int b) {
        backgroundColor = new Color(r, g, b);
    }

    public void background(float r, float g, float b) {
        backgroundColor = new Color(r, g, b);
    }

    public void fill(Color c) {
        actualColor = c;
        g.setColor(c);
    }

    public void fill(int c) {
        fill(new Color(c));
    }

    public void fill(float r, float g, float b) {
        fill(new Color(r, g, b));
    }

    public void fill(int r, int g, int b) {
        fill(new Color(r, g, b));
    }

    @Override
    public void mouseClicked(MouseEvent e) {}

    @Override
    public void mouseEntered(MouseEvent e) {}

    @Override
    public void mouseExited(MouseEvent e) {}

    @Override
    public void mousePressed(MouseEvent e) {}

    @Override
    public void mouseReleased(MouseEvent e) {}

    @Override
    public void mouseDragged(MouseEvent e) {}

    @Override
    public void mouseMoved(MouseEvent e) {}

    @Override
    public void mouseWheelMoved(MouseWheelEvent e) {}

    @Override
    public void keyPressed(KeyEvent e) {}

    @Override
    public void keyReleased(KeyEvent e) {}

    @Override
    public void keyTyped(KeyEvent e) {}

}

It doen't seem to work in the height. In the canvas class I have a mouse click event that displays the position of the click. The width I click and the output is a coordenade like (0, ?) for the left and (400, ?) for the right. The problem is the height, at the top I get (?, 0) but at the bottom the highest value I could get is (?, 370) and not (?, 400). My question is: why the bottom doesn't go to (?, 400)?
Thanks for the help, if something is not clear just ask it

EDIT:
Other clases of the program are:
A vector class:

public class Vector {

    public float x, y, z;

    public Vector(float x, float y, float z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

    public Vector(float x, float y) {
        this(x, y, 0);
    }

    public Vector() {
        this(0f, 0f, 0f);
    }

    public Vector multiply(float... values) {
        for (float f : values) {
            x *= f;
            y *= f;
            z *= f;
        }
        return this;
    }

    public Vector divide(float... values) {
        for (float f : values) {
            x /= f;
            y /= f;
            z /= f;
        }
        return this;
    }

    public Vector add(Vector... vectors) {
        for (Vector v : vectors)
            add(v.x, v.y, v.z);
        return this;
    }

    public Vector add(float x, float y, float z) {
        this.x += x;
        this.y += y;
        this.z += z;
        return this;
    }

    public Vector add(float x, float y) {
        return add(x, y, 0);
    }

    public Vector remove(Vector... vectors) {
        for (Vector v : vectors)
            remove(v.x, v.y, v.z);
        return this;
    }

    public Vector remove(float x, float y, float z) {
        this.x -= x;
        this.y -= y;
        this.z -= z;
        return this;
    }

    public Vector remove(float x, float y) {
        return remove(x, y, 0);
    }

    public Vector normalize() {
        double mod = module();
        this.x /= mod;
        this.y /= mod;
        this.z /= mod;
        return this;
    }

    public double module() {
        return Math.sqrt(moduleSquared());
    }

    public double moduleSquared() {
        return (double) (x * x + y * y + z * z);
    }

    public Vector clone() {
        return new Vector(x, y, z);
    }

    @Override
    public String toString() {
        return "[ " + x + ", " + y + ", " + z + "]";
    }

}

A drawing interface:

package me.nemo_64.particlessimulation.util;

import java.awt.Graphics2D;
import java.awt.geom.Ellipse2D;
import java.awt.geom.Rectangle2D;

public interface FigureDrawer {

    default public void fillRectangle(float x, float y, float width, float height) {
        getGraphics2D().fill(new Rectangle2D.Float(x, y, width, height));
    }

    default public void drawRectangle(float x, float y, float width, float height) {
        getGraphics2D().draw(new Rectangle2D.Float(x, y, width, height));
    }

    default public void fillCircle(float x, float y, float r) {
        fillCircle(x, y, r, r);
    }

    default public void drawCircle(float x, float y, float r) {
        drawCircle(x, y, r, r);
    }

    default public void fillCircle(float x, float y, float r1, float r2) {
        getGraphics2D().fill(new Ellipse2D.Float(x, y, r1, r2));
    }

    default public void drawCircle(float x, float y, float r1, float r2) {
        getGraphics2D().draw(new Ellipse2D.Float(x, y, r1, r2));
    }

    public Graphics2D getGraphics2D();

}

And the Drawable and Updateable interfaces:

package me.nemo_64.particlessimulation.util;

public interface Updateable {

    /**
     * Called when the component must be updated
     * @param delta The seconds that past between calls
     */
    public void update(float delta);

}

package me.nemo_64.particlessimulation.util;

import java.awt.Graphics;

public interface Drawable {

    /**
     * Called when the component must be drawn
     */
    public void draw(Graphics g);

}


问:
Auto deploy git pull if master branch is updated
I have 4 different sites on Linux server, and a repo on bitbucket.
How can I update (overwrite) folders and files which are host on same server and different domain name, after repo (master branch) is updated?

答:
I use,
git ftp init and git ftp push using bitbucket pipeline page.

```<code>..
apt-get -qq install git-ftp
git ftp init --user FTPuser --passwd FTPpass ftp://mydomain/serverIPaddress;
..
</code>```

Body:
I use,
git ftp init and git ftp push using bitbucket pipeline page.

..
apt-get -qq install git-ftp
git ftp init --user FTPuser --passwd FTPpass ftp://mydomain/serverIPaddress;
..


问:
Calling the variable property directly vs getter/setters - OOP Design
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

```<code>class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();
</code>```

Suggested Optimization:

```<code>$rover = new dog();
$rover->name = 'rover';
echo $rover->name;
</code>```

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?

答:
It depends on whether $name is public or not.  If it's not, you can't access/modify it directly.  The trade off is exposing your class's internal data elements directly to integrators. This may be OK for some classes, but not for others.

For example, you wouldn't necessarily want others to be able to modify the price of a product directly in a Product class.

Body:
I know this is probably subjective but I read this optimization page from Google for PHP and they suggest use the variable property directly without the need of getters and setters. Understandably I see the performance gain in this but is this really a good design practice to follow?

Their Example using getter/setter:

class dog {
  public $name = '';

  public function setName($name) {
    $this->name = $name;
  }

  public function getName() {
    return $this->name;
  }
}

$rover = new dog();
$rover->setName('rover');
echo $rover->getName();

Suggested Optimization:

$rover = new dog();
$rover->name = 'rover';
echo $rover->name;

This would be a welcome change in my design process as I see the need for getters/setters going away, but what other hurdles/benefits might occur in doing this?


问:
In Node.js I m using console.log which is not working
I used console.log to display a port number but it not working.It displaying string but when i use this with value it not displaying.

```<code>const http = require('http');
const express = require('express');
const socketio = require('socket.io');

const PORT = process.env.PORT || 5000;

const app = express();
const server = http.createServer(app);
const io = socketio(server);

server.listen(PORT,()=>{
    return console.log('server has started on port ${PORT}');
});
</code>```

I m getting Following:
Output:server has started on port ${PORT}

答:
Wrong quotes

Use ``

```<code>console.log(`server has started on port ${PORT}`);
</code>```

Body:
I used console.log to display a port number but it not working.It displaying string but when i use this with value it not displaying.

const http = require('http');
const express = require('express');
const socketio = require('socket.io');

const PORT = process.env.PORT || 5000;

const app = express();
const server = http.createServer(app);
const io = socketio(server);

server.listen(PORT,()=>{
    return console.log('server has started on port ${PORT}');
});

I m getting Following:
Output:server has started on port ${PORT}

Body:
Wrong quotes

Use ``

console.log(`server has started on port ${PORT}`);


问:
MS Teams Bot: test in web chat is unauthorized for Teams conversation bot from BotBuilder-Samples
I'm having trouble setting this up https://github.com/microsoft/BotBuilder-Samples/tree/master/samples/javascript_nodejs/57.teams-conversation-bot.

I used a bot channel registration and ngrok. I've replaced the MicrosoftAppId and MicrosoftAppPassword(client secret) in the .env file. I also edited the app id in the manifest. But when I try to test the bot in web chat, it's giving me unauthorized with this error: JwtTokenExtractor.getIdentity:err! FetchError: request to https://login.botframework.com/v1/.well-known/openidconfiguration failed, reason: connect ETIMEDOUT

It works when I test it in the emulator locally. Please help me.

答:
I just tested it, and it works for me, All i did was create a bot channel registration,
put the messaging endpoint https://xxxxxxa6ab9.ngrok.io/api/messages, and put the app reg secret and appid into the .env and ran the 2 things. </p>

<p>it sounds like you may have an antivirus/firewall blocking some of the communications between your ngrok or bot and outside.
make sure you turn off third party firewalls and such, and just to confirm, you need 2 command windows to run this, one window to run ngrok and a separate window to run the npm start. </p>

Body:
I just tested it, and it works for me, All i did was create a bot channel registration,
put the messaging endpoint https://xxxxxxa6ab9.ngrok.io/api/messages, and put the app reg secret and appid into the .env and ran the 2 things.

it sounds like you may have an antivirus/firewall blocking some of the communications between your ngrok or bot and outside.
make sure you turn off third party firewalls and such, and just to confirm, you need 2 command windows to run this, one window to run ngrok and a separate window to run the npm start.


问:
Why does my Python freeze when I do an overflow calculation?
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

```<code>print(9**9)
</code>```

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?

答:
the num 9**9**9 is very big to caculated

you can wait untill it will return a result

it can take much long time

Body:
I'm a MATLAB user trying to understand Python so sorry if this is obvious.

If I say

print(9**9)

I get:
387420489

Great.

If I say print(9**9**9)
Python just sits there indefinitely and freezes (I use Spyder version 4). Ctrl-C doesn't stop it.
Why does it not just immediately return Inf? Is this expected behavior?


问:
Filter the dataframe according to a list of dates
I have the following dataframe for weather stations (short dataframe):

```<code>      import pandas as pd
      import numpy as np

      df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                                 'Qtd_Instrumentation': [18, 5, 25, 10],
                                  'Year_Construction': [2015, 2008, 2016, 2020]})
</code>```

I would like to generate a new dataframe. This would need to be filtered by the year the station was built. I tried to create a list containing the objective years and build the df_ as follows:

```<code>      list_years = [2015, 2016, 2017, 2018, 2019, 2020]
      df_Filter =  df_Station[df_Station['Year_Construction'] == list_years]
</code>```

However, this code has the error: ValueError: Lengths must match to compare

I would like the output (df_Filter) to be:

```<code>            print(df_Filter)

            Hemisphere  Qtd_Instrumentation Year_Construction
               North            18              2015
               North            25              2016
               South            10              2020
</code>```

Thank you.

答:
Use pandas.Series.isin for this type of filtering.

df_Filter =  df_Station[df_Station['Year_Construction'].isin(list_years)]
```

Body:
I have the following dataframe for weather stations (short dataframe):

      import pandas as pd
      import numpy as np

      df_Station = pd.DataFrame({'Hemisphere': ['North', 'North', 'North', 'South'],
                                 'Qtd_Instrumentation': [18, 5, 25, 10],
                                  'Year_Construction': [2015, 2008, 2016, 2020]})

I would like to generate a new dataframe. This would need to be filtered by the year the station was built. I tried to create a list containing the objective years and build the df_ as follows:

      list_years = [2015, 2016, 2017, 2018, 2019, 2020]
      df_Filter =  df_Station[df_Station['Year_Construction'] == list_years]

However, this code has the error: ValueError: Lengths must match to compare

I would like the output (df_Filter) to be:

            print(df_Filter)

            Hemisphere  Qtd_Instrumentation Year_Construction
               North            18              2015
               North            25              2016
               South            10              2020

Thank you.


问:
SSIS: Code page goes back to 65001
In an SSIS package that I'm writing, I have a CSV file as a source. On the Connection Manager General page, it has 65001 as the Code page (I was testing something). Unicode is not checked.

The columns map to a SQL Server destination table with varchar (among others) columns.

There's an error at the destination: The column "columnname" cannot be processed because more than one code page (65001 and 1252) are specified for it.

My SQL columns have to be varchar, not nvarchar due to other applications that use it.

On the Connection Manager General page I then change the Code page to 1252 (ANSI - Latin I) and OK out, but when I open it again it's back to 65001. It doesn't make a difference if (just for test) I check Unicode or not.

As a note, all this started happening after the CSV file and the SQL table had columns added and removed (users, you know.) Before that, I had no issues whatsoever. Yes, I refreshed the OLE DB destination in the Advanced Editor.

This is SQL Server 2012 and whichever version of BIDS and SSIS come with it.

答: If it's a csv file, you can still use code page 1252 to process it.  When you open the flat file connection manager it shows you the code page for the file, but you don't need to save that setting.  If you have other changes to make in the connection manager, change the code page back to 1252 before you save the changes.  It will process fine if there are no unicode characters in the file.</p>

Title: SSIS: Code page goes back to 65001


问:
Sign extension from 16 to 32 bits in C
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

```<code>int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}
</code>```

The instruction (instr) is 32 bits and inside it I have a 16bit number.

答:
what's wrong in using the builtin types?

```<code>int32_t signExtension(int32_t instr) {
    int16_t value = (int16_t)instr;
    return (int32_t)value;
}
</code>```

or better yet (this might generate a warning if passed a int32_t)

```<code>int32_t signExtension(int16_t instr) {
    return (int32_t)instr;
}
</code>```

or, for all that matters, replace signExtension(value) with ((int32_t)(int16_t)value)

you obviously need to include <stdint.h> for the int16_t and int32_t data types.

Title: Sign extension from 16 to 32 bits in C

Body:
I have to do a sign extension for a 16-bit integer and for some reason, it seems not to be working properly. Could anyone please tell me where the bug is in the code? I've been working on it for hours.

int signExtension(int instr) {
    int value = (0x0000FFFF & instr);
    int mask = 0x00008000;
    int sign = (mask & instr) >> 15;
    if (sign == 1)
        value += 0xFFFF0000;
    return value;
}

The instruction (instr) is 32 bits and inside it I have a 16bit number.

Body:
what's wrong in using the builtin types?

int32_t signExtension(int32_t instr) {
    int16_t value = (int16_t)instr;
    return (int32_t)value;
}

or better yet (this might generate a warning if passed a int32_t)

int32_t signExtension(int16_t instr) {
    return (int32_t)instr;
}

or, for all that matters, replace signExtension(value) with ((int32_t)(int16_t)value)

you obviously need to include <stdint.h> for the int16_t and int32_t data types.


答:
You are using it wrong. You must use backticks - ` and not quotes - '

So the correct format is -

```<code>server.listen(PORT,()=>{
    return console.log(`server has started on port ${PORT}`);
});
</code>```

Quotes ('') will just output whatever is given inside them.

However, Backticks(``) will evaluate the expression inside ${}
and then output the evaluated value.

Hope this solves your issue !

Title: In Node.js I m using console.log which is not working

Body:
You are using it wrong. You must use backticks - ` and not quotes - '

So the correct format is -

server.listen(PORT,()=>{
    return console.log(`server has started on port ${PORT}`);
});

Quotes ('') will just output whatever is given inside them.

However, Backticks(``) will evaluate the expression inside ${}
and then output the evaluated value.

Hope this solves your issue !


问:
How to run code based on UIPickerview selections?
I'm making a simple iOS application similar to google docs or other text editor. I created a UIPickerview to change the font size but then I realized that when I chose something, nothing happens. So is there any way I can do this here is my code

```<code>import UIKit

class FirstViewController: UIViewController, UIPopoverPresentationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var fontBTN: UIButton!
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrayFruits.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return arrayFruits[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }
    var arrayFruits = [String]()
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var aligners: UISegmentedControl!

    @IBOutlet weak var foramtters: UISegmentedControl!
    @IBOutlet weak var textView: UITextView!

    var pickerData = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.picker.delegate = self
        self.picker.dataSource = self
        arrayFruits = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]
    }

    @IBAction func aligning(_ sender: Any) {
        switch aligners.selectedSegmentIndex {
        case 0:
            textView.textAlignment = .left
        case 1:
            textView.textAlignment = .center
        case 2:
            textView.textAlignment = .right
        case 3:
            textView.textAlignment = .justified
        default: break

        }
    }

    @IBAction func formating(_ sender: Any) {
        switch foramtters.selectedSegmentIndex {
        case 0:
            textView.font = UIFont.boldSystemFont(ofSize: 14)
        case 1:
            textView.attributedText = NSAttributedString(string: textView.text, attributes:
                [.underlineStyle: NSUnderlineStyle.single.rawValue])
            textView.font = UIFont(name: "Arial", size: 14)
        case 2:
            textView.font = UIFont.italicSystemFont(ofSize: 14)
        default: break

        }

    }

    @IBAction func fontPicker(_ sender: Any) {
        if picker.isHidden == true {
            picker.isHidden = false
            fontBTN.setTitle("Done", for: .normal)
        } else if picker.isHidden == false {
            fontBTN.setTitle("Aa", for: .normal)
            picker.isHidden = true

        }
    }

}
</code>```

I have tried doing a Switch statement, but I get an error saying "Expression pattern of type 'Int' cannot match values of type 'UIPickerView?'" I tried googling this up but nothing showed up so I asked this question.

```<code>switch picker {
        case 0:
            //funtion here
        default:

        }
</code>```

Can you please help me?

答:
Consider the following code:

```<code>class ViewController: UIViewController {
    @IBOutlet weak var picker: UIPickerView!

    @IBOutlet weak var textView: UITextView!
    let data: [CGFloat] = [20, 25, 30]

    override func viewDidLoad() {
        super.viewDidLoad()
        picker.delegate = self
        picker.dataSource = self
    }
}

extension ViewController: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        textView.font = UIFont.systemFont(ofSize: data[row])
    }
}

extension ViewController: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "\(data[row])"
    }
}
</code>```

So you can run code based on an UIPickerView selection by implementing the didSelectRow method as shown above.

Edit:

I have changed the code to update the fontSize of a textView.

Body:
I'm making a simple iOS application similar to google docs or other text editor. I created a UIPickerview to change the font size but then I realized that when I chose something, nothing happens. So is there any way I can do this here is my code

import UIKit

class FirstViewController: UIViewController, UIPopoverPresentationControllerDelegate, UIPickerViewDelegate, UIPickerViewDataSource {

    @IBOutlet weak var fontBTN: UIButton!
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }
    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return arrayFruits.count
    }
    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return arrayFruits[row]
    }
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {

    }
    var arrayFruits = [String]()
    @IBOutlet weak var picker: UIPickerView!
    @IBOutlet weak var aligners: UISegmentedControl!

    @IBOutlet weak var foramtters: UISegmentedControl!
    @IBOutlet weak var textView: UITextView!

    var pickerData = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        self.picker.delegate = self
        self.picker.dataSource = self
        arrayFruits = ["10", "12", "14", "16", "18", "20", "22", "24", "26", "28", "30", "36", "48", "72"]
    }

    @IBAction func aligning(_ sender: Any) {
        switch aligners.selectedSegmentIndex {
        case 0:
            textView.textAlignment = .left
        case 1:
            textView.textAlignment = .center
        case 2:
            textView.textAlignment = .right
        case 3:
            textView.textAlignment = .justified
        default: break

        }
    }

    @IBAction func formating(_ sender: Any) {
        switch foramtters.selectedSegmentIndex {
        case 0:
            textView.font = UIFont.boldSystemFont(ofSize: 14)
        case 1:
            textView.attributedText = NSAttributedString(string: textView.text, attributes:
                [.underlineStyle: NSUnderlineStyle.single.rawValue])
            textView.font = UIFont(name: "Arial", size: 14)
        case 2:
            textView.font = UIFont.italicSystemFont(ofSize: 14)
        default: break

        }

    }

    @IBAction func fontPicker(_ sender: Any) {
        if picker.isHidden == true {
            picker.isHidden = false
            fontBTN.setTitle("Done", for: .normal)
        } else if picker.isHidden == false {
            fontBTN.setTitle("Aa", for: .normal)
            picker.isHidden = true

        }
    }

}

I have tried doing a Switch statement, but I get an error saying "Expression pattern of type 'Int' cannot match values of type 'UIPickerView?'" I tried googling this up but nothing showed up so I asked this question.

switch picker {
        case 0:
            //funtion here
        default:

        }

Can you please help me?

Body:
Consider the following code:

class ViewController: UIViewController {
    @IBOutlet weak var picker: UIPickerView!

    @IBOutlet weak var textView: UITextView!
    let data: [CGFloat] = [20, 25, 30]

    override func viewDidLoad() {
        super.viewDidLoad()
        picker.delegate = self
        picker.dataSource = self
    }
}

extension ViewController: UIPickerViewDelegate {
    func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
        textView.font = UIFont.systemFont(ofSize: data[row])
    }
}

extension ViewController: UIPickerViewDataSource {
    func numberOfComponents(in pickerView: UIPickerView) -> Int {
        return 1
    }

    func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
        return data.count
    }

    func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
        return "\(data[row])"
    }
}

So you can run code based on an UIPickerView selection by implementing the didSelectRow method as shown above.

Edit:

I have changed the code to update the fontSize of a textView.