问:
How to specify Japanese encoding for a UILabel?
When I attempt to display a Japanese string in a UILabel on iOS, it gets displayed using Chinese encoding instead of Japanese.

The two encodings are nearly identical, except in a few specific cases.  For example, here is how the character 直 (Unicode U+76F4) is rendered in Chinese (top) vs. Japanese (bottom):

(see here for more examples)

The only time Japanese strings render correctly is when the user's system locale is ja-jp (Japan), but I'd like it to render as Japanese for all users.

Is there any way to force the Japanese encoding?  Android has TextView.TextLocale, but I don't see anything similar on iOS UILabel

(Same question for Android. I tagged this  Swift/Objective-C because, although I'm looking for a Xamarin.iOS solution, the API is almost the same)

答:
I found an extremely hacky solution that seems to work.  However, it seems absurd that there's no way to simply set the locale of a label, so if anyone finds something I missed, please post an answer.

The trick relies on the fact that the Hiragino font displays kanji using Japanese encoding rather than Chinese encoding by default.  However, the font looks like shit for English text, so I have to search every string in every label for Japanese substrings and manually change the font using NSMutableAttributedString. The font is also completely broken so I had to find another workaround to fix that.

```<code>[assembly: ExportRenderer(typeof(Label), typeof(RingotanLabelRenderer))]
namespace MyApp
{
    public class MyLabelRenderer : LabelRenderer
    {
        private readonly UIFont HIRAGINO_FONT = UIFont.FromName("HiraginoSans-W6", 1); // Size gets updated later

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            // BUGFIX: Chinese encoding is shown by default. Switch to Hiragino font, which correctly shows Japanese characters
            // Taken from https://stackoverflow.com/a/71045204/238419
            if (Control?.Text != null && e.PropertyName == "Text")
            {
                var kanjiRanges = GetJapaneseRanges(Control.Text).ToList();
                if (kanjiRanges.Count > 0)
                {
                    var font = HIRAGINO_FONT.WithSize((nfloat)Element.FontSize);
                    var attributedString = Control.AttributedText == null
                        ? new NSMutableAttributedString(Control.Text)
                        : new NSMutableAttributedString(Control.AttributedText);

                    // Search through string for all instances of Japanese characters and update the font
                    foreach (var (start, end) in kanjiRanges)
                    {
                        int length = end - start + 1;
                        var range = new NSRange(start, length);
                        attributedString.AddAttribute(UIStringAttributeKey.Font, font, range);

                        // Bugfix: Hiragino font is broken (https://stackoverflow.com/a/44397572/238419) so needs to be adjusted upwards
                        // jesus christ Apple
                        attributedString.AddAttribute(UIStringAttributeKey.BaselineOffset, (NSNumber)(Element.FontSize/10), range);
                    }

                    Control.AttributedText = attributedString;
                }
            }
        }

        // Returns all (start,end) ranges in the string which contain only Japanese strings
        private IEnumerable<(int,int)> GetJapaneseRanges(string str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (IsJapanese(str[i]))
                {
                    int start = i;
                    while (i < str.Length - 1 && KanjiHelper.IsJapanese(str[i]))
                    {
                        i++;
                    }
                    int end = i;
                    yield return (start, end);
                }
            }
        }

        private static bool IsJapanese(char character)
        {
            // An approximation. See https://github.com/caguiclajmg/WanaKanaSharp/blob/792f45a27d6e543d1b484d6825a9f22a803027fd/WanaKanaSharp/CharacterConstants.cs#L110-L118
            // for a more accurate version
            return character >= '\u3000' && character <= '\u9FFF'
                || character >= '\uFF00';
        }
    }
}
</code>```

Body:
I found an extremely hacky solution that seems to work.  However, it seems absurd that there's no way to simply set the locale of a label, so if anyone finds something I missed, please post an answer.

The trick relies on the fact that the Hiragino font displays kanji using Japanese encoding rather than Chinese encoding by default.  However, the font looks like shit for English text, so I have to search every string in every label for Japanese substrings and manually change the font using NSMutableAttributedString. The font is also completely broken so I had to find another workaround to fix that.

[assembly: ExportRenderer(typeof(Label), typeof(RingotanLabelRenderer))]
namespace MyApp
{
    public class MyLabelRenderer : LabelRenderer
    {
        private readonly UIFont HIRAGINO_FONT = UIFont.FromName("HiraginoSans-W6", 1); // Size gets updated later

        protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            base.OnElementPropertyChanged(sender, e);

            // BUGFIX: Chinese encoding is shown by default. Switch to Hiragino font, which correctly shows Japanese characters
            // Taken from https://stackoverflow.com/a/71045204/238419
            if (Control?.Text != null && e.PropertyName == "Text")
            {
                var kanjiRanges = GetJapaneseRanges(Control.Text).ToList();
                if (kanjiRanges.Count > 0)
                {
                    var font = HIRAGINO_FONT.WithSize((nfloat)Element.FontSize);
                    var attributedString = Control.AttributedText == null
                        ? new NSMutableAttributedString(Control.Text)
                        : new NSMutableAttributedString(Control.AttributedText);

                    // Search through string for all instances of Japanese characters and update the font
                    foreach (var (start, end) in kanjiRanges)
                    {
                        int length = end - start + 1;
                        var range = new NSRange(start, length);
                        attributedString.AddAttribute(UIStringAttributeKey.Font, font, range);

                        // Bugfix: Hiragino font is broken (https://stackoverflow.com/a/44397572/238419) so needs to be adjusted upwards
                        // jesus christ Apple
                        attributedString.AddAttribute(UIStringAttributeKey.BaselineOffset, (NSNumber)(Element.FontSize/10), range);
                    }

                    Control.AttributedText = attributedString;
                }
            }
        }

        // Returns all (start,end) ranges in the string which contain only Japanese strings
        private IEnumerable<(int,int)> GetJapaneseRanges(string str)
        {
            for (int i = 0; i < str.Length; i++)
            {
                if (IsJapanese(str[i]))
                {
                    int start = i;
                    while (i < str.Length - 1 && KanjiHelper.IsJapanese(str[i]))
                    {
                        i++;
                    }
                    int end = i;
                    yield return (start, end);
                }
            }
        }

        private static bool IsJapanese(char character)
        {
            // An approximation. See https://github.com/caguiclajmg/WanaKanaSharp/blob/792f45a27d6e543d1b484d6825a9f22a803027fd/WanaKanaSharp/CharacterConstants.cs#L110-L118
            // for a more accurate version
            return character >= '\u3000' && character <= '\u9FFF'
                || character >= '\uFF00';
        }
    }
}


来源: stackexchange

问:
How to filter a string list containing specific characters in python
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]
</code>```

Does anybody have an idea of how to do that?

Thank you in advance!

答:
You can use this way to solve the problem.

```<code>letters = ['R', 'E', 'T', 'O', 'P', 'A']
words_list = ["TOP", "CUT", "REPORT", "GOOD"]

final_list = [word for word in words_list if set(word).issubset(set(letters))]
print(final_list)
</code>```

In this code, we are checking each word in the words_list whether that word is made of letters in the letters_list. To do that we use the issubset method.

set(word).issubset(set(letters)) this part of code is return a boolean value. We include that word to final_list if and only if that boolean value is True.

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to write a program which filters a word list by letters. The aim is to get the words that contain any of the letters given without other letters. Im trying to do it with the all() function in a list comprehesion. That doest work as I expect, because it's just filtering the words containing this set of letters but no excluding the rest of the alphabet:

letters = ['R', 'E', 'T', 'O', 'P', 'A']

letters = ['R', 'E', 'T', 'O', 'P', 'A']

final_list = [word for word in dictionary if all(word for letter in letters if letter in word)]

Does anybody have an idea of how to do that?

Thank you in advance!

Body:
You can use this way to solve the problem.

letters = ['R', 'E', 'T', 'O', 'P', 'A']
words_list = ["TOP", "CUT", "REPORT", "GOOD"]

final_list = [word for word in words_list if set(word).issubset(set(letters))]
print(final_list)

In this code, we are checking each word in the words_list whether that word is made of letters in the letters_list. To do that we use the issubset method.

set(word).issubset(set(letters)) this part of code is return a boolean value. We include that word to final_list if and only if that boolean value is True.


问:
Is there a generic algorithm to put a list of sorted integers into buckets?
How do you filter integers 1-52 into 13 buckets? [1 to 4], [5 to 8], [9 to 12], etc. I want to know if given 2 random integers are they in the same bucket? I have tried

```<code>(X mod 4) - X]
</code>```

but get the wrong results below.

```<code>#first bucket
(1 mod 4) - 1 = 0
(2 mod 4) - 2 = 0
(3 mod 4) - 3 = 0
(4 mod 4) - 4 = -4 #wrong result

#2nd bucket
(5 mod 4) - 5 = -4
(6 mod 4) - 6 = -4
(7 mod 4) - 7 = -4
(8 mod 4) - 8 = -8 #wrong result
</code>```

Thank you for any guidance.

答:
As the numbers start with 1, subtract 1 first. And then you don't need to use the modulo operator. Instead use integer division, and you'll get a sequence number for a "bucket" (0..12):</p>
```<code>def bucketof(a):
    return (a - 1) // 4

