问:
(React/.NET) How to implement OAuth in a fullstack application? (my implementation in the description)
I am trying to implement OAuth in a way that makes sense to me. All the auth implementation is done in the backend as I have heard that's the best practice.

My company has a fullstack app, "MyApp" (React UI and .NET WebAPI backend) where I need to add SSO OAuth authentication and authorization, and retrieve user info.

I am thinking of implementing it this way:

Add an AuthController with a Login() endpoint (route: "/login").

The React app will call "/login" on homepage load.

"/login" will return the following URL string to the React App:

```<code>    "https://oauth2.provider/authorizationUrl?
    response_type=code&
    client_id=myClientId&
    redirect_uri=https://myApp/api/login&
    scope=openid+profile"
</code>```

React app will redirect page to that ☝ URL string, which will take the user to the SSO Login page (Note: Its an EXTERNAL authentication website, so we are navigating AWAY from the React UI app completely). Then the user will log in.

☝ As you can see in the URL string, the redirect_uri is the "/login" endpoint. So after the user logs in, the SSO provider will call "/login" with the auth_code in the URL params (let's say auth_code="xyz123") .

If params contain auth_code, "/login" uses that auth_code to get the Bearer token:

Request:

```<code>    POST
    https://oauth2.provider/tokenUrl?
    grant_type=authorization_code&
    code=xyz123&
    redirect_uri=https://myApp/api/login&
    client_id=myClientId&
    client_secret=secret123xyzabc

</code>```

Response body:

```<code>    {
    token_type: "Bearer"
    expires_in: 5000
    refresh_token: "2nMV5TMXuH4RQGjErsR7QkXUkcuqKhq"
    access_token: "VmQGGROr9Ln4QIJJTs"
    }
</code>```

"/login" then uses the ☝ access_token to retrieve User Info by making the below request:

Request:

```<code>    POST
    https://oauth2.provider/oauthUserInfoUrl

    Headers: {
      ContentType: "application/json"
      Authorization: "Bearer VmQGGROr9Ln4QIJJTs"
    }
</code>```

Response body:

```<code>    {
    username: "johndoe123"
    firstName: "John",
    lastName: "Doe",
    employeeType: "redditor",
    location: "mordor"
    ...
    ...
    }
</code>```

☝ Using the username, "/login" then checks our database's AppAccess table to see if the user is authorized to use MyApp. Turns out the user does have access!

... And now what? How does the React app know that user is authenticated and authorized to use this app? After redirecting to the EXTERNAL user login page, we have completely lost track of the React app.

Question 1: How do we redirect/go back to the HomePage or AnotherPage in the UI after authorization is done in "/login"?

Question 2: How should my app "remember" that the user is authenticated and authorized?

Question 3: This code flow makes sense to me (until the last step), so I would like to stick with it, but if there are easier/better ways to achieve authentication and authorization please let me know.

Body:
I am trying to implement OAuth in a way that makes sense to me. All the auth implementation is done in the backend as I have heard that's the best practice.

My company has a fullstack app, "MyApp" (React UI and .NET WebAPI backend) where I need to add SSO OAuth authentication and authorization, and retrieve user info.

I am thinking of implementing it this way:

Add an AuthController with a Login() endpoint (route: "/login").

The React app will call "/login" on homepage load.

"/login" will return the following URL string to the React App:

    "https://oauth2.provider/authorizationUrl?
    response_type=code&
    client_id=myClientId&
    redirect_uri=https://myApp/api/login&
    scope=openid+profile"

React app will redirect page to that ☝ URL string, which will take the user to the SSO Login page (Note: Its an EXTERNAL authentication website, so we are navigating AWAY from the React UI app completely). Then the user will log in.

☝ As you can see in the URL string, the redirect_uri is the "/login" endpoint. So after the user logs in, the SSO provider will call "/login" with the auth_code in the URL params (let's say auth_code="xyz123") .

If params contain auth_code, "/login" uses that auth_code to get the Bearer token:

Request:

    POST
    https://oauth2.provider/tokenUrl?
    grant_type=authorization_code&
    code=xyz123&
    redirect_uri=https://myApp/api/login&
    client_id=myClientId&
    client_secret=secret123xyzabc

Response body:

    {
    token_type: "Bearer"
    expires_in: 5000
    refresh_token: "2nMV5TMXuH4RQGjErsR7QkXUkcuqKhq"
    access_token: "VmQGGROr9Ln4QIJJTs"
    }

"/login" then uses the ☝ access_token to retrieve User Info by making the below request:

Request:

    POST
    https://oauth2.provider/oauthUserInfoUrl

    Headers: {
      ContentType: "application/json"
      Authorization: "Bearer VmQGGROr9Ln4QIJJTs"
    }

Response body:

    {
    username: "johndoe123"
    firstName: "John",
    lastName: "Doe",
    employeeType: "redditor",
    location: "mordor"
    ...
    ...
    }

☝ Using the username, "/login" then checks our database's AppAccess table to see if the user is authorized to use MyApp. Turns out the user does have access!

... And now what? How does the React app know that user is authenticated and authorized to use this app? After redirecting to the EXTERNAL user login page, we have completely lost track of the React app.

Question 1: How do we redirect/go back to the HomePage or AnotherPage in the UI after authorization is done in "/login"?

Question 2: How should my app "remember" that the user is authenticated and authorized?

Question 3: This code flow makes sense to me (until the last step), so I would like to stick with it, but if there are easier/better ways to achieve authentication and authorization please let me know.


来源: stackexchange

问:
Pyro GP: gpmodel.parameters() does not reflect assigned value
Code. X, and y should be irrelevant..

```<code>     ker = gp.kernels.RBF(input_dim=2,variance=torch.tensor(1.), lengthscale=torch.ones((2,)))
     gpr = gp.models.GPModel(kernel=ker, X=x, y=y)
</code>```

Input:

```<code>     list(gpr.parameters())
</code>```

Output:

```<code>[0]: [Parameter containing:
     tensor(0., requires_grad=True),
     Parameter containing:
     tensor([0., 0.], requires_grad=True)]
</code>```

The resulting tensors are 0. not 1. expected..

ContentLicense: CC BY-SA 4.0

Body:
Code. X, and y should be irrelevant..

     ker = gp.kernels.RBF(input_dim=2,variance=torch.tensor(1.), lengthscale=torch.ones((2,)))
     gpr = gp.models.GPModel(kernel=ker, X=x, y=y)

Input:

     list(gpr.parameters())

Output:

[0]: [Parameter containing:
     tensor(0., requires_grad=True),
     Parameter containing:
     tensor([0., 0.], requires_grad=True)]

The resulting tensors are 0. not 1. expected..


问:
Digital Fingerprints Server Side Best prictices
Im looking for a solution (or to develop one) that can track digital fingerprints server side without using data available to the client.

The idea is to be able to match users based on the fingerprints when they come to the website. Without using client side - only server side.

What are the cons and pros i should keep in mind? Generally is this possible to accurately track users this way in 2022?
Would you recommend any reading?
I found this repo is this any good?


问:
Run vulture on Python module with CLI arguments?

Context

Suppose one has a project structure with src.projectname.__main__.py which can be executed using the following command with accompanying arguments:

```<code>python -m src.projectname -e mdsa_size3_m1 -v -x
</code>```

Question

How would one run vulture whilst passing cli arguments to the script on which vulture runs?

Approach I

When I run:

```<code>python -m src.projectname -e mdsa_size3_m1 -v -x
</code>```

It throws the following

```<code>usage: vulture [options] [PATH ...]
vulture: error: unrecognized arguments: -e mdsa_size3_m1 -x
</code>```

because vulture tries to parse the arguments for the script that is being ran.

Notes

I am aware normally one would expect to run vulture on the script and its entirety without narrowing down the scope with arguments. However, in this case the arguments are required to specify the number of runs/duration of the code execution.

One can hack around this issue by temporarily manually hardcoding the args with (for example):

```<code>args = parse_cli_args()
args.experiment_settings_name = "mdsa_size3_m1"
args.export_images = True
process_args(args)
</code>```

assuming one has such an args object, however, I thought perhaps this functionality can be realised using the CLI, without temporarily modifying the code.

Body:
Context

Suppose one has a project structure with src.projectname.__main__.py which can be executed using the following command with accompanying arguments:

python -m src.projectname -e mdsa_size3_m1 -v -x

Question

How would one run vulture whilst passing cli arguments to the script on which vulture runs?

Approach I

When I run:

python -m src.projectname -e mdsa_size3_m1 -v -x

It throws the following

usage: vulture [options] [PATH ...]
vulture: error: unrecognized arguments: -e mdsa_size3_m1 -x

because vulture tries to parse the arguments for the script that is being ran.

Notes

I am aware normally one would expect to run vulture on the script and its entirety without narrowing down the scope with arguments. However, in this case the arguments are required to specify the number of runs/duration of the code execution.

One can hack around this issue by temporarily manually hardcoding the args with (for example):

args = parse_cli_args()
args.experiment_settings_name = "mdsa_size3_m1"
args.export_images = True
process_args(args)

assuming one has such an args object, however, I thought perhaps this functionality can be realised using the CLI, without temporarily modifying the code.


问:
I have a hamburger button issue
I have a hamburger button that opens up a mobile nav. When it closed it scrolls with the page, but when open I need to it scroll with the mobile-nav but it have sticky property still. The button appears inside dropdown menu on mobile version and must be on the top of it after scrolling.

`

```<code>    .menu-btn--mobile {
        position: relative;
        display: inline-block;
        z-index: 5;

        &:after {
            @include icon-base;
            @include icon('hamburger', rem-calc(36), $color-white);
            position: relative;
            background-color: $color-maroon-light;
            background-size: rem-calc(15);
            content: '';
        }
    }

    &.menu-hide--mobile {
        .mobile-menu {
            right: -100%;
        }
    }

    &.menu-show--mobile {

        .menu-btn--mobile {

            &:after {
                @include icon-base;
                @include icon('hamburger', rem-calc(36), $color-white);
                background-color: $color-red;
                background-size: rem-calc(15);
                content: '';
            }
        }
    }
</code>```

`

I've changed css but it still have the same property as on desktop version.

Title: I have a hamburger button issue

Body:
I have a hamburger button that opens up a mobile nav. When it closed it scrolls with the page, but when open I need to it scroll with the mobile-nav but it have sticky property still. The button appears inside dropdown menu on mobile version and must be on the top of it after scrolling.

`

    .menu-btn--mobile {
        position: relative;
        display: inline-block;
        z-index: 5;

        &:after {
            @include icon-base;
            @include icon('hamburger', rem-calc(36), $color-white);
            position: relative;
            background-color: $color-maroon-light;
            background-size: rem-calc(15);
            content: '';
        }
    }

    &.menu-hide--mobile {
        .mobile-menu {
            right: -100%;
        }
    }

    &.menu-show--mobile {

        .menu-btn--mobile {

            &:after {
                @include icon-base;
                @include icon('hamburger', rem-calc(36), $color-white);
                background-color: $color-red;
                background-size: rem-calc(15);
                content: '';
            }
        }
    }

`

I've changed css but it still have the same property as on desktop version.


问:
Python unittest fails because of import using a method that needs env variables even if env vars are mocked
I am trying to test my domain.awards file.
This file imports the interfaces.database.awards (which I mock in my test), which itself imports interfaces.database.supabase.

interfaces.database.supabase is where I setup my client so it has some env variables.

Even though I mock interfaces.database.awards the import still happens when testing.
Because this import happens, it needs the env variables, although I should not need to provide anything because I am not using this import in my test.
So I also mock the env variables. But I still get the error where it does not find that var:

```<code>File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'SUPABASE_URL'
</code>```

my file structure is like so:

```<code>|- src |-domain|-awards.py
       |       |-test_awards.py
       |       |-__init__.py
       |
       |-interfaces|-database|-awards.py
                             |-supabase.py

</code>```

interfaces.database.supabase is like so:

```<code>import os
from supabase import create_client, Client

client: Client = create_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])
</code>```

interfaces.database.awards is like so:

```<code>import src.interfaces.database.supabase as supabase

def create(id, name):
    return supabase.client.table("awards").insert({id, name}).execute()
</code>```

domain.awards is like so:

```<code>import src.interfaces.database.awards as database_awards

def create(id, name):
    new_award = database_awards.create(id, name)
    return new_award.id
</code>```

and finally my domain.test_awards is like so:

```<code>import unittest
import src.domain.awards as awards
from unittest import mock
import os

@mock.patch.dict(os.environ, {"SUPABASE_URL": "123", "SUPABASE_KEY": "456"})
class TestAwards(unittest.TestCase):
    def test_env_vars(self):
        self.assertEqual(os.environ["SUPABASE_URL"], "123") # <-- works when I commment out the import in `domain.awards`

    @mock.patch('src.interfaces.database.awards.create')
    def test_len_joke(self, mock_db_create_award):
        mock_db_create_award.return_value = {"id": 1, "name": "test"}
        self.assertEqual(awards.create(1, "test"), 1)
        self.assertEqual(os.environ["SUPABASE_URL"], "123")
</code>```

Body:
I am trying to test my domain.awards file.
This file imports the interfaces.database.awards (which I mock in my test), which itself imports interfaces.database.supabase.

interfaces.database.supabase is where I setup my client so it has some env variables.

Even though I mock interfaces.database.awards the import still happens when testing.
Because this import happens, it needs the env variables, although I should not need to provide anything because I am not using this import in my test.
So I also mock the env variables. But I still get the error where it does not find that var:

File "/Library/Developer/CommandLineTools/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/os.py", line 679, in __getitem__
    raise KeyError(key) from None
KeyError: 'SUPABASE_URL'

my file structure is like so:

|- src |-domain|-awards.py
       |       |-test_awards.py
       |       |-__init__.py
       |
       |-interfaces|-database|-awards.py
                             |-supabase.py

interfaces.database.supabase is like so:

import os
from supabase import create_client, Client

client: Client = create_client(
    os.environ["SUPABASE_URL"], os.environ["SUPABASE_KEY"])

interfaces.database.awards is like so:

import src.interfaces.database.supabase as supabase

def create(id, name):
    return supabase.client.table("awards").insert({id, name}).execute()

domain.awards is like so:

import src.interfaces.database.awards as database_awards

def create(id, name):
    new_award = database_awards.create(id, name)
    return new_award.id

and finally my domain.test_awards is like so:

import unittest
import src.domain.awards as awards
from unittest import mock
import os

@mock.patch.dict(os.environ, {"SUPABASE_URL": "123", "SUPABASE_KEY": "456"})
class TestAwards(unittest.TestCase):
    def test_env_vars(self):
        self.assertEqual(os.environ["SUPABASE_URL"], "123") # <-- works when I commment out the import in `domain.awards`

    @mock.patch('src.interfaces.database.awards.create')
    def test_len_joke(self, mock_db_create_award):
        mock_db_create_award.return_value = {"id": 1, "name": "test"}
        self.assertEqual(awards.create(1, "test"), 1)
        self.assertEqual(os.environ["SUPABASE_URL"], "123")


问:
Python: how to safely initialize a dataclass based on a dict with unexpected keys?
I'd like to initialize A from a dict which can contain unexpected keys. I'd like to initialize with the given, known keys and ignore the rest.

```<code>from dataclasses import dataclass

@dataclass
class A:
    a: str
    b: int

a1 = A(**{'a': 'Foo', 'b': 123})  # works
a2 = A(**{'a': 'Foo', 'b': 123, 'c': 'unexpected'})  # raises TypeError
</code>```

Is there a Python feature that I'm missing or do I have to filter the dict upfront?

Body:
I'd like to initialize A from a dict which can contain unexpected keys. I'd like to initialize with the given, known keys and ignore the rest.

from dataclasses import dataclass

@dataclass
class A:
    a: str
    b: int

a1 = A(**{'a': 'Foo', 'b': 123})  # works
a2 = A(**{'a': 'Foo', 'b': 123, 'c': 'unexpected'})  # raises TypeError

Is there a Python feature that I'm missing or do I have to filter the dict upfront?


问:
How do I change my GIT source control repository in VSCode
I'm trying to change my source control repository in VSCode, but I can't find any way to do it.

This happened because I was originally working on another project linked to this git repository, and then when I created a new expo app in a new folder, it seemed to be automatically linked to the old repository.

I saw some instructions online about adding a remote repository, but I was thinking that I wanted to change the source control repository rather than add a remote.

Currently I don't see any option to do this. Any help is appreciated, thanks!


问:
SCTP Protocol to sent informations real time immediately when it is available
I am new to SCTP Protocol, I am using SCTP to transfer a large number of binary chunks of a single video file from C Language.
Current issue is SCTP starts transmit the chunks to the other end only after all the chunks are ready.
Is there a way to tranmit chunks one by one immediately it is available.
callback used to sent the packet is "onSctpOutboundPacket".
Please let me know any solution.</p>


问:
Java uses or overrides a deprecated API. Native screen shot & fluttershare
Im having these error when i compile apk of my flutter app. What could be the workaround for this?

Note: C:\flutter.pub-cache\hosted\pub.dartlang.org\native_screenshot-1.0.0\android\src\main\java\jpg\ivan\native_screenshot\NativeScreenshotPlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: C:\flutter.pub-cache\hosted\pub.dartlang.org\flutter_share-2.0.0\android\src\main\java\com\example\fluttershare\FlutterSharePlugin.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.

Tried:
flutter pub clean
flutter pub upgrade
flutter pub get
flutter pub run

but still having  those errors.


问:
Finding Paths Within SVGs
I have a raster image marking up an SVG that I have attached...
Markup

Here is the SVG in html...
SVG code

```<code><svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="6.4in" height="3.6in" version="1.1" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
viewBox="0 0 6400 3600"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 xmlns:xodm="http://www.corel.com/coreldraw/odm/2003">
</code>```

How do I find the path as highlighted in the markup in order to ID it? Thank you.

Title: Finding Paths Within SVGs

Body:
I have a raster image marking up an SVG that I have attached...
Markup

Here is the SVG in html...
SVG code

<svg xmlns="http://www.w3.org/2000/svg" xml:space="preserve" width="6.4in" height="3.6in" version="1.1" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd"
viewBox="0 0 6400 3600"
 xmlns:xlink="http://www.w3.org/1999/xlink"
 xmlns:xodm="http://www.corel.com/coreldraw/odm/2003">

How do I find the path as highlighted in the markup in order to ID it? Thank you.


问:
I'm trying to retrieve data from Firebase Firestore Database , but I keep getting an empty array
Firebase Configure code

```<code>// Import the functions you need from the SDKs you need
import { getApp, getApps, initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'

const FirebaseConfigforEvents = {
  apiKey: "**************************",
  authDomain: "*********************",
  projectId: "club-ide-events",
  storageBucket: "****************",
  messagingSenderId: "255324871276",
  appId: "********************",
  measurementId: "***************"
};

// Initialize Firebase
const app = !getApps().length ? initializeApp(FirebaseConfigforEvents) : getApp();

export const storage = getStorage(app);
export const db = getFirestore(app);

</code>```
```<code>I made an effort to retrieve it in this manner.

`
```
import { db } from './FirebaseConfigforEvents'

const Eventpage = () => {

    const [NewEvents , setNewEvents] = useState([]);

    useEffect(()=>{
        const EventRef = collection(db , "Events");
        const q = query(EventRef , orderBy("createdAt" , "desc"));
        onSnapshot(q , (snapshot)=>{
            console.log(snapshot);
        })
    })
}
```
<p>This image can be displayed in the docs[]. It contains no elements. </p>
<p>This is my firebase Collection </p>
<p>I made an effort to retrieve it in this manner.</p>
```import { db } from './FirebaseConfigforEvents'

const Eventpage = () => {

    const [NewEvents , setNewEvents] = useState([]);

    useEffect(()=>{
        const EventRef = collection(db , "Events");
        const q = query(EventRef , orderBy("createdAt" , "desc"));
        onSnapshot(q , (snapshot)=>{
            console.log(snapshot);
        })
    })
}
```

This image can be displayed in the docs[]. It contains no elements.

This is my firebase Collection

Body:
Firebase Configure code

// Import the functions you need from the SDKs you need
import { getApp, getApps, initializeApp } from "firebase/app";
import { getFirestore } from 'firebase/firestore'
import { getStorage } from 'firebase/storage'

const FirebaseConfigforEvents = {
  apiKey: "**************************",
  authDomain: "*********************",
  projectId: "club-ide-events",
  storageBucket: "****************",
  messagingSenderId: "255324871276",
  appId: "********************",
  measurementId: "***************"
};

// Initialize Firebase
const app = !getApps().length ? initializeApp(FirebaseConfigforEvents) : getApp();

export const storage = getStorage(app);
export const db = getFirestore(app);

I made an effort to retrieve it in this manner.

`
```
import { db } from './FirebaseConfigforEvents'

const Eventpage = () => {

    const [NewEvents , setNewEvents] = useState([]);

    useEffect(()=>{
        const EventRef = collection(db , "Events");
        const q = query(EventRef , orderBy("createdAt" , "desc"));
        onSnapshot(q , (snapshot)=>{
            console.log(snapshot);
        })
    })
}

This image can be displayed in the docs[]. It contains no elements.

This is my firebase Collection

I made an effort to retrieve it in this manner.

import { db } from './FirebaseConfigforEvents'

const Eventpage = () => {

    const [NewEvents , setNewEvents] = useState([]);

    useEffect(()=>{
        const EventRef = collection(db , "Events");
        const q = query(EventRef , orderBy("createdAt" , "desc"));
        onSnapshot(q , (snapshot)=>{
            console.log(snapshot);
        })
    })
}

This image can be displayed in the docs[]. It contains no elements.

This is my firebase Collection


问:
Objective C to C# Equivalent
I've got this statement I'm trying to convert form objective c to c#:

```<code>NSData *blockData;

if(valid)
{
    if(sendingLast)
    {
         blockData = rawFirmwareData;
    }
    else
    {
        int startingPos = (currSensor.firmwareBlockIterator *
                (ourCurrentSensor.firmwareBlockSize - headerSize));
        blockData = [rawFirmwareData subdataWithRange:NSMakeRange(startingPos,
                    rawFirmwareData.length - startingPos)]
    }
}
else
{
    blockData = [rawFirmwareData
                subdataWithRange:NSMakeRange((currSensor.firmwareBlockIterator *
               (currSensor.firmwareBlockSize - headerSize)),
               (currSensor.firmwareBlockSize - headerSize))];
}
</code>```

I've tried translating it to the following, but I'm not sure if I've done it properly:

```<code>byte[] blockData;

if(valid)
{
    if(sendingLast)
    {
        blockData = rawFirmwareData;
    }
    else
    {
        blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
        Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
                  (currSensor.firmwareBlockSize - headerSize)), blockData, 0,
                  (currSensor.firmwareBlockSize - headerSize));
    }
}
else
{
    blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
    Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
               (currSensor.firmwareBlockSize  - headerSize)), blockData, 0,
               (currSensor.firmwareBlockSize - headerSize));
}
</code>```

I'm not sure if my array length is correct when I initialize it based on the starting and ending positions.

Title: Objective C to C# Equivalent

Body:
I've got this statement I'm trying to convert form objective c to c#:

NSData *blockData;

if(valid)
{
    if(sendingLast)
    {
         blockData = rawFirmwareData;
    }
    else
    {
        int startingPos = (currSensor.firmwareBlockIterator *
                (ourCurrentSensor.firmwareBlockSize - headerSize));
        blockData = [rawFirmwareData subdataWithRange:NSMakeRange(startingPos,
                    rawFirmwareData.length - startingPos)]
    }
}
else
{
    blockData = [rawFirmwareData
                subdataWithRange:NSMakeRange((currSensor.firmwareBlockIterator *
               (currSensor.firmwareBlockSize - headerSize)),
               (currSensor.firmwareBlockSize - headerSize))];
}

I've tried translating it to the following, but I'm not sure if I've done it properly:

byte[] blockData;

if(valid)
{
    if(sendingLast)
    {
        blockData = rawFirmwareData;
    }
    else
    {
        blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
        Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
                  (currSensor.firmwareBlockSize - headerSize)), blockData, 0,
                  (currSensor.firmwareBlockSize - headerSize));
    }
}
else
{
    blockData = new byte[(currSensor.firmwareBlockSize - headerSize)];
    Array.Copy(rawFirmwaredata, (currSensor.firmwareBlockIterator *
               (currSensor.firmwareBlockSize  - headerSize)), blockData, 0,
               (currSensor.firmwareBlockSize - headerSize));
}

