问:
How to scrap wit RSelenium without navigate
Here's the problem:
I need to atualize a database, to do that I must scrap a website that requires login. The only way to login is with RSelenium (rvest and httr didn't work).
But RSelenium opens a browser, I would like to make all the process without opening the browser, so I'll be able to automatize the process and still use my computer without getting annoyed with a window popping in my face. The code:

    library(tidyverse)
    library(RSelenium)
    library(rvest)
    library(netstat)
    library(data.table)

    rs_driver_object <- rsDriver(browser = "chrome",
                                 chromever = "108.0.5359.71",
                                 verbose = F,
                                 port = free_port())

    remDr <- rs_driver_object$client

    remDr$navigate("https://www.arcgis.com/sharing/oauth2/authorize?client_id=arcgisonline&response_type=code&state=%7B%22portalUrl%22%3A%22https%3A%2F%2Fwww.arcgis.com%22%2C%22uid%22%3A%22GJIYvS2pTpr70jmndJezzgcOh_WwR-J5qOLiA7z41DM%22%2C%22useLandingPage%22%3Atrue%2C%22clientId%22%3A%22arcgisonline%22%7D&expiration=20160&locale=pt-br&redirect_uri=https%3A%2F%2Fwww.arcgis.com%2Fhome%2Faccountswitcher-callback.html&force_login=true&redirectToUserOrgUrl=true&code_challenge=DBnPlE69KuG2CF_IJaLNEdxd7BZRUDnNz1Uyu8d-gRY&code_challenge_method=S256&display=default&hideCancel=true&showSignupOption=true&canHandleCrossOrgSignIn=true&signuptype=esri&allow_verification=true")

    #send username
    username <- remDr$findElement(using = "id", value = "user_username")
    username$sendKeysToElement(list("my_user"))

    #send password and Enter
    passwd <- remDr$findElement(using = "id", value = "user_password")
    passwd$sendKeysToElement(list("my_pass"))

    #loging in
    sign_in <- remDr$findElement(using = "id", value = 'signIn')
    sign_in$clickElement()
```


来源: stackexchange

问:
I'm trying to use the search bar of youtube but it returns error
```<code>(async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto('https://youtube.com')
    await page.waitForSelector("#search")
    await page.type('#search', 'cheese')
    await page.screenshot({path: 'youtube.png'});
    console.log('done')
})();
</code>```

I tried to run this to send me the search results of something but it returns "Uncaught Error Error: Evaluation failed: Error: Cannot focus non-HTMLElement" Any idea what I did wrong and need to fix? I saw a similar post but it didn't have an answer and I know I could just go straight to the page but I want to know how to use the search bar.

ContentLicense: CC BY-SA 4.0

Body:
(async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()
    await page.goto('https://youtube.com')
    await page.waitForSelector("#search")
    await page.type('#search', 'cheese')
    await page.screenshot({path: 'youtube.png'});
    console.log('done')
})();

I tried to run this to send me the search results of something but it returns "Uncaught Error Error: Evaluation failed: Error: Cannot focus non-HTMLElement" Any idea what I did wrong and need to fix? I saw a similar post but it didn't have an answer and I know I could just go straight to the page but I want to know how to use the search bar.


问:
get the delta of the nearest experation ATM option
i wanna display the delta of call and put options for nearest experation of the underlaying symbol thats open in the chart.</p>
```<code>def atmCallOption = GetATMOption(GetUnderlyingSymbol(), GetNextExpirationOption(),
OptionClass.CALL);

def atmPUTOption = GetATMOption(GetUnderlyingSymbol(), GetNextExpirationOption(),
OptionClass.PUT);

plot callDelta = Delta(atmCallOption);

plot putDelta = Delta(atmPUTOption);
</code>```

Body:
i wanna display the delta of call and put options for nearest experation of the underlaying symbol thats open in the chart.

def atmCallOption = GetATMOption(GetUnderlyingSymbol(), GetNextExpirationOption(),
OptionClass.CALL);

def atmPUTOption = GetATMOption(GetUnderlyingSymbol(), GetNextExpirationOption(),
OptionClass.PUT);

plot callDelta = Delta(atmCallOption);

plot putDelta = Delta(atmPUTOption);


问:
How to print array of values under same header horizontally one below the other using Export CSV in React Js
I am using ExportToCsv npm package for Export CSV,

so I've implemented in the same way as code sample in my solution,

```<code>var data = [
  {
    name: 'Test 1',
    age: [13,15,16,20,19,20],
    average: [8.5,8.7,9.5,8.9,7.7,9.0],
    approved: true,
    description: ["long texts 1................","long texts 2................","long texts 3................","long texts 4................","long texts 5................","long texts 6................"]
  }]
const exportCSVheaders = [
                { label: "name", key: "name" },
                { label: "age", key: "age" },
                { label: "average", key: "average" },
                { label: "approved", key: "approved" },
                { label: "description", key: "description" },
            ];
            //end - preparing the header for csv
            const dataToExport: any[] = [];
            dataToExport.push(JSON.parse(JSON.stringify(data)));
const options = {
                fieldSeparator: ',',
                quoteStrings: '"',
                decimalSeparator: '.',
                showLabels: true,
                showTitle: false,
                title: 'Insight Responses',
                useTextFile: false,
                useBom: true,
                useKeysAsHeaders: false,
                filename: exportFileName,
                headers: exportCSVheaders.map(e => { return e.label; })
            };
            const csvExporter = new ExportToCsv(options);
            csvExporter.generateCsv(dataToExport);
</code>```

Data I'm getting in excel and also the expected result.

All array values should be mapped below each each other, I'm not able to develop logic for this, might be silly question but any kind of help will be very useful.
Thanks.

What I've tried is attached in the image file itself.

Body:
I am using ExportToCsv npm package for Export CSV,

so I've implemented in the same way as code sample in my solution,

var data = [
  {
    name: 'Test 1',
    age: [13,15,16,20,19,20],
    average: [8.5,8.7,9.5,8.9,7.7,9.0],
    approved: true,
    description: ["long texts 1................","long texts 2................","long texts 3................","long texts 4................","long texts 5................","long texts 6................"]
  }]
const exportCSVheaders = [
                { label: "name", key: "name" },
                { label: "age", key: "age" },
                { label: "average", key: "average" },
                { label: "approved", key: "approved" },
                { label: "description", key: "description" },
            ];
            //end - preparing the header for csv
            const dataToExport: any[] = [];
            dataToExport.push(JSON.parse(JSON.stringify(data)));
const options = {
                fieldSeparator: ',',
                quoteStrings: '"',
                decimalSeparator: '.',
                showLabels: true,
                showTitle: false,
                title: 'Insight Responses',
                useTextFile: false,
                useBom: true,
                useKeysAsHeaders: false,
                filename: exportFileName,
                headers: exportCSVheaders.map(e => { return e.label; })
            };
            const csvExporter = new ExportToCsv(options);
            csvExporter.generateCsv(dataToExport);

Data I'm getting in excel and also the expected result.

All array values should be mapped below each each other, I'm not able to develop logic for this, might be silly question but any kind of help will be very useful.
Thanks.

What I've tried is attached in the image file itself.


问:
How to remove (all) option in filter_select function from plotly package?
I want to remove the (All) option from the plotly's filter_select function since it makes all the data from each filter options show up as the default in a way that doesn't make sense (see pic). If I can't remove the (All) option, is there a way to specify which of my filter options I'd like to display as the default?

Seems very similar to this question, but my package versions are more recent (crosstalk 1.2.0, ggplot2 3.4.0, plotly 4.10.1) How to remove (All) from crosstalk's filter_select in R?

Thanks so much!

```<code>trends_age_subplot <- subplot(plotly_trends_age_pctpos %>% layout(height=600),
                              style(plotly_trends_age_case, showlegend=F),
                              style(plotly_trends_age_test, showlegend=F),
                              nrows=3, shareX=TRUE, titleY=TRUE, which_layout=1)

</code>```
```<code>trends_age_final <- bscols(widths=c(2,10),
                           list(filter_select(id='tr_boro', label='Borough', sharedData=shared_trends_age, group=~boro, multiple=F)),
                           trends_age_subplot)
</code>```

Pic of how data is presented when (All) is selected as default

Body:
I want to remove the (All) option from the plotly's filter_select function since it makes all the data from each filter options show up as the default in a way that doesn't make sense (see pic). If I can't remove the (All) option, is there a way to specify which of my filter options I'd like to display as the default?

Seems very similar to this question, but my package versions are more recent (crosstalk 1.2.0, ggplot2 3.4.0, plotly 4.10.1) How to remove (All) from crosstalk's filter_select in R?

Thanks so much!

trends_age_subplot <- subplot(plotly_trends_age_pctpos %>% layout(height=600),
                              style(plotly_trends_age_case, showlegend=F),
                              style(plotly_trends_age_test, showlegend=F),
                              nrows=3, shareX=TRUE, titleY=TRUE, which_layout=1)

trends_age_final <- bscols(widths=c(2,10),
                           list(filter_select(id='tr_boro', label='Borough', sharedData=shared_trends_age, group=~boro, multiple=F)),
                           trends_age_subplot)

Pic of how data is presented when (All) is selected as default


问:
How "Plot" in mql5?
I need your help, for surely something simple for people who will know, but I'm looking for several days for the answer and I can't find.

I would like to make the equivalent of a plot in pinescript, but in my mql5 script, to represent a variable on my graph, we can take for example of high for the explanation.

Could someone explain me how to do it, please ?

Thanks in advance for your time.

Title: How "Plot" in mql5?


问:
React Firebase auth context updates too many times
I am trying to use the Firebase Firestore user record data from the useAuthUserContext, which gets logged into the console too many times. Does this code contain any potential disadvantages that may lead to so many calls, or can it be further adjusted? Here is the solution I have developed myself:

Hook:

```<code>export const useFirebaseAuth = () => {
    const [authUser, setAuthUser] = useState<IUser | null>(null);
    const [loading, setLoading] = useState(true);
    const router = useRouter();

    const auth = getAuth(app);
    const provider = new GoogleAuthProvider();

    provider.setCustomParameters({ prompt: 'select_account' });

    const authStateChanged = async (authState: any) => {
        if (!authState) {
            setLoading(false);
            return;
        }

        setLoading(true);

        const formattedUser = formatAuthUser(authState);

        setAuthUser(formattedUser);

        const { uid, stripeId } = authState;

        const docRef = doc(firestore, 'users', uid);
        const snap = await getDoc(docRef);

        const unsubscribe = onSnapshot(docRef, (doc) => {
            if (doc.exists()) {
                setAuthUser((f: any) => ({ ...f, ...doc.data() }));
            }
        });

        if (snap.exists()) {
            setAuthUser((f: any) => ({ ...f, ...snap.data() }));
        }

        if (stripeId) {
            unsubscribe();
        }

        setLoading(false);
    };

    const generateRecaptcha = () => {
        window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
            size: 'invisible',
            callback: () => {
            }
        }, auth);
    };

    useEffect(() => {
        window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
            size: 'invisible',
            callback: () => {
            }
        }, auth);

        return onAuthStateChanged(auth, authStateChanged);
    }, [auth]);

    const clear = () => {
        setAuthUser(null);
        setLoading(false);
    };

    const authWithPhone = async (phoneNumber: string): Promise<boolean> => {
        generateRecaptcha();

        if (typeof window !== 'undefined') {
            const appVerifier = window.recaptchaVerifier;

            return signInWithPhoneNumber(auth, phoneNumber, appVerifier)
                .then((confirmationResult) => {
                    window.confirmationResult = confirmationResult;
                    return true;
                })
                .catch(() => false);
        }

        return false;
    };

    return {
        authUser,
        loading,
        authWithPhone
    };
};