print(bucketof(5) == bucketof(8))  # True
</code>```

Body:
How do you filter integers 1-52 into 13 buckets? [1 to 4], [5 to 8], [9 to 12], etc. I want to know if given 2 random integers are they in the same bucket? I have tried

(X mod 4) - X]

but get the wrong results below.

#first bucket
(1 mod 4) - 1 = 0
(2 mod 4) - 2 = 0
(3 mod 4) - 3 = 0
(4 mod 4) - 4 = -4 #wrong result

#2nd bucket
(5 mod 4) - 5 = -4
(6 mod 4) - 6 = -4
(7 mod 4) - 7 = -4
(8 mod 4) - 8 = -8 #wrong result

Thank you for any guidance.

Body:
As the numbers start with 1, subtract 1 first. And then you don't need to use the modulo operator. Instead use integer division, and you'll get a sequence number for a "bucket" (0..12):

def bucketof(a):
    return (a - 1) // 4

print(bucketof(5) == bucketof(8))  # True


问:
Sort french words with diacritics in bash
Similar to question How to sort words with accents?, I try to sort french words in a file on the shell, running MacOS Monterey with LANG=en_US.UTF-8, LC_ALL and LC_COLLATE not set.

```<code>$ echo $'Bénéficiaires\néboueur\nComptabilité' > sample.txt
$ LC_ALL=C sort -fd  sample.txt
Bénéficiaires
éboueur
Comptabilité
</code>```

So the sort treats "é" like an empty char. Any way to fix this?

If I try sorting without LC_ALL=C, I get:

```<code>$ sort -fd  sample.txt
sort: string comparison failed: Illegal byte sequence
sort: Set LC_ALL='C' to work around the problem.
sort: The strings compared were ‘\303BOUEUR’ and ‘COMPTABILIT\303’.
</code>```

答:
Bash has no control over how sort works internally.

You seem to be confused about your locales. LC_ALL=C specifically overrides the collation order to ignore your locale's sorting conventions.

```<code>tripleee$ LANG=fr_FR.UTF-8 sort -fd sample.txt
bâtiment débutant
bénéficiaires
bricomarché
comptabilité
contrôle
éboueur
économie
</code>```

The LANG environment variable is technically fine here, though perhaps you want to set LC_ALL=fr_FR.UTF-8 if that is your permanent locale.  If you only want to affect the collation order, perhaps temporarily, that's LC_COLLATE.

The warning about invalid glyphs sounds like your text isn't actually UTF-8, so perhaps the proper fix is to change that. (Hint: iconv; but you obviously have to know or guess which encoding to translate from. Maybe see the Stack Overflow character-encoding tag info page for details.)

```<code>tripleee$ iconv -f utf-8 -t iso-8859-1 sample.txt >broken.txt
tripleee$  diff -u <(xxd sample.txt) <(xxd broken.txt) | grep 00000020
-00000020: 0a62 c3a9 6ec3 a966 6963 6961 6972 6573  .b..n..ficiaires
+00000020: 6ee9 6669 6369 6169 7265 730a 636f 6d70  n.ficiaires.comp
</code>```

Body:
Similar to question How to sort words with accents?, I try to sort french words in a file on the shell, running MacOS Monterey with LANG=en_US.UTF-8, LC_ALL and LC_COLLATE not set.

$ echo $'Bénéficiaires\néboueur\nComptabilité' > sample.txt
$ LC_ALL=C sort -fd  sample.txt
Bénéficiaires
éboueur
Comptabilité

So the sort treats "é" like an empty char. Any way to fix this?

If I try sorting without LC_ALL=C, I get:

$ sort -fd  sample.txt
sort: string comparison failed: Illegal byte sequence
sort: Set LC_ALL='C' to work around the problem.
sort: The strings compared were ‘\303BOUEUR’ and ‘COMPTABILIT\303’.

Body:
Bash has no control over how sort works internally.

You seem to be confused about your locales. LC_ALL=C specifically overrides the collation order to ignore your locale's sorting conventions.

tripleee$ LANG=fr_FR.UTF-8 sort -fd sample.txt
bâtiment débutant
bénéficiaires
bricomarché
comptabilité
contrôle
éboueur
économie

The LANG environment variable is technically fine here, though perhaps you want to set LC_ALL=fr_FR.UTF-8 if that is your permanent locale.  If you only want to affect the collation order, perhaps temporarily, that's LC_COLLATE.

The warning about invalid glyphs sounds like your text isn't actually UTF-8, so perhaps the proper fix is to change that. (Hint: iconv; but you obviously have to know or guess which encoding to translate from. Maybe see the Stack Overflow character-encoding tag info page for details.)

tripleee$ iconv -f utf-8 -t iso-8859-1 sample.txt >broken.txt
tripleee$  diff -u <(xxd sample.txt) <(xxd broken.txt) | grep 00000020
-00000020: 0a62 c3a9 6ec3 a966 6963 6961 6972 6573  .b..n..ficiaires
+00000020: 6ee9 6669 6369 6169 7265 730a 636f 6d70  n.ficiaires.comp


问:
VS Code does not change python environment
I am using VS-Code and anaconda environment for python interpreter. I select the exact anaconda base environment by ctrl + shift + ` and it also reflects in the downside panel of vscode. But, when I checked the python version it shows my system's default python environment 3.7.9. If you see the below screenshot than, the anaconda environment is with 3.8.3.

Please give me solution, Thank you.

答: after changing the environment, you  can restart the vs code again. it might be changed now. if not, then try changing now againg by clicking the interpreter name which is displayed on left bottom of the vscode window</p>


问:
when i run composer require laravel/ui this command
[Composer\Downloader\TransportException]
Unable to use a proxy: malformed http_proxy url

require [--dev] [--dry-run] [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--fixed] [--no-suggest] [--no-progress] [--no-update] [--no-install] [--update-no-dev] [-w|--update-with-dependencies] [-W|--update-with-all-dependencies] [--with-dependencies] [--with-all-dependencies] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--prefer-stable] [--prefer-lowest] [--sort-packages] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--] []...

答:
You can try by deleting http_proxy to navigate this path: Control Panel -> System -> Advanced system settings -> Environment Veriables -> http_proxy.
Then run the command again.

Or You can keep http_proxy as it is and navigate to your project directory(copy the directory path) and past the path over cmd then execute the command again.

Hope that both step will work.


问:
jquery.min.js not loading is the error I am getting after I am using the Google cdn in jQuery
I am just learning and checking if jQuery is working but I am unable to get the changes as it is showing unable to load I am using Google cdn and yes I have the script of it above my local js file

Javascript

```<code> $("h1").css("color", "red");
</code>```

HTML:

```<code><!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery</title>
    <link rel="stylesheet" href="styles.css">
</head>

<body>
    <h1>Hello</h1>
    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>
    <script src="https://ajaxgoogleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <script src="index.js"></script>
</body>

</html>
</code>```

答:
It is ajax.googleapis.com not ajaxgoogleapis
https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js</p>

Body:
I am just learning and checking if jQuery is working but I am unable to get the changes as it is showing unable to load I am using Google cdn and yes I have the script of it above my local js file

Javascript

 $("h1").css("color", "red");

HTML:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery</title>
    <link rel="stylesheet" href="styles.css">

Hello

    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>
    <button>Click me</button>


问:
scrape live scores from oddsportal live odds page using requests
I want to scrape inplay odds and scores.
I succeed to get live odds data using the below code, but without finding live scores:

```<code>import requests, re, time
from bs4 import BeautifulSoup

url = f"https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}"
headers = {'User-Agent': 'curl/7.64.0','Referer': 'https://www.oddsportal.com/inplay-odds/live-now/soccer/'}
r = requests.get(url, headers=headers)

live_html = re.findall(r'<table class=.*table>', r.text)[0].replace("\\","")
soup = BeautifulSoup(live_html, 'html.parser')

</code>```

I tried to search from from Developper Tools > Sources > Page, but can't find any source that provide live scores

答:
Use python's websocket-client-package to retrieve the LIVE data.

First, you need to copy your web browser’s header to here and use json.dumps to convert it into the string format.
Additionally, you have to do a handshake i.e., sending messages to the website and receiving messages when connecting to the websocket.

After that, create the connection to the server by using create_connection. Then, perform the handshake by sending the message, and you will be able to see the data on your side.

Body:
I want to scrape inplay odds and scores.
I succeed to get live odds data using the below code, but without finding live scores:

import requests, re, time
from bs4 import BeautifulSoup

url = f"https://fb.oddsportal.com/feed/livegames/live/1/0.dat?_{int(time.time() * 1000)}"
headers = {'User-Agent': 'curl/7.64.0','Referer': 'https://www.oddsportal.com/inplay-odds/live-now/soccer/'}
r = requests.get(url, headers=headers)