I'm not sure if my array length is correct when I initialize it based on the starting and ending positions.


问:
Using MVC Razor functionality in .NET Framework 4.8
We have a large application targeting Framework 4.8 which uses the RazorEngine library to generate HTML-formatted emails.  Due to the fact this library has a vulnerability and is no longer maintained, I am trying to find an alternate implementation.  The RazorEngineCore package is too limited in its functionality; RazorLight looks good but I found a lot of errors that I was not able to resolve.

So I am trying an implementation using the Microsoft.AspNetCore.Mvc.Razor library and the RazorViewToStringRenderer class from Github which seems to be frequently recommended.  My test concept application is throwing an error:

"Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'Microsoft.AspNetCore.Mvc.ViewFeatures.CookieTempDataProvider'."

My sample:

```<code>        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            services.AddMvcCore().AddRazorViewEngine();
            services.AddSingleton<RazorViewToStringRenderer>();

            var provider = services.BuildServiceProvider();
            var service = provider.GetRequiredService<RazorViewToStringRenderer>();
        }
</code>```

The error is thrown on the last line.

The only sample code I could find online was written for .NET Core so I had to modify it, since some of the method calls aren't available to me.  I am supposed to find a solution that will work while still targeting .NET Framework.  Can someone point out if I am doing something wrong?

