问:
Getting an error while retrieving a blob using user assigned managed identity
We have a C# code which used to retrieve a blob from storage account. The authentication is done using user assigned service principal. These things works till December. But now we are getting some weird error as follows.

ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.

Status: 400 (Bad Request)

Content:

{"error":"invalid_request","error_description":"Identity not found"}

The managed identity has storage data blob contributor access in the storage account.

Attaching the code for reference:

```<code>public static async Task<string> GetBlobAsync()
    {
        string storageName = "storage account name";

        Uri blobUri = new Uri("blob uri");

        TokenCredential cred = new ManagedIdentityCredential("client id");

        var blobClient = new BlobClient(blobUri, cred, null);

        try
        {

            var downloadInfo = await blobClient.DownloadAsync();
            using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
            {
                string metadataBlob = await reader.ReadToEndAsync();

                return metadataBlob;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("");
            return null;
        }
</code>```

P:S: the three environmental variables such as app id, app secret and tenant id are correct.

I have been stuck here for almost a month. Nothing works.

答:
Try this

```<code>Uri blobUri = new Uri("blob uri");

var cred = new DefaultAzureCredential(
    new DefaultAzureCredentialOptions {
           ManagedIdentityClientId = "your client id" });

var blobClient = new BlobClient(blobUri, cred, null);
</code>```

ref: https://learn.microsoft.com/pt-br/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet

Option 2 (work for me)

Create Identity and add in app service

Assign RBAC "Storage Blob Data Contributor" to your storage resource.

Add Key AZURE_CLIENT_ID (clientid of the identity that was created) in Environment App Service

Code to access blob
(you don't need to specify client id in the code because it will use the AZURE_CLIENT_ID configured in the AppService)

```<code>app.MapGet("/read", async () =>
{
    Uri blobUri = new Uri("https://xxxx.blob.core.windows.net/texts/text.txt");

    var cred = new DefaultAzureCredential();

    var blobClient = new BlobClient(blobUri, cred, null);

    var downloadInfo = await blobClient.DownloadAsync();
    using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
    {
        string metadataBlob = await reader.ReadToEndAsync();

        return metadataBlob;
    }

});

</code>```

Result print

Body:
We have a C# code which used to retrieve a blob from storage account. The authentication is done using user assigned service principal. These things works till December. But now we are getting some weird error as follows.

ManagedIdentityCredential authentication unavailable. The requested identity has not been assigned to this resource.

Status: 400 (Bad Request)

Content:

{"error":"invalid_request","error_description":"Identity not found"}

The managed identity has storage data blob contributor access in the storage account.

Attaching the code for reference:

public static async Task<string> GetBlobAsync()
    {
        string storageName = "storage account name";

        Uri blobUri = new Uri("blob uri");

        TokenCredential cred = new ManagedIdentityCredential("client id");

        var blobClient = new BlobClient(blobUri, cred, null);

        try
        {

            var downloadInfo = await blobClient.DownloadAsync();
            using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
            {
                string metadataBlob = await reader.ReadToEndAsync();

                return metadataBlob;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
            Console.WriteLine("");
            return null;
        }

P:S: the three environmental variables such as app id, app secret and tenant id are correct.

I have been stuck here for almost a month. Nothing works.

Body:
Try this

Uri blobUri = new Uri("blob uri");

var cred = new DefaultAzureCredential(
    new DefaultAzureCredentialOptions {
           ManagedIdentityClientId = "your client id" });

var blobClient = new BlobClient(blobUri, cred, null);

ref: https://learn.microsoft.com/pt-br/dotnet/api/azure.identity.defaultazurecredential?view=azure-dotnet

Option 2 (work for me)

Create Identity and add in app service

Assign RBAC "Storage Blob Data Contributor" to your storage resource.

Add Key AZURE_CLIENT_ID (clientid of the identity that was created) in Environment App Service

Code to access blob
(you don't need to specify client id in the code because it will use the AZURE_CLIENT_ID configured in the AppService)

app.MapGet("/read", async () =>
{
    Uri blobUri = new Uri("https://xxxx.blob.core.windows.net/texts/text.txt");

    var cred = new DefaultAzureCredential();

    var blobClient = new BlobClient(blobUri, cred, null);

    var downloadInfo = await blobClient.DownloadAsync();
    using (TextReader reader = new StreamReader(downloadInfo.Value.Content))
    {
        string metadataBlob = await reader.ReadToEndAsync();

        return metadataBlob;
    }

});

Result print


来源: stackexchange

问:
Repeated update of UIImage isn't shown on screen
I'm working with an iOS app that has an animation of a spinning body. A series of UIImages are stored in an NSArray and a variable keeps track on the index to the current image.

The following method updates the UIImageView

```<code>- (void)renewImage{
    [rotatingBody.image release];
    rotatingBody.image = [[UIImage alloc] initWithContentsOfFile:[currentPerson.imageArray objectAtIndex:pictureIndex]];
}
</code>```

Up until now i have called the method as a response to touch events. From the touch event I calculate a new pictureIndex and then call [self renewImage]. It works perfectly.

However, now I want to add momentum to the animation. Instead of calculating the next image right away I calculate a velocity. I'm planning to have a loop in a separate thread to update pictureIndex by using the velocity variable, decrease the velocity and eventually call [self renewImage].

ENTER THE PROBLEM

Whenever I call [self renewImage] more then once in a row in the same function (e.g. in a loop or just twice separated by some sort of sleep) the screen won't update until after the last call. It is as if the device (or compilator) rationalizes away the first updates even though I'm certain that the renewImage method has been visited (thanks to tracing).

Here is some test code that doesn't work:

```<code>while (velocity > 0) {
        pictureIndex++;
        pictureIndex = pictureIndex % [self getNumberOfImages];
        if (pictureIndex < 0)
        {
            pictureIndex += [self getNumberOfImages];
        }
        velocity -= 20;
        NSLog(@"velocity: %f", velocity);
        [self renewImage];
        [NSThread sleepForTimeInterval:0.5];
    }
</code>```

Neither does this:

```<code>pictureIndex += 20;
[self renewImage];
sleep(1);
pictureIndex += 20;
[self renewImage];
</code>```

Any thoughts?

答:
Use an NSTimer callback to change the image, this way everything happens in the run loop rather than on a separate thread.

If an NSTimer isn't sufficient for your needs, you'll need to call a method on your main thread to change the image as UI change on other threads do not update immediately.

ContentLicense: CC BY-SA 3.0

Body:
I'm working with an iOS app that has an animation of a spinning body. A series of UIImages are stored in an NSArray and a variable keeps track on the index to the current image.

The following method updates the UIImageView

- (void)renewImage{
    [rotatingBody.image release];
    rotatingBody.image = [[UIImage alloc] initWithContentsOfFile:[currentPerson.imageArray objectAtIndex:pictureIndex]];
}

Up until now i have called the method as a response to touch events. From the touch event I calculate a new pictureIndex and then call [self renewImage]. It works perfectly.

However, now I want to add momentum to the animation. Instead of calculating the next image right away I calculate a velocity. I'm planning to have a loop in a separate thread to update pictureIndex by using the velocity variable, decrease the velocity and eventually call [self renewImage].

ENTER THE PROBLEM

Whenever I call [self renewImage] more then once in a row in the same function (e.g. in a loop or just twice separated by some sort of sleep) the screen won't update until after the last call. It is as if the device (or compilator) rationalizes away the first updates even though I'm certain that the renewImage method has been visited (thanks to tracing).

Here is some test code that doesn't work:

while (velocity > 0) {
        pictureIndex++;
        pictureIndex = pictureIndex % [self getNumberOfImages];
        if (pictureIndex < 0)
        {
            pictureIndex += [self getNumberOfImages];
        }
        velocity -= 20;
        NSLog(@"velocity: %f", velocity);
        [self renewImage];
        [NSThread sleepForTimeInterval:0.5];
    }

Neither does this:

pictureIndex += 20;
[self renewImage];
sleep(1);
pictureIndex += 20;
[self renewImage];

Any thoughts?


问:
Building React native fail on iOS - using Apple M1 chip
I've got a new mac and I followed the instructions for the installation.

when I run the Command:

```<code>npx react-native init ProjectName
</code>```

I got the following Error

```<code>** BUILD FAILED **
</code>```

The following build commands failed:
CompileC /Users/aghiadmonier/Library/Developer/Xcode/DerivedData/test-
bbpkvpircnzzukgpgaaohkixdojw/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Flipper.build/Objects-normal/x86_64/ConnectionContextStore.o /Users/aghiadmonier/Desktop/React/test/ios/Pods/Flipper/xplat/Flipper/ConnectionContextStore.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)

I am using Xcode 12.5

答:
just update your Podfile like this

```<code> use_flipper!({ 'Flipper' => '0.91.1', 'Flipper-Folly' => '~> 2.6', 'Flipper-RSocket' => '~> 1.4' })

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings["ONLY_ACTIVE_ARCH"] = "NO"
      end
    end
    flipper_post_install(installer)
    react_native_post_install(installer)
  end
</code>```

and after run pod install

ContentLicense: CC BY-SA 4.0

Body:
I've got a new mac and I followed the instructions for the installation.

when I run the Command:

npx react-native init ProjectName

I got the following Error

** BUILD FAILED **

The following build commands failed:
CompileC /Users/aghiadmonier/Library/Developer/Xcode/DerivedData/test-
bbpkvpircnzzukgpgaaohkixdojw/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/Flipper.build/Objects-normal/x86_64/ConnectionContextStore.o /Users/aghiadmonier/Desktop/React/test/ios/Pods/Flipper/xplat/Flipper/ConnectionContextStore.cpp normal x86_64 c++ com.apple.compilers.llvm.clang.1_0.compiler
(1 failure)

I am using Xcode 12.5

Body:
just update your Podfile like this

 use_flipper!({ 'Flipper' => '0.91.1', 'Flipper-Folly' => '~> 2.6', 'Flipper-RSocket' => '~> 1.4' })

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings["ONLY_ACTIVE_ARCH"] = "NO"
      end
    end
    flipper_post_install(installer)
    react_native_post_install(installer)
  end

and after run pod install


问:
Extract rotation data with ffprobe 5 and newer
ffprobe releases after 4.4 don't allow to read the video orientation  via -select_streams v:0 -show_entries stream_tags=rotate. Apparently this is by design and the alternative is to read the display matrix side data, according to this ticket: https://trac.ffmpeg.org/ticket/9452

This works on Mac:

```<code>ffprobe -loglevel error -select_streams v:0 -show_entries side_data=rotation -of default=nw=1:nk=1 input.mp4
</code>```

But on ffprobe for Windows, old and new versions, the program hangs forever. Is there a viable alternative? Or should we stick to ffprobe 4.4 if we need rotation data? Or is there a way to read this in ffmpeg?

Thank you

答:
With git build newer than Feb 3rd 2022, you can use

ffprobe -v 0 -select_streams v:0 -show_entries stream_side_data=rotation -of default=nw=1:nk=1 input.mp4

Body:
ffprobe releases after 4.4 don't allow to read the video orientation  via -select_streams v:0 -show_entries stream_tags=rotate. Apparently this is by design and the alternative is to read the display matrix side data, according to this ticket: https://trac.ffmpeg.org/ticket/9452

This works on Mac:

ffprobe -loglevel error -select_streams v:0 -show_entries side_data=rotation -of default=nw=1:nk=1 input.mp4

But on ffprobe for Windows, old and new versions, the program hangs forever. Is there a viable alternative? Or should we stick to ffprobe 4.4 if we need rotation data? Or is there a way to read this in ffmpeg?

Thank you


问:
async axios get call axios returns nothing
I'm trying to get the current temperature from openweathermaps using axios.

I can put my url into the browser and it works fine. But when I try do an axios call with the correct url it doesnt event call.

Here is the relevant code section:

function Overview() {
  const [temperature, setTemperature] = useState('')
  const API_KEY = '{apikey}'

  const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
      2,
    )}&appid=${API_KEY}`

    console.log('my provided url is set to:', url)

    const response = await axios.get(url)
    if (response.data) {
      setTemperature(response.data.main.temp)
    }
  }, [latitude, longitude])

  useEffect(() => {
    getTemperature().catch(console.error)
  }, [getTemperature])

  return <>{temperature ? temperature : 'no data'}</>
}
```

Any help as to where I'm going wrong would be great as I just cant see my error!

答:
Your URL working on the browser showcases that your API key is correct. Now, make sure the  variables in your URL are properly set from the code, particularly the API key. you can console.log them to be sure. Passed that, the minimal code below would do.

import {useCallback, useEffect} from 'react';
import axios from 'axios';

function Overview() {

// YOUR_INITIAL_STATE rather be undefined
const [temperature, setTemperature] = useState(YOUR_INITIAL_STATE);

const API_KEY = 'YOUR_API_KEY';

const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

   console.log("my provided url is set to:", url);

    const response = await axios.get(url);
    if(response.data){
      setTemperature(response.data.main.temp);
    }
// only call the functtion when these deps change
}, [latitude, longitude])

useEffect(() => {
// Check the error for further debbugging
getTemperature()
.catch(console.error);

}, [getTemperature])

      return (
            <>
          {temperature ? temperature : "no data"}
            </>
        );
}

