问:
Symfony login from an external application
Is there a way to login in a symfony app from an external application ?

I tried to create a custom authenticator. With it, I can make working the login processus through the custom authenticator in a same environment, but when I try from an external app, I face to CORS errors : "Redirect is not allowed for a preflight request"

The process I tried :

The external app ask for a token on the symfony app (get request)

with this token, and a mail in the body, a post request trigger the authenticator (post request), this request is good in postman, it returns me the home page of the app with a connected user

I don't know what to do next to make it work correctly

Is anyone have an idea ?

Thanks by advance

UPDATE 1 :

The code that I tried :

```<code>/**
 * @throws \Exception
 */
public function authenticate(Request $request): Passport
{
    $apiToken = $request->headers->get('X-AUTH-TOKEN-OAV');
    $sessionId = $request->headers->get('X-AUTH-TOKEN-SESSION');
    $session = $request->getSession();
    $session->setId($sessionId);

    if (null === $apiToken) {
        // The token header was empty, authentication fails with HTTP Status
        // Code 401 "Unauthorized"
        throw new CustomUserMessageAuthenticationException('X-AUTH-TOKEN-OAV attendu dans les headers');
    }

    $content = json_decode($request->getContent(), true);
    if (\is_array($content) && \array_key_exists('userEmail', $content)) {
        $email = $content['userEmail'];
        $request->getSession()->set('email', $email);
    }

    // On inscrit l'email en session
    $email = $request->getSession()->get('email');
    // On vérifie la validité du token et on incrémente la durée de sa validité
    $this->checkTokenValidity($apiToken, true);
    return new Passport(new UserBadge('mail@mail.fr'), new PasswordCredentials('pswd!!'));
}
</code>```

And in the html page to simulate external app :

```<code>{% block body %}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://code.jquery.com/jquery-3.6.1.min.js"
        integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script>
    let tokenOav = '';
    let sessionOav = '';
    function sendSetRequest() {
        console.info('Sending set request');
        console.log(tokenOav.value);
        console.log('start');
        console.log(sessionOav)
        console.log('********')
        let set_params = {
            "action": "action_set"
        };
        return $.ajax({
            data: set_params,
            url: "https://my-site.fr/home",
            headers: {
                'X-AUTH-TOKEN-OAV': tokenOav.value,
                'withCredentials': true,
                'X-AUTH-TOKEN-SESSION': sessionOav
            },
            type: 'post',
            success: function (result) {
                window.location.href = "https://my-site.fr/home";
            }
        });
    }
    function sendGetRequest() {
        console.info('Sending get request');
        let get_params = {
            "action": "action_get"
        };
        return $.ajax({
            data: get_params,
            url: 'https://my-site.fr/api/generer-token?api_token=TOKEN',
            type: 'get',
            success: function (result) {
                console.log(result);
                tokenOav = result.token;
                sessionOav = result.session_id;
                $("#cntr_debug2").html(result);
            }
        });
    }
    function callApi() {
        sendGetRequest().then(sendSetRequest);
    }
</script>
<form><!---Removed form submit url-->
    <input type="text" id="keyName" value="testValue">
    <!---Id attribute added to input field to be submitted--->
    <input type="button" onclick="callApi()" value="Submit">
    <!---Input type is button NOT submit--->
</form>
</code>```

Body:
Is there a way to login in a symfony app from an external application ?

I tried to create a custom authenticator. With it, I can make working the login processus through the custom authenticator in a same environment, but when I try from an external app, I face to CORS errors : "Redirect is not allowed for a preflight request"

The process I tried :

The external app ask for a token on the symfony app (get request)

with this token, and a mail in the body, a post request trigger the authenticator (post request), this request is good in postman, it returns me the home page of the app with a connected user

I don't know what to do next to make it work correctly

Is anyone have an idea ?

Thanks by advance

UPDATE 1 :

The code that I tried :

/**
 * @throws \Exception
 */
public function authenticate(Request $request): Passport
{
    $apiToken = $request->headers->get('X-AUTH-TOKEN-OAV');
    $sessionId = $request->headers->get('X-AUTH-TOKEN-SESSION');
    $session = $request->getSession();
    $session->setId($sessionId);

    if (null === $apiToken) {
        // The token header was empty, authentication fails with HTTP Status
        // Code 401 "Unauthorized"
        throw new CustomUserMessageAuthenticationException('X-AUTH-TOKEN-OAV attendu dans les headers');
    }

    $content = json_decode($request->getContent(), true);
    if (\is_array($content) && \array_key_exists('userEmail', $content)) {
        $email = $content['userEmail'];
        $request->getSession()->set('email', $email);
    }

    // On inscrit l'email en session
    $email = $request->getSession()->get('email');
    // On vérifie la validité du token et on incrémente la durée de sa validité
    $this->checkTokenValidity($apiToken, true);
    return new Passport(new UserBadge('mail@mail.fr'), new PasswordCredentials('pswd!!'));
}

And in the html page to simulate external app :

{% block body %}

<form>
    <input type="text" id="keyName" value="testValue">

    <input type="button" onclick="callApi()" value="Submit">

</form>


来源: stackexchange

问:
Is it possible to use .lib file in .net core project?
I have a .lib file created using Cmake from c++ code ,
Is it possible to use .lib file in ( .NET Core ) project like DLL file ?
if not , is there any way to convert .lib file to .dll file ?</p>

ContentLicense: CC BY-SA 4.0


问:
IOS: How to list an already installed custom font in my app
I am building an app for iPad and would like to use an already installed custom font in my ipad. I have downloaded a custom font (Cabin Sketch) from Adobe Creative Cloud Suite. After installing, I am able to see the font in General > Fonts

In my code, I am trying to print all the available fonts in the system but unable to see the one that's already been installed.

Here are the codes I have tried to print the font families.

```<code>    NSDictionary *descriptorOptions = @{(id)kCTFontDownloadedAttribute : @YES}; // tried kCTFontDownloadableAttribute too
    CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)descriptorOptions);
    CFArrayRef fontDescriptors = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, NULL);
    for(UIFontDescriptor *descriptor in (NSArray *)CFBridgingRelease(fontDescriptors)) {
        NSString *fontFamilyName = [descriptor objectForKey:UIFontDescriptorFamilyAttribute];
        NSLog(@"Font Family Name = %@", fontFamilyName);
    }
</code>```
```<code>    NSArray *familyNames = [UIFont familyNames];
    for (NSString *aFamilyName in familyNames) {
         NSArray *fontNames = [UIFont fontNamesForFamilyName:aFamilyName];
         for (NSString *aFontName in fontNames) {
            NSLog(@"%@", aFontName);
         }
    }
</code>```
```<code>    QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames();
    for (NSString *familyName in familyNames.as<const NSArray *>())
        NSLog(@"%@", familyName);
</code>```

Thanks in advance.

Body:
I am building an app for iPad and would like to use an already installed custom font in my ipad. I have downloaded a custom font (Cabin Sketch) from Adobe Creative Cloud Suite. After installing, I am able to see the font in General > Fonts

In my code, I am trying to print all the available fonts in the system but unable to see the one that's already been installed.

Here are the codes I have tried to print the font families.

    NSDictionary *descriptorOptions = @{(id)kCTFontDownloadedAttribute : @YES}; // tried kCTFontDownloadableAttribute too
    CTFontDescriptorRef descriptor = CTFontDescriptorCreateWithAttributes((CFDictionaryRef)descriptorOptions);
    CFArrayRef fontDescriptors = CTFontDescriptorCreateMatchingFontDescriptors(descriptor, NULL);
    for(UIFontDescriptor *descriptor in (NSArray *)CFBridgingRelease(fontDescriptors)) {
        NSString *fontFamilyName = [descriptor objectForKey:UIFontDescriptorFamilyAttribute];
        NSLog(@"Font Family Name = %@", fontFamilyName);
    }

    NSArray *familyNames = [UIFont familyNames];
    for (NSString *aFamilyName in familyNames) {
         NSArray *fontNames = [UIFont fontNamesForFamilyName:aFamilyName];
         for (NSString *aFontName in fontNames) {
            NSLog(@"%@", aFontName);
         }
    }

    QCFType<CFArrayRef> familyNames = CTFontManagerCopyAvailableFontFamilyNames();
    for (NSString *familyName in familyNames.as<const NSArray *>())
        NSLog(@"%@", familyName);

Thanks in advance.


问:
How to return multiple images using File Response?
I managed to send an image using File Response: https://laravel.com/docs/9.x/responses#file-responses

From the Controller:

```<code>public function get_image(Request $request) {
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';
    return response()->file($pathToFile); }
</code>```

But I need to return multiple images, but this doesn't work (In this example I use the same image just for the test):

```<code>public function get_images(Request $request)
{
    $images = [];
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';

    for ($i = 0; $i < 20; $i++) {
        $images[] = response()->file($pathToFile);
    }
    return $images;
}
</code>```

It only returns array of empty headers. I am using Fetch API (Or AJAX) to get the images

Body:
I managed to send an image using File Response: https://laravel.com/docs/9.x/responses#file-responses

From the Controller:

public function get_image(Request $request) {
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';
    return response()->file($pathToFile); }

But I need to return multiple images, but this doesn't work (In this example I use the same image just for the test):

public function get_images(Request $request)
{
    $images = [];
    $pathToFile = '../storage/uploads/460s6DLmCnvoom90S7wfk.jpg';

    for ($i = 0; $i < 20; $i++) {
        $images[] = response()->file($pathToFile);
    }
    return $images;
}

It only returns array of empty headers. I am using Fetch API (Or AJAX) to get the images


问:
My NativeWind Css not working on HomeScreen.js File
```<code>I have tried clearing the expo cache with "expo start -c", still not working.

But it works on my App.js file,  when i use the css styling on my HomeScreen File, it does not work.

**App.Js**
import * as React from 'react';
import { StatusBar } from 'expo-status-bar';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';

 const Stack = createNativeStackNavigator();

 export default function App() {
  return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

**Homescreen.js file**

import { View, Text, SafeAreaView } from 'react-native';
import  React, { useLayoutEffect } from 'react';
import { useNavigation } from '@react-navigation/native';

const HomeScreen = () => {
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, []);
  return (
    <SafeAreaView>
      <Text className="text-red-500">   HomeScreen   </Text>
    </SafeAreaView>
  );
};

export default HomeScreen;

**Tailwind Config file**

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./App.{js,jsx,ts,tsx}",
    "./screens/**/ *.{js,jsx,ts,tsx}",
    "./pages/**/ *.{js,ts,jsx,tsx}",
    "./components/**/ *.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}
</code>```

What i mean is that, I'm using NativewWind in my React-native App. Now after following all of the documentation. i tried using the css in the App.js which is the default home screen, It worked fine. But when i created a new screen (Home) and made it as my default screen after installation REACT NAVIGATION. Using the css on the Home screen isn't reflecting. Its simply not working. And i've done all of the solutions online (Clearing cache, restarting and all but still same result)

Body:
I have tried clearing the expo cache with "expo start -c", still not working.

But it works on my App.js file,  when i use the css styling on my HomeScreen File, it does not work.

