问:
Spring DatabaseClient fetch method returns columns values in different order with different column names
When using database client and fetch method which returns Map<String,Any>, the keys seem to be out of order. Am I doing something wrong here?

The code that fetches the map is

```<code>val result = databaseClient
                .sql(SELECT_ISSUER_METADATA)
                .bind(0, id)
                .fetch()
                .awaitOne()
</code>```

The SELECT_ISSUER_METADATA is SELECT * FROM ISSUER_METADATA WHERE issuer = ?
The table contains these columns and values when I ran the example:

As you can see issuer has value soludcommunity.net while authorization_endpoint has the value soludcommunity.net/authorize.

But when I print the map I got from fetch I get this result:

```<code>{authorization_endpoint=https://solidcommunity.net, issuer=https://solidcommunity.net/authorize, jwk_uri=https://solidcommunity.net/jwks, registration_endpoint=https://solidcommunity.net/token, token_endpoint=https://solidcommunity.net/register}
</code>```

Am I missing something simple here(I feel like this)?I don't know how to fix this.

I am using MySql R2dbc drivers.

答:
This was due to a bug in the r2dbc-mysql driver, which has been fixed but not yet part of a stable release. So for now, the only option seems to be to use the build snapshot, which for maven would look something like:

    <properties>
        <r2dbc-mysql.version>0.8.3.BUILD-SNAPSHOT</r2dbc-mysql.version>
    </properties>

    <repositories>
        <repository>
            <id>sonatype-snapshots</id>
            <name>SonaType Snapshots</name>
            <url>https://oss.sonatype.org/content/repositories/snapshots</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
    </repositories>

    <dependencies>
        <dependency>
            <groupId>dev.miku</groupId>
            <artifactId>r2dbc-mysql</artifactId>
            <version>${r2dbc-mysql.version}</version>
        </dependency>
    <dependencies>
```

Body:
When using database client and fetch method which returns Map<String,Any>, the keys seem to be out of order. Am I doing something wrong here?

The code that fetches the map is

val result = databaseClient
                .sql(SELECT_ISSUER_METADATA)
                .bind(0, id)
                .fetch()
                .awaitOne()

The SELECT_ISSUER_METADATA is SELECT * FROM ISSUER_METADATA WHERE issuer = ?
The table contains these columns and values when I ran the example:

As you can see issuer has value soludcommunity.net while authorization_endpoint has the value soludcommunity.net/authorize.

But when I print the map I got from fetch I get this result:

{authorization_endpoint=https://solidcommunity.net, issuer=https://solidcommunity.net/authorize, jwk_uri=https://solidcommunity.net/jwks, registration_endpoint=https://solidcommunity.net/token, token_endpoint=https://solidcommunity.net/register}

Am I missing something simple here(I feel like this)?I don't know how to fix this.

I am using MySql R2dbc drivers.


来源: stackexchange

问:
Unknown column in 'where clause' while there`s no 'where clause' and the column isn`t mentioned in the query
I`m new in SQL and now straggling with an error 1054 Unknown column in 'where clause' in MySQL.

There`s a simple table 'customer_orders' with 3 columns 'order_id', 'staff_id' and 'order_total'

I needed to insert a line. My query was
INSERT INTO customer_orders VALUES (25,1,10.50);

First that worked, then I realized a need to delete the row and insert with a slight change

Now it throws the error 'Error Code: 1054. Unknown column 'order_id' in 'where clause''
Theres no such column in the query and the column isnt mentioned.
I renamed the column into 'order_id_new' and explicitly specified the column names in the INSERT statement - the same error.

INSERT INTO customer_orders (order_id_new, staff_id, order_total) VALUES
(23,1,11.43);

When I created a copy of the table the same worked fine.

Any ideas what is wrong with the table?

Thanks in advance.

答: It turned out there was a Trigger which conflicted with the query. Strange that the error doesn`t refer to the trigger in any way. Once I fixed the trigger the query worked.</p>

ContentLicense: CC BY-SA 4.0


问:
How to use LIKE Operator in LINQ to Entity Framework
I'm using Entity Framework.

Problem: search a name that start with 'a' in a list of strings:

```<code>var likeQuery = from k in dbContext.Categories
                where sqlMethod.Like(k.CategoryName, "a%" )  // name start with a
                select k;

foreach (var item in likeQuery)
{
    Console.WriteLine(Item.);
}
</code>```

答:
Do like this.</p>
```<code>var result
  = dbContext.Categories.Where(i => i.CategoryName.StartsWith("a")).ToList();
</code>```

Body:
I'm using Entity Framework.

Problem: search a name that start with 'a' in a list of strings:

var likeQuery = from k in dbContext.Categories
                where sqlMethod.Like(k.CategoryName, "a%" )  // name start with a
                select k;

foreach (var item in likeQuery)
{
    Console.WriteLine(Item.);
}

Body:
Do like this.

var result
  = dbContext.Categories.Where(i => i.CategoryName.StartsWith("a")).ToList();


问:
Passing Authentication Credentials From Webapplication A to Webapplication B?
I have got a Web application say A which via url needs to communicate with application B and get the response from B. Application B uses a HTTP authentication mechanism. What I need to do is pass the authentication credentials from Application A to Application B through url request. I dont want to use _GET or _POST method due to security issues</p>

答:
Attach an encrypted string to the URL request from A to B.
B should know the decryption method and parameters, it decrypt the encrypted string which received from A and check it is correct or not.</p>

ContentLicense: CC BY-SA 3.0


问:
How does Amazon blend the white background of it's images?
So I've been making a site for TheOdinProject using the fake store API and the images the API provides have a white background which is obvious if changing the background colour of it's container. I had a look around and found mix-blend-mode: multiply; which worked but also ended up having some weird problems. I decided to look at the Amazon website to see how they do it and found that all the images worked fine for them without any obvious background. Going through the Firefox inspector I couldn't find anywhere that made it obvious how they managed to blend the image background (Which is definitely white) into the grey colour they place it on top of. For that matter, I couldn't even figure out how they managed to get the grey colour (Image provided) at all despite following the nodes all the way from the image to the root which has a solid white background.

Can anyone give me any insight into 1) how they managed to get the grey colour displaying without it showing up in the inspector and 2) how they managed to blend the background colour of the image without mix-blend-mode: multiply;?

Thank you.

Grey background shown on left side of cards

Background colour of image on Amazon's site

Background colour of image directly from source

答:
It is actually a very dirty hack .

If you inspect the products page, you'll see that they've added an ::after (sudo) element with the following CSS:

{
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.03;
  pointer-events: none;
}
```

So as you can see they are adding a very very transparent gray filter to everything! so if you have a good eye (and monitor) you can see that white products turn gray a little.

Body:
It is actually a very dirty hack .

If you inspect the products page, you'll see that they've added an ::after (sudo) element with the following CSS:

{
  position: absolute;
  content: '';
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #000;
  opacity: 0.03;
  pointer-events: none;
}

So as you can see they are adding a very very transparent gray filter to everything! so if you have a good eye (and monitor) you can see that white products turn gray a little.


问:
Check if the path exists in Databricks
I try to check if the path exists in Databricks using Python:

```<code>try:
  dirs = dbutils.fs.ls ("/my/path")
  pass
except IOError:
  print("The path does not exist")
</code>```

If the path does not exist, I expect that the except statement executes.
However, instead of except statement, the try statement fails with the error:

```<code>java.io.FileNotFoundException: GET ...
ErrorMessage=The specified path does not exist.
</code>```

How to properly catch FileNotFoundException?

答:
This approach should work, and looks familiar with your code:</p>
```<code>  try:
    dbutils.fs.ls(path)
    pass
  except Exception as e:
    if 'java.io.FileNotFoundException' in str(e):
      print('The path does not exist')
    else:
      raise