```

Body:
I'm trying to get the current temperature from openweathermaps using axios.

I can put my url into the browser and it works fine. But when I try do an axios call with the correct url it doesnt event call.

Here is the relevant code section:

function Overview() {
  const [temperature, setTemperature] = useState('')
  const API_KEY = '{apikey}'

  const getTemperature = useCallback(async () => {
    const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.toFixed(2)}&lon=${longitude.toFixed(
      2,
    )}&appid=${API_KEY}`

    console.log('my provided url is set to:', url)

    const response = await axios.get(url)
    if (response.data) {
      setTemperature(response.data.main.temp)
    }
  }, [latitude, longitude])

  useEffect(() => {
    getTemperature().catch(console.error)
  }, [getTemperature])

  return <>{temperature ? temperature : 'no data'}</>
}

Any help as to where I'm going wrong would be great as I just cant see my error!


问:
subtract inside DataFrame columns
Would because maybe I did'n sleep this night but, given:

```<code>df1 = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], index=['rank1','rank2','rank3','rank4']}
df2 = {'Age':[28,34,29,42],'bubu':[98,33,3,30], index=['rank1','rank2','rank3','rank4']}
df_merged = = pd.concat([ df1, df2 ], axis = 1)
</code>```

now, for dynamically manage further arithmetic operation on the columns from a more column dense df:

```<code>a = ['Age']  #List
b = ['bubu'] #List
</code>```

the arithmetic operation:

```<code>df_merged['newCol'] = df_merged[a]-df_merged[b]
</code>```

or both

```<code>df_merged.assign(newCol = df_merged[a] - df_merged[b])
</code>```

I can't subtract the 2 columns because return such error

```<code>ValueError: Expected a 1D array, got an array with shape (556, 2)
</code>```

答:
```<code>df_merged['newCol'] = df_merged['Age']-df_merged['bubu'] or
df_merged.insert(3,'newCol', df_merged['Age']-df_merged['bubu'],True)
</code>```

Title: subtract inside DataFrame columns

Body:
Would because maybe I did'n sleep this night but, given:

df1 = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'], index=['rank1','rank2','rank3','rank4']}
df2 = {'Age':[28,34,29,42],'bubu':[98,33,3,30], index=['rank1','rank2','rank3','rank4']}
df_merged = = pd.concat([ df1, df2 ], axis = 1)

now, for dynamically manage further arithmetic operation on the columns from a more column dense df:

a = ['Age']  #List
b = ['bubu'] #List

the arithmetic operation:

df_merged['newCol'] = df_merged[a]-df_merged[b]

or both

df_merged.assign(newCol = df_merged[a] - df_merged[b])

I can't subtract the 2 columns because return such error

ValueError: Expected a 1D array, got an array with shape (556, 2)


问:
Global exception handler never get called in micronaut 3 with project reactor
After upgrading the micronaut application from 2.5.12 to 3.0.0 and using the Project reactor as reactive stream. The Global exception handler method never get called.

```<code> public class GlobalException extends RuntimeException{
        public GlobalException(Throwable throwable){super(throwable);}
    }

@Produces
@Singleton
@Requires(classes = {GlobalException.class, ExceptionHandler.class})
public class GlobalExceptionHandler implements ExceptionHandler<GlobalException, HttpResponse> {
    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Override
    public HttpResponse handle(HttpRequest request, GlobalException exception) {
        LOG.error(exception.getLocalizedMessage());
        LOG.error(exception.getCause().getMessage());
        Arrays.stream(exception.getStackTrace()).forEach(item -> LOG.error(item.toString()));
        return HttpResponse.serverError(exception.getLocalizedMessage());
    }
}
</code>```

On exception with below code, the handler method never get called

```<code>@Override
    public Flux<FindProductCommand> get(ProductSearchCriteriaCommand searchCriteria) {
        LOG.info("Controller --> Finding all the products");
        return iProductManager.find(searchCriteria).onErrorMap(throwable -> {
            return new GlobalException(throwable);
        });
    }
</code>```

I had this code Global exception handling in micronaut Java from rxjava 3 which was working fine, however, now with project reactor it is not working

答:
Try this one:</p>
```<code>@Override
    public Flux<FindProductCommand> get(ProductSearchCriteriaCommand searchCriteria) {
        LOG.info("Controller --> Finding all the products");
        return iProductManager
                  .find(searchCriteria)
                  .onErrorResume(e -> Mono.error(new GlobalException("My exception", e));
    }
</code>```

Body:
After upgrading the micronaut application from 2.5.12 to 3.0.0 and using the Project reactor as reactive stream. The Global exception handler method never get called.

 public class GlobalException extends RuntimeException{
        public GlobalException(Throwable throwable){super(throwable);}
    }

@Produces
@Singleton
@Requires(classes = {GlobalException.class, ExceptionHandler.class})
public class GlobalExceptionHandler implements ExceptionHandler<GlobalException, HttpResponse> {
    private static final Logger LOG = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @Override
    public HttpResponse handle(HttpRequest request, GlobalException exception) {
        LOG.error(exception.getLocalizedMessage());
        LOG.error(exception.getCause().getMessage());
        Arrays.stream(exception.getStackTrace()).forEach(item -> LOG.error(item.toString()));
        return HttpResponse.serverError(exception.getLocalizedMessage());
    }
}

On exception with below code, the handler method never get called

@Override
    public Flux<FindProductCommand> get(ProductSearchCriteriaCommand searchCriteria) {
        LOG.info("Controller --> Finding all the products");
        return iProductManager.find(searchCriteria).onErrorMap(throwable -> {
            return new GlobalException(throwable);
        });
    }

I had this code Global exception handling in micronaut Java from rxjava 3 which was working fine, however, now with project reactor it is not working

Body:
Try this one:

@Override
    public Flux<FindProductCommand> get(ProductSearchCriteriaCommand searchCriteria) {
        LOG.info("Controller --> Finding all the products");
        return iProductManager
                  .find(searchCriteria)
                  .onErrorResume(e -> Mono.error(new GlobalException("My exception", e));
    }


问:
Using Radio Button for boolean field in Modelform
in models

```<code>choice = models.BooleanField()
</code>```

in forms I use

```<code>choices = (
('1', 'Buy'),
('0', 'Sell'),
</code>```

)

