问:
LINQ queries give CS8600 and CS1662 warnings in VS2022 and C#10
Started a new task today of migrating a console app to VS2022 and C#10 and ran into a show stopper that I can't find a workaround for, other than using a compiler directive to suppress the warnings. I'm hoping to avoid that as this app has hundreds if not thousands of LINQ queries that use a similar syntax. Here are the basics of what I've run into.

```<code>public static class ResponseCodes
{
    public static string MEI0066 => "ME-I0066";
    public static string MEI0069 => "ME-I0069";
    public static string MEI0070 => "ME-I0070";
}

public class DebugLog
{
    public DebugLog()
    {
        this.DebugLogId = null;
        this.LogType = string.Empty;
        this.ResponseCode = string.Empty;
        this.Explanation = string.Empty;
    }

    public DebugLog(int? p_id, string p_logType, string p_responseCode, string p_explaination)
    {
        this.DebugLogId = p_id;
        this.LogType = p_logType;
        this.ResponseCode = p_responseCode;
        this.Explanation = p_explaination;
    }

    public int? LogId { get; set; }
    public string ResponseCode { get; set; }
    public string Explanation { get; set; }
    public string LogType { get; set; }
}

public enum LogEntryTypes
{
    BlackListedIP,
    DNSQuerySuccess,
    DNSQueryFailed,
    WhiteListedIP
}

public class QueryLogs
{
    public QueryLogs()
    {
        this.DebugLogQueue = new List<DebugLog>();
    }

    public List<DebugLog> DebugLogQueue {get;set;}

    public DebugLog? Query()
    {
        DebugLog _debugLog = new DebugLog()
        {
            LogId = 0,
            LogType = LogEntryTypes.DNSQuerySuccess.ToString(),
            Explanation = "IP was valid",
            ResponseCode = ResponseCodes.MEI0070
        };

        DebugLogQueue.Add(_debugLog);

        _debugLog = new DebugLog(1, LogEntryTypes.BlackListedIP.ToString(), "This a test", ResponseCodes.MEI0066);
        DebugLogQueue.Add(_debugLog);

        _debugLog = new DebugLog(2, LogEntryTypes.DNSQueryFailed.ToString(), "This string is not null", ResponseCodes.MEI0069);
        DebugLogQueue.Add(_debugLog);

        // This LINQ query gives a CS8600 warning "Converting null literal or possible
        // null value to non-nullable type.
        DebugLog returnValue = DebugLogQueue
            .FirstOrDefault(x =>
                (x.ResponseCode == ResponseCodes.MEI0069)
                && (x.LogType == LogEntryTypes.DNSQueryFailed.ToString()));

        // This form uses the null-coalescing operator but gives CS1662 warning
        // "Cannot convert lambda expression to intended delegate type because some of
        // the return types in the block are not implicitly convertible to to the
        // delegate return type."

        returnValue = DebugLogQueue
            .FirstOrDefault(x => (x.ResponseCode ?? ResponseCodes.MEI0069));

        return returnValue;
    }
}
</code>```

What's been tried:

Because class ResponseCodes is static its values will never be null.

Because the enum LogEntryTypes is converted to a string when used, they'll never return a null value.

As suggested by other posts I've tried the following:

Changing static class ResponseCodes to have nullable values by using "static string? MEI0066 => "ME-I0066";"

Changing the property getter/setter of DebugLog class to use "public string? ResponseCode { get; set; }"

Changing LogEntryTypes to a string const such as dNSQueryFailed = LogEntryTypes.DNSQueryFailed, but that's no different than using the static values from class ResponseCodes.

The Query method in class QueryLogs allows a nullable DebugLog to be returned so that it works with the .FirstOrDefault query operator, which doesn't apply to the DebugLog property values.

Setting compiler directive to:
"#pragma warning disable CS8600 // Converting null literal or possible null value to a non-nullable type." eliminates the warning and the code runs, but doing this on hundreds of queries will most definitely come back to bite me later.

So the CS8600 and CS1662 warnings have to be coming from the LINQ side when the property value is emitted and returned, but for the life of me, I haven't been able to come up with the correct syntax to get the query written so that the warning goes away. I'm not even sure where to look any further on this issue.

So am I missing something here or is this a non-starter approach for LINQ queries in C#10?

答:
The most  problems  when using net6, are caused by this new stupid nullable feature of c#. The worst thing is that it is going in new projects by default and the most people spend lots of time trying to find why it sudddenly stoped working or give strange warnings. Just make this small chanage in your net 6 propjects files</p>
```<code> <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->
</code>```

Body:
Started a new task today of migrating a console app to VS2022 and C#10 and ran into a show stopper that I can't find a workaround for, other than using a compiler directive to suppress the warnings. I'm hoping to avoid that as this app has hundreds if not thousands of LINQ queries that use a similar syntax. Here are the basics of what I've run into.

public static class ResponseCodes
{
    public static string MEI0066 => "ME-I0066";
    public static string MEI0069 => "ME-I0069";
    public static string MEI0070 => "ME-I0070";
}

public class DebugLog
{
    public DebugLog()
    {
        this.DebugLogId = null;
        this.LogType = string.Empty;
        this.ResponseCode = string.Empty;
        this.Explanation = string.Empty;
    }

    public DebugLog(int? p_id, string p_logType, string p_responseCode, string p_explaination)
    {
        this.DebugLogId = p_id;
        this.LogType = p_logType;
        this.ResponseCode = p_responseCode;
        this.Explanation = p_explaination;
    }

    public int? LogId { get; set; }
    public string ResponseCode { get; set; }
    public string Explanation { get; set; }
    public string LogType { get; set; }
}

public enum LogEntryTypes
{
    BlackListedIP,
    DNSQuerySuccess,
    DNSQueryFailed,
    WhiteListedIP
}

public class QueryLogs
{
    public QueryLogs()
    {
        this.DebugLogQueue = new List<DebugLog>();
    }

    public List<DebugLog> DebugLogQueue {get;set;}

    public DebugLog? Query()
    {
        DebugLog _debugLog = new DebugLog()
        {
            LogId = 0,
            LogType = LogEntryTypes.DNSQuerySuccess.ToString(),
            Explanation = "IP was valid",
            ResponseCode = ResponseCodes.MEI0070
        };

        DebugLogQueue.Add(_debugLog);

        _debugLog = new DebugLog(1, LogEntryTypes.BlackListedIP.ToString(), "This a test", ResponseCodes.MEI0066);
        DebugLogQueue.Add(_debugLog);

        _debugLog = new DebugLog(2, LogEntryTypes.DNSQueryFailed.ToString(), "This string is not null", ResponseCodes.MEI0069);
        DebugLogQueue.Add(_debugLog);

        // This LINQ query gives a CS8600 warning "Converting null literal or possible
        // null value to non-nullable type.
        DebugLog returnValue = DebugLogQueue
            .FirstOrDefault(x =>
                (x.ResponseCode == ResponseCodes.MEI0069)
                && (x.LogType == LogEntryTypes.DNSQueryFailed.ToString()));

        // This form uses the null-coalescing operator but gives CS1662 warning
        // "Cannot convert lambda expression to intended delegate type because some of
        // the return types in the block are not implicitly convertible to to the
        // delegate return type."

        returnValue = DebugLogQueue
            .FirstOrDefault(x => (x.ResponseCode ?? ResponseCodes.MEI0069));

        return returnValue;
    }
}

What's been tried:

Because class ResponseCodes is static its values will never be null.

Because the enum LogEntryTypes is converted to a string when used, they'll never return a null value.

As suggested by other posts I've tried the following:

Changing static class ResponseCodes to have nullable values by using "static string? MEI0066 => "ME-I0066";"

Changing the property getter/setter of DebugLog class to use "public string? ResponseCode { get; set; }"

Changing LogEntryTypes to a string const such as dNSQueryFailed = LogEntryTypes.DNSQueryFailed, but that's no different than using the static values from class ResponseCodes.

The Query method in class QueryLogs allows a nullable DebugLog to be returned so that it works with the .FirstOrDefault query operator, which doesn't apply to the DebugLog property values.

Setting compiler directive to:
"#pragma warning disable CS8600 // Converting null literal or possible null value to a non-nullable type." eliminates the warning and the code runs, but doing this on hundreds of queries will most definitely come back to bite me later.

So the CS8600 and CS1662 warnings have to be coming from the LINQ side when the property value is emitted and returned, but for the life of me, I haven't been able to come up with the correct syntax to get the query written so that the warning goes away. I'm not even sure where to look any further on this issue.

So am I missing something here or is this a non-starter approach for LINQ queries in C#10?

Body:
The most  problems  when using net6, are caused by this new stupid nullable feature of c#. The worst thing is that it is going in new projects by default and the most people spend lots of time trying to find why it sudddenly stoped working or give strange warnings. Just make this small chanage in your net 6 propjects files

 <TargetFramework>net6.0</TargetFramework>
    <!--<Nullable>enable</Nullable>-->


来源: stackexchange

问:
calculate tetrahedral no for all n number give in a range, store it in list and return it
Define a function which takes two input 1. startvalue 2. endvalue
calculate a tetrahedral no inclusive of startvalue and endvalue. store the output in list format and return to main function.
convert the list to str to display
here is what I have tried but unable to get the complete output.

```<code>def calculateNTetrahedralNumber(startvalue, endvalue):
    n = startvalue
    y = endvalue+1
    result = []
    while (n < y):
        result.append(((n*(n+1)*(n+2))/6))
        n = n+1
    return(result)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    startvalue = int(input().strip())

    endvalue = int(input().strip())

    result = calculateNTetrahedralNumber(startvalue, endvalue)
    print(result)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()
</code>```

User entered data
start value = 1
end value 7
Output
1

Expected output

1
4
10
20
35
56
84

答:
Just cast the value before you add it to your list