**App.Js**
import * as React from 'react';
import { StatusBar } from 'expo-status-bar';
import { Text, View } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';

 const Stack = createNativeStackNavigator();

 export default function App() {
  return (
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen name="Home" component={HomeScreen} />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

**Homescreen.js file**

import { View, Text, SafeAreaView } from 'react-native';
import  React, { useLayoutEffect } from 'react';
import { useNavigation } from '@react-navigation/native';

const HomeScreen = () => {
  const navigation = useNavigation();

  useLayoutEffect(() => {
    navigation.setOptions({
      headerShown: false,
    });
  }, []);
  return (
    <SafeAreaView>
      <Text className="text-red-500">   HomeScreen   </Text>
    </SafeAreaView>
  );
};

export default HomeScreen;

**Tailwind Config file**

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./App.{js,jsx,ts,tsx}",
    "./screens/**/ *.{js,jsx,ts,tsx}",
    "./pages/**/ *.{js,ts,jsx,tsx}",
    "./components/**/ *.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  plugins: [],
}

What i mean is that, I'm using NativewWind in my React-native App. Now after following all of the documentation. i tried using the css in the App.js which is the default home screen, It worked fine. But when i created a new screen (Home) and made it as my default screen after installation REACT NAVIGATION. Using the css on the Home screen isn't reflecting. Its simply not working. And i've done all of the solutions online (Clearing cache, restarting and all but still same result)


问:
error running: Element: class com.intellij.psi.impl.source.tree.LeafPsiElement #Gherkin because: different providers:
i open a new maven project with selenium bdd cucumber framework
when i try to run feature i got this error:

Error running 'Scenario: Verify user will be able to login entering phone number and password to login screen': Element: class com.intellij.psi.impl.source.tree.LeafPsiElement #Gherkin because: different providers: com.intellij.psi.SingleRootFileViewProvider{vFile=file://C:/Users/aliha/Documents/DCA-FOOD-AUTOMATION/src/test/resources/features/loginPageProd.feature, vFileId=371277, content=VirtualFileContent{size=398}, eventSystemEnabled=true}(4f6eaf43); com.intellij.psi.SingleRootFileViewProvider{vFile=file://C:/Users/aliha/Documents/DCA-FOOD-AUTOMATION/src/test/resources/features/loginPageProd.feature, vFileId=371277, content=VirtualFileContent{size=398}, eventSystemEnabled=true}(bb81516) invalidated at: see attachment; com.intellij.psi.impl.source.tree.LeafPsiElement:SCENARIO_KEYWORD / com.intellij.psi.impl.source.tree.CompositeElement:scenario / com.intellij.psi.impl.source.tree.CompositeElement:feature / com.intellij.psi.impl.source.tree.FileElement:FILE

How can i run my feature???

Thank you

i tried to run and failed


问:
React Authentication By Example tutorial with Auth0 stuck
I am just starting out with React and Authentication. I have to use Auth0 for my course but they don't give us any support on how to use it. I've tried following the tutorial on https://developer.auth0.com/resources/guides/spa/react/basic-authentication but the starter application just comes up with a blank screen. It requires React Router 5, and I was wondering if that was the problem but package.json seems to install that version, so it doesn't seem to be that.

Do I continue with the tutorial and will it work once I've gone through all the authorisation work? Or is something fundamentally wrong now? If anyone has done this and knows the answer, I would be most obliged to know. Failing that, I'll update this if I get any farther.

I installed the spa demo app and expected to see a dummy app but all I get is a black screen. The tutorial is for installing Auth0 so I don't know if I need to do that first before anything appears, but that seems odd.


问:
WPF TemplateBinding on attached properties
I would like to understand this kind of TemplateBinding use:

```<code>Background="{TemplateBinding Panel.Background}"
</code>```

This is used line inside of the definition of a ControlTemplate redefining the look&Feel of an expander. (The ControlTemplate TargetType=Expander)

As the expander class does not have a Panel Property, I would like to understand where the Panel.Background will come from when the control template will be applied.
I thought of an attached property, but in XAML I cannot write something like:

```<code><Expander Panel.Background ="..." />
</code>```

Hence the expander class does not seem to have the Panel.Background attached property.

ContentLicense: CC BY-SA 3.0

Body:
I would like to understand this kind of TemplateBinding use:

Background="{TemplateBinding Panel.Background}"

This is used line inside of the definition of a ControlTemplate redefining the look&Feel of an expander. (The ControlTemplate TargetType=Expander)

As the expander class does not have a Panel Property, I would like to understand where the Panel.Background will come from when the control template will be applied.
I thought of an attached property, but in XAML I cannot write something like:

<Expander Panel.Background ="..." />

Hence the expander class does not seem to have the Panel.Background attached property.


问:
In limited memory, use Apache POI to write data in specified rows and columns to an excel file that already has a large amount of data
I want to append data on an existing excel file, my code is as follows:

XSSFWorkbook book = new XSSFWorkbook("/my.xlsx");
Sheet sheet = book.getSheetAt(1);
//do something

```
<p>But this file already has a lot of data, so I get out of memory error.</p>
<p>I know it is possible to use <code>SXSSFWorkbook</code>, but this doesn't work for me, because it still loads the existing data into memory:</p>
<pre class="lang-java prettyprint-override"><code>new SXSSFWorkbook(new XSSFWorkbook("/my.xlsx"));
</code>```

How can I solve this problem with limited memory? thanks in advance.

As mentioned above, I hope that I can write data in specified rows and columns to an excel file that already has a large amount of data in limited memory.

Body:
I want to append data on an existing excel file, my code is as follows:

XSSFWorkbook book = new XSSFWorkbook("/my.xlsx");
Sheet sheet = book.getSheetAt(1);
//do something

But this file already has a lot of data, so I get out of memory error.

I know it is possible to use SXSSFWorkbook, but this doesn't work for me, because it still loads the existing data into memory:

new SXSSFWorkbook(new XSSFWorkbook("/my.xlsx"));

How can I solve this problem with limited memory? thanks in advance.

As mentioned above, I hope that I can write data in specified rows and columns to an excel file that already has a large amount of data in limited memory.


问:
Kafka Message loss when Kafkaserver goes down
I have a scenario that when Kafka server or Zookeeper both goes down, but the producer application trying to send a message to Kafka broker.

When the Kafka broker or Zookeeper comes online, messages is getting loss,  and i see the producer delivery result offset has  Offset: -1001 and Partition [Any]

Below are my configuration to reproduce

```<code>new ProducerConfig
{
    BootstrapServers = <BROKET_END_POINT>,
    MessageMaxBytes = 20971520,
    MessageCopyMaxBytes = 20971520,
    LogConnectionClose = false,
    BrokerAddressFamily = BrokerAddressFamily.V4,
    ConnectionsMaxIdleMs = 0,
    //https://github.com/Azure/azure-event-hubs-for-kafka/issues/139
    SocketKeepaliveEnable = true,
    MetadataMaxAgeMs = 180000,
    //https://learn.microsoft.com/en-us/azure/event-hubs/apache-kafka-configurations
    RequestTimeoutMs = 60000,
    MessageTimeoutMs = 0,
    MessageSendMaxRetries = int.MaxValue,
    RetryBackoffMs = 100,
    EnableIdempotence = true,
    Acks = Acks.All,
    BatchSize = 2000000,
    LingerMs = 0,
    CompressionType = CompressionType.Gzip
    SocketNagleDisable = true
};
</code>```

I used the above setting to produce the message using Confluent kafka nuget package version 1.8.2 from .Net code.

Appreciate your inputs in advance

Body:
I have a scenario that when Kafka server or Zookeeper both goes down, but the producer application trying to send a message to Kafka broker.

When the Kafka broker or Zookeeper comes online, messages is getting loss,  and i see the producer delivery result offset has  Offset: -1001 and Partition [Any]

Below are my configuration to reproduce

new ProducerConfig
{
    BootstrapServers = <BROKET_END_POINT>,
    MessageMaxBytes = 20971520,
    MessageCopyMaxBytes = 20971520,
    LogConnectionClose = false,
    BrokerAddressFamily = BrokerAddressFamily.V4,
    ConnectionsMaxIdleMs = 0,
    //https://github.com/Azure/azure-event-hubs-for-kafka/issues/139
    SocketKeepaliveEnable = true,
    MetadataMaxAgeMs = 180000,
    //https://learn.microsoft.com/en-us/azure/event-hubs/apache-kafka-configurations
    RequestTimeoutMs = 60000,
    MessageTimeoutMs = 0,
    MessageSendMaxRetries = int.MaxValue,
    RetryBackoffMs = 100,
    EnableIdempotence = true,
    Acks = Acks.All,
    BatchSize = 2000000,
    LingerMs = 0,
    CompressionType = CompressionType.Gzip
    SocketNagleDisable = true
};

I used the above setting to produce the message using Confluent kafka nuget package version 1.8.2 from .Net code.

Appreciate your inputs in advance


问:
ISO C++ forbids converting string to char*
The below is just a brief part of my code. And when I run it, it gives me the warning that ISO C++ forbids converting string to char* for visual studio code and exits with code 1. Is there a way I can ignore the warning to run the code?

```<code>
Class Airport
{
public:
    Airport(char *code, char *name);
}
</code>```
```<code>Airport::Airport(char *code, char *name)
{
    airport_code = new char[20];
    strcpy(airport_code, code);
    airport_name = new char[20];
    strcpy(airport_name, name);
}
</code>```
```<code>int main() {

    Airport *lax = new Airport("LAX", "LA");

}
</code>```

I saw on other stackoverflow posts that changing char to const char will solve the problem. But because the values will need to be changed using other predefined functions, it won't be the answer that I need.

Body:
The below is just a brief part of my code. And when I run it, it gives me the warning that ISO C++ forbids converting string to char* for visual studio code and exits with code 1. Is there a way I can ignore the warning to run the code?

Class Airport
{
public:
    Airport(char *code, char *name);
}

Airport::Airport(char *code, char *name)
{
    airport_code = new char[20];
    strcpy(airport_code, code);
    airport_name = new char[20];
    strcpy(airport_name, name);
}

int main() {

    Airport *lax = new Airport("LAX", "LA");

}

I saw on other stackoverflow posts that changing char to const char will solve the problem. But because the values will need to be changed using other predefined functions, it won't be the answer that I need.


问:
How to set custom "font_path" in python WordCloud App in Heroku?
I am making a fastapi app in Heroku with Python WordCloud package.

In my local test environment, I set my "font_path" like this code.

```<code>from wordcloud import WordCloud

wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf')
</code>```

Then, How Should I set my "font_path" in Heroku environment?

I tried to set font_path=None, and it works to English.(by default font(DroidSansMono)).

But, in my case, I should use custom font instead of default font.
Because I need to make WordCloud in Korean language.

Body:
I am making a fastapi app in Heroku with Python WordCloud package.

In my local test environment, I set my "font_path" like this code.

from wordcloud import WordCloud

wc = WordCloud(font_path='C:/Windows/Fonts/malgun.ttf')

Then, How Should I set my "font_path" in Heroku environment?

I tried to set font_path=None, and it works to English.(by default font(DroidSansMono)).

But, in my case, I should use custom font instead of default font.
Because I need to make WordCloud in Korean language.


问:
Parse() Version Number with a groovy? [P2]
Thanks in advance!
If it helps, this is my initial post.
As an input, I have this json:

```<code>{
    "BidId": "ID1088622222",
    "ItemNumber": "4.3.9",
    "CodiceNegoziazione": "Doc104222222",
    "CreationDate": "Wed, 15 Jun, 2022",
    "ProjectId": "WS1042222222",
    "ProjectOwner": "Silvia Gani",
    "ProjectTitle": "gara import Europa Y2022-2023",
    "CompanyCode": "A222 Olivetti",
    "PurchasingOrganization": "",
    "PurchasingGroup": "",
    "PaymentTerms": "",
    "Currency": "EUR",
    "EventType": "RFP",
    "EventOwner": "Silvia Gani",
    "EventId": "Doc1042222222",
    "EventTitle": "gara Import Europa Y2022-2023",
    "SupplierOrgName": "ARCESE",
    "SupplierOrgId": "buyersystemid:acm_2222",
    "SectionLot": "GERMANIA (Emmer)",
    "ItemName": "CAMION COMPLETO (EURO)",
    "Type": "Line Item",
    "SubmissionDate": "Mon, 4 Jul, 2022",
    "Price": "1530",
    "Quantity": "1",
    "ExtendedPrice": "1530",
    "MaterialGroup": "",
    "RequestedDeliveryDate": "",
    "BidCurrency": "EUR",
    "BidExtendedPrice": "1530",
    "BidSavings": "0",
    "BidPrice": "1530",
    "AwardAllocationPercentage": "100"
}

</code>```

I would like to adjust this part of code:

```<code>class Version {
   int major
   Integer minor, patch
   @Override String toString() {
       return [major, minor, patch].findAll().join('.')
   }
}

def parseVersion(String versionString) {
    if (!versionString) return null
    int[] tokens = versionString.split(/\./).collect { it as int }
    return new Version(
        major: tokens[0],
        minor: tokens.length > 1 ? tokens[1] : null,
        patch: tokens.length > 2 ? tokens[2] : null,
    )
}

class Payload {
   String ItemNumber
}

Payload payload = new Payload(ItemNumber: "2.4")
Version version = parseVersion(payload.ItemNumber?.trim())
printf("Major version : %d%n", version.major)
printf("Minor version : %s%n", version.minor ?: "<UNSET>")
printf("Patch version : %s%n", version.patch ?: "<UNSET>")
printf("Full version  : %s%n", version)
</code>```

In this groovy script:

```<code>import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*
def Message processData(Message message) {

//Body
def body = message.getBody(String.class);

def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)

def ItemNumber = list.get("ItemNumber")
def Price = list.get("Price")
def Quantity = list.get("Quantity")
def ExtendedPrice = list.get("ExtendedPrice")
def BidExtendedPrice = list.get("BidExtendedPrice")
def BidTotalCost = list.get("BidTotalCost")
def BidSavings = list.get("BidSavings")
def BidPrice = list.get("BidPrice")
def RfqItemNumber = list.get("RfqItemNumber")
def AwardAllocationPercentage = list.get("AwardAllocationPercentage")

if (ItemNumber?.trim()){
    list.ItemNumber = Double.parseDouble(ItemNumber.toString());
}

if (Price?.trim()){
    list.Price = Double.parseDouble(Price.toString());
}

if (Quantity?.trim()){
    list.Quantity= Double.parseDouble(Quantity.toString());
}

if (ExtendedPrice?.trim()){
    list.ExtendedPrice= Double.parseDouble(ExtendedPrice.toString());
}

if (BidExtendedPrice?.trim()){
    list.BidExtendedPrice= Double.parseDouble(BidExtendedPrice.toString());
}

if (BidTotalCost?.trim()){
    list.BidTotalCost= Double.parseDouble(BidTotalCost.toString())
}

if (BidSavings?.trim()){
    list.BidSavings= Double.parseDouble(BidSavings.toString());
}

if (BidPrice?.trim()){
    list.BidPrice= Double.parseDouble(BidPrice.toString());
}

if (RfqItemNumber?.trim() && RfqItemNumber != 'null'){
    list.RfqItemNumber= Integer.parseInt(RfqItemNumber.toString());
}else if (RfqItemNumber == 'null'){
    list.RfqItemNumber = null
}

if (AwardAllocationPercentage?.trim()){
    list.AwardAllocationPercentage= Double.parseDouble(AwardAllocationPercentage.toString());
}

def jsonOP = JsonOutput.toJson(list)

message.setBody(jsonOP)
return message;
}
</code>```

The goal is to parse the field ItemNumber. (From "ItemNumber": "4.4.5" --> "ItemNumber": 4.4.5)

The desired result:

```<code>{"BidId":"ID1088625754","ItemNumber":4.4.5,"CodiceNegoziazione":"Doc1042163109","CreationDate":"Wed, 15 Jun, 2022","ProjectId":"WS1042082696","ProjectOwner":"Silvia Ganio Mego","ProjectTitle":"gara import Europa Y2022-2023","CompanyCode":"A200 Olivetti S.p.A.","PurchasingOrganization":"","PurchasingGroup":"","PaymentTerms":"","Currency":"EUR","EventType":"RFP","EventOwner":"Silvia Ganio Mego","EventId":"Doc1042163109","EventTitle":"gara Import Europa Y2022-2023","SupplierOrgName":"ARCESE TRASPORTI S.P.A.","SupplierOrgId":"buyersystemid:acm_36628101|sap:0000333441|networkid:an01009585103","SectionLot":"GERMANIA (Emmerich)","ItemName":"CAMION COMPLETO (EURO)","Type":"Line Item","SubmissionDate":"Mon, 4 Jul, 2022","Price":1530.0,"Quantity":1.0,"ExtendedPrice":1530.0,"MaterialGroup":"","RequestedDeliveryDate":"","BidCurrency":"EUR","BidExtendedPrice":1530.0,"BidSavings":0.0,"BidPrice":1530.0,"AwardAllocationPercentage":100.0}
</code>```

I tried to adjust the above part of code in the groovy but I still get "ItemNumber": "4.4.5" .
If I try the code in a groovy ide it works fine though. I am not so familiar with all of this, not so long in this area.

Body:
Thanks in advance!
If it helps, this is my initial post.
As an input, I have this json:

{
    "BidId": "ID1088622222",
    "ItemNumber": "4.3.9",
    "CodiceNegoziazione": "Doc104222222",
    "CreationDate": "Wed, 15 Jun, 2022",
    "ProjectId": "WS1042222222",
    "ProjectOwner": "Silvia Gani",
    "ProjectTitle": "gara import Europa Y2022-2023",
    "CompanyCode": "A222 Olivetti",
    "PurchasingOrganization": "",
    "PurchasingGroup": "",
    "PaymentTerms": "",
    "Currency": "EUR",
    "EventType": "RFP",
    "EventOwner": "Silvia Gani",
    "EventId": "Doc1042222222",
    "EventTitle": "gara Import Europa Y2022-2023",
    "SupplierOrgName": "ARCESE",
    "SupplierOrgId": "buyersystemid:acm_2222",
    "SectionLot": "GERMANIA (Emmer)",
    "ItemName": "CAMION COMPLETO (EURO)",
    "Type": "Line Item",
    "SubmissionDate": "Mon, 4 Jul, 2022",
    "Price": "1530",
    "Quantity": "1",
    "ExtendedPrice": "1530",
    "MaterialGroup": "",
    "RequestedDeliveryDate": "",
    "BidCurrency": "EUR",
    "BidExtendedPrice": "1530",
    "BidSavings": "0",
    "BidPrice": "1530",
    "AwardAllocationPercentage": "100"
}

I would like to adjust this part of code:

class Version {
   int major
   Integer minor, patch
   @Override String toString() {
       return [major, minor, patch].findAll().join('.')
   }
}

def parseVersion(String versionString) {
    if (!versionString) return null
    int[] tokens = versionString.split(/\./).collect { it as int }
    return new Version(
        major: tokens[0],
        minor: tokens.length > 1 ? tokens[1] : null,
        patch: tokens.length > 2 ? tokens[2] : null,
    )
}

class Payload {
   String ItemNumber
}

Payload payload = new Payload(ItemNumber: "2.4")
Version version = parseVersion(payload.ItemNumber?.trim())
printf("Major version : %d%n", version.major)
printf("Minor version : %s%n", version.minor ?: "<UNSET>")
printf("Patch version : %s%n", version.patch ?: "<UNSET>")
printf("Full version  : %s%n", version)

In this groovy script:

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*
def Message processData(Message message) {

//Body
def body = message.getBody(String.class);

def jsonSlurper = new JsonSlurper()
def list = jsonSlurper.parseText(body)

def ItemNumber = list.get("ItemNumber")
def Price = list.get("Price")
def Quantity = list.get("Quantity")
def ExtendedPrice = list.get("ExtendedPrice")
def BidExtendedPrice = list.get("BidExtendedPrice")
def BidTotalCost = list.get("BidTotalCost")
def BidSavings = list.get("BidSavings")
def BidPrice = list.get("BidPrice")
def RfqItemNumber = list.get("RfqItemNumber")
def AwardAllocationPercentage = list.get("AwardAllocationPercentage")

if (ItemNumber?.trim()){
    list.ItemNumber = Double.parseDouble(ItemNumber.toString());
}

if (Price?.trim()){
    list.Price = Double.parseDouble(Price.toString());
}

if (Quantity?.trim()){
    list.Quantity= Double.parseDouble(Quantity.toString());
}

if (ExtendedPrice?.trim()){
    list.ExtendedPrice= Double.parseDouble(ExtendedPrice.toString());
}

if (BidExtendedPrice?.trim()){
    list.BidExtendedPrice= Double.parseDouble(BidExtendedPrice.toString());
}

if (BidTotalCost?.trim()){
    list.BidTotalCost= Double.parseDouble(BidTotalCost.toString())
}

if (BidSavings?.trim()){
    list.BidSavings= Double.parseDouble(BidSavings.toString());
}

if (BidPrice?.trim()){
    list.BidPrice= Double.parseDouble(BidPrice.toString());
}

if (RfqItemNumber?.trim() && RfqItemNumber != 'null'){
    list.RfqItemNumber= Integer.parseInt(RfqItemNumber.toString());
}else if (RfqItemNumber == 'null'){
    list.RfqItemNumber = null
}

if (AwardAllocationPercentage?.trim()){
    list.AwardAllocationPercentage= Double.parseDouble(AwardAllocationPercentage.toString());
}

def jsonOP = JsonOutput.toJson(list)

message.setBody(jsonOP)
return message;
}

The goal is to parse the field ItemNumber. (From "ItemNumber": "4.4.5" --> "ItemNumber": 4.4.5)

The desired result:

{"BidId":"ID1088625754","ItemNumber":4.4.5,"CodiceNegoziazione":"Doc1042163109","CreationDate":"Wed, 15 Jun, 2022","ProjectId":"WS1042082696","ProjectOwner":"Silvia Ganio Mego","ProjectTitle":"gara import Europa Y2022-2023","CompanyCode":"A200 Olivetti S.p.A.","PurchasingOrganization":"","PurchasingGroup":"","PaymentTerms":"","Currency":"EUR","EventType":"RFP","EventOwner":"Silvia Ganio Mego","EventId":"Doc1042163109","EventTitle":"gara Import Europa Y2022-2023","SupplierOrgName":"ARCESE TRASPORTI S.P.A.","SupplierOrgId":"buyersystemid:acm_36628101|sap:0000333441|networkid:an01009585103","SectionLot":"GERMANIA (Emmerich)","ItemName":"CAMION COMPLETO (EURO)","Type":"Line Item","SubmissionDate":"Mon, 4 Jul, 2022","Price":1530.0,"Quantity":1.0,"ExtendedPrice":1530.0,"MaterialGroup":"","RequestedDeliveryDate":"","BidCurrency":"EUR","BidExtendedPrice":1530.0,"BidSavings":0.0,"BidPrice":1530.0,"AwardAllocationPercentage":100.0}

I tried to adjust the above part of code in the groovy but I still get "ItemNumber": "4.4.5" .
If I try the code in a groovy ide it works fine though. I am not so familiar with all of this, not so long in this area.


问:
How to get users in Enterprise Github org?
```<code>const users = await octokit.users.list();
</code>```

How can you use octokit to list users in a organization?

For example if your enterprise github is

github.your-company.com

and within this github you have multiple organization

how do you display users per org?

Also I can search for all users using search.users({q:"type:user"})

however when I try /api/v3/users it shows less results.

WHY IS THAT?

Body:
const users = await octokit.users.list();

How can you use octokit to list users in a organization?

For example if your enterprise github is

github.your-company.com

and within this github you have multiple organization

how do you display users per org?

Also I can search for all users using search.users({q:"type:user"})

however when I try /api/v3/users it shows less results.

WHY IS THAT?


问:
Error when switching user account using the command firebase login:use email
I am getting this error when running firebase login:use email@gmail.com

```<code>Could not determine active Firebase project directory
</code>```

firebase --version ====> 11.16.0

Body:
I am getting this error when running firebase login:use email@gmail.com

Could not determine active Firebase project directory

firebase --version ====> 11.16.0


问:
Catch external requests in Laravel Telescope
Is it possible to catch external requests in Laravel Telescope. I'm new to telescope and I've done my research but I couldn't find any blog/article that mentioned this except this but it didn't work for me

I've Installed telescope on my app according to the documentation, Iv'e created a new watcher called GuzzleRequestWatcher and registered it under config/telescope.php, I've also created a test route that sends an http::post message to this. Telescope is catching my API request and recording it under requests as shown in the screenshot but I need it to see the URL the request is hitting not only the route for example rather than showing in Path '/api/v1/guzzle-test' I need it to show the URL I'm requesting 'http://httpbin.org/anything'.screenshot

<?php

declare(strict_types=1);

namespace App\Telescope\Watchers;

use Closure;
use GuzzleHttp\Client;
use GuzzleHttp\TransferStats;
use Illuminate\Foundation\Application;
use Illuminate\Support\Facades\Log;
use Laravel\Telescope\IncomingEntry;
use Laravel\Telescope\Telescope;
use Laravel\Telescope\Watchers\FetchesStackTrace;
use Laravel\Telescope\Watchers\Watcher;

final class GuzzleRequestWatcher extends Watcher
{
    use FetchesStackTrace;

    public function register($app)
    {
        $app->bind(Client::class, $this->buildClient($app));
    }

    private function buildClient(Application $app): Closure
    {
        return static function (Application $app): Client {
            $config = $app['config']['guzzle'] ?? [];

            if (Telescope::isRecording()) {
                $config['on_stats'] = function (TransferStats $stats) {
                    $caller = $this->getCallerFromStackTrace();
                    Telescope::recordQuery(
                        IncomingEntry::make([
                            'connection' => 'guzzle',
                            'bindings' => [],
                            'sql' => (string) $stats->getEffectiveUri(),
                            'time' => number_format(
                                $stats->getTransferTime() * 1000,
                                2,
                                ''
                            ),
                            'slow' => $stats->getTransferTime() > 1,
                            'file' => $caller['file'],
                            'line' => $caller['line'],
                            'hash' => md5((string) $stats->getEffectiveUri()),
                        ])
                    );
                };
            }

            return new Client(
                $config
            );
        };
    }
}```


问:
Flutter widgets so confusing
Why is flutter widgets so incompatible with each other?

Why can't have const TextField inside Row's children?

I'm using sliverboxadapter as parent to below widget.

```<code>Column(
      children: [
        const TextField( // IF I PUT HERE NO EXCEPTION
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'Enter answer',
          ),
        ),
        Row(
          children: [
          const TextField( // IF I PUT HERE ERRORS
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'Enter answer',
          ),
        ),
            ElevatedButton(
              onPressed: () {
              },
              child: const Text("Check"),
            ),
            ElevatedButton(
              onPressed: () {
              },
              child: const Text("Refresh"),
            ),
          ],
        ),
      ],
    );