```<code>choice = forms.TypedChoiceField(label=u'Тип предожения', choices=choices, widget=forms.RadioSelect,)
</code>```

but when i edit item, value is not selected... How can I make to previous selected value be marked

答: You've used strings for your choices keys. Booleans are True and False.

Body:
in models

choice = models.BooleanField()

in forms I use

choices = (
('1', 'Buy'),
('0', 'Sell'),

)

choice = forms.TypedChoiceField(label=u'Тип предожения', choices=choices, widget=forms.RadioSelect,)

but when i edit item, value is not selected... How can I make to previous selected value be marked


问:
How to check if current date is between two dates in javascript
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.</p>
```<code>const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];
</code>```

答:
You can check by calling this function.</p>
```<code>function compareDates(startDate,endDate){
  let current=new Date();
  return startDate>=current && endDate<=current;
}
</code>```

Body:
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.

const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];

Body:
You can check by calling this function.

function compareDates(startDate,endDate){
  let current=new Date();
  return startDate>=current && endDate<=current;
}


问:
Display List items horizontally not vertically
I want to display books list in a horizontal way not in a vertical way..

Here is my foreach loop in book_view.blade.php

```<code>@foreach ($books as $book)
<div class="d-inline p-2">
<div class="w3-card-4 w3-dark-grey" style="width:50%">
<div class="w3-container w3-center">
<h5 style="color:#3490dc;"> {{ $book->title }}</h5>
<?php
$books = (json_decode($book->img))[0]->download_link;
?>
<img src="{{ Voyager::image( $books ) }}" alt="images"/>
<br/>
<h6>Auther: <span class="badge badge-secondary">{{ $book->auther }}</h6>
<h6>Published: {{ $book->published }}<h6>
<h6 style="color:#3490dc;">ISBN: {{ $book->isbn }}</h6>

  <div class="w3-section">
  </div>
  <?php
  $books = (json_decode($book->pdf))[0]->download_link;
  ?>enter code here
  <a href="{{ Voyager::image( $books ) }}" class="btn btn-primary">Read Book</a>
  <a href="{{ url('/checkout') }}" class="btn btn-success">Buy Book</a>
  <br/>
</div>
</div>

    @endforeach
</code>```

Here is the image  of the current output...

答:
You are missing a closing div. You should format your code and make it more readable then you will spot errors like this faster:

@foreach ($books as $book)

 {{ $book->title }}

      <?php $books = (json_decode($book->img))[0]->download_link; ?>

Auther: {{ $book->auther }}

Published: {{ $book->published }}

ISBN: {{ $book->isbn }}

      <?php $books = (json_decode($book->pdf))[0]->download_link; ?>
      enter code here
      Read Book
      Buy Book

@endforeach
```

Body:
I want to display books list in a horizontal way not in a vertical way..

Here is my foreach loop in book_view.blade.php

@foreach ($books as $book)

 {{ $book->title }}

<?php
$books = (json_decode($book->img))[0]->download_link;
?>

Auther: {{ $book->auther }}

Published: {{ $book->published }}

ISBN: {{ $book->isbn }}

  <?php
  $books = (json_decode($book->pdf))[0]->download_link;
  ?>enter code here
  Read Book
  Buy Book

    @endforeach

Here is the image  of the current output...

Body:
You are missing a closing div. You should format your code and make it more readable then you will spot errors like this faster:

@foreach ($books as $book)
<div class="d-inline p-2">
  <div class="w3-card-4 w3-dark-grey" style="width:50%">
    <div class="w3-container w3-center">
      <h5 style="color:#3490dc;"> {{ $book->title }}</h5>
      <?php $books = (json_decode($book->img))[0]->download_link; ?>
      <img src="{{ Voyager::image( $books ) }}" alt="images"/>
      <br/>
      <h6>Auther: <span class="badge badge-secondary">{{ $book->auther }}</h6>
      <h6>Published: {{ $book->published }}<h6>
      <h6 style="color:#3490dc;">ISBN: {{ $book->isbn }}</h6>
      <div class="w3-section">
      </div>
      <?php $books = (json_decode($book->pdf))[0]->download_link; ?>
      enter code here
      <a href="{{ Voyager::image( $books ) }}" class="btn btn-primary">Read Book</a>
      <a href="{{ url('/checkout') }}" class="btn btn-success">Buy Book</a>
      <br/>
    </div>
  </div>
</div>  <!-- You are missing this -->
@endforeach


问:
Updating a PriorityQueue when iterating it
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}
</code>```

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}
</code>```

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

```<code>PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());
</code>```

with:

```<code>public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}
</code>```

答:
The Javadoc for PriorityQueue says explicitly:

"Note that this implementation is not synchronized. Multiple threads should not access a PriorityQueue instance concurrently if any of the threads modifies the list structurally. Instead, use the thread-safe PriorityBlockingQueue class."

This seems to be your case.

Body:
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());

with:

public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}


问:
Inject default template argument type from user code
Is there a way to "inject" a default type for a template member function of a template class "after" the definition of said template member function?

Basically similar to this (which does not compile), so that I can specify NS::Default (the default type for Z) outside of the library in which template class S and its member function template are defined:

// In library
namespace NS {}

template<typename T>
struct S {
  template<typename X, typename Z = NS::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code
namespace NS {
  using Default = int;
}

S<SomeClass> s;
s.foo(3.14); // z == int(0)
```
<p>I think I once had code like this working with later specified type traits, but it's been a while and my template foo is a bit rusty.</p>
<p>Primary goal is to be able to call <code>S::foo</code> with just one argument and have it use a default argument with a default type, which is specified NOT by the library but rather the using code.</p>
<p>Injection of that type via the class templates is of course an option but NOT what I'm asking for. So I don't want to have to do:</p>
<pre class="lang-cpp prettyprint-override"><code>// library
template<typename T, typename ZDefault>
struct S {
  template<typename X, typename Z = ZDefault>
  void foo(X x, Z z = Z{}) {}
};

// User
S<SomeClass, int> s;
s.foo(3.14);
</code>```

答:
You can create a traits that customer should define/specialize:</p>
```<code>// In library
template <typename> struct DefaultType; // declaration without definition.

template<typename T>
struct S {
  template<typename X, typename Z = typename DefaultType<X>::type>
  void foo(X x, Z z = Z{}) {}
};

// In user code
template <typename> struct DefaultType
{
    using type = int;
};

S<SomeClass> s;
s.foo(3.14); // z == int(0)
</code>```

Body:
Is there a way to "inject" a default type for a template member function of a template class "after" the definition of said template member function?

Basically similar to this (which does not compile), so that I can specify NS::Default (the default type for Z) outside of the library in which template class S and its member function template are defined:

// In library
namespace NS {}

template<typename T>
struct S {
  template<typename X, typename Z = NS::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code
namespace NS {
  using Default = int;
}

S<SomeClass> s;
s.foo(3.14); // z == int(0)

I think I once had code like this working with later specified type traits, but it's been a while and my template foo is a bit rusty.

Primary goal is to be able to call S::foo with just one argument and have it use a default argument with a default type, which is specified NOT by the library but rather the using code.

Injection of that type via the class templates is of course an option but NOT what I'm asking for. So I don't want to have to do:

// library
template<typename T, typename ZDefault>
struct S {
  template<typename X, typename Z = ZDefault>
  void foo(X x, Z z = Z{}) {}
};

// User
S<SomeClass, int> s;
s.foo(3.14);

Body:
You can create a traits that customer should define/specialize:

// In library
template <typename> struct DefaultType; // declaration without definition.

template<typename T>
struct S {
  template<typename X, typename Z = typename DefaultType<X>::type>
  void foo(X x, Z z = Z{}) {}
};

// In user code
template <typename> struct DefaultType
{
    using type = int;
};

S<SomeClass> s;
s.foo(3.14); // z == int(0)


问:
Windows Cmake Error: No CUDA toolset found
I was doing a project about image processing. I installed darknet, OpenCV and NVIDIA GPU Computing Toolkit\CUDA\v10.2. I was able to get build on OpenCV, but when trying to get build on darknet, it gives the following errors and I couldn't find the solution even though I searched for hours.</p>

```<code>CMake Error at C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCompilerId.cmake:367 (message):
  No CUDA toolset found.
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCompilerId.cmake:32 (CMAKE_DETERMINE_COMPILER_ID_BUILD)
  C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCUDACompiler.cmake:72 (CMAKE_DETERMINE_COMPILER_ID)
  CMakeLists.txt:60 (enable_language)
</code>```

答: It is effective to reinstall cuda without uninstalling the original cuda</p>

Body:
I was doing a project about image processing. I installed darknet, OpenCV and NVIDIA GPU Computing Toolkit\CUDA\v10.2. I was able to get build on OpenCV, but when trying to get build on darknet, it gives the following errors and I couldn't find the solution even though I searched for hours.

CMake Error at C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCompilerId.cmake:367 (message):
  No CUDA toolset found.
Call Stack (most recent call first):
  C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCompilerId.cmake:32 (CMAKE_DETERMINE_COMPILER_ID_BUILD)
  C:/Program Files/CMake/share/cmake-3.17/Modules/CMakeDetermineCUDACompiler.cmake:72 (CMAKE_DETERMINE_COMPILER_ID)
  CMakeLists.txt:60 (enable_language)


问:
when would I use create-react-app and when would I use Webpack
Which is top performance giver and Is there any specific advantage of webpack over react-scripts build?</p>

答: Both are not fast enough when Compared to Snowpack or Vite. I don't know why react-script popular. React Script is actually using Webpack under the hoods.


问:
How to replace home page in Azure Function App with something else?
Using application setting "AzureWebJobsDisableHomepage": true the default home page for an Azure Function App is disabled, but how can I replace this page with something else?

For example, having a function that returns an HTML page:

```<code>import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { promises as fs } from "fs"
import { resolve } from "path"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    const htmlPage = await fs.readFile(resolve(__dirname, "../../index.html"), "utf-8")

    context.res = {
        headers: {
            "content-type": "text/html"
        },
        body: htmlPage
    }
};