Body:
We have a large application targeting Framework 4.8 which uses the RazorEngine library to generate HTML-formatted emails.  Due to the fact this library has a vulnerability and is no longer maintained, I am trying to find an alternate implementation.  The RazorEngineCore package is too limited in its functionality; RazorLight looks good but I found a lot of errors that I was not able to resolve.

So I am trying an implementation using the Microsoft.AspNetCore.Mvc.Razor library and the RazorViewToStringRenderer class from Github which seems to be frequently recommended.  My test concept application is throwing an error:

"Unable to resolve service for type 'Microsoft.Extensions.Logging.ILoggerFactory' while attempting to activate 'Microsoft.AspNetCore.Mvc.ViewFeatures.CookieTempDataProvider'."

My sample:

        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            services.AddMvcCore().AddRazorViewEngine();
            services.AddSingleton<RazorViewToStringRenderer>();

            var provider = services.BuildServiceProvider();
            var service = provider.GetRequiredService<RazorViewToStringRenderer>();
        }

The error is thrown on the last line.

The only sample code I could find online was written for .NET Core so I had to modify it, since some of the method calls aren't available to me.  I am supposed to find a solution that will work while still targeting .NET Framework.  Can someone point out if I am doing something wrong?


问:
Where is setting option that allows to change the app's location?
Basically VS Code can't update because it is located in the different location to the default one. It tries to update itself in the default location, but fails. How can I change this without uninstalling it?
Here is a picture of the error:

Here is what the log says:


问:
Struggling to find the declaration/definition of `Proxied` in ROOT
I'm trying to better understand the code in ROOT's RDataFrame and the type/class Proxied appears a lot. For example here. It seems likely to be a root specific thing, since it has methods like GetTree. I've downloaded the repo, but I haven't compiled it.

What I've tried;

Asking YouCompleteMe to automatically find it.

Grepping the dataframe folder for just Proxied. There are a lot of results for this, but none of them are a class definition or a typedef.

Grepping the whole repository with grep "class.*Proxied" . -R -I. I thought if it were defined somewhere, that would get it. No results.

Grepping the whole repository with grep "typedef.*Proxied" . -R -I, to try to find a typedef in the same manner. No results here either.

I also searched the ROOT documentation for Proxied; closest match is Proxy, which appears unrelated.

I could probably try building ROOT, and then see if then see if the the build logs held any secrets, but that seems a bit extreme for just finding out what this thing is. I don't actually need to work on ROOT right now, just understand how RDataFrame handles TChains, for which I need to know what a Proxied is.

What tips for finding declarations/definitions should I have tried here?


问:
php-fpm request_terminate_timeout catch SIGTERM
In my PHP-FPM configurations I've set the request_terminate_timeout which generates a SIGTERM when the timeout is reached.

What I would like to do is catching the signal just to write one last log to keep track that the current request has been terminated because of the timeout.