</code>```

Title: Check if the path exists in Databricks

Body:
I try to check if the path exists in Databricks using Python:

try:
  dirs = dbutils.fs.ls ("/my/path")
  pass
except IOError:
  print("The path does not exist")

If the path does not exist, I expect that the except statement executes.
However, instead of except statement, the try statement fails with the error:

java.io.FileNotFoundException: GET ...
ErrorMessage=The specified path does not exist.

How to properly catch FileNotFoundException?

Body:
This approach should work, and looks familiar with your code:

  try:
    dbutils.fs.ls(path)
    pass
  except Exception as e:
    if 'java.io.FileNotFoundException' in str(e):
      print('The path does not exist')
    else:
      raise


问:
Setting Background Color CMDIFrameWnd
Is there a way to change the color of the background for a MDIParent windows in MFC (2005)?

I have tried intercepting ON_WM_CTLCOLOR AND ON_WM_ERASEBKGND but neither work. OnEraseBkgnd does work, but then it gets overwritten by the standard WM_CTL color.

Cheers

答:
There appears to be a simple solution to this problem in VS2008 at least:

In

CMainFrame::OnPaint()

{

..

// get the dc of the background window

CWnd* pWnd = CWnd::FromHandle(m_hWndMDIClient) ;

CPaintDC dc1(pWnd) ;

//and then draw or bitblt in this DC

}

OwnerDisplayName: KiwiBastard

ContentLicense: CC BY-SA 2.5

Title: Setting Background Color CMDIFrameWnd


问:
Javascript: return all rangs between two numbers based on a number
I have a case where I need to split a range of numbers [1, 60] into ranges that has 11 in each.

I want to push each range into JSON Array, so the expected result would be:

[
{'first: 1, 'last': 11},  // count = 11
{'first: 12, 'last': 22}, // count = 11
{'first: 23, 'last': 33}, // count = 11
{'first: 34, 'last': 44}, // count = 11
{'first: 45, 'last': 55}, // count = 11
{'first: 56, 'last': 60}  // the rest, count = 5
]
```
<p>My code so far:</p>
<pre class="lang-js prettyprint-override"><code>var count = 11, first = 1, last = 60;
var all = [];
var starter = first;
for(i = first; i <= last; i++){
if(i % count == 0){
all.push({'first': (i - count + (all.length == 0 ? 1 : 0)), 'last': (i-1)});
 }
}
console.log(all);
</code>```

My code return only 5 ranges not 6 as expected and this code not work for all cases like [1, 10] and it return wrong result in many other cases.

答:
```<code>var count = 11, first = 1, last = 60;
var all = [];
for(i = first; i <= last; i += count){
    var l = i + count - 1;
    all.push({'first': i, 'last': l > last ? last : l});
}
console.log(all);
</code>```

Body:
I have a case where I need to split a range of numbers [1, 60] into ranges that has 11 in each.

I want to push each range into JSON Array, so the expected result would be:

[
{'first: 1, 'last': 11},  // count = 11
{'first: 12, 'last': 22}, // count = 11
{'first: 23, 'last': 33}, // count = 11
{'first: 34, 'last': 44}, // count = 11
{'first: 45, 'last': 55}, // count = 11
{'first: 56, 'last': 60}  // the rest, count = 5
]

My code so far:

var count = 11, first = 1, last = 60;
var all = [];
var starter = first;
for(i = first; i <= last; i++){
if(i % count == 0){
all.push({'first': (i - count + (all.length == 0 ? 1 : 0)), 'last': (i-1)});
 }
}
console.log(all);

My code return only 5 ranges not 6 as expected and this code not work for all cases like [1, 10] and it return wrong result in many other cases.


问:
Using Fluent Results inside a MediatR validation pipeline to return a Result<TResponse>
First off, I'm using Fluent Results in combination with Mediatr and Fluent Validation

I initially followed this article but instead of reinventing the wheel I started using FluentResults in my Fluent Validation pipeline. Basically all responses coming from my CQRS Queries are wrapped in the Result object, this avoids having to work with exceptions as a method of error handeling.

However, I can't get my pipeline to play nice:

```<code>public class ValidationPipeline<TRequest, TResponse>
    : IPipelineBehavior<TRequest, TResponse>
    where TResponse : class
    where TRequest : IRequest<TResponse>
{
    private readonly IValidator<TRequest> _compositeValidator;

    public ValidationPipeline(IValidator<TRequest> compositeValidator)
    {
        _compositeValidator = compositeValidator;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var result = await _compositeValidator.ValidateAsync(request, cancellationToken);

        if (!result.IsValid)
        {
            Error error = new Error();
            var responseType = typeof(TResponse);

            foreach (var validationFailure in result.Errors)
            {
                Log.Warning($"{responseType} - {validationFailure.ErrorMessage}");
                error.Reasons.Add(new Error(validationFailure.ErrorMessage));
            }
            // This always returns null instead of a Result with errors in it.
            var f = Result.Fail(error) as TResponse;
            return f;

        }

        return await next();
    }
}
</code>```

I also have to somehow convert the Result object back to TResponse, where TResponse is always a Result

Any suggestions are greatly appreciated!

Edit:

Autofac integration

```<code>    protected override void Load(ContainerBuilder builder)
    {
        var assembly = Assembly.GetExecutingAssembly();

        // MediatR
        builder.AddMediatR(assembly);
        // Register the Command's Validators (Validators based on FluentValidation library)
        builder.RegisterAssemblyTypes(assembly)
            .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
            .AsImplementedInterfaces();
        // Register all the Command classes (they implement IRequestHandler) in assembly holding the Commands
        builder.RegisterAssemblyTypes(assembly)
            .AsClosedTypesOf(typeof(IRequestHandler<,>));
        // Register Behavior Pipeline
        builder.RegisterGeneric(typeof(ValidationPipeline<,>)).As(typeof(IPipelineBehavior<,>));

    }