</code>```

Title: Flutter widgets so confusing

Body:
Why is flutter widgets so incompatible with each other?

Why can't have const TextField inside Row's children?

I'm using sliverboxadapter as parent to below widget.

Column(
      children: [
        const TextField( // IF I PUT HERE NO EXCEPTION
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'Enter answer',
          ),
        ),
        Row(
          children: [
          const TextField( // IF I PUT HERE ERRORS
          textAlign: TextAlign.center,
          decoration: InputDecoration(
            border: OutlineInputBorder(),
            hintText: 'Enter answer',
          ),
        ),
            ElevatedButton(
              onPressed: () {
              },
              child: const Text("Check"),
            ),
            ElevatedButton(
              onPressed: () {
              },
              child: const Text("Refresh"),
            ),
          ],
        ),
      ],
    );


问:
UnitTest Case for Flask application
Writting UniTTest For Flask Application
I have a simple Flask Application below , flask application will work perfectly fine without any issues

```<code>import sys , os , os.path , time , datetime , json , logging, warnings
from os import listdir
from os.path import isfile, join
from flask_wtf.csrf import CSRFProtect

from flask import Flask
from flask import render_template
from flask import request

from datetime import datetime
from logging import FileHandler
from logging import Formatter

# --> Required Host and Env
_cloudhost='dev.net'
_cloudenv='dev'
_portNumber=4444