result.append(int((n*(n+1)*(n+2))/6))
```

ContentLicense: CC BY-SA 4.0

Body:
Define a function which takes two input 1. startvalue 2. endvalue
calculate a tetrahedral no inclusive of startvalue and endvalue. store the output in list format and return to main function.
convert the list to str to display
here is what I have tried but unable to get the complete output.

def calculateNTetrahedralNumber(startvalue, endvalue):
    n = startvalue
    y = endvalue+1
    result = []
    while (n < y):
        result.append(((n*(n+1)*(n+2))/6))
        n = n+1
    return(result)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    startvalue = int(input().strip())

    endvalue = int(input().strip())

    result = calculateNTetrahedralNumber(startvalue, endvalue)
    print(result)

    fptr.write('\n'.join(map(str, result)))
    fptr.write('\n')

    fptr.close()

User entered data
start value = 1
end value 7
Output
1

Expected output

1
4
10
20
35
56
84


问:
xfce-terminal new window at random location plus echo that value
I want to spawn new xfce-terminal windows and run some arbitrary code. I can get it to generate a random number and use that as the X coordinate for the window location, but I would like to also pass the value and have it (for example) print it in the new window.

So if I have:

```<code>TEST=$(( $RANDOM % 100 + 20 ))
xfce4-terminal --geometry 160x40+$TEST+40 -e 'bash -c "echo the number is $TEST; bash"'
</code>```

It correctly creates the window at the random location, but the terminal output in the new window is "the number is " without the value attached.

Any insight appreciated, thanks.

答:
Single quotes don't allow variable expansions. Use double quotes instead (which requires switching to single quotes on the inside).</p>
```<code>... -e "bash -c 'echo the number is $TEST; bash'"
</code>```

Body:
I want to spawn new xfce-terminal windows and run some arbitrary code. I can get it to generate a random number and use that as the X coordinate for the window location, but I would like to also pass the value and have it (for example) print it in the new window.

So if I have:

TEST=$(( $RANDOM % 100 + 20 ))
xfce4-terminal --geometry 160x40+$TEST+40 -e 'bash -c "echo the number is $TEST; bash"'

It correctly creates the window at the random location, but the terminal output in the new window is "the number is " without the value attached.

Any insight appreciated, thanks.

Body:
Single quotes don't allow variable expansions. Use double quotes instead (which requires switching to single quotes on the inside).

... -e "bash -c 'echo the number is $TEST; bash'"


问:
preg_match words followed by numbers
I've got the following string:

```<code>Query_time: 77.571216 Lock_time: 2.793139 Rows_sent: 20 Rows_examined: 4654071
</code>```

How would i go about placing each number into a variable?
eg:

```<code>$query_time    = 77.571216;
$lock_time     = 2.793139;
$rows_sent     = 20;
$rows_examined = 4654071;
</code>```

答:
```<code>if (preg_match('/Query_time: ([0-9.]+) Lock_time: ([0-9.]+) Rows_sent: ([0-9.]+) Rows_examined: ([0-9.]+)/', $string, $matches)) {
    list($query_time, $lock_time, $rows_sent, $rows_examined) =
            array_slice($matches, 1);
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: preg_match words followed by numbers

Body:
I've got the following string:

Query_time: 77.571216 Lock_time: 2.793139 Rows_sent: 20 Rows_examined: 4654071

How would i go about placing each number into a variable?
eg:

$query_time    = 77.571216;
$lock_time     = 2.793139;
$rows_sent     = 20;
$rows_examined = 4654071;


问:
R, New Column that's a Sum to Row
I'm trying to find an easy way to create a new variable that will give me the sum of a column, up to a certain row. I input a new variable, "Spend.to.Date" to illustrate what I'm looking for. I can do it "by hand" by specifying the specific cells to add together, but I'd imagine there must be a more efficient way to achieve it. Any help would be greatly appreciated!

df <- as.data.frame(matrix(c(1, 2, 3, 4, 5, 100, 200, 300, 400, 500), 5, 2)) #Take as given

colnames(df) <- c("Day", "Spend")

df$Spend.to.Date <- c(100, 300, 600, 1000, 1500)
```

答:
```<code>df$Spend.to.Date <- cumsum(df$Spend)
</code>```

Title: R, New Column that's a Sum to Row

Body: df$Spend.to.Date <- cumsum(df$Spend)


问:
Overflow-x value ignored in mobile safari
We set the overflow-x values to hidden on both the body and scrollable elements, but mobile Safari ignores these values. On the desktop, the overflow values work fine.

Relevant code:

```<code>body { overflow-x:hidden; width:320px; height:100%; min-height:100%; margin:0; background:-webkit-linear-gradient(top,#e8e4dc,#f2f0eb); }

.page_list, .content { max-height:370px; box-sizing:border-box; padding:0; overflow-x:hidden; overflow-y:auto; -webkit-overflow-scrolling:touch }

#catalog_page { border-left:1px solid #CCC; z-index:28; position:absolute; top:0; width:200px; height:460px; background:white; -webkit-transition:-webkit-transform 0.1s ease-in;; -webkit-transform:translate3d(0,0,0); display:none; }
</code>```

catalog_page is what sits outside the viewport, sliding into view only after someone does a gesture.

To reproduce:

1) Visit www.tekiki.com on your iPhone (not iPad). Scroll to the right, and you'll see how catalog_page extends the site's width, even though we fixed the body width.

答:
It's 2022. Mobile safari can still be quirky. But it seems for me the way to get overflow-x working on the body is to do the following:

```<code>html,
body {
  height: 100%;
  overflow-x: hidden;
  transform: translate3d(0, 0, 0);
}
</code>```

I wish I understood the transform, but it seems necessary. The other way was to set the body to position of relative, but this seems safer.

OR

Another way thats definitely safe, and future proof, is to place everything in body directly into a div and give that div an overflow of hidden and make sure it has a min-height of 100vh. Like so:

```<code><body>
  <div class="page">
    everything...
  </div>
</body>
</code>```

Then in CSS:

```<code>.page {
    min-height: 100vh;
    overflow: hidden;
    position: relative;
}
</code>```

Body:
We set the overflow-x values to hidden on both the body and scrollable elements, but mobile Safari ignores these values. On the desktop, the overflow values work fine.

Relevant code:

body { overflow-x:hidden; width:320px; height:100%; min-height:100%; margin:0; background:-webkit-linear-gradient(top,#e8e4dc,#f2f0eb); }

.page_list, .content { max-height:370px; box-sizing:border-box; padding:0; overflow-x:hidden; overflow-y:auto; -webkit-overflow-scrolling:touch }

#catalog_page { border-left:1px solid #CCC; z-index:28; position:absolute; top:0; width:200px; height:460px; background:white; -webkit-transition:-webkit-transform 0.1s ease-in;; -webkit-transform:translate3d(0,0,0); display:none; }

catalog_page is what sits outside the viewport, sliding into view only after someone does a gesture.

To reproduce:

1) Visit www.tekiki.com on your iPhone (not iPad). Scroll to the right, and you'll see how catalog_page extends the site's width, even though we fixed the body width.

Body:
It's 2022. Mobile safari can still be quirky. But it seems for me the way to get overflow-x working on the body is to do the following:

html,
body {
  height: 100%;
  overflow-x: hidden;
  transform: translate3d(0, 0, 0);
}

I wish I understood the transform, but it seems necessary. The other way was to set the body to position of relative, but this seems safer.

OR

Another way thats definitely safe, and future proof, is to place everything in body directly into a div and give that div an overflow of hidden and make sure it has a min-height of 100vh. Like so:

<body>
  <div class="page">
    everything...
  </div>
</body>

Then in CSS:

.page {
    min-height: 100vh;
    overflow: hidden;
    position: relative;
}


问:
Conditionally importing JS library
In my Rails 6.x app, I was using Webpacker in order to compile my styles and transpile my JS.

As part of my apps upgrade to Rails 7, I scrapped Webpacker (as it's no longer recommended) and switched over to the new cssbundling-rails and jsbundling-rails gems.

These are super fast and sooo much easier to use.

However, I just ran a Lighthouse report on my site and I think certain pages on my site are loading all my JS even though a lot of it is not even executed on most pages.

For example I have a script that plays audio using the Plyr library on one page.

My script for this, at the top has an import like:

import Plyr from 'plyr'

I've tried to conditionalism this by checking if a specific element exists on the page first before importing but it didn't like that.

How can I only perform some of these imports when they are necessary and not when they are not.

How do I convert the above to be conditional?

Thanks,
Neil

UPDATE:

My updated script:

```<code>if (document.querySelector('audio')) {
    let audio = document.querySelector('audio');
    import('plyr').then(Plyr => {
        const player = new Plyr(audio, {
            'controls' : ['play'],
            'autoplay' : false
        })
    });
}
</code>```

The error i'm getting is:

Uncaught (in promise) TypeError: Plyr2 is not a constructor.

How can I access the Plyr object?

答:
Instead of using import Plyr from 'plyr', you can use dynamic import of
import('plyr') which you can use anywhere, including conditional logic. Keep in mind, dynamic imports return promises. So async/await
So,

```<code>if(somevalue === true){
   import('plyr').then(resp => doSomething)
}
</code>```

Title: Conditionally importing JS library

Body:
In my Rails 6.x app, I was using Webpacker in order to compile my styles and transpile my JS.

As part of my apps upgrade to Rails 7, I scrapped Webpacker (as it's no longer recommended) and switched over to the new cssbundling-rails and jsbundling-rails gems.

These are super fast and sooo much easier to use.

However, I just ran a Lighthouse report on my site and I think certain pages on my site are loading all my JS even though a lot of it is not even executed on most pages.

For example I have a script that plays audio using the Plyr library on one page.

My script for this, at the top has an import like:

import Plyr from 'plyr'

I've tried to conditionalism this by checking if a specific element exists on the page first before importing but it didn't like that.

How can I only perform some of these imports when they are necessary and not when they are not.

How do I convert the above to be conditional?

Thanks,
Neil

UPDATE:

My updated script:

if (document.querySelector('audio')) {
    let audio = document.querySelector('audio');
    import('plyr').then(Plyr => {
        const player = new Plyr(audio, {
            'controls' : ['play'],
            'autoplay' : false
        })
    });
}

The error i'm getting is:

Uncaught (in promise) TypeError: Plyr2 is not a constructor.

How can I access the Plyr object?

Body:
Instead of using import Plyr from 'plyr', you can use dynamic import of
import('plyr') which you can use anywhere, including conditional logic. Keep in mind, dynamic imports return promises. So async/await
So,

if(somevalue === true){
   import('plyr').then(resp => doSomething)
}


问:
types of facebook application and their differences
I try to understand the difference betweeen a facebook canvaas application and a facebook enabled website. For me the only difference is that Canvas integrates into Facebook with an iFrame and Websites are stand allone.

But in terms of policy and functionality these two types look the same. Is this true or am I wrong?

答: For all extents and purposes they are the same.  On Canvas/Page apps there is an additional signed_request post that is sent to your application with a little FB specific information that doesn't get provided to the website.</p>


问:
Why is my html displaying a snippet of js as body text?
I wanna preface this by saying I'm very new at this and learning as I go so there may be several mistakes in this and I'm open to all helpful feedback!

I created this bit of animated text forked from a codepen pen using a combo of html/css/js and it's running exactly as it should be, except a little while after the animated text finishes loading, it adds a portion of my nested js as visible html text. I think it has something to do with a rogue unclosed ">" somewhere because the portion of js that it's mistakenly displaying exists between two unrelated ">" and "<". Can anyone explain why this is happening? TIA! full code is as follows:

<!DOCTYPE html>

    <meta charset='UTF-8'/>

     hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...
     I guess uncertainty seems appropriate
     for matters of this world
     only thing I can really be certain of these days
     is that I'm so-and-so and I exist
     anyhow, looking back is a bad habit, y'know
     while we're both here,
     might as well take a look around...
     ...well?
     you gonna do somethin'?
     or are you just gonna stand there and bleed?<type>

```

答:
There are a few small errors here, most notably a missing ```</code> tag (which is causing the script issue)</p>
```
    </style>

 <--------- this opening tag is missing a closing tag
     hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...
```

Body:
There are a few small errors here, most notably a missing </pre> tag (which is causing the script issue)

    </style>
  </head>
  <body>
        <pre id="typewriter"> <--------- this opening tag is missing a closing tag
    </span> hmmm
     seems I've gotten myself all turned around...
     could've sworn the road was back that way...


问:
'UFuncTypeError' regarding dtype('int64') and dtype('<m8[s]') working with numpy
I'm using this Python script:

```<code>import pandas as pd
import numpy as np
from utils import timedelta64_to_secs

if __name__ == '__main__':
    data_frame = pd.read_csv("/path/to/file.csv", nrows=1000000, skiprows=0, header=0)
    data_array = data_frame.iloc[:, 1]

    activations = get_activations(data_array, min_off_duration=30, min_on_duration=12, border=1, on_power_threshold=200)
</code>```

where get_activations() is defined here.

At line 954, the function timedelta64_to_secs() is called; it generates the error:

```<code>File "C:\Users\username\Documents\PyCharmProjects\NILMTK\nilmtk\utils.py", line 65, in timedelta64_to_secs
return timedelta / np.timedelta64(1, 's')
numpy.core._exceptions.UFuncTypeError: ufunc 'true_divide' cannot use operands with types dtype('int64') and dtype('<m8[s]')
</code>```

The definition of timedelta64_to_secs() (which can be found here) is:

```<code>def timedelta64_to_secs(timedelta):
    """Convert `timedelta` to seconds.

    Parameters | timedelta : np.timedelta64

    Returns | float : seconds
    """
    if len(timedelta) == 0:
       return np.array([])
    else:
        return timedelta / np.timedelta64(1, 's')
</code>```

where timedelta is a 712-element numpy array, while np.timedelta64(1, 's') is timedelta64 type.

How could I solve?

答:
You are dividing numpy arrays of different types. In order to divide you should make the types consistent, in this case I suggest changing the numpy "<m8[s]" (a datetime dtype) into a relevant type, e.g. "int64". A suggested update to the function timedelta64_to_secs is shown below (docstrings removed for brevity).

import numpy as np
def timedelta64_to_secs(timedelta):
    if len(timedelta) == 0:
        return np.array([])
    else:
        return timedelta / np.timedelta64(1, 's').astype('int64')
```

Body:
I'm using this Python script:

import pandas as pd
import numpy as np
from utils import timedelta64_to_secs

if __name__ == '__main__':
    data_frame = pd.read_csv("/path/to/file.csv", nrows=1000000, skiprows=0, header=0)
    data_array = data_frame.iloc[:, 1]

    activations = get_activations(data_array, min_off_duration=30, min_on_duration=12, border=1, on_power_threshold=200)

where get_activations() is defined here.

At line 954, the function timedelta64_to_secs() is called; it generates the error:

File "C:\Users\username\Documents\PyCharmProjects\NILMTK\nilmtk\utils.py", line 65, in timedelta64_to_secs
return timedelta / np.timedelta64(1, 's')
numpy.core._exceptions.UFuncTypeError: ufunc 'true_divide' cannot use operands with types dtype('int64') and dtype('<m8[s]')

The definition of timedelta64_to_secs() (which can be found here) is:

def timedelta64_to_secs(timedelta):
    """Convert `timedelta` to seconds.

    Parameters | timedelta : np.timedelta64

    Returns | float : seconds
    """
    if len(timedelta) == 0:
       return np.array([])
    else:
        return timedelta / np.timedelta64(1, 's')

where timedelta is a 712-element numpy array, while np.timedelta64(1, 's') is timedelta64 type.

How could I solve?


问:
How do I process email from timestamp with exchangelib?
I will be storing the last processed email timestamp to the database and then when I run the process I want to do greater than that email timestamp.

Right now I m doing this way.. which was fine to run for old records but now I want to automate this with a corn job run every 1 hour.

```<code>
pytz_tz = pytz.timezone('US/Pacific')
py_dt = pytz_tz.localize(datetime(2022, 2, 3))
py_dt1 = pytz_tz.localize(datetime(2022, 2, 4))  ####ENTER DATE
ews_bfr = EWSDateTime.from_datetime(py_dt)
ews_bfr1 = EWSDateTime.from_datetime(py_dt1)
# print(ews_bfr)

query = Q(subject='MediaCore process')
recent_emails = account.inbox.filter(~query, datetime_received__range=(
    ews_bfr,
    ews_bfr1
))

</code>```

But now instead of using the start and end date, I want to pass the timestamp of the email to start from, Can anyone please advise or help me with this?

答:
I got my result with the help of dateutil.parse</p>
```<code>from dateutil.parser import parse

timestampdate = "2022-02-07 18:16:45+00:00"
recentkey = parse(timestampdate)

recent_emails = account.inbox.filter(datetime_received__gt = recentkey) ##__gt and gte for greater than or greater than or equal to for filtering.
</code>```

Body:
I will be storing the last processed email timestamp to the database and then when I run the process I want to do greater than that email timestamp.

Right now I m doing this way.. which was fine to run for old records but now I want to automate this with a corn job run every 1 hour.

pytz_tz = pytz.timezone('US/Pacific')
py_dt = pytz_tz.localize(datetime(2022, 2, 3))
py_dt1 = pytz_tz.localize(datetime(2022, 2, 4))  ####ENTER DATE
ews_bfr = EWSDateTime.from_datetime(py_dt)
ews_bfr1 = EWSDateTime.from_datetime(py_dt1)
# print(ews_bfr)

query = Q(subject='MediaCore process')
recent_emails = account.inbox.filter(~query, datetime_received__range=(
    ews_bfr,
    ews_bfr1
))

But now instead of using the start and end date, I want to pass the timestamp of the email to start from, Can anyone please advise or help me with this?

Body:
I got my result with the help of dateutil.parse

from dateutil.parser import parse

timestampdate = "2022-02-07 18:16:45+00:00"
recentkey = parse(timestampdate)

recent_emails = account.inbox.filter(datetime_received__gt = recentkey) ##__gt and gte for greater than or greater than or equal to for filtering.


问:
Converting Typed Properties in JavaScript Classes
Just starting to use JavaScript Classes and have a quick question.  In the example below, I want to ensure/convert certain properties to be numeric when I create the class.  For instance, if the user enters "$10.50" for the unit price, I want the class to only have 10.50 so the total function works.  I'm sure this can be done with a getter/setter but I can't quite figure out how to implement it.

    <form name="orderform">
      order date: <input name="order_date" value="" type=text>

item_name: <input name="item_name" value="" type=text>

unit_price: <input name="unit_price" value="" type=text>

quantity: <input name="quantity" value="0" type=text>
    </form>
```
```class OrderItem {
  constructor(
    order_date,
    item_name,
    unit_price,
    quantity,
  ) {
    this.order_date = order_date;
    this.item_name = item_name;
    this.unit_price = unit_price;
    this.quantity = quantity;
  }
  get total() {
    return this.unit_price * this.quantity;
  }
}

const orderitem1 = new OrderItem();

function GetNumber(val)
{
  if (typeof val !== 'undefined')
  {
      return Number(val.replace(/[^0-9.-]+/g, ""));
  }
  else
  {
    return 0;
  }
}

function getOrder()
{
  $("#orderform").serializeArray().map(function(x){orderitem1[x.name] = x.value;});

  var total = orderitem.total;  //doesn't work if they enter '$10.50'

//...do stuff here with the orderitem1 class....
}
```

答:
Instead of creating the OrderItem and then updating its values in getOrder, you could create the OrderItem on the spot.

The snippet below instantiates an OrderItem from the form data on submit, and parses the numeric values in the constructor using your existing GetNumber function.

You could also consider changing the input type from 'text' to 'number' for those inputs, which would (mostly) prevent users from entering $ in the first place.

// get a reference to the form
const form = document.querySelector('form[name=orderform]');

// add an onsubmit handler
form.addEventListener('submit', (e) => {
  // stop the form from submitting
  e.preventDefault();

  // convert the form's inputs into a key-value mapping, e.g. { quantity: "12", unit_price: "$10.50", ... }
  const data = new FormData(e.target);
  const config = [...data.entries()].reduce((acc, [key, value]) => ({...acc, [key]: value}), {})

  // instantiate an OrderItem from the config
  const orderItem = new OrderItem(config);

  // do whatever you need to do with it
  console.log(orderItem.total);
})

class OrderItem {
  constructor({
    order_date,
    item_name,
    unit_price,
    quantity,
  } = {}) {
    this.order_date = order_date;
    this.item_name = item_name;
    this.unit_price = GetNumber(unit_price);
    this.quantity = GetNumber(quantity);
  }
  get total() {
    return this.unit_price * this.quantity;
  }
}

function GetNumber(val) {
  if (typeof val !== 'undefined') {
    return Number(val.replace(/[^0-9.-]+/g, ""));
  } else {
    return 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="orderform">
  order date: <input name="order_date" value="" type=text>
  <br>item_name: <input name="item_name" value="" type=text>
  <br>unit_price: <input name="unit_price" value="$10.50" type=text>
  <br>quantity: <input name="quantity" value="1" type=text>
  <button>Get Order</button>
</form></code>```

alternative

If for some reason you need to be able to change the OrderItem's values after instantiating it, you could do it in a getter or setter. (But generally speaking immutability is A Good Thing™.)

class OrderItem {
  set unit_price(p) {
    // needs a different internal name to avoid recursion
    this._unitPrice = toNumber(p);
  }

  get unit_price() {
    return this._unitPrice;
  }
}

const toNumber = v => Number(`${v}`.replace(/[^0-9.]/g, ''));

const item = new OrderItem();
item.unit_price = '$10.50';

console.log(item.unit_price);```

Body:
Just starting to use JavaScript Classes and have a quick question.  In the example below, I want to ensure/convert certain properties to be numeric when I create the class.  For instance, if the user enters "$10.50" for the unit price, I want the class to only have 10.50 so the total function works.  I'm sure this can be done with a getter/setter but I can't quite figure out how to implement it.

    <form name="orderform">
      order date: <input name="order_date" value="" type=text>

item_name: <input name="item_name" value="" type=text>

unit_price: <input name="unit_price" value="" type=text>

quantity: <input name="quantity" value="0" type=text>
    </form>

class OrderItem {
  constructor(
    order_date,
    item_name,
    unit_price,
    quantity,
  ) {
    this.order_date = order_date;
    this.item_name = item_name;
    this.unit_price = unit_price;
    this.quantity = quantity;
  }
  get total() {
    return this.unit_price * this.quantity;
  }
}

const orderitem1 = new OrderItem();

function GetNumber(val)
{
  if (typeof val !== 'undefined')
  {
      return Number(val.replace(/[^0-9.-]+/g, ""));
  }
  else
  {
    return 0;
  }
}

function getOrder()
{
  $("#orderform").serializeArray().map(function(x){orderitem1[x.name] = x.value;});

  var total = orderitem.total;  //doesn't work if they enter '$10.50'

//...do stuff here with the orderitem1 class....
}

Body:
Instead of creating the OrderItem and then updating its values in getOrder, you could create the OrderItem on the spot.

The snippet below instantiates an OrderItem from the form data on submit, and parses the numeric values in the constructor using your existing GetNumber function.

You could also consider changing the input type from 'text' to 'number' for those inputs, which would (mostly) prevent users from entering $ in the first place.

// get a reference to the form
const form = document.querySelector('form[name=orderform]');

// add an onsubmit handler
form.addEventListener('submit', (e) => {
  // stop the form from submitting
  e.preventDefault();

  // convert the form's inputs into a key-value mapping, e.g. { quantity: "12", unit_price: "$10.50", ... }
  const data = new FormData(e.target);
  const config = [...data.entries()].reduce((acc, [key, value]) => ({...acc, [key]: value}), {})

  // instantiate an OrderItem from the config
  const orderItem = new OrderItem(config);

  // do whatever you need to do with it
  console.log(orderItem.total);
})

class OrderItem {
  constructor({
    order_date,
    item_name,
    unit_price,
    quantity,
  } = {}) {
    this.order_date = order_date;
    this.item_name = item_name;
    this.unit_price = GetNumber(unit_price);
    this.quantity = GetNumber(quantity);
  }
  get total() {
    return this.unit_price * this.quantity;
  }
}

function GetNumber(val) {
  if (typeof val !== 'undefined') {
    return Number(val.replace(/[^0-9.-]+/g, ""));
  } else {
    return 0;
  }
}

<form name="orderform">
  order date: <input name="order_date" value="" type=text>
  <br>item_name: <input name="item_name" value="" type=text>
  <br>unit_price: <input name="unit_price" value="$10.50" type=text>
  <br>quantity: <input name="quantity" value="1" type=text>
  <button>Get Order</button>
</form>

alternative

If for some reason you need to be able to change the OrderItem's values after instantiating it, you could do it in a getter or setter. (But generally speaking immutability is A Good Thing™.)

class OrderItem {
  set unit_price(p) {
    // needs a different internal name to avoid recursion
    this._unitPrice = toNumber(p);
  }

  get unit_price() {
    return this._unitPrice;
  }
}

const toNumber = v => Number(`${v}`.replace(/[^0-9.]/g, ''));

const item = new OrderItem();
item.unit_price = '$10.50';

console.log(item.unit_price);


问:
Filter multiple values on a string column in dplyr
I have a data.frame with character data in one of the columns.
I would like to filter multiple options in the data.frame from the same column. Is there an easy way to do this that I'm missing?

Example:
data.frame name = dat

```<code>days      name
88        Lynn
11        Tom
2         Chris
5         Lisa
22        Kyla
1         Tom
222       Lynn
2         Lynn
</code>```

I'd like to filter out Tom and Lynn for example.

When I do:

```<code>target <- c("Tom", "Lynn")
filt <- filter(dat, name == target)
</code>```

I get  this error:

```<code>longer object length is not a multiple of shorter object length
</code>```

答:
In case you have long strings as values in your string columns
you can use this powerful method with the stringr package.
A method that filter( %in% ) and base R can't do.

```<code>library(dplyr)
library(stringr)

sentences_tb = as_tibble(sentences) %>%
                 mutate(row_number())
sentences_tb
# A tibble: 720 x 2
   value                                       `row_number()`
   <chr>                                                <int>
 1 The birch canoe slid on the smooth planks.               1
 2 Glue the sheet to the dark blue background.              2
 3 Its easy to tell the depth of a well.                   3
 4 These days a chicken leg is a rare dish.                 4
 5 Rice is often served in round bowls.                     5
 6 The juice of lemons makes fine punch.                    6
 7 The box was thrown beside the parked truck.              7
 8 The hogs were fed chopped corn and garbage.              8
 9 Four hours of steady work faced us.                      9
10 Large size in stockings is hard to sell.                10
# ... with 710 more rows

matching_letters <- c(
  "canoe","dark","often","juice","hogs","hours","size"
)
matching_letters <- str_c(matching_letters, collapse = "|")
matching_letters
[1] "canoe|dark|often|juice|hogs|hours|size"

letters_found <- str_subset(sentences_tb$value,matching_letters)
letters_found_tb = as_tibble(letters_found)
inner_join(sentences_tb,letters_found_tb)

# A tibble: 16 x 2
   value                                          `row_number()`
   <chr>                                                   <int>
 1 The birch canoe slid on the smooth planks.                  1
 2 Glue the sheet to the dark blue background.                 2
 3 Rice is often served in round bowls.                        5
 4 The juice of lemons makes fine punch.                       6
 5 The hogs were fed chopped corn and garbage.                 8
 6 Four hours of steady work faced us.                         9
 7 Large size in stockings is hard to sell.                   10
 8 Note closely the size of the gas tank.                     33
 9 The bark of the pine tree was shiny and dark.             111
10 Both brothers wear the same size.                         253
11 The dark pot hung in the front closet.                    261
12 Grape juice and water mix well.                           383
13 The wall phone rang loud and often.                       454
14 The bright lanterns were gay on the dark lawn.            476
15 The pleasant hours fly by much too soon.                  516
16 A six comes up more often than a ten.                     609
</code>```

It's a bit verbose, but it's very handy and powerful if you have long strings and want to filter in what row is located a specific word.

Comparing with the accepted answers:

```<code>> target <- c("canoe","dark","often","juice","hogs","hours","size")
> filter(sentences_tb, value %in% target)
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>

> df<- select(filter(sentences_tb,value=='canoe'| value=='dark'), c('value','row_number()'))
> df
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>

> target <- c("canoe","dark","often","juice","hogs","hours","size")
> index <- sentences_tb$value %in% target
> sentences_tb[index, ]
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>
</code>```

You need to write all the sentences to get the desired result.

Body:
I have a data.frame with character data in one of the columns.
I would like to filter multiple options in the data.frame from the same column. Is there an easy way to do this that I'm missing?

Example:
data.frame name = dat

days      name
88        Lynn
11        Tom
2         Chris
5         Lisa
22        Kyla
1         Tom
222       Lynn
2         Lynn

I'd like to filter out Tom and Lynn for example.

When I do:

target <- c("Tom", "Lynn")
filt <- filter(dat, name == target)

I get  this error:

longer object length is not a multiple of shorter object length

Body:
In case you have long strings as values in your string columns
you can use this powerful method with the stringr package.
A method that filter( %in% ) and base R can't do.

library(dplyr)
library(stringr)

sentences_tb = as_tibble(sentences) %>%
                 mutate(row_number())
sentences_tb
# A tibble: 720 x 2
   value                                       `row_number()`
   <chr>                                                <int>
 1 The birch canoe slid on the smooth planks.               1
 2 Glue the sheet to the dark blue background.              2
 3 Its easy to tell the depth of a well.                   3
 4 These days a chicken leg is a rare dish.                 4
 5 Rice is often served in round bowls.                     5
 6 The juice of lemons makes fine punch.                    6
 7 The box was thrown beside the parked truck.              7
 8 The hogs were fed chopped corn and garbage.              8
 9 Four hours of steady work faced us.                      9
10 Large size in stockings is hard to sell.                10
# ... with 710 more rows

matching_letters <- c(
  "canoe","dark","often","juice","hogs","hours","size"
)
matching_letters <- str_c(matching_letters, collapse = "|")
matching_letters
[1] "canoe|dark|often|juice|hogs|hours|size"

letters_found <- str_subset(sentences_tb$value,matching_letters)
letters_found_tb = as_tibble(letters_found)
inner_join(sentences_tb,letters_found_tb)

# A tibble: 16 x 2
   value                                          `row_number()`
   <chr>                                                   <int>
 1 The birch canoe slid on the smooth planks.                  1
 2 Glue the sheet to the dark blue background.                 2
 3 Rice is often served in round bowls.                        5
 4 The juice of lemons makes fine punch.                       6
 5 The hogs were fed chopped corn and garbage.                 8
 6 Four hours of steady work faced us.                         9
 7 Large size in stockings is hard to sell.                   10
 8 Note closely the size of the gas tank.                     33
 9 The bark of the pine tree was shiny and dark.             111
10 Both brothers wear the same size.                         253
11 The dark pot hung in the front closet.                    261
12 Grape juice and water mix well.                           383
13 The wall phone rang loud and often.                       454
14 The bright lanterns were gay on the dark lawn.            476
15 The pleasant hours fly by much too soon.                  516
16 A six comes up more often than a ten.                     609

It's a bit verbose, but it's very handy and powerful if you have long strings and want to filter in what row is located a specific word.

Comparing with the accepted answers:

> target <- c("canoe","dark","often","juice","hogs","hours","size")
> filter(sentences_tb, value %in% target)
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>

> df<- select(filter(sentences_tb,value=='canoe'| value=='dark'), c('value','row_number()'))
> df
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>

> target <- c("canoe","dark","often","juice","hogs","hours","size")
> index <- sentences_tb$value %in% target
> sentences_tb[index, ]
# A tibble: 0 x 2
# ... with 2 variables: value <chr>, row_number() <int>

You need to write all the sentences to get the desired result.


问:
Custom Windows 10 Universal App Theme
Windows provides Light and Dark Themes for Windows 10 Universal Apps. This is changed in App.xaml in the application node at Requested Theme.

```<code><Application
x:Class="Template.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Template"
RequestedTheme="Dark">
</code>```

Is there a way to make a custom theme? I realize you can make a resource dictionary and put custom colors, but then you have to include {static resource...} at every attribute you want to apply it to. I think it would be easy to define my own RequestedTheme so I would only need to include it one time.

答:
On copying Generic.xaml

On the topic of copying Generic.xaml into your project, a comment on this page states:

This will prevent you from ever receiving updates

While this is true, you may want to have more control over when your app receives updates.

I agree it is a bad idea to copy generic.xaml into your project. These resources are built into the framework you are using, so if you want to align with those resources you can simply refer to them by key and they will be available.

However, to maintain control over the timing of accepting updates to those resources (i.e. you don't want to be affected by updates beyond your control without testing your app), creating your own base styles using copies from generic.xaml and basing your own styles on those copies is the right way to go.

On Custom Themes

None of this addresses the question here though; if you use the RequestedTheme system you only have choices between 2 theme palettes called Light and Dark.  The only flexibility you have is which palette to apply to which elements.

In other words, the RequestedTheme mechanism is limited to a set number of palettes.  Those palette colours can be whatever you like, though they are usually defined at design time.  I'm not sure about runtime customisation of the palette at this stage.

If you wanted to allow the user for a custom theme palette, you would need to sacrifice one of light/dark palettes for your palette, making the sacrificed palette unavailable.  This may or may not be what your users want, so weigh the decision appropriately.

The RequestedTheme system is powerful and allows switching between the two light/dark modes simple, but isn't flexible enough to support more than 2 custom palettes at this stage.

High Contrast

There is a HighContrast mode allowing 4 (?) more palettes, though I'm not familiar with those.  Defining those palettes is done in the same way as defining the Light/Dark palettes through the RequestedTheme system, so it may be that those other palettes are configurable in the same way.

Perhaps in the future I'll gain experience in High Contrast theming and come back to complete this section.

Title: Custom Windows 10 Universal App Theme

Body:
Windows provides Light and Dark Themes for Windows 10 Universal Apps. This is changed in App.xaml in the application node at Requested Theme.

<Application
x:Class="Template.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Template"
RequestedTheme="Dark">

Is there a way to make a custom theme? I realize you can make a resource dictionary and put custom colors, but then you have to include {static resource...} at every attribute you want to apply it to. I think it would be easy to define my own RequestedTheme so I would only need to include it one time.


问:
ASP MVC3 Charting (A Step Backwards)?
I attemtping to use Charts in MVC 3 and asside from the default ChartThemes provided it seems way harder to specify themes. There is no longer a way to edit ChartAreas or access many strongly typed properties (the argument type for chart area is just a string).

Previously you could do something like this:

Old Way

```<code>    ChartArea area = new ChartArea {
        BackColor = Color.Transparent,
        AxisX = new Axis {
          Interval = 7,
          IntervalType = DateTimeIntervalType.Days,
          IsMarginVisible = false,
          LabelStyle = new LabelStyle { ForeColor = Color.FromArgb(255, 128, 128, 128), Font = new Font("Arial", 10, FontStyle.Regular), Format = "MMM dd" },
          LineColor = Color.FromArgb(255, 208, 208, 208),
          MajorGrid = new Grid { LineColor = Color.FromArgb(255, 242, 242, 242), LineDashStyle = ChartDashStyle.Solid },
          MajorTickMark = new TickMark { LineColor = Color.Transparent, Size = 4.8f }
        },
        AxisY = new Axis {
          IntervalAutoMode = IntervalAutoMode.VariableCount,
          LabelStyle = new LabelStyle { ForeColor = Color.FromArgb(255, 128, 128, 128), Font = new Font("Arial", 10, FontStyle.Regular) },
          LineColor = Color.Transparent,
          MajorGrid = new Grid { LineColor = Color.FromArgb(255, 242, 242, 242), LineDashStyle = ChartDashStyle.Solid },
          MajorTickMark = new TickMark { LineColor = Color.Transparent, Size = 0.8f }
        },
        Position = new ElementPosition { Height = 90, Width = 99, X = 0, Y = 10 }
      };
</code>```

New Way

```<code>Chart chart = new Chart(width: 400, height: 200, theme: ChartTheme.Yellow)
                .AddSeries(
                    chartType: "line",
                    xValue: dates.ToArray(),
                    yValues: data.ToArray(),
                    chartArea: someString)
</code>```

The chart area data is now just a string and you have chart themes are a string and there are a few defaults.

This seems like a massive step backwards? Am I missing something fundamental?

答: I think you'll find the the default themes are just that. You still have the ability to override styling by substituting your own chartarea xml. Take a look here at the ChartTheme reference </p>

Title: ASP MVC3 Charting (A Step Backwards)?

Body:
I attemtping to use Charts in MVC 3 and asside from the default ChartThemes provided it seems way harder to specify themes. There is no longer a way to edit ChartAreas or access many strongly typed properties (the argument type for chart area is just a string).

Previously you could do something like this:

Old Way

    ChartArea area = new ChartArea {
        BackColor = Color.Transparent,
        AxisX = new Axis {
          Interval = 7,
          IntervalType = DateTimeIntervalType.Days,
          IsMarginVisible = false,
          LabelStyle = new LabelStyle { ForeColor = Color.FromArgb(255, 128, 128, 128), Font = new Font("Arial", 10, FontStyle.Regular), Format = "MMM dd" },
          LineColor = Color.FromArgb(255, 208, 208, 208),
          MajorGrid = new Grid { LineColor = Color.FromArgb(255, 242, 242, 242), LineDashStyle = ChartDashStyle.Solid },
          MajorTickMark = new TickMark { LineColor = Color.Transparent, Size = 4.8f }
        },
        AxisY = new Axis {
          IntervalAutoMode = IntervalAutoMode.VariableCount,
          LabelStyle = new LabelStyle { ForeColor = Color.FromArgb(255, 128, 128, 128), Font = new Font("Arial", 10, FontStyle.Regular) },
          LineColor = Color.Transparent,
          MajorGrid = new Grid { LineColor = Color.FromArgb(255, 242, 242, 242), LineDashStyle = ChartDashStyle.Solid },
          MajorTickMark = new TickMark { LineColor = Color.Transparent, Size = 0.8f }
        },
        Position = new ElementPosition { Height = 90, Width = 99, X = 0, Y = 10 }
      };

New Way

Chart chart = new Chart(width: 400, height: 200, theme: ChartTheme.Yellow)
                .AddSeries(
                    chartType: "line",
                    xValue: dates.ToArray(),
                    yValues: data.ToArray(),
                    chartArea: someString)

The chart area data is now just a string and you have chart themes are a string and there are a few defaults.

This seems like a massive step backwards? Am I missing something fundamental?


问:
Excel: How to merge two columns into one (from different sheets or separated columns)
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

```<code>A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3
</code>```

To get the above solution in C column I should use:

```<code>=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)
</code>```

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

答:
If you want to stick to your formula, then you could modify it like this:

https://1drv.ms/x/s!AncAhUkdErOkguUaToQkVkl5Qw-l_g?e=5d9gVM

Odd Start row

```<code>=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$2);2)=1;4;1))
</code>```

Even Start row

```<code>=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$1);2)=1;4;1))
</code>```

What is A1 in the picture is the cell directly above your first data cell.

If you want to place it on a different sheet you just add the sheet name:

```<code>=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$2);2)=1;4;1))
=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$1);2)=1;4;1))
</code>```

Body:
I have met some problem with merging two columns to one.
I have some solution but not exactly fits to my problem (found here: Excel: Merge two columns into one column with alternating values)

As I understand two columns has to be one by one:

A       B       C
==================
A       1       A
B       2       1
C       3       B
                2
                C
                3

To get the above solution in C column I should use:

=INDEX($A$2:$B$9;ROUND(ROW(A1)/2;0);MOD(ROW();2)+1)

So in the formula I'm using data like A1:B4.

How to do it if I will have columns with data A and D and I dont want to include columns B and C?
Or for instance I will have one column from sheet_A and second column from sheet_B?

Body:
If you want to stick to your formula, then you could modify it like this:

https://1drv.ms/x/s!AncAhUkdErOkguUaToQkVkl5Qw-l_g?e=5d9gVM

Odd Start row

=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$2);2)=1;4;1))

Even Start row

=INDEX($A$2:$D$9;ROUND(ROW(A1)/2;0);IF(MOD(ROW()-ROW($A$1);2)=1;4;1))

What is A1 in the picture is the cell directly above your first data cell.

If you want to place it on a different sheet you just add the sheet name:

=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$2);2)=1;4;1))
=INDEX(MySheet!$A$2:$D$9;ROUND(ROW(MySheet!A1)/2;0);IF(MOD(ROW()-ROW(MySheet!$A$1);2)=1;4;1))


问:
Why can't Selenium Web Driver find the elements in this case?
Selenium newbie here. The examples I tried so far worked well but now I stumbled upon a case that seemingly doesn't work:

```<code>import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GeckoDriverTest
{

public static void main(String[] args) throws Throwable
{
    System.setProperty("webdriver.gecko.driver", "D://XXX/seleniumdrivers/geckodriver.exe");
    FirefoxDriver driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.aerzen.com/de/karriere/stellenangebote.html");

    System.out.println("URL = "+driver.getCurrentUrl());

    Thread.sleep(3000);

    driver.findElement(By.cssSelector("a.consent-banner--accept.button.submit")).click();

    Thread.sleep(3000);

    System.out.println("URL = "+driver.getCurrentUrl());

    List<WebElement> elements = driver.findElements(By.cssSelector("tr > td > a"));
    System.out.println("Elements: "+elements.size());
    for(WebElement element : elements)
    {
        String url = element.getAttribute("href");
        System.out.println(url);
    }
}
}
</code>```

The first part does work but the "tr > td > a" selector doesn't find any elements although I'm pretty sure they exist (I can see them in the browser window).

Any idea what's going wrong there? Thanks a lot.

答:
The table is inside an iframe. In order to access these elements you will need to switch to that iframe.

Also instead of tr > td > a cssSelector try using table td.real_table_col1 a cssSelector.

This should work better:

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe")));
List<WebElement> elements = driver.findElements(By.cssSelector("table td.real_table_col1 a"));
    System.out.println("Elements: "+elements.size());
    for(WebElement element : elements)
    {
        String url = element.getAttribute("href");
        System.out.println(url);
    }
```
<p>Also instead of hardcoded pauses like</p>
<pre class="lang-java prettyprint-override"><code>Thread.sleep(3000);
</code>```

You should use ExpectedConditions something like

WebdriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.consent-banner--accept.button.submit")));
```