</code>```

答:
I had a similar problem. Moreover some handlers returned Result while other Result<ABC> or Result<XYZ>. Generic behavior couldn't handle this.

Two workarounds:

Instead of returning Result<> throw an exception and covert to a Result down the pipeline (catch or global error handle).

Register each handler and pipeline separately like this

services.AddTransient( typeof(IPipelineBehavior<MyCommand,Result<MyCommandResult>>), typeof(MyBehavior<MyCommand, MyCommandResult>));

But it's a lot of headache and has to be automated.

Body:
First off, I'm using Fluent Results in combination with Mediatr and Fluent Validation

I initially followed this article but instead of reinventing the wheel I started using FluentResults in my Fluent Validation pipeline. Basically all responses coming from my CQRS Queries are wrapped in the Result object, this avoids having to work with exceptions as a method of error handeling.

However, I can't get my pipeline to play nice:

public class ValidationPipeline<TRequest, TResponse>
    : IPipelineBehavior<TRequest, TResponse>
    where TResponse : class
    where TRequest : IRequest<TResponse>
{
    private readonly IValidator<TRequest> _compositeValidator;

    public ValidationPipeline(IValidator<TRequest> compositeValidator)
    {
        _compositeValidator = compositeValidator;
    }

    public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)
    {
        var result = await _compositeValidator.ValidateAsync(request, cancellationToken);

        if (!result.IsValid)
        {
            Error error = new Error();
            var responseType = typeof(TResponse);

            foreach (var validationFailure in result.Errors)
            {
                Log.Warning($"{responseType} - {validationFailure.ErrorMessage}");
                error.Reasons.Add(new Error(validationFailure.ErrorMessage));
            }
            // This always returns null instead of a Result with errors in it.
            var f = Result.Fail(error) as TResponse;
            return f;

        }

        return await next();
    }
}

I also have to somehow convert the Result object back to TResponse, where TResponse is always a Result

Any suggestions are greatly appreciated!

Edit:

Autofac integration

    protected override void Load(ContainerBuilder builder)
    {
        var assembly = Assembly.GetExecutingAssembly();

        // MediatR
        builder.AddMediatR(assembly);
        // Register the Command's Validators (Validators based on FluentValidation library)
        builder.RegisterAssemblyTypes(assembly)
            .Where(t => t.IsClosedTypeOf(typeof(IValidator<>)))
            .AsImplementedInterfaces();
        // Register all the Command classes (they implement IRequestHandler) in assembly holding the Commands
        builder.RegisterAssemblyTypes(assembly)
            .AsClosedTypesOf(typeof(IRequestHandler<,>));
        // Register Behavior Pipeline
        builder.RegisterGeneric(typeof(ValidationPipeline<,>)).As(typeof(IPipelineBehavior<,>));

    }


问:
Create a tree structure from a graph
I'm trying to find the right approach to graphing a dataset that contains information on amount of time users typically spend in various locations. Importantly, there are categories and subcategories with increasing levels of granularity to my data (for example, 60% of people are at "home", and of those 40% are in the "living room"). I am aware of TreeMaps which would display the information and relationships I need, but I have been asked to make a "network" visualization of the data.

What I specifically am looking for is a graphing approach in Python that would allow me to visualize my data with the nodes (better yet, the node labels) automatically sized according to the number of users that fall within its category. Importantly, all the child node counts would also be counted in the parent nodes as well (so dendrograms aren't really an option because I need to display information at every branching point).

My data looks somewhat like this (note that some locations get more granular than other):

```<code>| ID | BUILDING | subcat01  | subcat02 |
----------------------------------------
| 00 |  home    | kitchen   | fridge   |
| 01 |  office  | desk      | NaN      |
| 02 |  office  | reception | NaN      |
| 03 |  home    | bedroom   | bed      |
| 04 |  home    | yard      | NaN      |
| 05 |  home    | livingroom| couch    |
| 06 |  office  | conf_room | NaN      |
| 07 | outdoors | NaN       | NaN      |
|... | ...      | ...       | ...      |
</code>```

For a very rough approximation of what I want to produce, see the image below. The important thing is that I'm able to size the nodes according to the sum of their children (or just themselves if its an end node). I will be running lots of iterations with different filters, so I need something that I can easily iterate rather than just manually coding the appearance of each graph.

Any suggestions on which Python libraries might best accomplish this? I've briefly looked into networkX, graph-tool, and etetoolkit, but I'm not sure if any of them have exactly the functionality I'm seeking.

Here's a rough approximation of what I want to produce:

答: Maybe ETE package could help you. ETE is a python package intended, among other stuff, for programmatic tree rendering and visualization.

Title: Create a tree structure from a graph

Body:
I'm trying to find the right approach to graphing a dataset that contains information on amount of time users typically spend in various locations. Importantly, there are categories and subcategories with increasing levels of granularity to my data (for example, 60% of people are at "home", and of those 40% are in the "living room"). I am aware of TreeMaps which would display the information and relationships I need, but I have been asked to make a "network" visualization of the data.

What I specifically am looking for is a graphing approach in Python that would allow me to visualize my data with the nodes (better yet, the node labels) automatically sized according to the number of users that fall within its category. Importantly, all the child node counts would also be counted in the parent nodes as well (so dendrograms aren't really an option because I need to display information at every branching point).

My data looks somewhat like this (note that some locations get more granular than other):

| ID | BUILDING | subcat01  | subcat02 |
----------------------------------------
| 00 |  home    | kitchen   | fridge   |
| 01 |  office  | desk      | NaN      |
| 02 |  office  | reception | NaN      |
| 03 |  home    | bedroom   | bed      |
| 04 |  home    | yard      | NaN      |
| 05 |  home    | livingroom| couch    |
| 06 |  office  | conf_room | NaN      |
| 07 | outdoors | NaN       | NaN      |
|... | ...      | ...       | ...      |

For a very rough approximation of what I want to produce, see the image below. The important thing is that I'm able to size the nodes according to the sum of their children (or just themselves if its an end node). I will be running lots of iterations with different filters, so I need something that I can easily iterate rather than just manually coding the appearance of each graph.

Any suggestions on which Python libraries might best accomplish this? I've briefly looked into networkX, graph-tool, and etetoolkit, but I'm not sure if any of them have exactly the functionality I'm seeking.

Here's a rough approximation of what I want to produce:


问:
FileSystemRights Issues (C#)
I'm fairly new to file systems and permissions/rights access (aka Access Control List, ACL). While coding with regards to ACL, I am not able to set properties I want to the files. I'm unsure if my understanding of FileSystemRights members are wrong, or I'm totally doing the wrong thing. (And I'm spending quite some time on this part already)

What I'd like to do is change the rights of a file, so that it can only be soelly readable AND cannot be edited, renamed, deleted and copied elsewhere.

Using the MSDN's example, here's what I have so far:

```<code>try
{
    //Get current identity
    WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();

    // Add the access control entry to the file.
    AddFileSecurity(filename, self.Name, FileSystemRights.Modify, AccessControlType.Deny);
    AddFileSecurity(filename, self.Name, FileSystemRights.Write, AccessControlType.Deny);
    AddFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Allow);

    // Remove the access control entry from the file.
    RemoveFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Deny);
    RemoveFileSecurity(filename, self.Name, FileSystemRights.Read, AccessControlType.Deny);

    Console.WriteLine("Done.");
}
catch (Exception e)
{
    Console.WriteLine(e);
}
</code>```

My logic is that:

Add Deny Modify rights (Denying .Modify will cause the file to become unreadable)

Add Deny Write rights

Add Allow ReadAndExecute rights

Remove Deny entry on ReadAndExecute (As .Modify denies ReadAndExecute)

Remove Deny entry on Read (As .Modify denies Read)

Am I doing this part correctly? If not, please advise on what should I do to make the file only readable only and not editable, renamable, deletable and copiable. Many thanks in advance!

答: Please explain what it is doing wrong.  The only thing I see that may be an issue is that you're setting the permissions for yourself, but not the other users, or groups.  Perhaps you should iterate through all the groups (admins, users, etc) and disable all but read&execute.  Although I think SYSTEM always has full control of all files.</p>

Title: FileSystemRights Issues (C#)

Body:
I'm fairly new to file systems and permissions/rights access (aka Access Control List, ACL). While coding with regards to ACL, I am not able to set properties I want to the files. I'm unsure if my understanding of FileSystemRights members are wrong, or I'm totally doing the wrong thing. (And I'm spending quite some time on this part already)

What I'd like to do is change the rights of a file, so that it can only be soelly readable AND cannot be edited, renamed, deleted and copied elsewhere.

Using the MSDN's example, here's what I have so far:

try
{
    //Get current identity
    WindowsIdentity self = System.Security.Principal.WindowsIdentity.GetCurrent();

    // Add the access control entry to the file.
    AddFileSecurity(filename, self.Name, FileSystemRights.Modify, AccessControlType.Deny);
    AddFileSecurity(filename, self.Name, FileSystemRights.Write, AccessControlType.Deny);
    AddFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Allow);

    // Remove the access control entry from the file.
    RemoveFileSecurity(filename, self.Name, FileSystemRights.ReadAndExecute, AccessControlType.Deny);
    RemoveFileSecurity(filename, self.Name, FileSystemRights.Read, AccessControlType.Deny);

    Console.WriteLine("Done.");
}
catch (Exception e)
{
    Console.WriteLine(e);
}

My logic is that:

Add Deny Modify rights (Denying .Modify will cause the file to become unreadable)

Add Deny Write rights

Add Allow ReadAndExecute rights

Remove Deny entry on ReadAndExecute (As .Modify denies ReadAndExecute)

Remove Deny entry on Read (As .Modify denies Read)

Am I doing this part correctly? If not, please advise on what should I do to make the file only readable only and not editable, renamable, deletable and copiable. Many thanks in advance!


答:
You could take a multiple of count and get the ranges.

function getRanges(first, to, count) {
    const result = [];
    while (first < to) {
        let last = Math.min(to, (Math.floor(first / count) + 1) * count);
        if (last + 1 === to) last = to;
        result.push({ first, last });
        first = last + 1;
    }
    return result;
}

console.log(getRanges(1, 60, 11));
console.log(getRanges(1, 11, 5));```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.as-console-wrapper { max-height: 100% !important; top: 0; }</code>```

Title: Javascript: return all rangs between two numbers based on a number

Body:
You could take a multiple of count and get the ranges.

function getRanges(first, to, count) {
    const result = [];
    while (first < to) {
        let last = Math.min(to, (Math.floor(first / count) + 1) * count);
        if (last + 1 === to) last = to;
        result.push({ first, last });
        first = last + 1;
    }
    return result;
}

console.log(getRanges(1, 60, 11));
console.log(getRanges(1, 11, 5));

.as-console-wrapper { max-height: 100% !important; top: 0; }


问:
How to change Tailwind CSS background color with Svelte, based on a value unpacked in #each?
I am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:

I generate rows of a table with an #each loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).

My idea was to conditionally render different  tags based on this value. Like this:

```<code>        {#each allLZ as {id, name, mac, status, lastcontact, battery}, i}

        {#if battery > 70}
          <tr class="bg-green-50">
        {:else if battery > 40}
          <tr class="bg-yellow-50">
        {:else }
          <tr class="bg-red-50">
        {/if}
</code>```

But this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.

So is there a good way to change tailwind background color based on a value unpacked in #each?

答:
I think you should change approach for that problem. You could use the class:name element directive.

A class: directive provides a shorter way of toggling a class on an element.

Example

{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}
<tr
  class:bg-red-500={battery < 39}
  class:bg-yellow-500={battery >= 40 && battery < 70}
  class:bg-green-500={ battery >= 70}>

    {name}/{battery}

{/each}
```

repl link

Body:
I am a beginner in both Svelte and Tailwind and want to avoid an XY-Problem, so here is my goal:

I generate rows of a table with an #each loop in Svelte. (6 values per row). I now want to conditionally color the background of this row based on one value (the battery charge).

My idea was to conditionally render different  tags based on this value. Like this:

        {#each allLZ as {id, name, mac, status, lastcontact, battery}, i}

        {#if battery > 70}

        {:else if battery > 40}

        {:else }

        {/if}

But this doesn't work as Svelte wants to see the tags closed to be full elements, not piecemeal code, fair enough.

So is there a good way to change tailwind background color based on a value unpacked in #each?

Body:
I think you should change approach for that problem. You could use the class:name element directive.

A class: directive provides a shorter way of toggling a class on an element.

Example

{#each allLZ as {id, name, mac, status, lastcontact, battery}, i}
<tr
  class:bg-red-500={battery < 39}
  class:bg-yellow-500={battery >= 40 && battery < 70}
  class:bg-green-500={ battery >= 70}>

    <td>{name}/{battery}</td>

</tr>
{/each}

repl link


问:
Provided data source did not match an array, Observable, or DataSource when using web api
I try to put material table using web api data

my response look like :

```<code>{
    "Code": "1",
    "Message": "Role List",
    "Data": [
        {
            "id": 1,
            "name": "Employee"
        },
        {
            "id": 2,
            "name": "Admin"
        }
    ]
}
</code>```

when i try to run code i have this "Provided data source did not match an array, Observable, or DataSource"

my html file:

```<code> <table mat-table [dataSource]="listUsers" class="mat-elevation-z8">
 <ng-container matColumnDef="id">
      <th mat-header-cell *matHeaderCellDef> Id. </th>
      <td mat-cell *matCellDef="let element"> {{element.id}} </td>
    </ng-container>

    <ng-container matColumnDef="name">
      <th mat-header-cell *matHeaderCellDef> Name </th>
      <td mat-cell *matCellDef="let element"> {{element.name}} </td>
    </ng-container>

    <tr mat-header-row *matHeaderRowDef="displayedColumns"></tr>
    <tr mat-row *matRowDef="let row; columns: displayedColumns;"></tr>
  </table>
</code>```

my component.ts file :

```<code>export interface User {   name: string;  id: number;  }const ELEMENT_DATA: User[] = [];

export class ListCompanyComponent implements OnInit
{
  displayedColumns: string[] = ['id', 'name' ];
  dataSource = ELEMENT_DATA;
  listUsers :User[]=[];
  constructor(private CommonService:CommonService){}
  ngOnInit(): void {
  this.getalldata();
 }
 getalldata()
 {
   this.CommonService.listUsers().subscribe(data=>{
   this.listUsers=data;
  })
 }
}
</code>```

my servicefile :

```<code>  listUsers():Observable<User[]>
  {
     return this.http.get<User[]>(this.LURL + 'users')
   }
</code>```

how to overcome this issue..

答:
Your response is consist of Code, Message, and Data, but clearly what you want to pass to the dataSource is the Data part only

So you can modify the getalldata() method and use data.Data instead of data to achieve your goal

{
   this.CommonService.listUsers().subscribe(data=>{
   this.listUsers= data.Data;
  })
```
<p><strong>EDIT:</strong><br />
You need also to change the type for <code>listUsers()</code> to receive <code>any</code> or maybe you can make an interface with your actual response that contains <code>Code</code>, <code>Message</code>, and <code>Data</code> and pass it as the type for your method</p>
<pre class="lang-js prettyprint-override"><code>listUsers():Observable<any>
  {
     return this.http.get<any>(this.LURL + 'users')
   }
</code>```

Body:
I try to put material table using web api data

my response look like :

{
    "Code": "1",
    "Message": "Role List",
    "Data": [
        {
            "id": 1,
            "name": "Employee"
        },
        {
            "id": 2,
            "name": "Admin"
        }
    ]
}

when i try to run code i have this "Provided data source did not match an array, Observable, or DataSource"

my html file:

 <ng-container matColumnDef="id">
       Id.
       {{element.id}}
    </ng-container>

    <ng-container matColumnDef="name">
       Name
       {{element.name}}
    </ng-container>

my component.ts file :

export interface User {   name: string;  id: number;  }const ELEMENT_DATA: User[] = [];

export class ListCompanyComponent implements OnInit
{
  displayedColumns: string[] = ['id', 'name' ];
  dataSource = ELEMENT_DATA;
  listUsers :User[]=[];
  constructor(private CommonService:CommonService){}
  ngOnInit(): void {
  this.getalldata();
 }
 getalldata()
 {
   this.CommonService.listUsers().subscribe(data=>{
   this.listUsers=data;
  })
 }
}

my servicefile :

  listUsers():Observable<User[]>
  {
     return this.http.get<User[]>(this.LURL + 'users')
   }

how to overcome this issue..

Body:
Your response is consist of Code, Message, and Data, but clearly what you want to pass to the dataSource is the Data part only

So you can modify the getalldata() method and use data.Data instead of data to achieve your goal

{
   this.CommonService.listUsers().subscribe(data=>{
   this.listUsers= data.Data;
  })

EDIT:

You need also to change the type for listUsers() to receive any or maybe you can make an interface with your actual response that contains Code, Message, and Data and pass it as the type for your method

listUsers():Observable<any>
  {
     return this.http.get<any>(this.LURL + 'users')
   }


问:
live-server gives "Change detected" but chrome console doesn't, how do I make my change auto loaded?
I'm trying to have live-server auto reload the code once I save my change.

I've installed live-server globally and created a folder test and put 3 files in there

```<code>mkdir test
cd test
touch index.html main.js .live-server.json
live-server
</code>```

Here's the contents of index.html

```<code><script src='main.js'></script>
</code>```

Here's the contents of main.js

```<code>console.log('hi');
</code>```

and I got 'hi' in my chrome dev console.

When I changed the code, I got

Change detected /Users/ubuntu/dev/test/main.js

However, my chrome dev console didn't yield that change. I have to refresh the page manually. How do I make my change auto loaded?

答:
Firstly update your browser and live-server package!
Try to re-run your live-server without .live-server.json (remove it !) file because as we can read in docs:

If a file ~/.live-server.json exists it will be loaded and used as
default options for live-server on the command line. See "Usage from
node" for option names.

You need to add to your index.html boilerplate ! Now it should works like a charm! ;-)

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>
</code>```

You can also try run live-server with different port like so:

```<code>live-server --port=5000
</code>```

Body:
I'm trying to have live-server auto reload the code once I save my change.

I've installed live-server globally and created a folder test and put 3 files in there

mkdir test
cd test
touch index.html main.js .live-server.json
live-server

Here's the contents of index.html

Here's the contents of main.js

console.log('hi');

and I got 'hi' in my chrome dev console.

When I changed the code, I got

Change detected /Users/ubuntu/dev/test/main.js

However, my chrome dev console didn't yield that change. I have to refresh the page manually. How do I make my change auto loaded?

Body:
Firstly update your browser and live-server package!
Try to re-run your live-server without .live-server.json (remove it !) file because as we can read in docs:

If a file ~/.live-server.json exists it will be loaded and used as
default options for live-server on the command line. See "Usage from
node" for option names.

You need to add to your index.html boilerplate ! Now it should works like a charm! ;-)

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script src="main.js"></script>
  </body>
</html>

You can also try run live-server with different port like so:

live-server --port=5000


问:
Create an editable wpf treeview item
I'm checking this page and I like the only answer there is.

Editable WPF treeview item on doubleclick? (with styles?)

But I don't like the idea to use c# lines, Might there be a possible to write that code using XAML?

答: You can use CheckBox in the XAML and using its IsChecked property change the Style to the Editable mode</p>

Title: Create an editable wpf treeview item


问:
How to set a "Custom" sensitivity label?
I would like to set the mail item "Custom" sensitivity label.

I looked at: OlSensitivity enumeration (Outlook), which showed the standard 4 label values, like: Outmail.Sensitivity = OlSensitivity.olConfidential for the confidential label.

In my case, there are more than 5 labels -> sensitivity option with custom label name. How can I retrieve it based on custom label name in Excel VBA?

答:
I also faced similar kind of issue where the company have their own Sensitivity Labels. We can't select with them with default numbering.

I came up with the solution by using the SendKeys in VBA.

The trick is not to use the .Send, instead use .Display. So once you have display of the draft email then see the keyboard hits to reach out to the custom Sensitivity.
As I am working in MS Office 365, the keyboard shortcuts to select my Custom sensitivity is below:

```<code>SendKeys "%h"           'Keystroke for ALT + h
SendKeys "y"            'Keystroke for selecting the Sensitivity
SendKeys "{TAB}{ENTER}%s"      'Keystroke for selecting the organization custom sensitivity and %s is for ALT + s to send the email
</code>```

Sample code

```<code>With objMail
    .To = strEmail
    .Body = strBody
    .Subject = strSubject
    .Display
SendKeys "%h"
SendKeys "y"
SendKeys "{TAB}{ENTER}%s"

End With
</code>```

Also check the different codes for SendKeys from the below link:

https://learn.microsoft.com/en-us/office/vba/api/excel.application.sendkeys

Body:
I also faced similar kind of issue where the company have their own Sensitivity Labels. We can't select with them with default numbering.

I came up with the solution by using the SendKeys in VBA.

The trick is not to use the .Send, instead use .Display. So once you have display of the draft email then see the keyboard hits to reach out to the custom Sensitivity.
As I am working in MS Office 365, the keyboard shortcuts to select my Custom sensitivity is below:

SendKeys "%h"           'Keystroke for ALT + h
SendKeys "y"            'Keystroke for selecting the Sensitivity
SendKeys "{TAB}{ENTER}%s"      'Keystroke for selecting the organization custom sensitivity and %s is for ALT + s to send the email

Sample code

With objMail
    .To = strEmail
    .Body = strBody
    .Subject = strSubject
    .Display
SendKeys "%h"
SendKeys "y"
SendKeys "{TAB}{ENTER}%s"

End With

Also check the different codes for SendKeys from the below link:

https://learn.microsoft.com/en-us/office/vba/api/excel.application.sendkeys


问:
How to out of while and for loop combined
I am trying to write a code that is capturing number 3. using while loop as the condition, so that the for statement will be the evaluation condition of $x, of the while loop statement, and by the same time, using if statement to evaluate the value of $x=3 and so it can echo 'three..'; . please enlighten me. thank you

```<code><?php
$x = 0;
$y = 5;

while ($x <= $y) {
    for ($z = 0; $z < 3; $z++) {
        if ($x = 3) {
            echo 'three..' . "\n";
        }
    }
    $y++;
}
</code>```

Body:
I am trying to write a code that is capturing number 3. using while loop as the condition, so that the for statement will be the evaluation condition of $x, of the while loop statement, and by the same time, using if statement to evaluate the value of $x=3 and so it can echo 'three..'; . please enlighten me. thank you

<?php
$x = 0;
$y = 5;

while ($x <= $y) {
    for ($z = 0; $z < 3; $z++) {
        if ($x = 3) {
            echo 'three..' . "\n";
        }
    }
    $y++;
}

Body:
<?php
$x = 0;
$y = 5;

while ($x <= $y) {
    for ($z = 0; $z < 3; $z++) {
        echo $z;
    }
        if ($x == 3) {
            echo 'three..' . "\n";
        }
    $x++;
}


问:
How to read terminal output of nc utility?
I need to run a command like

```<code>nc 123.123.123.123 1111
</code>```

in Bash. The service I'm connecting to will send occasional messages and expect a response in the terminal. After hitting enter, it will send another prompt and expect another response.

I want to automate this in Python, but I don't know how to read the output of the nc command. I need to continually re-read from the terminal after submitting the previous reply.

Is there an easy way to point Python at a specific terminal and say "get the contents of this"?

答:
You can open nc from python in subprocess and pipe stdin, stdout and stderr.

I've put together example, which will read from nc server and consume messages. Just for demonstration I've added some primitive protocol handling. When b"OK\n" is received, our client respond with b"Got it!\n". When b"EXIT\n" is received, client close.

Please make sure to run Your nc server with -k parameter, to keep server alive after client closes connection.

```<code>nc -lk 123.123.123.123 1111
</code>```

Here is full example:

```<code>import subprocess

# Open new subprocess and run nc in a shell, pipe stdin, stdout and stderr
proc = subprocess.Popen(["nc 123.123.123.123 1111"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
while True:
    response = proc.stdout.readline()
    if response == b"OK\n":
        # Write back to the process
        proc.stdin.write(b"Got it!\n")
        proc.stdin.flush()
    elif response == b"EXIT\n":
        print("Client is closing")
        break
    else:
        print(response)

# Terminate process
proc.terminate()
</code>```

Body:
I need to run a command like

nc 123.123.123.123 1111

in Bash. The service I'm connecting to will send occasional messages and expect a response in the terminal. After hitting enter, it will send another prompt and expect another response.

I want to automate this in Python, but I don't know how to read the output of the nc command. I need to continually re-read from the terminal after submitting the previous reply.

Is there an easy way to point Python at a specific terminal and say "get the contents of this"?

Body:
You can open nc from python in subprocess and pipe stdin, stdout and stderr.

I've put together example, which will read from nc server and consume messages. Just for demonstration I've added some primitive protocol handling. When b"OK\n" is received, our client respond with b"Got it!\n". When b"EXIT\n" is received, client close.

Please make sure to run Your nc server with -k parameter, to keep server alive after client closes connection.

nc -lk 123.123.123.123 1111

Here is full example:

import subprocess

# Open new subprocess and run nc in a shell, pipe stdin, stdout and stderr
proc = subprocess.Popen(["nc 123.123.123.123 1111"], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE)
while True:
    response = proc.stdout.readline()
    if response == b"OK\n":
        # Write back to the process
        proc.stdin.write(b"Got it!\n")
        proc.stdin.flush()
    elif response == b"EXIT\n":
        print("Client is closing")
        break
    else:
        print(response)

# Terminate process
proc.terminate()


问:
Python. IOError: [Errno 13] Permission denied: when i'm copying file
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:

```<code>>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
  File "C:\Python27\lib\shutil.py", line 82, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'
</code>```

What's the problem?

答:
Visual Studio 2019

Solution : Administrator provided full Access to this folder "C:\ProgramData\Docker"
it is working.

ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'
[ERROR]: Failed to run 'iotedgehubdev start -d "C:\Users\radhe.sah\source\repos\testing\AzureIotEdgeApp1\config\deployment.windows-amd64.json" -v' with error: WARNING! Using --password via the CLI is insecure. Use --password-stdin.
ERROR: File IO error seen copying files to volume: edgehubdev. Errno: 13, Error Permission denied : [Errno 13] Permission denied: 'C:\ProgramData\Docker\volumes\edgehubdev\_data\edge-chain-ca.cert.pem'

Body:
I have two folders: In, Out - it is not system folder on disk D: - Windows 7. Out contain "myfile.txt" I run the following command in python:

>>> shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )

Traceback (most recent call last):
  File "<pyshell#39>", line 1, in <module>
    shutil.copyfile( r"d:\Out\myfile.txt", r"D:\In" )
  File "C:\Python27\lib\shutil.py", line 82, in copyfile
    with open(dst, 'wb') as fdst:
IOError: [Errno 13] Permission denied: 'D:\\In'

What's the problem?


问:
vite replace an import statement
I have a vue file

```<code>// myComponent.vue
import { something } from 'some-module'
...
</code>```

I want to replace this import statement into

```<code>import { something } from '@/utils/myModule'
</code>```

in case when running the vitest command.
Do we have some plugin which I can use to get the above result?

答:
Ok its working</p>
```<code>// vite.config.js
    alias: [
          {
            find: /some-module/,
            replacement: fileURLToPath(new URL('./src/utils/someModuleFake.ts', import.meta.url)),
          },
          {
            find: '@',
            replacement: fileURLToPath(new URL('./src', import.meta.url))
          },
        ],
</code>```

Title: vite replace an import statement

Body:
I have a vue file

// myComponent.vue
import { something } from 'some-module'
...

I want to replace this import statement into

import { something } from '@/utils/myModule'

in case when running the vitest command.
Do we have some plugin which I can use to get the above result?

Body:
Ok its working

// vite.config.js
    alias: [
          {
            find: /some-module/,
            replacement: fileURLToPath(new URL('./src/utils/someModuleFake.ts', import.meta.url)),
          },
          {
            find: '@',
            replacement: fileURLToPath(new URL('./src', import.meta.url))
          },
        ],


问:
How to call a method in other class/object in Scala using azure Data bricks Notebooks
I have below similar scenario in local Scala IDE. I was trying to replicate same in Azure Databricks Notebook. I was not able to do it.

Scenario Explained: I have one main class. I am calling methods in other object in to main class
using Threading to execute parallelly.

I have tried by putting each object in different notebook and tried in data bricks. But able to do.

Main Class

```<code>object cli_main {

   def main(args: Array[String]): Unit = {

    var ModuleOneStart = "Y"
    var ModuleTwoStart = "Y"

    var ResultOne="0"
    var ResultTwo="0"

    var a=100
    var b=200

    val ThreadOne = new Thread {
        override def run(): Unit = {
            ResultOne = cli_cpm.cpm_process(a, b)
          }
        }
    val ThreadTwo = new Thread {
         override def run(): Unit = {
             ResultTwo = cli_res.res_process(a, b)
            }
        }

    if (ModuleOneStart == "Y") {
          ThreadOne.start()
        }
    if (ModuleTwoStart == "Y") {
            ThreadTwo.start()
        }

    }

}
</code>```

Method-1

```<code>object cli_cpm extends Thread {
    def cpm_process(a: Int, b: Int): String = {

    val mul=a*b

    if(mul>100){
    "1"  //return
    }
    "0"//return
    }
}
</code>```

Method-2

```<code>object cli_res extends Thread {
    def res_process(a: Int, b: Int): String = {

    val sum=a+b

    if(sum>10){
    "1"  //return
    }
    "0"//return
    }
}
</code>```

I know  %run  and dbutils.notebook.run are used to call a notebook.

Any different way to implement above scenario in Azure Databricks.

答:
You can run one notebook into another using two ways:

%run

%run notebook1.ipynb

Databricks Utilities ( dbutils )

dbutils.notebook.run()

Other than these two options you can run multiple notebooks at the same time by using standard Scala and Python constructs such as Threads (Scala, Python) and Futures (Scala, Python).

Follow databricks official documentation

Body:
I have below similar scenario in local Scala IDE. I was trying to replicate same in Azure Databricks Notebook. I was not able to do it.

Scenario Explained: I have one main class. I am calling methods in other object in to main class
using Threading to execute parallelly.

I have tried by putting each object in different notebook and tried in data bricks. But able to do.

Main Class

object cli_main {

   def main(args: Array[String]): Unit = {

    var ModuleOneStart = "Y"
    var ModuleTwoStart = "Y"

    var ResultOne="0"
    var ResultTwo="0"

    var a=100
    var b=200

    val ThreadOne = new Thread {
        override def run(): Unit = {
            ResultOne = cli_cpm.cpm_process(a, b)
          }
        }
    val ThreadTwo = new Thread {
         override def run(): Unit = {
             ResultTwo = cli_res.res_process(a, b)
            }
        }

    if (ModuleOneStart == "Y") {
          ThreadOne.start()
        }
    if (ModuleTwoStart == "Y") {
            ThreadTwo.start()
        }

    }

}

Method-1

object cli_cpm extends Thread {
    def cpm_process(a: Int, b: Int): String = {

    val mul=a*b

    if(mul>100){
    "1"  //return
    }
    "0"//return
    }
}

Method-2

object cli_res extends Thread {
    def res_process(a: Int, b: Int): String = {

    val sum=a+b

    if(sum>10){
    "1"  //return
    }
    "0"//return
    }
}

I know  %run  and dbutils.notebook.run are used to call a notebook.

Any different way to implement above scenario in Azure Databricks.


问:
How to configure Azure APIM policy to send emails in case 401 errors
I have a requirement to send alerts via emails in case if an API fails with 401 (Unauthorized access) errors. These apis use api-key for authentication.
I tried to trigger a logic app from the on-error section of the Azure APIM policy but that didn't work. Is there a way to trigger an email (via logic app or any other means) in case of a 401 error?

Please note: I have already configured Azure Monitor alerts for 401 errors which notify us when the number of 401 errors exceed a threshold value. However, for some of our critical APIs we want to get alerted as soon as there is an unauthorised access error.

答: Just attach App Insights to your APIM and create a metric based alert. No need to setup logic apps or write up your own query.</p>


问:
adding sha1 in firebase app fails with error
I am migrating my project from Digits to Firebase. In this process, I need to create an app in Firebase and add SHA-1 of the release build. When I trying to add SHA-1, it gives the following error:

An error occurred when attempting to modify an Android certificate fingerprint. Please try again later.

Found the following two similar question here. Both say that there should be an already existing app on Google API project of Firebase with the same SHA-1. I don't have any other app with the same SHA-1.

Adding sha1 key fails with error

Can android certificate fingerprint sha1 use in firebase and Google Place API?

Need help to resolve this issue.

答:
Update Date : 08 Fab 2022

I too got the same problem and found a solution that If you want to add new SHA1 key in your firebase app then you have to delete one of the previously added SHA1 key.

This solution worked for me


问:
Running bazel query without downloading external dependencies
Given a rather big repository built with bazel and tons of third party dependencies in multiple languages (including heavy docker containers), I have the following problem:

running Bazel queries triggers the downloading of many of these dependencies, resulting in slow query performance. Hence, the question:

Is there a way to run bazel query without having to download the dependencies?

Typical query: bazel query 'kind("source file", deps(//...) except deps(//3rdparty/...))

I'm aware of the caching options, which I mostly use, but depending on the languages, things can still be slow.

答:
After asking on Bazel's Slack channel, the response (from Sahin Yort) is not encouraging:

I don’t believe that’s possible due to nature of workspace files. loads from a workspace leads to fetch of the given workspace because has to expand the workspaces in order to know their targets.  at that point, it is up to the repository rule to fetch whatever it needs to fetch eagerly or  lazily.   workspace rules usually expand BUILD files using various patterns. eg running a executable or using expand_template.  i have little faith in that it is possible to get what you want.

I'll be looking into other ways to speed things up: a likely culprit for the slowness is probably the action/analysis cache being invalidated due to some flags changing.


问:
Error in Internet Explorer: ` Invalid character
I am testing an app on IE.

I'm having the problem reading the ` character when the (dynamic) table is read.

list.forEach(item=>{
  let child = document.createElement("tr");
  child.innerHTML = `<td>${item.id}</td><td>${item.name}</td><td>${item.password}</td><td>${item.email}</td><td>${item.sex}</td><td>${item.country}</td><td>-</td><td>-</td>`;
  table.appendChild(child);
})```

If it can be fixed, how can I do this?

答:
IE supports ES5.

You will have to rewrite your code.

```<code>list.forEach(item=>{
  let child = document.createElement("tr");
  child.innerHTML = '<td>'+item.id+'</td><td>'+item.name+'</td><td>'+item.password+'</td><td>'+item.email+'</td><td>'+item.sex+'</td><td>'+item.country+'</td><td>-</td><td>-</td>';
  table.appendChild(child);
})
</code>```

Body:
I am testing an app on IE.

I'm having the problem reading the ` character when the (dynamic) table is read.

list.forEach(item=>{
  let child = document.createElement("tr");
  child.innerHTML = `<td>${item.id}</td><td>${item.name}</td><td>${item.password}</td><td>${item.email}</td><td>${item.sex}</td><td>${item.country}</td><td>-</td><td>-</td>`;
  table.appendChild(child);
})

If it can be fixed, how can I do this?

Body:
IE supports ES5.

You will have to rewrite your code.

list.forEach(item=>{
  let child = document.createElement("tr");
  child.innerHTML = '<td>'+item.id+'</td><td>'+item.name+'</td><td>'+item.password+'</td><td>'+item.email+'</td><td>'+item.sex+'</td><td>'+item.country+'</td><td>-</td><td>-</td>';
  table.appendChild(child);
})


问:
How to get InteractiveViewer image pixel coordinate in flutter?
i want to get pixel coordinate when i tapped the screen, i use interactiveView and GestureDetect in Fultter, i am so confused about the matrix transform , i am new to App develop, please give some advice if you could, very appraciate, Below is my code, which now i can zoom the image, but i can't calculate the coorect pixel coordiante when i click the screen. and since i have no idea how to calculate the ratio between pixel distance<->screen distance, i was stucked there. please help me.

What i am doing is i need pick a pixel position from the image, so i need zoom image first to get precise position,that's why i need ineractiveViewer . and at the same time i need record the gesture behavior, to monitor the behavior, then i wrapper InteractiveView to GestureDetect.

it look like this for now:
enter image description here

```<code>Widget mapView() {
    double offsetX, offsetY;
    return Stack(
      children: <Widget>[
        Positioned.fill(

          child:
          GestureDetector(
            onTapUp: (TapUpDetails details) {
              offsetX = details.localPosition.dx;
              offsetY = details.localPosition.dy;
              // print(
                  //"tap local pos, X: ${details.localPosition.dx}, Y: ${details.localPosition.dy}");
              // print(
              //     "tap global pos, X: ${details.globalPosition.dx}, Y: ${details.globalPosition.dy}");
              _childWasTappedAt = _transformationController!.toScene(details.localPosition);
              // print(
              //     "child pos to scene , X: ${_childWasTappedAt!.dx}, Y: ${_childWasTappedAt!.dy}");
              //double origin_scree_pixel_radio = 17;

              MediaQueryData queryData;
              queryData = MediaQuery.of(context);

              double pixel_ratio = queryData.devicePixelRatio;

              double scree_pixel_radio =  (1.0 / _cur_scale_value!)*pixel_ratio;

              double trans_x = -1.0 * _transformationController!.value.getTranslation().x;

              double local_offset_x = offsetX;

              double pixel_x = trans_x + local_offset_x * scree_pixel_radio;

              print("scale: ${_cur_scale_value}");
              print("radio: ${pixel_ratio}");
              print("view tran x: ${trans_x}");
              print("offset x: ${local_offset_x}");

              //print("image_Info: ${_image_info.toString()}");

              print("Pixel X: ${pixel_x}");

            },
            child:
            InteractiveViewer(
              transformationController: _transformationController,
              minScale: 0.001,
              maxScale: 200.0,
              constrained: false,
              child: Image.asset(
                imagePath,
                filterQuality:FilterQuality.high,
              ),
              onInteractionEnd: (ScaleEndDetails details) {
                _cur_scale_value = _transformationController!.value.getMaxScaleOnAxis();
                //print("current scale: ${_cur_scale_value}");
              },
              onInteractionUpdate: (ScaleUpdateDetails details){
                //print('onInteractionUpdate----' + details.toString());
              },
            ),
          ),
        ),
        Positioned(
          top: 0.0,//_vehicle_y,
          left: 0.0,//_vehicle_x,
          child: Icon(Icons.favorite, color: Colors.red,),
        ),
      ],
    );
  }
</code>```

答:
Use this onInteractionUpdate method to get Coordinates. use also use different methods.

Vist This site for more info:-
https://api.flutter.dev/flutter/widgets/InteractiveViewer/onInteractionUpdate.html

https://api.flutter.dev/flutter/gestures/ScaleStartDetails/localFocalPoint.html

```<code>Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InteractiveViewer(
          onInteractionUpdate: (v) {
            print(v.localFocalPoint.dx);
            print(v.localFocalPoint.dy);
          },
          child: Image.network(
            "https://images.unsplash.com/photo-1643832678771-fdd9ed7638ae?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDd8Ym84alFLVGFFMFl8fGVufDB8fHx8&auto=format&fit=crop&w=2400&q=60",
            fit: BoxFit.fitHeight,
          ),
        ),
      ),
    );
  }
</code>```

Body:
i want to get pixel coordinate when i tapped the screen, i use interactiveView and GestureDetect in Fultter, i am so confused about the matrix transform , i am new to App develop, please give some advice if you could, very appraciate, Below is my code, which now i can zoom the image, but i can't calculate the coorect pixel coordiante when i click the screen. and since i have no idea how to calculate the ratio between pixel distance<->screen distance, i was stucked there. please help me.

What i am doing is i need pick a pixel position from the image, so i need zoom image first to get precise position,that's why i need ineractiveViewer . and at the same time i need record the gesture behavior, to monitor the behavior, then i wrapper InteractiveView to GestureDetect.

it look like this for now:
enter image description here

Widget mapView() {
    double offsetX, offsetY;
    return Stack(
      children: <Widget>[
        Positioned.fill(

          child:
          GestureDetector(
            onTapUp: (TapUpDetails details) {
              offsetX = details.localPosition.dx;
              offsetY = details.localPosition.dy;
              // print(
                  //"tap local pos, X: ${details.localPosition.dx}, Y: ${details.localPosition.dy}");
              // print(
              //     "tap global pos, X: ${details.globalPosition.dx}, Y: ${details.globalPosition.dy}");
              _childWasTappedAt = _transformationController!.toScene(details.localPosition);
              // print(
              //     "child pos to scene , X: ${_childWasTappedAt!.dx}, Y: ${_childWasTappedAt!.dy}");
              //double origin_scree_pixel_radio = 17;

              MediaQueryData queryData;
              queryData = MediaQuery.of(context);

              double pixel_ratio = queryData.devicePixelRatio;

              double scree_pixel_radio =  (1.0 / _cur_scale_value!)*pixel_ratio;

              double trans_x = -1.0 * _transformationController!.value.getTranslation().x;

              double local_offset_x = offsetX;

              double pixel_x = trans_x + local_offset_x * scree_pixel_radio;

              print("scale: ${_cur_scale_value}");
              print("radio: ${pixel_ratio}");
              print("view tran x: ${trans_x}");
              print("offset x: ${local_offset_x}");

              //print("image_Info: ${_image_info.toString()}");

              print("Pixel X: ${pixel_x}");

            },
            child:
            InteractiveViewer(
              transformationController: _transformationController,
              minScale: 0.001,
              maxScale: 200.0,
              constrained: false,
              child: Image.asset(
                imagePath,
                filterQuality:FilterQuality.high,
              ),
              onInteractionEnd: (ScaleEndDetails details) {
                _cur_scale_value = _transformationController!.value.getMaxScaleOnAxis();
                //print("current scale: ${_cur_scale_value}");
              },
              onInteractionUpdate: (ScaleUpdateDetails details){
                //print('onInteractionUpdate----' + details.toString());
              },
            ),
          ),
        ),
        Positioned(
          top: 0.0,//_vehicle_y,
          left: 0.0,//_vehicle_x,
          child: Icon(Icons.favorite, color: Colors.red,),
        ),
      ],
    );
  }

Body:
Use this onInteractionUpdate method to get Coordinates. use also use different methods.

Vist This site for more info:-
https://api.flutter.dev/flutter/widgets/InteractiveViewer/onInteractionUpdate.html

https://api.flutter.dev/flutter/gestures/ScaleStartDetails/localFocalPoint.html

Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: InteractiveViewer(
          onInteractionUpdate: (v) {
            print(v.localFocalPoint.dx);
            print(v.localFocalPoint.dy);
          },
          child: Image.network(
            "https://images.unsplash.com/photo-1643832678771-fdd9ed7638ae?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDd8Ym84alFLVGFFMFl8fGVufDB8fHx8&auto=format&fit=crop&w=2400&q=60",
            fit: BoxFit.fitHeight,
          ),
        ),
      ),
    );
  }


问:
How to populate mongoose with obejectId which is defined as Number?
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

```<code>const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');
</code>```

Second Schema:

```<code>const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');
</code>```

Here is my code:

```<code>const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);
</code>```

Here is the output:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Here is the output without populate:

```<code>[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]
</code>```

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

答:
try this:</p>
```<code>User.findById(req.user).populate({
    path: 'requests',
    populate: {
        path:  'profileId',
        model: 'Profile'
    }
  })
</code>```

Body:
I'm trying to populate my user requests.profileId but it returns only nulls.

I have the following schemas:

First Schema:

const profileSchema = new mongoose.Schema({
  _id: { type: Number }, //<- _id is defined as a number which represents mobile number (easier for me to handle)
  first: { type: String },
  second: { type: String },
});

module.exports = mongoose.model('Profile', profileSchema, 'profiles');

Second Schema:

const userSchema = new mongoose.Schema({
  firstName: { type: String },
  lastName: { type: String },
  requests: [
    {
      profileId: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Profile',
      },
      requestTime: { type: Date, default: Date.now },
    },
  ],
});

module.exports = mongoose.model('User', userSchema, 'users');

Here is my code:

const user = await User.findById(req.user).populate('requests.profileId');
console.log(user.requests);

Here is the output:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: null,
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: null,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: null,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: null,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Here is the output without populate:

[
  {
    _id: 6201633869648e2b74c00a10,
    profileId: 393732353235303134343330, //<- typeof profileId is obeject
    requestTime: 2022-02-07T18:21:44.722Z
  },
  {
    _id: 6201633b69648e2b74c00a11,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-07T18:21:47.238Z
  },
  {
    _id: 620238f9d2b5dd3dee6c41a2,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:33:45.176Z
  },
  {
    _id: 620239253220343dfd7cfdd9,
    profileId: 393732353435353333313131,
    requestTime: 2022-02-08T09:34:29.780Z
  }
]

Currently Profile.findById(mobileNumber) works fine.

Any ideas what went wrong?

Will greatly appreciate your assistance.

Thanks in advance :)

Body:
try this:

User.findById(req.user).populate({
    path: 'requests',
    populate: {
        path:  'profileId',
        model: 'Profile'
    }
  })


问:
Can we create iframe apps via the api?
I am adding app to fan page as a tab.I wanted to create many tab to my facebook page.Does I need to create diffrent app for that.Can we create app through code or any api?</p>

答:
An app can only be added one time to any given page as a tab.  So you'll need to create an app for each tab you'd like to display.

At this time there is no current method of creating an app via code.  There was previously a method with the old connect product but it seems to have become obsolete.

Title: Can we create iframe apps via the api?


问:
JavaScript domain read cookie from subdomain
I have a simple question - is there any way to read subdomain cookie on main domain by JavaScript?
For example: I set cookie 'hello' with value '2' in subdomain yeah.something.com and after that I want to read it on something.com.
I tried to find answer for that but I found only information how to set cookie on subdomain by creating it on domain.</p>

答:
An ancient question, but better to have it answered
You can do it by creating a cookie on the domain with a dot on the start to support reading from all subdomains and from the main domain as well:

document.cookie = "_id=MY_ID;domain=.example.com;expires=;SameSite=none;Secure";
```

Hope it will help other lookers like me :)

Body:
An ancient question, but better to have it answered
You can do it by creating a cookie on the domain with a dot on the start to support reading from all subdomains and from the main domain as well:

document.cookie = "_id=MY_ID;domain=.example.com;expires=;SameSite=none;Secure";

Hope it will help other lookers like me :)


问:
ActiveRecord Query Union
I've written a couple of complex queries (at least to me) with Ruby on Rail's query interface:

```<code>watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})
</code>```

Both of these queries work fine by themselves.  Both return Post objects.  I would like to combine these posts into a single ActiveRelation.  Since there could be hundreds of thousands of posts at some point, this needs to be done at the database level.  If it were a MySQL query, I could simply user the UNION operator.  Does anybody know if I can do something similar with RoR's query interface?

答:
When we add UNION to the scopes, it breaks at time due to order_by clause added before the UNION.

So I changed it in a way to give it a UNION effect.

```<code>module UnionScope
  def self.included(base)
    base.send(:extend, ClassMethods)
  end

  module ClassMethods
    def union_scope(*scopes)
      id_column = "#{table_name}.id"
      sub_query = scopes.map { |s| s.pluck(:id) }.flatten
      where("#{id_column} IN (?)", sub_query)
    end
  end
end
</code>```

And then use it like this in any model

```<code>class Model
  include UnionScope
  scope :union_of_scopeA_scopeB, -> { union_scope(scopeA, scopeB) }
end
</code>```

Title: ActiveRecord Query Union

Body:
I've written a couple of complex queries (at least to me) with Ruby on Rail's query interface:

watched_news_posts = Post.joins(:news => :watched).where(:watched => {:user_id => id})
watched_topic_posts = Post.joins(:post_topic_relationships => {:topic => :watched}).where(:watched => {:user_id => id})

Both of these queries work fine by themselves.  Both return Post objects.  I would like to combine these posts into a single ActiveRelation.  Since there could be hundreds of thousands of posts at some point, this needs to be done at the database level.  If it were a MySQL query, I could simply user the UNION operator.  Does anybody know if I can do something similar with RoR's query interface?

Body:
When we add UNION to the scopes, it breaks at time due to order_by clause added before the UNION.

So I changed it in a way to give it a UNION effect.

module UnionScope
  def self.included(base)
    base.send(:extend, ClassMethods)
  end

  module ClassMethods
    def union_scope(*scopes)
      id_column = "#{table_name}.id"
      sub_query = scopes.map { |s| s.pluck(:id) }.flatten
      where("#{id_column} IN (?)", sub_query)
    end
  end
end

And then use it like this in any model

class Model
  include UnionScope
  scope :union_of_scopeA_scopeB, -> { union_scope(scopeA, scopeB) }
end


问:
How to use a loop then calculate the sum of a list?
I need to write a function "sum_reciprocals()" which takes 1 input argument, a positive integer "n", and returns 1 output value, the sum of the reciprocals of all integers from 1 to n (inclusive).
The result should be returned as a floating point number, and rounded to 5 decimal places.

here is my code

```<code>def sum_reciprocals(n):
    x = [1]
    n = 10000
    for i in range(2,n+1):
        x.append(x[i-2]+1/x[i-1])
    sum_reciprocals = round(sum(x))
    return sum_reciprocals
</code>```

But it says that "IndexError: list index out of range" on my fifth line.

答: Your list only has one element, but in the first iteration of the for loop you try to access the 0-th and the 1st element :)</p>

Body:
I need to write a function "sum_reciprocals()" which takes 1 input argument, a positive integer "n", and returns 1 output value, the sum of the reciprocals of all integers from 1 to n (inclusive).
The result should be returned as a floating point number, and rounded to 5 decimal places.

here is my code

def sum_reciprocals(n):
    x = [1]
    n = 10000
    for i in range(2,n+1):
        x.append(x[i-2]+1/x[i-1])
    sum_reciprocals = round(sum(x))
    return sum_reciprocals

But it says that "IndexError: list index out of range" on my fifth line.


问:
Figsize in pixels in Matplotlib
I am trying to make two side by side graphs take up half my screen (resolution of 1600). Matplotlib defines figure size in inches and dots per inch. How can I use these to make each 810 pixels and is there any difference between the two?</p>

```<code>fig, ax = plt.subplots(figsize=(8,4), dpi=100)
fig, ax = plt.subplots(figsize=(4,2), dpi=200)
</code>```

答:
The product of your figure size and the resolution of the figure in dots-per-inch needs to match the desired width and height of the image. At a screen resolution of e.g. 1600 × 900 pixels an image should be 800 pixels wide to take up half your screen, so this looks good:

```<code>fig, ax = plt.subplots(figsize=(8, 4), dpi=100)
</code>```

“The native figure size unit in Matplotlib is inches, deriving from print industry standards.” You can, however, specify your figures in other units like centimeters or pixels, see Matplotlib documentation: Figure size in different units, so this should also work for you:

```<code>fig, ax = plt.subplots(figsize=(800*px, 400*px))
</code>```

Title: Figsize in pixels in Matplotlib

Body:
I am trying to make two side by side graphs take up half my screen (resolution of 1600). Matplotlib defines figure size in inches and dots per inch. How can I use these to make each 810 pixels and is there any difference between the two?

fig, ax = plt.subplots(figsize=(8,4), dpi=100)
fig, ax = plt.subplots(figsize=(4,2), dpi=200)

Body:
The product of your figure size and the resolution of the figure in dots-per-inch needs to match the desired width and height of the image. At a screen resolution of e.g. 1600 × 900 pixels an image should be 800 pixels wide to take up half your screen, so this looks good:

fig, ax = plt.subplots(figsize=(8, 4), dpi=100)

“The native figure size unit in Matplotlib is inches, deriving from print industry standards.” You can, however, specify your figures in other units like centimeters or pixels, see Matplotlib documentation: Figure size in different units, so this should also work for you:

fig, ax = plt.subplots(figsize=(800*px, 400*px))


问:
How to dynamically change the scale/ticks of y axis in plotly charts upon zooming in?
I am trying to make a candle stick chart using plotly. I am using stock data spanning over 10 years. Due to this the candles appear very small as the y axis has a large scale. However if I zoom into a smaller time period (lets say any 1 month in the 10 years) I want the y axis scale to change so that the candle looks big. Below is my code:

```<code>df_stockData = pdr.DataReader('TSLA', data_source='yahoo', start='2011-11-04', end='2021-11-04')

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_width=[0.25, 0.75])
fig.add_trace(go.Candlestick(
    x=df_stockData.index,
    open=df_stockData['Open'],
    high=df_stockData['High'],
    low=df_stockData['Low'],
    close=df_stockData['Close'],
    increasing_line_color='green',
    decreasing_line_color='red',
    showlegend=False
), row=1, col=1)
fig.add_trace(go.Scatter(
    x=df_stockData.index,
    y=df_stockData['RSI_14'],
    line=dict(color='#ff9900', width=2),
    showlegend=False,
), row=2, col=1
)
fig.show()