live_html = re.findall(r'
', r.text)[0].replace("\\","")
soup = BeautifulSoup(live_html, 'html.parser')

I tried to search from from Developper Tools > Sources > Page, but can't find any source that provide live scores


问:
Why do I get multiple active Tokens for my Device with Googles Cloud To Device Messaging Service?
I just added C2DM capability to my Android App.

At the moment the following happens if C2DM is started in my App.

My App sends the registration Intent

The answer broadcast is received by my app

The device token is retrieved from the intent and sent to my server

From that moment everything is working fine. The client receives the push notifications etc.
A problem occurs if the following hapens:

The user uninstalls the application without disabling push. (Completely deleting it not only updating)

The user reinstalls the application

If after step 5 a push notification is sent my app still receives this notification.
It seems that the token which was retrieved from the previous install is still active and is reconnected to the new instance of my application.

This leeds to the following problem:

A user who reinstalls my app but has no intention of receiving push notifications has no possibility to remove himself from the service because the new instance of the app has no way to unregister the old token from my server.

Is this a bug in the C2DM system or is something wrong in my setup?

Update

I followed Berdons advice and did the following:

For testing purposes only start an unregister Intent every time my app starts up.
After I send the unregister intent no push notification from my server is sent to my application. That seems to do the trick, but if I now go the C2DM Settings Screen and turn on push notifications for my app all the old tokens get active again and I receive information that I did not register for in the current installation of my app.

Next Update

It seems I'm not the only one with this problem:

Android C2DM : Duplicate message to the same device and App

I hoped that Google would manage those tokens in a way that old tokens from the same device get disabled after a new one was issued. I also expect that after I sent an unregister Intent all tokens for that application and that device are marked as invalid or deleted from the Google Server for ever. If this is somehow a design decision by Google for special use cases I don't see please enlighten me.

答:
We now found a solution that should work in most of the cases.

The server adds the C2DM registration id as a data field with every C2D Message.

The device now only shows a notification if the token in the message and the token that is stored in a pref file match. That way we guarantee that we don't show messages for device tokens that were obtained by previous installs.

If the tokens do not match we found an old token that should not be active anymore. We now mark the token on our own web server as inactive to prevent the server from sending more unnecessary C2D Messages

This solution enables us to show only relevant data without the need to store a unique user id.

ContentLicense: CC BY-SA 3.0


问:
How do I use Assert.Throws to assert the type of the exception?
How do I use Assert.Throws to assert the type of the exception and the actual message wording?

Something like this:

```<code>Assert.Throws<Exception>(
    ()=>user.MakeUserActive()).WithMessage("Actual exception message")
</code>```

The method I am testing throws multiple messages of the same type, with different messages, and I need a way to test that the correct message is thrown depending on the context.

答:
Asserting exception :

In Junit 5 :

```<code>    @Test
    public void whenExceptionThrown_thenAssertionSucceeds() {
        Exception exception = assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("1a");
        });

        String expectedMessage = "For input string";
        String actualMessage = exception.getMessage();

        assertTrue(actualMessage.contains(expectedMessage));
    }
</code>```

In Junit 4:

```<code>@Test(expected = NullPointerException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
    String test = null;
    test.length();
}
</code>```

Body:
How do I use Assert.Throws to assert the type of the exception and the actual message wording?

Something like this:

Assert.Throws<Exception>(
    ()=>user.MakeUserActive()).WithMessage("Actual exception message")

The method I am testing throws multiple messages of the same type, with different messages, and I need a way to test that the correct message is thrown depending on the context.

Body:
Asserting exception :

In Junit 5 :

    @Test
    public void whenExceptionThrown_thenAssertionSucceeds() {
        Exception exception = assertThrows(NumberFormatException.class, () -> {
            Integer.parseInt("1a");
        });

        String expectedMessage = "For input string";
        String actualMessage = exception.getMessage();

        assertTrue(actualMessage.contains(expectedMessage));
    }

In Junit 4:

@Test(expected = NullPointerException.class)
public void whenExceptionThrown_thenExpectationSatisfied() {
    String test = null;
    test.length();
}


问:
How can i convert a file .png to a Bitmap? Nothing works for me. Error "'Failed to decode image. The provided image must be a Bitmap.'" Xamarin.forms
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

```<code>Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen
</code>```

EDIT 2 This is my method to show the pins in google maps

```<code>private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }
</code>```

This is the class Pin where i save the image

```<code>public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }
</code>```

this is the icon .png i want to show in googlemaps

Pin Blue Image

答:
i have 5 types of pins (pins are the image .png) when i put the pins
in format .png

if you want to custom the pins in your map, you can simply use Custom Renderers to achieve this.

The icon used to represent a marker can be customized by calling the MarkerOptions.SetIcon method. This can be accomplished by overriding the CreateMarker method, which is invoked for each Pin that's added to the map:

```<code>protected override MarkerOptions CreateMarker(Pin pin)
{
    var marker = new MarkerOptions();
    marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
    marker.SetTitle(pin.Label);
    marker.SetSnippet(pin.Address);
    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
    return marker;
}
</code>```

If you want to display different icons, you can  refer to the following code:

```<code>protected override MarkerOptions CreateMarker(Pin pin)
    {
        var marker = new MarkerOptions();
        marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
        marker.SetTitle(pin.Label);
        marker.SetSnippet(pin.Address);
        var customPin = (Element as CustomMap).CustomPins.FirstOrDefault(p => p.Position == pin.Position);
        if (customPin != null)
        {
            if (customPin.IconType == "corporate")
            {
                marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.corporate));
            }
            else if (customPin.IconType == "pickup")
            {
                marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.bus));
            }
        }

        return marker;
    }
</code>```

For more, check:Customizing the Marker.

Body:
I'm working with Xamarin in the part of  Xamarin.Forms  i need to convert a file ("image.png") to a Bitmap because when project run its enter in "break mode" and show me this message "Java.Lang.IllegalArgumentException: 'Failed to decode image. The provided image must be a Bitmap.'". So i tried to convert the file in many ways like:

1_ Using methods from System.Drawing.Bitmap but it's show this exception "This operation is not supported in this platform"

2_ Cannot use Android.Graphics because i'm working in xamarin.forms not in xamarin.android.

3_ I tried to convert the "image.png" into a base64 or byte[] array and then into a bitmap but the problem is the same like in first problem because to convert from byte[] array or base64 to a Bitmap i have use methods from System.Drawing.Bitmap.

4_ I tried using the library SkiaSharp but i don't have success because i don't found so much information  about how to convert .png to SKBitmap and then convert SKBitmap to Bitmap (even i don't know if this is possible).

5_ Finally i converted "image.png" to a "image.bmp" with an app and use the file .bmp in my project but it doesn't work too.

the "image.png" i have to save in a string variable, well that's the idea.

If you have a solution with SkiaSharp o whatever i will glad

EDIT

here is a part of my code, i just save in a variable the image

Icon = "pin_blue.png";
//i can't use a path because in xamarin you have many size from the same
//image for the different size of the screen

EDIT 2 This is my method to show the pins in google maps

private void ShowPins(List<PointsOfInterest> resultPointsOfInterest)
        {
            if (resultPointsOfInterest != null && resultPointsOfInterest.Any())
            {
                var location = Geolocation.GetLastKnownLocationAsync();
                PointsOfInterest position = new PointsOfInterest();
                if (location != null)
                {
                    position.ccsm0166latitud = location.Result.Latitude;
                   position.ccsm0166longitud = location.Result.Longitude;

            }
            else {
                position = resultPointsOfInterest.First();
            }
            //Distance = Distance.FromKilometers(new Random().Next(23,35));
            Distance = Distance.FromKilometers(3);
            Position = new Position(position.ccsm0166latitud, position.ccsm0166longitud);
            PinsFiltered= Pins = new List<PinCustom>(resultPointsOfInterest.Select(
                x => new PinCustom()
                {
                    Position =
                        new Position(x.ccsm0166latitud, x.ccsm0166longitud),
                    Address = x.ccsm0166direccion,
                    Label = x.ccsm0166nombre,
                    Type = PinType.Place,
                    TypePointOfInterest = x.ccsm0166tipositio,
                    IconBM = Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ?  PinCustom.ConvertToBitmap("pin_blue.png") :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branch ? "pin_blue.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours2 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.branchWithExtendedHours3 ? "pin_black.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.selfServiceTerminal ? "pin_green.png" :
                        Int32.Parse(x.ccsm0166tipositio) == (int)PointOfInterestType.atmServBox ? "pin_yellow.png" : string.Empty
                }).ToList());
        }
        else
        {
            Pins = new List<PinCustom>();
        }
    }

This is the class Pin where i save the image

public class PinCustom : Pin
    {
        public string TypePointOfInterest { get; set; }
        public string Icon { get; set; }
        public Bitmap { get; set; }
        //Here  i create this variable to save a bitmap but i don't know if i do the things well
    }

this is the icon .png i want to show in googlemaps

Pin Blue Image

Body:
i have 5 types of pins (pins are the image .png) when i put the pins
in format .png

if you want to custom the pins in your map, you can simply use Custom Renderers to achieve this.

The icon used to represent a marker can be customized by calling the MarkerOptions.SetIcon method. This can be accomplished by overriding the CreateMarker method, which is invoked for each Pin that's added to the map:

protected override MarkerOptions CreateMarker(Pin pin)
{
    var marker = new MarkerOptions();
    marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
    marker.SetTitle(pin.Label);
    marker.SetSnippet(pin.Address);
    marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.pin));
    return marker;
}

If you want to display different icons, you can  refer to the following code:

protected override MarkerOptions CreateMarker(Pin pin)
    {
        var marker = new MarkerOptions();
        marker.SetPosition(new LatLng(pin.Position.Latitude, pin.Position.Longitude));
        marker.SetTitle(pin.Label);
        marker.SetSnippet(pin.Address);
        var customPin = (Element as CustomMap).CustomPins.FirstOrDefault(p => p.Position == pin.Position);
        if (customPin != null)
        {
            if (customPin.IconType == "corporate")
            {
                marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.corporate));
            }
            else if (customPin.IconType == "pickup")
            {
                marker.SetIcon(BitmapDescriptorFactory.FromResource(Resource.Drawable.bus));
            }
        }

        return marker;
    }

For more, check:Customizing the Marker.


问:
How do i declare good routes in angular?
Im using angular and wanted to try lazy loading with multiples modules,  and i getting this error Error: Cannot match any routes. URL Segment: 'home/users/profile'

So well i been like a few long hours trying to solve this problem but i foundno answer

APP MODULE

```<code>{
    path: 'home',
    component: HomeComponent,
    loadChildren: () =>
      import('./components/home/home.module').then((m) => m.HomeModule),
  },
  {
    path: 'auth',
    loadChildren: () =>
      import('./components/auth/auth.module').then((m) => m.AuthModule),
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'home',
  },
</code>```

HOME ROUTING MODULE

```<code> {
    path: 'users',
    loadChildren: () =>
      import('../users/users.module').then((m) => m.UsersModule),
  },
</code>```

USERS ROUTING MODULE

```<code> {
    path: '',
    outlet: 'child',
    component: UsersComponent,
  },
  {
    path: 'user/:id',
    outlet: 'child',
    component: UserComponent,
  },
  {
    path: 'profile',
    outlet: 'child',
    component: ProfileComponent,
  },
</code>```

Here is the repo if you need to see something else https://github.com/ginebras/user-system

答:
I don't see any need for using named outlets, you are complicating things for yourself. Let's keep it simple, So I removed 'child' from your <router-outlet> as well as removed outlet: child from your routes.

I updated your User's Routing in user-routing.module, It should look like this:

  RouterModule.forChild([
      {
        path: '',
        component: UsersComponent,
        pathMatch: 'full',
      },
      { path: 'profile', component: ProfileComponent },
      {
        path: 'user-detail/:id',
        component: UserComponent,
      },
    ]),
  ],