Body:
Selenium newbie here. The examples I tried so far worked well but now I stumbled upon a case that seemingly doesn't work:

import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class GeckoDriverTest
{

public static void main(String[] args) throws Throwable
{
    System.setProperty("webdriver.gecko.driver", "D://XXX/seleniumdrivers/geckodriver.exe");
    FirefoxDriver driver=new FirefoxDriver();
    driver.manage().window().maximize();
    driver.get("https://www.aerzen.com/de/karriere/stellenangebote.html");

    System.out.println("URL = "+driver.getCurrentUrl());

    Thread.sleep(3000);

    driver.findElement(By.cssSelector("a.consent-banner--accept.button.submit")).click();

    Thread.sleep(3000);

    System.out.println("URL = "+driver.getCurrentUrl());

    List<WebElement> elements = driver.findElements(By.cssSelector("tr > td > a"));
    System.out.println("Elements: "+elements.size());
    for(WebElement element : elements)
    {
        String url = element.getAttribute("href");
        System.out.println(url);
    }
}
}

The first part does work but the "tr > td > a" selector doesn't find any elements although I'm pretty sure they exist (I can see them in the browser window).

Any idea what's going wrong there? Thanks a lot.

Body:
The table is inside an iframe. In order to access these elements you will need to switch to that iframe.