</code>```

My chart looks as follows:

As you can see the y-axis (stock price) has a very large scale. Even if I zoom in to a smaller time period the y axis scale remains the same. Is there any way to make the y-axis scale change dynamically so that the candles appear bigger when I zoom in?

答:
This approach uses a callback with dash to set the range of y-axis based on values selected in range slider.

A significant amount of the code is making your figure an MWE (calc RSI_14)

```<code>import pandas_datareader as pdr
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
import dash
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash

# make dataframe complete ...
df_stockData = pdr.DataReader(
    "TSLA", data_source="yahoo", start="2011-11-04", end="2021-11-04"
)

def rma(x, n, y0):
    a = (n - 1) / n
    ak = a ** np.arange(len(x) - 1, -1, -1)
    return np.r_[
        np.full(n, np.nan),
        y0,
        np.cumsum(ak * x) / ak / n + y0 * a ** np.arange(1, len(x) + 1),
    ]

n = 14
df = df_stockData
df["change"] = df["Close"].diff()
df["gain"] = df.change.mask(df.change < 0, 0.0)
df["loss"] = -df.change.mask(df.change > 0, -0.0)
df["avg_gain"] = rma(
    df.gain[n + 1 :].to_numpy(), n, np.nansum(df.gain.to_numpy()[: n + 1]) / n
)
df["avg_loss"] = rma(
    df.loss[n + 1 :].to_numpy(), n, np.nansum(df.loss.to_numpy()[: n + 1]) / n
)
df["rs"] = df.avg_gain / df.avg_loss
df["RSI_14"] = 100 - (100 / (1 + df.rs))

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_width=[0.25, 0.75])
fig.add_trace(
    go.Candlestick(
        x=df_stockData.index,
        open=df_stockData["Open"],
        high=df_stockData["High"],
        low=df_stockData["Low"],
        close=df_stockData["Close"],
        increasing_line_color="green",
        decreasing_line_color="red",
        showlegend=False,
    ),
    row=1,
    col=1,
)
fig.add_trace(
    go.Scatter(
        x=df_stockData.index,
        y=df_stockData["RSI_14"],
        line=dict(color="#ff9900", width=2),
        showlegend=False,
    ),
    row=2,
    col=1,
)