```

I also changed the user:/id path to user-detail:id for readability. You can change it back or you change from where you are opening user:/id to user-detail:id.

I update the stackblitz too, have a look: https://stackblitz.com/edit/angular-ivy-rmxi8g?

Body:
Im using angular and wanted to try lazy loading with multiples modules,  and i getting this error Error: Cannot match any routes. URL Segment: 'home/users/profile'

So well i been like a few long hours trying to solve this problem but i foundno answer

APP MODULE

{
    path: 'home',
    component: HomeComponent,
    loadChildren: () =>
      import('./components/home/home.module').then((m) => m.HomeModule),
  },
  {
    path: 'auth',
    loadChildren: () =>
      import('./components/auth/auth.module').then((m) => m.AuthModule),
  },
  {
    path: '',
    pathMatch: 'full',
    redirectTo: 'home',
  },

HOME ROUTING MODULE

 {
    path: 'users',
    loadChildren: () =>
      import('../users/users.module').then((m) => m.UsersModule),
  },

USERS ROUTING MODULE

 {
    path: '',
    outlet: 'child',
    component: UsersComponent,
  },
  {
    path: 'user/:id',
    outlet: 'child',
    component: UserComponent,
  },
  {
    path: 'profile',
    outlet: 'child',
    component: ProfileComponent,
  },

Here is the repo if you need to see something else https://github.com/ginebras/user-system

Body:
I don't see any need for using named outlets, you are complicating things for yourself. Let's keep it simple, So I removed 'child' from your <router-outlet> as well as removed outlet: child from your routes.

I updated your User's Routing in user-routing.module, It should look like this:

  RouterModule.forChild([
      {
        path: '',
        component: UsersComponent,
        pathMatch: 'full',
      },
      { path: 'profile', component: ProfileComponent },
      {
        path: 'user-detail/:id',
        component: UserComponent,
      },
    ]),
  ],

I also changed the user:/id path to user-detail:id for readability. You can change it back or you change from where you are opening user:/id to user-detail:id.

I update the stackblitz too, have a look: https://stackblitz.com/edit/angular-ivy-rmxi8g?


问:
Cannot horizontally center elements in CSS Grid

I have a CSS Grid like this, and I want to be able to center the child elements horizontally. For example, in this pic, I want to see "Queen" come in the center and not at the left side.

Trying with align-items: center and justify-content: center does not work. What do I do?

This is my CSS (scss) for the grid (parent):

```<code>display: grid;
gap: 1rem 0;
grid-template-columns: 1fr;

--node-min-width: 235px;

@media (min-width: 576px){
   grid-template-columns: repeat(auto-fit, minmax(var(--node-min-width), 1fr));
}
</code>```

答:
with a flex container you can play with flex property on item to manipulate their size

here is the minimal code to have a similar situation working

.element {
  background:darkgrey;
  color:white;
  text-align:center;
  margin-top: 12px;
  flex:0 0 25%;
}

.grid {
  display: flex;
  flex-wrap: wrap;
  justify-content:center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div class="element">rook</div>
  <div class="element">bishop</div>
  <div class="element">knight</div>
  <div class="element">king</div>
  <div class="element">queen</div>
</div></code>```

Body:
I have a CSS Grid like this, and I want to be able to center the child elements horizontally. For example, in this pic, I want to see "Queen" come in the center and not at the left side.

Trying with align-items: center and justify-content: center does not work. What do I do?

This is my CSS (scss) for the grid (parent):

display: grid;
gap: 1rem 0;
grid-template-columns: 1fr;

--node-min-width: 235px;

@media (min-width: 576px){
   grid-template-columns: repeat(auto-fit, minmax(var(--node-min-width), 1fr));
}

Body:
with a flex container you can play with flex property on item to manipulate their size

here is the minimal code to have a similar situation working

.element {
  background:darkgrey;
  color:white;
  text-align:center;
  margin-top: 12px;
  flex:0 0 25%;
}

.grid {
  display: flex;
  flex-wrap: wrap;
  justify-content:center;
}

<div class="grid">
  <div class="element">rook</div>
  <div class="element">bishop</div>
  <div class="element">knight</div>
  <div class="element">king</div>
  <div class="element">queen</div>
</div>


问:
How do you make a Serde struct work with both borrowed and owned data?
I want to make a Serde struct that is capable of being deserialized from either borrowed data (serde_json::from_str) or owned data (serde_json::from_reader).  I have read Understanding deserializer lifetimes, and I understand the difference between the two trait bounds (<'de, T> where T: Deserialize<'de> and <T> where T: DeserializeOwned); what I want is a struct that implements both trait bounds, such that it can be used from either deserialization function.

The following code (playground) refuses to compile:

use serde_json; // 1.0.56
use serde; // 1.0.114
use std::fs;
use std::io;
use std::borrow::Cow;

#[derive(serde::Deserialize)]
struct Resource<'s> {
    // The Cow should allow for either borrowed or owned data
    #[serde(borrow)]
    pub foo: Cow<'s, str>,
}

fn main() {
    {
        // Works as expected when referencing a string...
        let s = "{\"foo\":\"bar\"}";
        let resource: Resource = serde_json::from_str(s).unwrap();
    }
    {
        // ...but refuses to compile when reading from a file
        let file = fs::File::open("dummy.json").unwrap();
        let reader = io::BufReader::new(file);
        let resource: Resource = serde_json::from_reader(reader).unwrap();
    }
}
```

How do I make this struct work with both owned and borrowed data?  Is there a way to do something like #[serde(borrow_optional)]?

答:
(playground link)

It's not possible with the constraints on serde_json::from_reader. However, it is possible if you construct Deserializer yourself:

        // ...but refuses to compile when reading from a file
        let file = fs::File::open("dummy.json").unwrap();
        let reader = io::BufReader::new(file);
        let mut deser = serde_json::Deserializer::from_reader(reader);
        let resource = Resource::deserialize(&mut deser).unwrap();
```

Body:
I want to make a Serde struct that is capable of being deserialized from either borrowed data (serde_json::from_str) or owned data (serde_json::from_reader).  I have read Understanding deserializer lifetimes, and I understand the difference between the two trait bounds (<'de, T> where T: Deserialize<'de> and <T> where T: DeserializeOwned); what I want is a struct that implements both trait bounds, such that it can be used from either deserialization function.

The following code (playground) refuses to compile:

use serde_json; // 1.0.56
use serde; // 1.0.114
use std::fs;
use std::io;
use std::borrow::Cow;

#[derive(serde::Deserialize)]
struct Resource<'s> {
    // The Cow should allow for either borrowed or owned data
    #[serde(borrow)]
    pub foo: Cow<'s, str>,
}

fn main() {
    {
        // Works as expected when referencing a string...
        let s = "{\"foo\":\"bar\"}";
        let resource: Resource = serde_json::from_str(s).unwrap();
    }
    {
        // ...but refuses to compile when reading from a file
        let file = fs::File::open("dummy.json").unwrap();
        let reader = io::BufReader::new(file);
        let resource: Resource = serde_json::from_reader(reader).unwrap();
    }
}

How do I make this struct work with both owned and borrowed data?  Is there a way to do something like #[serde(borrow_optional)]?


问:
How to test my linq repository calls
I have the following UserRepository:

```<code>public class UserRepository : Repository<Entities.User> {

public Entities.IUser Find(string domain, string username, string password) {
            return (from u in FindAll()
                    where u.Account.SubDomain == domain && u.EmailAddress == username && u.PasswordHash == password
                    && !u.IsArchived
                    select u).FirstOrDefault();
        }
}
</code>```

The "FindAll" method is part of Repository and basically just calls context.GetTable().AsQueryable()

I want to be able to write a test that will call this repository method but instead of accessing the database use some in-memory store.

I have done lots of searching and everything I seem to come across talks about mocking the repository out and returning a List (usually created at the start of the unit test) instead but what I don't understand is what use is that. I want to make sure that the linq query I have written is actually filtering the objects correctly and retrieving only the required records.
As the DataContext doesn't have an interface I can't simply mock that out.

The only other way I can see handling this is to actually talk to the db but I know this isn't the point of unit testing.

My question is how have others handled this?

答: Thanks to @Daniel Higarths last comment above where he mentioned Moles this helped me to solve the issue along with the following video http://dimecasts.net/Content/WatchEpisode/170</p>

Title: How to test my linq repository calls

Body:
I have the following UserRepository:

public class UserRepository : Repository<Entities.User> {

public Entities.IUser Find(string domain, string username, string password) {
            return (from u in FindAll()
                    where u.Account.SubDomain == domain && u.EmailAddress == username && u.PasswordHash == password
                    && !u.IsArchived
                    select u).FirstOrDefault();
        }
}

The "FindAll" method is part of Repository and basically just calls context.GetTable().AsQueryable()

I want to be able to write a test that will call this repository method but instead of accessing the database use some in-memory store.

I have done lots of searching and everything I seem to come across talks about mocking the repository out and returning a List (usually created at the start of the unit test) instead but what I don't understand is what use is that. I want to make sure that the linq query I have written is actually filtering the objects correctly and retrieving only the required records.
As the DataContext doesn't have an interface I can't simply mock that out.

The only other way I can see handling this is to actually talk to the db but I know this isn't the point of unit testing.

My question is how have others handled this?


问:
C++ Fizz Buzz alternative version
I'm relatively new to stack overflow (yes, i'm extremely new to coding), and i'm currently working on an altered version of the Fizz Buzz Question. Could someone help me figure out as to what i'm doing wrong? I can't seem to find the answer on Stack Overflow.
Use a while loop instead of for loop to write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Output:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

My code is

```<code>   #include <iostream>
using namespace std;
int n = 0;
{
       cout << "Enter your number ";      // Prompt for input
       cin >> n;                          // Get the input.
       for (int i = 1; i <= n; i++)
       {
               if ((i % 15) == 0)
                       cout << "FizzBuzz\n";
               else if ((i % 3) == 0)
                       cout << "Fizz\n";
               else if ((i % 5) == 0)
                       cout << "Buzz\n";
               else
                       cout << i << "\n";
       }
       return 0;
}
</code>```

While I am receiving the error  for line 4:

```<code>4:1: error: expected ',' or ';' before '{' token
</code>```

答:
#include

using namespace std;

int main(){

int num{0};

cout<< "enter number" << "\n" ;

cin>>num;

for(int i = 1; i <= num; i++){

```<code>if(i % 3 == 0 && i % 5 == 0){

    cout<< "FizzBuzz" << "\n" ;
}

else if (i % 3 == 0 ){

    cout<< "Fizz" << "\n" ;

}

else if (i % 5 == 0){

    cout<< "Buzz" << "\n";

}

else

    cout<< i << "\n";
</code>```

}
}

Title: C++ Fizz Buzz alternative version

Body:
I'm relatively new to stack overflow (yes, i'm extremely new to coding), and i'm currently working on an altered version of the Fizz Buzz Question. Could someone help me figure out as to what i'm doing wrong? I can't seem to find the answer on Stack Overflow.
Use a while loop instead of for loop to write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

Example:

n = 15,

Output:

1

2

Fizz

4

Buzz