#CRF Compliant / (.)
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)

@app.route('/')
@app.route('/index')
def index():
    project = "CFTP - TBRP & TBLP "
    framework = "Publish Framework"
    version = '0.1'
    hostname = os.popen("echo $(hostname)").read().split('\n')[0]
    return render_template('index.html', title=project , description=f'{project} : {framework} v - {version}' , hostname=hostname , logFile=readlogs(), get_env=_cloudenv)

app.run(host=_cloudhost, port=_portNumber)
</code>```

UnitTest Function . I am struggling to understand on how i can create unit test cases for flask application. Inside my unittest file which i created , i was wondering if i am doing this right .
1 -> To test the csrf if that i included above and also on how i can test my index page can result as pass
test_flask.py

```<code>import unittest , sys , tempfile, os , json , shutil
from unittest import mock
from subprocess import Popen, PIPE
import logging

with mock.patch.dict(os.environ, {'PROJECT_FOLDER':'CitiFTP Reports','RPM_ENVIRONMENT': 'DEV', 'HOST_NAME': 'sd-nzvp-czog.nam.nsroot.net', 'USER': 'citiftptabhyper','TABLEAU_PUBLISH_TYPE':'TABCMD','TABCMD_PATH':'/home/citiftptabhyper/tabcmd','CYBERARK_TYPE':'DYNAMIC','JOB_TYPE':'workbook_TP','JOB_FILE':'publish_workbook_TP','RESTAPI_LOG_TYPE':'TP'}):
    sys.path.insert(2, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/src')
    sys.path.insert(1, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/app')
    import env_conf as conf
    import run_flask as flk_app
    from run_flask import app

class test_tbrp_case(unittest.TestCase):

    def setUp(self):
        self.ctx = app.app_context()
        self.ctx.push()
        self.client = app.test_client()

    def tearDown(self):
        self.ctx.pop()

    def test_home(self): ## Fail
        response = self.client.post("/index", data={"title": "CFTP - TBRP & TBLP "})
        assert response.status_code == 200

    ## test flask port used -- PASS
    def  test_port(self):
        self.assertEqual(flk_app._portNumber,4444)

    ## Test host is returning the same value -- PASS
    def test_host(self):
        self.assertEqual(flk_app._cloudhost,conf.FLASK_CONFIGURATION.get('ENV_URL'))

    def test_csrf(self):
        pass

if __name__=='__main__':
    unittest.main()
</code>```

Title: UnitTest Case for Flask application

Body:
Writting UniTTest For Flask Application
I have a simple Flask Application below , flask application will work perfectly fine without any issues

import sys , os , os.path , time , datetime , json , logging, warnings
from os import listdir
from os.path import isfile, join
from flask_wtf.csrf import CSRFProtect

from flask import Flask
from flask import render_template
from flask import request

from datetime import datetime
from logging import FileHandler
from logging import Formatter

# --> Required Host and Env
_cloudhost='dev.net'
_cloudenv='dev'
_portNumber=4444

#CRF Compliant / (.)
app = Flask(__name__)
csrf = CSRFProtect()
csrf.init_app(app)

@app.route('/')
@app.route('/index')
def index():
    project = "CFTP - TBRP & TBLP "
    framework = "Publish Framework"
    version = '0.1'
    hostname = os.popen("echo $(hostname)").read().split('\n')[0]
    return render_template('index.html', title=project , description=f'{project} : {framework} v - {version}' , hostname=hostname , logFile=readlogs(), get_env=_cloudenv)

app.run(host=_cloudhost, port=_portNumber)

UnitTest Function . I am struggling to understand on how i can create unit test cases for flask application. Inside my unittest file which i created , i was wondering if i am doing this right .
1 -> To test the csrf if that i included above and also on how i can test my index page can result as pass
test_flask.py

import unittest , sys , tempfile, os , json , shutil
from unittest import mock
from subprocess import Popen, PIPE
import logging

with mock.patch.dict(os.environ, {'PROJECT_FOLDER':'CitiFTP Reports','RPM_ENVIRONMENT': 'DEV', 'HOST_NAME': 'sd-nzvp-czog.nam.nsroot.net', 'USER': 'citiftptabhyper','TABLEAU_PUBLISH_TYPE':'TABCMD','TABCMD_PATH':'/home/citiftptabhyper/tabcmd','CYBERARK_TYPE':'DYNAMIC','JOB_TYPE':'workbook_TP','JOB_FILE':'publish_workbook_TP','RESTAPI_LOG_TYPE':'TP'}):
    sys.path.insert(2, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/src')
    sys.path.insert(1, 'C:/Users/mm13854/Desktop/FileCopy_Dec_122/cftp_tableau_filecopy/deploy/app')
    import env_conf as conf
    import run_flask as flk_app
    from run_flask import app

class test_tbrp_case(unittest.TestCase):

    def setUp(self):
        self.ctx = app.app_context()
        self.ctx.push()
        self.client = app.test_client()

    def tearDown(self):
        self.ctx.pop()

    def test_home(self): ## Fail
        response = self.client.post("/index", data={"title": "CFTP - TBRP & TBLP "})
        assert response.status_code == 200

    ## test flask port used -- PASS
    def  test_port(self):
        self.assertEqual(flk_app._portNumber,4444)

    ## Test host is returning the same value -- PASS
    def test_host(self):
        self.assertEqual(flk_app._cloudhost,conf.FLASK_CONFIGURATION.get('ENV_URL'))

    def test_csrf(self):
        pass

if __name__=='__main__':
    unittest.main()


问:
Display data on oled 1.3 inch screen after 5 seconds but update data on google sheet after every 15 minutes
I am working with DHT22 sensor and NodeMCU to get temperature and humidity values. I want to store values on google sheet and also display values on 1.3 inch oled display. I have used millis() to do multitasking but still not able to do multitask. Both task (display on oled and update on google sheet) take place after 1 minute interval. Please suggest what modifications can be done to code.</p>
```<code>#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include "DHT.h"
#include <OneWire.h>
#include <SPI.h>
#define DHTTYPE DHT22 // type of the temperature sensor
#include "SH1106Wire.h"
SH1106Wire display (0x3C, D1, D2);

unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 4000;           // interval at which to blink (milliseconds)

const int DHTPin = 14; //--> The pin used for the DHT11 sensor is Pin D1 = GPIO5
DHT dht(DHTPin, DHTTYPE); //--> Initialize DHT sensor, DHT dht(Pin_used, Type_of_DHT_Sensor);
#define ON_Board_LED 2  //--> Defining an On Board LED, used for indicators when the process of       connecting to a wifi router
const char* ssid = "OPPO F11 Pro"; //--> Your wifi name or SSID.
//const char* ssid = "SWE-SEEIT";
const char* host = "script.google.com";
const int httpsPort = 443;

WiFiClientSecure client; //--> Create a WiFiClientSecure object.
String GAS_ID = "AKfycbxoDW-7HxrMx90MH7ggsM_0DOTz3gIj-Z06kWTGOwOaoFoaUxW4xfGn_8L7WJh6LX3o"; //--> spreadsheet script ID

void setup() {
dht.begin();
delay(500);
display.init();
display.flipScreenVertically();
Serial.begin(115200);
WiFi.begin(ssid, NULL); //--> Connect to your WiFi router

pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

while (WiFi.status() != WL_CONNECTED) {
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.

client.setInsecure();
}

void loop() {
int h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor !");
delay(500);
return;
}
String Temp = "Temperature : " + String(t) + " °C";
String Humi = "Humidity : " + String(h) + " %";
Serial.println(Temp);
Serial.println(Humi);
servosweep();
sendData(t, h);
delay(60000) ;
}

void servosweep(){
int h = dht.readHumidity();
float t = dht.readTemperature();

unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
display.setFont(ArialMT_Plain_16);
display.clear();
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString (60,0,"Temperature (°C)");
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,16,String(t));
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,32,"Humidity (%)");
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,48,String(h));
display.display();
}

}