export default httpTrigger;

</code>```

Setting "routePrefix": "" in host.json I should be able to serve this function from any route:

```<code>"extensions": {
  "http": {
    "routePrefix": ""
  }
}
</code>```

But I just can't serve it from /, it always returns an empty page. Is there any way to overwrite this behavior?

答:
Here is the workaround I did to replace the default home page of the Azure Functions (typeScript Stack - Http Trigger) with an HTML Page.

Firstly, Created the Azure Functions in typeScript with Http Trigger using VS Code.

Created the HTML File with some code under the Http Trigger Directory:

and here is the folder structure:

In local.settings.json, defined the setting AzureWebJobsDisableHomepage which means Set to "true" to disable the default landing page shown for the root of the Azure Functions site.

Ref: Configuration settings Information for Azure Functions Site.

```<code>{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"AzureWebJobsDisableHomepage": "true"
}
}
</code>```

Index.ts code:

```<code>import { AzureFunction, Context, HttpRequest } from  "@azure/functions"
import { promises  as  fs } from  "fs"
import { resolve } from  "path"

const  httpTrigger: AzureFunction = async  function (context: Context, req: HttpRequest): Promise<void> {
context.log('HTTP trigger function processed a request.');

var  __dirname = "HttpTrigger1";
const  htmlPage = await  fs.readFile(resolve("./" + __dirname + "/index.html"), 'utf-8');

context.res = {
headers: {
"content-type":  "text/html"
},
body:  htmlPage
}
};

export  default  httpTrigger;
</code>```

Running the function locally:

Deployed to Azure and running in the cloud successfully:

Body:
Using application setting "AzureWebJobsDisableHomepage": true the default home page for an Azure Function App is disabled, but how can I replace this page with something else?

For example, having a function that returns an HTML page:

import { AzureFunction, Context, HttpRequest } from "@azure/functions"
import { promises as fs } from "fs"
import { resolve } from "path"

const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    const htmlPage = await fs.readFile(resolve(__dirname, "../../index.html"), "utf-8")

    context.res = {
        headers: {
            "content-type": "text/html"
        },
        body: htmlPage
    }
};

export default httpTrigger;

Setting "routePrefix": "" in host.json I should be able to serve this function from any route:

"extensions": {
  "http": {
    "routePrefix": ""
  }
}

But I just can't serve it from /, it always returns an empty page. Is there any way to overwrite this behavior?

Body:
Here is the workaround I did to replace the default home page of the Azure Functions (typeScript Stack - Http Trigger) with an HTML Page.

Firstly, Created the Azure Functions in typeScript with Http Trigger using VS Code.

Created the HTML File with some code under the Http Trigger Directory:

and here is the folder structure:

In local.settings.json, defined the setting AzureWebJobsDisableHomepage which means Set to "true" to disable the default landing page shown for the root of the Azure Functions site.

Ref: Configuration settings Information for Azure Functions Site.

{
"IsEncrypted": false,
"Values": {
"AzureWebJobsStorage": "",
"FUNCTIONS_WORKER_RUNTIME": "node",
"AzureWebJobsDisableHomepage": "true"
}
}

Index.ts code:

import { AzureFunction, Context, HttpRequest } from  "@azure/functions"
import { promises  as  fs } from  "fs"
import { resolve } from  "path"

const  httpTrigger: AzureFunction = async  function (context: Context, req: HttpRequest): Promise<void> {
context.log('HTTP trigger function processed a request.');

var  __dirname = "HttpTrigger1";
const  htmlPage = await  fs.readFile(resolve("./" + __dirname + "/index.html"), 'utf-8');

context.res = {
headers: {
"content-type":  "text/html"
},
body:  htmlPage
}
};

export  default  httpTrigger;

Running the function locally:

Deployed to Azure and running in the cloud successfully:


问:
Calling a Rest-API using C#
I'm trying to call a rest-api in asp.net to test if people are trustworthy with paying by invoice. The problem is that i've never used any rest-api before and couldn't find a good example on how to call it in asp.net. Can someone help me?

Here are the values that the request needs.

```<code>/api/v1/RiskCube/claim

{
  "shopId": "20071992",
  "orderProcessId": "ref001",
  "ipAddress": null,
  "macAddress": null,
  "customerId": "cus001",
  "billingAddress": {
    "type": "Consumer",
    "businessName": null,
    "firstName": "Martin",
    "lastName": "Früh",
    "co": null,
    "street": "Funkenbüelstrasse",
    "houseNumber": "1",
    "postCode": "9243",
    "locationName": "Jonschwil",
    "country": "CH",
    "email": null,
    "phone": null,
    "dateOfBirth": null
  },
  "shippingAddress": null,
  "orderAmount": 1200
}
</code>```

答:
So, you can try out using HttpClient to call another API. Ex. https://learn.microsoft.com/ru-ru/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0 . And you can use libraries for that like Refit https://github.com/reactiveui/refit

edit: Link in english
https://learn.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-6.0

Title: Calling a Rest-API using C#

Body:
I'm trying to call a rest-api in asp.net to test if people are trustworthy with paying by invoice. The problem is that i've never used any rest-api before and couldn't find a good example on how to call it in asp.net. Can someone help me?

Here are the values that the request needs.

/api/v1/RiskCube/claim

{
  "shopId": "20071992",
  "orderProcessId": "ref001",
  "ipAddress": null,
  "macAddress": null,
  "customerId": "cus001",
  "billingAddress": {
    "type": "Consumer",
    "businessName": null,
    "firstName": "Martin",
    "lastName": "Früh",
    "co": null,
    "street": "Funkenbüelstrasse",
    "houseNumber": "1",
    "postCode": "9243",
    "locationName": "Jonschwil",
    "country": "CH",
    "email": null,
    "phone": null,
    "dateOfBirth": null
  },
  "shippingAddress": null,
  "orderAmount": 1200
}


问:
Message is stuck at azure service Bus. How to retrigger delivery of message?
Message is stuck on azure service bus for last 24 hours. It is not getting delivered to Listener.
Active message: 2
message time to live : 14 days
Message lock duration: 5 minutes
max delivery count:1 (we have reduced it to 1 as 5 minutes is not enough to finish processing)
Is there any way we can re trigger these messages to the listener?</p>

答:
In your listener, please make sure you need to recheck once the active and deadletter queue.

If you are using Recieve();/ RecieveBatch();/ onMessage(); in your listener it will receive the queues messages not to get the stuck or not processed messages, for that you have to use the Complete() or abandon().

complete():

Complete() is used for any message you have to process.

abandon()

The abandon() is immediately available in the queue for another worker to process. And check the BrokeredMessage.Abandon()

DeliveryCount

The DeliveryCount property is used to not process a message twice.

Refer here

Message lock duration: 5 minutes max delivery count:1 (we have reduced it to 1 as 5 minutes is not enough to finish processing) Is there any way we can re-trigger these messages to the listener?

The Maximum delivery count is our flexibility only we can Gets or sets the maximum delivery count. A message is automatically deadlettered after this number of deliveries.

The Lock Duration (Seconds) has some limitations like we can Gets or sets the duration of a peek lock. The maximum value for LockDuration is 5 minutes(default is 1 minute).

Please refer here for more information


问:
Convert decimal mark when reading numbers as input
I have a CSV file with data reading that I want to read into Python. I get lists that contain strings like "2,5". Now doing float("2,5") does not work, because it has the wrong decimal mark.

How do I read this into Python as 2.5?

答:
float("2,5".replace(',', '.')) will do in most cases

If valueis a large number and .has been used for thousands, you can:

Replace all commas for points: value.replace(",", ".")

Remove all but the last point: value.replace(".", "", value.count(".") -1)


问:
Add empty form field to an existing page
I tried to use the "CreateEmptySignatureForm.java" example in PDFBox GitHub, and it is only working if I have a new page on my document. If I want to use the first page of the document, the empty signature form field does not appear in Adobe Reader.

This is the code that works for a new page:

```<code>PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);
</code>```

This is my code:

```<code>PDPage page =  document.getPages().get(0);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);

</code>```

Can anybody help me out?

答:
I figured out the problem :

I need to add this line code :

```<code>page.getCOSObject().setNeedToBeUpdated(true);
</code>```

Body:
I tried to use the "CreateEmptySignatureForm.java" example in PDFBox GitHub, and it is only working if I have a new page on my document. If I want to use the first page of the document, the empty signature form field does not appear in Adobe Reader.

This is the code that works for a new page:

PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);

This is my code:

PDPage page =  document.getPages().get(0);

PDAcroForm acroForm = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(acroForm);

String defaultAppearanceString = "/Helv 0 Tf 0 g";
acroForm.setDefaultAppearance(defaultAppearanceString);

PDTextField textBox = new PDTextField(acroForm);
textBox.setPartialName("SampleField");

defaultAppearanceString = "/Helv 12 Tf 0 0 1 rg";
textBox.setDefaultAppearance(defaultAppearanceString);

acroForm.getFields().add(textBox);

PDSignatureField signatureField = new PDSignatureField(acroForm);
PDAnnotationWidget widget = signatureField.getWidgets().get(0);
PDRectangle rect = new PDRectangle(50, 100, 200, 50);
widget.setRectangle(rect);

widget.setPage(page);

widget.setPrinted(true);

page.getAnnotations().add(widget);

acroForm.getFields().add(signatureField);

ByteArrayOutputStream out = new ByteArrayOutputStream();

document.save(out);

Can anybody help me out?

Body:
I figured out the problem :

I need to add this line code :

page.getCOSObject().setNeedToBeUpdated(true);


问:
How to print 1 2 3 4 in double digits in a C++ program
I want to print a 4x4 matrix starting from 1 to 16 and printing just 1, 2, 3, and 4 are simply ruining the aesthetic of the output.

I want it to be symmetric, how can I print 01, 02, 03 instead of 1, 2, 3?

答:
Check iomanip

```<code>#include <iostream>
#include <iomanip>