Also instead of tr > td > a cssSelector try using table td.real_table_col1 a cssSelector.

This should work better:

wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//iframe")));
driver.switchTo().frame(driver.findElement(By.xpath("//iframe")));
List<WebElement> elements = driver.findElements(By.cssSelector("table td.real_table_col1 a"));
    System.out.println("Elements: "+elements.size());
    for(WebElement element : elements)
    {
        String url = element.getAttribute("href");
        System.out.println(url);
    }

Also instead of hardcoded pauses like

Thread.sleep(3000);

You should use ExpectedConditions something like

WebdriverWait wait = new WebDriverWait(driver, 30);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("a.consent-banner--accept.button.submit")));


问:
package com.sun.beans.finder does not exist openjdk
When a file is compiled that imports com.sun.beans.finder.ConstructorFinder, this error comes out:

```<code>./src/Demo/FeatConstruction.java:14: error: package com.sun.beans.finder does not exist
</code>```

The system is an Ubuntu 18.04.1 with OpenJDK:

```<code>openjdk version "1.8.0_322"
OpenJDK Runtime Environment (build 1.8.0_322-b06)
</code>```

Where can I find this package?

The compilation process is as follows:

Sources files are located in src

Some jar dependencies are in lib

The output classes are in bin

For ./src/Demo/FeatConstruction.java, I compile it using:

javac -cp "./src:./lib" -d bin ./src/Demo/FeatConstruction.java
```

答:
I found a trace of these classes here:
https://www.programcreek.com/java-api-examples/docs/?api=com.sun.beans.finder.ClassFinder

From the package name I'd conclude they come from the times when Sun owned the Java stuff and thus are at most to be found in Oracle JDK - but not as the standard classes.

To lookup classes, you may want to switch to the standardized API.
For any Object (or derived class instance), run

```<code>Class objectClass = Class.forName("java.lang.Object");
</code>```

With that you can also find classes by name and get class references back - and it is available on all Java implementations.

Body:
When a file is compiled that imports com.sun.beans.finder.ConstructorFinder, this error comes out:

./src/Demo/FeatConstruction.java:14: error: package com.sun.beans.finder does not exist

The system is an Ubuntu 18.04.1 with OpenJDK:

openjdk version "1.8.0_322"
OpenJDK Runtime Environment (build 1.8.0_322-b06)

Where can I find this package?

The compilation process is as follows:

Sources files are located in src

Some jar dependencies are in lib

The output classes are in bin

For ./src/Demo/FeatConstruction.java, I compile it using:

javac -cp "./src:./lib" -d bin ./src/Demo/FeatConstruction.java

Body:
I found a trace of these classes here:
https://www.programcreek.com/java-api-examples/docs/?api=com.sun.beans.finder.ClassFinder

From the package name I'd conclude they come from the times when Sun owned the Java stuff and thus are at most to be found in Oracle JDK - but not as the standard classes.

To lookup classes, you may want to switch to the standardized API.
For any Object (or derived class instance), run

Class objectClass = Class.forName("java.lang.Object");

With that you can also find classes by name and get class references back - and it is available on all Java implementations.


问:
Flutter JSON serializable using json_annotation package how to use JsonConverter with Firebase Firestore DocumentReference
I'm trying to save a DocumentReference in models using JSON serializable with a custom JsonConverter but not doing it correct

here is my model

```<code>@DocumentSerializer()
DocumentReference? recentTrainingRef;
</code>```

My DocumentSerializer Class

```<code>class DocumentSerializer
    implements JsonConverter<DocumentReference, DocumentReference> {
  const DocumentSerializer();

  @override
  DocumentReference fromJson(DocumentReference docRef) => docRef;

  @override
  DocumentReference toJson(DocumentReference docRef) => docRef;
}
</code>```

I'm getting the following error Could not generate fromJson code for recentTrainingRef.

答:
As noted in my answer Are type DocumentReference supported by json_serializable?, due to https://github.com/google/json_serializable.dart/issues/822, you need a nullable document serializer because your type (DocumentReference?) is nullable (because of the ? at the end).

Quite simply (and you'll need to add @DocumentSerializerNullable() annotation before the class you're trying to use it with).

```<code>class DocumentSerializerNullable
    implements JsonConverter<DocumentReference?, DocumentReference?> {
  const DocumentSerializerNullable();

  @override
  DocumentReference? fromJson(DocumentReference? docRef) => docRef;

  @override
  DocumentReference? toJson(DocumentReference? docRef) => docRef;
}
</code>```

Body:
I'm trying to save a DocumentReference in models using JSON serializable with a custom JsonConverter but not doing it correct

here is my model

@DocumentSerializer()
DocumentReference? recentTrainingRef;

My DocumentSerializer Class

class DocumentSerializer
    implements JsonConverter<DocumentReference, DocumentReference> {
  const DocumentSerializer();

  @override
  DocumentReference fromJson(DocumentReference docRef) => docRef;

  @override
  DocumentReference toJson(DocumentReference docRef) => docRef;
}

I'm getting the following error Could not generate fromJson code for recentTrainingRef.

Body:
As noted in my answer Are type DocumentReference supported by json_serializable?, due to https://github.com/google/json_serializable.dart/issues/822, you need a nullable document serializer because your type (DocumentReference?) is nullable (because of the ? at the end).

Quite simply (and you'll need to add @DocumentSerializerNullable() annotation before the class you're trying to use it with).

class DocumentSerializerNullable
    implements JsonConverter<DocumentReference?, DocumentReference?> {
  const DocumentSerializerNullable();

  @override
  DocumentReference? fromJson(DocumentReference? docRef) => docRef;

  @override
  DocumentReference? toJson(DocumentReference? docRef) => docRef;
}


问:
Adding files to stripe connect
I'm trying to add some files (identity documents) to stripe to create a connected account, but I'm having trouble with uploading them from client side to stripe. My backend is in Node.js and the Stripe documentation says it should use this format:

```<code>const Stripe = require('stripe');
const stripe = Stripe('stripeAPIKEY');
var fp = fs.readFileSync('/path/to/a/file.jpg');
var file = await stripe.files.create({
  purpose: 'identity_document',
  file: {
    data: fp,
    name: 'file.jpg',
    type: 'image/jpg',
  },
});
</code>```

I need to upload the file data (the variable fp), but I can't seem to get the relevant path for when the user uploads their document in the client side in Javascript. Here is my function call to Stripe:

```<code>export const uploadPersonIdFile = async (identityDocument: any) => {
    const fp = fs.readFileSync(identityDocument);
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: fp,
            name: 'idDocument.jpg',
            type: 'image/jpg',
        },
    });
    return personId;
}
</code>```

My client side looks like this:

```<code>        const inpFileU = $("#utilityButton");
        const previewImage = $("#image-preview__image-U");
        const previewDefaultText = $("#image-preview__default-text-U");

        inpFileU.change(function(){
            const file = this.files[0];
            if(file){
                const reader = new FileReader();
                previewImage.css("display", "block");
                reader.addEventListener("load", function(){
                    previewImage.attr("src", this.result);
                });
                reader.readAsDataURL(file);
                utilityFileName = file.name;

                await uploadMerchantUtilityDocument({
                    utilityDocument: utilityFileName
                }).then((result) => {
                    /** @type {any} */
                    const data = result.data;
                    const textData = data.text;
                    console.log(JSON.stringify(data));
                    console.log(JSON.stringify(textData));
                }).catch((error) => {
                    console.log("Error message: " + error.message);
                    console.log("Error details: " + error.details);
                });

            } else {
              console.log('no file');
            }
        });