# Build App
app = JupyterDash(__name__)

app.layout = dash.html.Div(
    [
        dash.dcc.Graph(
            id="fig",
            figure=fig,
        ),
    ]
)

@app.callback(
    Output("fig", "figure"),
    Input("fig", "relayoutData"),
)
def scaleYaxis(rng):
    if rng and "xaxis.range" in rng.keys():
        try:
            d = df_stockData.loc[
                rng["xaxis.range"][0] : rng["xaxis.range"][1],
                ["High", "Low", "Open", "Close"],
            ]
            if len(d) > 0:
                fig["layout"]["yaxis"]["range"] = [d.min().min(), d.max().max()]
        except KeyError:
            pass
        finally:
            fig["layout"]["xaxis"]["range"] = rng["xaxis.range"]

    return fig

app.run_server(mode="inline")
</code>```

Body:
I am trying to make a candle stick chart using plotly. I am using stock data spanning over 10 years. Due to this the candles appear very small as the y axis has a large scale. However if I zoom into a smaller time period (lets say any 1 month in the 10 years) I want the y axis scale to change so that the candle looks big. Below is my code:

df_stockData = pdr.DataReader('TSLA', data_source='yahoo', start='2011-11-04', end='2021-11-04')

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_width=[0.25, 0.75])
fig.add_trace(go.Candlestick(
    x=df_stockData.index,
    open=df_stockData['Open'],
    high=df_stockData['High'],
    low=df_stockData['Low'],
    close=df_stockData['Close'],
    increasing_line_color='green',
    decreasing_line_color='red',
    showlegend=False
), row=1, col=1)
fig.add_trace(go.Scatter(
    x=df_stockData.index,
    y=df_stockData['RSI_14'],
    line=dict(color='#ff9900', width=2),
    showlegend=False,
), row=2, col=1
)
fig.show()

My chart looks as follows:

As you can see the y-axis (stock price) has a very large scale. Even if I zoom in to a smaller time period the y axis scale remains the same. Is there any way to make the y-axis scale change dynamically so that the candles appear bigger when I zoom in?

Body:
This approach uses a callback with dash to set the range of y-axis based on values selected in range slider.

A significant amount of the code is making your figure an MWE (calc RSI_14)

import pandas_datareader as pdr
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import numpy as np
import dash
from dash.dependencies import Input, Output, State
from jupyter_dash import JupyterDash

# make dataframe complete ...
df_stockData = pdr.DataReader(
    "TSLA", data_source="yahoo", start="2011-11-04", end="2021-11-04"
)

def rma(x, n, y0):
    a = (n - 1) / n
    ak = a ** np.arange(len(x) - 1, -1, -1)
    return np.r_[
        np.full(n, np.nan),
        y0,
        np.cumsum(ak * x) / ak / n + y0 * a ** np.arange(1, len(x) + 1),
    ]

n = 14
df = df_stockData
df["change"] = df["Close"].diff()
df["gain"] = df.change.mask(df.change < 0, 0.0)
df["loss"] = -df.change.mask(df.change > 0, -0.0)
df["avg_gain"] = rma(
    df.gain[n + 1 :].to_numpy(), n, np.nansum(df.gain.to_numpy()[: n + 1]) / n
)
df["avg_loss"] = rma(
    df.loss[n + 1 :].to_numpy(), n, np.nansum(df.loss.to_numpy()[: n + 1]) / n
)
df["rs"] = df.avg_gain / df.avg_loss
df["RSI_14"] = 100 - (100 / (1 + df.rs))

fig = make_subplots(rows=2, cols=1, shared_xaxes=True, row_width=[0.25, 0.75])
fig.add_trace(
    go.Candlestick(
        x=df_stockData.index,
        open=df_stockData["Open"],
        high=df_stockData["High"],
        low=df_stockData["Low"],
        close=df_stockData["Close"],
        increasing_line_color="green",
        decreasing_line_color="red",
        showlegend=False,
    ),
    row=1,
    col=1,
)
fig.add_trace(
    go.Scatter(
        x=df_stockData.index,
        y=df_stockData["RSI_14"],
        line=dict(color="#ff9900", width=2),
        showlegend=False,
    ),
    row=2,
    col=1,
)

# Build App
app = JupyterDash(__name__)

app.layout = dash.html.Div(
    [
        dash.dcc.Graph(
            id="fig",
            figure=fig,
        ),
    ]
)

@app.callback(
    Output("fig", "figure"),
    Input("fig", "relayoutData"),
)
def scaleYaxis(rng):
    if rng and "xaxis.range" in rng.keys():
        try:
            d = df_stockData.loc[
                rng["xaxis.range"][0] : rng["xaxis.range"][1],
                ["High", "Low", "Open", "Close"],
            ]
            if len(d) > 0:
                fig["layout"]["yaxis"]["range"] = [d.min().min(), d.max().max()]
        except KeyError:
            pass
        finally:
            fig["layout"]["xaxis"]["range"] = rng["xaxis.range"]

    return fig

app.run_server(mode="inline")


问:
Does any change in program state constitute observable behavior?
Consider the two following programs:

program one

```<code>int main()
{
   printf( "hello\n" );
}
</code>```

program two

```<code>int main()
{
   srand( 0 );
   if( rand() ) {
      printf( "hello\n" );
   } else {
      printf( "hello\n" );
   }
}
</code>```

Do they have the same observable behavior or not? According to C++ Standard (1.9/6) the observable behavior includes:

reads and writes to volatile data

library I/O functions

Now srand() and rand() are likely not I/O functions (although I have no idea whether a given implementation uses some hardware noise source), but they modify program internal state. Do they manipulate volatile data? I don't know. Calls to printf() are clearly I/O operations and sequences thereof are identical in both programs.

Do the two programs above have the same observable behavior? How do I know if two given programs have the same observable behavior?

答:
Do the two programs above have the same observable behavior?

As you say, that depends on whether srand() and rand() have observable side effects. They shouldn't; there can be no external noise source, since the sequence is required to be repeatable for a given seed, and there is no other reason to perform I/O or access volatile data.

If the compiler is able to determine that they don't (e.g. if they are defined inline in a header, or the linker is smart enough to perform extra optimisations), then it would be able to omit them; otherwise, it must assume that they do, and include them. In many implementations, these functions will be in a precompiled library, and the linker won't be that smart, so you will end up calling the functions; however, a decent compiler should notice that both branches of the if are identical and omit the test.

(UPDATE: as noted in the comments, the call to rand() can also only be omitted if the compiler can determine that no future observable behaviour can depend on its side effects).

How do I know if two given programs have the same observable behavior?

In general, that's a very difficult problem, and there will be some programs where it's impossible to tell (for reasons similar to the Halting Problem). For programs as simple as this, you can simply list the observable operations and compare them; if the behaviour depends on the program's input in a non-trivial way, then that soon gets very difficult to do.

Body:
Consider the two following programs:

program one

int main()
{
   printf( "hello\n" );
}

program two

int main()
{
   srand( 0 );
   if( rand() ) {
      printf( "hello\n" );
   } else {
      printf( "hello\n" );
   }
}

Do they have the same observable behavior or not? According to C++ Standard (1.9/6) the observable behavior includes:

reads and writes to volatile data

library I/O functions

Now srand() and rand() are likely not I/O functions (although I have no idea whether a given implementation uses some hardware noise source), but they modify program internal state. Do they manipulate volatile data? I don't know. Calls to printf() are clearly I/O operations and sequences thereof are identical in both programs.

Do the two programs above have the same observable behavior? How do I know if two given programs have the same observable behavior?


问:
When generating multiple buttons in C# how do I give each one a separate function?
In my code, I generate one extra label and button every time a different button is clicked. I want it so each button can be programmed with a different function. Ex: If I clicked on generated button1 I would be brought to page 1. If I clicked on generated button2 I would be brought to page 2 etc. What would be the best way to approach this?

Here is my code below:

```<code>if (task1 == false)
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, 183);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;

                Button taskButton  = new Button();
                taskButton.Text = "Let's Go";
                taskButton.Location = new Point(labelWidth + 30, 180);
                taskButton.AutoSize = true;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
                task1 = true;

            }
            else
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, labelHeight + 30);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);

                Button taskButton = new Button();
                taskButton.Text = "Let's Go";
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;
                taskButton.Location = new Point(labelWidth + 30, labelHeight - 18);
                taskButton.AutoSize = true;
                buttonHeight = taskButton.Top;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