// Subroutine for sending data to Google Sheets
void sendData(float tem, int hum) {
//Serial.println("==========");
//Serial.print("connecting to ");
//Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
//----------------------------------------Processing data and sending data
String string_temperature =  String(tem);
String string_humidity =  String(hum, DEC);
String url = "/macros/s/" + GAS_ID + "/exec?temperature=" + string_temperature + "&humidity=" +   string_humidity;
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
     "Host: " + host + "\r\n" +
     "User-Agent: BuildFailureDetectorESP8266\r\n" +
     "Connection: close\r\n\r\n");

 //----------------------------------------Checking whether the data was sent successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
  //Serial.println("headers received");
  break;
}
}
String line = client.readStringUntil('\n');
}
</code>```

Body:
I am working with DHT22 sensor and NodeMCU to get temperature and humidity values. I want to store values on google sheet and also display values on 1.3 inch oled display. I have used millis() to do multitasking but still not able to do multitask. Both task (display on oled and update on google sheet) take place after 1 minute interval. Please suggest what modifications can be done to code.

#include <Wire.h>
#include <ESP8266WiFi.h>
#include <WiFiClientSecure.h>
#include "DHT.h"
#include <OneWire.h>
#include <SPI.h>
#define DHTTYPE DHT22 // type of the temperature sensor
#include "SH1106Wire.h"
SH1106Wire display (0x3C, D1, D2);

unsigned long previousMillis = 0;        // will store last time LED was updated
const long interval = 4000;           // interval at which to blink (milliseconds)

const int DHTPin = 14; //--> The pin used for the DHT11 sensor is Pin D1 = GPIO5
DHT dht(DHTPin, DHTTYPE); //--> Initialize DHT sensor, DHT dht(Pin_used, Type_of_DHT_Sensor);
#define ON_Board_LED 2  //--> Defining an On Board LED, used for indicators when the process of       connecting to a wifi router
const char* ssid = "OPPO F11 Pro"; //--> Your wifi name or SSID.
//const char* ssid = "SWE-SEEIT";
const char* host = "script.google.com";
const int httpsPort = 443;

WiFiClientSecure client; //--> Create a WiFiClientSecure object.
String GAS_ID = "AKfycbxoDW-7HxrMx90MH7ggsM_0DOTz3gIj-Z06kWTGOwOaoFoaUxW4xfGn_8L7WJh6LX3o"; //--> spreadsheet script ID

void setup() {
dht.begin();
delay(500);
display.init();
display.flipScreenVertically();
Serial.begin(115200);
WiFi.begin(ssid, NULL); //--> Connect to your WiFi router

pinMode(ON_Board_LED,OUTPUT); //--> On Board LED port Direction output
digitalWrite(ON_Board_LED, HIGH); //--> Turn off Led On Board

while (WiFi.status() != WL_CONNECTED) {
digitalWrite(ON_Board_LED, LOW);
delay(250);
digitalWrite(ON_Board_LED, HIGH);
delay(250);
}
digitalWrite(ON_Board_LED, HIGH); //--> Turn off the On Board LED when it is connected to the wifi router.

client.setInsecure();
}

void loop() {
int h = dht.readHumidity();
float t = dht.readTemperature();
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t)) {
Serial.println("Failed to read from DHT sensor !");
delay(500);
return;
}
String Temp = "Temperature : " + String(t) + " °C";
String Humi = "Humidity : " + String(h) + " %";
Serial.println(Temp);
Serial.println(Humi);
servosweep();
sendData(t, h);
delay(60000) ;
}

void servosweep(){
int h = dht.readHumidity();
float t = dht.readTemperature();

unsigned long currentMillis = millis();
if (currentMillis - previousMillis >= interval) {
// save the last time you blinked the LED
previousMillis = currentMillis;
display.setFont(ArialMT_Plain_16);
display.clear();
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString (60,0,"Temperature (°C)");
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,16,String(t));
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,32,"Humidity (%)");
display.setTextAlignment(TEXT_ALIGN_CENTER);
display.drawString(60,48,String(h));
display.display();
}

}

// Subroutine for sending data to Google Sheets
void sendData(float tem, int hum) {
//Serial.println("==========");
//Serial.print("connecting to ");
//Serial.println(host);
if (!client.connect(host, httpsPort)) {
Serial.println("connection failed");
return;
}
//----------------------------------------Processing data and sending data
String string_temperature =  String(tem);
String string_humidity =  String(hum, DEC);
String url = "/macros/s/" + GAS_ID + "/exec?temperature=" + string_temperature + "&humidity=" +   string_humidity;
client.print(String("GET ") + url + " HTTP/1.1\r\n" +
     "Host: " + host + "\r\n" +
     "User-Agent: BuildFailureDetectorESP8266\r\n" +
     "Connection: close\r\n\r\n");

 //----------------------------------------Checking whether the data was sent successfully or not
while (client.connected()) {
String line = client.readStringUntil('\n');
if (line == "\r") {
  //Serial.println("headers received");
  break;
}
}
String line = client.readStringUntil('\n');
}


问:
groupingBy a join in KTORM
I want to join a  N x M relation, returning all N, and a count of how many M are there:

```<code>SELECT N.*, COUNT(M.id) FROM N LEFT JOIN M ON N.id = M.n_id GROUP BY N.id
</code>```

but I don't see how.  Joining and aggregation seem to exclude each other, or are not implemented, or not documented (or I didn't find it).

Title: groupingBy a join in KTORM

Body:
I want to join a  N x M relation, returning all N, and a count of how many M are there:

SELECT N.*, COUNT(M.id) FROM N LEFT JOIN M ON N.id = M.n_id GROUP BY N.id

but I don't see how.  Joining and aggregation seem to exclude each other, or are not implemented, or not documented (or I didn't find it).


问:
Why React function component call WITHOUT state change
here is the code: https://codesandbox.io/s/interesting-mirzakhani-h38g1k

```<code>import "./styles.css";
import { useState } from "react";

export default function App() {
  const [state, setState] = useState(false);
  console.log("executed");
  return (
    <>
      <p>This component renders three (3) times:</p>
      <p>1) First time is initial render.</p>
      <p>
        2) Second time is when clicking the button for the first time to update
        state.
      </p>
      <p>
        <strong>
          3) Why does is render again when clicking the button second time and
          settings the same state again?
        </strong>
      </p>
      <p>Check console.</p>
      ```state: {String(state)}```
      <button onClick={() => setState(true)}>setState(true)</button>
    </>
  );
}