</code>```

I upload the file and then the error message response I keep getting is this:
Error: ENOENT: no such file or directory, open 'insuranceImage.jpeg'

How should I upload my file? I think my fp variable is wrong, but I don't know what to replace it with

答:
As far as I understood you are uploading files from the client to the server and from the server you want to upload to stripe API. In this case, when you read a file with fs default encoding is utf8 but maybe when the file uploaded it was encoded as base64. I do not know too much about jquery. Check how it was encoded, so use the correct encoding.

```<code>  const image= fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});
</code>```

I think somehow the image is broken. If the image path is correct, just manually place an image in that directory, and then read from it as utf8 encoding.

since u got this error base64 string is too large to process in fs.readFileSync which means your path is correct.

```<code>reader = fs.createReadStream('imagePath', {
  flag: 'a+',
  // then try this to base64
  encoding: 'UTF-8',
  start: 5,
  end: 64,
  highWaterMark: 16
});

// Read and display the file data on console
reader.on('data', function (chunk) {
   console.log(chunk);
});
</code>```

Title: Adding files to stripe connect

Body:
I'm trying to add some files (identity documents) to stripe to create a connected account, but I'm having trouble with uploading them from client side to stripe. My backend is in Node.js and the Stripe documentation says it should use this format:

const Stripe = require('stripe');
const stripe = Stripe('stripeAPIKEY');
var fp = fs.readFileSync('/path/to/a/file.jpg');
var file = await stripe.files.create({
  purpose: 'identity_document',
  file: {
    data: fp,
    name: 'file.jpg',
    type: 'image/jpg',
  },
});

I need to upload the file data (the variable fp), but I can't seem to get the relevant path for when the user uploads their document in the client side in Javascript. Here is my function call to Stripe:

export const uploadPersonIdFile = async (identityDocument: any) => {
    const fp = fs.readFileSync(identityDocument);
    const personId = await stripe.files.create({
        purpose: 'identity_document',
        file: {
            data: fp,
            name: 'idDocument.jpg',
            type: 'image/jpg',
        },
    });
    return personId;
}

My client side looks like this:

        const inpFileU = $("#utilityButton");
        const previewImage = $("#image-preview__image-U");
        const previewDefaultText = $("#image-preview__default-text-U");

        inpFileU.change(function(){
            const file = this.files[0];
            if(file){
                const reader = new FileReader();
                previewImage.css("display", "block");
                reader.addEventListener("load", function(){
                    previewImage.attr("src", this.result);
                });
                reader.readAsDataURL(file);
                utilityFileName = file.name;

                await uploadMerchantUtilityDocument({
                    utilityDocument: utilityFileName
                }).then((result) => {
                    /** @type {any} */
                    const data = result.data;
                    const textData = data.text;
                    console.log(JSON.stringify(data));
                    console.log(JSON.stringify(textData));
                }).catch((error) => {
                    console.log("Error message: " + error.message);
                    console.log("Error details: " + error.details);
                });

            } else {
              console.log('no file');
            }
        });

I upload the file and then the error message response I keep getting is this:
Error: ENOENT: no such file or directory, open 'insuranceImage.jpeg'

How should I upload my file? I think my fp variable is wrong, but I don't know what to replace it with

Body:
As far as I understood you are uploading files from the client to the server and from the server you want to upload to stripe API. In this case, when you read a file with fs default encoding is utf8 but maybe when the file uploaded it was encoded as base64. I do not know too much about jquery. Check how it was encoded, so use the correct encoding.

  const image= fs.readFileSync('/path/to/file.jpg', {encoding: 'base64'});

I think somehow the image is broken. If the image path is correct, just manually place an image in that directory, and then read from it as utf8 encoding.

since u got this error base64 string is too large to process in fs.readFileSync which means your path is correct.

reader = fs.createReadStream('imagePath', {
  flag: 'a+',
  // then try this to base64
  encoding: 'UTF-8',
  start: 5,
  end: 64,
  highWaterMark: 16
});

// Read and display the file data on console
reader.on('data', function (chunk) {
   console.log(chunk);
});


问:
How to grant access to google cloud storage buckets based on users auth uid
I am running a cloud function that saves images like this:

```<code>//Pseudocode
const admin = await import("firebase-admin");
const bucket = admin.storage().bucket();
const file = bucket.file('myName');
const stream = file.createWriteStream({ resumable: false });
...
</code>```

After the images are uploaded, I get the publicUrl like so

```<code>file.publicUrl()
</code>```

and store it in an Object.

This object then gets stored to firestore.

When I now copy this url from the object(the url structure looks like this)
https://storage.googleapis.com/new-project.appspot.com/ZWHpYGSQWYXLlUcAwkRFQLC0u7s1/f2a48bdc-7eb3-4174-9f6e-3fd963003bd7/177373254.png

and paste it into a browser field am getting an error:

<Error>
  AccessDenied
  <Message>Access denied.</Message>
  Anonymous caller does not have storage.objects.get access to the Google Cloud Storage
  object.
</Error>
```
<p>even with the test rules:</p>
```service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true;
      allow write: if false;
    }
  }
}
```