export default useFirebaseAuth;
</code>```

AuthUserContext file:

```<code>const authUserContext = createContext<IDefault>({
    authUser: null,
    loading: true,
    authWithPhone: async (phoneNumber: string) => false
});

export function AuthUserProvider({ children }: IAuthUserProvider) {
    const auth = useFirebaseAuth();
    return <authUserContext.Provider value={ auth }>{ children }</authUserContext.Provider>;
}

export const useAuthUserContext = () => useContext(authUserContext);
</code>```

Hook usage example:

```<code>export const PaymentOptions = () => {
  const { authUser, loading } = useAuthUserContext();

  // Logs too many times here!
  console.log(authUser);
}
</code>```

Body:
I am trying to use the Firebase Firestore user record data from the useAuthUserContext, which gets logged into the console too many times. Does this code contain any potential disadvantages that may lead to so many calls, or can it be further adjusted? Here is the solution I have developed myself:

Hook:

export const useFirebaseAuth = () => {
    const [authUser, setAuthUser] = useState<IUser | null>(null);
    const [loading, setLoading] = useState(true);
    const router = useRouter();

    const auth = getAuth(app);
    const provider = new GoogleAuthProvider();

    provider.setCustomParameters({ prompt: 'select_account' });

    const authStateChanged = async (authState: any) => {
        if (!authState) {
            setLoading(false);
            return;
        }

        setLoading(true);

        const formattedUser = formatAuthUser(authState);

        setAuthUser(formattedUser);

        const { uid, stripeId } = authState;

        const docRef = doc(firestore, 'users', uid);
        const snap = await getDoc(docRef);

        const unsubscribe = onSnapshot(docRef, (doc) => {
            if (doc.exists()) {
                setAuthUser((f: any) => ({ ...f, ...doc.data() }));
            }
        });

        if (snap.exists()) {
            setAuthUser((f: any) => ({ ...f, ...snap.data() }));
        }

        if (stripeId) {
            unsubscribe();
        }

        setLoading(false);
    };

    const generateRecaptcha = () => {
        window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
            size: 'invisible',
            callback: () => {
            }
        }, auth);
    };

    useEffect(() => {
        window.recaptchaVerifier = new RecaptchaVerifier('recaptcha-container', {
            size: 'invisible',
            callback: () => {
            }
        }, auth);

        return onAuthStateChanged(auth, authStateChanged);
    }, [auth]);

    const clear = () => {
        setAuthUser(null);
        setLoading(false);
    };

    const authWithPhone = async (phoneNumber: string): Promise<boolean> => {
        generateRecaptcha();

        if (typeof window !== 'undefined') {
            const appVerifier = window.recaptchaVerifier;

            return signInWithPhoneNumber(auth, phoneNumber, appVerifier)
                .then((confirmationResult) => {
                    window.confirmationResult = confirmationResult;
                    return true;
                })
                .catch(() => false);
        }

        return false;
    };

    return {
        authUser,
        loading,
        authWithPhone
    };
};

export default useFirebaseAuth;

AuthUserContext file:

const authUserContext = createContext<IDefault>({
    authUser: null,
    loading: true,
    authWithPhone: async (phoneNumber: string) => false
});

export function AuthUserProvider({ children }: IAuthUserProvider) {
    const auth = useFirebaseAuth();
    return <authUserContext.Provider value={ auth }>{ children }</authUserContext.Provider>;
}

export const useAuthUserContext = () => useContext(authUserContext);

Hook usage example:

export const PaymentOptions = () => {
  const { authUser, loading } = useAuthUserContext();

  // Logs too many times here!
  console.log(authUser);
}


问:
Is there an efficient way to check for an approximate floating point equality in C++?

Possible Duplicate:

  Most effective way for float and double comparison

I have a function that calculates distance and then that distance is then later compared to the square root of 2 to see if two items are adjacent on a grid.  In Java this works fine, apparently the Math.sqrt(Math.pow(x1-x2,2)....) produces the same as Math.sqrt(2) but in C++ cmath's sqrt(pow(x1-x2,2)...) is not equal.

I cout<<ed the doubles and to the precision shown (I will also output higher precision just to see) they looked equal but didn't evaluate as equal.  On the other hand, if I test for values within +- 0.01 of sqrt(2) then this test for "approximate equality" works.  Is this what I should do or is something else the matter?  Is there some better way of doing this test if this is what I must do?

Thanks.

ContentLicense: CC BY-SA 3.0


问:
Copy data range into A Column, but copy single cell into B Column for as many rows as in A Column
I have a spreadsheet with "Sheet 1" containing barcode values for X number of rows in Column A, as well as a single "Client" name. I am wanting to copy this barcode data range into another sheet ("Sheet 2"), but in a separate column, copy the single cell (Client) for as many rows as there are in the barcode data range.

The idea being that once I clear the data from Sheet 1 for a new client, I can still retain a full log in Sheet 2.

Sheet 1
Sheet 2

I have successfully copied the barcode data range within Apps Script (see below), but cannot figure out how to copy and paste the single cell for the same number of rows.

```<code>function copyBarcode() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName('Sheet1');
  var targetSheet = ss.getSheetByName('Sheet2');

  var barcodeRange = sourceSheet.getRange('A1:A').getValues();
  for(i = 0; i < barcodeRange.length; i++)
  {
    targetSheet.appendRow(barcodeRange[i]);
  }

}
</code>```

Body:
I have a spreadsheet with "Sheet 1" containing barcode values for X number of rows in Column A, as well as a single "Client" name. I am wanting to copy this barcode data range into another sheet ("Sheet 2"), but in a separate column, copy the single cell (Client) for as many rows as there are in the barcode data range.

The idea being that once I clear the data from Sheet 1 for a new client, I can still retain a full log in Sheet 2.

Sheet 1
Sheet 2

I have successfully copied the barcode data range within Apps Script (see below), but cannot figure out how to copy and paste the single cell for the same number of rows.

function copyBarcode() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sourceSheet = ss.getSheetByName('Sheet1');
  var targetSheet = ss.getSheetByName('Sheet2');

  var barcodeRange = sourceSheet.getRange('A1:A').getValues();
  for(i = 0; i < barcodeRange.length; i++)
  {
    targetSheet.appendRow(barcodeRange[i]);
  }

}


问:
I cant add "Emmet" to Atom

What I need to fix it?

I tried everything and I cant fix it.

Title: I cant add "Emmet" to Atom


问:
What is the precise method to render credentials in UI after restore?
I have been exploring aries-mobile-agent-react-native wallet for a while. I am trying to add a backup and restore option in the Wallet.

Has anyone worked on this wallet?⏬

https://github.com/hyperledger/aries-mobile-agent-react-native

I am trying to restore credentials into wallet from backed up. What is the exact way to insert into credential array after restore credentials from anywhere (like database) and then render it (with existing one) in the mobile UI?

Thanks in advance.


问:
How to use install django_debug_toolbar
I am trying to run django_debug_toolbar
I followed the instructions at:
https://django-debug-toolbar.readthedocs.io/en/latest/installation.html
I also saw several YouTube videos, this should be working.

Here's the code
urls.py

```<code>import debug_toolbar
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('__debug__/', include(debug_toolbar.urls)),
]
</code>```

settings.py

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

</code>```

I tried to install django_debug_toolbar, but it gives a 404

Title: How to use install django_debug_toolbar

Body:
I am trying to run django_debug_toolbar
I followed the instructions at:
https://django-debug-toolbar.readthedocs.io/en/latest/installation.html
I also saw several YouTube videos, this should be working.

Here's the code
urls.py

import debug_toolbar
from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('__debug__/', include(debug_toolbar.urls)),
]

settings.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'debug_toolbar',
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

I tried to install django_debug_toolbar, but it gives a 404