</code>```

And the situation here is:

initial (expected)

click the btn first time. State is updated and console. (expected)

click the btn second time, and state didn't change, but console again. (why?)

I found some source code about function dispatchSetState which is actually is setState in the demo.  And here is the critical code is shown as the img.

First time click the btn,  fiber.lanes === NoLanes is true, and then check the state is equal or not and then decide to update or not (objectIs).

Second time click the btn,  fiber.lanes === NoLanes is false, and it just skip the comparison between old state and new state. Then the React start update.

So, what is exactly fiber.lanes is in second time? I found it is 1 which is SyncLane. here is ALL I found in source code.

diagram

I still don't know why react did this.

Body:
here is the code: https://codesandbox.io/s/interesting-mirzakhani-h38g1k

import "./styles.css";
import { useState } from "react";

export default function App() {
  const [state, setState] = useState(false);
  console.log("executed");
  return (
    <>

This component renders three (3) times:

1) First time is initial render.

        2) Second time is when clicking the button for the first time to update
        state.

          3) Why does is render again when clicking the button second time and
          settings the same state again?

Check console.

state: {String(state)}

      <button onClick={() => setState(true)}>setState(true)</button>
    </>
  );
}

And the situation here is:

initial (expected)

click the btn first time. State is updated and console. (expected)

click the btn second time, and state didn't change, but console again. (why?)

I found some source code about function dispatchSetState which is actually is setState in the demo.  And here is the critical code is shown as the img.

First time click the btn,  fiber.lanes === NoLanes is true, and then check the state is equal or not and then decide to update or not (objectIs).

Second time click the btn,  fiber.lanes === NoLanes is false, and it just skip the comparison between old state and new state. Then the React start update.

So, what is exactly fiber.lanes is in second time? I found it is 1 which is SyncLane. here is ALL I found in source code.

diagram

I still don't know why react did this.


问:
How Pass uid and email to shared preference when signup in flutter?
In my code when signup then should pass and save uid and email in saveDataToSharedPreferences() method. saveDataToSharedPreferences method  also used for google signin then that's work nicely. But when signup using email password I want pass email and uid to same "saveDataToSharedPreferences() " method.(google signin saveDataToSharedPreferences method).

saveDataToSharedPreferences() method This has in SignInProvider class

```<code>class SignInProvider extends ChangeNotifier {
  //instantiate of  firebaseAuth, facebook and google

  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  final GoogleSignIn googleSignIn = GoogleSignIn();

  bool _isSignedIn = false;
  bool get isSignedIn => _isSignedIn;

  //hasError, errorCode, provider,uid,email,name,imageUrl
  bool _hasError = false;

  bool get hasError => _hasError;

  String? _errorCode;

  String? get errorCode => _errorCode;

  String? _uid;

  String? get uid => _uid;

  String? _email;

  String? get email => _email;

  Future saveDataToSharedPreferences() async {
    final SharedPreferences s = await SharedPreferences.getInstance();
    await s.setString('email', _email!);
    await s.setString('uid', _uid!);
    notifyListeners();
  }

  Future getDataFromSharedPreferences() async {
    final SharedPreferences s = await SharedPreferences.getInstance();
    _email = s.getString('email');
    _uid = s.getString('uid');
    notifyListeners();
  }
}
</code>```

email password signup method (postDetailsToFirestore() method)

```<code>  postDetailsToFirestore() async {
    // calling our fireStore
    //calling our user model
    // sending these values

    FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
    User? user = _auth.currentUser;
    final sp = context.read<SignInProvider>();

    UserModel userModel = UserModel();

    if (user != null) {
      //writing all the values
      userModel.email = user?.email;
      userModel.uid = user?.uid;

      await firebaseFirestore
          .collection("users")
          .doc(user?.uid)
          .set(userModel.toMap())
          .then((value) => sp
              .saveDataToSharedPreferences()
              .then((value) => sp.setSignIn().then((value) {})));

      Fluttertoast.showToast(msg: "Account created successfully ");
      Navigator.pushAndRemoveUntil(
          (context),
          MaterialPageRoute(builder: (context) => HomeScreen()),
          (route) => false);
    }
  }
</code>```

in postDetailsToFirestore() method added sp.saveDataToSharedPreferences() to pass uid and email to saveDataToSharedPreferences() in siginInProvider class.

email password signup has another model

```<code>class UserModel {
  String? uid;
  String? email;
  String? isSignedIn;

  UserModel({
    this.uid,
    this.email,
  });

  //receiving data from server
  factory UserModel.formMap(map) {
    return UserModel(
      uid: map['uid'],
      email: map['email'],
    );
  }

  // sending data to server

  Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
    };
  }
}
</code>```

when added sp.saveDataToSharedPreferences() in postDetailsToFirestore() then show this error.

How pass uid and email to saveDataToSharedPreferences() from in signup method?

Body:
In my code when signup then should pass and save uid and email in saveDataToSharedPreferences() method. saveDataToSharedPreferences method  also used for google signin then that's work nicely. But when signup using email password I want pass email and uid to same "saveDataToSharedPreferences() " method.(google signin saveDataToSharedPreferences method).

saveDataToSharedPreferences() method This has in SignInProvider class

class SignInProvider extends ChangeNotifier {
  //instantiate of  firebaseAuth, facebook and google

  final FirebaseAuth firebaseAuth = FirebaseAuth.instance;

  final GoogleSignIn googleSignIn = GoogleSignIn();

  bool _isSignedIn = false;
  bool get isSignedIn => _isSignedIn;

  //hasError, errorCode, provider,uid,email,name,imageUrl
  bool _hasError = false;

  bool get hasError => _hasError;

  String? _errorCode;

  String? get errorCode => _errorCode;

  String? _uid;

  String? get uid => _uid;

  String? _email;

  String? get email => _email;

  Future saveDataToSharedPreferences() async {
    final SharedPreferences s = await SharedPreferences.getInstance();
    await s.setString('email', _email!);
    await s.setString('uid', _uid!);
    notifyListeners();
  }

  Future getDataFromSharedPreferences() async {
    final SharedPreferences s = await SharedPreferences.getInstance();
    _email = s.getString('email');
    _uid = s.getString('uid');
    notifyListeners();
  }
}

email password signup method (postDetailsToFirestore() method)

  postDetailsToFirestore() async {
    // calling our fireStore
    //calling our user model
    // sending these values

    FirebaseFirestore firebaseFirestore = FirebaseFirestore.instance;
    User? user = _auth.currentUser;
    final sp = context.read<SignInProvider>();

    UserModel userModel = UserModel();

    if (user != null) {
      //writing all the values
      userModel.email = user?.email;
      userModel.uid = user?.uid;

      await firebaseFirestore
          .collection("users")
          .doc(user?.uid)
          .set(userModel.toMap())
          .then((value) => sp
              .saveDataToSharedPreferences()
              .then((value) => sp.setSignIn().then((value) {})));

      Fluttertoast.showToast(msg: "Account created successfully ");
      Navigator.pushAndRemoveUntil(
          (context),
          MaterialPageRoute(builder: (context) => HomeScreen()),
          (route) => false);
    }
  }

in postDetailsToFirestore() method added sp.saveDataToSharedPreferences() to pass uid and email to saveDataToSharedPreferences() in siginInProvider class.

email password signup has another model

class UserModel {
  String? uid;
  String? email;
  String? isSignedIn;

  UserModel({
    this.uid,
    this.email,
  });

  //receiving data from server
  factory UserModel.formMap(map) {
    return UserModel(
      uid: map['uid'],
      email: map['email'],
    );
  }

  // sending data to server

  Map<String, dynamic> toMap() {
    return {
      'uid': uid,
      'email': email,
    };
  }
}

when added sp.saveDataToSharedPreferences() in postDetailsToFirestore() then show this error.

How pass uid and email to saveDataToSharedPreferences() from in signup method?


问:
structures and assigning values. Why doesn't it set them all to B and gets cut?
```<code>#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h> //comment out ko muna pero gumagana yan
#include <unistd.h>

struct gameBoard
{
    char A[37];
};

void setBoard(struct gameBoard *GameBoard, int nBoardLength, int nBoardWidth)
{
    int i;
    int j;

    for(i = 0; i < nBoardWidth; i++)
    {
        for(j = 0; j < nBoardLength; j++)
        {
            if(j >= 1 && j <= 6 && i >= 2 && i <= 7)
                strcpy(&GameBoard->A[i - 2 + (6 * (j - 1))], "B");
        }
    }
}

int main(void)
{
    struct gameBoard GameBoard;

    int nBoardLength = 15;
    int nBoardWidth = 17;
    int i;

    setBoard(&GameBoard, nBoardLength, nBoardWidth);

    for(i = 0; i < 36; i++)
    {
        printf(" i = %d Q1 = (%c)", i, GameBoard.A[i]);
//      printf(" i = %d Q2 = (%c)", i, GameBoard.Quadrant2[i]);
//      printf(" i = %d Q3 = (%c)", i, GameBoard.Quadrant3[i]);
//      printf(" i = %d Q4 = (%c)", i, GameBoard.Quadrant4[i]);
        printf("\n");
    }

    return 0;
}
</code>```

I am trying to set the values of the structured array, and I'm testing it out right now with just B. But, it seems that when I try to set them all to a specific value, some just end up with a blank.

Body:
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <string.h>
#include <conio.h> //comment out ko muna pero gumagana yan
#include <unistd.h>

struct gameBoard
{
    char A[37];
};

void setBoard(struct gameBoard *GameBoard, int nBoardLength, int nBoardWidth)
{
    int i;
    int j;

    for(i = 0; i < nBoardWidth; i++)
    {
        for(j = 0; j < nBoardLength; j++)
        {
            if(j >= 1 && j <= 6 && i >= 2 && i <= 7)
                strcpy(&GameBoard->A[i - 2 + (6 * (j - 1))], "B");
        }
    }
}

int main(void)
{
    struct gameBoard GameBoard;

    int nBoardLength = 15;
    int nBoardWidth = 17;
    int i;

    setBoard(&GameBoard, nBoardLength, nBoardWidth);

    for(i = 0; i < 36; i++)
    {
        printf(" i = %d Q1 = (%c)", i, GameBoard.A[i]);
//      printf(" i = %d Q2 = (%c)", i, GameBoard.Quadrant2[i]);
//      printf(" i = %d Q3 = (%c)", i, GameBoard.Quadrant3[i]);
//      printf(" i = %d Q4 = (%c)", i, GameBoard.Quadrant4[i]);
        printf("\n");
    }

    return 0;
}

I am trying to set the values of the structured array, and I'm testing it out right now with just B. But, it seems that when I try to set them all to a specific value, some just end up with a blank.


问:
Cocoapods how to find out the minimum iOS deployment target for a specified version of a specified pod?
How can I find out the minimum iOS deployment target for a specified version of a specified pod? For example, how can I found out the iOS minimum deployment target for version 10.3.0 of the FirebaseRemoteConfig pod?


问:
Singleton pattern python
I'm trying to learn how to implement singleton pattern in python. It seems little bit difficult to implement singleton pattern in python.i don't know it's becauses of the nature of the language.

This is what i tried

```<code>class Singleton(object):
    _instance = None
    def __new__(cls):
        if cls._instance is not None:
            pass
        else:
            cls._instance = super().__new__(cls)
            return Singleton._instance
    def getInstance():
        return Singleton._instance
</code>```

Does this code will create a singleton pattern, if it does is it a proper/good approach if it not what is bad about this code. I've read some SO questions and looked at the python data model documentation and this what i could come up with i wanna know what is the best approach in python to create a singleton pattern

Title: Singleton pattern python

Body:
I'm trying to learn how to implement singleton pattern in python. It seems little bit difficult to implement singleton pattern in python.i don't know it's becauses of the nature of the language.

This is what i tried

class Singleton(object):
    _instance = None
    def __new__(cls):
        if cls._instance is not None:
            pass
        else:
            cls._instance = super().__new__(cls)
            return Singleton._instance
    def getInstance():
        return Singleton._instance

Does this code will create a singleton pattern, if it does is it a proper/good approach if it not what is bad about this code. I've read some SO questions and looked at the python data model documentation and this what i could come up with i wanna know what is the best approach in python to create a singleton pattern


问:
Why does BitBlt() Zoom in when copying the exact same pixels from the same bitmap onto itself?
I'm trying to make a window that copies the desktop, and mess around with the pixels on it. I do this by using BitBlt from the Desktop Handle to my Window handle. This works as expected -  a window is created which looks exactly like the desktop. However, when I use BitBlt() again to move a segment of pixels from my Window to another area of my Window, the pixels are zoomed in. Why does this happen and how do I fix it?

Here is the code, I have commented on the section where the issue seems to be coming from:

```<code>#include <windows.h>