int main() {
    const size_t N = 3;
    int mat[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (size_t i = 0; i < N; ++i) {
        for (size_t j = 0; j < N; ++j) {
            std::cout << std::setw(2) << std::setfill('0') << mat[i][j] << ' ';
        }
        std::cout << std::endl;
    }
    return 0;
}
</code>```

Body:
Check iomanip

#include <iostream>
#include <iomanip>

int main() {
    const size_t N = 3;
    int mat[N][N] = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
    };

    for (size_t i = 0; i < N; ++i) {
        for (size_t j = 0; j < N; ++j) {
            std::cout << std::setw(2) << std::setfill('0') << mat[i][j] << ' ';
        }
        std::cout << std::endl;
    }
    return 0;
}


问:
How to get fibonacci in c#
Guys I have a question regarding on fibonacci..How do I get the fibonacci series that the number will also end on user input...example if I put 21 the output must be 0 1 1 2 3 5 8 13 21

This is my code

```<code>    static void Main(string[] args)
    {

        int input, first = 0, second = 1, third = 0;
        Console.Write("Enter a number : ");
        n = Convert.ToInt32(Console.ReadLine());
        Console.Write("First {0} Fibonacci numbers {1} {2} ", input, first, second);

        for (int i = 3; i <= input; i++)
        {
            third = first + second;
            Console.Write("{0} ", third);
            first = second;
            second = third;
        }

    }
</code>```

答:
What i did is;</p>
```<code>public int Fibonacci(int nth)
            {
                if (nth < 0) return 0;
                if (nth < 2) return nth;

                int Next = 0;
                int Current = 1;
                int Previous = 0;

                for (int i = 1; i < nth; i++)
                {
                    Next = Current + Previous;
                    Previous = Current;
                    Current = Next;
                }
                return Next;
            }
</code>```

Title: How to get fibonacci in c#

Body:
Guys I have a question regarding on fibonacci..How do I get the fibonacci series that the number will also end on user input...example if I put 21 the output must be 0 1 1 2 3 5 8 13 21

This is my code

    static void Main(string[] args)
    {

        int input, first = 0, second = 1, third = 0;
        Console.Write("Enter a number : ");
        n = Convert.ToInt32(Console.ReadLine());
        Console.Write("First {0} Fibonacci numbers {1} {2} ", input, first, second);

        for (int i = 3; i <= input; i++)
        {
            third = first + second;
            Console.Write("{0} ", third);
            first = second;
            second = third;
        }

    }

Body:
What i did is;

public int Fibonacci(int nth)
            {
                if (nth < 0) return 0;
                if (nth < 2) return nth;

                int Next = 0;
                int Current = 1;
                int Previous = 0;

                for (int i = 1; i < nth; i++)
                {
                    Next = Current + Previous;
                    Previous = Current;
                    Current = Next;
                }
                return Next;
            }


问:
500 errors are not caught in prod environment
I have a strange problem in a symfony 5.3.10 app and i can't wrap my head around it.

If I trigger a 500 error, like so:

```<code>/**
 * @Route("/", name="pvr_index", methods={"GET"})
 */
public function index(): Response
{
    echo $a;
</code>```

Where $a is not defined, in dev environment I get a nice error page.

I'd expect that in prod I would get a not so nice error page that just tells me that i have a 500 error.  And this would happen correctly until some time ago, when something changed, but I don't know what.

Now instead I get no error, not even in the symfony server console, and the script execution would keep on going like nothing happened.

What I have tried:

Adding the supposed exception inside a try/catch:

```<code>try {
        echo $a;
    }
    catch (\Exception $e)
    {
        dump($e);
        die();
    }
</code>```

Nothing happens, the catch isn't triggered.

Creating an exception listener:

In services.yaml i have:

```<code>exception_listener:
    class: App\Event\ExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception }
</code>```

And in ExceptionListener.php i have:

```<code>class ExceptionListener
{
    public function __construct(Environment $engine) {
        $this->engine = $engine;
    }
    public function onKernelException(ExceptionEvent $event)
    {
        dd($event->getThrowable()->getMessage());
    }
}
</code>```

Still nothing happens, the listener isn't triggered.

Everything works as expected in dev environment, the problem presents itself only in prod.

Looking at a phpinfo(); page I see that the error reporting is enabled, so I think that the problem lies in the symfony configuration.

I'm using php 7.4 and have no real access to the php.ini file

答:
This is not a Symfony error (nor a PHP error for that matter).

On PHP 7.4, trying to output an undefined variable would only raise a notice, not a fatal error (code 500). Notices are silently swallowed up by the engine unless you configure your server to log them or output them, where you'd get something like:

Notice: Undefined variable: a in file xxx.php line Y

A try/catch won't do anything for you, since no exception is thrown for you to catch.

Even on PHP 8 or 8.1, this will only raise a warning like:

Warning: Undefined variable $a

You can see the result under version < 8 and >= 8 here.

Body:
I have a strange problem in a symfony 5.3.10 app and i can't wrap my head around it.

If I trigger a 500 error, like so:

/**
 * @Route("/", name="pvr_index", methods={"GET"})
 */
public function index(): Response
{
    echo $a;

Where $a is not defined, in dev environment I get a nice error page.

I'd expect that in prod I would get a not so nice error page that just tells me that i have a 500 error.  And this would happen correctly until some time ago, when something changed, but I don't know what.

Now instead I get no error, not even in the symfony server console, and the script execution would keep on going like nothing happened.

What I have tried:

Adding the supposed exception inside a try/catch:

try {
        echo $a;
    }
    catch (\Exception $e)
    {
        dump($e);
        die();
    }

Nothing happens, the catch isn't triggered.

Creating an exception listener:

In services.yaml i have:

exception_listener:
    class: App\Event\ExceptionListener
    tags:
        - { name: kernel.event_listener, event: kernel.exception }

And in ExceptionListener.php i have:

class ExceptionListener
{
    public function __construct(Environment $engine) {
        $this->engine = $engine;
    }
    public function onKernelException(ExceptionEvent $event)
    {
        dd($event->getThrowable()->getMessage());
    }
}

Still nothing happens, the listener isn't triggered.

Everything works as expected in dev environment, the problem presents itself only in prod.

Looking at a phpinfo(); page I see that the error reporting is enabled, so I think that the problem lies in the symfony configuration.

I'm using php 7.4 and have no real access to the php.ini file


问:
ORA 01722 : Dealing with invalid number
I am dealing with some data quality issues. I would like to remove all the dots and replace dot with comma in the end and replace negative in the end to front.
Below are the examples:

70.693.271.273,20- convert to -70693271273,20
1.312.871.286.870- convert to -1312871286,870

For the first case 70.693.271.273,20- I am using the below syntax which gives me results -70693271273,20

```<code>CASE WHEN REGEXP_COUNT("/BIC/ISMVALUE", '\.') >= 1
AND REGEXP_COUNT("/BIC/ISMVALUE", ',') = 1 THEN
to_number(REPLACE(TRIM(BOTH '-' FROM TRIM("/BIC/ISMVALUE")), '.', '') * (-1))
ELSE TO_NUMBER(TRIM("/BIC/ISMVALUE")) END oprl_value
</code>```

Similarly I would like to get same format results for case 2.
Can you please help on how to deal with second case 1.312.871.286.870- ?
Thanks

答:
Use multiple replace and concatenation</p>
```<code>SELECT '-' || REPLACE(REPLACE(TRIM(your_value),'.',','),'-','') AS oprl_value
</code>```

Title: ORA 01722 : Dealing with invalid number

Body:
I am dealing with some data quality issues. I would like to remove all the dots and replace dot with comma in the end and replace negative in the end to front.
Below are the examples:

70.693.271.273,20- convert to -70693271273,20
1.312.871.286.870- convert to -1312871286,870

For the first case 70.693.271.273,20- I am using the below syntax which gives me results -70693271273,20

CASE WHEN REGEXP_COUNT("/BIC/ISMVALUE", '\.') >= 1
AND REGEXP_COUNT("/BIC/ISMVALUE", ',') = 1 THEN
to_number(REPLACE(TRIM(BOTH '-' FROM TRIM("/BIC/ISMVALUE")), '.', '') * (-1))
ELSE TO_NUMBER(TRIM("/BIC/ISMVALUE")) END oprl_value

Similarly I would like to get same format results for case 2.
Can you please help on how to deal with second case 1.312.871.286.870- ?
Thanks

Body:
Use multiple replace and concatenation

SELECT '-' || REPLACE(REPLACE(TRIM(your_value),'.',','),'-','') AS oprl_value


问:
Flutter build ipa without buildName and BuildNumber
I have set the version in my pubspec.yaml file like below,

```<code>version: 3.0.0+5
</code>```

and put these key/string in my Info.plist file under my project.

```<code><key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>

<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>
</code>```

I have open XCode and check the target under my project, and in the General tab, the Version and Build column seems normal, the numbers are correct.

And then when I run flutter build ipa in my terminal, it just build an archive without Version.

After the fail, I change the Version and Build number directly in Xcode, which cause the change in Info.plist below.

```<code><key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>

<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>
</code>```

And I run flutter build ipa again, this time it works fine.

Is this behavior normal that I have to change the Version and Build manually?

Or is there something wrong with my setting somewhere in my project?

I've tried method below

flutter clean

clean build in xcode

delete derivedata folder in xcode

flutter pub get

cd ios

pod install

pod update

flutter build ipa

Still not working.

答:
Try below steps:

flutter clean

flutter pub get

cd ios

pod install

pod update

flutter build ipa

Body:
I have set the version in my pubspec.yaml file like below,

version: 3.0.0+5

and put these key/string in my Info.plist file under my project.

<key>CFBundleShortVersionString</key>
<string>$(FLUTTER_BUILD_NAME)</string>

<key>CFBundleVersion</key>
<string>$(FLUTTER_BUILD_NUMBER)</string>

I have open XCode and check the target under my project, and in the General tab, the Version and Build column seems normal, the numbers are correct.

And then when I run flutter build ipa in my terminal, it just build an archive without Version.

After the fail, I change the Version and Build number directly in Xcode, which cause the change in Info.plist below.

<key>CFBundleShortVersionString</key>
<string>$(MARKETING_VERSION)</string>

<key>CFBundleVersion</key>
<string>$(CURRENT_PROJECT_VERSION)</string>

And I run flutter build ipa again, this time it works fine.

Is this behavior normal that I have to change the Version and Build manually?

Or is there something wrong with my setting somewhere in my project?

I've tried method below

flutter clean

clean build in xcode

delete derivedata folder in xcode

flutter pub get

cd ios

pod install

pod update

flutter build ipa

Still not working.


问:
Centering CSS grid divs with iFrame and Img
So I want to create a grid on my site that has 2 i frames at the top and 2 imgs below e.g

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

I have managed to get some code working, but it doesn't look quite right, right now the grid is stuck to the left-hand side of the page and in mobile view it just goes off the screen and doesn't fit to a mobile version, another issue is there is a random gap between each column. E.g below.

iframe {
  border: 1px solid;
}

.plotly-charts {
  justify-content: center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="plotly-charts">
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <iframe width="600px" height="500px" frameborder="0" scrolling="no" src="someframe"></iframe>
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Positive" style="width:300px; height:300px;">
  </div>
  <div class="charts">
    <img src="https://dummyimage.com/300x300/525eff/ffffff" alt="Word Cloud Negative-Neutral" style="width:300px; height:300px;">
  </div>
</div></code>```

答:
The best way is to use Bootstrap.. Or you should use media queries including some Javascript... Bootstrap is easy tho

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

hello world

```

that's it

Body:
So I want to create a grid on my site that has 2 i frames at the top and 2 imgs below e.g

X X
X X

I have managed to get some code working, but it doesn't look quite right, right now the grid is stuck to the left-hand side of the page and in mobile view it just goes off the screen and doesn't fit to a mobile version, another issue is there is a random gap between each column. E.g below.

iframe {
  border: 1px solid;
}

.plotly-charts {
  justify-content: center;
  display: grid;
  grid-template-columns: 1fr 1fr;
  padding: 5px;
}

Body:
The best way is to use Bootstrap.. Or you should use media queries including some Javascript... Bootstrap is easy tho

<!--Import bootstrap-->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">

<!--Add classes to your elements-->
<!--No need of grids instead use div classes-->

<div class="text-center d-flex col-md-4">
<h1>hello world</h1>
</div>

<!--Bootstrap script-->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>

that's it


问:
How to close connection objects created for Gcp-Storage and pub-sub using Google Cloud Platform's python libraries
My application is creating pub-sub objects using:

```<code>google.cloud import pubsub_v1
publisher_client = pubsub_v1.PublisherClient
</code>```

and storage objects using:

```<code>from google.cloud import storage
client = storage.Client()
</code>```

how  can I quickly and gracefully  close/release these connection objects  so that can be used at scale?

答:
The client objects are in memory objects if functions required for the interaction with google services, but they don't open network connection since they are created and keep it opened. So, having many objects created may not be a problem, since they are in memory allocations, like variables.

I have made a test creating thousands of clients in loop and there was no problem at all.

But, thay can be closed if you want. Basically just calling the following should delete them by:

google.cloud import pubsub_v1
from google.cloud import storage

publisher_client = pubsub_v1.PublisherClient()
client = storage.Client()

del publisher_client
del client
```

Its also recommended calling the following functions before del the objects:

publisher_client.stop():

Asynchronously sends all outstanding messages and prevents future calls to publish(). Method should be invoked prior to deleting this Client() object in order to ensure that no pending messages are lost.

client.close():

Documentation is not very clear about it, but seams to close any files being read to be uploaded.

The another problem you have facing in production related to the GOOGLE_APPLICATION_CREDENTIALS env variable is because you have to set it on the production env.

Create a service account on GCP IAM console;

Add proper permissions (Cloud Store Editor, Pub/Sub Editor (?))

create a key on it (json) download and set env variable GOOGLE_APPLICATION_CREDENTIALS pointing to /path/of/key/key.json

more details in this documentation.

Body:
My application is creating pub-sub objects using:

google.cloud import pubsub_v1
publisher_client = pubsub_v1.PublisherClient

and storage objects using:

from google.cloud import storage
client = storage.Client()

how  can I quickly and gracefully  close/release these connection objects  so that can be used at scale?

Body:
The client objects are in memory objects if functions required for the interaction with google services, but they don't open network connection since they are created and keep it opened. So, having many objects created may not be a problem, since they are in memory allocations, like variables.

I have made a test creating thousands of clients in loop and there was no problem at all.

But, thay can be closed if you want. Basically just calling the following should delete them by:

google.cloud import pubsub_v1
from google.cloud import storage

publisher_client = pubsub_v1.PublisherClient()
client = storage.Client()

del publisher_client
del client

Its also recommended calling the following functions before del the objects:

publisher_client.stop():

Asynchronously sends all outstanding messages and prevents future calls to publish(). Method should be invoked prior to deleting this Client() object in order to ensure that no pending messages are lost.

client.close():

Documentation is not very clear about it, but seams to close any files being read to be uploaded.

The another problem you have facing in production related to the GOOGLE_APPLICATION_CREDENTIALS env variable is because you have to set it on the production env.

Create a service account on GCP IAM console;

Add proper permissions (Cloud Store Editor, Pub/Sub Editor (?))

create a key on it (json) download and set env variable GOOGLE_APPLICATION_CREDENTIALS pointing to /path/of/key/key.json

more details in this documentation.


问:
Print array of strings - Shell Script
Dears,

Simple question, I have a shell variable with the following values,

```<code>myarr=["Life","is","good","when","you","learning"]
</code>```

It is an array of strings ! Here is how I want to print it. Also, I need to do with a loop because each of these element would be passed to a function to process the string

Expected Output

```<code>Life \
is \
good \
when \
you \
learning
</code>```

答:
An array literal is declared in the shell like so:

```<code>myarr=(Life is good when you learning)
</code>```

And if you have such an array you can pass it to printf like so (note the "double quotes" around the expansion):

```<code>printf "%s\n" "${myarr[@]}"
Life
is
good
when
you
learning
</code>```

You use "double quotes" if you have spaces in individual elements when declaring the array:

```<code>myarr=("Life is good" when you learning)
printf "%s\n" "${myarr[@]}"
Life is good
when
you
learning
</code>```

You can also just make a string value then NOT use quotes which will split the string:

```<code>mys="Life is good when you learning"
printf "%s\n" $mys
Life
is
good
when
you
learning
</code>```

Beware though that that will also expand globs:

```<code>mys="Life is good when * you learning"
printf "%s\n" $mys
Life
is
good
when
...
a bunch of files from the glob in the cwd
...
file
you
learning
</code>```

Title: Print array of strings - Shell Script

Body:
Dears,

Simple question, I have a shell variable with the following values,

myarr=["Life","is","good","when","you","learning"]

It is an array of strings ! Here is how I want to print it. Also, I need to do with a loop because each of these element would be passed to a function to process the string

Expected Output

Life \
is \
good \
when \
you \
learning

Body:
An array literal is declared in the shell like so:

myarr=(Life is good when you learning)

And if you have such an array you can pass it to printf like so (note the "double quotes" around the expansion):

printf "%s\n" "${myarr[@]}"
Life
is
good
when
you
learning

You use "double quotes" if you have spaces in individual elements when declaring the array:

myarr=("Life is good" when you learning)
printf "%s\n" "${myarr[@]}"
Life is good
when
you
learning

You can also just make a string value then NOT use quotes which will split the string:

mys="Life is good when you learning"
printf "%s\n" $mys
Life
is
good
when
you
learning

Beware though that that will also expand globs:

mys="Life is good when * you learning"
printf "%s\n" $mys
Life
is
good
when
...
a bunch of files from the glob in the cwd
...
file
you
learning


问:
SQLite WHERE-Clause for every column?
Does SQLite offer a way to search every column of a table for a searchkey?

```<code>SELECT * FROM table WHERE id LIKE ...
</code>```

Selects all rows where ... was found in the column id. But instead to only search in the column id, I want to search in every column if the searchstring was found. I believe this does not work:

```<code>SELECT * FROM table WHERE * LIKE ...
</code>```

Is that possible? Or what would be the next easy way?

I use Python 3 to query the SQLite database. Should I go the route to search through the dictionary after the query was executed and data returned?

答:
I could not comment on @raging-bull answer. So I had to write a new one. My problem was, that I have columns with null values and got no results because the "search string" was null.

Using coalesce I could solve that problem. Here sqlite chooses the column content, or if it is null an empty string (""). So there is an actual search string available.

```<code>SELECT *
FROM table
WHERE (coalesce(col1,"") || coalesce(col2,"") || coalesce(col3,"") || coalesce(col4,"")) LIKE '%something%')
</code>```

Title: SQLite WHERE-Clause for every column?

Body:
Does SQLite offer a way to search every column of a table for a searchkey?

SELECT * FROM table WHERE id LIKE ...

Selects all rows where ... was found in the column id. But instead to only search in the column id, I want to search in every column if the searchstring was found. I believe this does not work:

SELECT * FROM table WHERE * LIKE ...

Is that possible? Or what would be the next easy way?

I use Python 3 to query the SQLite database. Should I go the route to search through the dictionary after the query was executed and data returned?

Body:
I could not comment on @raging-bull answer. So I had to write a new one. My problem was, that I have columns with null values and got no results because the "search string" was null.

Using coalesce I could solve that problem. Here sqlite chooses the column content, or if it is null an empty string (""). So there is an actual search string available.

SELECT *
FROM table
WHERE (coalesce(col1,"") || coalesce(col2,"") || coalesce(col3,"") || coalesce(col4,"")) LIKE '%something%')


