问:
Create Mutex throws Error The system cannot open the device or file specified
I have a dotnet WebApi application which is running on OpenShift (RHEL).
To build the application I am using source2image strategy with the RedHat Image.

https://catalog.redhat.com/software/containers/ubi8/dotnet-60/6182efb9be25a74c00923849

https://github.com/redhat-developer/s2i-dotnetcore

After updating to .net 6.0-22 I am getting following error when I am trying to create a Mutex:

System.IO.IOException: The system cannot open the device or file specified. : 'MutexName'
at System.Threading.Mutex.CreateMutexCore(Boolean initiallyOwned, String name, Boolean& createdNew)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
at Network.Services.GitService.AddSchedule(String region, String site, ScheduleConfigurationViewModel configuration, String commitMessage) in /opt/app-root/src/Src/Infrastructure/Network/Services/GitService.cs:line 122
at WebApi.Controllers.ConfigurationController.Post(String assetId, String commitMessage) in /opt/app-root/src/Src/WebApi/Controllers/ConfigurationController.cs:line 236
at lambda_method259(Closure, Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at WebApi.Common.CustomExceptionHandlerMiddleware.InvokeAsync(HttpContext context, ILogger1 logger, ICurrentUserService currentUserService) in /opt/app-root/src/Src/WebApi/Common/CustomExceptionHandlerMiddleware.cs:line 33
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Code Fragment where the error is thrown:

```<code>public void AddSchedule(string region, string site, ScheduleConfigurationViewModel configuration, string commitMessage)
{
    using var mutex = new Mutex(false, MutexName);
    var hasHandle = false;
    try
    {
        try
        {
            hasHandle = mutex.WaitOne(new TimeSpan(0, 0, 0, 5), false);
        }
        catch (AbandonedMutexException)
        {
            // Log the fact that the mutex was abandoned in another process,
            // it will still get acquired
            hasHandle = true;
        }

        var repoDir = Clone();
        Pull();
        WriteScheduleFile(repoDir, configuration);
        AddAll();
        Commit(commitMessage);
        Push();
    }
    finally
    {
        if (hasHandle)
            mutex.ReleaseMutex();
    }
}
</code>```

Edit

Below you can see the permissions of the mentioned folders. There is a session folder where I don't have rights. Is this the problem?

```<code>ls -la /
</code>```

```<code>ls -la /tmp
</code>```

```<code>ls -la /tmp/.dotnet/shm
</code>```

Rights before the update:

```<code>ls -la /tmp/.dotnet/shm
</code>```

Workaround

Add .s2i/bin folder to the source repo with an assemble file with following content.

This will delete the session folder from the build process.

#!/bin/bash
echo "Before assembling"

/usr/libexec/s2i/assemble
rc=$?

if [ $rc -eq 0 ]; then
    echo "After successful assembling"
    echo "Delete /tmp/.dotnet/shm/*"
    rm -rf /tmp/.dotnet/shm/*
else
    echo "After failed assembling"
fi

exit $rc
```

Body:
I have a dotnet WebApi application which is running on OpenShift (RHEL).
To build the application I am using source2image strategy with the RedHat Image.

https://catalog.redhat.com/software/containers/ubi8/dotnet-60/6182efb9be25a74c00923849

https://github.com/redhat-developer/s2i-dotnetcore

After updating to .net 6.0-22 I am getting following error when I am trying to create a Mutex:

System.IO.IOException: The system cannot open the device or file specified. : 'MutexName'
at System.Threading.Mutex.CreateMutexCore(Boolean initiallyOwned, String name, Boolean& createdNew)
at System.Threading.Mutex..ctor(Boolean initiallyOwned, String name)
at Network.Services.GitService.AddSchedule(String region, String site, ScheduleConfigurationViewModel configuration, String commitMessage) in /opt/app-root/src/Src/Infrastructure/Network/Services/GitService.cs:line 122
at WebApi.Controllers.ConfigurationController.Post(String assetId, String commitMessage) in /opt/app-root/src/Src/WebApi/Controllers/ConfigurationController.cs:line 236
at lambda_method259(Closure, Object)
at Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor.TaskOfActionResultExecutor.Execute(ActionContext actionContext, IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask1 actionResultValueTask) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|25_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|20_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope) at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger) at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context) at WebApi.Common.CustomExceptionHandlerMiddleware.InvokeAsync(HttpContext context, ILogger1 logger, ICurrentUserService currentUserService) in /opt/app-root/src/Src/WebApi/Common/CustomExceptionHandlerMiddleware.cs:line 33
at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
at Serilog.AspNetCore.RequestLoggingMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddlewareImpl.Invoke(HttpContext context)

Code Fragment where the error is thrown:

public void AddSchedule(string region, string site, ScheduleConfigurationViewModel configuration, string commitMessage)
{
    using var mutex = new Mutex(false, MutexName);
    var hasHandle = false;
    try
    {
        try
        {
            hasHandle = mutex.WaitOne(new TimeSpan(0, 0, 0, 5), false);
        }
        catch (AbandonedMutexException)
        {
            // Log the fact that the mutex was abandoned in another process,
            // it will still get acquired
            hasHandle = true;
        }

        var repoDir = Clone();
        Pull();
        WriteScheduleFile(repoDir, configuration);
        AddAll();
        Commit(commitMessage);
        Push();
    }
    finally
    {
        if (hasHandle)
            mutex.ReleaseMutex();
    }
}

Edit

Below you can see the permissions of the mentioned folders. There is a session folder where I don't have rights. Is this the problem?

ls -la /

ls -la /tmp

ls -la /tmp/.dotnet/shm

Rights before the update:

ls -la /tmp/.dotnet/shm

Workaround

Add .s2i/bin folder to the source repo with an assemble file with following content.

This will delete the session folder from the build process.

#!/bin/bash
echo "Before assembling"

/usr/libexec/s2i/assemble
rc=$?

if [ $rc -eq 0 ]; then
    echo "After successful assembling"
    echo "Delete /tmp/.dotnet/shm/*"
    rm -rf /tmp/.dotnet/shm/*
else
    echo "After failed assembling"
fi

exit $rc


来源: stackexchange

问:
Flutter application - Google play console advertising ID error
I have the following error when uploading my flutter app bundle to google play console.

In my application I don't have com.google.android.gms.permission.AD_ID included in applicationmanifest.xml

Please help me with this

ContentLicense: CC BY-SA 4.0


问:
Interpolate 3D circle to 2D to draw a polyline
I want to improve my 3d circle rendering code by reducing the amount of world2screen calls.

The 3D center and radius of the circle is known, and I have a working example which converts the 3D circle in world coordinates to a 2D poly line with screen coordinates.
However when profiling I noticed that the excessive amount of world2screen calls is really a bottle neck when rendering a lot of circles.
I guess I can just project a limited amount of points to 2D using w2s and interpolate the rest of them?

The minimum amount of points should be 3 for an circle/ellipse, however I didn't find a working solution/algorithm for my issue yet.
Can anyone help me or point me in the right direction with this?

void
draw_circle_3d(const glm::vec3& center, float radius)
{
  constexpr auto DRAW_CIRCLE_3D_SEGMENTS = 64;

  std::vector<glm::vec2> screen_points;
  screen_points.reserve(DRAW_CIRCLE_3D_SEGMENTS);

  constexpr float slice = glm::two_pi<float>() / static_cast<float>(DRAW_CIRCLE_3D_SEGMENTS);
  for (size_t i = 0; i < DRAW_CIRCLE_3D_SEGMENTS; ++i) {
    float theta = slice * static_cast<float>(i);
    auto dir = glm::vec3{ radius * std::cos(theta), radius * std::sin(theta), 0 };

    glm::vec2 screen_pos = world2screen(center + dir);
    screen_points.emplace_back(screen_pos);
  }

  draw_poly_line(screen_points);
}
``
```


问:
How to perform an async await operation without Exception?
I want to send email verification in Firebase. Here is what I have tried:

```<code>Scaffold(
    content = {
        Content(
            signUp = { email, password ->
                viewModel.signUp(email, password)
            }
        )
    }
)
</code>```

In the ViewModel I have:

```<code>var signUp by mutableStateOf<Result<Boolean>>(Result.Success(false))

fun signUp(email: String, password: String) = viewModelScope.launch {
    signUp = repo.signUp(email, password)
}
</code>```

And in the repository class I have:

```<code>override suspend fun signUp(email: String, password: String): Result<Boolean> {
    return try {
        auth.createUserWithEmailAndPassword(email, password).await()
        Result.Success(true)
    } catch (exception: Exception) {
        Result.Failure(exception)
    }
}
</code>```

And to get the result I use:

```<code>when(val signUp = viewModel.signUp) {
    is Result.Success -> sendEmail()
    is Result.Failure -> print(signUp.exception.message)
}
</code>```

Which works as expected. I get a Success and I call sendEmail(). Same thing inside the ViewModel:

```<code>var sendEmail by mutableStateOf<Result<Boolean>>(Result.Success(false))

fun sendEmail() = viewModelScope.launch {
    sendEmail = repo.sendEmail()
}
</code>```

Inside the repository I have:

```<code>override suspend fun sendEmail(): Result<Boolean> {
    return try {
        auth.currentUser?.sendEmailVerification()?.await()
        Result.Success(true)
    } catch (exception: Exception) {
        Result.Failure(exception)
    }
}
</code>```

And get it the result:

```<code>when(val sendEmail = viewModel.sendEmail) {
    is Result.Success -> Log.d(TAG, "Please verify email.")
    is Result.Failure -> print(signUp.exception.message)
}
</code>```

Which sends the email, but it also throws an Exception:

```<code>kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelling}@3551205
</code>```

Which means that "Please verify email." is never displayed to the user. How to overcome this situation? Any help would be greatly appreciated.

P.S.

I also have an auth state listener:

```<code>override fun getState(scope: CoroutineScope) = callbackFlow  {
    val listener = FirebaseAuth.AuthStateListener { auth ->
        trySend(auth.currentUser == null)
    }
    auth.addAuthStateListener(listener)
    awaitClose {
        auth.removeAuthStateListener(listener)
    }
}.stateIn(scope, SharingStarted.WhileSubscribed(), auth.currentUser == null)
</code>```

If I remove auth.addAuthStateListener(authStateListener), both operations complete perfectly. How are these operations connected?

Body:
I want to send email verification in Firebase. Here is what I have tried:

Scaffold(
    content = {
        Content(
            signUp = { email, password ->
                viewModel.signUp(email, password)
            }
        )
    }
)

In the ViewModel I have:

var signUp by mutableStateOf<Result<Boolean>>(Result.Success(false))

fun signUp(email: String, password: String) = viewModelScope.launch {
    signUp = repo.signUp(email, password)
}

And in the repository class I have:

override suspend fun signUp(email: String, password: String): Result<Boolean> {
    return try {
        auth.createUserWithEmailAndPassword(email, password).await()
        Result.Success(true)
    } catch (exception: Exception) {
        Result.Failure(exception)
    }
}

And to get the result I use:

when(val signUp = viewModel.signUp) {
    is Result.Success -> sendEmail()
    is Result.Failure -> print(signUp.exception.message)
}

Which works as expected. I get a Success and I call sendEmail(). Same thing inside the ViewModel:

var sendEmail by mutableStateOf<Result<Boolean>>(Result.Success(false))

fun sendEmail() = viewModelScope.launch {
    sendEmail = repo.sendEmail()
}

Inside the repository I have:

override suspend fun sendEmail(): Result<Boolean> {
    return try {
        auth.currentUser?.sendEmailVerification()?.await()
        Result.Success(true)
    } catch (exception: Exception) {
        Result.Failure(exception)
    }
}

And get it the result:

when(val sendEmail = viewModel.sendEmail) {
    is Result.Success -> Log.d(TAG, "Please verify email.")
    is Result.Failure -> print(signUp.exception.message)
}

Which sends the email, but it also throws an Exception:

kotlinx.coroutines.JobCancellationException: Job was cancelled; job=SupervisorJobImpl{Cancelling}@3551205

Which means that "Please verify email." is never displayed to the user. How to overcome this situation? Any help would be greatly appreciated.

P.S.

I also have an auth state listener:

override fun getState(scope: CoroutineScope) = callbackFlow  {
    val listener = FirebaseAuth.AuthStateListener { auth ->
        trySend(auth.currentUser == null)
    }
    auth.addAuthStateListener(listener)
    awaitClose {
        auth.removeAuthStateListener(listener)
    }
}.stateIn(scope, SharingStarted.WhileSubscribed(), auth.currentUser == null)

If I remove auth.addAuthStateListener(authStateListener), both operations complete perfectly. How are these operations connected?


问:
Building Pipelines
I've been recently trying to set up a Pipeline to produce a Machine Learning model. I have built my own data preprocessing classes and a new class with an optimized sklearn algorithm: Regresor_Model; however when I declare the pipeline steps, for example:

```<code>from source.preprocessing_functions import Change_Data_Type, Years_Passed, Duplicated_Data
from source.preprocessing_functions import One_Hot_Encoding_Train, Standard_Scaling_Train, Reduce_Memory_Usage
from source.machine_learning_toolbox import Regresor_Model
from sklearn.pipeline import Pipeline

# Loading the data
# ================
data = lp.load_data(config.DATA,config.ID_VAR)
X, y = data.drop(config.TARGET,axis=1), data[config.TARGET]
X = X[config.PREDICTORS]

# Train-Test Split
# ================
X_train, X_tests, y_train, y_tests = train_test_split(X, y, test_size=0.3, random_state=config.SEED)

# Defining the Pipeline steps
# ===========================
steps = [('to_float', Change_Data_Type('Kms_Driven','Float')), ('years_passed', Years_Passed('Year',config.YEAR)),
         ('duplicates', Duplicated_Data()), ('one_hot_train', One_Hot_Encoding_Train(config.CATEGORICAL,drop_first=False)),
         ('scale_train', Standard_Scaling_Train(config.NUMERICAL)),
         ('reduce_memory', Reduce_Memory_Usage()), ('model', Regresor_Model(config.BOUNDS))]

# Producing the pipeline
# ======================
pipeline = Pipeline(steps)
pipeline.fit(X_train, y_train)
</code>```

and start running the script, I get an error message that it cannot find the module sklearn.preprocessing_functions

preprocessing_functions and machine_learning_toolbox are two scripts where I have stored the preprocessing classes and the optimized machine learning algorithm. In the literature, I have seen they use sklearn.Pipeline with pure sklearn libraries such as estimators = [('reduce_dim', PCA()), ('clf', SVC())]

Is there a walk-around method to create a pipeline using our own preprocessing tools and thus building the pipeline using sklearn?

Title: Building Pipelines

Body:
I've been recently trying to set up a Pipeline to produce a Machine Learning model. I have built my own data preprocessing classes and a new class with an optimized sklearn algorithm: Regresor_Model; however when I declare the pipeline steps, for example:

from source.preprocessing_functions import Change_Data_Type, Years_Passed, Duplicated_Data
from source.preprocessing_functions import One_Hot_Encoding_Train, Standard_Scaling_Train, Reduce_Memory_Usage
from source.machine_learning_toolbox import Regresor_Model
from sklearn.pipeline import Pipeline

# Loading the data
# ================
data = lp.load_data(config.DATA,config.ID_VAR)
X, y = data.drop(config.TARGET,axis=1), data[config.TARGET]
X = X[config.PREDICTORS]

# Train-Test Split
# ================
X_train, X_tests, y_train, y_tests = train_test_split(X, y, test_size=0.3, random_state=config.SEED)

# Defining the Pipeline steps
# ===========================
steps = [('to_float', Change_Data_Type('Kms_Driven','Float')), ('years_passed', Years_Passed('Year',config.YEAR)),
         ('duplicates', Duplicated_Data()), ('one_hot_train', One_Hot_Encoding_Train(config.CATEGORICAL,drop_first=False)),
         ('scale_train', Standard_Scaling_Train(config.NUMERICAL)),
         ('reduce_memory', Reduce_Memory_Usage()), ('model', Regresor_Model(config.BOUNDS))]

# Producing the pipeline
# ======================
pipeline = Pipeline(steps)
pipeline.fit(X_train, y_train)

and start running the script, I get an error message that it cannot find the module sklearn.preprocessing_functions

preprocessing_functions and machine_learning_toolbox are two scripts where I have stored the preprocessing classes and the optimized machine learning algorithm. In the literature, I have seen they use sklearn.Pipeline with pure sklearn libraries such as estimators = [('reduce_dim', PCA()), ('clf', SVC())]

Is there a walk-around method to create a pipeline using our own preprocessing tools and thus building the pipeline using sklearn?


问:
loop validation list set value for dependent validation then save all iterations
i have a data validation list at cell A1
and a dependent validation list at B1 i want this to always be set at last listed item with every change in A1... so far my code
....i have error with that line that has formula1

```<code>
Sub LoopAndSavePDF()
Dim cellA1 As Range
Dim cellB1 As Range
Dim validationA1 As Validation
Dim validationB1 As Validation
Dim item As Variant
Dim lastItem As String

Set cellA1 = Range("A1")
Set validationA1 = cellA1.Validation

Set cellB1 = Range("B1")
Set validationB1 = cellB1.Validation

If validationA1.Type = 3 Then ' 3 indicates a list validation
For Each item In validationA1.Formula1
Set the last item in the dependent validation list in cell B1
lastItem = item

validationB1.Delete
validationB1.Add Type:=3, AlertStyle:=1, Operator:=3, Formula1:=lastItem
validationB1.IgnoreBlank = True
validationB1.InCellDropdown = True

Save the result as a PDF file
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\username\Desktop\" & lastItem & ".pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Next item
End If
End Sub

</code>```

Thanks in advance

```<code></code>```

Body:
i have a data validation list at cell A1
and a dependent validation list at B1 i want this to always be set at last listed item with every change in A1... so far my code
....i have error with that line that has formula1

Sub LoopAndSavePDF()
Dim cellA1 As Range
Dim cellB1 As Range
Dim validationA1 As Validation
Dim validationB1 As Validation
Dim item As Variant
Dim lastItem As String

Set cellA1 = Range("A1")
Set validationA1 = cellA1.Validation

Set cellB1 = Range("B1")
Set validationB1 = cellB1.Validation

If validationA1.Type = 3 Then ' 3 indicates a list validation
For Each item In validationA1.Formula1
Set the last item in the dependent validation list in cell B1
lastItem = item

validationB1.Delete
validationB1.Add Type:=3, AlertStyle:=1, Operator:=3, Formula1:=lastItem
validationB1.IgnoreBlank = True
validationB1.InCellDropdown = True

Save the result as a PDF file
ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF, Filename:= _
        "C:\Users\username\Desktop\" & lastItem & ".pdf", Quality:= _
xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, OpenAfterPublish:=False
Next item
End If
End Sub

Thanks in advance


问:
pytest-bdd StepDefinitionNotFoundError: Step definition is not found:
I have created pytest BDD framework but when I am adding new feature file and test file. I can use shared steps but can't use other steps which are defined in the exact feature file. Please help how can I figure out this.

This shared given step which takes token is working but other step which belongs to exact feature doesn't works.


问:
Links to where OS APIs are invoked in the current .Net source code
My understanding is that .NET has to make invocations to OS-specific API's at some layer in the .NET source code in order to complete the job. This should be depending on the host/target OS, which will result in different invocations to different OS API's (i.e. native library files). My question is: where in the current/latest source code of .NET can I see these OS-specific invocations?

Thank you.


问:
spyder debugger : Windows fatal exception access violation
I got the error message below when debugging in Spyder 5.4 win10.

Note: code is running without problem in vscode!


问:
Will the net.sf.jasperreports » jasperreports-fonts maven dependency add Arial Font?
I'm getting the exception net.sf.jasperreports.engine.util.JRFontNotFoundException Font 'Arial' is not available to the JVM

So after some reading I found a maven dependency which seems to add the Arial font.
https://mvnrepository.com/artifact/net.sf.jasperreports/jasperreports-fonts/6.20.0

Will this dependency add the Arial font, so jasperreports can use it?


问:
Date Object in different Timezone other than servers default timezone | Timezone aware datetime object in java
My Server is running on UTC timezone, I want to save time of any operation in database in IST format, I tried various ways including following.

```<code>Date ISTDate = Calendar.getInstance(TimeZone.getTimeZone("Asia/Kolkata")).getTime();
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata"));
jobRepository.save(new IncremetalJob(ISTDate,ISTDate, JobState.IN_PROGRESS));
</code>```

Everytime UTC date is being saved, can someone suggest here.

Body:
My Server is running on UTC timezone, I want to save time of any operation in database in IST format, I tried various ways including following.

Date ISTDate = Calendar.getInstance(TimeZone.getTimeZone("Asia/Kolkata")).getTime();
TimeZone.setDefault(TimeZone.getTimeZone("Asia/Kolkata"));
jobRepository.save(new IncremetalJob(ISTDate,ISTDate, JobState.IN_PROGRESS));

Everytime UTC date is being saved, can someone suggest here.


问:
Ruby Dir.glob with UNC paths containing spaces
I would like to list all files and folders in an UNC path.
I'm on Windows Server 2012, Ruby 2.5.8

By using Dir.entries, it works:

```<code>Dir.entries('//example.xyz/se/PA/abc/T - Projects/15 B').each do | filename |
    puts filename
end
</code>```

But with Dir.glob I get an empty output:

```<code>Dir.glob('//example.xyz/se/PA/abc/T - Projects/15 B/*').each do | filename |
    puts filename
end
</code>```

I want to use the glob variant, as I will possibly not want to list everything in the directory.

Help would be much appreciated, thank you.

Body:
I would like to list all files and folders in an UNC path.
I'm on Windows Server 2012, Ruby 2.5.8

By using Dir.entries, it works:

Dir.entries('//example.xyz/se/PA/abc/T - Projects/15 B').each do | filename |
    puts filename
end

But with Dir.glob I get an empty output:

Dir.glob('//example.xyz/se/PA/abc/T - Projects/15 B/*').each do | filename |
    puts filename
end

I want to use the glob variant, as I will possibly not want to list everything in the directory.

Help would be much appreciated, thank you.


问:
GTM debugger shows correctly fired GA4 tag, but is not visible in Network tab or GA4 debug view
I have SPA with running gtm container. GTM debugger shows correct container ID. GA4 is set to enhanced measurement with history listener which propagates to GTM Event with correct values for dl and dr for basic page_view.

configuration tag showing "fired"
history changes in gtm debug from GA4 enhanced measurement

But still no page_view collect visible in network, also after adding history/click/link click triggers in gtm, noone of these do appear in gtm debug.

I tried adding custom events to fire along automated ones, moved configuration tag back and forth between init and load. But nothing can send page_view to GA4. I also tried firing page_view manualy from gtm on various events (automated and custom made) with zero effect. This is not the case for testing console.log from custom html code via gtm, which works as expected.


问:
How to limit network ranges in Dovecot
I want to specify some netrange to access dovecot on my mail server.

I adjusted the

```<code>login_trusted_networks =
</code>```

parameter in dovecot.conf but it didn't work, I still can access dovecot in some others netranges.

Here is my dovecot configuration

```<code>/etc/dovecot/dovecot.conf
protocols = imap pop3
listen = *, ::
login_trusted_networks = 192.168.10.0/24 172.18.16.0/24

/etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = no
auth_mechanisms = plain login
!include auth-system.conf.ext

/etc/dovecot/conf.d/10-ssl.conf
ssl = no
</code>```

Title: How to limit network ranges in Dovecot

Body:
I want to specify some netrange to access dovecot on my mail server.

I adjusted the

login_trusted_networks =

parameter in dovecot.conf but it didn't work, I still can access dovecot in some others netranges.

Here is my dovecot configuration

/etc/dovecot/dovecot.conf
protocols = imap pop3
listen = *, ::
login_trusted_networks = 192.168.10.0/24 172.18.16.0/24

/etc/dovecot/conf.d/10-auth.conf
disable_plaintext_auth = no
auth_mechanisms = plain login
!include auth-system.conf.ext

/etc/dovecot/conf.d/10-ssl.conf
ssl = no


问:
How to get a program zero exit code with the help of runtime.addShutdownhook?
I have a thread designed to run forever.

But I want to shut down it gracefully when the program receives an int signal.

I try to use runtime.addShutdownHook() to solve it.

This is my code:

import java.time.LocalDateTime;

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            while (!Thread.interrupted()) {
                String log = String.format("hello %d", LocalDateTime.now().getSecond());
                System.out.println(log);
            }
            System.out.println("end normally");
        });

        thread.start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("I jvm am done");
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }));

//        Signal.handle(new Signal("INT"), signal -> {
//            System.out.println(signal.getName() + " (" + signal.getNumber() + ")");
//            thread.interrupt();
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        });

    }
}
```
<p>As you can see.</p>
<p>The <code>thread</code> can exit normally.</p>
<p>But I got the non-zero exit code!</p>
```Process finished with exit code 130
```
<p>I don't know why and how to get a zero exit code.</p>
<p>I try to use another way:</p>
<pre class="lang-java prettyprint-override"><code>Signal.handle(new Signal("INT"), signal -> {...}
</code>```

It works! I got the zero exit code and it also works correctly.

But I don't know what is wrong with the shutdown hook.

I think it's the best way to deal with the graceful shutdown because I don't need to process all kinds of signals such as SIGHUP, SIGQUIT, and so on.

Body:
I have a thread designed to run forever.

But I want to shut down it gracefully when the program receives an int signal.

I try to use runtime.addShutdownHook() to solve it.

This is my code:

import java.time.LocalDateTime;

public class Main {

    public static void main(String[] args) {

        Thread thread = new Thread(() -> {
            while (!Thread.interrupted()) {
                String log = String.format("hello %d", LocalDateTime.now().getSecond());
                System.out.println(log);
            }
            System.out.println("end normally");
        });

        thread.start();

        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            System.out.println("I jvm am done");
            thread.interrupt();
            try {
                thread.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }));

//        Signal.handle(new Signal("INT"), signal -> {
//            System.out.println(signal.getName() + " (" + signal.getNumber() + ")");
//            thread.interrupt();
//            try {
//                thread.join();
//            } catch (InterruptedException e) {
//                throw new RuntimeException(e);
//            }
//        });

    }
}

As you can see.

The thread can exit normally.

But I got the non-zero exit code!

Process finished with exit code 130

I don't know why and how to get a zero exit code.

I try to use another way:

Signal.handle(new Signal("INT"), signal -> {...}

It works! I got the zero exit code and it also works correctly.

But I don't know what is wrong with the shutdown hook.

I think it's the best way to deal with the graceful shutdown because I don't need to process all kinds of signals such as SIGHUP, SIGQUIT, and so on.


问:
I am trying to use [react-owl-carousel] getting warning in console but this code is running properly in local but not in server
```<code>/** @format */

import React from 'react';
import './Home.css';
import OwlCarousel from 'react-owl-carousel';import 'owl.carousel/dist/assets/owl.carousel.css';import 'owl.carousel/dist/assets/owl.theme.default.css';
const Home = () => {
const options = {autoplay: true,autoplayTimeout: 4000,autoplayHoverPause: true,items: 1,mouseDrag: true,stagePadding: 5,center: true,nav: false,margin: 50,dots: true,loop: true,responsive: {0: { items: 1 },480: { items: 1 },575: { items: 2 },768: { items: 2 },991: { items: 3 },1200: { items: 3 },},};
return (<section>
  <div className='container carousel'>
    <h4 className='text-center m-3 head-title'>Our Completed Projects</h4>
    <OwlCarousel {...options}>

    </OwlCarousel>
  </div>
</section>
);};
export default Home;
</code>```

`react-dom.development.js:86 Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.

Move data fetching code or side effects to componentDidUpdate.

If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state

Please update the following components: ReactOwlCarousel
`

Body:
/** @format */

import React from 'react';
import './Home.css';
import OwlCarousel from 'react-owl-carousel';import 'owl.carousel/dist/assets/owl.carousel.css';import 'owl.carousel/dist/assets/owl.theme.default.css';
const Home = () => {
const options = {autoplay: true,autoplayTimeout: 4000,autoplayHoverPause: true,items: 1,mouseDrag: true,stagePadding: 5,center: true,nav: false,margin: 50,dots: true,loop: true,responsive: {0: { items: 1 },480: { items: 1 },575: { items: 2 },768: { items: 2 },991: { items: 3 },1200: { items: 3 },},};
return (

Our Completed Projects

    <OwlCarousel {...options}>

    </OwlCarousel>

);};
export default Home;

`react-dom.development.js:86 Warning: Using UNSAFE_componentWillReceiveProps in strict mode is not recommended and may indicate bugs in your code. See https://reactjs.org/link/unsafe-component-lifecycles for details.

Move data fetching code or side effects to componentDidUpdate.

If you're updating state whenever props change, refactor your code to use memoization techniques or move it to static getDerivedStateFromProps. Learn more at: https://reactjs.org/link/derived-state

Please update the following components: ReactOwlCarousel
`


问:
cant transfer dataframe into sql server database
I am not able to transfer this dataframe into a sql server database.

```<code>import pyodbc
import pandas as pd

# Connect to the database
conn = pyodbc.connect("Driver={SQL Server};"
                      "Server=servername;"
                      "Database=databasename;"
                      "Trusted_Connection=yes;")

# Create the table
cursor = conn.cursor()
cursor.execute("CREATE TABLE emails (email VARCHAR(255))")

# Write the DataFrame to the database
df.to_sql("emails", conn, if_exists="replace", index=False)

# Commit the transaction
conn.commit()

# Close the connection
conn.close()
</code>```

The error it fives me is

ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server
Driver][SQL Server]Invalid object name 'sqlite_master'. (208)
(SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL
Server]Statement(s) could not be prepared. (8180)")

The above exception was the direct cause of the following exception:

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master
WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC
SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'.
(208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server
Driver][SQL Server]Statement(s) could not be prepared. (8180)")

What am I doing wrong?

Is pyodbc not correctly installed and if so how can i check it? Should I use another Driver as "ODBC Driver 17 for SQL Server" and if so how do I install it?

EDIT: I installed OCDB Driver 18 and added                       "TrustServerCertificate=YES;") to the connection bit. But now it just prints my first error.

('42S02', "[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL
Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW);
[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL
Server]Statement(s) could not be prepared. (8180)")

The above exception was the direct cause of the following exception:

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master
WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC
Driver 18 for SQL Server][SQL Server]Invalid object name
'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC
Driver 18 for SQL Server][SQL Server]Statement(s) could not be
prepared. (8180)")

Body:
I am not able to transfer this dataframe into a sql server database.

import pyodbc
import pandas as pd

# Connect to the database
conn = pyodbc.connect("Driver={SQL Server};"
                      "Server=servername;"
                      "Database=databasename;"
                      "Trusted_Connection=yes;")

# Create the table
cursor = conn.cursor()
cursor.execute("CREATE TABLE emails (email VARCHAR(255))")

# Write the DataFrame to the database
df.to_sql("emails", conn, if_exists="replace", index=False)

# Commit the transaction
conn.commit()

# Close the connection
conn.close()

The error it fives me is

ProgrammingError: ('42S02', "[42S02] [Microsoft][ODBC SQL Server
Driver][SQL Server]Invalid object name 'sqlite_master'. (208)
(SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server Driver][SQL
Server]Statement(s) could not be prepared. (8180)")

The above exception was the direct cause of the following exception:

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master
WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC
SQL Server Driver][SQL Server]Invalid object name 'sqlite_master'.
(208) (SQLExecDirectW); [42S02] [Microsoft][ODBC SQL Server
Driver][SQL Server]Statement(s) could not be prepared. (8180)")

What am I doing wrong?

Is pyodbc not correctly installed and if so how can i check it? Should I use another Driver as "ODBC Driver 17 for SQL Server" and if so how do I install it?

EDIT: I installed OCDB Driver 18 and added                       "TrustServerCertificate=YES;") to the connection bit. But now it just prints my first error.

('42S02', "[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL
Server]Invalid object name 'sqlite_master'. (208) (SQLExecDirectW);
[42S02] [Microsoft][ODBC Driver 18 for SQL Server][SQL
Server]Statement(s) could not be prepared. (8180)")

The above exception was the direct cause of the following exception:

DatabaseError: Execution failed on sql 'SELECT name FROM sqlite_master
WHERE type='table' AND name=?;': ('42S02', "[42S02] [Microsoft][ODBC
Driver 18 for SQL Server][SQL Server]Invalid object name
'sqlite_master'. (208) (SQLExecDirectW); [42S02] [Microsoft][ODBC
Driver 18 for SQL Server][SQL Server]Statement(s) could not be
prepared. (8180)")


问:
I am trying to build a Flutter project and are encountering an error related to the location package, How I fix this error?
```<code>
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':location'.
> Could not load compiled classes for build file 'C:\Flutter\flutter\.pub-cache\hosted\pub.dartlang.org\location-4.4.0\android\build.gradle' from cache.
> Failed to notify project evaluation listener.
2
   > Could not get unknown property 'android' for project ':location' of type org.gradle.api.Project.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 18s
</code>```

I have tried flutter clean , Pub cache repair.
Same project works in other devices, without any code change.

Body:
FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ':location'.
> Could not load compiled classes for build file 'C:\Flutter\flutter\.pub-cache\hosted\pub.dartlang.org\location-4.4.0\android\build.gradle' from cache.
> Failed to notify project evaluation listener.
2
   > Could not get unknown property 'android' for project ':location' of type org.gradle.api.Project.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 2m 18s

I have tried flutter clean , Pub cache repair.
Same project works in other devices, without any code change.


问:
How to package a react.js app for offline installation and use?
I'm developing a PWA with preact which can be used in offline mode.
I use API calls to get some media files for my app.
So far so good.

I've been asked recently if I could install this PWA on a local environment (mainly Windows) taking into account that :

someone with zero knowledge into programming can one click a file to launch the app. So no third party install,

it should ideally be done without the need of having an internet connection at all.

First question is : can it be done with this two constraints ?
If no, how can it be done in the easiest way ?
I'm rather new to js and react and almost without knowledge on node backend, servers etc.

I've been thinking of "packaging" into a folder the built code and the media retrieved from the API. Then simply open the index.html file with a browser. But with this, I have CORS issues I do not know how to bypass...

Then some people told me about electron, expressjs, vercel/pkg, nodejs backend with webpack and my head just blown off :)

If my first idea can work, can someone just guide me towards the solution ?
Else, I'd gladly ask for more precise explanations using another method with some tutorials or at least the great steps.

Thank you all in advance.


问:
How to set an objective C constant from my cocoa pod?
I must pass a variable into the POD's source code at compile time (the IP address of the computer running Xcode), because there is no way to know for the iOS device at runtime otherwise.

I noticed that there is a pre_install hook, but I'm not sure how to use it to set a constant in my source.
Previously, we were using a swift package to do this, now we are trying to make this work in cocoa pods.


问:
How to clip div with animated gradient to an h1 text? See example
So basically I want this animated background to be behind the text, clipped to its outline. Somehow make text transparent. There is a solution to do this if text property of background is set, but i have an underlying div here.
Example is in the CodePen: https://codepen.io/mikhasev/pen/NWBKWmE?editors=1100

```<code><div class="background-text">
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>
  <span></span>

  <h2 class="text-gradient" style="font-size: 10rem; font-family: Verdana, Geneva, Tahoma, sans-serif;z-index: 1;">Hey this is text!</h2>

</div>
</code>```
```<code>@keyframes move {
  100% {
    transform: translate3d(0, 0, 1px) rotate(360deg);
  }
}

.text-gradient {
  mix-blend-mode: overlay;
}
span {
  z-index: -1;
}

.background-text {
  position: fixed;
  width: 100vw;
  height: 100vh;
  bottom: 0;
  left: 0;
  background: #efead7;
  overflow: hidden;
  z-index: -1;
  mix-blend-mode: overlay;
}

.background-text span {
  width: 50vmin;
  height: 50vmin;
  border-radius: 50vmin;
  backface-visibility: hidden;
  position: absolute;
  animation: move;
  animation-duration: 1;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.background-text span:nth-child(0) {
  color: #92b1b6;
  top: 18%;
  left: 69%;
  animation-duration: 415s;
  animation-delay: -83s;
  transform-origin: -23vw -17vh;
  box-shadow: -100vmin 0 13.277364360806693vmin currentColor;
}
.background-text span:nth-child(1) {
  color: #ebe6d4;
  top: 85%;
  left: 52%;
  animation-duration: 84s;
  animation-delay: -475s;
  transform-origin: 24vw -20vh;
  box-shadow: 100vmin 0 12.698539235599371vmin currentColor;
}
.background-text span:nth-child(2) {
  color: #afc0bc;
  top: 50%;
  left: 73%;
  animation-duration: 215s;
  animation-delay: -223s;
  transform-origin: -3vw -21vh;
  box-shadow: 100vmin 0 12.619329856077202vmin currentColor;
}
.background-text span:nth-child(3) {
  color: #92b1b6;
  top: 57%;
  left: 100%;
  animation-duration: 152s;
  animation-delay: -184s;
  transform-origin: 16vw -5vh;
  box-shadow: 100vmin 0 13.391412531934302vmin currentColor;
}
.background-text span:nth-child(4) {
  color: #afc0bc;
  top: 29%;
  left: 31%;
  animation-duration: 251s;
  animation-delay: -479s;
  transform-origin: 8vw 11vh;
  box-shadow: -100vmin 0 13.392276163622956vmin currentColor;
}
.background-text span:nth-child(5) {
  color: #92b1b6;
  top: 8%;
  left: 16%;
  animation-duration: 458s;
  animation-delay: -347s;
  transform-origin: 0vw -8vh;
  box-shadow: 100vmin 0 12.953360718377933vmin currentColor;
}
.background-text span:nth-child(6) {
  color: #afc0bc;
  top: 52%;
  left: 81%;
  animation-duration: 240s;
  animation-delay: -259s;
  transform-origin: -4vw -6vh;
  box-shadow: -100vmin 0 13.364099723400827vmin currentColor;
}
.background-text span:nth-child(7) {
  color: #ebe6d4;
  top: 15%;
  left: 86%;
  animation-duration: 316s;
  animation-delay: -242s;
  transform-origin: 5vw -23vh;
  box-shadow: 100vmin 0 13.403178270311724vmin currentColor;
}
.background-text span:nth-child(8) {
  color: #afc0bc;
  top: 92%;
  left: 94%;
  animation-duration: 52s;
  animation-delay: -160s;
  transform-origin: 10vw 7vh;
  box-shadow: 100vmin 0 12.679415823145838vmin currentColor;
}
.background-text span:nth-child(9) {
  color: #92b1b6;
  top: 50%;
  left: 36%;
  animation-duration: 386s;
  animation-delay: -216s;
  transform-origin: -18vw 11vh;
  box-shadow: -100vmin 0 12.656955807640959vmin currentColor;
}
.background-text span:nth-child(10) {
  color: #ebe6d4;
  top: 90%;
  left: 59%;
  animation-duration: 201s;
  animation-delay: -376s;
  transform-origin: 16vw 23vh;
  box-shadow: -100vmin 0 13.135094466756232vmin currentColor;
}
.background-text span:nth-child(11) {
  color: #ebe6d4;
  top: 60%;
  left: 25%;
  animation-duration: 166s;
  animation-delay: -475s;
  transform-origin: 8vw -24vh;
  box-shadow: 100vmin 0 12.870926137509548vmin currentColor;
}
.background-text span:nth-child(12) {
  color: #afc0bc;
  top: 45%;
  left: 7%;
  animation-duration: 34s;
  animation-delay: -282s;
  transform-origin: -6vw -3vh;
  box-shadow: -100vmin 0 12.98838036669823vmin currentColor;
}
.background-text span:nth-child(13) {
  color: #92b1b6;
  top: 14%;
  left: 70%;
  animation-duration: 482s;
  animation-delay: -359s;
  transform-origin: 20vw 17vh;
  box-shadow: 100vmin 0 13.21853155211687vmin currentColor;
}
.background-text span:nth-child(14) {
  color: #ebe6d4;
  top: 77%;
  left: 17%;
  animation-duration: 31s;
  animation-delay: -323s;
  transform-origin: 2vw 5vh;
  box-shadow: 100vmin 0 12.667784718131708vmin currentColor;
}
.background-text span:nth-child(15) {
  color: #ebe6d4;
  top: 1%;
  left: 85%;
  animation-duration: 101s;
  animation-delay: -268s;
  transform-origin: 12vw -9vh;
  box-shadow: 100vmin 0 12.603938694898146vmin currentColor;
}
.background-text span:nth-child(16) {
  color: #92b1b6;
  top: 8%;
  left: 53%;
  animation-duration: 73s;
  animation-delay: -18s;
  transform-origin: -3vw 2vh;
  box-shadow: -100vmin 0 12.538501381850562vmin currentColor;
}
.background-text span:nth-child(17) {
  color: #92b1b6;
  top: 41%;
  left: 3%;
  animation-duration: 262s;
  animation-delay: -482s;
  transform-origin: -21vw 19vh;
  box-shadow: 100vmin 0 13.134640505582095vmin currentColor;
}
.background-text span:nth-child(18) {
  color: #afc0bc;
  top: 97%;
  left: 51%;
  animation-duration: 289s;
  animation-delay: -285s;
  transform-origin: 8vw 14vh;
  box-shadow: 100vmin 0 13.198355036839116vmin currentColor;
}

</code>```

and the result is this:
enter image description here

Body:
So basically I want this animated background to be behind the text, clipped to its outline. Somehow make text transparent. There is a solution to do this if text property of background is set, but i have an underlying div here.
Example is in the CodePen: https://codepen.io/mikhasev/pen/NWBKWmE?editors=1100

Hey this is text!

@keyframes move {
  100% {
    transform: translate3d(0, 0, 1px) rotate(360deg);
  }
}

.text-gradient {
  mix-blend-mode: overlay;
}
span {
  z-index: -1;
}

.background-text {
  position: fixed;
  width: 100vw;
  height: 100vh;
  bottom: 0;
  left: 0;
  background: #efead7;
  overflow: hidden;
  z-index: -1;
  mix-blend-mode: overlay;
}

.background-text span {
  width: 50vmin;
  height: 50vmin;
  border-radius: 50vmin;
  backface-visibility: hidden;
  position: absolute;
  animation: move;
  animation-duration: 1;
  animation-timing-function: linear;
  animation-iteration-count: infinite;
}

.background-text span:nth-child(0) {
  color: #92b1b6;
  top: 18%;
  left: 69%;
  animation-duration: 415s;
  animation-delay: -83s;
  transform-origin: -23vw -17vh;
  box-shadow: -100vmin 0 13.277364360806693vmin currentColor;
}
.background-text span:nth-child(1) {
  color: #ebe6d4;
  top: 85%;
  left: 52%;
  animation-duration: 84s;
  animation-delay: -475s;
  transform-origin: 24vw -20vh;
  box-shadow: 100vmin 0 12.698539235599371vmin currentColor;
}
.background-text span:nth-child(2) {
  color: #afc0bc;
  top: 50%;
  left: 73%;
  animation-duration: 215s;
  animation-delay: -223s;
  transform-origin: -3vw -21vh;
  box-shadow: 100vmin 0 12.619329856077202vmin currentColor;
}
.background-text span:nth-child(3) {
  color: #92b1b6;
  top: 57%;
  left: 100%;
  animation-duration: 152s;
  animation-delay: -184s;
  transform-origin: 16vw -5vh;
  box-shadow: 100vmin 0 13.391412531934302vmin currentColor;
}
.background-text span:nth-child(4) {
  color: #afc0bc;
  top: 29%;
  left: 31%;
  animation-duration: 251s;
  animation-delay: -479s;
  transform-origin: 8vw 11vh;
  box-shadow: -100vmin 0 13.392276163622956vmin currentColor;
}
.background-text span:nth-child(5) {
  color: #92b1b6;
  top: 8%;
  left: 16%;
  animation-duration: 458s;
  animation-delay: -347s;
  transform-origin: 0vw -8vh;
  box-shadow: 100vmin 0 12.953360718377933vmin currentColor;
}
.background-text span:nth-child(6) {
  color: #afc0bc;
  top: 52%;
  left: 81%;
  animation-duration: 240s;
  animation-delay: -259s;
  transform-origin: -4vw -6vh;
  box-shadow: -100vmin 0 13.364099723400827vmin currentColor;
}
.background-text span:nth-child(7) {
  color: #ebe6d4;
  top: 15%;
  left: 86%;
  animation-duration: 316s;
  animation-delay: -242s;
  transform-origin: 5vw -23vh;
  box-shadow: 100vmin 0 13.403178270311724vmin currentColor;
}
.background-text span:nth-child(8) {
  color: #afc0bc;
  top: 92%;
  left: 94%;
  animation-duration: 52s;
  animation-delay: -160s;
  transform-origin: 10vw 7vh;
  box-shadow: 100vmin 0 12.679415823145838vmin currentColor;
}
.background-text span:nth-child(9) {
  color: #92b1b6;
  top: 50%;
  left: 36%;
  animation-duration: 386s;
  animation-delay: -216s;
  transform-origin: -18vw 11vh;
  box-shadow: -100vmin 0 12.656955807640959vmin currentColor;
}
.background-text span:nth-child(10) {
  color: #ebe6d4;
  top: 90%;
  left: 59%;
  animation-duration: 201s;
  animation-delay: -376s;
  transform-origin: 16vw 23vh;
  box-shadow: -100vmin 0 13.135094466756232vmin currentColor;
}
.background-text span:nth-child(11) {
  color: #ebe6d4;
  top: 60%;
  left: 25%;
  animation-duration: 166s;
  animation-delay: -475s;
  transform-origin: 8vw -24vh;
  box-shadow: 100vmin 0 12.870926137509548vmin currentColor;
}
.background-text span:nth-child(12) {
  color: #afc0bc;
  top: 45%;
  left: 7%;
  animation-duration: 34s;
  animation-delay: -282s;
  transform-origin: -6vw -3vh;
  box-shadow: -100vmin 0 12.98838036669823vmin currentColor;
}
.background-text span:nth-child(13) {
  color: #92b1b6;
  top: 14%;
  left: 70%;
  animation-duration: 482s;
  animation-delay: -359s;
  transform-origin: 20vw 17vh;
  box-shadow: 100vmin 0 13.21853155211687vmin currentColor;
}
.background-text span:nth-child(14) {
  color: #ebe6d4;
  top: 77%;
  left: 17%;
  animation-duration: 31s;
  animation-delay: -323s;
  transform-origin: 2vw 5vh;
  box-shadow: 100vmin 0 12.667784718131708vmin currentColor;
}
.background-text span:nth-child(15) {
  color: #ebe6d4;
  top: 1%;
  left: 85%;
  animation-duration: 101s;
  animation-delay: -268s;
  transform-origin: 12vw -9vh;
  box-shadow: 100vmin 0 12.603938694898146vmin currentColor;
}
.background-text span:nth-child(16) {
  color: #92b1b6;
  top: 8%;
  left: 53%;
  animation-duration: 73s;
  animation-delay: -18s;
  transform-origin: -3vw 2vh;
  box-shadow: -100vmin 0 12.538501381850562vmin currentColor;
}
.background-text span:nth-child(17) {
  color: #92b1b6;
  top: 41%;
  left: 3%;
  animation-duration: 262s;
  animation-delay: -482s;
  transform-origin: -21vw 19vh;
  box-shadow: 100vmin 0 13.134640505582095vmin currentColor;
}
.background-text span:nth-child(18) {
  color: #afc0bc;
  top: 97%;
  left: 51%;
  animation-duration: 289s;
  animation-delay: -285s;
  transform-origin: 8vw 14vh;
  box-shadow: 100vmin 0 13.198355036839116vmin currentColor;
}

and the result is this:
enter image description here


问:
Is there a way around requiring consuming code from having to use `useCallback` when passing a callback to my component

Scenario

WeekdayPicker.tsx

```<code>type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
type WeekdayPickerProps = {
  value: Weekday;
  onChange?: (value: Weekday) => void;
};

export default function WeekdayPicker({ value, onChange }: WeekdayPickerProps) {
  const [weekday, setWeekday] = useState(value);

  const onWeekDayChange = (newValue: Weekday) => {
    setWeekday(newValue); // Keep internal state
    onChange?.(newValue); // Inform consumers about the change...
  }

  return (
    <>
      {/* Pseudo code... */}
      <Select options={allWeekdays} onChange={onWeekDayChange}></Select>
    </>
  )
}
</code>```

Consumer.tsx

```<code>export default function Consumer() {
  const [weekday, setWeekday] = useState('mon');

  // If not wrapped into `useCallback`, every render of the consumer would also
  // cause a unwanted re-render of the `WeekdayPicker`.
  const onWeekDayChange = useCallback((value: Weekday) => {
    persistNewWeekdayOnServer(value); // Pseudo code...
    setWeekday(value);
  }, [setWeekday, persistNewWeekdayOnServer]);

  return (
    <>
      {/* ... */}
      <WeekdayPicker value={weekday} onChange={onWeekDayChange}></WeekdayPicker>
      {/* ... */}
    </>
  )
}
</code>```

The question

Can I somehow write the component WeekdayPicker in a way which does not require the consumer to wrap its onChange callback in useCallback?
I'm mainly asking because libraries like Material UI don't seem to require this and I'm wondering, how they do this.

E.g. code example from MUI docs:

```<code>export default function StateTextFields() {
  const [name, setName] = React.useState('Cat in the Hat');

  // No `useCallback` here!
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  return (
    <Box {/* ... */}>
      <TextField {/* ... */} onChange={handleChange} />
    </Box>
  );
}
</code>```

Body:
Scenario

WeekdayPicker.tsx

type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
type WeekdayPickerProps = {
  value: Weekday;
  onChange?: (value: Weekday) => void;
};

export default function WeekdayPicker({ value, onChange }: WeekdayPickerProps) {
  const [weekday, setWeekday] = useState(value);

  const onWeekDayChange = (newValue: Weekday) => {
    setWeekday(newValue); // Keep internal state
    onChange?.(newValue); // Inform consumers about the change...
  }

  return (
    <>
      {/* Pseudo code... */}
      <Select options={allWeekdays} onChange={onWeekDayChange}></Select>
    </>
  )
}

Consumer.tsx

export default function Consumer() {
  const [weekday, setWeekday] = useState('mon');

  // If not wrapped into `useCallback`, every render of the consumer would also
  // cause a unwanted re-render of the `WeekdayPicker`.
  const onWeekDayChange = useCallback((value: Weekday) => {
    persistNewWeekdayOnServer(value); // Pseudo code...
    setWeekday(value);
  }, [setWeekday, persistNewWeekdayOnServer]);

  return (
    <>
      {/* ... */}
      <WeekdayPicker value={weekday} onChange={onWeekDayChange}></WeekdayPicker>
      {/* ... */}
    </>
  )
}

The question

Can I somehow write the component WeekdayPicker in a way which does not require the consumer to wrap its onChange callback in useCallback?
I'm mainly asking because libraries like Material UI don't seem to require this and I'm wondering, how they do this.

E.g. code example from MUI docs:

export default function StateTextFields() {
  const [name, setName] = React.useState('Cat in the Hat');

  // No `useCallback` here!
  const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
    setName(event.target.value);
  };

  return (
    <Box {/* ... */}>
      <TextField {/* ... */} onChange={handleChange} />
    </Box>
  );
}


问:
load model spacy error: ExtraData: unpack(b) received extra data
I have trained a custom NER model in spacy(v3.4.2) and then I trained the Roberta base model for custom NER again with spacy(v3.4.4) transformers.

Now I am trying to load the Roberta trained model in spacy(v3.4.2) in order to combine NERs and I am facing this error:

Can anybody help? Maybe it is happening because of different versions?


问:
Merging overlapping dates
I was given the following dataset and need to simplify it. The goal is to end up with one row for flights with the same Airports_Code, Airports_1_Code, Airlines_Code, FlightNo, which include the earliest fromDate and the latest toDate, whilst taking the max amount of daysofweek and one of the given values for the columns: deptime,arrtime, deltaArrDay, Seats, Freight.

Right now the only values that i am able to extract are the first and last value respectively, whilst this is not always the earliest and latest value (f.e.  row 3 and 4 result into 8-7-2018 and 11-9-2018, while it should give 11-5-2018 and 11-9-2018).
It also doesn't include the other columns in the new dataset.

The code I used, is mostly based on code I found on the internet, so there is no plagiarism intended.

```<code>data['days'] = (data['toDate']-data['fromDate'])
def merge_times(x):
    startdf = pd.DataFrame({'time':x['fromDate'], 'what':1})
    enddf = pd.DataFrame({'time':x['toDate'], 'what':-1})
    mergdf = pd.concat([startdf, enddf]).sort_values('time')
    mergdf['running'] = mergdf['what'].cumsum()
    mergdf['newwin'] = mergdf['running'].eq(1) & mergdf['what'].eq(1)
    mergdf['group'] = mergdf['newwin'].cumsum()
    x['group'] = mergdf['group'].loc[mergdf['what'].eq(1)]
    res = x.groupby('group').agg({'days':'sum','fromDate':'first'})
    res['toDate'] = res.apply(lambda x : x['fromDate']+ x['days'], axis=1)
    return res

data3 = data.groupby(['FlightNo','Airlines_Code','Airports_Code','Airports_1_Code']).apply(merge_times).reset_index().drop('group', axis=1)
</code>```

In addition I also worked with this, again found on internet:

```<code>def f(grp):
    #define a list to collect valid start and end ranges
    d=[]
    (
        #append a new row if the start date is at least 2 days greater than the last date from previous row,
        #otherwise update last rows's end date with current row's end date.
        grp.reset_index(drop=True)
           .apply(lambda x: d.append({x.fromDate:x.toDate})
                            if x.name==0 or (x.fromDate-pd.DateOffset(1))>grp.iloc[x.name-1].toDate
                            else d[-1].update({list(d[-1].keys())[0]:x.toDate}),
                  axis=1)
    )
    #reconstruct a df using only valid start and end dates pairs.
    return pd.DataFrame([[list(e.keys())[0],list(e.values())[0]] for e in d],
                        columns=['fromDate','toDate'])

data2 = data.groupby('idx').apply(f).reset_index().drop('level_1',1)
</code>```

Thanks in advance to anyone able to help!
Dataset

Title: Merging overlapping dates

Body:
I was given the following dataset and need to simplify it. The goal is to end up with one row for flights with the same Airports_Code, Airports_1_Code, Airlines_Code, FlightNo, which include the earliest fromDate and the latest toDate, whilst taking the max amount of daysofweek and one of the given values for the columns: deptime,arrtime, deltaArrDay, Seats, Freight.

Right now the only values that i am able to extract are the first and last value respectively, whilst this is not always the earliest and latest value (f.e.  row 3 and 4 result into 8-7-2018 and 11-9-2018, while it should give 11-5-2018 and 11-9-2018).
It also doesn't include the other columns in the new dataset.

The code I used, is mostly based on code I found on the internet, so there is no plagiarism intended.

data['days'] = (data['toDate']-data['fromDate'])
def merge_times(x):
    startdf = pd.DataFrame({'time':x['fromDate'], 'what':1})
    enddf = pd.DataFrame({'time':x['toDate'], 'what':-1})
    mergdf = pd.concat([startdf, enddf]).sort_values('time')
    mergdf['running'] = mergdf['what'].cumsum()
    mergdf['newwin'] = mergdf['running'].eq(1) & mergdf['what'].eq(1)
    mergdf['group'] = mergdf['newwin'].cumsum()
    x['group'] = mergdf['group'].loc[mergdf['what'].eq(1)]
    res = x.groupby('group').agg({'days':'sum','fromDate':'first'})
    res['toDate'] = res.apply(lambda x : x['fromDate']+ x['days'], axis=1)
    return res

data3 = data.groupby(['FlightNo','Airlines_Code','Airports_Code','Airports_1_Code']).apply(merge_times).reset_index().drop('group', axis=1)

In addition I also worked with this, again found on internet:

def f(grp):
    #define a list to collect valid start and end ranges
    d=[]
    (
        #append a new row if the start date is at least 2 days greater than the last date from previous row,
        #otherwise update last rows's end date with current row's end date.
        grp.reset_index(drop=True)
           .apply(lambda x: d.append({x.fromDate:x.toDate})
                            if x.name==0 or (x.fromDate-pd.DateOffset(1))>grp.iloc[x.name-1].toDate
                            else d[-1].update({list(d[-1].keys())[0]:x.toDate}),
                  axis=1)
    )
    #reconstruct a df using only valid start and end dates pairs.
    return pd.DataFrame([[list(e.keys())[0],list(e.values())[0]] for e in d],
                        columns=['fromDate','toDate'])

data2 = data.groupby('idx').apply(f).reset_index().drop('level_1',1)

Thanks in advance to anyone able to help!
Dataset


问:
How does WordPad deal with fonts in RTF files with non-ASCII characters?
I open WordPad. The default font is Calibri. I type in my text containing non-ASCII characters. The head of it is:

{\rtf1\ansi\ansicpg1252\deff0\nouicompat\deflang1033{\fonttbl{\f0\fnil\fcharset0 Calibri;}{\f1\fnil\fcharset163 Calibri;}{\f2\fnil\fcharset238 Calibri;}}

Why is one same font declared 3 times? Why not simply using 1 time?

Related: Why are RTF files created by Word so huge and complicate, while WordPad are not?


问:
matplotlib detect if left mouse button is held down
I am developing an application on using matplotlib on jupyter notebook, where I need to interactively draw a rectangle on an image. To draw the rectangle, I first start detect when the user performs a double click with the left mouse button. This registers the start x and y coordinate of the mouse point and work as expected.

```<code>def _roiMouseclick(self, event):
        drawStartXY = False
        if event.inaxes == self.SVDAnnotationImageAxesLeft  and event.dblclick:
            drawStartXY = True

        if event.inaxes == self.SVDAnnotationImageAxesRight and event.dblclick:
            drawStartXY = True

        if drawStartXY:
            self.currentROI['xStart'] = event.xdata
            self.currentROI['yStart'] = event.ydata
            self.currentROI['axesInFocus'] = event.inaxes

            #Since this is first time user has clicked xEnd and yEnd is set to None
            self.currentROI['xEnd'] = None
            self.currentROI['yEnd'] = None
</code>```

Then when the user moves the mouse button, I need to draw a rectangle as long as the left mouse button is kept held down. How do I detect if the left mouse button is KEPT held down? My current code below only detects of motion, but it is unable to detect if the left mouse button has been release or still pressed down.

```<code>def _roiMouseMotion(self, event):
        drawRectangle = False
        if event.button == MouseButton.LEFT and event.inaxes == self.SVDAnnotationImageAxesLeft:
            drawRectangle = True

        if event.button == MouseButton.LEFT and event.inaxes == self.SVDAnnotationImageAxesRight:
            drawRectangle = True

        if drawRectangle:
            self.currentROI['xEnd'] = event.xdata
            self.currentROI['yEnd'] = event.ydata
            self._drawRectangle()
</code>```

Body:
I am developing an application on using matplotlib on jupyter notebook, where I need to interactively draw a rectangle on an image. To draw the rectangle, I first start detect when the user performs a double click with the left mouse button. This registers the start x and y coordinate of the mouse point and work as expected.

def _roiMouseclick(self, event):
        drawStartXY = False
        if event.inaxes == self.SVDAnnotationImageAxesLeft  and event.dblclick:
            drawStartXY = True

        if event.inaxes == self.SVDAnnotationImageAxesRight and event.dblclick:
            drawStartXY = True

        if drawStartXY:
            self.currentROI['xStart'] = event.xdata
            self.currentROI['yStart'] = event.ydata
            self.currentROI['axesInFocus'] = event.inaxes

            #Since this is first time user has clicked xEnd and yEnd is set to None
            self.currentROI['xEnd'] = None
            self.currentROI['yEnd'] = None

Then when the user moves the mouse button, I need to draw a rectangle as long as the left mouse button is kept held down. How do I detect if the left mouse button is KEPT held down? My current code below only detects of motion, but it is unable to detect if the left mouse button has been release or still pressed down.

def _roiMouseMotion(self, event):
        drawRectangle = False
        if event.button == MouseButton.LEFT and event.inaxes == self.SVDAnnotationImageAxesLeft:
            drawRectangle = True

        if event.button == MouseButton.LEFT and event.inaxes == self.SVDAnnotationImageAxesRight:
            drawRectangle = True

        if drawRectangle:
            self.currentROI['xEnd'] = event.xdata
            self.currentROI['yEnd'] = event.ydata
            self._drawRectangle()


问:
Zend Route and Infinite Categories
I'm building a Cms for an organization and url scheme is like this:

```<code>departmentName.site.edu/subDepartment/subDepartment/evenMoreSubDepartments/module/controller/action/*
</code>```

I think i have to combine Zend_Controller_Router_Route and Zend_Controller_Router_Route_Hostname but i don't know how.

If someone can help, i appreciate it.

ContentLicense: CC BY-SA 3.0

Title: Zend Route and Infinite Categories

Body:
I'm building a Cms for an organization and url scheme is like this:

departmentName.site.edu/subDepartment/subDepartment/evenMoreSubDepartments/module/controller/action/*

I think i have to combine Zend_Controller_Router_Route and Zend_Controller_Router_Route_Hostname but i don't know how.

If someone can help, i appreciate it.


问:
One of my users who has valid fcm token, can't receive notifications
I am storing users FCM tokens in the database each time they got in. When I heard one of my users says he can't get notification, to test him phone I sent notification via his token. But he can't get it also he can't get subscribe any topic.

Token is valid, syntax is correct, notification settings are okay. I am using Firebase 10.2 on iOS, should I use any other services like OneSignal or Braze? What could be the problem and how to solve?


问:
smtp not working on airflow on aws instance
I have airflow on aws instance, there i am trying to send email on dag failure using smtp.
I am using emailOperator (airflow builtin) for sending email.

It is giving

```<code>ConnectionRefusedError: [Errno 111] Connection refused
</code>```

error.

```<code>  File "/home/airflow/env/lib/python3.10/site-packages/airflow/operators/email.py", line 75, in execute
    send_email(
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 58, in send_email
    return backend(
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 119, in send_email_smtp
    send_mime_email(e_from=mail_from, e_to=recipients, mime_msg=msg, conn_id=conn_id, dryrun=dryrun)
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 230, in send_mime_email
    smtp_conn = _get_smtp_connection(smtp_host, smtp_port, smtp_timeout, smtp_ssl)
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 264, in _get_smtp_connection
    else smtplib.SMTP(host=host, port=port, timeout=timeout)
  File "/usr/lib/python3.10/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.10/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.10/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.10/socket.py", line 845, in create_connection
    raise err
  File "/usr/lib/python3.10/socket.py", line 833, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused
</code>```

I have changed configurations in airflow.cfg also.

enter image description here

for smtp - i have generated App password (in gmail security setting) and have used that password.

and for ports - i have tried using port 25, 578 and have opened both of these ports on aws.

This is how dag looks like

```<code>dag_email = DAG(
    dag_id = 'emailoperator_demo',
    default_args=default_args,
    schedule_interval='@once',
    dagrun_timeout=timedelta(minutes=60),
    description='use case of email operator in airflow',
    start_date = airflow.utils.dates.days_ago(1)
    )

start_task = PythonOperator(
    task_id='executetask',
    python_callable=start_task,
    dag=dag_email)

send_email = EmailOperator(
    task_id='send_email',
    to='my_email_id',
    subject='ingestion complete',
    html_content="Date: {{ ds }}",
    dag=dag_email)

send_email.set_upstream(start_task)

if __name__ == "__main__":
    dag_spark.cli()
</code>```

Body:
I have airflow on aws instance, there i am trying to send email on dag failure using smtp.
I am using emailOperator (airflow builtin) for sending email.

It is giving

ConnectionRefusedError: [Errno 111] Connection refused

error.

  File "/home/airflow/env/lib/python3.10/site-packages/airflow/operators/email.py", line 75, in execute
    send_email(
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 58, in send_email
    return backend(
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 119, in send_email_smtp
    send_mime_email(e_from=mail_from, e_to=recipients, mime_msg=msg, conn_id=conn_id, dryrun=dryrun)
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 230, in send_mime_email
    smtp_conn = _get_smtp_connection(smtp_host, smtp_port, smtp_timeout, smtp_ssl)
  File "/home/airflow/env/lib/python3.10/site-packages/airflow/utils/email.py", line 264, in _get_smtp_connection
    else smtplib.SMTP(host=host, port=port, timeout=timeout)
  File "/usr/lib/python3.10/smtplib.py", line 255, in __init__
    (code, msg) = self.connect(host, port)
  File "/usr/lib/python3.10/smtplib.py", line 341, in connect
    self.sock = self._get_socket(host, port, self.timeout)
  File "/usr/lib/python3.10/smtplib.py", line 312, in _get_socket
    return socket.create_connection((host, port), timeout,
  File "/usr/lib/python3.10/socket.py", line 845, in create_connection
    raise err
  File "/usr/lib/python3.10/socket.py", line 833, in create_connection
    sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

I have changed configurations in airflow.cfg also.

enter image description here

for smtp - i have generated App password (in gmail security setting) and have used that password.

and for ports - i have tried using port 25, 578 and have opened both of these ports on aws.

This is how dag looks like

dag_email = DAG(
    dag_id = 'emailoperator_demo',
    default_args=default_args,
    schedule_interval='@once',
    dagrun_timeout=timedelta(minutes=60),
    description='use case of email operator in airflow',
    start_date = airflow.utils.dates.days_ago(1)
    )

start_task = PythonOperator(
    task_id='executetask',
    python_callable=start_task,
    dag=dag_email)

send_email = EmailOperator(
    task_id='send_email',
    to='my_email_id',
    subject='ingestion complete',
    html_content="Date: {{ ds }}",
    dag=dag_email)

send_email.set_upstream(start_task)

if __name__ == "__main__":
    dag_spark.cli()


问:
How to draw() again with each level in MDN Javascript Breakout game tutorial?
I recently did the MDN Javascript Breakout game tutorial and I added some stuff of mine.

I added levels and ball speed increment with each level. The problem is that I can't make the bricks restore or redraw the bricks with each level.

So, currently I managed to redraw the bricks, the ball and the paddle only one level.

How can I draw the bricks, the ball and the paddle in the canvas with each level increment?

Here is my full code.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title>MDN JavaScript Game</title>
    <style>
      * {
        padding: 0;
        margin: 0;
      }
      canvas {
        background-color: rgb(0, 0, 0);
        background-image:
         linear-gradient(335deg, #b00 23px, transparent 23px),
         linear-gradient(155deg, #d00 23px, transparent 23px),
         linear-gradient(335deg, #b00 23px, transparent 23px),
         linear-gradient(155deg, #d00 23px, transparent 23px);
        background-size: 58px 58px;
        background-position: 0px 2px, 4px 35px, 29px 31px, 34px 6px;
        display: block;
        margin: 0 auto;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="560" height="400"></canvas>

    <script>
      var canvas = document.getElementById("myCanvas");
      var ctx = canvas.getContext("2d");
      var ballRadius = 10;
      var x = canvas.width / 2;
      var y = canvas.height - 30;
      var dx = 4;
      var dy = -4;
      var paddleHeight = 10;
      var paddleWidth = 75;
      var paddleX = (canvas.width - paddleWidth) / 2;
      var rightPressed = false;
      var leftPressed = false;
      var brickRowCount = 1;
      var brickColumnCount = 1;
      var brickWidth = 75;
      var brickHeight = 20;
      var brickPadding = 10;
      var brickOffsetTop = 30;
      var brickOffsetLeft = 30;
      var score = 0;
      var level = 1;
      var lives = 3;

      var bricks = [];
      for (var c = 0; c < brickColumnCount; c++) {
        bricks[c] = [];
        for (var r = 0; r < brickRowCount; r++) {
          bricks[c][r] = { x: 0, y: 0, status: 1 };
        }
      }

      document.addEventListener("keydown", keyDownHandler, false);
      document.addEventListener("keyup", keyUpHandler, false);
      document.addEventListener("mousemove", mouseMoveHandler, false);

      function keyDownHandler(e) {
        if (e.code == "ArrowRight") {
          rightPressed = true;
        } else if (e.code == "ArrowLeft") {
          leftPressed = true;
        }
      }
      function keyUpHandler(e) {
        if (e.code == "ArrowRight") {
          rightPressed = false;
        } else if (e.code == "ArrowLeft") {
          leftPressed = false;
        }
      }
      function mouseMoveHandler(e) {
        var relativeX = e.clientX - canvas.offsetLeft;
        if (relativeX > 0 && relativeX < canvas.width) {
          paddleX = relativeX - paddleWidth / 2;
        }
      }
      function collisionDetection() {
        for (var c = 0; c < brickColumnCount; c++) {
          for (var r = 0; r < brickRowCount; r++) {
            var b = bricks[c][r];
            if (b.status == 1) {
              if (
                x > b.x &&
                x < b.x + brickWidth &&
                y > b.y &&
                y < b.y + brickHeight
              ) {
                dy = -dy;
                b.status = 0;
                score++;
                if (score == brickRowCount * brickColumnCount) {

                  // Reseting the bricks
                  for (var c = 0; c < brickColumnCount; c++) {
                    bricks[c] = [];
                    for (var r = 0; r < brickRowCount; r++) {
                      bricks[c][r] = { x: 0, y: 0, status: 1 };

                    }
                    // Reseting the ball and the paddle
                  x = canvas.width / 2;
                  y = canvas.height - 30;
                  paddleX = (canvas.width - paddleWidth) / 2;
                  };
                  // Incrementing the level

                    level++;

                  // Incrementing the ball speed
                  dx += 10;
                  dy += -10;
                }
              }
            }
          }
        }
      }

      function drawBall() {
        ctx.beginPath();
        ctx.arc(x, y, ballRadius, 0, Math.PI * 2);
        ctx.fillStyle = "yellow";
        ctx.fill();
        ctx.closePath();
      }
      function drawPaddle() {
        ctx.beginPath();
        ctx.rect(
          paddleX,
          canvas.height - paddleHeight,
          paddleWidth,
          paddleHeight
        );
        ctx.fillStyle = "yellow";
        ctx.fill();
        ctx.closePath();
      }
      function drawBricks() {
        for (var c = 0; c < brickColumnCount; c++) {
          for (var r = 0; r < brickRowCount; r++) {
            if (bricks[c][r].status == 1) {
              var brickX = r * (brickWidth + brickPadding) + brickOffsetLeft;
              var brickY = c * (brickHeight + brickPadding) + brickOffsetTop;
              bricks[c][r].x = brickX;
              bricks[c][r].y = brickY;
              ctx.beginPath();
              ctx.rect(brickX, brickY, brickWidth, brickHeight);
              ctx.fillStyle = "yellow";
              ctx.fill();
              ctx.closePath();
            }
          }
        }
      }
      function drawScore() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#FFFFFF";
        ctx.fillText("Score: " + score, 8, 20);
      }
      function drawLevel() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#FFFFFF";
        ctx.fillText("Level: " + level, 260, 20);
      }
      function drawLives() {
        ctx.font = "16px Arial";
        ctx.fillStyle = "#FFFFFF";
        ctx.fillText("Lives: " + lives, canvas.width - 65, 20);
      }

      function draw() {
        ctx.clearRect(0, 0, canvas.width, canvas.height);
        drawBricks();
        drawBall();
        drawPaddle();
        drawScore();
        drawLevel();
        drawLives();
        collisionDetection();

        if (x + dx > canvas.width - ballRadius || x + dx < ballRadius) {
          dx = -dx;
        }
        if (y + dy < ballRadius) {
          dy = -dy;
        } else if (y + dy > canvas.height - ballRadius) {
          if (x > paddleX && x < paddleX + paddleWidth) {
            dy = -dy;
          } else {
            lives--;
            if (!lives) {
              alert("GAME OVER");
              document.location.reload();
            } else {
              x = canvas.width / 2;
              y = canvas.height - 30;
              dx = 4;
              dy = -4;
              paddleX = (canvas.width - paddleWidth) / 2;
            }
          }
        }

        if (rightPressed && paddleX < canvas.width - paddleWidth) {
          paddleX += 7;
        } else if (leftPressed && paddleX > 0) {
          paddleX -= 7;
        }

        x += dx;
        y += dy;
        requestAnimationFrame(draw);
      }

      draw();
    </script>
  </body>
</html>

</code>```

I tried for loops and while loops.

Body:
I recently did the MDN Javascript Breakout game tutorial and I added some stuff of mine.

I added levels and ball speed increment with each level. The problem is that I can't make the bricks restore or redraw the bricks with each level.

So, currently I managed to redraw the bricks, the ball and the paddle only one level.

How can I draw the bricks, the ball and the paddle in the canvas with each level increment?

Here is my full code.

<!DOCTYPE html>

    <meta charset="utf-8" />
    <title>MDN JavaScript Game</title>

    <canvas id="myCanvas" width="560" height="400"></canvas>

I tried for loops and while loops.


问:
Backup script throught crontab not working
i have sh script to backup database. If i run scrip manually, everything working fine. I add job to crontab, to run script, but if crontab make file with db backup, and i gunzip, in .sql file are no datas. Thank you for help

Script:

```<code>mysqldump --column-statistics=0  -h *IP ADD* -P *port* -u *user* -p *db* | gzip -9 -c  > PATH*-`date +%Y-%m-%d`.sql.gz
</code>```

Crontab

Crontab -e

Im trying to add root to crontab

Body:
i have sh script to backup database. If i run scrip manually, everything working fine. I add job to crontab, to run script, but if crontab make file with db backup, and i gunzip, in .sql file are no datas. Thank you for help

Script:

mysqldump --column-statistics=0  -h *IP ADD* -P *port* -u *user* -p *db* | gzip -9 -c  > PATH*-`date +%Y-%m-%d`.sql.gz

Crontab

Crontab -e

Im trying to add root to crontab


问:
Error Uploading ipa : ERROR: RETRIEVE UPLOAD OPERATIONS (ASSET_UPLOAD): Did not receive a response
I have been trying to upload the ipa for my app a couple of days now and it keeps erroring out with the error message ERROR: RETRIEVE UPLOAD OPERATIONS (ASSET_UPLOAD): Did not receive a response..

I tried to upload with XCode, Transporter and xcrun altool. All fail with the same message.

Images for the Transporter error and xcrun altoool are attached below:

Transporter Error:

xcrun atool output:

Uploads from the Transporter app or the terminal should not error out and make it to test flight


问:
Optimze d3 graph zooming performances
I have a complexe graph whith many svg shapes.
I would like to optimise code in order to gain performances.

I don't see what can I do more to make it better.

```<code>private manageZoom(svgs: AllSvg, allAxis: AllAxis, dimension: Dimension, sillons: Circulation[]): D3ZoomBehavior {
    const zoom: D3ZoomBehavior = d3
        .zoom()
        .scaleExtent([1, 40])
        .translateExtent([
            [0, 0],
            [dimension.width, dimension.height]
        ])
        .on('zoom', zoomed.bind(null, allAxis));

    svgs.svgContainer.call(zoom);
    return zoom;

    function zoomed({ xAxis, xAxisBottom, yAxis }: AllAxis, { transform }: any) {
        const start = performance.now();
        svgs.grids
            .selectAll('.vertical-grid line')
            .nodes()
            .forEach((lineV) => {
                const lineVSelect = d3.select(lineV);
                const lineVData = JSON.parse(lineVSelect.attr('data'));
                lineVSelect
                    .attr('x1', xAxis.scale(new Date(lineVData)) * transform.k + transform.x)
                    .attr('x2', xAxis.scale(new Date(lineVData)) * transform.k + transform.x);
            });
        svgs.grids
            .selectAll('.horizontal-grid line')
            .nodes()
            .forEach((lineH) => {
                const lineHSelect = d3.select(lineH);
                const lineHData = JSON.parse(lineHSelect.attr('data'));
                lineHSelect
                    .attr('x1', lineHData.x * transform.k + transform.x)
                    .attr(
                        'x2',
                        lineHData.isPrincipal
                            ? lineHData.x * transform.k + transform.x - 6
                            : lineHData.x * transform.k + transform.x - 3
                    );
            });
        svgs.sillons
            .selectAll('path')
            .nodes()
            .forEach((path, j) => {
                const pathSelect = d3.select(path);
                const pathData = JSON.parse(pathSelect.attr('data'));
                const line = d3
                    .line()
                    .x((d) => d[0] * transform.k + transform.x)
                    .y((d) => d[1]);
                pathSelect.attr('d', line(pathData));
            });
        svgs.sillons
            .selectAll('circle')
            .nodes()
            .forEach((circle) => {
                const circleSelect = d3.select(circle);
                const circleData = JSON.parse(circleSelect.attr('data'));
                circleSelect.attr('cx', circleData[0] * transform.k + transform.x);
            });
        svgs.fenetres
            .selectAll('polygon')
            .nodes()
            .forEach((polygon) => {
                const polygonSelect = d3.select(polygon);
                const polygonData = JSON.parse(polygonSelect.attr('data'));

                polygonSelect.attr('points', () => {
                    return polygonData
                        .map(function (d: [number, number]) {
                            return [d[0] * transform.k + transform.x, d[1]].join(',');
                        })
                        .join(' ');
                });
            });
        const end = performance.now();
        console.log('performance', end - start);
        xAxis.axisContainer.call(xAxis.axis.scale(transform.rescaleX(xAxis.scale)) as any);
        xAxisBottom.axisContainer.call(xAxisBottom.axis.scale(transform.rescaleX(xAxisBottom.scale)) as any);

    }
</code>```

I'm trying to change transform.k and transform.x multiplications by transform.rescaleX() but it does add X2 more slowness.

I'm open to others code optimisation

Title: Optimze d3 graph zooming performances

Body:
I have a complexe graph whith many svg shapes.
I would like to optimise code in order to gain performances.

I don't see what can I do more to make it better.

private manageZoom(svgs: AllSvg, allAxis: AllAxis, dimension: Dimension, sillons: Circulation[]): D3ZoomBehavior {
    const zoom: D3ZoomBehavior = d3
        .zoom()
        .scaleExtent([1, 40])
        .translateExtent([
            [0, 0],
            [dimension.width, dimension.height]
        ])
        .on('zoom', zoomed.bind(null, allAxis));

    svgs.svgContainer.call(zoom);
    return zoom;

    function zoomed({ xAxis, xAxisBottom, yAxis }: AllAxis, { transform }: any) {
        const start = performance.now();
        svgs.grids
            .selectAll('.vertical-grid line')
            .nodes()
            .forEach((lineV) => {
                const lineVSelect = d3.select(lineV);
                const lineVData = JSON.parse(lineVSelect.attr('data'));
                lineVSelect
                    .attr('x1', xAxis.scale(new Date(lineVData)) * transform.k + transform.x)
                    .attr('x2', xAxis.scale(new Date(lineVData)) * transform.k + transform.x);
            });
        svgs.grids
            .selectAll('.horizontal-grid line')
            .nodes()
            .forEach((lineH) => {
                const lineHSelect = d3.select(lineH);
                const lineHData = JSON.parse(lineHSelect.attr('data'));
                lineHSelect
                    .attr('x1', lineHData.x * transform.k + transform.x)
                    .attr(
                        'x2',
                        lineHData.isPrincipal
                            ? lineHData.x * transform.k + transform.x - 6
                            : lineHData.x * transform.k + transform.x - 3
                    );
            });
        svgs.sillons
            .selectAll('path')
            .nodes()
            .forEach((path, j) => {
                const pathSelect = d3.select(path);
                const pathData = JSON.parse(pathSelect.attr('data'));
                const line = d3
                    .line()
                    .x((d) => d[0] * transform.k + transform.x)
                    .y((d) => d[1]);
                pathSelect.attr('d', line(pathData));
            });
        svgs.sillons
            .selectAll('circle')
            .nodes()
            .forEach((circle) => {
                const circleSelect = d3.select(circle);
                const circleData = JSON.parse(circleSelect.attr('data'));
                circleSelect.attr('cx', circleData[0] * transform.k + transform.x);
            });
        svgs.fenetres
            .selectAll('polygon')
            .nodes()
            .forEach((polygon) => {
                const polygonSelect = d3.select(polygon);
                const polygonData = JSON.parse(polygonSelect.attr('data'));

                polygonSelect.attr('points', () => {
                    return polygonData
                        .map(function (d: [number, number]) {
                            return [d[0] * transform.k + transform.x, d[1]].join(',');
                        })
                        .join(' ');
                });
            });
        const end = performance.now();
        console.log('performance', end - start);
        xAxis.axisContainer.call(xAxis.axis.scale(transform.rescaleX(xAxis.scale)) as any);
        xAxisBottom.axisContainer.call(xAxisBottom.axis.scale(transform.rescaleX(xAxisBottom.scale)) as any);

    }

I'm trying to change transform.k and transform.x multiplications by transform.rescaleX() but it does add X2 more slowness.

I'm open to others code optimisation


问:
unwanted dll being generated automatically
I upgraded our code (C++, on Win) from openssl 1 into openssl 3.
From some reason now there is a bcrypt.dll (which is a system dll) being generated automatically in our exe folder.

I don't understand how and why it's generated, and it causing problems because it suitable to the compiled machine and when running our program on another win version it crushes (because the prog uses it instead of the local win dll)

thank you in advance for your help!


问:
Flutter Web + Firebase Cloud Messaging
My Flutter Web app needs to support receiving FCMs. Unfortunately, the docs to integrate FCM with Flutter Web are pretty thin on the ground.

In the past, I've used something like this, this and this, but all of these REPLACE flutters PWA service worker with FCM's, (and relate to old version of flutter when the generated index.html was different) and I want to retain it.

The main problem I'm having is that in Flutter 3.3.9, a freshly created web project includes support for Progressive Web Apps (PWAs) by generating 3 files in the web folder:

index.html

flutter.js

flutter-service-worker.js

index.html contains this block to install a service worker to manage PWA stuff:

```<code>     window.addEventListener('load', function(ev) {
      // Download main.dart.js
      _flutter.loader.loadEntrypoint({
        serviceWorker: {
          serviceWorkerVersion: serviceWorkerVersion,
        }
      }).then(function(engineInitializer) {
        return engineInitializer.initializeEngine();
      }).then(function(appRunner) {
        return appRunner.runApp();
      });
    });

</code>```

But the links above suggest FCM needs a service worker of its own. (Makes sense because it needs to receive FCMs while the app is not open in the browser)

My question is, how to I integrate support for FCM on top of the service worker that Flutter Web already provides so that my app retains PWA features and also supports FCM? My understanding is that each service worker scope can only have a single service worker.

My expertise in javascript is a bit limited.

Thanks

Title: Flutter Web + Firebase Cloud Messaging

Body:
My Flutter Web app needs to support receiving FCMs. Unfortunately, the docs to integrate FCM with Flutter Web are pretty thin on the ground.

In the past, I've used something like this, this and this, but all of these REPLACE flutters PWA service worker with FCM's, (and relate to old version of flutter when the generated index.html was different) and I want to retain it.

The main problem I'm having is that in Flutter 3.3.9, a freshly created web project includes support for Progressive Web Apps (PWAs) by generating 3 files in the web folder:

index.html

flutter.js

flutter-service-worker.js

index.html contains this block to install a service worker to manage PWA stuff:

     window.addEventListener('load', function(ev) {
      // Download main.dart.js
      _flutter.loader.loadEntrypoint({
        serviceWorker: {
          serviceWorkerVersion: serviceWorkerVersion,
        }
      }).then(function(engineInitializer) {
        return engineInitializer.initializeEngine();
      }).then(function(appRunner) {
        return appRunner.runApp();
      });
    });

But the links above suggest FCM needs a service worker of its own. (Makes sense because it needs to receive FCMs while the app is not open in the browser)

My question is, how to I integrate support for FCM on top of the service worker that Flutter Web already provides so that my app retains PWA features and also supports FCM? My understanding is that each service worker scope can only have a single service worker.

My expertise in javascript is a bit limited.

Thanks


问:
I don't know how to combine SDL2 and pygame on android
I'm currently trying to create a game on my phone using the Pydroid IDE. I'm using Pygame and I would like to use the pygame._sdl2.touch function to detect multi touch on my phone.
Learning from the official Pygame website, I apparently need to install SDL2, and that's what I did. I have currently installed Pygame and PySDL2 and imported Pygame in the code by typing import pygame, and I'm now locked, because the pygame._sdl2.touch function doesn't work. I tried importing sdl2 (typing import sdl2, it works and do import sdl2), and it didn't help.

What can I do to be able to use this function ? If there is another way to detect multi touch on phone using python, I would be happy to hear it.
Thanks !

Tried pygame._sdl2.touch, sdl2.touch, pygame.sdl2.touch and always got an error telling me this function doesn't exists.