I have read some issues here on stackoverflow and it seems like this is because I am using google cloud storage buckets and not firebase storage buckets (I thought they are the same)

but I am very confused about how to write rules in this case, so that only authenticated firebase users can read files.

Any help is highly appreciated.

答:
The bucket is shared between Firebase and Cloud Storage, but the way you access the bucket is quite different.

When you access the bucket through a Firebase SDK, or through a download URL generated by a Firebase SDK, your access goes through a Firebase layer. This layer enforces the security rules (for the SDK), and grants temporary read-only access to the download URL.

When you access the bucket through a Cloud SDK, or a signed URL generated by a Cloud SDK, your access does not go through any Firebase layer, and thus Firebase security rules have no effect on this access.

The public URL you have is just a way to identify a file in your Cloud Storage bucket. It does not have any implied access permissions. You will need to make sure the IAM properties for your bucket allow the access you want the user to have to the file.

Body:
I am running a cloud function that saves images like this:

//Pseudocode
const admin = await import("firebase-admin");
const bucket = admin.storage().bucket();
const file = bucket.file('myName');
const stream = file.createWriteStream({ resumable: false });
...

After the images are uploaded, I get the publicUrl like so

file.publicUrl()

and store it in an Object.

This object then gets stored to firestore.

When I now copy this url from the object(the url structure looks like this)
https://storage.googleapis.com/new-project.appspot.com/ZWHpYGSQWYXLlUcAwkRFQLC0u7s1/f2a48bdc-7eb3-4174-9f6e-3fd963003bd7/177373254.png

and paste it into a browser field am getting an error:

<Error>
  AccessDenied
  <Message>Access denied.</Message>
  Anonymous caller does not have storage.objects.get access to the Google Cloud Storage
  object.
</Error>

even with the test rules:

service firebase.storage {
  match /b/{bucket}/o {
    match /{allPaths=**} {
      allow read: if true;
      allow write: if false;
    }
  }
}

I have read some issues here on stackoverflow and it seems like this is because I am using google cloud storage buckets and not firebase storage buckets (I thought they are the same)

but I am very confused about how to write rules in this case, so that only authenticated firebase users can read files.

Any help is highly appreciated.


问:
Terraform : for_each one by one
I have created a module on terraform, this module creates aws_servicecatalog_provisioned_product resources.

When I call this module from the root I am using for_each to run into a list of objects.

The module runs into this list of objects and creates the aws_servicecatalog_provisioned_product resources in parallel.

Is there a way to create the resources one by one? I want that the module will wait for the first iteration to be done and to create the next just after.

答:
I am using terraform templatefile that creates resources with a depends on order, and then terraform creates resources one by one.

Here is the code:

```<code>locals {

     expanded_accounts = [
      {
          AccountEmail                           = example1@example.com
          AccountName                         = example1
          ManagedOrganizationalUnit           = example_ou1
          SSOUserEmail                        = example1@example.com
          SSOUserFirstName                    = Daniel
          SSOUserLastName                     = Wor
          ou_id                               = ou_id1
      },
      {
          AccountEmail                           = example2@example.com
          AccountName                         = example2
          ManagedOrganizationalUnit           = example_ou2
          SSOUserEmail                        = example2@example.com
          SSOUserFirstName                    = Ben
          SSOUserLastName                     = John
          ou_id                               = ou_id2
     }
     ]

  previous_resource = [
    for acc in local.expanded_accounts :
    acc.AccountName
  ]

     resources = { res = local.expanded_accounts, previous = concat([""], local.previous_resource)
}

resource "local_file" "this" {
  content              = templatefile("./provisioned_accounts.tpl", local.resources)
  filename             = "./generated_provisioned_accounts.tf"
  directory_permission = "0777"
  file_permission      = "0777"

  lifecycle {
    ignore_changes = [directory_permission, file_permission, filename]
  }
}
</code>```

provisioned_accounts.tpl configuration:

```<code>%{ for acc in res }
resource "aws_servicecatalog_provisioned_product" "${acc.AccountName}" {
  name                     = "${acc.AccountName}"
  product_id               = replace(data.local_file.product_name.content, "\n", "")
  provisioning_artifact_id = replace(data.local_file.pa_name.content, "\n", "")

  provisioning_parameters {
    key   = "SSOUserEmail"
    value = "${acc.SSOUserEmail}"
  }
  provisioning_parameters {
    key   = "AccountEmail"
    value = "${acc.AccountEmail}"
  }
  provisioning_parameters {
    key   = "AccountName"
    value = "${acc.AccountName}"
  }
  provisioning_parameters {
    key   = "ManagedOrganizationalUnit"
    value = "${acc.ManagedOrganizationalUnit} (${acc.ou_id})"
  }
  provisioning_parameters {
    key   = "SSOUserLastName"
    value = "${acc.SSOUserLastName}"
  }
  provisioning_parameters {
    key   = "SSOUserFirstName"
    value = "${acc.SSOUserFirstName}"
  }

  timeouts {
    create = "60m"
  }

%{if index != 0 }
  depends_on = [aws_servicecatalog_provisioned_product.${previous[index]}]
%{ endif }

}

%{~ endfor ~}
</code>```