问:
How to create DynamoDB table using docker CMD instruction and the AWS CLI inside running container?
Hello have a simple Dockerfile which has to create the DynamoDB tables:

```<code>FROM amazon/aws-cli AS seed

CMD \
aws dynamodb --endpoint-url http://localhost:8080 create-table \
    --table-name mytable \
    --attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
    --key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --region eu-west-2
</code>```

When I'm trying to run it I get the following output:

```<code>Attaching to my-container
my-container       |
my-container       | usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
my-container       | To see help text, you can run:
my-container       |
my-container       |   aws help
my-container       |   aws <command> help
my-container       |   aws <command> <subcommand> help
my-container       |
my-container       | aws: error: argument command: Invalid choice, valid choices are:
my-container       |
my-container       | accessanalyzer                           | account
my-container       | acm                                      | acm-pca
my-container       | alexaforbusiness                         | amp
my-container       | amplify                                  | amplifybackend
my-container       | amplifyuibuilder                         | apigateway
my-container       | apigatewaymanagementapi                  | apigatewayv2

// Lot of services in here

my-container       | s3                                       | ddb
my-container       | configure                                | deploy
my-container       | configservice                            | opsworks-cm
my-container       | history                                  | cli-dev
my-container       | help
my-container       |
my-container exited with code 252
</code>```