Fizz

7

8

Fizz

Buzz

11

Fizz

13

14

FizzBuzz

My code is

   #include <iostream>
using namespace std;
int n = 0;
{
       cout << "Enter your number ";      // Prompt for input
       cin >> n;                          // Get the input.
       for (int i = 1; i <= n; i++)
       {
               if ((i % 15) == 0)
                       cout << "FizzBuzz\n";
               else if ((i % 3) == 0)
                       cout << "Fizz\n";
               else if ((i % 5) == 0)
                       cout << "Buzz\n";
               else
                       cout << i << "\n";
       }
       return 0;
}

While I am receiving the error  for line 4:

4:1: error: expected ',' or ';' before '{' token

Body:
#include

using namespace std;

int main(){

int num{0};

cout<< "enter number" << "\n" ;

cin>>num;

for(int i = 1; i <= num; i++){

if(i % 3 == 0 && i % 5 == 0){

    cout<< "FizzBuzz" << "\n" ;
}

else if (i % 3 == 0 ){

    cout<< "Fizz" << "\n" ;

}

else if (i % 5 == 0){

    cout<< "Buzz" << "\n";

}

else

    cout<< i << "\n";

}
}


问:
Save list of object in hive flutter
I want to save List of objects in flutter hive. Is there any way to implement it. I create a model class for notes. That has fields as note title and description. I want to save List in hive flutter with DateTime.now() as Key. Is there any way to implement it?

```<code>class NotedBox {
  static Box<List<NotesModel>> getNotedBox() {
    return Hive.box<List<NotesModel>>("Notes");
  }
}
</code>```

this is my box that I'm opening in the main.dart.

```<code>   Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      Directory appDocDir = await getApplicationDocumentsDirectory();
      Prefrences.init();
      await Hive.initFlutter(appDocDir.path);
      Hive.registerAdapter(NotesModelAdapter());
      await Hive.openBox<List<NotesModel>>("Notes");
      runApp(MyApp());
    }
</code>```

Here is the Adapter File

```<code>class NotesModelAdapter extends TypeAdapter<NotesModel> {
  @override
  final int typeId = 1;

  @override
  TimeBlockModel read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return NotesModel(
      title: fields[0] as String,
      description: fields[1] as String,
    );
  }

  @override
  void write(BinaryWriter writer, NotesModel obj) {
    writer
      ..writeByte(4)
      ..writeByte(0)
      ..write(obj.title)
      ..writeByte(1)
      ..write(obj.description);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is TimeBlockModelAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}
</code>```

Here is the error I'm encountering.

```<code> Unhandled Exception: HiveError: Cannot write, unknown type: String. Did you forget to register an adapter?
</code>```

Note: This is the second time I'm using the hive in the same app. The first hive box is working fine but at that time I wasn't saving List.

答:
maybe you did not register your adapter in the main method.

Hive.registerAdapter(MyObjectAdapter());

hive

Title: Save list of object in hive flutter

Body:
I want to save List of objects in flutter hive. Is there any way to implement it. I create a model class for notes. That has fields as note title and description. I want to save List in hive flutter with DateTime.now() as Key. Is there any way to implement it?

class NotedBox {
  static Box<List<NotesModel>> getNotedBox() {
    return Hive.box<List<NotesModel>>("Notes");
  }
}

this is my box that I'm opening in the main.dart.

   Future<void> main() async {
      WidgetsFlutterBinding.ensureInitialized();
      Directory appDocDir = await getApplicationDocumentsDirectory();
      Prefrences.init();
      await Hive.initFlutter(appDocDir.path);
      Hive.registerAdapter(NotesModelAdapter());
      await Hive.openBox<List<NotesModel>>("Notes");
      runApp(MyApp());
    }

Here is the Adapter File

class NotesModelAdapter extends TypeAdapter<NotesModel> {
  @override
  final int typeId = 1;

  @override
  TimeBlockModel read(BinaryReader reader) {
    final numOfFields = reader.readByte();
    final fields = <int, dynamic>{
      for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
    };
    return NotesModel(
      title: fields[0] as String,
      description: fields[1] as String,
    );
  }

  @override
  void write(BinaryWriter writer, NotesModel obj) {
    writer
      ..writeByte(4)
      ..writeByte(0)
      ..write(obj.title)
      ..writeByte(1)
      ..write(obj.description);
  }

  @override
  int get hashCode => typeId.hashCode;

  @override
  bool operator ==(Object other) =>
      identical(this, other) ||
      other is TimeBlockModelAdapter &&
          runtimeType == other.runtimeType &&
          typeId == other.typeId;
}

Here is the error I'm encountering.

 Unhandled Exception: HiveError: Cannot write, unknown type: String. Did you forget to register an adapter?

Note: This is the second time I'm using the hive in the same app. The first hive box is working fine but at that time I wasn't saving List.


问:
How we can Integrate HMS Kit in Android Studio Bumblebee (2021.1.1) Patch 1)?
Android Studio Bumblebee (2021.1.1) Patch 1) released on February 4, 2022</p>

答:
Here I am going to discuss you about HMS Kit Integration in Android Studio new version Bumblebee (2021.1.1) Patch 1)  which is released on February 4, 2022. There are some changes in project level build.gradle file and settings.gradle. So I am sharing a temporary solution to integrate HMS Kits here.

1) In root build.gradle

There are some changes in root level build.gradle file in new version.

buildscript removed here in new version,  where we add Add the AppGallery Connect plugin.

So to integrate HMS Kits  add buildscript as given

Note : No need to configure the Maven repository address in root level build.gradle

2) settings.gradle

Few changes are there in settings.gradle. We can find pluginManagement and dependencyResolutionManagement there. Add maven url in both sections as mentioned in below image.

3) App level build.gradle

No other changes in App level build.gradle file. You can add a build dependency in the dependencies block and can add the AppGallery Connect plugin configuration.

That's it.

I know it is a temporary solution, but you can use it till we get a permanent solution.

Thank you.


问:
Local [Polkadot + Statemine] testnet with polkadot-launch
I want to deploy a local Polkadot Testnet via polkadot-launch.

I built the executables from:

polkadot: v0.9.9-1

cumulus: statemine_v3

This is the config.json:

```<code>{
    "relaychain": {
        "bin": "./bin/polkadot",
        "chain": "rococo-local",
        "nodes": [
            {
                "name": "alice",
                "wsPort": 9944,
                "port": 30444
            },
            {
                "name": "bob",
                "wsPort": 9955,
                "port": 30555
            },
            {
                "name": "charlie",
                "wsPort": 9966,
                "port": 30666
            },
            {
                "name": "dave",
                "wsPort": 9977,
                "port": 30777
            }
        ],
        "genesis": {
            "runtime": {
                "runtime_genesis_config": {
                    "configuration": {
                        "config": {
                            "validation_upgrade_frequency": 1,
                            "validation_upgrade_delay": 1
                        }
                    }
                }
            }
        }
    },
    "parachains": [
        {
            "bin": "./bin/polkadot-collator",
            "id": "200",
            "balance": "1000000000000000000000",
            "nodes": [
                {
                    "wsPort": 9988,
                    "port": 31200,
                    "name": "alice",
                    "flags": ["--force-authoring", "--", "--execution=wasm"]
                }
            ]
        },
        {
            "bin": "./bin/polkadot-collator",
            "id": "300",
            "balance": "1000000000000000000000",
            "nodes": [
                {
                    "wsPort": 9999,
                    "port": 31300,
                    "name": "alice",
                    "flags": ["--force-authoring", "--", "--execution=wasm"]
                }
            ]
        }
    ],
    "simpleParachains": [
        {
            "bin": "./bin/adder-collator",
            "id": "400",
            "port": "31400",
            "name": "alice",
            "balance": "1000000000000000000000"
        }
    ],
    "hrmpChannels": [
        {
            "sender": 200,
            "recipient": 300,
            "maxCapacity": 8,
            "maxMessageSize": 512
        }
    ],
    "types": {},
    "finalization": false
}
</code>```

When I call polkadot-launch, all alice, bob, charlieanddave` have ok logs:

```<code>$ tail -f alice.log
2021-09-25 19:34:30  Starting consensus session on top of parent 0x7df9c10b7ff6ded2b2712273633582c445345541a3a5d20fab85e67c041bab5c
2021-09-25 19:34:30  Prepared block for proposing at 8 [hash: 0x9b44a965ee76e35f4721888c53f31ebe8920224bcea359e82ff8dedb1734502b; parent_hash: 0x7df9…ab5c; extrinsics (2): [0xc67d…93c7, 0xecd4…0d35]]
2021-09-25 19:34:30  Pre-sealed block for proposal at 8. Hash now 0xd167ba86acc9f96c1282793387bc37f09b9cd4132113e8c59027958673bd22ae, previously 0x9b44a965ee76e35f4721888c53f31ebe8920224bcea359e82ff8dedb1734502b.
2021-09-25 19:34:30 ✨ Imported #8 (0xd167…22ae)
2021-09-25 19:34:32  Idle (3 peers), best: #8 (0xd167…22ae), finalized #5 (0x4ab2…f178), ⬇ 1.4kiB/s ⬆ 2.2kiB/s
2021-09-25 19:34:36  Starting consensus session on top of parent 0xd167ba86acc9f96c1282793387bc37f09b9cd4132113e8c59027958673bd22ae
2021-09-25 19:34:36  Prepared block for proposing at 9 [hash: 0x5978b3aded771de9bdbcbe1cbb8d65f36dd0f85db791cf4faa7a43c2ad9a720e; parent_hash: 0xd167…22ae; extrinsics (2): [0xf381…4795, 0xfe0b…8a55]]
2021-09-25 19:34:36  Pre-sealed block for proposal at 9. Hash now 0x0f3261953f7ee2bf7973d5b3b988eceaf001ab8f8c0ee770d2c47e360e597caa, previously 0x5978b3aded771de9bdbcbe1cbb8d65f36dd0f85db791cf4faa7a43c2ad9a720e.
2021-09-25 19:34:36 ✨ Imported #9 (0x0f32…7caa)
2021-09-25 19:34:37  Idle (3 peers), best: #9 (0x0f32…7caa), finalized #6 (0x6046…7629), ⬇ 1.5kiB/s ⬆ 2.7kiB/s
2021-09-25 19:34:42 ✨ Imported #10 (0x7a55…a45a)
2021-09-25 19:34:42  Idle (3 peers), best: #10 (0x7a55…a45a), finalized #7 (0x7df9…ab5c), ⬇ 1.6kiB/s ⬆ 1.6kiB/s
2021-09-25 19:34:47  Idle (3 peers), best: #10 (0x7a55…a45a), finalized #8 (0xd167…22ae), ⬇ 3.0kiB/s ⬆ 3.4kiB/s
2021-09-25 19:34:48  New epoch 1 launching at block 0x7602…ec7f (block slot 272101548 >= start slot 272101548).
2021-09-25 19:34:48  Next epoch starts at slot 272101558
2021-09-25 19:34:48 ✨ Imported #11 (0x7602…ec7f)
2021-09-25 19:34:50  Round #9 concluded, committed: SignedCommitment { commitment: Commitment { payload: 0xf0a3fb9ad9246d2071beed4daebaf1145e4ccc2939d2a739a832cbbf51fc28ed, block_number: 9, validator_set_id: 0 }, signatures: [Some(Signature(d586df10c3502ca9f0babf7b032e409a79c2506f384ea48216a6d802435d7cd45caf1eca39d7972d01e0a019de10061c40b8f13d5e07f4c7a1865e36d0a72c3100)), None, Some(Signature(ac6edcd9d5df9ed08ddb3870ab058b2709c2e2c31aef9e758a76cc0032971f8d6063048a5fa051f5b6d0be98ef12e9d964b9c9ab371aa1a422eaef4da394773200)), Some(Signature(32635d143cb5f1f4ab1475a0cbc3565f96ae68bf55f7090c53180075fc6f11a86e547e45d6c98b1b8af70cb07e14d3f188c1186320ea9b862fcc83553d059f2101))] }.
</code>```

But 9988.log seems weird:

```<code>$ tail -f 9988.log
error: The argument '--force-authoring' was provided more than once, but cannot be used multiple times