As far as I found register_shutdown_functions will not be called (https://www.php.net/manual/en/function.register-shutdown-function.php)

Shutdown functions will not be executed if the process is killed with
a SIGTERM or SIGKILL signal. While you cannot intercept a SIGKILL, you
can
use pcntl_signal() to install a handler for a SIGTERM which
uses exit() to end
cleanly.

And in web context PCNTL functions are not available (https://www.php.net/manual/en/intro.pcntl.php):

Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment.

The following statement left me searching for answers for about a day before I finally clued in:

"Process Control should not be enabled within a web server environment and unexpected results may happen if any Process Control functions are used within a web server environment."

At least for PHP 5.3.8 which I am using, and who knows how far back, it's not a matter of "should not", it's "can not". Even though I have compiled in PCNTL with --enable-pcntl, it turns out that it only compiles in to the CLI version of PHP, not the Apache module. As a result, I spent many hours trying to track down why function_exists('pcntl_fork') was returning false even though it compiled correctly. It turns out it returns true just fine from the CLI, and only returns false for HTTP requests. The same is true of ALL of the pcntl_*() functions.

So, is there something I can do to catch the SIGTERM and let me write a log?


问:
CsvMapper - unable to get get escaped quotes working
I have a file in the following format:

a,"\"b\"","c"

OpenCSV can read it fine (returning [a, "b", c]), but CsvMapper is breaking:

Exception in thread "main" java.lang.RuntimeException: Unexpected character ('b' (code 98)): Expected column separator character (',' (code 44)) or end-of-line

I've tried various combination of escape and quote characters but I can't seem to get it working - can anyone tell me what I'm doing wrong, please?

Example:

```<code>import java.io.IOException;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;

public class CsvMapperTest {
    public static void main(final String[] args) throws IOException {
    new CsvMapper().readerFor(String.class).with(CsvSchema.emptySchema()).readValues("""
        a,"\"b\"","c"
        """).forEachRemaining(System.out::println);
    }
}
</code>```

Body:
I have a file in the following format:

a,"\"b\"","c"

OpenCSV can read it fine (returning [a, "b", c]), but CsvMapper is breaking:

Exception in thread "main" java.lang.RuntimeException: Unexpected character ('b' (code 98)): Expected column separator character (',' (code 44)) or end-of-line

I've tried various combination of escape and quote characters but I can't seem to get it working - can anyone tell me what I'm doing wrong, please?

Example:

import java.io.IOException;

import com.fasterxml.jackson.dataformat.csv.CsvMapper;

public class CsvMapperTest {
    public static void main(final String[] args) throws IOException {
    new CsvMapper().readerFor(String.class).with(CsvSchema.emptySchema()).readValues("""
        a,"\"b\"","c"
        """).forEachRemaining(System.out::println);
    }
}


问:
Need details on nginx info log
I see a large number of the below info log in our nginx logs. What do these mean? There is almost no docs on these.

client terminated stream 3 with status 0 while sending request to upstream

Title: Need details on nginx info log


问:
building kivy app for ios fails (no teamID)
I created a simple app using python 3.8.10 / kivy and was able to build and deploy an Android apk.  I am now trying to build it for iOS.  Following are installed.. using homebrew: autoconf automake libtool pkg-config.  using pip: Cython==0.29.28, kivy-ios.  Tried two approaches (maybe they are the same under the covers...newbie here)

Ran buildozer ios debug.   When I initially ran this it was giving me errors about missing libraries which I installed and kept going.  I have also wiped out the .buildozer directory to get a fresh install.  About 20mins after the build process I got an error saying ios.codesign.debug was not filled in.  I thought that was odd given that this was set ios.codesign.allowed = false.  I followed the instructions in a this SO post to get the developer certificate.

When I then try the same command I get the following error

```<code># Creating IPA...
# Run 'xcodebuild -exportArchive -archivePath "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-0.1.intermediates/MyApp-0.1.xcarchive" -exportOptionsPlist "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-ios/MyApp-Info.plist" -exportPath "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-0.1.intermediates/MyApp-0.1.ipa" CODE_SIGN_IDENTITY="Apple Development: nori.sangeeta@gmail.com (AX6CHB96V5)" ENABLE_BITCODE=NO'
# Cwd /Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-ios
2022-12-07 02:52:29.932 xcodebuild[4687:2833519] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path "/var/folders/4k/q9h0y35d5f775bw_07lngvrr0000gs/T/MyApp_2022-12-07_02-52-29.930.xcdistributionlogs".
** EXPORT FAILED **

error: exportArchive: No "teamID" specified and no team ID found in the archive

Error Domain=IDEFoundationErrorDomain Code=1 "No "teamID" specified and no team ID found in the archive" UserInfo={NSLocalizedDescription=No "teamID" specified and no team ID found in the archive}
</code>```

I took that to assume that ios.codesign.development_team.debug = <hexstring> has to be filled in but I have no idea what to put there!  I tired "Personal Team" / same hex string as above, neither worked.

Following the instructions here

I am able to open xcode using open myapp-ios/myapp.xcodeproj but when I click on play, I don't get to "enjoy"(!), it tries to build and I eventually get an error.

The developer account is not a paid account and this is a simple prototype preferable without the need for codesign etc.  If/when compiled, the app will be run on just 1 iPhone 13!!

Any thoughts?

Body:
I created a simple app using python 3.8.10 / kivy and was able to build and deploy an Android apk.  I am now trying to build it for iOS.  Following are installed.. using homebrew: autoconf automake libtool pkg-config.  using pip: Cython==0.29.28, kivy-ios.  Tried two approaches (maybe they are the same under the covers...newbie here)

Ran buildozer ios debug.   When I initially ran this it was giving me errors about missing libraries which I installed and kept going.  I have also wiped out the .buildozer directory to get a fresh install.  About 20mins after the build process I got an error saying ios.codesign.debug was not filled in.  I thought that was odd given that this was set ios.codesign.allowed = false.  I followed the instructions in a this SO post to get the developer certificate.

When I then try the same command I get the following error

# Creating IPA...
# Run 'xcodebuild -exportArchive -archivePath "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-0.1.intermediates/MyApp-0.1.xcarchive" -exportOptionsPlist "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-ios/MyApp-Info.plist" -exportPath "/Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-0.1.intermediates/MyApp-0.1.ipa" CODE_SIGN_IDENTITY="Apple Development: nori.sangeeta@gmail.com (AX6CHB96V5)" ENABLE_BITCODE=NO'
# Cwd /Users/<snip>/MyApp/.buildozer/ios/platform/kivy-ios/MyApp-ios
2022-12-07 02:52:29.932 xcodebuild[4687:2833519] [MT] IDEDistribution: -[IDEDistributionLogging _createLoggingBundleAtPath:]: Created bundle at path "/var/folders/4k/q9h0y35d5f775bw_07lngvrr0000gs/T/MyApp_2022-12-07_02-52-29.930.xcdistributionlogs".
** EXPORT FAILED **

error: exportArchive: No "teamID" specified and no team ID found in the archive

Error Domain=IDEFoundationErrorDomain Code=1 "No "teamID" specified and no team ID found in the archive" UserInfo={NSLocalizedDescription=No "teamID" specified and no team ID found in the archive}

I took that to assume that ios.codesign.development_team.debug = <hexstring> has to be filled in but I have no idea what to put there!  I tired "Personal Team" / same hex string as above, neither worked.

Following the instructions here

I am able to open xcode using open myapp-ios/myapp.xcodeproj but when I click on play, I don't get to "enjoy"(!), it tries to build and I eventually get an error.

The developer account is not a paid account and this is a simple prototype preferable without the need for codesign etc.  If/when compiled, the app will be run on just 1 iPhone 13!!

Any thoughts?


问:
How can I get my data to show as percentages on an Rmarkdown (HTML)
I have the following code:

```<code>proportion_ts <- function(wt, site) {
  wt %>%
    filter(Area == site) %>%
    group_by(month_yr) %>%
    summarise(`ATR` = sum(atrreqt == "ATR")/sum(co_sso_flag == "CO_SSO"),
              `DRR` = sum(drrreqt =="DRR")/sum(co_sso_flag == "CO_SSO"),
              `MHTR` = sum(mhtrreqt == "MHTR")/sum(co_sso_flag == "CO_SSO"))
</code>```

It produces my time series graph for proportions in a HTML output in Rmd. Currently when I hover over the time series it shows data as a decimal but I need it to present as a percentage. Can anyone help?

Body:
I have the following code:

proportion_ts <- function(wt, site) {
  wt %>%
    filter(Area == site) %>%
    group_by(month_yr) %>%
    summarise(`ATR` = sum(atrreqt == "ATR")/sum(co_sso_flag == "CO_SSO"),
              `DRR` = sum(drrreqt =="DRR")/sum(co_sso_flag == "CO_SSO"),
              `MHTR` = sum(mhtrreqt == "MHTR")/sum(co_sso_flag == "CO_SSO"))

It produces my time series graph for proportions in a HTML output in Rmd. Currently when I hover over the time series it shows data as a decimal but I need it to present as a percentage. Can anyone help?


问:
FileNotFoundException: Could not find file. Path given appears to correct maybe needs permissions?
Hi im building an app for android via unity and I am trying to access a file on my computer for testing purposes.

```<code>var stream = File.Open(@"C:\Users\LIA\Documents\wat.txt", FileMode.Open);
        bool ifexists = File.Exists(@"C:\Users\LIA\Documents\wat.txt");
</code>```

Once i run the code avoce i get an " FileNotFoundException: Could not find file "/C:\Users\LIA\Documents\wat.txt" " error on the logcat.

I am running the build on an external android device connected to the pc via USB, do I need to add permissions anywhere on unity so the android device can access these files ? Or is the error related to some other factor? I have tried running unity as admin but same error applied.

Appeciate any help, thx.

Error message:

File Location:

Full code:

```<code>        var stream = File.Open(@"C:\Users\LIA\Documents\wat.txt", FileMode.Open);
     //   bool ifexists = File.Exists(@"C:\Users\LIA\Documents\wat.txt");

     //       Debug.Log("1: " + stream.ToString() + ifexists);

        //Firestore Reference
        storage = FirebaseStorage.DefaultInstance;
        storageReference = storage.GetReferenceFromUrl("gs://houdini-ac884.appspot.com");

        //Uploading to firestore
        StorageReference uploadRef = storageReference.Child("uploads/newFile.meta"); // Name of file
        Debug.Log("Beginning Upload;;");
        uploadRef.PutFileAsync(stream.ToString()).ContinueWithOnMainThread((task) => {
            if(task.IsFaulted || task.IsCanceled){
                Debug.Log("Upload Failed with following error:");
                Debug.Log(task.Exception.ToString());
            }else{
                Debug.Log("File Uploaded with success");
            }
        });
</code>```

Body:
Hi im building an app for android via unity and I am trying to access a file on my computer for testing purposes.

var stream = File.Open(@"C:\Users\LIA\Documents\wat.txt", FileMode.Open);
        bool ifexists = File.Exists(@"C:\Users\LIA\Documents\wat.txt");

Once i run the code avoce i get an " FileNotFoundException: Could not find file "/C:\Users\LIA\Documents\wat.txt" " error on the logcat.

I am running the build on an external android device connected to the pc via USB, do I need to add permissions anywhere on unity so the android device can access these files ? Or is the error related to some other factor? I have tried running unity as admin but same error applied.

Appeciate any help, thx.

Error message:

File Location:

Full code:

        var stream = File.Open(@"C:\Users\LIA\Documents\wat.txt", FileMode.Open);
     //   bool ifexists = File.Exists(@"C:\Users\LIA\Documents\wat.txt");

     //       Debug.Log("1: " + stream.ToString() + ifexists);

        //Firestore Reference
        storage = FirebaseStorage.DefaultInstance;
        storageReference = storage.GetReferenceFromUrl("gs://houdini-ac884.appspot.com");

        //Uploading to firestore
        StorageReference uploadRef = storageReference.Child("uploads/newFile.meta"); // Name of file
        Debug.Log("Beginning Upload;;");
        uploadRef.PutFileAsync(stream.ToString()).ContinueWithOnMainThread((task) => {
            if(task.IsFaulted || task.IsCanceled){
                Debug.Log("Upload Failed with following error:");
                Debug.Log(task.Exception.ToString());
            }else{
                Debug.Log("File Uploaded with success");
            }
        });


问:
Manual Benders Algorithm with CPLEX in python
I have written a manual benders algorithm on python. I utilize CPLEX to solve both master and subproblems.

My problem is, the algorithm never ends. I debugged and found out that even though it adds a new constraint (I do not know how to see the added constraint, I can only see the number of constraints in the master problem increases), the upper and lower bounds never change, the solutions for the sub and master problems are always the same.

Do you see anything extraordinary with the code?

Is there a way that CPLEX allow me to see the added constraints while debugging the code?

Am I adding the optimality cuts in a wrong way?

Is there a more efficient way to solve this problem after splitting the master and subproblems? (I know CPLEX's automatic solver, as far as I know it only solves if you provide the original formulation.)

The code is as follows:

```<code>while abs(UB-LB)>8:
    sub.solve()
    sub_obj_value=sub_obj.solution_value
    UB=sub_obj_value
    for j in range(facility):
        u_bar[j]=u[j].solution_value
    master.add_constraint(q <=master.sum(-var[i,j]*u_bar[j]*x[i,j] for i in range(demand) for j in range(facility)), ctname='new constraint')
    master.solve()
    for i in range(demand):
        for j in range(facility):
            x_bar[i,j]=x[i,j].solution_value
    master_obj_value=master_obj.solution_value
    q_value=q.solution_value
    LB=q_value
    iter=iter+1
</code>```

x is the decision variable for the master problem.

u is the decision variable for the subproblem.

q is the variable for the optimality cut in the master problem.

var is a parameter.

Btw, code is not quite efficient. If you have any suggestions on that too, I'd love to hear.

Edit:

Objective of the Subproblem:

```<code>sub_obj = sub.sum((var[i,j]*x_bar[i,j]*u[j] for i in range(demand) for j in range(facility)))
sub.set_objective("max", sub_obj)
</code>```

Body:
I have written a manual benders algorithm on python. I utilize CPLEX to solve both master and subproblems.

My problem is, the algorithm never ends. I debugged and found out that even though it adds a new constraint (I do not know how to see the added constraint, I can only see the number of constraints in the master problem increases), the upper and lower bounds never change, the solutions for the sub and master problems are always the same.

Do you see anything extraordinary with the code?

Is there a way that CPLEX allow me to see the added constraints while debugging the code?

Am I adding the optimality cuts in a wrong way?

Is there a more efficient way to solve this problem after splitting the master and subproblems? (I know CPLEX's automatic solver, as far as I know it only solves if you provide the original formulation.)

The code is as follows:

while abs(UB-LB)>8:
    sub.solve()
    sub_obj_value=sub_obj.solution_value
    UB=sub_obj_value
    for j in range(facility):
        u_bar[j]=u[j].solution_value
    master.add_constraint(q <=master.sum(-var[i,j]*u_bar[j]*x[i,j] for i in range(demand) for j in range(facility)), ctname='new constraint')
    master.solve()
    for i in range(demand):
        for j in range(facility):
            x_bar[i,j]=x[i,j].solution_value
    master_obj_value=master_obj.solution_value
    q_value=q.solution_value
    LB=q_value
    iter=iter+1

x is the decision variable for the master problem.

u is the decision variable for the subproblem.

q is the variable for the optimality cut in the master problem.

var is a parameter.

Btw, code is not quite efficient. If you have any suggestions on that too, I'd love to hear.

Edit:

Objective of the Subproblem:

sub_obj = sub.sum((var[i,j]*x_bar[i,j]*u[j] for i in range(demand) for j in range(facility)))
sub.set_objective("max", sub_obj)


问:
Use gitlab-ci variables in java sping boot application
I would like to use predefined GitLab CI/CD variable -e gitlab-user-email="$GITLAB_USER_EMAIL" (that's a part of .gitlab-ci.yml file's deployment job) in my java spring boot application

My java code:

```<code>@Service
public class LocalEmailSenderStartupTest {
    Logger logger = Logger.getLogger(LocalEmailSenderStartupTest.class);

    @Value("${gitlab-user-email}")
    private String gitlabUserEmail;
</code>```

How can this be done?

Body:
I would like to use predefined GitLab CI/CD variable -e gitlab-user-email="$GITLAB_USER_EMAIL" (that's a part of .gitlab-ci.yml file's deployment job) in my java spring boot application

My java code:

@Service
public class LocalEmailSenderStartupTest {
    Logger logger = Logger.getLogger(LocalEmailSenderStartupTest.class);

    @Value("${gitlab-user-email}")
    private String gitlabUserEmail;

How can this be done?


问:
Vue 3: How to type Functional Component props with TypeScript
When I use TypeScript I prefer typing Vue component props with it like:

```<code>defineProps<{ name: string }>()
</code>```

I am experimenting with Functional components and I want to do the same: Type Functional Component Props with TypeScript and in general enable TypeScript support when using Functional Components.

After some digging all around, I found that there is a FunctionalComponent type and that enabled some Intellisense:

```

<p>That works great and I get auto-completion but according to the docs:</p>
<blockquote>
<p>The prop names will not be normalized to camelCase unless the props option is specified.</p>
</blockquote>
<p>So if I pass <code>my-name</code> like <code><MyComponent my-name="SO friend" /></code> as a prop that will not work as a normal prop, so I will have to access it like <code>props['my-name']</code> instead of <code>props.myName</code>.</p>
<p>So I should specify <code>props</code> but according to the docs, that can be done using the Object Syntax:</p>
```const MyComponent = /*...*/

MyComponent.props = { name: { type: String, required: true } }
```
<p>I don't want to do with Object Syntax because then I lose IntelliSense for props but also I would prefer to just use TypeScript as I do with defineProps. Currently I found a workaround which I don't like too much (as it doesn't work 100%):</p>
```import type { FunctionalComponent, ExtractPropTypes } from 'vue'

const componentProps = { name: { type: String, required: true } }
type componentPropsType = ExtractPropTypes<typeof componentProps>

const MyComponent: FunctionalComponent<componentPropsType> = /*...*/

MyComponent.props = componentProps
```

With this workaround, typing are provided for props and props are normalized though somehow this ExtractPropTypes isn't inferring the required property.

No matter what I do, I don't get any IDE highlights that props are not passed into the component using VSCode or Webstorm. Also all these workarounds look like "hacks" and in the docs I don't find any mention about how to type Functional Components.

Anyone knows how to properly do it?

Body:
When I use TypeScript I prefer typing Vue component props with it like:

defineProps<{ name: string }>()

I am experimenting with Functional components and I want to do the same: Type Functional Component Props with TypeScript and in general enable TypeScript support when using Functional Components.

After some digging all around, I found that there is a FunctionalComponent type and that enabled some Intellisense:

That works great and I get auto-completion but according to the docs:

The prop names will not be normalized to camelCase unless the props option is specified.

So if I pass my-name like <MyComponent my-name="SO friend" /> as a prop that will not work as a normal prop, so I will have to access it like props['my-name'] instead of props.myName.

So I should specify props but according to the docs, that can be done using the Object Syntax:

const MyComponent = /*...*/

MyComponent.props = { name: { type: String, required: true } }

I don't want to do with Object Syntax because then I lose IntelliSense for props but also I would prefer to just use TypeScript as I do with defineProps. Currently I found a workaround which I don't like too much (as it doesn't work 100%):

import type { FunctionalComponent, ExtractPropTypes } from 'vue'

const componentProps = { name: { type: String, required: true } }
type componentPropsType = ExtractPropTypes<typeof componentProps>

const MyComponent: FunctionalComponent<componentPropsType> = /*...*/

MyComponent.props = componentProps

With this workaround, typing are provided for props and props are normalized though somehow this ExtractPropTypes isn't inferring the required property.

No matter what I do, I don't get any IDE highlights that props are not passed into the component using VSCode or Webstorm. Also all these workarounds look like "hacks" and in the docs I don't find any mention about how to type Functional Components.

Anyone knows how to properly do it?


问:
Calling a namespaced callback function by name
This is probably basic...  given a fully qualified function name, I'm trying to call it via .apply()

Superficial example

```<code>var ns = {
    someFunc: function() { console.log('stuff'); }
}

function someTopLevelFunc() { console.log('top level'); }
</code>```

Given a method that takes the name of that function, us there some way to call the namespaced function?

function theCaller(funcName) {
  console.log("Callback name: " + callbackFunctionName)
  const callbackFunction = window[callbackFunctionName];
  console.log("Type: " + (typeof callbackFunction))

  if((typeof callbackFunction) === "function") {
     callbackFunction.apply(null, []);
  }
}

theCaller('topLevelFunc');
theCaller('ns.someFunc');
```

The first call works while the second call shows the callbackFunction type as undefined

Probably a simple syntax issue, but my googling has failed me.

Body:
This is probably basic...  given a fully qualified function name, I'm trying to call it via .apply()

Superficial example

var ns = {
    someFunc: function() { console.log('stuff'); }
}

function someTopLevelFunc() { console.log('top level'); }

Given a method that takes the name of that function, us there some way to call the namespaced function?

function theCaller(funcName) {
  console.log("Callback name: " + callbackFunctionName)
  const callbackFunction = window[callbackFunctionName];
  console.log("Type: " + (typeof callbackFunction))

  if((typeof callbackFunction) === "function") {
     callbackFunction.apply(null, []);
  }
}

theCaller('topLevelFunc');
theCaller('ns.someFunc');

The first call works while the second call shows the callbackFunction type as undefined

Probably a simple syntax issue, but my googling has failed me.


问:
Saving output from a for loop in a dictionary (python)
I have a for loop that goes through dataframes:

```<code>dataframes = [df_1, df_oslo_2, df_3, df_4, df_5]
cost_dict = {}

for name in dataframes:
    df = name
    list_cost = df.loc[5:128, ['A','B', 'C']].values.tolist()
    list_cost_tuple = tuple(tuple(sub) for sub in list_cost)
    cost_dict[name] = list_cost_tuple

</code>```

I want to save them in a dictionary but I i get an error: TypeError: unhashable type: 'DataFrame'

Is there anything wrong with the loop i made, or is it not possible to store it in a dictionary?

Body:
I have a for loop that goes through dataframes:

dataframes = [df_1, df_oslo_2, df_3, df_4, df_5]
cost_dict = {}

for name in dataframes:
    df = name
    list_cost = df.loc[5:128, ['A','B', 'C']].values.tolist()
    list_cost_tuple = tuple(tuple(sub) for sub in list_cost)
    cost_dict[name] = list_cost_tuple

I want to save them in a dictionary but I i get an error: TypeError: unhashable type: 'DataFrame'

Is there anything wrong with the loop i made, or is it not possible to store it in a dictionary?


问:
Somewhat Resolved: Problem with Upsampling for Image Classification
I have an image dataset of 12 classes. I'm comparing some different techniques of upsampling for image classication and wanted to upsample the classes that are massively imbalanced using SMOTE.

I defined by training set as seen below:

```<code>img_height = 256
img_width = 256
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
  image_directory,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)
</code>```

Output : "Found 11730 files belonging to 12 classes.
Using 9384 files for training."

The problem is, from my understanding, is that in order to upsample with SMOTE, I have to actually have a defined x_train & y_train. I attempted to do so with

```<code>for images, labels in train_ds:  # only take first element of dataset
    numpy_images = images.numpy()
    numpy_labels = labels.numpy()
    numpy_images.shape

</code>```

The shape returns (8,256, 256, 3). This "8" feels out of place. I imagined that the shape would be the length of my training set, but maybe I'm misunderstanding.

I re-shaped the numpy array to make it 2D to be passed through SMOTE

```<code>x_train = numpy_images.reshape(8, 256 * 256 * 3)
x_train.shape
</code>```

The shape returns (8, 196608)

```<code>from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=42)
X_smote, y_smote = SMOTE(k_neighbors=2).fit_resample(x_train, numpy_labels)
</code>```

Finally, the above returns the error that n_samples = 1, n_neighbors = 2.

My questions are

How do I resolve this issue?

Why would the shape be (8, 256, 256, 3) instead of (9384, 256, 256, 3)?

Any help is appreciated!

SMOTE initialisation expects n_neighbors <= n_samples, but n_samples < n_neighbors

^This forum was extremely helpful but I still can't explain the shape of my numpy array.

My solution: I ended up just duplicating a specified number of images for each of the underrepresented categories. I did the preceding in File Explorer.

Body:
I have an image dataset of 12 classes. I'm comparing some different techniques of upsampling for image classication and wanted to upsample the classes that are massively imbalanced using SMOTE.

I defined by training set as seen below:

img_height = 256
img_width = 256
batch_size = 32
train_ds = tf.keras.utils.image_dataset_from_directory(
  image_directory,
  validation_split=0.2,
  subset="training",
  seed=123,
  image_size=(img_height, img_width),
  batch_size=batch_size)

Output : "Found 11730 files belonging to 12 classes.
Using 9384 files for training."

The problem is, from my understanding, is that in order to upsample with SMOTE, I have to actually have a defined x_train & y_train. I attempted to do so with

for images, labels in train_ds:  # only take first element of dataset
    numpy_images = images.numpy()
    numpy_labels = labels.numpy()
    numpy_images.shape

The shape returns (8,256, 256, 3). This "8" feels out of place. I imagined that the shape would be the length of my training set, but maybe I'm misunderstanding.

I re-shaped the numpy array to make it 2D to be passed through SMOTE

x_train = numpy_images.reshape(8, 256 * 256 * 3)
x_train.shape

The shape returns (8, 196608)

from imblearn.over_sampling import SMOTE
sm = SMOTE(random_state=42)
X_smote, y_smote = SMOTE(k_neighbors=2).fit_resample(x_train, numpy_labels)

Finally, the above returns the error that n_samples = 1, n_neighbors = 2.

My questions are

How do I resolve this issue?

Why would the shape be (8, 256, 256, 3) instead of (9384, 256, 256, 3)?

Any help is appreciated!

SMOTE initialisation expects n_neighbors <= n_samples, but n_samples < n_neighbors

^This forum was extremely helpful but I still can't explain the shape of my numpy array.

My solution: I ended up just duplicating a specified number of images for each of the underrepresented categories. I did the preceding in File Explorer.


问:
How to modify the reading/parsing of an Excel Column in a data Frame?
I am trying to process an Excel file with Pandas. The filter to be applied is by the values of the "Test Code" column which has the format "XX10.X/XX12.X" (i.e: EF10.1). The problem is that the dataframe and neglects everything after the dot when reading the column, leaving just "XX10". The information after the dot is the most important information.

The original document classifies those cells as a date, which probably is altering the normal processing of the values.

excelfile

The code I am using is:

```<code>import os
import pandas as pd
file = "H2020_TRI-HP_T6.2_PropaneIceFaultTests_v1"
folder = "J:\Downloads"
file_path = os.path.join(folder,file+".xlsx")
df = pd.read_excel(file_path,sheet_name="NF10")
df["Test Code"]
</code>```

The output is:
output

Body:
I am trying to process an Excel file with Pandas. The filter to be applied is by the values of the "Test Code" column which has the format "XX10.X/XX12.X" (i.e: EF10.1). The problem is that the dataframe and neglects everything after the dot when reading the column, leaving just "XX10". The information after the dot is the most important information.

The original document classifies those cells as a date, which probably is altering the normal processing of the values.

excelfile

The code I am using is:

import os
import pandas as pd
file = "H2020_TRI-HP_T6.2_PropaneIceFaultTests_v1"
folder = "J:\Downloads"
file_path = os.path.join(folder,file+".xlsx")
df = pd.read_excel(file_path,sheet_name="NF10")
df["Test Code"]

The output is:
output


问:
Why am I getting Unknown column '' in 'field list' (sequelize)?
I am working with node, express and sequelize (I'm pretty new with all these three) and I'm getting "Unknown column 'productTeam' in 'field list'" in what I think is the simplest possible scenario:

In my backend code, I have the following:

    const repos = await ScasRepo.findAll(
        {
            where: {"productId": productId}
        }
    )
```
<p>I can see that the generated query is as follows:</p>
```Executing (default):
SELECT `id`, `productTeam`, `productId`
FROM `ScasRepos` AS `ScasRepo`
WHERE `ScasRepo`.`productId` = '10519';
```
<p>And this is what my table looks like:</p>
```
mysql> describe ScasRepos;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| id             | int          | NO   | PRI | NULL    | auto_increment |
| productId      | int          | YES  |     | NULL    |                |
| productTeam    | varchar(255) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+
```

As you can see, the productTeam field is defined in the table, so why am I getting an error message saying "Unknown column 'productTeam' in 'field list'"?

Any insight is appreciated!

Body:
I am working with node, express and sequelize (I'm pretty new with all these three) and I'm getting "Unknown column 'productTeam' in 'field list'" in what I think is the simplest possible scenario:

In my backend code, I have the following:

    const repos = await ScasRepo.findAll(
        {
            where: {"productId": productId}
        }
    )

I can see that the generated query is as follows:

Executing (default):
SELECT `id`, `productTeam`, `productId`
FROM `ScasRepos` AS `ScasRepo`
WHERE `ScasRepo`.`productId` = '10519';

And this is what my table looks like:

mysql> describe ScasRepos;
+----------------+--------------+------+-----+---------+----------------+
| Field          | Type         | Null | Key | Default | Extra          |
+----------------+--------------+------+-----+---------+----------------+
| id             | int          | NO   | PRI | NULL    | auto_increment |
| productId      | int          | YES  |     | NULL    |                |
| productTeam    | varchar(255) | YES  |     | NULL    |                |
+----------------+--------------+------+-----+---------+----------------+

As you can see, the productTeam field is defined in the table, so why am I getting an error message saying "Unknown column 'productTeam' in 'field list'"?

Any insight is appreciated!


问:
Python/Django MakeMigrations Error Traceback
Here is what appears when i try to use python manage.py makemigrations

traceback error

Here is models.py code

----------------------code-------------------------------------

```<code>from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=255, db_index=True)
    slug = models.SlugField(max_length=255, unique=True)

    class Meta:
        verbose_name_plural = 'categories'

#   def get_absolute_url(self):
#      return reverse("store:category_list", args=[self.slug])

    def __str__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255,default='admin')
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='images/')
    slug = models.SlugField(max_length=255)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Products'
        ordering = ('-created',)

    def __str__(self):
        return self.title

</code>```

------------------code end-------------------------------

im new and i dont know whats the problem

Body:
Here is what appears when i try to use python manage.py makemigrations

traceback error

Here is models.py code

----------------------code-------------------------------------

from django.db import models
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=255, db_index=True)
    slug = models.SlugField(max_length=255, unique=True)

    class Meta:
        verbose_name_plural = 'categories'

#   def get_absolute_url(self):
#      return reverse("store:category_list", args=[self.slug])

    def __str__(self):
        return self.name

class Product(models.Model):
    category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
    created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=255,default='admin')
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to='images/')
    slug = models.SlugField(max_length=255)
    price = models.DecimalField(max_digits=4, decimal_places=2)
    in_stock = models.BooleanField(default=True)
    is_active = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)

    class Meta:
        verbose_name_plural = 'Products'
        ordering = ('-created',)

    def __str__(self):
        return self.title

------------------code end-------------------------------

im new and i dont know whats the problem


问:
Unable to call SOAP service using apache call method
Following code for calling SOAP webservice

```<code>String serviceURL="http://cbswebpr.ptcl.net.pk/QueryBillInfoServices?wsdl";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(serviceURL));
call.setPortTypeName(new QName("http://ocs.ztesoft.com/xsd","QueryBillInfoServices"));
call.setOperationName(new QName("http://ocs.ztesoft.com/xsd", "queryBillInfo"));
call.setUsername("abc");
call.setPassword("1234");

 call.addParameter("computerId", org.apache.axis.Constants.SOAP_STRING,ParameterMode.IN);
 call.addParameter("number", org.apache.axis.Constants.SOAP_STRING ,ParameterMode.IN);
 call.addParameter("packetType",org.apache.axis.Constants.SOAP_STRING ,ParameterMode.IN);

String computerId="192.168.1.1";
String number="0931231313";
String packetType="R9";
String returnValue = (String) call.invoke(new Object[] {computerId,number,packetType});
</code>```

Getting following error

xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode xmlns:nsIDc08="http://schemas.xmlsoap.org/soap/envelope/">nsIDc08:Client</faultcode><faultstring>Fail to find service because request URI is not start with service path [/services/].</faultstring></soapenv:Fault></soapenv:Body></soapenv:Envelope>
    {http://xml.apache.org/axis/}HttpErrorCode:400
```
<p>WSDL</p>
```<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ocs.ztesoft.com/xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" name="QueryBillInfoServices" targetNamespace="http://ocs.ztesoft.com/xsd">
<wsdl:types>
<xs:schema xmlns:tns="http://ocs.ztesoft.com/xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://ocs.ztesoft.com/xsd">
<xs:element name="queryBillInfo" type="tns:queryBillInfo"/>
<xs:element name="queryBillInfoResponse" type="tns:queryBillInfoResponse"/>
<xs:complexType name="queryBillInfo">
<xs:sequence>
<xs:element minOccurs="0" name="QueryBillInfoReq" type="tns:queryBillInfoReq"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoReq">
<xs:sequence>
<xs:element minOccurs="0" name="addCode" type="xs:string"/>
<xs:element minOccurs="0" name="bankCode" type="xs:string"/>
<xs:element minOccurs="0" name="beginNum" type="xs:string"/>
<xs:element minOccurs="0" name="computerId" type="xs:string"/>
<xs:element minOccurs="0" name="contactNumber" type="xs:string"/>
<xs:element minOccurs="0" name="endNum" type="xs:string"/>
<xs:element minOccurs="0" name="esnNumber" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceNbr" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceTag" type="xs:string"/>
<xs:element minOccurs="0" name="locationId" type="xs:string"/>
<xs:element minOccurs="0" name="mdn" type="xs:string"/>
<xs:element minOccurs="0" name="number" type="xs:string"/>
<xs:element minOccurs="0" name="packetType" type="xs:string"/>
<xs:element minOccurs="0" name="queryType" type="xs:string"/>
<xs:element minOccurs="0" name="transNumber" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="header">
<xs:sequence>
<xs:element minOccurs="0" name="passWord" type="xs:string"/>
<xs:element minOccurs="0" name="userName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoResponse">
<xs:sequence>
<xs:element minOccurs="0" name="return" type="tns:queryBillInfoResp"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoResp">
<xs:sequence>
<xs:element minOccurs="0" name="accNbr" type="xs:string"/>
<xs:element minOccurs="0" name="acctId" type="xs:string"/>
<xs:element minOccurs="0" name="address" type="xs:string"/>
<xs:element minOccurs="0" name="areaCode" type="xs:string"/>
<xs:element minOccurs="0" name="balance" type="xs:string"/>
<xs:element minOccurs="0" name="billNbr" type="xs:string"/>
<xs:element minOccurs="0" name="billState" type="xs:string"/>
<xs:element minOccurs="0" name="chargingTime" type="xs:string"/>
<xs:element minOccurs="0" name="custId" type="xs:string"/>
<xs:element minOccurs="0" name="customerName" type="xs:string"/>
<xs:element minOccurs="0" name="dueDate" type="xs:string"/>
<xs:element minOccurs="0" name="esn" type="xs:string"/>
<xs:element minOccurs="0" name="installationDate" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceNbr" type="xs:string"/>
<xs:element minOccurs="0" name="latnId" type="xs:string"/>
<xs:element minOccurs="0" name="mdn" type="xs:string"/>
<xs:element minOccurs="0" name="mdnLocked" type="xs:string"/>
<xs:element minOccurs="0" name="mdnLockedCode" type="xs:string"/>
<xs:element minOccurs="0" name="mdnState" type="xs:string"/>
<xs:element minOccurs="0" name="mdnStateCode" type="xs:string"/>
<xs:element minOccurs="0" name="mdnSubscriberType" type="xs:string"/>
<xs:element minOccurs="0" name="mobile" type="xs:string"/>
<xs:element minOccurs="0" name="mobileNo" type="xs:string"/>
<xs:element minOccurs="0" name="payAfterDueDate" type="xs:string"/>
<xs:element minOccurs="0" name="payByDueDate" type="xs:string"/>
<xs:element minOccurs="0" name="resultCode" type="xs:string"/>
<xs:element minOccurs="0" name="resultMsg" type="xs:string"/>
<xs:element minOccurs="0" name="transNumber" type="xs:string"/>
<xs:element minOccurs="0" name="validForPayment" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="AuthHeader" nillable="true" type="tns:header"/>
</xs:schema>
</wsdl:types>
<wsdl:message name="queryBillInfoResponse">
<wsdl:part name="parameters" element="tns:queryBillInfoResponse"> </wsdl:part>
</wsdl:message>
<wsdl:message name="queryBillInfo">
<wsdl:part name="parameters" element="tns:queryBillInfo"> </wsdl:part>
<wsdl:part name="AuthHeader" element="tns:AuthHeader"> </wsdl:part>
</wsdl:message>
<wsdl:portType name="QueryBillInfoServices">
<wsdl:operation name="queryBillInfo">
<wsdl:input name="queryBillInfo" message="tns:queryBillInfo"> </wsdl:input>
<wsdl:output name="queryBillInfoResponse" message="tns:queryBillInfoResponse"> </wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="QueryBillInfoServicesSoapBinding" type="tns:QueryBillInfoServices">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="queryBillInfo">
<soap:operation soapAction="" style="document"/>
<wsdl:input name="queryBillInfo">
<soap:header message="tns:queryBillInfo" part="AuthHeader" use="literal"> </soap:header>
<soap:body parts="parameters" use="literal"/>
</wsdl:input>
<wsdl:output name="queryBillInfoResponse">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="QueryBillInfoServices">
<wsdl:port name="QueryBillInfoServicesPort" binding="tns:QueryBillInfoServicesSoapBinding">
<soap:address location="http://cbswebpr.ptcl.net.pk:8180/services/QueryBillInfoServices/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>
```

Body:
Following code for calling SOAP webservice

String serviceURL="http://cbswebpr.ptcl.net.pk/QueryBillInfoServices?wsdl";
Service service = new Service();
Call call = (Call) service.createCall();
call.setTargetEndpointAddress(new URL(serviceURL));
call.setPortTypeName(new QName("http://ocs.ztesoft.com/xsd","QueryBillInfoServices"));
call.setOperationName(new QName("http://ocs.ztesoft.com/xsd", "queryBillInfo"));
call.setUsername("abc");
call.setPassword("1234");

 call.addParameter("computerId", org.apache.axis.Constants.SOAP_STRING,ParameterMode.IN);
 call.addParameter("number", org.apache.axis.Constants.SOAP_STRING ,ParameterMode.IN);
 call.addParameter("packetType",org.apache.axis.Constants.SOAP_STRING ,ParameterMode.IN);

String computerId="192.168.1.1";
String number="0931231313";
String packetType="R9";
String returnValue = (String) call.invoke(new Object[] {computerId,number,packetType});

Getting following error

xml version='1.0' encoding='utf-8'?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body><soapenv:Fault><faultcode xmlns:nsIDc08="http://schemas.xmlsoap.org/soap/envelope/">nsIDc08:Client</faultcode><faultstring>Fail to find service because request URI is not start with service path [/services/].</faultstring></soapenv:Fault></soapenv:Body></soapenv:Envelope>
    {http://xml.apache.org/axis/}HttpErrorCode:400

WSDL

<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" xmlns:tns="http://ocs.ztesoft.com/xsd" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/" name="QueryBillInfoServices" targetNamespace="http://ocs.ztesoft.com/xsd">
<wsdl:types>
<xs:schema xmlns:tns="http://ocs.ztesoft.com/xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" attributeFormDefault="unqualified" elementFormDefault="unqualified" targetNamespace="http://ocs.ztesoft.com/xsd">
<xs:element name="queryBillInfo" type="tns:queryBillInfo"/>
<xs:element name="queryBillInfoResponse" type="tns:queryBillInfoResponse"/>
<xs:complexType name="queryBillInfo">
<xs:sequence>
<xs:element minOccurs="0" name="QueryBillInfoReq" type="tns:queryBillInfoReq"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoReq">
<xs:sequence>
<xs:element minOccurs="0" name="addCode" type="xs:string"/>
<xs:element minOccurs="0" name="bankCode" type="xs:string"/>
<xs:element minOccurs="0" name="beginNum" type="xs:string"/>
<xs:element minOccurs="0" name="computerId" type="xs:string"/>
<xs:element minOccurs="0" name="contactNumber" type="xs:string"/>
<xs:element minOccurs="0" name="endNum" type="xs:string"/>
<xs:element minOccurs="0" name="esnNumber" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceNbr" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceTag" type="xs:string"/>
<xs:element minOccurs="0" name="locationId" type="xs:string"/>
<xs:element minOccurs="0" name="mdn" type="xs:string"/>
<xs:element minOccurs="0" name="number" type="xs:string"/>
<xs:element minOccurs="0" name="packetType" type="xs:string"/>
<xs:element minOccurs="0" name="queryType" type="xs:string"/>
<xs:element minOccurs="0" name="transNumber" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="header">
<xs:sequence>
<xs:element minOccurs="0" name="passWord" type="xs:string"/>
<xs:element minOccurs="0" name="userName" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoResponse">
<xs:sequence>
<xs:element minOccurs="0" name="return" type="tns:queryBillInfoResp"/>
</xs:sequence>
</xs:complexType>
<xs:complexType name="queryBillInfoResp">
<xs:sequence>
<xs:element minOccurs="0" name="accNbr" type="xs:string"/>
<xs:element minOccurs="0" name="acctId" type="xs:string"/>
<xs:element minOccurs="0" name="address" type="xs:string"/>
<xs:element minOccurs="0" name="areaCode" type="xs:string"/>
<xs:element minOccurs="0" name="balance" type="xs:string"/>
<xs:element minOccurs="0" name="billNbr" type="xs:string"/>
<xs:element minOccurs="0" name="billState" type="xs:string"/>
<xs:element minOccurs="0" name="chargingTime" type="xs:string"/>
<xs:element minOccurs="0" name="custId" type="xs:string"/>
<xs:element minOccurs="0" name="customerName" type="xs:string"/>
<xs:element minOccurs="0" name="dueDate" type="xs:string"/>
<xs:element minOccurs="0" name="esn" type="xs:string"/>
<xs:element minOccurs="0" name="installationDate" type="xs:string"/>
<xs:element minOccurs="0" name="invoiceNbr" type="xs:string"/>
<xs:element minOccurs="0" name="latnId" type="xs:string"/>
<xs:element minOccurs="0" name="mdn" type="xs:string"/>
<xs:element minOccurs="0" name="mdnLocked" type="xs:string"/>
<xs:element minOccurs="0" name="mdnLockedCode" type="xs:string"/>
<xs:element minOccurs="0" name="mdnState" type="xs:string"/>
<xs:element minOccurs="0" name="mdnStateCode" type="xs:string"/>
<xs:element minOccurs="0" name="mdnSubscriberType" type="xs:string"/>
<xs:element minOccurs="0" name="mobile" type="xs:string"/>
<xs:element minOccurs="0" name="mobileNo" type="xs:string"/>
<xs:element minOccurs="0" name="payAfterDueDate" type="xs:string"/>
<xs:element minOccurs="0" name="payByDueDate" type="xs:string"/>
<xs:element minOccurs="0" name="resultCode" type="xs:string"/>
<xs:element minOccurs="0" name="resultMsg" type="xs:string"/>
<xs:element minOccurs="0" name="transNumber" type="xs:string"/>
<xs:element minOccurs="0" name="validForPayment" type="xs:string"/>
</xs:sequence>
</xs:complexType>
<xs:element name="AuthHeader" nillable="true" type="tns:header"/>
</xs:schema>
</wsdl:types>
<wsdl:message name="queryBillInfoResponse">
<wsdl:part name="parameters" element="tns:queryBillInfoResponse"> </wsdl:part>
</wsdl:message>
<wsdl:message name="queryBillInfo">
<wsdl:part name="parameters" element="tns:queryBillInfo"> </wsdl:part>
<wsdl:part name="AuthHeader" element="tns:AuthHeader"> </wsdl:part>
</wsdl:message>
<wsdl:portType name="QueryBillInfoServices">
<wsdl:operation name="queryBillInfo">
<wsdl:input name="queryBillInfo" message="tns:queryBillInfo"> </wsdl:input>
<wsdl:output name="queryBillInfoResponse" message="tns:queryBillInfoResponse"> </wsdl:output>
</wsdl:operation>
</wsdl:portType>
<wsdl:binding name="QueryBillInfoServicesSoapBinding" type="tns:QueryBillInfoServices">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<wsdl:operation name="queryBillInfo">
<soap:operation soapAction="" style="document"/>
<wsdl:input name="queryBillInfo">
<soap:header message="tns:queryBillInfo" part="AuthHeader" use="literal"> </soap:header>
<soap:body parts="parameters" use="literal"/>
</wsdl:input>
<wsdl:output name="queryBillInfoResponse">
<soap:body use="literal"/>
</wsdl:output>
</wsdl:operation>
</wsdl:binding>
<wsdl:service name="QueryBillInfoServices">
<wsdl:port name="QueryBillInfoServicesPort" binding="tns:QueryBillInfoServicesSoapBinding">
<soap:address location="http://cbswebpr.ptcl.net.pk:8180/services/QueryBillInfoServices/"/>
</wsdl:port>
</wsdl:service>
</wsdl:definitions>


问:
S3 access point as Spark Eventlog Directory
We have a standalone Spring boot based Spark application where at the moment property spark.eventLog.dir is set to an s3 location.

```<code>SparkConf sparkConf = new SparkConf()
                           .setMaster("local[*]")
                           .setAppName("MyApp")
                           .set("spark.hadoop.fs.permissions.umask-mode", "000")
                           .set("hive.warehouse.subdir.inherit.perms", "false")
                           .set("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", "2")
                           .set("spark.speculation", "false")
                           .set("spark.eventLog.enabled", "true")
                           .set("spark.extraListeners", "com.ClassName");

sparkConf.set("spark.eventLog.dir", "s3a://my-bucket-name/eventlog");
</code>```

This has been working as expected however now the bucket access has changed to access point, so now the URL has to be arn:aws:s3:<bucket-region>:<accountNumber>:accesspoint:<access-point-name> e.g:

```<code>sparkConf.set("spark.eventLog.dir", "s3a://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point/eventlog");
</code>```

After this change we are getting following Stack trace while booting up this app:

```<code>java.lang.NullPointerException: null uri host.
    at java.base/java.util.Objects.requireNonNull(Objects.java:246)
    at org.apache.hadoop.fs.s3native.S3xLoginHelper.buildFSURI(S3xLoginHelper.java:71)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.setUri(S3AFileSystem.java:470)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:235)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:3303)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:124)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:3352)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:3320)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:479)
    at org.apache.spark.util.Utils$.getHadoopFileSystem(Utils.scala:1866)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:71)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:522)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2520)
    at org.apache.spark.sql.SparkSession$Builder.$anonfun$getOrCreate$5(SparkSession.scala:935)
    at scala.Option.getOrElse(Option.scala:138)
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:926)
</code>```

Looking at the class S3xLoginHelper, looks like it is failing to create a java.net.URI object with the : char in the URL string.

I have following following relevant maven dependencies:

```<code><dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.12</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.12</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-aws</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>3.2.0</version>
</dependency>
</code>```

Update:
Also, tried to add following in core-site.xml (also tried in hdfc-site.xml) as mentioned in the hadoop-aws documentation:

```<code><property>
    <name>fs.s3a.bucket.my-access-point.accesspoint.arn</name>
    <value>arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point</value>
    <description>Configure S3a traffic to use this AccessPoint</description>
</property>
</code>```

And updated the code with sparkConf.set("spark.eventLog.dir", "s3a://my-access-point/eventlog");

This give a stack trace with java.io.FileNotFoundException: Bucket my-access-point does not exist which indicates that it is not using those updated properties for spark.eventLog.dir and treating my-access-point as bucket name!

Body:
We have a standalone Spring boot based Spark application where at the moment property spark.eventLog.dir is set to an s3 location.

SparkConf sparkConf = new SparkConf()
                           .setMaster("local[*]")
                           .setAppName("MyApp")
                           .set("spark.hadoop.fs.permissions.umask-mode", "000")
                           .set("hive.warehouse.subdir.inherit.perms", "false")
                           .set("spark.hadoop.mapreduce.fileoutputcommitter.algorithm.version", "2")
                           .set("spark.speculation", "false")
                           .set("spark.eventLog.enabled", "true")
                           .set("spark.extraListeners", "com.ClassName");

sparkConf.set("spark.eventLog.dir", "s3a://my-bucket-name/eventlog");

This has been working as expected however now the bucket access has changed to access point, so now the URL has to be arn:aws:s3:<bucket-region>:<accountNumber>:accesspoint:<access-point-name> e.g:

sparkConf.set("spark.eventLog.dir", "s3a://arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point/eventlog");

After this change we are getting following Stack trace while booting up this app:

java.lang.NullPointerException: null uri host.
    at java.base/java.util.Objects.requireNonNull(Objects.java:246)
    at org.apache.hadoop.fs.s3native.S3xLoginHelper.buildFSURI(S3xLoginHelper.java:71)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.setUri(S3AFileSystem.java:470)
    at org.apache.hadoop.fs.s3a.S3AFileSystem.initialize(S3AFileSystem.java:235)
    at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:3303)
    at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:124)
    at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:3352)
    at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:3320)
    at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:479)
    at org.apache.spark.util.Utils$.getHadoopFileSystem(Utils.scala:1866)
    at org.apache.spark.scheduler.EventLoggingListener.<init>(EventLoggingListener.scala:71)
    at org.apache.spark.SparkContext.<init>(SparkContext.scala:522)
    at org.apache.spark.SparkContext$.getOrCreate(SparkContext.scala:2520)
    at org.apache.spark.sql.SparkSession$Builder.$anonfun$getOrCreate$5(SparkSession.scala:935)
    at scala.Option.getOrElse(Option.scala:138)
    at org.apache.spark.sql.SparkSession$Builder.getOrCreate(SparkSession.scala:926)