What am I doing wrong? Thanks for any help!

答:
With this particular image, the CMD must be in JSON-array syntax (one shell word to an array element) and must not contain the aws command.

FROM amazon/aws-cli
CMD ["dynamodb", "create-table", "..."]
```

This is because the aws-cli image declares ENTRYPOINT ["aws"], the ENTRYPOINT and CMD are combined into a single command, and string-format CMD inserts a shell wrapper.  Your main container command in the current form is something like aws sh -c 'aws dynamodb ...' which the tool doesn't really understand.

(I might run this particular command as a standalone docker run command and not try to package it into an image, or possibly use the AWS SDK as part of your integration-test setup code.  The explicit localhost endpoint also seems like it might not work well, since that will usually refer to the same container that's only running the AWS CLI.)

Body:
Hello have a simple Dockerfile which has to create the DynamoDB tables:

FROM amazon/aws-cli AS seed

CMD \
aws dynamodb --endpoint-url http://localhost:8080 create-table \
    --table-name mytable \
    --attribute-definitions AttributeName=user_id,AttributeType=N AttributeName=order_id,AttributeType=N \
    --key-schema AttributeName=user_id,KeyType=HASH AttributeName=order_id,KeyType=RANGE \
    --provisioned-throughput ReadCapacityUnits=5,WriteCapacityUnits=5 \
    --region eu-west-2

When I'm trying to run it I get the following output:

Attaching to my-container
my-container       |
my-container       | usage: aws [options] <command> <subcommand> [<subcommand> ...] [parameters]
my-container       | To see help text, you can run:
my-container       |
my-container       |   aws help
my-container       |   aws <command> help
my-container       |   aws <command> <subcommand> help
my-container       |
my-container       | aws: error: argument command: Invalid choice, valid choices are:
my-container       |
my-container       | accessanalyzer                           | account
my-container       | acm                                      | acm-pca
my-container       | alexaforbusiness                         | amp
my-container       | amplify                                  | amplifybackend
my-container       | amplifyuibuilder                         | apigateway
my-container       | apigatewaymanagementapi                  | apigatewayv2

// Lot of services in here

my-container       | s3                                       | ddb
my-container       | configure                                | deploy
my-container       | configservice                            | opsworks-cm
my-container       | history                                  | cli-dev
my-container       | help
my-container       |
my-container exited with code 252

What am I doing wrong? Thanks for any help!

Body:
With this particular image, the CMD must be in JSON-array syntax (one shell word to an array element) and must not contain the aws command.

FROM amazon/aws-cli
CMD ["dynamodb", "create-table", "..."]

This is because the aws-cli image declares ENTRYPOINT ["aws"], the ENTRYPOINT and CMD are combined into a single command, and string-format CMD inserts a shell wrapper.  Your main container command in the current form is something like aws sh -c 'aws dynamodb ...' which the tool doesn't really understand.

(I might run this particular command as a standalone docker run command and not try to package it into an image, or possibly use the AWS SDK as part of your integration-test setup code.  The explicit localhost endpoint also seems like it might not work well, since that will usually refer to the same container that's only running the AWS CLI.)


问:
Trying to get a bot to move people to afk channel once they deafen
I made a post yesterday but I think accidentally used python code instead of Java, not entirely sure. I know almost nothing about coding, especially java/python so any help would be much appreciated

at this point I'm not even sure if this is java or python code, if it's java I need help with the error I'm getting if it's python can I get some help translating it to java.
thanks <3

code:

```<code>async def on_voice_state_update(member, before, after):
if member.VoiceState.self_deaf:
    await member.move_to(afkchannel)
</code>```

error:

```<code>C:\Users\olivi\Desktop\DiscordBot\main.js:6
@bot.event
^