</code>```

答:
You can set the click handler for each button you create like this

```<code>Button taskButton1 = new Button;
taskButton1.Click += taskButton1_Click;

private void taskButton1_Click(object sender, EventArgs e)
{
    // code for the first button
}

Button taskButton2 = new Button;
taskButton2.Click += taskButton2_Click;

private void taskButton2_Click(object sender, EventArgs e)
{
    // code for the second button
}

</code>```

If you have many buttons you could assign them all the same click event and in that click event determine which button was clicked

```<code>Button taskButton1 = new Button;
taskButton1.Tag = 1;
taskButton1.Click += taskButton_Click;

Button taskButton2 = new Button;
taskButton2.Tag = 2;
taskButton2.Click += taskButton_Click;

Button taskButton3 = new Button;
taskButton3.Tag = 3;
taskButton3.Click += taskButton_Click;

private void taskButton_Click(object sender, EventArgs e)
{
    if ( ((Button)sender).Tag == 1) then
    {
         // code for the first button
    }
    else if ( ((Button)sender).Tag == 2) then
    {
         // code for the second button
    }
    else if ( ((Button)sender).Tag == 3) then
    {
         // code for the third button
    }

}
</code>```

or without using the Tag property

```<code>Button taskButton1 = new Button;
taskButton1.Click += taskButton_Click;