int myWidth, myHeight;

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CREATE:
    {
        HDC DhWnd = GetDC(HWND_DESKTOP);
        HDC MhWnd = GetDC(hwnd);
        BitBlt(MhWnd, 0, 0, myWidth, myHeight, DhWnd, 0, 0, SRCCOPY);
        ShowWindow(hwnd, SW_SHOW);
        BitBlt(MhWnd, 300, 0, 100, 500, MhWnd, 300, 0, SRCCOPY);

        /*^^^^ The above segment zooms in the pixels despite copy pasting the EXACT
       SAME coordinates of the bitmap onto itself. ^^^^*/

        ReleaseDC(hwnd, DhWnd);
        ReleaseDC(hwnd, MhWnd);
        return 0;
    }
    case WM_PAINT:
        ValidateRect(hwnd, NULL);
        return 0;

    case WM_CLOSE:
    case WM_DESTROY:
        DestroyWindow(hwnd);
        PostQuitMessage(0);
        return 0;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    RECT Drc;
    MSG msg;
    HWND DhWnd = GetDesktopWindow();
    HWND MyhWnd;
    GetWindowRect(DhWnd, &Drc);
    myWidth = Drc.right - Drc.left;
    myHeight = Drc.bottom - Drc.top;

    WNDCLASS wc;
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL,IDC_ARROW);
    wc.hbrBackground = NULL;
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "MyWindow";

    if (!RegisterClass(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    MyhWnd = CreateWindow("MyWindow", NULL, WS_POPUP, 0, 0, myWidth, myHeight, NULL, NULL, hInstance, NULL);
    if (MyhWnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;

}
</code>```

Body:
I'm trying to make a window that copies the desktop, and mess around with the pixels on it. I do this by using BitBlt from the Desktop Handle to my Window handle. This works as expected -  a window is created which looks exactly like the desktop. However, when I use BitBlt() again to move a segment of pixels from my Window to another area of my Window, the pixels are zoomed in. Why does this happen and how do I fix it?

Here is the code, I have commented on the section where the issue seems to be coming from:

#include <windows.h>

int myWidth, myHeight;

LRESULT CALLBACK WndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    switch (uMsg)
    {
    case WM_CREATE:
    {
        HDC DhWnd = GetDC(HWND_DESKTOP);
        HDC MhWnd = GetDC(hwnd);
        BitBlt(MhWnd, 0, 0, myWidth, myHeight, DhWnd, 0, 0, SRCCOPY);
        ShowWindow(hwnd, SW_SHOW);
        BitBlt(MhWnd, 300, 0, 100, 500, MhWnd, 300, 0, SRCCOPY);

        /*^^^^ The above segment zooms in the pixels despite copy pasting the EXACT
       SAME coordinates of the bitmap onto itself. ^^^^*/

        ReleaseDC(hwnd, DhWnd);
        ReleaseDC(hwnd, MhWnd);
        return 0;
    }
    case WM_PAINT:
        ValidateRect(hwnd, NULL);
        return 0;

    case WM_CLOSE:
    case WM_DESTROY:
        DestroyWindow(hwnd);
        PostQuitMessage(0);
        return 0;
    default:
        return DefWindowProc(hwnd, uMsg, wParam, lParam);
    }

}

int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
{
    RECT Drc;
    MSG msg;
    HWND DhWnd = GetDesktopWindow();
    HWND MyhWnd;
    GetWindowRect(DhWnd, &Drc);
    myWidth = Drc.right - Drc.left;
    myHeight = Drc.bottom - Drc.top;

    WNDCLASS wc;
    wc.style = 0;
    wc.lpfnWndProc = WndProc;
    wc.cbClsExtra = 0;
    wc.cbWndExtra = 0;
    wc.hInstance = hInstance;
    wc.hIcon = NULL;
    wc.hCursor = LoadCursor(NULL,IDC_ARROW);
    wc.hbrBackground = NULL;
    wc.lpszMenuName = NULL;
    wc.lpszClassName = "MyWindow";

    if (!RegisterClass(&wc))
    {
        MessageBox(NULL, "Window Registration Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    MyhWnd = CreateWindow("MyWindow", NULL, WS_POPUP, 0, 0, myWidth, myHeight, NULL, NULL, hInstance, NULL);
    if (MyhWnd == NULL)
    {
        MessageBox(NULL, "Window Creation Failed!", "Error!",
            MB_ICONEXCLAMATION | MB_OK);
        return 0;
    }

    while (GetMessage(&msg, NULL, 0, 0) > 0)
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
    return 0;

}


问:
What is 'URIError: Failed to decode param '%C0' error in Node.js?
Sometimes, I get

```<code>/�
URIError: Failed to decode param '%C0'
   at decodeURIComponent (<anonymous>)
   at decode_param (/var/app/current/node_modules/express/lib/router/layer.js:172:12)
   at Layer.match (/var/app/current/node_modules/express/lib/router/layer.js:148:15)
   at matchLayer (/var/app/current/node_modules/express/lib/router/index.js:574:18)
   at next (/var/app/current/node_modules/express/lib/router/index.js:220:15)
   at urlencodedParser (/var/app/current/node_modules/body-parser/lib/types/urlencoded.js:100:7)
   at Layer.handle [as handle_request] (/var/app/current/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/var/app/current/node_modules/express/lib/router/index.js:317:13)
   at /var/app/current/node_modules/express/lib/router/index.js:284:7
   at Function.process_params (/var/app/current/node_modules/express/lib/router/index.js:335:12)
   at next (/var/app/current/node_modules/express/lib/router/index.js:275:10)
   at jsonParser (/var/app/current/node_modules/body-parser/lib/types/json.js:119:7)
   at Layer.handle [as handle_request] (/var/app/current/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/var/app/current/node_modules/express/lib/router/index.js:317:13)
   at /var/app/current/node_modules/express/lib/router/index.js:284:7
   at Function.process_params (/var/app/current/node_modules/express/lib/router/index.js:335:12)
</code>```

this error but can't find the reason, How can I solve this issue?

Body:
Sometimes, I get

/�
URIError: Failed to decode param '%C0'
   at decodeURIComponent (<anonymous>)
   at decode_param (/var/app/current/node_modules/express/lib/router/layer.js:172:12)
   at Layer.match (/var/app/current/node_modules/express/lib/router/layer.js:148:15)
   at matchLayer (/var/app/current/node_modules/express/lib/router/index.js:574:18)
   at next (/var/app/current/node_modules/express/lib/router/index.js:220:15)
   at urlencodedParser (/var/app/current/node_modules/body-parser/lib/types/urlencoded.js:100:7)
   at Layer.handle [as handle_request] (/var/app/current/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/var/app/current/node_modules/express/lib/router/index.js:317:13)
   at /var/app/current/node_modules/express/lib/router/index.js:284:7
   at Function.process_params (/var/app/current/node_modules/express/lib/router/index.js:335:12)
   at next (/var/app/current/node_modules/express/lib/router/index.js:275:10)
   at jsonParser (/var/app/current/node_modules/body-parser/lib/types/json.js:119:7)
   at Layer.handle [as handle_request] (/var/app/current/node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (/var/app/current/node_modules/express/lib/router/index.js:317:13)
   at /var/app/current/node_modules/express/lib/router/index.js:284:7
   at Function.process_params (/var/app/current/node_modules/express/lib/router/index.js:335:12)

this error but can't find the reason, How can I solve this issue?


问:
How to make Bootstrap's .container fill full available width and height irrespective of its contents' size
As the title says, I'm trying to make a div.container full (available) width and height, not more, not less. I've been playing around with the following code and I haven't figured out how to do it, despite several searches and attempts. My CSS knowledge is very rusty.

This is what I have now (https://jsfiddle.net/qf1azopr/1/), which looks close to what I'm trying to do (only because of the padding: 255px 0px;). However, it only does on my screen, and I know this is not the proper way to do it.

With this, if I shrink the window, then the content automatically overflows it and the footer is out of sight. I'm not so worried about this, but I know there will be some space below the footer on bigger screens. If you see www.google.com, the footer is always at the bottom, even if you shrink the window. The content only overflows it when it shrinks to some specific size. This is what I'd like to accomplish.

I think the actual way to do it with with the padding, but I'm not sure how. I'd just like the content, from navbar to footer, to just fit the available space and only overflow it if the window gets too small. What should change with the window size is the padding of the div.front.

How can I do this?

html,
body {
  height: 100%;
}

.front {
  padding: 255px 0px;
  width: 100%;
  height: 100%;
  min-height: 100%;
}

h1 {
  font-weight: bold;
  font-size: 90px;
}

.lorem {
  font-size: 30px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>

<nav class="navbar navbar-expand-lg">
  <div class="container-fluid">
    Brand Name
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">
              <span class="navbar-toggler-icon"></span>
            </button>
    <div class="collapse navbar-collapse" id="navbarScroll">
      <ul class="navbar-nav me-auto my-2 my-lg-0 navbar-nav-scroll" style="--bs-scroll-height: 100px;">
        <li class="nav-item">
          About
        </li>
        <li class="nav-item dropdown">

                    Tools

          <ul class="dropdown-menu">
            <li>Tool 1</li>
          </ul>
        </li>
      </ul>
      <ul class="navbar-nav">
        <li class="nav-item">Sign Up</li>
        <li class="nav-item">Login</li>
      </ul>
    </div>
  </div>
</nav>
<div class="container full-size">
  <div class="row text-center">
    <div class="front">
      <h1>Some Title</h1>
      <p class="lorem">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>
    </div>
  </div>
</div>
<footer class="py-3">
  <ul class="nav justify-content-center border-bottom pb-3 mb-3">
    <li class="nav-item">Home</li>
    <li class="nav-item">About</li>
    <li class="nav-item">Privacy Policy</li>
  </ul>
  <p class="text-center text-muted">© 2022 Company, Inc</p>
</footer></code>```

Body:
As the title says, I'm trying to make a div.container full (available) width and height, not more, not less. I've been playing around with the following code and I haven't figured out how to do it, despite several searches and attempts. My CSS knowledge is very rusty.

This is what I have now (https://jsfiddle.net/qf1azopr/1/), which looks close to what I'm trying to do (only because of the padding: 255px 0px;). However, it only does on my screen, and I know this is not the proper way to do it.

With this, if I shrink the window, then the content automatically overflows it and the footer is out of sight. I'm not so worried about this, but I know there will be some space below the footer on bigger screens. If you see www.google.com, the footer is always at the bottom, even if you shrink the window. The content only overflows it when it shrinks to some specific size. This is what I'd like to accomplish.

I think the actual way to do it with with the padding, but I'm not sure how. I'd just like the content, from navbar to footer, to just fit the available space and only overflow it if the window gets too small. What should change with the window size is the padding of the div.front.

How can I do this?

html,
body {
  height: 100%;
}

.front {
  padding: 255px 0px;
  width: 100%;
  height: 100%;
  min-height: 100%;
}

h1 {
  font-weight: bold;
  font-size: 90px;
}

.lorem {
  font-size: 30px;
}

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://getbootstrap.com/docs/5.2/assets/css/docs.css" rel="stylesheet">

    Brand Name
    <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarScroll" aria-controls="navbarScroll" aria-expanded="false" aria-label="Toggle navigation">

            </button>

          About

                    Tools

Tool 1

Sign Up

Login

Some Title

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Home

About

Privacy Policy

© 2022 Company, Inc


问:
In angular application target selector href value binding in the url.How to restrict that?
In angular application I am using target selector functionality.But when clicking the menu the href value binding to the URL that points to 404 error page.How to use the target selector within the page without affecting the URL

https://stackblitz.com/edit/flex-layout-angular-material-ngipq2?file=app/app.component.html


问:
Android : How to have an app appearing in the share menu with several variants like Whatsapp does
I know how to get my Android app in the share menu but I would like to have it appearing with several variants like Whatsapp does : In the direct share menu it appears as an whatsapp icon and also an icon to share with specifics whatsapp contacts probably the most or last used. how to do this for my app ?

TIA


问:
on change event is not working on custom select
I am trying to follow below example for custom select but I am not able to perform on change event and on focus event.

https://www.w3schools.com/howto/howto_custom_select.asp

I am not able to perform any event for option value . So how can I perform any event on select?

here is my javascript code

var x, i, j, l, ll, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
l = x.length;
for (i = 0; i < l; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  ll = selElmnt.length;
  /*for each element, create a new DIV that will act as the selected item:*/
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /*for each element, create a new DIV that will contain the option list:*/
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < ll; j++) {
    /*for each option in the original select element,
    create a new DIV that will act as an option item:*/
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
      /*when an item is clicked, update the original select box,
        and the selected item:*/
      var y, i, k, s, h, sl, yl;
      s = this.parentNode.parentNode.getElementsByTagName("select")[0];
      sl = s.length;
      h = this.parentNode.previousSibling;
      for (i = 0; i < sl; i++) {
        if (s.options[i].innerHTML == this.innerHTML) {
          s.selectedIndex = i;
          h.innerHTML = this.innerHTML;
          y = this.parentNode.getElementsByClassName("same-as-selected");
          yl = y.length;
          for (k = 0; k < yl; k++) {
            y[k].removeAttribute("class");
          }
          this.setAttribute("class", "same-as-selected");
          break;
        }
      }
      h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /*when the select box is clicked, close any other select boxes,
      and open/close the current select box:*/
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /*a function that will close all select boxes in the document,
     except the current select box:*/
  var x,
    y,
    i,
    xl,
    yl,
    arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  xl = x.length;
  yl = y.length;
  for (i = 0; i < yl; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i);
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < xl; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}
/*if the user clicks anywhere outside the select box,
            then close all select boxes:*/

let selectDiv = document.getElementById('selectopt');

selectDiv.addEventListener('change', function() {
  console.log('Mouse Clicked');
});

let changeEvent = new Event('change');
selectDiv.dispatchEvent(changeEvent);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="custom-select inputfieldwithoutanimation" style="width: 737px">
  <select id="selectopt" class="inputfield-control-withoutanimation">
    <option value="0">Choose:</option>
    <option value="1">Department - A</option>
    <option value="2">Department - B</option>
    <option value="3">Department - C</option>
  </select>
  <label class="form-label-withoutanimation selectcls">Department</label>
</div>
 css code

         <style>
  /*the container must be positioned relative:*/
  .custom-select {
    position: absolute;
    top: 26px;
    left: 24px;
  }

  .custom-select select {
    display: none; /*hide original SELECT element:*/
  }

  .select-selected {
    background-color: white;
  }

  /*style the arrow inside the select element:*/
  .select-selected:after {
    position: absolute;
    content: "";
    top: 21px;
    right: 15px;
    width: 0;
    height: 0;
    background-repeat: no-repeat;
    border: 6px solid black;
    border-color: #000 transparent transparent transparent;
  }

  /*point the arrow upwards when the select box is open (active):*/
  .select-selected.select-arrow-active:after {
    border-color: transparent transparent #000 transparent;
    top: 16px;
  }

  .select-selected {
    border: 1.5px solid #c4c4c4;
    border-radius: 5px;
    height: 50px;
    width: 737px;
  }

  /*style the items (options), including the selected item:*/
  .select-items div,
  .select-selected {
    color: #000;
    padding: 13px 16px;
    /* border: 1px solid black; */
    /* border-color: transparent transparent rgba(0, 0, 0, 0.1) transparent; */
    cursor: pointer;
    user-select: none;
  }

  /*style items (options):*/
  .select-items {
    position: absolute;
    background-color: #ecf7fe;
    top: 100%;
    left: 0;
    right: 0;
    z-index: 99;
  }

  /*hide the items when the select box is closed:*/
  .select-hide {
    display: none;
  }

  .select-items div:hover,
  .same-as-selected {
    background-color: #ccecfe;
  }

  .dropdown-icon {
    position: absolute;
    right: 0px;
    top: 20px;
    padding-right: 16px;
  }
</style></code>```

Body:
I am trying to follow below example for custom select but I am not able to perform on change event and on focus event.

https://www.w3schools.com/howto/howto_custom_select.asp

I am not able to perform any event for option value . So how can I perform any event on select?

here is my javascript code

var x, i, j, l, ll, selElmnt, a, b, c;
/*look for any elements with the class "custom-select":*/
x = document.getElementsByClassName("custom-select");
l = x.length;
for (i = 0; i < l; i++) {
  selElmnt = x[i].getElementsByTagName("select")[0];
  ll = selElmnt.length;
  /*for each element, create a new DIV that will act as the selected item:*/
  a = document.createElement("DIV");
  a.setAttribute("class", "select-selected");
  a.innerHTML = selElmnt.options[selElmnt.selectedIndex].innerHTML;
  x[i].appendChild(a);
  /*for each element, create a new DIV that will contain the option list:*/
  b = document.createElement("DIV");
  b.setAttribute("class", "select-items select-hide");
  for (j = 1; j < ll; j++) {
    /*for each option in the original select element,
    create a new DIV that will act as an option item:*/
    c = document.createElement("DIV");
    c.innerHTML = selElmnt.options[j].innerHTML;
    c.addEventListener("click", function(e) {
      /*when an item is clicked, update the original select box,
        and the selected item:*/
      var y, i, k, s, h, sl, yl;
      s = this.parentNode.parentNode.getElementsByTagName("select")[0];
      sl = s.length;
      h = this.parentNode.previousSibling;
      for (i = 0; i < sl; i++) {
        if (s.options[i].innerHTML == this.innerHTML) {
          s.selectedIndex = i;
          h.innerHTML = this.innerHTML;
          y = this.parentNode.getElementsByClassName("same-as-selected");
          yl = y.length;
          for (k = 0; k < yl; k++) {
            y[k].removeAttribute("class");
          }
          this.setAttribute("class", "same-as-selected");
          break;
        }
      }
      h.click();
    });
    b.appendChild(c);
  }
  x[i].appendChild(b);
  a.addEventListener("click", function(e) {
    /*when the select box is clicked, close any other select boxes,
      and open/close the current select box:*/
    e.stopPropagation();
    closeAllSelect(this);
    this.nextSibling.classList.toggle("select-hide");
    this.classList.toggle("select-arrow-active");
  });
}

function closeAllSelect(elmnt) {
  /*a function that will close all select boxes in the document,
     except the current select box:*/
  var x,
    y,
    i,
    xl,
    yl,
    arrNo = [];
  x = document.getElementsByClassName("select-items");
  y = document.getElementsByClassName("select-selected");
  xl = x.length;
  yl = y.length;
  for (i = 0; i < yl; i++) {
    if (elmnt == y[i]) {
      arrNo.push(i);
    } else {
      y[i].classList.remove("select-arrow-active");
    }
  }
  for (i = 0; i < xl; i++) {
    if (arrNo.indexOf(i)) {
      x[i].classList.add("select-hide");
    }
  }
}
/*if the user clicks anywhere outside the select box,
            then close all select boxes:*/

let selectDiv = document.getElementById('selectopt');

selectDiv.addEventListener('change', function() {
  console.log('Mouse Clicked');
});

let changeEvent = new Event('change');
selectDiv.dispatchEvent(changeEvent);

  <select id="selectopt" class="inputfield-control-withoutanimation">
    <option value="0">Choose:</option>
    <option value="1">Department - A</option>
    <option value="2">Department - B</option>
    <option value="3">Department - C</option>
  </select>
  Department

 css code


问:
User register with Country code and flag with NuxtJs and Ant design
User Register:
Please check picture and code.

I want all of them in one line Contry flag,phone number. but i didnt
was successfull. Contry selecting is working properly. I am using
NuxtJs and Ant design. thank you.

User Register From

```<code><a-form-item
            class="lg:w-1/2 flex justify-center w-full"
            v-bind="formItemLayout"
          >
            <vue-country-code
              @onSelect="onSelect"
              :preferredCountries="['tm', 'ru', 'tr']"
              defaultCountry="tm"
            >
            </vue-country-code>

            <a-input
              :addon-before="dialCode"
              :placeholder="example_number"
              v-decorator="[
                'companyPhone',
                {
                  rules: [
                    {
                      //pattern: /^[0-9]{12}$/im,
                      message: this.$i18n.t('registerPhoneMessageValid'),
                    },
                    {
                      required: true,
                      message: this.$i18n.t('registerPhoneMessage'),
                    },
                  ],
                },
              ]"
            />
          </a-form-item>
</code>```

second part:

```<code>name: "app",
  components: {
    VueCountryCode,
  },
  data() {
    return {
      selectedCountry: null,
      name: null,
      iso2: null,
      dialCode: null,
      example_number: null,
    };
  },
  methods: {
    onSelect(data) {
      this.selectedCountry = data;
      this.name = data.name;
      this.iso2 = data.iso2;
      this.dialCode = data.dialCode;
      this.example_number = data.example_number;
    },
  },

</code>```

Body:
User Register:
Please check picture and code.

I want all of them in one line Contry flag,phone number. but i didnt
was successfull. Contry selecting is working properly. I am using
NuxtJs and Ant design. thank you.

User Register From

            <vue-country-code
              @onSelect="onSelect"
              :preferredCountries="['tm', 'ru', 'tr']"
              defaultCountry="tm"
            >
            </vue-country-code>

            <a-input
              :addon-before="dialCode"
              :placeholder="example_number"
              v-decorator="[
                'companyPhone',
                {
                  rules: [
                    {
                      //pattern: /^[0-9]{12}$/im,
                      message: this.$i18n.t('registerPhoneMessageValid'),
                    },
                    {
                      required: true,
                      message: this.$i18n.t('registerPhoneMessage'),
                    },
                  ],
                },
              ]"
            />

second part:

name: "app",
  components: {
    VueCountryCode,
  },
  data() {
    return {
      selectedCountry: null,
      name: null,
      iso2: null,
      dialCode: null,
      example_number: null,
    };
  },
  methods: {
    onSelect(data) {
      this.selectedCountry = data;
      this.name = data.name;
      this.iso2 = data.iso2;
      this.dialCode = data.dialCode;
      this.example_number = data.example_number;
    },
  },