SyntaxError: Invalid or unexpected token
←[90m    at Object.compileFunction (node:vm:352:18)←[39m
←[90m    at wrapSafe (node:internal/modules/cjs/loader:1032:15)←[39m
←[90m    at Module._compile (node:internal/modules/cjs/loader:1067:27)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)←[39m
←[90m    at node:internal/main/run_main_module:17:47←[39m

</code>```

答:
C:\Users\olivi\Desktop\DiscordBot\main.js:6

Your file is main.js so that means that it is JavaScript.And you were trying to run python code which obviously is not compatible.

You have to delete all your Python code, and you should use:

```<code>client.on('voiceStateUpdate', (oldState, newState) => {
     let memchange = newState.member;
     if (memchange.selfDeaf){
        memchange.setChannel(afkchannelid);
     } else return;
});
</code>```

Body:
I made a post yesterday but I think accidentally used python code instead of Java, not entirely sure. I know almost nothing about coding, especially java/python so any help would be much appreciated

at this point I'm not even sure if this is java or python code, if it's java I need help with the error I'm getting if it's python can I get some help translating it to java.
thanks <3

code:

async def on_voice_state_update(member, before, after):
if member.VoiceState.self_deaf:
    await member.move_to(afkchannel)

error:

C:\Users\olivi\Desktop\DiscordBot\main.js:6
@bot.event
^

SyntaxError: Invalid or unexpected token
←[90m    at Object.compileFunction (node:vm:352:18)←[39m
←[90m    at wrapSafe (node:internal/modules/cjs/loader:1032:15)←[39m
←[90m    at Module._compile (node:internal/modules/cjs/loader:1067:27)←[39m
←[90m    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:981:32)←[39m
←[90m    at Function.Module._load (node:internal/modules/cjs/loader:822:12)←[39m
←[90m    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)←[39m
←[90m    at node:internal/main/run_main_module:17:47←[39m

Body:
C:\Users\olivi\Desktop\DiscordBot\main.js:6

Your file is main.js so that means that it is JavaScript.And you were trying to run python code which obviously is not compatible.

You have to delete all your Python code, and you should use:

client.on('voiceStateUpdate', (oldState, newState) => {
     let memchange = newState.member;
     if (memchange.selfDeaf){
        memchange.setChannel(afkchannelid);
     } else return;
});


问:
Typescript. Can I define conditional types?
Imagine I have the following type

```<code>type BannerConditions = {
    publication_id?: number;
    product_id?: number;
    resource?: string;
    type: string;
  };
</code>```

But publication_id and product_id can only exist if resource exists. Can I define it somehow?

答:
You could use a union to describe the two type

```<code>type BannerConditions = {
    publication_id: number;
    product_id: number;
    resource: string;
    type: string;
  } | {
    publication_id: undefined;
    product_id: undefined;
    resource: undefined;
    type: string;
}
</code>```
```<code>// foo would throw an error
const foo: BannerConditions = {
  publication_id: 1,
  product_id: 2,
  resource: undefined,
    type: 'x'
}
// no error for bar
const bar: BannerConditions = {
  publication_id: 1,
  product_id: 2,
  resource: 'test',
  type: 'x'
}
</code>```

Playground example

Body:
Imagine I have the following type

type BannerConditions = {
    publication_id?: number;
    product_id?: number;
    resource?: string;
    type: string;
  };

But publication_id and product_id can only exist if resource exists. Can I define it somehow?

Body:
You could use a union to describe the two type

type BannerConditions = {
    publication_id: number;
    product_id: number;
    resource: string;
    type: string;
  } | {
    publication_id: undefined;
    product_id: undefined;
    resource: undefined;
    type: string;
}

// foo would throw an error
const foo: BannerConditions = {
  publication_id: 1,
  product_id: 2,
  resource: undefined,
    type: 'x'
}
// no error for bar
const bar: BannerConditions = {
  publication_id: 1,
  product_id: 2,
  resource: 'test',
  type: 'x'
}

Playground example


问:
Swift 4 - Filtering Array with Array
I have a list of entries, that have an id, and I want to filter them down to ones that have an entry.id matching one of the ids in selectedIDs. Is there a way to do this with filter or do I have to use a for loop?

```<code>struct Entry {
    let id: String
}
var allEntries = [Entry]()
var selectedIDs = [String]
</code>```

e.g.

```<code>allEntries = [Entry(id: "1"), Entry(id:"2"), Entry(id:"3"), Entry(id:"4")]
selectedIDs = ["1", "3"]

// return selectedEntries
var selectedEntries = [Entry(id: "1"), Entry(id: "3")]
</code>```

答:
Swift 5.5:

```<code>let filteredArray = array.filter { self.selectedIDs.map(\.id).contains($0.id) }
</code>```

Title: Swift 4 - Filtering Array with Array

Body:
I have a list of entries, that have an id, and I want to filter them down to ones that have an entry.id matching one of the ids in selectedIDs. Is there a way to do this with filter or do I have to use a for loop?

struct Entry {
    let id: String
}
var allEntries = [Entry]()
var selectedIDs = [String]

e.g.

allEntries = [Entry(id: "1"), Entry(id:"2"), Entry(id:"3"), Entry(id:"4")]
selectedIDs = ["1", "3"]

// return selectedEntries
var selectedEntries = [Entry(id: "1"), Entry(id: "3")]

Body:
Swift 5.5:

let filteredArray = array.filter { self.selectedIDs.map(\.id).contains($0.id) }


问:
Inject default template argument type from user code
Is there a way to "inject" a default type for a template member function of a template class "after" the definition of said template member function?

Basically similar to this (which does not compile), so that I can specify NS::Default (the default type for Z) outside of the library in which template class S and its member function template are defined:

// In library
namespace NS {}

template<typename T>
struct S {
  template<typename X, typename Z = NS::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code
namespace NS {
  using Default = int;
}

S<SomeClass> s;
s.foo(3.14); // z == int(0)
```
<p>I think I once had code like this working with later specified type traits, but it's been a while and my template foo is a bit rusty.</p>
<p>Primary goal is to be able to call <code>S::foo</code> with just one argument and have it use a default argument with a default type, which is specified NOT by the library but rather the using code.</p>
<p>Injection of that type via the class templates is of course an option but NOT what I'm asking for. So I don't want to have to do:</p>
<pre class="lang-cpp prettyprint-override"><code>// library
template<typename T, typename ZDefault>
struct S {
  template<typename X, typename Z = ZDefault>
  void foo(X x, Z z = Z{}) {}
};

// User
S<SomeClass, int> s;
s.foo(3.14);
</code>```

答:
If you can expect your clients to be in full control of their types, you could design the lib so that the default type is part of the parameterized T type of the class template S:

```<code>// In library
/// @attention `T` shall have a public alias declaration name `Default`
template<typename T>
struct S {
  template<typename X, typename Z = typename T::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code

// Default config for all my types: let my type inherit from this class.
struct DefaultConfig {
   using Default = int;
};

struct SomeClass : DefaultConfig {};

int main() {
    S<SomeClass> s;
    s.foo(3.14); // z == int(0)
};
</code>```

Body:
Is there a way to "inject" a default type for a template member function of a template class "after" the definition of said template member function?

Basically similar to this (which does not compile), so that I can specify NS::Default (the default type for Z) outside of the library in which template class S and its member function template are defined:

// In library
namespace NS {}

template<typename T>
struct S {
  template<typename X, typename Z = NS::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code
namespace NS {
  using Default = int;
}

S<SomeClass> s;
s.foo(3.14); // z == int(0)

I think I once had code like this working with later specified type traits, but it's been a while and my template foo is a bit rusty.

Primary goal is to be able to call S::foo with just one argument and have it use a default argument with a default type, which is specified NOT by the library but rather the using code.

Injection of that type via the class templates is of course an option but NOT what I'm asking for. So I don't want to have to do:

// library
template<typename T, typename ZDefault>
struct S {
  template<typename X, typename Z = ZDefault>
  void foo(X x, Z z = Z{}) {}
};

// User
S<SomeClass, int> s;
s.foo(3.14);

Body:
If you can expect your clients to be in full control of their types, you could design the lib so that the default type is part of the parameterized T type of the class template S:

// In library
/// @attention `T` shall have a public alias declaration name `Default`
template<typename T>
struct S {
  template<typename X, typename Z = typename T::Default>
  void foo(X x, Z z = Z{}) {}
};

// In user code

// Default config for all my types: let my type inherit from this class.
struct DefaultConfig {
   using Default = int;
};

struct SomeClass : DefaultConfig {};

int main() {
    S<SomeClass> s;
    s.foo(3.14); // z == int(0)
};


问:
why previous code isn't executing if require's condition is false in solidity?
// Why previous code require isn't executing it's before require condition so it should execute why it's happening?</p>
```<code>pragma solidity ^0.8.0;

contract Req {
    uint public year = 2022;
    uint public age = 5;
    function changeAge() internal {
        age++;
    }
    function checkingN(uint _x) public {
        year++;
        changeAge();
        require(_x == 5, "You entered wrong number");
    }

}
</code>```

答:
That's a feature of the require() function. It stops and reverts the transaction when the condition is not met.

So effectively, the changeAge() is executed (and the sender pays gas fees for its execution) - but then it's reverted.

Body:
// Why previous code require isn't executing it's before require condition so it should execute why it's happening?

pragma solidity ^0.8.0;

contract Req {
    uint public year = 2022;
    uint public age = 5;
    function changeAge() internal {
        age++;
    }
    function checkingN(uint _x) public {
        year++;
        changeAge();
        require(_x == 5, "You entered wrong number");
    }

}


问:
Angular programmatically add ngbTooltip on event target doesn't work
I'm trying to add a tooltip on the clicked elements in my component view, which are mostly svg polygons and paths,
I have tried this function to set the ngbtooltip attribute on the target clicked elements,
but nothing is happening when I click an element and hover on it again, although the clicked element in my inspector appear to have the ngbtooltip attribute added

my View

```<code><div class="col py-2" #ngbTooltipp>
    <!-- poc only -->
    <svg-icon (click)="selectSector($event)" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>
  </div>
</code>```

my ts file

```<code> public selectSector($event: MouseEvent) {
    // set the tooltip
    let clickedEl = $event.target;
    this.renderer.setAttribute(clickedEl, "ngbtooltip", "hello");
  }
</code>```

答:
You can use it this way

```<code><button type="button" ngbTooltip="You see, I show up on click!" >
  Click me!
</button>

<div>
 <ng-containt ngbTooltip="You see, I show up on click!" > Click
   <svg-icon name="eye" [svgStyle]="{ 'width.px':90 }"></svg-icon>
 </ng-containt>
</div>
</code>```

https://stackblitz.com/edit/angular-funyr5?file=src%2Fapp%2Ftooltip-triggers.html

Body:
I'm trying to add a tooltip on the clicked elements in my component view, which are mostly svg polygons and paths,
I have tried this function to set the ngbtooltip attribute on the target clicked elements,
but nothing is happening when I click an element and hover on it again, although the clicked element in my inspector appear to have the ngbtooltip attribute added

my View

    <svg-icon (click)="selectSector($event)" [src]="mapPath" [svgStyle]="{ 'width.px':675}"></svg-icon>

my ts file

 public selectSector($event: MouseEvent) {
    // set the tooltip
    let clickedEl = $event.target;
    this.renderer.setAttribute(clickedEl, "ngbtooltip", "hello");
  }

Body:
You can use it this way

<button type="button" ngbTooltip="You see, I show up on click!" >
  Click me!
</button>

<div>
 <ng-containt ngbTooltip="You see, I show up on click!" > Click
   <svg-icon name="eye" [svgStyle]="{ 'width.px':90 }"></svg-icon>
 </ng-containt>
</div>

https://stackblitz.com/edit/angular-funyr5?file=src%2Fapp%2Ftooltip-triggers.html


问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
The Child::disp() method will never be called - c is a variable of type Base, and not a pointer or reference, so it won't check for virtual methods.

```<code>Base * c = new Child("1");
c->disp();
delete c;
</code>```

would call Child::disp().

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
The Child::disp() method will never be called - c is a variable of type Base, and not a pointer or reference, so it won't check for virtual methods.

Base * c = new Child("1");
c->disp();
delete c;

would call Child::disp().

OwnerDisplayName: Khoth


问:
How to check if current date is between two dates in javascript
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.</p>
```<code>const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];
</code>```

答:
You can get a new date and compare it against your stored dates (though you appear to have not stored the dates as correct date-timestamps). The item you are after is the one with a startDate less than current and end endDate greater than current. This will also give an empty array if no matches found - so you will need to have a check against the returned matches length.

const programs = [
    { video: "URL1", startDate: 1644492517146, endDate: 1644492517446 },
    { video: "URL2", startDate: 1644492517726, endDate: 1644492517646 },
    { video: "URL3", startDate: 1644492507746, endDate: 1644492517546 },
    { video: "URL4", startDate: 1644492517746, endDate: 16474492519746 }
];

const now =new Date().getTime(); // gives similar to 1644492517146

const currentProgram = programs.filter(
  p => new Date(p.startDate) < now && new Date(p.endDate) > now
);

console.log(currentProgram) // gives [{ video: "URL4", startDate: 1644492517746, endDate: 16474492519746 }]```

Body:
I'm trying to make a Livestream feature in my project, I have an array of programs (videos), every video has startDate and endDate. I should run every video when its time has come.

const programs = [
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 },
    { video: "URL", startDate: 1644405993, endDate: 1644406032 }
];