USAGE:
    polkadot-collator --alice --collator --offchain-worker <ENABLED> --force-authoring --in-peers <COUNT> --max-parallel-downloads <COUNT> --node-key-type <TYPE> --out-peers <COUNT> --parachain-id <parachain-id> --pool-kbytes <COUNT> --pool-limit <COUNT> --port <PORT> --rpc-methods <METHOD SET> --state-cache-size <Bytes> --sync <SYNC_MODE> --tmp --tracing-receiver <RECEIVER> --wasm-execution <METHOD> --ws-port <PORT>

For more information try --help
</code>```

So I guess I'm only running a Relay Chain?
Collators for Cumulus/Statemine chains 200 and 300 are dead?

What's wrong with my setup?

答: Polkadot launch is handing over that argument by default now (because it was almost always needed). So just delete "--force-authoring", and it should all work.

Body:
I want to deploy a local Polkadot Testnet via polkadot-launch.

I built the executables from:

polkadot: v0.9.9-1

cumulus: statemine_v3

This is the config.json:

{
    "relaychain": {
        "bin": "./bin/polkadot",
        "chain": "rococo-local",
        "nodes": [
            {
                "name": "alice",
                "wsPort": 9944,
                "port": 30444
            },
            {
                "name": "bob",
                "wsPort": 9955,
                "port": 30555
            },
            {
                "name": "charlie",
                "wsPort": 9966,
                "port": 30666
            },
            {
                "name": "dave",
                "wsPort": 9977,
                "port": 30777
            }
        ],
        "genesis": {
            "runtime": {
                "runtime_genesis_config": {
                    "configuration": {
                        "config": {
                            "validation_upgrade_frequency": 1,
                            "validation_upgrade_delay": 1
                        }
                    }
                }
            }
        }
    },
    "parachains": [
        {
            "bin": "./bin/polkadot-collator",
            "id": "200",
            "balance": "1000000000000000000000",
            "nodes": [
                {
                    "wsPort": 9988,
                    "port": 31200,
                    "name": "alice",
                    "flags": ["--force-authoring", "--", "--execution=wasm"]
                }
            ]
        },
        {
            "bin": "./bin/polkadot-collator",
            "id": "300",
            "balance": "1000000000000000000000",
            "nodes": [
                {
                    "wsPort": 9999,
                    "port": 31300,
                    "name": "alice",
                    "flags": ["--force-authoring", "--", "--execution=wasm"]
                }
            ]
        }
    ],
    "simpleParachains": [
        {
            "bin": "./bin/adder-collator",
            "id": "400",
            "port": "31400",
            "name": "alice",
            "balance": "1000000000000000000000"
        }
    ],
    "hrmpChannels": [
        {
            "sender": 200,
            "recipient": 300,
            "maxCapacity": 8,
            "maxMessageSize": 512
        }
    ],
    "types": {},
    "finalization": false
}

When I call polkadot-launch, all alice, bob, charlieanddave` have ok logs:

$ tail -f alice.log
2021-09-25 19:34:30  Starting consensus session on top of parent 0x7df9c10b7ff6ded2b2712273633582c445345541a3a5d20fab85e67c041bab5c
2021-09-25 19:34:30  Prepared block for proposing at 8 [hash: 0x9b44a965ee76e35f4721888c53f31ebe8920224bcea359e82ff8dedb1734502b; parent_hash: 0x7df9…ab5c; extrinsics (2): [0xc67d…93c7, 0xecd4…0d35]]
2021-09-25 19:34:30  Pre-sealed block for proposal at 8. Hash now 0xd167ba86acc9f96c1282793387bc37f09b9cd4132113e8c59027958673bd22ae, previously 0x9b44a965ee76e35f4721888c53f31ebe8920224bcea359e82ff8dedb1734502b.
2021-09-25 19:34:30 ✨ Imported #8 (0xd167…22ae)
2021-09-25 19:34:32  Idle (3 peers), best: #8 (0xd167…22ae), finalized #5 (0x4ab2…f178), ⬇ 1.4kiB/s ⬆ 2.2kiB/s
2021-09-25 19:34:36  Starting consensus session on top of parent 0xd167ba86acc9f96c1282793387bc37f09b9cd4132113e8c59027958673bd22ae
2021-09-25 19:34:36  Prepared block for proposing at 9 [hash: 0x5978b3aded771de9bdbcbe1cbb8d65f36dd0f85db791cf4faa7a43c2ad9a720e; parent_hash: 0xd167…22ae; extrinsics (2): [0xf381…4795, 0xfe0b…8a55]]
2021-09-25 19:34:36  Pre-sealed block for proposal at 9. Hash now 0x0f3261953f7ee2bf7973d5b3b988eceaf001ab8f8c0ee770d2c47e360e597caa, previously 0x5978b3aded771de9bdbcbe1cbb8d65f36dd0f85db791cf4faa7a43c2ad9a720e.
2021-09-25 19:34:36 ✨ Imported #9 (0x0f32…7caa)
2021-09-25 19:34:37  Idle (3 peers), best: #9 (0x0f32…7caa), finalized #6 (0x6046…7629), ⬇ 1.5kiB/s ⬆ 2.7kiB/s
2021-09-25 19:34:42 ✨ Imported #10 (0x7a55…a45a)
2021-09-25 19:34:42  Idle (3 peers), best: #10 (0x7a55…a45a), finalized #7 (0x7df9…ab5c), ⬇ 1.6kiB/s ⬆ 1.6kiB/s
2021-09-25 19:34:47  Idle (3 peers), best: #10 (0x7a55…a45a), finalized #8 (0xd167…22ae), ⬇ 3.0kiB/s ⬆ 3.4kiB/s
2021-09-25 19:34:48  New epoch 1 launching at block 0x7602…ec7f (block slot 272101548 >= start slot 272101548).
2021-09-25 19:34:48  Next epoch starts at slot 272101558
2021-09-25 19:34:48 ✨ Imported #11 (0x7602…ec7f)
2021-09-25 19:34:50  Round #9 concluded, committed: SignedCommitment { commitment: Commitment { payload: 0xf0a3fb9ad9246d2071beed4daebaf1145e4ccc2939d2a739a832cbbf51fc28ed, block_number: 9, validator_set_id: 0 }, signatures: [Some(Signature(d586df10c3502ca9f0babf7b032e409a79c2506f384ea48216a6d802435d7cd45caf1eca39d7972d01e0a019de10061c40b8f13d5e07f4c7a1865e36d0a72c3100)), None, Some(Signature(ac6edcd9d5df9ed08ddb3870ab058b2709c2e2c31aef9e758a76cc0032971f8d6063048a5fa051f5b6d0be98ef12e9d964b9c9ab371aa1a422eaef4da394773200)), Some(Signature(32635d143cb5f1f4ab1475a0cbc3565f96ae68bf55f7090c53180075fc6f11a86e547e45d6c98b1b8af70cb07e14d3f188c1186320ea9b862fcc83553d059f2101))] }.

But 9988.log seems weird:

$ tail -f 9988.log
error: The argument '--force-authoring' was provided more than once, but cannot be used multiple times

USAGE:
    polkadot-collator --alice --collator --offchain-worker <ENABLED> --force-authoring --in-peers <COUNT> --max-parallel-downloads <COUNT> --node-key-type <TYPE> --out-peers <COUNT> --parachain-id <parachain-id> --pool-kbytes <COUNT> --pool-limit <COUNT> --port <PORT> --rpc-methods <METHOD SET> --state-cache-size <Bytes> --sync <SYNC_MODE> --tmp --tracing-receiver <RECEIVER> --wasm-execution <METHOD> --ws-port <PORT>

For more information try --help

So I guess I'm only running a Relay Chain?
Collators for Cumulus/Statemine chains 200 and 300 are dead?

What's wrong with my setup?


问:
Bump Python package version upon main branch merge

My Problem

I am developing a Python package consumed by several internal consumers in my company using their CI/CD pipeline. Therefore, it's important for them to know what is the latest version of the package so that they can install it if it has been changed. The package uses the classic PEP 440 SemVer structure, so I usually just update the minor number.

I'm using Git and GitHub, so every new commit to the main branch means a new version. I'm currently updating the version manually, which is error-prone and tedious. I'm looking for a way to automatically bump the minor version whenever I merge a PR to the main branch.

What Have I Tried

Manual version bump before the merge