Title: Terraform : for_each one by one

Body:
I am using terraform templatefile that creates resources with a depends on order, and then terraform creates resources one by one.

Here is the code:

locals {

     expanded_accounts = [
      {
          AccountEmail                           = example1@example.com
          AccountName                         = example1
          ManagedOrganizationalUnit           = example_ou1
          SSOUserEmail                        = example1@example.com
          SSOUserFirstName                    = Daniel
          SSOUserLastName                     = Wor
          ou_id                               = ou_id1
      },
      {
          AccountEmail                           = example2@example.com
          AccountName                         = example2
          ManagedOrganizationalUnit           = example_ou2
          SSOUserEmail                        = example2@example.com
          SSOUserFirstName                    = Ben
          SSOUserLastName                     = John
          ou_id                               = ou_id2
     }
     ]

  previous_resource = [
    for acc in local.expanded_accounts :
    acc.AccountName
  ]

     resources = { res = local.expanded_accounts, previous = concat([""], local.previous_resource)
}

resource "local_file" "this" {
  content              = templatefile("./provisioned_accounts.tpl", local.resources)
  filename             = "./generated_provisioned_accounts.tf"
  directory_permission = "0777"
  file_permission      = "0777"

  lifecycle {
    ignore_changes = [directory_permission, file_permission, filename]
  }
}

provisioned_accounts.tpl configuration:

%{ for acc in res }
resource "aws_servicecatalog_provisioned_product" "${acc.AccountName}" {
  name                     = "${acc.AccountName}"
  product_id               = replace(data.local_file.product_name.content, "\n", "")
  provisioning_artifact_id = replace(data.local_file.pa_name.content, "\n", "")

  provisioning_parameters {
    key   = "SSOUserEmail"
    value = "${acc.SSOUserEmail}"
  }
  provisioning_parameters {
    key   = "AccountEmail"
    value = "${acc.AccountEmail}"
  }
  provisioning_parameters {
    key   = "AccountName"
    value = "${acc.AccountName}"
  }
  provisioning_parameters {
    key   = "ManagedOrganizationalUnit"
    value = "${acc.ManagedOrganizationalUnit} (${acc.ou_id})"
  }
  provisioning_parameters {
    key   = "SSOUserLastName"
    value = "${acc.SSOUserLastName}"
  }
  provisioning_parameters {
    key   = "SSOUserFirstName"
    value = "${acc.SSOUserFirstName}"
  }

  timeouts {
    create = "60m"
  }

%{if index != 0 }
  depends_on = [aws_servicecatalog_provisioned_product.${previous[index]}]
%{ endif }

}

%{~ endfor ~}


问:
Django if created new object
I will running something function if created new object. But i will not run if the object already exists

Example:

```<code>class Model(models.Model):
   test = models.Charfield(max_length=255)

   if created new object(!):
      requests.POST(blablabla)
</code>```

答:
You can use django post_save signal:

```<code>from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, created, **kwargs):
    if created:
        # do what you want
        # instance is your just created model instance
</code>```

More about signals in Django docs.

Title: Django if created new object

Body:
I will running something function if created new object. But i will not run if the object already exists

Example:

class Model(models.Model):
   test = models.Charfield(max_length=255)

   if created new object(!):
      requests.POST(blablabla)

Body:
You can use django post_save signal:

from django.db.models.signals import post_save
from django.dispatch import receiver
from myapp.models import MyModel

@receiver(post_save, sender=MyModel)
def my_handler(sender, instance, created, **kwargs):
    if created:
        # do what you want
        # instance is your just created model instance

More about signals in Django docs.


问:
Device manager does not work (open) after updating Android Studio to 2021.1.1
Android studio's device manager AVD manager works fine in old versions, but in 2021.1.1 version does not open!
Windows 10 and 11 tested
last version flutter
Intel
Sdk manager everything updated
could anyone help?</p>

答:
I still have the same problem with the Bumblebee version, but for now you can use the Search Everywhere feature (you can access "Search Everywhere" by pressing double shift) and type in

"Virtual Device Manager"

then it will works.
This is a temporary solution for now.


问:
Vaadin Layout dont Diaply Buttons
Hi am usin Vaadin to code an WebApplication.
I use this Vaadin Addon:
https://vaadin.com/directory/component/carousel-addon

My Problem is that my Button layout only display on the 3rd Carousel Slide and i dont know why.

```<code>private Component crateCarouselSlides(Image iconimage, H1 header, Label infoText) {
    HorizontalLayout buttonLayout = new HorizontalLayout(previousSlideButton,nextSlideButton);
    if(infoText != null){
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,infoText,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }else{
        HorizontalLayout textFields = new HorizontalLayout(new TextField("Name"),new TextField("Playlist"));
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,textFields,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }
}
</code>```

Thanks for your Help. :)

Slide1
Slide3

答:
Could it be that your Label infoText takes more vertical space than your HorizontalLayout textFields in the second case and therefore the buttonLayout is just out of view?

I know that this is no real answer. I tried to add this as comment, but i don't have enough reputation.

Title: Vaadin Layout dont Diaply Buttons

Body:
Hi am usin Vaadin to code an WebApplication.
I use this Vaadin Addon:
https://vaadin.com/directory/component/carousel-addon

My Problem is that my Button layout only display on the 3rd Carousel Slide and i dont know why.

private Component crateCarouselSlides(Image iconimage, H1 header, Label infoText) {
    HorizontalLayout buttonLayout = new HorizontalLayout(previousSlideButton,nextSlideButton);
    if(infoText != null){
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,infoText,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }else{
        HorizontalLayout textFields = new HorizontalLayout(new TextField("Name"),new TextField("Playlist"));
        VerticalLayout slideLayout = new VerticalLayout(iconimage,header,textFields,buttonLayout);
        slideLayout.setClassName("slideLayout");
        iconimage.setClassName("iconImage");
        return slideLayout;
    }
}

Thanks for your Help. :)

Slide1
Slide3


问:
Module appearing as uninstalled even though it installed
The title says it all basically. I was trying to code a macro to automate responding to emails, set up the main.py. Just wrote the import and a print. Ran and boom.
Here is a screenshot because I cant actually explain it correctly https://imgur.com/a/faAt7fY</p>

答:
Answer: I tried updating to a new version of python but it seems like it didn't
install correctly, so I opened the installer, uninstalled the new python version from there and now everything works correctly. Thanks to everyone that collaborated!</p>


问:
Error: useHref() may be used only in the context of a <Router> component. It works when I directly put the url as localhost:3000/experiences
I have a navbar that is rendered in every route while the route changes on click.

./components/navbar.jsx

```<code>import React, { Component } from 'react';
import '../App.css';
import { Link } from 'react-router-dom';

class Navbar extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (
            <div id = 'navbar'>

                <div className='name-head'>
                    My Name
                </div>

                <div id = 'nav-links-container'>

                    <Link to='/experiences'>
                        <div className = 'nav-links'>
                            Experiences
                        </div>
                    </Link>

                    <div className = 'nav-links'>
                        Projects
                    </div>

                    <div className = 'nav-links'>
                        Skills
                    </div>

                    <div className = 'nav-links'>
                        Resume
                    </div>

                </div>

            </div>
        );
    }
}

export default Navbar;
</code>```

./components/experiences.jsx

```<code>import React, { Component } from 'react';

class Experiences extends Component {

    render() {
        return (
            <div>
                <h1>hi</h1>
            </div>
        );
    }
}

export default Experiences;
</code>```

index.js

```<code>import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Experiences from './components/experience';

import {
  BrowserRouter as Router,
  Routes,
  Route
} from 'react-router-dom';

ReactDOM.render(

  <React.StrictMode>

    <Navbar />

    <Router>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/experiences" element={<Experiences />} />
      </Routes>

    </Router>

  </React.StrictMode>,

  document.getElementById('root')
);

reportWebVitals();
</code>```

The error doesn't come when I remove the <Link> from the experiences tag in navbar.
There is a similar question posted here: Error: useHref() may be used only in the context of a <Router> component
but doesn't help.

I'm using react router v6

答:
in React Route v6 you can solve this giving the route context to your entire App with  <BrowserRouter>

This is an complete example of index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter } from 'react-router-dom';
import { App }  from './components/App/App.jsx';

ReactDOM.render(
  <React.StrictMode>
    <BrowserRouter>  //that is the key
      <App />
    </BrowserRouter>
  </React.StrictMode>,
  document.getElementById('root')
);
```

Body:
I have a navbar that is rendered in every route while the route changes on click.

./components/navbar.jsx

import React, { Component } from 'react';
import '../App.css';
import { Link } from 'react-router-dom';

class Navbar extends Component {
    constructor(props) {
        super(props);
        this.state = {};
    }
    render() {
        return (

                    My Name

                    <Link to='/experiences'>

                            Experiences

                    </Link>

                        Projects

                        Skills

                        Resume

        );
    }
}

export default Navbar;

./components/experiences.jsx

import React, { Component } from 'react';

class Experiences extends Component {

    render() {
        return (

hi

        );
    }
}

export default Experiences;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import reportWebVitals from './reportWebVitals';
import Navbar from './components/Navbar';
import Home from './components/Home';
import Experiences from './components/experience';

import {
  BrowserRouter as Router,
  Routes,
  Route
} from 'react-router-dom';

ReactDOM.render(

  <React.StrictMode>

    <Navbar />

    <Router>

      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/experiences" element={<Experiences />} />
      </Routes>

    </Router>

  </React.StrictMode>,

  document.getElementById('root')
);

reportWebVitals();

The error doesn't come when I remove the <Link> from the experiences tag in navbar.
There is a similar question posted here: Error: useHref() may be used only in the context of a <Router> component
but doesn't help.

I'm using react router v6