Button taskButton2 = new Button;
taskButton2.Click += taskButton_Click;

Button taskButton3 = new Button;
taskButton3.Click += taskButton_Click;

private void taskButton_Click(object sender, EventArgs e)
{
    if (sender == Button1) then
    {
         // code for the first button
    }
    else if (sender == Button2) then
    {
         // code for the second button
    }
    else if (sender == Button3) then
    {
         // code for the third button
    }

}
</code>```

Body:
In my code, I generate one extra label and button every time a different button is clicked. I want it so each button can be programmed with a different function. Ex: If I clicked on generated button1 I would be brought to page 1. If I clicked on generated button2 I would be brought to page 2 etc. What would be the best way to approach this?

Here is my code below:

if (task1 == false)
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, 183);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;

                Button taskButton  = new Button();
                taskButton.Text = "Let's Go";
                taskButton.Location = new Point(labelWidth + 30, 180);
                taskButton.AutoSize = true;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";
                task1 = true;

            }
            else
            {
                Label taskLabel = new Label();
                taskLabel.Text = taskInput.Text;
                taskLabel.Location = new Point(63, labelHeight + 30);
                taskLabel.BorderStyle = BorderStyle.FixedSingle;
                taskLabel.AutoSize = true;
                page2.Controls.Add(taskLabel);

                Button taskButton = new Button();
                taskButton.Text = "Let's Go";
                labelHeight = taskLabel.Bottom;
                labelWidth = taskLabel.Right;
                taskButton.Location = new Point(labelWidth + 30, labelHeight - 18);
                taskButton.AutoSize = true;
                buttonHeight = taskButton.Top;
                page2.Controls.Add(taskButton);
                taskInput.Text = "";

Body:
You can set the click handler for each button you create like this

Button taskButton1 = new Button;
taskButton1.Click += taskButton1_Click;

private void taskButton1_Click(object sender, EventArgs e)
{
    // code for the first button
}

Button taskButton2 = new Button;
taskButton2.Click += taskButton2_Click;

private void taskButton2_Click(object sender, EventArgs e)
{
    // code for the second button
}

If you have many buttons you could assign them all the same click event and in that click event determine which button was clicked

Button taskButton1 = new Button;
taskButton1.Tag = 1;
taskButton1.Click += taskButton_Click;

Button taskButton2 = new Button;
taskButton2.Tag = 2;
taskButton2.Click += taskButton_Click;

Button taskButton3 = new Button;
taskButton3.Tag = 3;
taskButton3.Click += taskButton_Click;

private void taskButton_Click(object sender, EventArgs e)
{
    if ( ((Button)sender).Tag == 1) then
    {
         // code for the first button
    }
    else if ( ((Button)sender).Tag == 2) then
    {
         // code for the second button
    }
    else if ( ((Button)sender).Tag == 3) then
    {
         // code for the third button
    }

}

or without using the Tag property

Button taskButton1 = new Button;
taskButton1.Click += taskButton_Click;

Button taskButton2 = new Button;
taskButton2.Click += taskButton_Click;

Button taskButton3 = new Button;
taskButton3.Click += taskButton_Click;

private void taskButton_Click(object sender, EventArgs e)
{
    if (sender == Button1) then
    {
         // code for the first button
    }
    else if (sender == Button2) then
    {
         // code for the second button
    }
    else if (sender == Button3) then
    {
         // code for the third button
    }

}


问:
React useEffect hook dependency array
I'm learning about the React useEffect hook, especially the dependency array. Having such simple counter:

```<code>import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Only re-run the effect if count changes!?

  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>You clicked {count} times!</h2>

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
</code>```

Even if the dependency array is empty the counter still works - the counter value is still increased/decreased when I click the button.

As far as I understand from the doc, setting the dependency array empty should just disable the useEffect to run if the dependency array doesn't explicitly list/include the changing value.

答:
First of all useEffect hook runs only once in component life cycle as far as you understand it unless you specify something in dependency array. Now for your question that why the counter is still updating that is because you are using useState which is hook responsible for updating the value in screen and has nothing to do with useEffect hook
And to make sure console.log("i run only once") in useEffect hook and you will see that it runs only one time and counter value also doesn't get increased or decreased

Title: React useEffect hook dependency array

Body:
I'm learning about the React useEffect hook, especially the dependency array. Having such simple counter:

import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";

import "./styles.css";

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    document.title = `You clicked ${count} times`;
  }, []); // Only re-run the effect if count changes!?

  return (

Hello CodeSandbox

You clicked {count} times!

      <button onClick={() => setCount(count - 1)}>Decrement</button>
      <button onClick={() => setCount(count + 1)}>Increment</button>

  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Even if the dependency array is empty the counter still works - the counter value is still increased/decreased when I click the button.

As far as I understand from the doc, setting the dependency array empty should just disable the useEffect to run if the dependency array doesn't explicitly list/include the changing value.