Using bump2version - I don't know how to make it happen automatically on a merge to the main branch

My Question

How can I automatically bump the minor version of a Python package upon a PR merged to the main branch of a repo?

答:
Thanks @VonC for your elegant solution - it works beautifully :-)

(On same dev team as @AdamMatan)

Just one tweak we found necessary:

    on:
      push:
        branches:
        - master
        paths-ignore:
        - version.md
```

Without this (or equivalent "action filter") - this action will perpetually self trigger in a "github fork bomb" :-)

Body:
Thanks @VonC for your elegant solution - it works beautifully :-)

(On same dev team as @AdamMatan)

Just one tweak we found necessary:

    on:
      push:
        branches:
        - master
        paths-ignore:
        - version.md

Without this (or equivalent "action filter") - this action will perpetually self trigger in a "github fork bomb" :-)


问:
Enum.TryParse doesn't accept my out parameter as an object
I have the following line:

var parseSortField = (BasicProfileSortableFields?)Enum.TryParse(typeof(BasicProfileSortableFields?), sortOptions.SortColumn, out BasicProfileSortableFields? sortField);

Around the out parameter, I'm getting an error that says

Argument 3: cannot convert from 'out Services.Models.BasicProfileSortableFields?' to 'out object?'

Regular parsing works but I'm trying to catch a scenario where my string is not in the mentioned enum. Also the enum I'm referencing is from a nuget package and not actually written by me if that helps.

答:
There are two forms of Enum.TryParse method:

Non-generic ones with a Type parameter first and an out object parameter at the end

Generic ones without the Type parameter (because the generic type parameter is used instead) and with an out TEnum parameter at the end

Currently it looks like you're half-way between the two - but with a nullable final parameter (out TEnum? instead of out TEnum). Additionally, you're trying to cast the result of the TryParse method to the enum type - whereas actually it returns a bool saying whether or not the parsing succeeded.

I would advise using the generic forms, in code a little like Fubo's answer, but declaring the temp variable "inline" in the call:

var sortField =
    Enum.TryParse<BasicProfileSortableFields>(sortOptions.SortColumn, out var temp)
        ? temp
        : default(BasicProfileSortableFields?);
```


问:
What is an optional value in Swift?
From Apple's documentation:

You can use if and let together to work with values that might be missing. These values are represented as optionals. An optional value either contains a value or contains nil to indicate that the value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

Why would you want to use an optional value?

答:
There are lots of errors which are caused by people trying to use a value which is not set, sometime this can cause a crash, in objective c trying to call the methods of a nil object reference would just be ignored, so some piece of your code not executing and the compiler or written code has no way of telling your why. An optional argument let you have variables that can never be nil, and if you try to do build it the compiler can tell you before your code has even had a chance to run, or you can decide that its appropriate for the object to be undefined, and then the compiler can tell you when you try to write something that doesn't take this into account.

In the case of calling a possible nil object you can just go

```<code>object?.doSomthing()
</code>```

You have made it explicit to the compiler and any body who reads your code, that its possible object is nil and nothing will happen. Some times you have a few lines of code you only want to occur if the value exists, so you can do

```<code>if let obj = object {
    obj.doSomthing()
    doSomethingto(obj)
}
</code>```

The two statements will only execute if object is something, simarly you may want to stop the rest of the entire block of code if its not something

```<code>guard let obj = object {
    return
}
obj.doSomthing()
doSomethingto(obj)
</code>```

This can be simpler to read if everything after is only applicable if object is something, another possiblity is you want to use a default value

```<code>let obj = object ?? <default-object>
obj.doSomthing()
doSomethingto(obj)
</code>```

Now obj will be assigned to something even if its a default value for the type

options are useful in situation where a value may not gain a value until some event has occurred or you can use setting an option to nil as a way to say its no longer relevant or needs to be set again and everything that uses it has no point it doing anything with it until it is set, one way I like to use optionals is to tell me something has to be done or if has already been done for example

```<code>func eventFired() {
    guard timer == nil else { return }
    timer = scheduleTimerToCall(method, in: 60)
}

func method() {
    doSomthing()
    timer = nil
}
</code>```

This sudo code can call eventFired many times, but it's only on the first call that a timer is scheduled, once the schedule executes, it runs some method and sets timer back to nil so another timer can be scheduled.

Once you get around your head around variables being in an undefined state you can use that for all sort of thing.

Title: What is an optional value in Swift?

Body:
There are lots of errors which are caused by people trying to use a value which is not set, sometime this can cause a crash, in objective c trying to call the methods of a nil object reference would just be ignored, so some piece of your code not executing and the compiler or written code has no way of telling your why. An optional argument let you have variables that can never be nil, and if you try to do build it the compiler can tell you before your code has even had a chance to run, or you can decide that its appropriate for the object to be undefined, and then the compiler can tell you when you try to write something that doesn't take this into account.

In the case of calling a possible nil object you can just go

object?.doSomthing()

You have made it explicit to the compiler and any body who reads your code, that its possible object is nil and nothing will happen. Some times you have a few lines of code you only want to occur if the value exists, so you can do

if let obj = object {
    obj.doSomthing()
    doSomethingto(obj)
}

The two statements will only execute if object is something, simarly you may want to stop the rest of the entire block of code if its not something

guard let obj = object {
    return
}
obj.doSomthing()
doSomethingto(obj)

This can be simpler to read if everything after is only applicable if object is something, another possiblity is you want to use a default value

let obj = object ?? <default-object>
obj.doSomthing()
doSomethingto(obj)

Now obj will be assigned to something even if its a default value for the type

options are useful in situation where a value may not gain a value until some event has occurred or you can use setting an option to nil as a way to say its no longer relevant or needs to be set again and everything that uses it has no point it doing anything with it until it is set, one way I like to use optionals is to tell me something has to be done or if has already been done for example

func eventFired() {
    guard timer == nil else { return }
    timer = scheduleTimerToCall(method, in: 60)
}

func method() {
    doSomthing()
    timer = nil
}

This sudo code can call eventFired many times, but it's only on the first call that a timer is scheduled, once the schedule executes, it runs some method and sets timer back to nil so another timer can be scheduled.

Once you get around your head around variables being in an undefined state you can use that for all sort of thing.


问:
Eventbridge - Use FIFO SQS for deduplication
I need some events to be delivered exactly once, but I have no control of the message processor (so I can‘t make the recipient idempotent).