Looking at the class S3xLoginHelper, looks like it is failing to create a java.net.URI object with the : char in the URL string.

I have following following relevant maven dependencies:

<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.12</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.12</artifactId>
    <version>2.4.4</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-aws</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-common</artifactId>
    <version>3.2.0</version>
</dependency>
<dependency>
    <groupId>org.apache.hadoop</groupId>
    <artifactId>hadoop-client</artifactId>
    <version>3.2.0</version>
</dependency>

Update:
Also, tried to add following in core-site.xml (also tried in hdfc-site.xml) as mentioned in the hadoop-aws documentation:

<property>
    <name>fs.s3a.bucket.my-access-point.accesspoint.arn</name>
    <value>arn:aws:s3:eu-west-2:1234567890:accesspoint:my-access-point</value>
    <description>Configure S3a traffic to use this AccessPoint</description>
</property>

And updated the code with sparkConf.set("spark.eventLog.dir", "s3a://my-access-point/eventlog");

This give a stack trace with java.io.FileNotFoundException: Bucket my-access-point does not exist which indicates that it is not using those updated properties for spark.eventLog.dir and treating my-access-point as bucket name!


问:
Unable to locate the pvt key for a csr generated using Windows MMC snap-in
To access a public server, I was asked to generate a CSR. I generated the CSR using the Windows MMC snap-in, which was then validated by the authorities, and a CER file was issued to me. I have successfully imported that CER file as well.

However, I am unable to locate the private key corresponding to this CSR. Need serious help here. No option was specified to save the pvt key, even though the checkbox to make it exportable was selected.

The MMC console mentions that a private key exists for this certificate - but does not specify where.
Have managed to export the certificate to a PFX file (asked for a passcode - provided one) - but for all my attempts, extracting the private key from PFX without using any commercial tool is proving to be challenging (using any commercial or online tool is not permitted, unfortunately). (Have trawled through quite a few SO posts - too numerous to be listed).

Will be happy to write a program (in C or Assembly) if that helps extract the private key.

Thanks for your attention.


问:
Check if site is in Iframe + global variable
I have a react.js application. I have another application where I need to Iframe my react application and trim out/hide few elements.

Wondering how do I set a global flag that I can use across application.