问:
issue with loading a saved ensemble model with Python ( Can't get attribute 'Ensemble' on <module '__main__'>)
I have an ensemble of XGBoost models that I saved with both "pickle" and "joblib". If I load the model in the same script that I save, it will be loaded successfully. However, if I load the model in another script, it will give me an AttributError saying that

"AttributeError: Can't get attribute 'Ensemble' on <module 'main'>".

Any suggestion is appreciated.

It is a general issue because I have this issue with both "pickle" and "joblib".

loading library

import pickle

load saved model

with open('/scratch/gpfs/sg6615/known_antibiotics/Code/test.pkl', 'rb') as f:
lr = pickle.load(f)

AttributeError                            Traceback (most recent call last)
Input In [5], in <cell line: 8>()
7 # load saved model
8 with open('/scratch/gpfs/sg6615/known_antibiotics/Code/test.pkl', 'rb') as f:
----> 9     lr = pickle.load(f)

AttributeError: Can't get attribute 'Ensemble' on <module 'main'>


问:
Modify data inside thread
I am writing unit tests for one of the classes I want to test. Function infFooLoop() what I want to test is executed in endless loop (request to stop it comes externally). My problem is I want to change the private variable state_ via setter in setState when function executes in separate thread asynchronously. Some simplified code example is here:

```<code>enum class State : int
{
    Success = 1,
    Failure = 2
};

class Foo
{
private:
    State state_{State::Success};
    bool stop_flag_{false};

public:
    void setState(State state) { state_ = state; }
    void infFooLoop(bool &start)
    {
        while (start)
        {
            std::cout << "While loop executes \n";
            if (state_ == State::Failure)
            {
                stop_flag_ = true;
            }
            else if (stop_flag_)
            {
                std::cout << "Program stopped\n";
                // Report error but for this example break
                break;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
    }
};

int main()
{
    Foo obj;
    bool flag{true};

    std::future<void> future = std::async(std::launch::async, [&](){ obj.infFooLoop(flag);});

    // Try to change the data:
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    // I want to change data for `Failure` so stop_flag condition will be used
    obj.setState(State::Failure);
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // terminate loop
    flag = false;

    return 0;
}
</code>```

state_ will be taken from external component and stop_flag_ is used to handle some corner-case here (in real it wont break the loop, just report error to different component).

I assume infFooLoop executes on a separate thread so I can't just call another function in a different thread to change this data. stop_flag_ is some internal variable used only in this one function so I want to leave it as simple as possible (do not introduce mutexes/atomic in Foo class only for tests). Can you give me some suggestions on what should I do here?

Title: Modify data inside thread

Body:
I am writing unit tests for one of the classes I want to test. Function infFooLoop() what I want to test is executed in endless loop (request to stop it comes externally). My problem is I want to change the private variable state_ via setter in setState when function executes in separate thread asynchronously. Some simplified code example is here:

enum class State : int
{
    Success = 1,
    Failure = 2
};

class Foo
{
private:
    State state_{State::Success};
    bool stop_flag_{false};

public:
    void setState(State state) { state_ = state; }
    void infFooLoop(bool &start)
    {
        while (start)
        {
            std::cout << "While loop executes \n";
            if (state_ == State::Failure)
            {
                stop_flag_ = true;
            }
            else if (stop_flag_)
            {
                std::cout << "Program stopped\n";
                // Report error but for this example break
                break;
            }
            std::this_thread::sleep_for(std::chrono::milliseconds(200));
        }
    }
};

int main()
{
    Foo obj;
    bool flag{true};

    std::future<void> future = std::async(std::launch::async, [&](){ obj.infFooLoop(flag);});

    // Try to change the data:
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    // I want to change data for `Failure` so stop_flag condition will be used
    obj.setState(State::Failure);
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // terminate loop
    flag = false;

    return 0;
}

state_ will be taken from external component and stop_flag_ is used to handle some corner-case here (in real it wont break the loop, just report error to different component).

I assume infFooLoop executes on a separate thread so I can't just call another function in a different thread to change this data. stop_flag_ is some internal variable used only in this one function so I want to leave it as simple as possible (do not introduce mutexes/atomic in Foo class only for tests). Can you give me some suggestions on what should I do here?


问:
nginx reverse proxy all request when location match
I am trying to use nginx to host 2 different web apps and make it work on the same domain (eg, www.myapp.com). I want to be able to detect a specific location and then load all resources from a specific app based on a location. Previously I had worked on proxying /api to a specific upstream, but the requirements are a little more complicated due to presence of other resources that needs to get loaded.

```<code>server {
   listen      80;

   location / {
       proxy_pass http://app1;
   }

   location /app2/ {
        proxy_pass http://app2;
   }
}

upstream app1 {
    server 127.0.0.1:8080;
}

upstream app2 {
    server 127.0.0.1:3000;
}
</code>```

When the url hits myapp.com/app2, it loads the html from app2 but there are other resources (like js, css, translations, analytics) files that are being searched in app1 (which obviously results in 404 NOT FOUND). Adding a location rule to match all css, js, etc does not make sense because both the app has their own cs, jss and other resource files. Adding a rule for hardcoded resources is also taxing beccause the it changes with every build.

The 2 main requirements are:

Load all resources from app2 when the url is www.myapp.com/app2, including all js, css and other resources. For instance, the js and css files are served at /static/js/*.js and /static/css/*.css, and they are being searched in https://app1/static/js/*.js, rather than app2. There could be additional resources in the future too so I want to remain flexible.

I don't want to rewrite the url and retain the same www.myapp.com. The url for the end-users should always remain at www.myapp.com/*, rather than using any subdomains. When using subdomains, it works as expected.

Body:
I am trying to use nginx to host 2 different web apps and make it work on the same domain (eg, www.myapp.com). I want to be able to detect a specific location and then load all resources from a specific app based on a location. Previously I had worked on proxying /api to a specific upstream, but the requirements are a little more complicated due to presence of other resources that needs to get loaded.

server {
   listen      80;

   location / {
       proxy_pass http://app1;
   }

   location /app2/ {
        proxy_pass http://app2;
   }
}

upstream app1 {
    server 127.0.0.1:8080;
}

upstream app2 {
    server 127.0.0.1:3000;
}

When the url hits myapp.com/app2, it loads the html from app2 but there are other resources (like js, css, translations, analytics) files that are being searched in app1 (which obviously results in 404 NOT FOUND). Adding a location rule to match all css, js, etc does not make sense because both the app has their own cs, jss and other resource files. Adding a rule for hardcoded resources is also taxing beccause the it changes with every build.

The 2 main requirements are:

Load all resources from app2 when the url is www.myapp.com/app2, including all js, css and other resources. For instance, the js and css files are served at /static/js/*.js and /static/css/*.css, and they are being searched in https://app1/static/js/*.js, rather than app2. There could be additional resources in the future too so I want to remain flexible.

I don't want to rewrite the url and retain the same www.myapp.com. The url for the end-users should always remain at www.myapp.com/*, rather than using any subdomains. When using subdomains, it works as expected.


问:
Use TLA expression to update state within a PlusCal block?
I have a distributed mutex algorithm which I would like to model with PlusCal/TLA. As part of this, I wrote a parameterized TLA module which encapsulates a model of synchronization of variables over a network. Now, I would like to model the main algorithm's control flow using PlusCal, since its control flow constructs are less verbose and more intuitive than TLA's.

However, I can't find a way to use the state change operators I specify in the TLA module in a PlusCal block. For instance, if I write a PlusCal block like:

```<code>Label:
    if VarInstance!ValueAt(self) = SOME_VALUE then
        VarInstance!SetAndBroadcastValue(self, SOME_OTHER_VALUE);
    end if;
</code>```

the translator complains about a lack of := operator, which only exists in PlusCal. The SetAndBroadcastValue operator is of the form /\ x' = ... /\ y' = ... etc (in addition to the new value, it also updates some hidden variables for the synchronization model). There are multiple variables in the algorithm which I need to model this way.

I really don't want to convert all of that into inline assignments in PlusCal format -- not least because having to write the same code over and over again increases the risk of making a silly mistake which will be hard to find later. I considered macros as a solution, but I found them insufficient because the parameterized module not only defines operations on state, but also defines a separate parallel process for delivery of variable updates.

So, is there a way to combine TLA-defined state updates with PlusCal control flow? Or do I need to convert the model into pure TLA?

Body:
I have a distributed mutex algorithm which I would like to model with PlusCal/TLA. As part of this, I wrote a parameterized TLA module which encapsulates a model of synchronization of variables over a network. Now, I would like to model the main algorithm's control flow using PlusCal, since its control flow constructs are less verbose and more intuitive than TLA's.

However, I can't find a way to use the state change operators I specify in the TLA module in a PlusCal block. For instance, if I write a PlusCal block like:

Label:
    if VarInstance!ValueAt(self) = SOME_VALUE then
        VarInstance!SetAndBroadcastValue(self, SOME_OTHER_VALUE);
    end if;

the translator complains about a lack of := operator, which only exists in PlusCal. The SetAndBroadcastValue operator is of the form /\ x' = ... /\ y' = ... etc (in addition to the new value, it also updates some hidden variables for the synchronization model). There are multiple variables in the algorithm which I need to model this way.

I really don't want to convert all of that into inline assignments in PlusCal format -- not least because having to write the same code over and over again increases the risk of making a silly mistake which will be hard to find later. I considered macros as a solution, but I found them insufficient because the parameterized module not only defines operations on state, but also defines a separate parallel process for delivery of variable updates.

So, is there a way to combine TLA-defined state updates with PlusCal control flow? Or do I need to convert the model into pure TLA?


问:
QPalette and app.setStyleSheet() not impacting child Widget colors
I've got a pretty large PyQt5 application that I'm finally polishing with some colors.  I've created a QPalette() and pass that to the app at launch. For the most part, it works (yay!). But not all of the child widgets are picking up the QPalette settings, and so I added a StyleSheet, but that again isn't working consistently. The only way I've been able to impact a widget color is by directly adding it when the widget is created, which is fine in something small.

The Main window:

```<code>    class MyBigApplication(QMainWindow, QWidget):
            def __init__(self):
                super(MyBigApplication, self).__init__()

            # ... load the various pieces, which include prompting user login and making some background connections.

            # Build the GUI
            def init_ui(self):

                self.statusBar().showMessage('Welcome to MyBigApplication!')

                self.grid_layout = QGridLayout()

                # Initialize tab screen
                self.tabs = QTabWidget()
                self.tabs.setTabShape(QTabWidget.Triangular)
                self.foo = fooTab(self, self.tabs)
                self.bar = barTab(self, self.tabs)
                self.baz = bazTab(self, self.tabs)

                self.grid_layout.addWidget(self.tabs,0,1,4,1)

                main_widget = QWidget()
                main_widget.setLayout(self.grid_layout)
                self.setCentralWidget(main_widget)

                # Additional setup of menus and such

        if __name__.endswith('__main__'):
            app = QCoreApplication.instance()
            while app is not None:
                app.close()
            app = QApplication(sys.argv)

            app.setStyle('Fusion')

            dark_palette = QPalette()

            # Define some colors to get started
            light_grey = QColor(243,243,243)
            medium_grey = QColor(211,216,219)
            dark_grey = QColor(52,59,64)

            dark_palette.setColor(QPalette.Window, QColor(dark_grey))
            dark_palette.setColor(QPalette.AlternateBase, QColor(medium_grey))
            dark_palette.setColor(QPalette.Button, QColor(dark_grey))
            dark_palette.setColor(QPalette.Base, QColor(25, 25, 25)) # almost black
            dark_palette.setColor(QPalette.Link, QColor(green))
            dark_palette.setColor(QPalette.Highlight, QColor(half_green))
            dark_palette.setColor(QPalette.WindowText, QColor(light_grey))
            dark_palette.setColor(QPalette.ToolTipBase, QColor(light_grey))
            dark_palette.setColor(QPalette.ToolTipText, QColor(light_grey))
            dark_palette.setColor(QPalette.Text, QColor(light_grey))
            dark_palette.setColor(QPalette.ButtonText, QColor(light_grey))
            dark_palette.setColor(QPalette.BrightText, Qt.red)
            dark_palette.setColor(QPalette.HighlightedText, Qt.black)

            app.setPalette(dark_palette)

            app.setFont(QFont('Franklin Gothic Book', 9))

            app.setStyleSheet("""
                QMainWindow {

                }
                QToolTip {
                    color: #f3f3f3;
                    background-color: #2a82da;
                    border: 1px solid white;
                }
                QTableView {   # This works
                    border: 1px solid #218a21
                }
                QPushButton {   # And this works
                    padding: 10px 15px 10px 15px,
                }
                QPushButton:hover {   # But this does not
                    background-color: red,
                }
                QTableView::item:alternate {  # And this also does not
                    background-color: #d3d8db,
                }
                """)

            execute = MyBigApplication()
            sys.exit(app.exec_())
</code>```

The fooTab includes tables of data:

```<code>class fooTab(QWidget):
    def __init__(self, parent, tabs):
        super(fooTab,self).__init__()
        self.root = parent
        self.tabs = tabs

    def init_foo_one(self):
        self.foo_tab = QWidget()
        self.tabs.addTab(self.foo_tab, 'FOO')
        tab_layout = QVBoxLayout()
        foo_id_box = QGroupBox('FOO DATA')

        clear_button = QPushButton('Clear Foo Data Table')
        clear_button.clicked.connect(self.clear_foo_table)

        # Set up the Table Model/View/Proxy
        self.foo_id_table = QTableView()

        self.foo_data_model = fooTableModel()  # This is a QAbstractTableModel class

        self.foo_data_model.setDataDict(data)
        self.foo_id_table_columns = ['1','2','3','4']
        self.foo_resizable_cols = [0,1,2,3,4]
        self.foo_data_model.setDataHeader(self.foo_id_table_columns)
        self.foo_table_proxy.setSourceModel(self.foo_data_model)
        self.foo_id_table.setModel(self.foo_table_proxy)
        self.foo_id_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.foo_id_table.setSortingEnabled(True)
        self.foo_id_table.setWordWrap(False)
        self.foo_id_table.setAlternatingRowColors(True)

        # Create a layout for that box using a grid
        foo_id_box_layout = QGridLayout()

        # Add the widgets into the layout
        foo_id_box_layout.addWidget(self.foo_id_table,0,0,1,5)
        foo_id_box_layout.addWidget(clear_button,1,2,1,1)

        # Setup the layout to be displayed in the box
        foo_id_box.setLayout(foo_id_box_layout)
        tab_layout.addWidget(foo_id_box)
        self.foo_tab.setLayout(tab_layout)
</code>```

The bazTab:

```<code>    class BazTab(QWidget):
        def __init__(self, parent, tabs):
            super(BazTab,self).__init__()
            self.root = parent
            self.tabs = tabs
            self.h1_font = QFont()
            self.h1_font.setBold(True)
            self.h1_font.setPointSize(16)
            self.h2_font = QFont()
            self.h2_font.setBold(False)
            self.h2_font.setPointSize(12)
            self.h3_font = QFont()
            self.h3_font.setBold(True)
            self.init_ui()

        def init_ui(self):
            self.component_tab = QScrollArea()
            self.tabs.addTab(self.baz_tab, 'Baz')
            self.tab_layout = QHBoxLayout()
            self.component_tab.setLayout(self.tab_layout)

            component_button_box = QGroupBox('Various Buttons')
            component_button_layout = QVBoxLayout()
            component_button_layout.setAlignment(Qt.AlignTop)
            component_button_box.setLayout(component_button_layout)
            self.tab_layout.addWidget(component_button_box)

            first_button = QPushButton('Request #1')
            first_button.clicked.connect(self.request_one)
            component_button_layout.addWidget(first_button)

            second_button = QPushButton('Request #2')
            second_button.clicked.connect(self.request_two)
            component_button_layout.addWidget(second_button)

            # Several more buttons created in here
            # None of these buttons look like the buttons in the info dialog (which have a color from the QPalette)
</code>```

I can manually edit the QTableView to show alternating colors, only if I add it to each instance.

I cannot get some of the QPushButtons to change, even when I add each instance's styleSheet.

Using the QPalette has saved a ton, by not having to modify widget by widget.  For the extra details, I'm fine to use the app.setStyleSheet except that it doesn't always work.

Is it me, or is this just the way it is?

Body:
I've got a pretty large PyQt5 application that I'm finally polishing with some colors.  I've created a QPalette() and pass that to the app at launch. For the most part, it works (yay!). But not all of the child widgets are picking up the QPalette settings, and so I added a StyleSheet, but that again isn't working consistently. The only way I've been able to impact a widget color is by directly adding it when the widget is created, which is fine in something small.

The Main window:

    class MyBigApplication(QMainWindow, QWidget):
            def __init__(self):
                super(MyBigApplication, self).__init__()

            # ... load the various pieces, which include prompting user login and making some background connections.

            # Build the GUI
            def init_ui(self):

                self.statusBar().showMessage('Welcome to MyBigApplication!')

                self.grid_layout = QGridLayout()

                # Initialize tab screen
                self.tabs = QTabWidget()
                self.tabs.setTabShape(QTabWidget.Triangular)
                self.foo = fooTab(self, self.tabs)
                self.bar = barTab(self, self.tabs)
                self.baz = bazTab(self, self.tabs)

                self.grid_layout.addWidget(self.tabs,0,1,4,1)

                main_widget = QWidget()
                main_widget.setLayout(self.grid_layout)
                self.setCentralWidget(main_widget)

                # Additional setup of menus and such

        if __name__.endswith('__main__'):
            app = QCoreApplication.instance()
            while app is not None:
                app.close()
            app = QApplication(sys.argv)

            app.setStyle('Fusion')

            dark_palette = QPalette()

            # Define some colors to get started
            light_grey = QColor(243,243,243)
            medium_grey = QColor(211,216,219)
            dark_grey = QColor(52,59,64)

            dark_palette.setColor(QPalette.Window, QColor(dark_grey))
            dark_palette.setColor(QPalette.AlternateBase, QColor(medium_grey))
            dark_palette.setColor(QPalette.Button, QColor(dark_grey))
            dark_palette.setColor(QPalette.Base, QColor(25, 25, 25)) # almost black
            dark_palette.setColor(QPalette.Link, QColor(green))
            dark_palette.setColor(QPalette.Highlight, QColor(half_green))
            dark_palette.setColor(QPalette.WindowText, QColor(light_grey))
            dark_palette.setColor(QPalette.ToolTipBase, QColor(light_grey))
            dark_palette.setColor(QPalette.ToolTipText, QColor(light_grey))
            dark_palette.setColor(QPalette.Text, QColor(light_grey))
            dark_palette.setColor(QPalette.ButtonText, QColor(light_grey))
            dark_palette.setColor(QPalette.BrightText, Qt.red)
            dark_palette.setColor(QPalette.HighlightedText, Qt.black)

            app.setPalette(dark_palette)

            app.setFont(QFont('Franklin Gothic Book', 9))

            app.setStyleSheet("""
                QMainWindow {

                }
                QToolTip {
                    color: #f3f3f3;
                    background-color: #2a82da;
                    border: 1px solid white;
                }
                QTableView {   # This works
                    border: 1px solid #218a21
                }
                QPushButton {   # And this works
                    padding: 10px 15px 10px 15px,
                }
                QPushButton:hover {   # But this does not
                    background-color: red,
                }
                QTableView::item:alternate {  # And this also does not
                    background-color: #d3d8db,
                }
                """)

            execute = MyBigApplication()
            sys.exit(app.exec_())

The fooTab includes tables of data:

class fooTab(QWidget):
    def __init__(self, parent, tabs):
        super(fooTab,self).__init__()
        self.root = parent
        self.tabs = tabs

    def init_foo_one(self):
        self.foo_tab = QWidget()
        self.tabs.addTab(self.foo_tab, 'FOO')
        tab_layout = QVBoxLayout()
        foo_id_box = QGroupBox('FOO DATA')

        clear_button = QPushButton('Clear Foo Data Table')
        clear_button.clicked.connect(self.clear_foo_table)

        # Set up the Table Model/View/Proxy
        self.foo_id_table = QTableView()

        self.foo_data_model = fooTableModel()  # This is a QAbstractTableModel class

        self.foo_data_model.setDataDict(data)
        self.foo_id_table_columns = ['1','2','3','4']
        self.foo_resizable_cols = [0,1,2,3,4]
        self.foo_data_model.setDataHeader(self.foo_id_table_columns)
        self.foo_table_proxy.setSourceModel(self.foo_data_model)
        self.foo_id_table.setModel(self.foo_table_proxy)
        self.foo_id_table.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.foo_id_table.setSortingEnabled(True)
        self.foo_id_table.setWordWrap(False)
        self.foo_id_table.setAlternatingRowColors(True)

        # Create a layout for that box using a grid
        foo_id_box_layout = QGridLayout()

        # Add the widgets into the layout
        foo_id_box_layout.addWidget(self.foo_id_table,0,0,1,5)
        foo_id_box_layout.addWidget(clear_button,1,2,1,1)

        # Setup the layout to be displayed in the box
        foo_id_box.setLayout(foo_id_box_layout)
        tab_layout.addWidget(foo_id_box)
        self.foo_tab.setLayout(tab_layout)

The bazTab:

    class BazTab(QWidget):
        def __init__(self, parent, tabs):
            super(BazTab,self).__init__()
            self.root = parent
            self.tabs = tabs
            self.h1_font = QFont()
            self.h1_font.setBold(True)
            self.h1_font.setPointSize(16)
            self.h2_font = QFont()
            self.h2_font.setBold(False)
            self.h2_font.setPointSize(12)
            self.h3_font = QFont()
            self.h3_font.setBold(True)
            self.init_ui()

        def init_ui(self):
            self.component_tab = QScrollArea()
            self.tabs.addTab(self.baz_tab, 'Baz')
            self.tab_layout = QHBoxLayout()
            self.component_tab.setLayout(self.tab_layout)

            component_button_box = QGroupBox('Various Buttons')
            component_button_layout = QVBoxLayout()
            component_button_layout.setAlignment(Qt.AlignTop)
            component_button_box.setLayout(component_button_layout)
            self.tab_layout.addWidget(component_button_box)

            first_button = QPushButton('Request #1')
            first_button.clicked.connect(self.request_one)
            component_button_layout.addWidget(first_button)

            second_button = QPushButton('Request #2')
            second_button.clicked.connect(self.request_two)
            component_button_layout.addWidget(second_button)

            # Several more buttons created in here
            # None of these buttons look like the buttons in the info dialog (which have a color from the QPalette)

I can manually edit the QTableView to show alternating colors, only if I add it to each instance.

I cannot get some of the QPushButtons to change, even when I add each instance's styleSheet.

Using the QPalette has saved a ton, by not having to modify widget by widget.  For the extra details, I'm fine to use the app.setStyleSheet except that it doesn't always work.

Is it me, or is this just the way it is?


问:
Next.Js page is not crawlable by the google even if page is not broken
I just finished up my next.js music application beatsbajao and uploaded to live server. Then I submitted my site to google search console. After few days when I checked there was an error in the search console and pages were not indexed.

Screenshot of google search console.

Then I checked with some of the crawlers like https://www.siteliner.com and alphacrawler.pro to crawl my site and they were also not able to crawl many of the pages from site and getting 500 error.

For the first time I was using  without baseUrl of site like given below

```<code><Link href="/foo/bar"><a>Go to another page </Link>
</code>```

and tested it with alphacrawler.pro and it was showing me some errors i.e. page broken.

Then I decided to change  tag and added baseUrl of every  tag given below

```<code><Link href="https://beatsbajao.com/foo/bar"><a>Go to another page </Link>
</code>```

In both the scenarios the app works fine in browser but the issue comes when crawlers want to crawl the site and it finds that the page is broken.

I am not sure why the page is not getting crawled by the crawlers.

Above is the screenshot of crawler result which shows the broken page even if it is not broken and can be accessed using that url shown in the screenshot.

I am not able to figure out why crawler is getting 500 error. If this is fixed may be Google can start indexing my site. The project can be seen here beatsbajao.com

Body:
I just finished up my next.js music application beatsbajao and uploaded to live server. Then I submitted my site to google search console. After few days when I checked there was an error in the search console and pages were not indexed.

Screenshot of google search console.

Then I checked with some of the crawlers like https://www.siteliner.com and alphacrawler.pro to crawl my site and they were also not able to crawl many of the pages from site and getting 500 error.

For the first time I was using  without baseUrl of site like given below

<Link href="/foo/bar">Go to another page </Link>

and tested it with alphacrawler.pro and it was showing me some errors i.e. page broken.

Then I decided to change  tag and added baseUrl of every  tag given below

<Link href="https://beatsbajao.com/foo/bar">Go to another page </Link>

In both the scenarios the app works fine in browser but the issue comes when crawlers want to crawl the site and it finds that the page is broken.

I am not sure why the page is not getting crawled by the crawlers.

Above is the screenshot of crawler result which shows the broken page even if it is not broken and can be accessed using that url shown in the screenshot.

I am not able to figure out why crawler is getting 500 error. If this is fixed may be Google can start indexing my site. The project can be seen here beatsbajao.com


问:
Flutter and Cloud Storage - upload and download files, best approach
Using Flutter and Cloud Storage, let's say that the user wants to upload files from the App, and later on (in another session) download the files.

What would be a better approach:

Upload the file, get a downloadUrl and store it in Firestore.

Once the user needs to download the file, the app gets the downloadUrl from the DB and downloads it

Upload the file.

Only when the user needs to download the file, a downloadUrl is generated from reference, using getDownloadUrl, and this downloadUrl is used in order to download the file. The downloadUrl isn't store anywhere

The first approach seems to be simpler (storing the downloadUrl in the DB), but if someone access this downloadUrl, he can access the file via simple http call (from the browser).

The second approach requires the app to make an async call (getDownloadUrl) whenever it needs to download / display the store file...


问:
Is there any difference between handling TCP connection in .netCore vs .netFramework?
I'm trying to write a stable server that can handle many concurrent TCP connections and can be scaled up.

I have a class library that is my TCP Server and a Server Host console app that is the entry point to the server and execute the server in console;
I have two versions of Server Host that are exactly the same (I mean same lines of code with no difference) but in different frameworks :

.netFramework4.8 console app

.net7 console app

Everything's good in the first app (.net framework 4.8) but I have a situation in the second one (.net7).

b.t.w: I'm using a port monitoring tool (Nirsoft CurrPorts) to see the current port states in my OS.

I'm sending many concurrent requests (e.g: 3000+) to both of them. The first one (.netFramework4.8) can handle the connections correctly; It releases the port after its job done, and I see just a little of TIME_WAIT ports in my monitoring tool.
But the second one (.net7), I don't know what happened, but I see a lot of TIME_WAIT ports in my monitoring tool, and because of this, I will run out of free/available dynamic TCP ports and cannot open a new connection! (I know it's sth related to TCP Port Exhaustion and this TIME_WAIT state is related to TCP Protocol handshake and the timeout differs in each OS)

So my question is, Is it any difference in handling TCP connection and states in .net framework to .net core?
And what should I do? How to investigate the situation?

I also increased my dynamic ports range (MaxUserPort) in my OS (windows 10). But I didn't change the default value of TcpTimedWaitDelay setting.


问:
Amazon EventBridge: example of C# function making API call
I'm using EventBridge and have set it up so if an S3 bucket receives a new file, my function is called.

From that function (which I would prefer be in C#, but other languages would be fine too if it's simpler) I want to call my application's API.  Just do a Post with something like https://myip.com/newFile?name=thenewfilename.txt

My understanding is that it would be better to put 'myip.com' as an environment variable so it could be changed more easily?

Any example or code which shows how to do this?


问:
Using vm_read to read another process memory
I have written some code in order to read another process memory. This is for macOS/GNU Mach.

```<code>#include <stdio.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>

int main() {
    pid_t pid;
    printf("PID: ");
    scanf("%d", &pid);
    vm_address_t address;
    printf("Address: ");
    scanf("%lx", &address);
    vm_offset_t readMem;
    vm_map_read_t task = task_for_pid(mach_task_self(), pid, &task);
    mach_msg_type_number_t size = sizeof(int);
    kern_return_t result = vm_read(task, address, (pointer_t)sizeof(int), &readMem, &size);
    if (result) {
        fprintf(stderr, "cant read, result 0x%x\n", result);
    }
    printf("%lu", readMem);
}
</code>```

Upon running it and providing a valid PID, it returns MACH_SEND_INVALID_DEST.

Body:
I have written some code in order to read another process memory. This is for macOS/GNU Mach.

#include <stdio.h>
#include <sys/types.h>
#include <mach/mach.h>
#include <mach/mach_vm.h>

int main() {
    pid_t pid;
    printf("PID: ");
    scanf("%d", &pid);
    vm_address_t address;
    printf("Address: ");
    scanf("%lx", &address);
    vm_offset_t readMem;
    vm_map_read_t task = task_for_pid(mach_task_self(), pid, &task);
    mach_msg_type_number_t size = sizeof(int);
    kern_return_t result = vm_read(task, address, (pointer_t)sizeof(int), &readMem, &size);
    if (result) {
        fprintf(stderr, "cant read, result 0x%x\n", result);
    }
    printf("%lu", readMem);
}

Upon running it and providing a valid PID, it returns MACH_SEND_INVALID_DEST.


问:
React Native: how to make patch versions match on iOS/Android?
I'm on version 4.4.33.3 of my React Native app. In XCode this works fine:

but for Android, if I make the versionCode 3 if prevents me from uploading to Google Play because I've already uploaded one with versionCode 3. It makes me increment the versionCode every time. So right now I'm forced to use 7 or above, but when users download this Android build it shows 4.4.33.7. Is there a way to avoid this mismatch between versions in iOS vs Android?


问:
how do i use getter and setter in flutter?
Im trying to create tic tac toe game, but im getting some logical error when Im trying to use
provider method.

in the home page i have column containing three widget. first for player scores , second for gird layout, third for winner result.

i did some research and i found out using provider calss is the best option to send data from a widget to another.

```<code>import 'package:flutter/cupertino.dart';
import 'package:tictactoe/widgets/scores.dart';
import '../widgets/layout.dart';

// import '../widgets/scores.dart';

class GameProvider with ChangeNotifier {
  bool oTrue = true;
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = 'hey';
  int oScores = 0;
  int xScores = 0;
  int failedScores = 0;
  checkWinner() {
    // checking 1 row
    if ((displayXO[0] == displayXO[1]) &&
        (displayXO[0] == displayXO[2]) &&
        displayXO[0] != '') {
      resultDetection = 'player ' + displayXO[0] + 'wins';
      print('$resultDetection');
    }
    // checking 2 row
    if ((displayXO[3] == displayXO[4]) &&
        (displayXO[3] == displayXO[5]) &&
        (displayXO[3] != '')) {
      resultDetection = 'player ' + displayXO[3] + 'wins';
    }
    // checking 3 row
    if ((displayXO[6] == displayXO[7]) &&
        (displayXO[6] == displayXO[8]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + 'wins';
    }
    // checking 1 column
    if ((displayXO[0] == displayXO[3]) &&
        (displayXO[0] == displayXO[6]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + 'wins';
    }
    // checking 2 column
    if ((displayXO[1] == displayXO[4]) &&
        (displayXO[1] == displayXO[7]) &&
        (displayXO[1] != '')) {
      resultDetection = 'player ' + displayXO[1] + 'wins';
    }
    // checking 3 column
    if ((displayXO[2] == displayXO[5]) &&
        (displayXO[2] == displayXO[8]) &&
        (displayXO[2] != '')) {
      resultDetection = 'player ' + displayXO[2] + 'wins';
    }
    // checking 1 axis
    if ((displayXO[6] == displayXO[4]) &&
        (displayXO[6] == displayXO[2]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + 'wins';
    }
    // checking 2 axis
    if ((displayXO[0] == displayXO[4]) &&
        (displayXO[0] == displayXO[8]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + 'wins';
    }
    notifyListeners();
  }

  set upgrateScores(String winner) {
    if (winner == 'O') {
      oScores++;
    } else if (winner == 'X') {
      xScores++;
    }
    print('$oScores, $xScores');
    notifyListeners();
  }

  get winnerfunction => checkWinner();
  // get upgrarate => upgrateScores();
  get result => resultDetection;
}
</code>```

and this is my great layout

```<code> Widget build(BuildContext context) {
    void _tap() {}
    return GridView.builder(
        itemCount: 9,
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemBuilder: ((context, index) {
          return GestureDetector(
            onTap: () {
              tapped(index);
            },
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                border: Border.all(width: 5, color: Colors.red),
                color: Colors.yellow,
              ),
              child: Center(
                child: Text(
                  displayXO[index],
                  style: GoogleFonts.coiny(fontSize: 64, color: Colors.red),
                ),
              ),
            ),
          );
        }));
  }

  void tapped(int tap) {
    setState(() {
      if (oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'O';
        oTrue = false;
      } else if (!oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'X';
        oTrue = true;
      }

      print('object');
      GameProvider provider = Provider.of<GameProvider>(context, listen: false);
      provider.checkWinner();
    });

</code>```

}

Body:
Im trying to create tic tac toe game, but im getting some logical error when Im trying to use
provider method.

in the home page i have column containing three widget. first for player scores , second for gird layout, third for winner result.

i did some research and i found out using provider calss is the best option to send data from a widget to another.

import 'package:flutter/cupertino.dart';
import 'package:tictactoe/widgets/scores.dart';
import '../widgets/layout.dart';

// import '../widgets/scores.dart';

class GameProvider with ChangeNotifier {
  bool oTrue = true;
  List displayXO = ['', '', '', '', '', '', '', '', ''];
  String resultDetection = 'hey';
  int oScores = 0;
  int xScores = 0;
  int failedScores = 0;
  checkWinner() {
    // checking 1 row
    if ((displayXO[0] == displayXO[1]) &&
        (displayXO[0] == displayXO[2]) &&
        displayXO[0] != '') {
      resultDetection = 'player ' + displayXO[0] + 'wins';
      print('$resultDetection');
    }
    // checking 2 row
    if ((displayXO[3] == displayXO[4]) &&
        (displayXO[3] == displayXO[5]) &&
        (displayXO[3] != '')) {
      resultDetection = 'player ' + displayXO[3] + 'wins';
    }
    // checking 3 row
    if ((displayXO[6] == displayXO[7]) &&
        (displayXO[6] == displayXO[8]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + 'wins';
    }
    // checking 1 column
    if ((displayXO[0] == displayXO[3]) &&
        (displayXO[0] == displayXO[6]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + 'wins';
    }
    // checking 2 column
    if ((displayXO[1] == displayXO[4]) &&
        (displayXO[1] == displayXO[7]) &&
        (displayXO[1] != '')) {
      resultDetection = 'player ' + displayXO[1] + 'wins';
    }
    // checking 3 column
    if ((displayXO[2] == displayXO[5]) &&
        (displayXO[2] == displayXO[8]) &&
        (displayXO[2] != '')) {
      resultDetection = 'player ' + displayXO[2] + 'wins';
    }
    // checking 1 axis
    if ((displayXO[6] == displayXO[4]) &&
        (displayXO[6] == displayXO[2]) &&
        (displayXO[6] != '')) {
      resultDetection = 'player ' + displayXO[6] + 'wins';
    }
    // checking 2 axis
    if ((displayXO[0] == displayXO[4]) &&
        (displayXO[0] == displayXO[8]) &&
        (displayXO[0] != '')) {
      resultDetection = 'player ' + displayXO[0] + 'wins';
    }
    notifyListeners();
  }

  set upgrateScores(String winner) {
    if (winner == 'O') {
      oScores++;
    } else if (winner == 'X') {
      xScores++;
    }
    print('$oScores, $xScores');
    notifyListeners();
  }

  get winnerfunction => checkWinner();
  // get upgrarate => upgrateScores();
  get result => resultDetection;
}

and this is my great layout

 Widget build(BuildContext context) {
    void _tap() {}
    return GridView.builder(
        itemCount: 9,
        gridDelegate:
            SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 3),
        itemBuilder: ((context, index) {
          return GestureDetector(
            onTap: () {
              tapped(index);
            },
            child: Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(15),
                border: Border.all(width: 5, color: Colors.red),
                color: Colors.yellow,
              ),
              child: Center(
                child: Text(
                  displayXO[index],
                  style: GoogleFonts.coiny(fontSize: 64, color: Colors.red),
                ),
              ),
            ),
          );
        }));
  }

  void tapped(int tap) {
    setState(() {
      if (oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'O';
        oTrue = false;
      } else if (!oTrue && displayXO[tap] == '') {
        displayXO[tap] = 'X';
        oTrue = true;
      }

      print('object');
      GameProvider provider = Provider.of<GameProvider>(context, listen: false);
      provider.checkWinner();
    });

}


问:
KeyError with hypixel api when profile json does exist
I'm using the Hypixel API while getting a response I try to find a certain key (last_save) in the json request.get(url) gets but while to print it, it keeps saying that the key doesn't exist this is my code

```<code>import requests
import json
api_key = 'API KEY HERE'
uuid = 'UUID HERE'
profileID = 'PROFILE ID HERE'

 #Set the player name to the desired username
player = 'PLAYER NAME HERE'

 #Make the request to the API
url = f'https://api.hypixel.net/skyblock/profile?key={api_key}&profile={profileID}'
response = requests.get(url)

 #Parse the JSON response
data = response.json()
last_save = data["last_save"]

 #Print the player's information
print(data['profile'])
</code>```

this is the error it throws

```<code>'Traceback (most recent call last):
  File "c:\Users\...\main.py", line 16, in <module>
    last_save = data["last_save"]
KeyError: 'last_save''
</code>```

how do i fix

Body:
I'm using the Hypixel API while getting a response I try to find a certain key (last_save) in the json request.get(url) gets but while to print it, it keeps saying that the key doesn't exist this is my code

import requests
import json
api_key = 'API KEY HERE'
uuid = 'UUID HERE'
profileID = 'PROFILE ID HERE'

 #Set the player name to the desired username
player = 'PLAYER NAME HERE'

 #Make the request to the API
url = f'https://api.hypixel.net/skyblock/profile?key={api_key}&profile={profileID}'
response = requests.get(url)

 #Parse the JSON response
data = response.json()
last_save = data["last_save"]

 #Print the player's information
print(data['profile'])

this is the error it throws

'Traceback (most recent call last):
  File "c:\Users\...\main.py", line 16, in <module>
    last_save = data["last_save"]
KeyError: 'last_save''

how do i fix


问:
Do PySpark window functions affect the write operation?
I am having trouble writing a PySpark dataframe (~50 columns and ~9 million rows) to an S3 bucket, and I have isolated the problem, though I am not sure why the problem occurs.

The following runs quite quickly (< 1 minute):

```<code># Runs < 1 minute
df.write.format('parquet') \
    .option("escape", "\"")\
    .option('header', 'true') \
    .mode('overwrite') \
    .save("s3://userName/folderName")
</code>```

However, if I perform the following steps, then the write doesn’t finish (i.e., it just "hangs" for hours)?

```<code>window1 = Window.partitionBy("state")\
    .orderBy(F.col("date").cast('timestamp').cast('long'))\
    .rangeBetween(-100,0)

df = df.withColumn('new_variable', F.avg(F.col('binary_variable_01')).over(window1))

df.count()

# Runs for hours after running the window funciton
df.write.format('parquet') \
    .option("escape", "\"")\
    .option('header', 'true') \
    .mode('overwrite') \
    .save("s3://userName/folderName")
</code>```

Here is what I have tried:

Repartitioning to correct for data skew didn’t work (i.e. df = df.repartition(50))

Coalesce to correct for data skew also didn’t work (i.e. df = df.coalesce(50))

Missing values in the partitionBy variable (i.e., "state" above) were imputed, but this didn’t solve the issue.

Created a random partition variable (50 random values) and then repartitioned based on this; didn’t work.

Does anyone have an idea as to how to resolve this issue?

Body:
I am having trouble writing a PySpark dataframe (~50 columns and ~9 million rows) to an S3 bucket, and I have isolated the problem, though I am not sure why the problem occurs.

The following runs quite quickly (< 1 minute):

# Runs < 1 minute
df.write.format('parquet') \
    .option("escape", "\"")\
    .option('header', 'true') \
    .mode('overwrite') \
    .save("s3://userName/folderName")

However, if I perform the following steps, then the write doesn’t finish (i.e., it just "hangs" for hours)?

window1 = Window.partitionBy("state")\
    .orderBy(F.col("date").cast('timestamp').cast('long'))\
    .rangeBetween(-100,0)

df = df.withColumn('new_variable', F.avg(F.col('binary_variable_01')).over(window1))

df.count()

# Runs for hours after running the window funciton
df.write.format('parquet') \
    .option("escape", "\"")\
    .option('header', 'true') \
    .mode('overwrite') \
    .save("s3://userName/folderName")

Here is what I have tried:

Repartitioning to correct for data skew didn’t work (i.e. df = df.repartition(50))

Coalesce to correct for data skew also didn’t work (i.e. df = df.coalesce(50))

Missing values in the partitionBy variable (i.e., "state" above) were imputed, but this didn’t solve the issue.

Created a random partition variable (50 random values) and then repartitioned based on this; didn’t work.

Does anyone have an idea as to how to resolve this issue?


问:
undefined reference to functions in gzip
When I was trying to build the Hiawatha webserver, I got the following error:

[  1%] Linking C executable cgi-wrapper
/usr/bin/ld: CMakeFiles/cgi-wrapper.dir/src/libfs.c.o: in function gzip_file': /home/yliang19/Downloads/hiawatha-11.3/src/libfs.c:403: undefined reference to gzopen64'
/usr/bin/ld: /home/yliang19/Downloads/hiawatha-11.3/src/libfs.c:424: undefined reference to gzclose' /usr/bin/ld: /home/yliang19/Downloads/hiawatha-11.3/src/libfs.c:417: undefined reference to gzwrite'
/usr/bin/ld: /home/yliang19/Downloads/hiawatha-11.3/src/libfs.c:424: undefined reference to `gzclose'
collect2: error: ld returned 1 exit status

But gzip has been installed by default and is already the newest version. The makefile is generated by cmake. Any ideas what's going wrong?

Tried to install gzip and no change was made.

gzip is already the newest version (1.10-4ubuntu4.1).
The following packages were automatically installed and are no longer required:
libflashrom1 libftdi1-2
Use 'sudo apt autoremove' to remove them.
0 upgraded, 0 newly installed, 0 to remove and 33 not upgraded.

The error stays the same when running "make install".


问:
Win form test automation finding information using the ui attribute id
Disclaimer: I am not an Win form test automation expert...

I am work with FlaUI, XUnit and C#.  Through FlaUI, I was able to obtain something called the UIA Attribute Id as referenced here by Microsoft.

My question is how can I obtain the actual value by using this id?

Thanks!


问:
Confirming understanding of security protocol modelled in Scyther
In university, I'm currently learning how to use Scyther to model security protocols. Currently I am trying to understand what is happening in an example protocol given to me which is:

```<code># Key Establishment Protocol
#

usertype SessionKey;

protocol ke11(I,R,S)
{
    role I
    {
        var Kir: SessionKey;

        send_1(I,S, R);
        recv_2(S,I,{Kir}k(I,S));

        claim_I1(I,Running,R,Kir);

        send_4(I,R,{I}Kir);
        recv_5(R,I,{R}Kir);

        claim_I3(I,Commit,R,Kir);
        claim_I1(I,Secret,Kir);
    }

    role R
    {
        var Kir: SessionKey;

        recv_3(S,R, (I,{Kir}k(R,S)));
        recv_4(I,R,{I}Kir);

        claim_R3(R,Running,I,Kir);

        send_5(R,I,{R}Kir);

        claim_R2(R,Commit,I,Kir);

        claim_R1(R,Secret,Kir);
    }

    role S
    {
        fresh Kir : SessionKey;

        recv_1(I,S, R);
        send_2(S,I, {Kir}k(I,S));
        send_3(S,R, I,{Kir}k(R,S));
    }
}
</code>```

This has also been given to me:

```<code>1. I → S : R
2. S → I : {Kir}k(I,S)
3. S → R : I,{Kir}k(R,S)
4. R → I : {I}Kir
5. I → R : {R}Kir
</code>```

From my understanding:

I is sending S the value of R

S is sending I the encryption of Kir, which is encrypted using a shared symmetric
key between I and S

S is sending R the encryption of Kir, which is encrypted using a shared symmetric
key between R and S

I is sending R the value of I encrypted using Kir which it got from decrypting the
value in 2 using the shared symmetric key

R is sending I the value of R encrypted using Kir which it got from decrypting the
value in 3 using the shared symmetric key.

I'm not really sure if this is correct so could someone please comment on if my understanding is correct or not. Specifically, I don't really understand what is being sent when I have written that the value of I or R is being sent (I -> S:R).

Any comments would greatly be appreciated.
Many thanks.

Body:
In university, I'm currently learning how to use Scyther to model security protocols. Currently I am trying to understand what is happening in an example protocol given to me which is:

# Key Establishment Protocol
#

usertype SessionKey;

protocol ke11(I,R,S)
{
    role I
    {
        var Kir: SessionKey;

        send_1(I,S, R);
        recv_2(S,I,{Kir}k(I,S));

        claim_I1(I,Running,R,Kir);

        send_4(I,R,{I}Kir);
        recv_5(R,I,{R}Kir);

        claim_I3(I,Commit,R,Kir);
        claim_I1(I,Secret,Kir);
    }

    role R
    {
        var Kir: SessionKey;

        recv_3(S,R, (I,{Kir}k(R,S)));
        recv_4(I,R,{I}Kir);

        claim_R3(R,Running,I,Kir);

        send_5(R,I,{R}Kir);

        claim_R2(R,Commit,I,Kir);

        claim_R1(R,Secret,Kir);
    }

    role S
    {
        fresh Kir : SessionKey;

        recv_1(I,S, R);
        send_2(S,I, {Kir}k(I,S));
        send_3(S,R, I,{Kir}k(R,S));
    }
}

This has also been given to me:

1. I → S : R
2. S → I : {Kir}k(I,S)
3. S → R : I,{Kir}k(R,S)
4. R → I : {I}Kir
5. I → R : {R}Kir

From my understanding:

I is sending S the value of R

S is sending I the encryption of Kir, which is encrypted using a shared symmetric
key between I and S

S is sending R the encryption of Kir, which is encrypted using a shared symmetric
key between R and S

I is sending R the value of I encrypted using Kir which it got from decrypting the
value in 2 using the shared symmetric key

R is sending I the value of R encrypted using Kir which it got from decrypting the
value in 3 using the shared symmetric key.

I'm not really sure if this is correct so could someone please comment on if my understanding is correct or not. Specifically, I don't really understand what is being sent when I have written that the value of I or R is being sent (I -> S:R).

Any comments would greatly be appreciated.
Many thanks.


问:
Can I use Keymando To Bind Things With MonoDevelop?
I'm working with the lovely Keymando and also with MonoDevelop, but I couldn't figure out how to use the bindings.</p>


问:
How to position a control generated by code in a panel?
Im trying to position a Circular progress bar generated by code in a panel but i dont know how did it
I have a button to generated this control i do it in the form but i cant in the panel.

im using this code but i dont found the correct function

 circularPB.Location = panel1.;


问:
./configure results in bootstrapping make fragment error only on github
I have a docker container build from debian:latest. The Dockerfile configures and makes the project the project. This build works on local and builds a container. However on github it gives me the following error:

```<code>[1/2] STEP 16/17: RUN ./configure GIT_BRANCH=$BRANCH GIT_VERSION=$VERSION
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether make supports nested variables... (cached) yes
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking whether make supports the include directive... yes (GNU style)
checking dependency style of g++... gcc3
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking dependency style of gcc... gcc3
checking for gcc option to accept ISO C99... none needed
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking how to print strings... printf
checking for a sed that does not truncate output... /bin/sed
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for fgrep... /bin/grep -F
checking for ld used by gcc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 3145728
checking how to convert x86_64-pc-linux-gnu file names to x86_64-pc-linux-gnu format... func_convert_file_noop
checking how to convert x86_64-pc-linux-gnu file names to toolchain format... func_convert_file_noop
checking for /usr/bin/ld option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... @
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm -B output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... no
checking if : is a manifest tool... no
checking how to run the C preprocessor... gcc -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... no
checking for gcc option to produce PIC... -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works... yes
checking if gcc static flag -static works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... /usr/bin/ld -m elf_x86_64
checking if the linker (/usr/bin/ld -m elf_x86_64) is GNU ld... yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking for g++ option to produce PIC... -fPIC -DPIC
checking if g++ PIC flag -fPIC -DPIC works... yes
checking if g++ static flag -static works... yes
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking dynamic linker characteristics... (cached) GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether g++ supports C++14 features with -std=c++14... yes
checking for boostlib >= 1.42.0... yes
checking whether the Boost::Regex library is available... yes
checking for exit in -lboost_regex... yes
checking for sphirewall-libs... configure: We could not detect the sphirewall libraries.
checking for ldap_simple_bind_s in -lldap... yes
checking for pthread_create in -lpthread... yes
checking for curl_global_init in -lcurl... yes
checking for sys/types.h... (cached) yes
checking for netinet/in.h... yes
checking for arpa/nameser.h... yes
checking for netdb.h... yes
checking for resolv.h... yes
checking whether to enable assertions... yes
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for libprocps... yes
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating src/Makefile
config.status: creating Makefile
config.status: creating src/autoconf.h
config.status: executing depfiles commands
config.status: error: in `/sphirewall-code/sphirewall-core':
config.status: error: Something went wrong bootstrapping makefile fragments
    for automatic dependency tracking.  If GNU make was not used, consider
    re-running the configure script with MAKE="gmake" (or whatever is
    necessary).  You can also try re-running configure with the
    '--disable-dependency-tracking' option to at least be able to build
    the package (albeit without support for automatic dependency tracking).
See `config.log' for more details
[2/2] STEP 1/10: FROM debian:latest
error building at STEP "RUN ./configure GIT_BRANCH=$BRANCH GIT_VERSION=$VERSION": error while running runtime: exit status 1
time="2023-01-12T15:41:50Z" level=error msg="exit status 1"
Error: Error: buildah exited with code 1
</code>```

I expect my github action to build a container out of this. I have attached my docker file too. I also wish I could see the config.log that github generates. Is there a way to do that?

Docker file:

```<code>#Taking base as bookworm version and naming it builder
FROM debian:latest as builder

ENV DEBIAN_FRONTEND=noninteractive

#Libraries needed
RUN apt-get update
RUN apt-get -y install build-essential apt-utils\
                    libprocps-dev\
                    iproute2\
                    g++\
                    libcurl4-openssl-dev\
                    libdumbnet-dev\
                    libjemalloc-dev\
                    libpam0g-dev\
                    libldap2-dev\
                    libpcap-dev\
                    libevent-dev\
                    libnfnetlink-dev\
                    libmnl-dev\
                    ldap-utils\
                    libnetfilter-queue-dev\
                    uuid-dev\
                    libtool\
                    libncurses5\
                    libncurses5-dev\
                    libboost-dev\
                    libgtest-dev\
                    libboost-regex-dev\
                    openssl\
                    libssl-dev\
                    automake\
                    libboost-thread-dev\
                    libboost-system-dev\
                    libsqlite3-dev\
                    libboost-serialization-dev\
                    libboost-random-dev\
                    libboost-iostreams-dev\
                    procps\
                    libnetfilter-conntrack-dev\
                    libpstreams-dev\
                    kmod\
                    vim\
                    iptables\
                    pkg-config

COPY fz-pkgrepo_1.0_amd64.deb /tmp
RUN dpkg -i /tmp/fz-pkgrepo_1.0_amd64.deb
RUN apt-get update

COPY sphirewall.conf /etc/sphirewall.conf
RUN mkdir sphirewall-code
COPY ../sphirewall-code sphirewall-code/
WORKDIR /sphirewall-code/sphirewall-core

#Make the sphirewalld service inside
RUN ls
RUN autoreconf -ivf
RUN ./configure
RUN make
</code>```

Body:
I have a docker container build from debian:latest. The Dockerfile configures and makes the project the project. This build works on local and builds a container. However on github it gives me the following error:

[1/2] STEP 16/17: RUN ./configure GIT_BRANCH=$BRANCH GIT_VERSION=$VERSION
checking for a BSD-compatible install... /usr/bin/install -c
checking whether build environment is sane... yes
checking for a thread-safe mkdir -p... /bin/mkdir -p
checking for gawk... no
checking for mawk... mawk
checking whether make sets $(MAKE)... yes
checking whether make supports nested variables... yes
checking whether make supports nested variables... (cached) yes
checking for g++... g++
checking whether the C++ compiler works... yes
checking for C++ compiler default output file name... a.out
checking for suffix of executables...
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C++ compiler... yes
checking whether g++ accepts -g... yes
checking whether make supports the include directive... yes (GNU style)
checking dependency style of g++... gcc3
checking for gcc... gcc
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking whether gcc understands -c and -o together... yes
checking dependency style of gcc... gcc3
checking for gcc option to accept ISO C99... none needed
checking build system type... x86_64-pc-linux-gnu
checking host system type... x86_64-pc-linux-gnu
checking how to print strings... printf
checking for a sed that does not truncate output... /bin/sed
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for fgrep... /bin/grep -F
checking for ld used by gcc... /usr/bin/ld
checking if the linker (/usr/bin/ld) is GNU ld... yes
checking for BSD- or MS-compatible name lister (nm)... /usr/bin/nm -B
checking the name lister (/usr/bin/nm -B) interface... BSD nm
checking whether ln -s works... yes
checking the maximum length of command line arguments... 3145728
checking how to convert x86_64-pc-linux-gnu file names to x86_64-pc-linux-gnu format... func_convert_file_noop
checking how to convert x86_64-pc-linux-gnu file names to toolchain format... func_convert_file_noop
checking for /usr/bin/ld option to reload object files... -r
checking for objdump... objdump
checking how to recognize dependent libraries... pass_all
checking for dlltool... no
checking how to associate runtime and link libraries... printf %s\n
checking for ar... ar
checking for archiver @FILE support... @
checking for strip... strip
checking for ranlib... ranlib
checking command to parse /usr/bin/nm -B output from gcc object... ok
checking for sysroot... no
checking for a working dd... /bin/dd
checking how to truncate binary pipes... /bin/dd bs=4096 count=1
checking for mt... no
checking if : is a manifest tool... no
checking how to run the C preprocessor... gcc -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
checking for dlfcn.h... yes
checking for objdir... .libs
checking if gcc supports -fno-rtti -fno-exceptions... no
checking for gcc option to produce PIC... -fPIC -DPIC
checking if gcc PIC flag -fPIC -DPIC works... yes
checking if gcc static flag -static works... yes
checking if gcc supports -c -o file.o... yes
checking if gcc supports -c -o file.o... (cached) yes
checking whether the gcc linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking whether -lc should be explicitly linked in... no
checking dynamic linker characteristics... GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether stripping libraries is possible... yes
checking if libtool supports shared libraries... yes
checking whether to build shared libraries... yes
checking whether to build static libraries... yes
checking how to run the C++ preprocessor... g++ -E
checking for ld used by g++... /usr/bin/ld -m elf_x86_64
checking if the linker (/usr/bin/ld -m elf_x86_64) is GNU ld... yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking for g++ option to produce PIC... -fPIC -DPIC
checking if g++ PIC flag -fPIC -DPIC works... yes
checking if g++ static flag -static works... yes
checking if g++ supports -c -o file.o... yes
checking if g++ supports -c -o file.o... (cached) yes
checking whether the g++ linker (/usr/bin/ld -m elf_x86_64) supports shared libraries... yes
checking dynamic linker characteristics... (cached) GNU/Linux ld.so
checking how to hardcode library paths into programs... immediate
checking whether g++ supports C++14 features with -std=c++14... yes
checking for boostlib >= 1.42.0... yes
checking whether the Boost::Regex library is available... yes
checking for exit in -lboost_regex... yes
checking for sphirewall-libs... configure: We could not detect the sphirewall libraries.
checking for ldap_simple_bind_s in -lldap... yes
checking for pthread_create in -lpthread... yes
checking for curl_global_init in -lcurl... yes
checking for sys/types.h... (cached) yes
checking for netinet/in.h... yes
checking for arpa/nameser.h... yes
checking for netdb.h... yes
checking for resolv.h... yes
checking whether to enable assertions... yes
checking for pkg-config... /usr/bin/pkg-config
checking pkg-config is at least version 0.9.0... yes
checking for libprocps... yes
checking that generated files are newer than configure... done
configure: creating ./config.status
config.status: creating src/Makefile
config.status: creating Makefile
config.status: creating src/autoconf.h
config.status: executing depfiles commands
config.status: error: in `/sphirewall-code/sphirewall-core':
config.status: error: Something went wrong bootstrapping makefile fragments
    for automatic dependency tracking.  If GNU make was not used, consider
    re-running the configure script with MAKE="gmake" (or whatever is
    necessary).  You can also try re-running configure with the
    '--disable-dependency-tracking' option to at least be able to build
    the package (albeit without support for automatic dependency tracking).
See `config.log' for more details
[2/2] STEP 1/10: FROM debian:latest
error building at STEP "RUN ./configure GIT_BRANCH=$BRANCH GIT_VERSION=$VERSION": error while running runtime: exit status 1
time="2023-01-12T15:41:50Z" level=error msg="exit status 1"
Error: Error: buildah exited with code 1

I expect my github action to build a container out of this. I have attached my docker file too. I also wish I could see the config.log that github generates. Is there a way to do that?

Docker file:

#Taking base as bookworm version and naming it builder
FROM debian:latest as builder

ENV DEBIAN_FRONTEND=noninteractive

#Libraries needed
RUN apt-get update
RUN apt-get -y install build-essential apt-utils\
                    libprocps-dev\
                    iproute2\
                    g++\
                    libcurl4-openssl-dev\
                    libdumbnet-dev\
                    libjemalloc-dev\
                    libpam0g-dev\
                    libldap2-dev\
                    libpcap-dev\
                    libevent-dev\
                    libnfnetlink-dev\
                    libmnl-dev\
                    ldap-utils\
                    libnetfilter-queue-dev\
                    uuid-dev\
                    libtool\
                    libncurses5\
                    libncurses5-dev\
                    libboost-dev\
                    libgtest-dev\
                    libboost-regex-dev\
                    openssl\
                    libssl-dev\
                    automake\
                    libboost-thread-dev\
                    libboost-system-dev\
                    libsqlite3-dev\
                    libboost-serialization-dev\
                    libboost-random-dev\
                    libboost-iostreams-dev\
                    procps\
                    libnetfilter-conntrack-dev\
                    libpstreams-dev\
                    kmod\
                    vim\
                    iptables\
                    pkg-config

COPY fz-pkgrepo_1.0_amd64.deb /tmp
RUN dpkg -i /tmp/fz-pkgrepo_1.0_amd64.deb
RUN apt-get update

COPY sphirewall.conf /etc/sphirewall.conf
RUN mkdir sphirewall-code
COPY ../sphirewall-code sphirewall-code/
WORKDIR /sphirewall-code/sphirewall-core

#Make the sphirewalld service inside
RUN ls
RUN autoreconf -ivf
RUN ./configure
RUN make


问:
Amplify AppSync Auth for Membership Model with Cognito User Pools
I'm trying to understand how to use AppSync GraphQL Schema and DataStore to grant access to models and sub-models to Users that have been granted access.

Let's say we have a Course model that hasMany Lessons.

I want only Users that have been granted access to a Course to be able to access the Course and its Lessons.

The owner of a Course can also create and access all content for that course.

I was exploring trying to create a Membership model, but can't quite seem to get the auth working correctly, and I'm still not sure how to cascade that all the way down to a Lesson level.

Any assistance on how to best accommodate this would be greatly appreciated.

```<code>type Course @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  description: String
  status: String
  Lessons: [Lesson] @hasMany(indexName: "bySection", fields: ["id"])
}

type Lesson @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  courseID: ID! @index(name: "byCourse")
}

type Membership
  @model
  @auth(rules: [{ allow: owner, ownerField: "member", operations: [read] }]) {
  id: ID!
  member: String
  Course: Course
    @hasOne
    @auth(rules: [{ allow: owner, ownerField: "member", operations: [read] }])
}
</code>```

Body:
I'm trying to understand how to use AppSync GraphQL Schema and DataStore to grant access to models and sub-models to Users that have been granted access.

Let's say we have a Course model that hasMany Lessons.

I want only Users that have been granted access to a Course to be able to access the Course and its Lessons.

The owner of a Course can also create and access all content for that course.

I was exploring trying to create a Membership model, but can't quite seem to get the auth working correctly, and I'm still not sure how to cascade that all the way down to a Lesson level.

Any assistance on how to best accommodate this would be greatly appreciated.

type Course @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  description: String
  status: String
  Lessons: [Lesson] @hasMany(indexName: "bySection", fields: ["id"])
}

type Lesson @model @auth(rules: [{ allow: owner }]) {
  id: ID!
  title: String!
  courseID: ID! @index(name: "byCourse")
}

type Membership
  @model
  @auth(rules: [{ allow: owner, ownerField: "member", operations: [read] }]) {
  id: ID!
  member: String
  Course: Course
    @hasOne
    @auth(rules: [{ allow: owner, ownerField: "member", operations: [read] }])
}


问:
How to get a role in SocketMessage in discord.net to check whether the user has this role
```<code>private async Task checkMessage(SocketMessage arg)
{
 IGuildUser user = (IGuildUser)arg.Author;
 if (!user.IsBot)
 {
  if (arg.Author.Role == "pop")
  {
   var emoji = new Emoji("\ud83d\udca9");
   await arg.AddReactionAsync(emoji);
   }
  }
}
</code>```

I want to check the role of the user who wrote the message, if there is a certain role, then perform a certain action, but I don't understand how to check the role of the user. Even reading the documentation I didn't understand anything.

I tried to get roles through SocketGuildUser, but nothing came out.

Body:
private async Task checkMessage(SocketMessage arg)
{
 IGuildUser user = (IGuildUser)arg.Author;
 if (!user.IsBot)
 {
  if (arg.Author.Role == "pop")
  {
   var emoji = new Emoji("\ud83d\udca9");
   await arg.AddReactionAsync(emoji);
   }
  }
}

I want to check the role of the user who wrote the message, if there is a certain role, then perform a certain action, but I don't understand how to check the role of the user. Even reading the documentation I didn't understand anything.

I tried to get roles through SocketGuildUser, but nothing came out.