Is it possible to route events from Eventbridge to a FIFO SQS for deduplication and from the FIFO sqs to the recipient (lambda on other account? Would this achieve exact-once delivery?

答:
It is possible, but you have to configure the FIFO queue. It can detect duplicates based on the body of the message. See this docs.

FIFO queues help you avoid sending duplicates to a queue. If you retry
the SendMessage action within the 5-minute deduplication interval,
Amazon SQS doesn't introduce any duplicates into the queue.

The link goes on to state what configurations are required, so be sure to check it out.


问:
i want to change my API response to become array of array object in laravel
i have a problem for the response, i want to change the response API because i need for my mobile APP, the feature have filter object based on date. So i hope you all can help me to solve the problem

i wanna change the response for my API

before:

```<code>{
    "tasks": [
        {
            "id": 7,
            "user_id": 1,
            "title": "gh",
            "date": "2022-02-10 13:05:00",
            "deskripsi": "gfh",
            "created_at": "2022-02-09T06:05:56.000000Z",
            "updated_at": "2022-02-09T06:05:56.000000Z"
        },
        {
            "id": 5,
            "user_id": 1,
            "title": "ghf",
            "date": "2022-02-17 16:05:00",
            "deskripsi": "fghf",
            "created_at": "2022-02-09T06:05:12.000000Z",
            "updated_at": "2022-02-09T06:05:12.000000Z"
        },
        {
            "id": 6,
            "user_id": 1,
            "title": "fgh",
            "date": "2022-02-17 18:05:00",
            "deskripsi": "gh",
            "created_at": "2022-02-09T06:05:40.000000Z",
            "updated_at": "2022-02-09T06:05:40.000000Z"
        }
    ]
}
</code>```

here is the code for the response API above

```<code>return response([
            'tasks' => Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);
</code>```

and i want to change it my response API into this response

```<code>{
    "tasks": [
        {
            "date": "2022-02-10",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               },
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 15:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
        {
            "date": "2022-02-12",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-12 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
    ]
}
</code>```

答:
It sounds like you want to create a human friendly date field based on the date column, then group by it.

While solutions do exists to accomplish this at the database level, I believe you'd still need to loop around it again afterwards to get the hierarchy structure you're looking for. I don't think it's too complicated for PHP to loop through it.

My suggestion is as follows:

Before:

```<code>return response([
            'tasks' => Task::where('user_id', auth()->user()->id)
                ->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);
</code>```

After:

```<code>$out = [];
$tasks = Task::where('user_id', auth()->user()->id)
        ->where('date','>',NOW())->orderBy('date','asc')->get();

foreach($tasks as $task) {
    $date = strtok((string)$task->date, ' ');
            if (empty($out[$date])) {
                $out[$date] = (object)['date' => $date, 'task' => []];
            }
            $out[$date]->task[] = $task;
}

$out = array_values($out);

return response(['tasks' => $out], 200);
</code>```

Note in the above I'm using the function strtok. This function might look new even to the most senior of php developers.... It's a lot like explode, except it can be used to grab only the first part before the token you're splitting on. While I could have used explode, since the latter part after the token isn't needed, strtok is better suited for the job here.

Body:
i have a problem for the response, i want to change the response API because i need for my mobile APP, the feature have filter object based on date. So i hope you all can help me to solve the problem

i wanna change the response for my API

before:

{
    "tasks": [
        {
            "id": 7,
            "user_id": 1,
            "title": "gh",
            "date": "2022-02-10 13:05:00",
            "deskripsi": "gfh",
            "created_at": "2022-02-09T06:05:56.000000Z",
            "updated_at": "2022-02-09T06:05:56.000000Z"
        },
        {
            "id": 5,
            "user_id": 1,
            "title": "ghf",
            "date": "2022-02-17 16:05:00",
            "deskripsi": "fghf",
            "created_at": "2022-02-09T06:05:12.000000Z",
            "updated_at": "2022-02-09T06:05:12.000000Z"
        },
        {
            "id": 6,
            "user_id": 1,
            "title": "fgh",
            "date": "2022-02-17 18:05:00",
            "deskripsi": "gh",
            "created_at": "2022-02-09T06:05:40.000000Z",
            "updated_at": "2022-02-09T06:05:40.000000Z"
        }
    ]
}

here is the code for the response API above

return response([
            'tasks' => Task::where('user_id', auth()->user()->id)->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);

and i want to change it my response API into this response

{
    "tasks": [
        {
            "date": "2022-02-10",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               },
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-10 15:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
        {
            "date": "2022-02-12",
            "task": [
               {
                  "id": 7,
                  "user_id": 1,
                  "title": "gh",
                  "date": "2022-02-12 13:05:00",
                  "deskripsi": "gfh",
                  "created_at": "2022-02-09T06:05:56.000000Z",
                  "updated_at": "2022-02-09T06:05:56.000000Z"
               }
            ]
        },
    ]
}

Body:
It sounds like you want to create a human friendly date field based on the date column, then group by it.

While solutions do exists to accomplish this at the database level, I believe you'd still need to loop around it again afterwards to get the hierarchy structure you're looking for. I don't think it's too complicated for PHP to loop through it.

My suggestion is as follows:

Before:

return response([
            'tasks' => Task::where('user_id', auth()->user()->id)
                ->where('date','>',NOW())->orderBy('date','asc')->get(),
        ],200);

After:

$out = [];
$tasks = Task::where('user_id', auth()->user()->id)
        ->where('date','>',NOW())->orderBy('date','asc')->get();

foreach($tasks as $task) {
    $date = strtok((string)$task->date, ' ');
            if (empty($out[$date])) {
                $out[$date] = (object)['date' => $date, 'task' => []];
            }
            $out[$date]->task[] = $task;
}

$out = array_values($out);

return response(['tasks' => $out], 200);

Note in the above I'm using the function strtok. This function might look new even to the most senior of php developers.... It's a lot like explode, except it can be used to grab only the first part before the token you're splitting on. While I could have used explode, since the latter part after the token isn't needed, strtok is better suited for the job here.


问:
Unusual behaviour of Z3py optimization program
I'm writing a program that scrapes option_chain data off the TMX website and suggests an optimized Covered Call options portfolio based on those data. for the optimization process, I used the z3py library as discussed on this website by many users. the optimization process works by maximizing the premiums and setting the portfolio delta to a user-specified amount.

initially, I made a mistake in my calculation for portfolio delta which made everything work so smoothly but I'm facing issues after correcting it. portfolio delta is calculated by taking the Weighted average delta of non-zero positions in the portfolio. to achieve this I used the following setup:

```<code>eng = Optimize()
Weights = [Real(row.symbol) for row in df.itertuples()]
#to count non-zero positions
TotCount = Real("TotCount")
eng.add(TotCount == Sum([If(w > 0, 1, 0) for w in Weights]))
eng.add(TotCount == If(TotCount >= 0, TotCount, 1))
#to get portfolio delta
eng.add(TotDelta == (Sum([(w * row.delta) for w, row in zip(Weights, df.itertuples())]) / TotCount))
eng.add(TotDelta == delta)
res = eng.check()
</code>```

the weird behavior happens when I run this as a function in a loop with different values for delta, the first loop actually does the calculation and spits out an answer but after that my code gets stuck on the last line for hours without any progress. i tried a few things like completely reformatting it but nothing seems to make a difference. I was wondering if anyone knows what's happening here or not?

答:
Unfortunately, there isn't much in your description for anyone to go on without knowing further details of your setup. All one can deduce from your text is that the constraints are hard to solve for those values of delta where it takes longer. Without seeing the rest of your program, it's impossible to opine on what else might be going on.

See if you can isolate the value of delta that it runs slowly on, and just run it for that one instance separately to see if there's interaction coming from elsewhere. That's by no means a solution of course, but it's one way to get started.

One thing I noticed, though, is this line you have:

eng.add(TotCount == If(TotCount >= 0, TotCount, 1))
```
<p>Let's see what this line is saying: If <code>TotCount >= 0</code>, then it says <code>TotCount == TotCount</code>. i.e., it puts no restrictions on it. Otherwise, it says <code>TotCount == 1</code>; i.e., if <code>TotCount < 0</code>, then <code>TotCount == 1</code>. Well this latter statement is obviously false. That is if, the other constraints force <code>TotCount < 0</code>, then your program would be <code>unsat</code>. This essentially means that whole line is functionally equivalent to:</p>
<pre class="lang-py prettyprint-override"><code>eng.add(TotCount >= 0)
</code>```

It's hard for anyone to tell if that's what you intended; but I suspect perhaps it isn't; since you'd have just written the simpler form above. Perhaps you wanted to say something more along the lines of if TotCount < 0, then make it 1. But looking at the previous line, (i.e., the Sum expression), we see that this'll never be the case. So, something is fishy there.

Hope that helps to get you started; note that you cannot model "sequential assignment" like in a programming language in this way. (You'd need to do what's known as single static assignment, a.k.a. SSA, conversion.) But then again, without knowing your exact intention, it's hard to opine.

Body:
I'm writing a program that scrapes option_chain data off the TMX website and suggests an optimized Covered Call options portfolio based on those data. for the optimization process, I used the z3py library as discussed on this website by many users. the optimization process works by maximizing the premiums and setting the portfolio delta to a user-specified amount.

initially, I made a mistake in my calculation for portfolio delta which made everything work so smoothly but I'm facing issues after correcting it. portfolio delta is calculated by taking the Weighted average delta of non-zero positions in the portfolio. to achieve this I used the following setup:

eng = Optimize()
Weights = [Real(row.symbol) for row in df.itertuples()]
#to count non-zero positions
TotCount = Real("TotCount")
eng.add(TotCount == Sum([If(w > 0, 1, 0) for w in Weights]))
eng.add(TotCount == If(TotCount >= 0, TotCount, 1))
#to get portfolio delta
eng.add(TotDelta == (Sum([(w * row.delta) for w, row in zip(Weights, df.itertuples())]) / TotCount))
eng.add(TotDelta == delta)
res = eng.check()

the weird behavior happens when I run this as a function in a loop with different values for delta, the first loop actually does the calculation and spits out an answer but after that my code gets stuck on the last line for hours without any progress. i tried a few things like completely reformatting it but nothing seems to make a difference. I was wondering if anyone knows what's happening here or not?

Body:
Unfortunately, there isn't much in your description for anyone to go on without knowing further details of your setup. All one can deduce from your text is that the constraints are hard to solve for those values of delta where it takes longer. Without seeing the rest of your program, it's impossible to opine on what else might be going on.

See if you can isolate the value of delta that it runs slowly on, and just run it for that one instance separately to see if there's interaction coming from elsewhere. That's by no means a solution of course, but it's one way to get started.

One thing I noticed, though, is this line you have:

eng.add(TotCount == If(TotCount >= 0, TotCount, 1))

Let's see what this line is saying: If TotCount >= 0, then it says TotCount == TotCount. i.e., it puts no restrictions on it. Otherwise, it says TotCount == 1; i.e., if TotCount < 0, then TotCount == 1. Well this latter statement is obviously false. That is if, the other constraints force TotCount < 0, then your program would be unsat. This essentially means that whole line is functionally equivalent to:

eng.add(TotCount >= 0)

It's hard for anyone to tell if that's what you intended; but I suspect perhaps it isn't; since you'd have just written the simpler form above. Perhaps you wanted to say something more along the lines of if TotCount < 0, then make it 1. But looking at the previous line, (i.e., the Sum expression), we see that this'll never be the case. So, something is fishy there.

Hope that helps to get you started; note that you cannot model "sequential assignment" like in a programming language in this way. (You'd need to do what's known as single static assignment, a.k.a. SSA, conversion.) But then again, without knowing your exact intention, it's hard to opine.


问:
How to split a field up and create columns in a new table SQL Server
I'm having trouble figuring out how to split a field up and create columns with those values in a new table.

Here is an example of what my table looks like

snippet

Basically, inside of the keyhash column there are multiple values in there separated by carrots that I need to turn into their own columns in a new table. I don't really know how to get started on accomplishing that.

答:
You can try something like this to split a column of string to multiple columns.

PARSENAME(object_name nvarchar(128),object_part int) receives a string with '.' delimeter and can return the nth part of that string

```<code>select
    tableNumber,
    currVer,
    KeyAnalysis,
    Replace(REPLACE(keyhash,'<',''),'>','.') as KeyHash,
    REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 1)) AS [Column1]
   , REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 2)) AS [Column2]
   , REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 3)) AS [Column3]
from SOF
</code>```

the results will be like this

tableNumber
currVer
KeyAnalysis
KeyHash
Column1
Column2
Column3

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Lessors Liability per $100 of limit of ins.
704
Lessors Liability per $100 of limit of ins
NULL

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Occ Liability per $1000 of Annual Gross Sales.Fountain Hills.
704
Occ Liability per $1000 of Annual Gross Sales
Fountain Hills

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Occ Liability per $1000 of Annual Gross Sales.
704
Occ Liability per $1000 of Annual Gross Sales
NULL

Body:
You can try something like this to split a column of string to multiple columns.

PARSENAME(object_name nvarchar(128),object_part int) receives a string with '.' delimeter and can return the nth part of that string

select
    tableNumber,
    currVer,
    KeyAnalysis,
    Replace(REPLACE(keyhash,'<',''),'>','.') as KeyHash,
    REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 1)) AS [Column1]
   , REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 2)) AS [Column2]
   , REVERSE(PARSENAME(REVERSE(Replace(REPLACE(keyhash,'<',''),'>','.')), 3)) AS [Column3]
from SOF

the results will be like this

tableNumber
currVer
KeyAnalysis
KeyHash
Column1
Column2
Column3

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Lessors Liability per $100 of limit of ins.
704
Lessors Liability per $100 of limit of ins
NULL

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Occ Liability per $1000 of Annual Gross Sales.Fountain Hills.
704
Occ Liability per $1000 of Annual Gross Sales
Fountain Hills

#(LC)
21.0401
Key is: Region row header then subregion if available
704.Occ Liability per $1000 of Annual Gross Sales.
704
Occ Liability per $1000 of Annual Gross Sales
NULL