问:
Saving a char value with fwrite returns incorrect data when loaded
I am using the frwite feature to save previous math equation result data and the code works when using integers but if I use char values (which I am trying to implement in order to make a certain future feature possible), I get weird values back. For example when the result 50 was saved, when the data was loaded I got the following:

```<code>2

2
</code>```

The following is the code I wrote in question:

```<code>#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <cbm.h>

int integer1;
int integer2;
int integer3;
int option;
char save;
char c;
FILE *fp; //?????

void startup() {
    textcolor (COLOR_WHITE);
    bordercolor (COLOR_BLACK);
    bgcolor (COLOR_BLACK);
    clrscr ();
}

void get2nums() {
    printf("FIRST NUMBER?\n");
    scanf("%d", &integer1);
    printf("SECOND NUMBER?\n");
    scanf("%d", &integer2);
}

void addition() {
    get2nums();
    save = integer1 + integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void subtraction() {
    get2nums();
    save = integer1 - integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void multiplication() {
    get2nums();
    save = integer1 * integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void division() {
    get2nums();
    if(integer2 == 0)
        printf("Div by 0 undefined\n");
    else
        save = integer1 / integer2; //save into the save variable which will provide input to the save file function
        printf("%d with %d remainder", integer1 / integer2, integer1 % integer2);
        printf("\n");
}

static void savedata(void) {
    char data_out = save; //Data that goes into the file

    //Saving
    _filetype = 's'; //Does this set the file as a .SEQ?
    if ((fp = fopen ("CALCDATA", "w")) == 0) {
        printf("ERROR COULD NOT OPEN FILE\n\r"); //Error handler
        printf("CHECK DISK DRIVE\n");
        exit(1);
    }
    fwrite (&data_out, sizeof(data_out), 1, fp);
    fclose (fp);
}

static void loaddata(void) {
    _filetype = 's';
    if ((fp = fopen ("CALCDATA", "r")) == 0) {
        printf("ERROR COULD NOT OPEN FILE\n\r");
        printf("CHECK DISK DRIVE\n");
        exit(1);
    }
    while (1) {
        c = fgetc (fp);
        if (feof (fp)) {
            break;
        }
        printf("\n");
        printf ("%c\n", c);
    }
    fclose (fp);
}

void debug() {
    printf("%d", save);
}

int main() {
    startup();
    for( ;; ) { // uncomment this line and below for infinite looping
        printf("\n");
    printf("ADVANCED CALCULATOR VERSION 0.9\n");
    //printf("CODED BY REDACTED\n");
    //printf("BUILD DATE: 12/12/2022\n");
    //delay(5000);
    //clrscr ();
    printf("CALCULATOR OPTIONS ARE:\n");
    printf("1. ADDITION\n");
    printf("2. SUBTRACTION\n");
    printf("3. MULTIPLICATION\n");
    printf("4. DIVISION\n");
    printf("5. SAVE PREVIOUS\n");
    printf("6. LOAD SAVE\n");
    printf("7. QUIT\n");
//  printf("8. DEBUG\n");
//  printf("5. ADVANCED OPERATIONS\n"); // TODO
    printf("PLEASE SELECT YOUR OPTION.\n");

    scanf("%d", &option);

    if(option == 1)
        addition();

    else if(option == 2)
        subtraction();

    else if(option == 3)
        multiplication();

    else if(option == 4)
        division();

    else if(option == 5)
        savedata();

    else if(option == 6)
        loaddata();

    else if(option == 7)
        exit(1);

    //else if(option == 8)
        //debug();

    else
        printf("INVALID RESPONSE\n");
    }  // uncomment this line for infinite looping
    return 0;
}
</code>```

I checked using the function I wrote called debug to see if the results of the previous math problem were being put in the variable correctly and they were. This leads me to the conclusion that it is something with the way the save or load code is written that is causing this issue. Also to note, I have previously gotten char data to save, but only when it was predefined with the char data_out variable written as char data_out[]. Any information on this issue helps, thanks!

Body:
I am using the frwite feature to save previous math equation result data and the code works when using integers but if I use char values (which I am trying to implement in order to make a certain future feature possible), I get weird values back. For example when the result 50 was saved, when the data was loaded I got the following:

2

2

The following is the code I wrote in question:

#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <cbm.h>

int integer1;
int integer2;
int integer3;
int option;
char save;
char c;
FILE *fp; //?????

void startup() {
    textcolor (COLOR_WHITE);
    bordercolor (COLOR_BLACK);
    bgcolor (COLOR_BLACK);
    clrscr ();
}

void get2nums() {
    printf("FIRST NUMBER?\n");
    scanf("%d", &integer1);
    printf("SECOND NUMBER?\n");
    scanf("%d", &integer2);
}

void addition() {
    get2nums();
    save = integer1 + integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void subtraction() {
    get2nums();
    save = integer1 - integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void multiplication() {
    get2nums();
    save = integer1 * integer2; //save into the save variable which will provide input to the save file function
    printf("%d", save);
    printf("\n");
}

void division() {
    get2nums();
    if(integer2 == 0)
        printf("Div by 0 undefined\n");
    else
        save = integer1 / integer2; //save into the save variable which will provide input to the save file function
        printf("%d with %d remainder", integer1 / integer2, integer1 % integer2);
        printf("\n");
}

static void savedata(void) {
    char data_out = save; //Data that goes into the file

    //Saving
    _filetype = 's'; //Does this set the file as a .SEQ?
    if ((fp = fopen ("CALCDATA", "w")) == 0) {
        printf("ERROR COULD NOT OPEN FILE\n\r"); //Error handler
        printf("CHECK DISK DRIVE\n");
        exit(1);
    }
    fwrite (&data_out, sizeof(data_out), 1, fp);
    fclose (fp);
}

static void loaddata(void) {
    _filetype = 's';
    if ((fp = fopen ("CALCDATA", "r")) == 0) {
        printf("ERROR COULD NOT OPEN FILE\n\r");
        printf("CHECK DISK DRIVE\n");
        exit(1);
    }
    while (1) {
        c = fgetc (fp);
        if (feof (fp)) {
            break;
        }
        printf("\n");
        printf ("%c\n", c);
    }
    fclose (fp);
}

void debug() {
    printf("%d", save);
}

int main() {
    startup();
    for( ;; ) { // uncomment this line and below for infinite looping
        printf("\n");
    printf("ADVANCED CALCULATOR VERSION 0.9\n");
    //printf("CODED BY REDACTED\n");
    //printf("BUILD DATE: 12/12/2022\n");
    //delay(5000);
    //clrscr ();
    printf("CALCULATOR OPTIONS ARE:\n");
    printf("1. ADDITION\n");
    printf("2. SUBTRACTION\n");
    printf("3. MULTIPLICATION\n");
    printf("4. DIVISION\n");
    printf("5. SAVE PREVIOUS\n");
    printf("6. LOAD SAVE\n");
    printf("7. QUIT\n");
//  printf("8. DEBUG\n");
//  printf("5. ADVANCED OPERATIONS\n"); // TODO
    printf("PLEASE SELECT YOUR OPTION.\n");

    scanf("%d", &option);

    if(option == 1)
        addition();

    else if(option == 2)
        subtraction();

    else if(option == 3)
        multiplication();

    else if(option == 4)
        division();

    else if(option == 5)
        savedata();

    else if(option == 6)
        loaddata();

    else if(option == 7)
        exit(1);

    //else if(option == 8)
        //debug();

    else
        printf("INVALID RESPONSE\n");
    }  // uncomment this line for infinite looping
    return 0;
}

I checked using the function I wrote called debug to see if the results of the previous math problem were being put in the variable correctly and they were. This leads me to the conclusion that it is something with the way the save or load code is written that is causing this issue. Also to note, I have previously gotten char data to save, but only when it was predefined with the char data_out variable written as char data_out[]. Any information on this issue helps, thanks!


来源: stackexchange

问:
Undefined reference?
A simple program but for some reason it can't run

```<code>#include <stdio.h>
#include <stdlib.h>
#include "simpio.h"
int main()
{
float kop;
kop = GetReal();
printf("%d",kop);
    return 0;
}

</code>```

it says undefined reference to 'GetReal' and 'getInteger' and the other

the compiler I guess is not in the right place

ContentLicense: CC BY-SA 4.0

Title: Undefined reference?

Body:
A simple program but for some reason it can't run

#include <stdio.h>
#include <stdlib.h>
#include "simpio.h"
int main()
{
float kop;
kop = GetReal();
printf("%d",kop);
    return 0;
}

it says undefined reference to 'GetReal' and 'getInteger' and the other

the compiler I guess is not in the right place


问:
Skicit-learn and sklearn both stuck in my code
I a trying to run a code, which worked perfectly a couple of hours ago. Now, the code causes an issue from here on:

```<code># string label to categorical values
from sklearn.preprocessing import LabelEncoder

for i in range(df_train.shape[1]):
    if df_train.iloc[:,i].dtypes == object:
        lbl = LabelEncoder()
        lbl.fit(list(df_train.iloc[:,i].values) + list(df_test.iloc[:,i].values))
        df_train.iloc[:,i] = lbl.transform(list(df_train.iloc[:,i].values))
        df_test.iloc[:,i] = lbl.transform(list(df_test.iloc[:,i].values))

print(df_train['zust_klassen'].unique())
</code>```
```<code>ModuleNotFoundError                       Traceback (most recent call last)
c:\Users\ehler\Documents\Masterarbeit\Codes\MAcoding_v5.ipynb Zelle 30 in <cell line: 2>()
      1 # string label to categorical values
----> 2 from sklearn.preprocessing import LabelEncoder
      4 for i in range(df_train.shape[1]):
      5     if df_train.iloc[:,i].dtypes == object:

ModuleNotFoundError: No module named 'sklearn'
</code>```

So I wanted to take a step back and install sklearn / scikit-learn. However it keeps telling me, that it is installed already (requirement already satisfied):

Requirement already satisfied: sklearn in c:\users\ehler\appdata\local\programs\python\python38-32\lib\site-packages (0.0.post1)

As you can see it tells me it is the version "0.0.post1" - this also appears under "pip list".

I am very thankful for any idea!

I tried to install / reinstall sklearn and/or scikit-learn. Both do not work.

I am working with visual studio code (not anaconda) and jupyter notebook, if that helps.

It has worked all day, now it stopped all of a sudden. Also I could not figure out how to uninstall the packages in order to reinstall, it always gives me a "syntax error".

Body:
I a trying to run a code, which worked perfectly a couple of hours ago. Now, the code causes an issue from here on:

# string label to categorical values
from sklearn.preprocessing import LabelEncoder

for i in range(df_train.shape[1]):
    if df_train.iloc[:,i].dtypes == object:
        lbl = LabelEncoder()
        lbl.fit(list(df_train.iloc[:,i].values) + list(df_test.iloc[:,i].values))
        df_train.iloc[:,i] = lbl.transform(list(df_train.iloc[:,i].values))
        df_test.iloc[:,i] = lbl.transform(list(df_test.iloc[:,i].values))

print(df_train['zust_klassen'].unique())

ModuleNotFoundError                       Traceback (most recent call last)
c:\Users\ehler\Documents\Masterarbeit\Codes\MAcoding_v5.ipynb Zelle 30 in <cell line: 2>()
      1 # string label to categorical values
----> 2 from sklearn.preprocessing import LabelEncoder
      4 for i in range(df_train.shape[1]):
      5     if df_train.iloc[:,i].dtypes == object:

ModuleNotFoundError: No module named 'sklearn'

So I wanted to take a step back and install sklearn / scikit-learn. However it keeps telling me, that it is installed already (requirement already satisfied):

Requirement already satisfied: sklearn in c:\users\ehler\appdata\local\programs\python\python38-32\lib\site-packages (0.0.post1)

As you can see it tells me it is the version "0.0.post1" - this also appears under "pip list".

I am very thankful for any idea!

I tried to install / reinstall sklearn and/or scikit-learn. Both do not work.

I am working with visual studio code (not anaconda) and jupyter notebook, if that helps.

It has worked all day, now it stopped all of a sudden. Also I could not figure out how to uninstall the packages in order to reinstall, it always gives me a "syntax error".


问:
Need to integrate REST APIs (endpoints) for fetching Canadian Weather Station Data
We want to integrate CKAN REST APIs to fetch Canadian Weather Station Data as per the URL: https://climate.weather.gc.ca/
This is the data that we are looking for: Sample Data

We have already gone through CKAN's available document URL: https://docs.ckan.org/en/2.8/api/index.html#get-able-api-functions

But we don't have any endpoints for integration.

How can we get access to CKAN endpoints?
Can anyone help us on the endpoints, so that we could complete the integration?

We have already gone through CKAN's available document URL: https://docs.ckan.org/en/2.8/api/index.html#get-able-api-functions

But we don't have any endpoints for integration.


问:
autopep 8 does not fix lengthy lists and dictionaries
Following the example, https://pypi.org/project/autopep8/ I tried to run autopep8 on the example file.

I ran autopep8 -i test.py. Also tried aggressive options and --select=E501. It does not fix the line length of the dictionary in the example 1.

Python 3.9.12 (Anaconda distribution), autopep8 2.0.0, MAC OS.

Original:

```<code>import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)
</code>```

Output:

```<code>import math
import sys

def example1():
    # This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {'long': 'Long code lines should be wrapped within 79     characters.',
                     'other': [math.pi, 100, 200, 300, 9876543210, 'This is a long     string that goes on'],
                     'more': {'inner': 'This whole logical line should be wrapped.',     some_tuple: [1,
                                                                                20, 300, 40000, 500000000, 60000000000000000]}}
    return (some_tuple, some_variable)

def example2(): return ('' in {'f': 2}) in {
    'has_key() is deprecated': True}

class Example3(object):
    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar :
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)
</code>```

Body:
Following the example, https://pypi.org/project/autopep8/ I tried to run autopep8 on the example file.

I ran autopep8 -i test.py. Also tried aggressive options and --select=E501. It does not fix the line length of the dictionary in the example 1.

Python 3.9.12 (Anaconda distribution), autopep8 2.0.0, MAC OS.

Original:

import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)

Output:

import math
import sys

def example1():
    # This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {'long': 'Long code lines should be wrapped within 79     characters.',
                     'other': [math.pi, 100, 200, 300, 9876543210, 'This is a long     string that goes on'],
                     'more': {'inner': 'This whole logical line should be wrapped.',     some_tuple: [1,
                                                                                20, 300, 40000, 500000000, 60000000000000000]}}
    return (some_tuple, some_variable)

def example2(): return ('' in {'f': 2}) in {
    'has_key() is deprecated': True}

class Example3(object):
    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar :
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)


问:
Linear Feature Improving Performance of Time-Series LSTM
I am currently training a time-series LSTM with daily timesteps between 2005 and 2019. My model includes hourly data as separate features, plus sin/cos cyclical encoding of the day of the year and one-hot encoding of the day of the week. I have found that if I also include a straight-line feature in the model, i.e. just start the first date in the data as a 1 and add one to every day until the end of the dataset, then scale it, the predictions greatly improve on the testing data. Has anybody else used a linear feature like this before? Is there any precedent for it?</p>


问:
How to pass over a python dictionary to a jinja template
I have a python dict containing let's say

```<code>mydict = {"US":5, "DE":3, "FR":2, "UK":2}
</code>```

I want to pass it over to my jinja template so that it would be stored as if I declared it like

```<code>var data = {"US":5, "DE":3, "FR":2, "UK":2};
</code>```

in Javascript.

I tried

```<code>var data = {{ mydict }}
</code>```

but here's what get's passed over:

```<code>{'US': 5, 'DE': 3, 'FR': 2}
</code>```

(and I get a syntax error obviously...)

Body:
I have a python dict containing let's say

mydict = {"US":5, "DE":3, "FR":2, "UK":2}

I want to pass it over to my jinja template so that it would be stored as if I declared it like

var data = {"US":5, "DE":3, "FR":2, "UK":2};

in Javascript.

I tried

var data = {{ mydict }}

but here's what get's passed over:

{'US': 5, 'DE': 3, 'FR': 2}

(and I get a syntax error obviously...)


问:
Using ActiveRecord to query count() over()
I want to limit the SQL query result set while also knowing how many possible rows match. I found that (with Postgresql), I could write

```<code>SELECT *,count(*) over() as total FROM ... WHERE ... LIMIT 5
</code>```

which will return a max of 5 rows, with a column called total which contains the total number of rows which match the query (it's the same value for all rows); this, to avoid multiple queries.

How can represent this as an ActiveRecord query? While I can pass the select clause to .select, but the "count(*) over()" field is ignored. I had to resort to exec_query and specify then entire select string.

Body:
I want to limit the SQL query result set while also knowing how many possible rows match. I found that (with Postgresql), I could write

SELECT *,count(*) over() as total FROM ... WHERE ... LIMIT 5

which will return a max of 5 rows, with a column called total which contains the total number of rows which match the query (it's the same value for all rows); this, to avoid multiple queries.

How can represent this as an ActiveRecord query? While I can pass the select clause to .select, but the "count(*) over()" field is ignored. I had to resort to exec_query and specify then entire select string.


问:
how do I convert a single char to a uint in a well defined way and cross platform way?
Let's say I have a single char:

```<code>char myChar = 'A';
</code>```

and I want to populate an uint:

```<code>uint8_t myUint8 = 0;  // 0 is just a default;
</code>```

is it well defined to do this:

```<code>myUint8 = static_cast<uint8_t>(myChar);
</code>```

So in this case I would expect

```<code>myUint8 == 65
</code>```

to evaluate to true.  Is this well defined?  Will this function cross platform?  If not how can I make it well defined and portable?

Update: While I would like to handle the problem of determining the encoding scheme and if uint8_t is available on target eventually, they are beyond the scope of this question, hence I would like to refine my example as follows:

    char myChar = 'A';
    unsigned myUnsigned = 0;  // 0 is just a default;
    myUnsigned = static_cast<unsigned>(myChar);
    char myRoundTripChar = static_cast<char>(myUnsigned);

    printf("char is unchanged: %s", myRoundTripChar == 'A' ? "true" : "false" );
```

the desired output here is true.  This alternate example removes all the 'magic numbers' and possibly defined types I think to show the problem another way.

Body:
Let's say I have a single char:

char myChar = 'A';

and I want to populate an uint:

uint8_t myUint8 = 0;  // 0 is just a default;

is it well defined to do this:

myUint8 = static_cast<uint8_t>(myChar);

So in this case I would expect

myUint8 == 65

to evaluate to true.  Is this well defined?  Will this function cross platform?  If not how can I make it well defined and portable?

Update: While I would like to handle the problem of determining the encoding scheme and if uint8_t is available on target eventually, they are beyond the scope of this question, hence I would like to refine my example as follows:

    char myChar = 'A';
    unsigned myUnsigned = 0;  // 0 is just a default;
    myUnsigned = static_cast<unsigned>(myChar);
    char myRoundTripChar = static_cast<char>(myUnsigned);

    printf("char is unchanged: %s", myRoundTripChar == 'A' ? "true" : "false" );

the desired output here is true.  This alternate example removes all the 'magic numbers' and possibly defined types I think to show the problem another way.


问:
I want to disable Clear Data button on Firefox or Kiwi Apk
im editing this Kiwi.apk because i want to be able to prevent that people go to manage apps in settings and clear data on this app
the reason why is because of the extensions that i can install.

it does not need to disable clear data button
i just want when people click on clear data that it launch a different activity like these.

```<code></application>android:label="Kiwi Browser" android:icon="@drawable/icon"
   android:manageSpaceActivity=".ActivityOfMyChoice">
</code>```

on the Application tag i added this
and i recompile it. when i try to install the apk the apk is succesfully installed but it crashed when i open the app
did i do something wrong? can anybody help me with AndroidManifest.xml

please be aware that this is my first time ever for editing a Apk

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

Body:
im editing this Kiwi.apk because i want to be able to prevent that people go to manage apps in settings and clear data on this app
the reason why is because of the extensions that i can install.

it does not need to disable clear data button
i just want when people click on clear data that it launch a different activity like these.

</application>android:label="Kiwi Browser" android:icon="@drawable/icon"
   android:manageSpaceActivity=".ActivityOfMyChoice">

on the Application tag i added this
and i recompile it. when i try to install the apk the apk is succesfully installed but it crashed when i open the app
did i do something wrong? can anybody help me with AndroidManifest.xml

please be aware that this is my first time ever for editing a Apk


问:
Angular material datepicker has weird styling
I was trying to make a good looking datepicker, something like in the material datepicker documentation

Datepicker I want

But I ended up with a weird looking datepicker that I can write text over and has awful styling, can anyone help with this?

My datepicker

Edit: this warning might be part of the problem?
Warning: (C://path..)\node_modules\ngx-material-timepicker_ivy_ngcc_\fesm2015\ngx-material-timepicker.js depends on 'luxon'. CommonJS or AMD
dependencies can cause optimization bailouts.

new-reservation.component.html

```<code><h3>Create reservation here</h3>
<form [formGroup]="reservationForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>
    <div>
      <input matInput>
      <ngx-timepicker-field [defaultTime]="'12:00 am'" formControlName="beginTime"></ngx-timepicker-field>
    </div>
  </mat-form-field>
  <br/>
  <mat-form-field>
    <div>
      <input matInput formControlName="endTime">
      <ngx-timepicker-field [defaultTime]="'12:00 am'" formControlName="endTime"></ngx-timepicker-field>
    </div>
  </mat-form-field>
  <br/>
  <br/>
  <mat-form-field appearance="standard">
    <mat-label>Choose date</mat-label>
    <input matInput [matDatepicker]="picker" min="{{ currentDate | date: 'yyyy-MM-dd' }}" formControlName="date">
    <mat-hint>DD MM YYYY</mat-hint>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker startView="year"></mat-datepicker>
  </mat-form-field>
  <br/><br/>
  <button mat-raised-button class="btn btn-primary">Create</button>
</form>
</code>```

new-reservation.component.ts

```<code>import { Component, OnInit } from '@angular/core';
import { FormBuilder } from "@angular/forms";
import { NewReservationService } from './new-reservation.service';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-new-reservation',
  templateUrl: './new-reservation.component.html',
  styleUrls: ['./new-reservation.component.scss'],
  providers: [DatePipe]
})
export class NewReservationComponent implements OnInit {
  constructor(private formBuilder: FormBuilder, private newReservationService: NewReservationService) { }

  currentDate: any = new Date();

  ngOnInit(): void {
  }

  reservationForm = this.formBuilder.group({
    beginTime: '',
    endTime: '',
    date: '',
    checkedin: false,
    canceled: false
  });
  onFormSubmit() {
    this.newReservationService.saveStudent(this.reservationForm.value);
    this.reservationForm.reset();
  }

}

</code>```
```<code>import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class NewReservationService {
  saveStudent(reservation) {
    console.log(JSON.stringify(reservation));
  }
}

</code>```

app-module.ts

```<code>import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {RegisterComponent} from "./register/register.component";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {RegisterService} from "./register/register.service";
import {HttpClientModule} from "@angular/common/http";
import { MainHeaderComponent } from './main-header/main-header.component';
import { CurrentReservationsComponent } from './reservations/current-reservations/current-reservations.component';
import { CheckInComponent } from './reservations/check-in/check-in.component';
import { NewReservationComponent } from './reservations/new-reservation/new-reservation.component';
import { ReservationsComponent } from './reservations/reservations.component';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatInputModule } from '@angular/material/input';
import {MatSlideToggleModule} from "@angular/material/slide-toggle";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NgxMaterialTimepickerModule} from "ngx-material-timepicker";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatButtonModule} from "@angular/material/button";

@NgModule({
  declarations: [
    AppComponent,
    RegisterComponent,
    MainHeaderComponent,
    CurrentReservationsComponent,
    CheckInComponent,
    NewReservationComponent,
    ReservationsComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    MatInputModule,
    MatDatepickerModule,
    FormsModule,
    MatSlideToggleModule,
    BrowserAnimationsModule,
    MatNativeDateModule,
    NgxMaterialTimepickerModule,
    MatFormFieldModule,
    MatButtonModule
  ],
  providers: [
    RegisterService,
    MatDatepickerModule

  ],
  entryComponents: [],
  schemas: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

</code>```

Body:
I was trying to make a good looking datepicker, something like in the material datepicker documentation

Datepicker I want

But I ended up with a weird looking datepicker that I can write text over and has awful styling, can anyone help with this?

My datepicker

Edit: this warning might be part of the problem?
Warning: (C://path..)\node_modules\ngx-material-timepicker_ivy_ngcc_\fesm2015\ngx-material-timepicker.js depends on 'luxon'. CommonJS or AMD
dependencies can cause optimization bailouts.

new-reservation.component.html

Create reservation here

<form [formGroup]="reservationForm" (ngSubmit)="onFormSubmit()">
  <mat-form-field>

      <input matInput>
      <ngx-timepicker-field [defaultTime]="'12:00 am'" formControlName="beginTime"></ngx-timepicker-field>

  </mat-form-field>

  <mat-form-field>

      <input matInput formControlName="endTime">
      <ngx-timepicker-field [defaultTime]="'12:00 am'" formControlName="endTime"></ngx-timepicker-field>

  </mat-form-field>

  <mat-form-field appearance="standard">
    <mat-label>Choose date</mat-label>
    <input matInput [matDatepicker]="picker" min="{{ currentDate | date: 'yyyy-MM-dd' }}" formControlName="date">
    <mat-hint>DD MM YYYY</mat-hint>
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker startView="year"></mat-datepicker>
  </mat-form-field>

  <button mat-raised-button class="btn btn-primary">Create</button>
</form>

new-reservation.component.ts

import { Component, OnInit } from '@angular/core';
import { FormBuilder } from "@angular/forms";
import { NewReservationService } from './new-reservation.service';
import { DatePipe } from '@angular/common';

@Component({
  selector: 'app-new-reservation',
  templateUrl: './new-reservation.component.html',
  styleUrls: ['./new-reservation.component.scss'],
  providers: [DatePipe]
})
export class NewReservationComponent implements OnInit {
  constructor(private formBuilder: FormBuilder, private newReservationService: NewReservationService) { }

  currentDate: any = new Date();

  ngOnInit(): void {
  }

  reservationForm = this.formBuilder.group({
    beginTime: '',
    endTime: '',
    date: '',
    checkedin: false,
    canceled: false
  });
  onFormSubmit() {
    this.newReservationService.saveStudent(this.reservationForm.value);
    this.reservationForm.reset();
  }

}

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class NewReservationService {
  saveStudent(reservation) {
    console.log(JSON.stringify(reservation));
  }
}

app-module.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import {RegisterComponent} from "./register/register.component";
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
import {RegisterService} from "./register/register.service";
import {HttpClientModule} from "@angular/common/http";
import { MainHeaderComponent } from './main-header/main-header.component';
import { CurrentReservationsComponent } from './reservations/current-reservations/current-reservations.component';
import { CheckInComponent } from './reservations/check-in/check-in.component';
import { NewReservationComponent } from './reservations/new-reservation/new-reservation.component';
import { ReservationsComponent } from './reservations/reservations.component';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatNativeDateModule } from '@angular/material/core';
import { MatInputModule } from '@angular/material/input';
import {MatSlideToggleModule} from "@angular/material/slide-toggle";
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import {NgxMaterialTimepickerModule} from "ngx-material-timepicker";
import {MatFormFieldModule} from "@angular/material/form-field";
import {MatButtonModule} from "@angular/material/button";

@NgModule({
  declarations: [
    AppComponent,
    RegisterComponent,
    MainHeaderComponent,
    CurrentReservationsComponent,
    CheckInComponent,
    NewReservationComponent,
    ReservationsComponent,
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    ReactiveFormsModule,
    HttpClientModule,
    MatInputModule,
    MatDatepickerModule,
    FormsModule,
    MatSlideToggleModule,
    BrowserAnimationsModule,
    MatNativeDateModule,
    NgxMaterialTimepickerModule,
    MatFormFieldModule,
    MatButtonModule
  ],
  providers: [
    RegisterService,
    MatDatepickerModule

  ],
  entryComponents: [],
  schemas: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


问:
How to show Swipe transition with tkinter?
I'm creating a project where the Swipe transition between two images. I'm using the tkinter library and I'm stuck.

Šobrīd fragments:

```<code>import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
image1 = Image.open('name.jpg')
image2 = Image.open('name2.jpg')

width = min(image1.width, image2.width)
height = min(image1.height, image2.height)

image1 = image1.resize((width, height),Image.ANTIALIAS)
image2 = image2.resize((width, height),Image.ANTIALIAS)

def Swipe(image1, image2, end):
    new_image = Image.new('RGB', (image1.width, image1.height), color='white')
    for y in range(image1.height):
        for x in range(image1.width):
            if y <= end: new_image[x][y] = image1[x][y]
            else: new_image[x][y] = image2[x][y]

    return new_image

for i in range(image1.height):
    got = Swipe(image1, image2, i)
</code>```

But I get a error /'Image' object is not subscriptable/ And how do I realize this transition in the root window? Maybe someone could help?

Body:
I'm creating a project where the Swipe transition between two images. I'm using the tkinter library and I'm stuck.

Šobrīd fragments:

import tkinter as tk
from PIL import ImageTk, Image
root = tk.Tk()
image1 = Image.open('name.jpg')
image2 = Image.open('name2.jpg')

width = min(image1.width, image2.width)
height = min(image1.height, image2.height)

image1 = image1.resize((width, height),Image.ANTIALIAS)
image2 = image2.resize((width, height),Image.ANTIALIAS)

def Swipe(image1, image2, end):
    new_image = Image.new('RGB', (image1.width, image1.height), color='white')
    for y in range(image1.height):
        for x in range(image1.width):
            if y <= end: new_image[x][y] = image1[x][y]
            else: new_image[x][y] = image2[x][y]

    return new_image

for i in range(image1.height):
    got = Swipe(image1, image2, i)

But I get a error /'Image' object is not subscriptable/ And how do I realize this transition in the root window? Maybe someone could help?


问:
Monodevelop referces (Gtk etc.)
I have started simple C# GUI program using Monodevelop at Ubuntu 18 (GTK-based), to open files, show graphics etc. Now that I updated to Ubuntu 22, I planned to continue, but I for my project I have most references on gray with (X): "Assembly not found for framework .NET Framework 4.6.1" (gtk-sharp, atk-sharp, gdk-shart, glade-sharp, gtk-dotnet, pango-sharp).
Original code start with "using Gtk;", which is not found.

I hope to update the code for latest supported versions GTK. ChatGPT advice me to run

sudo apt install monodevelop gtk-sharp2
but that did not solve it.
Where to find & how to install GTK for C# programming with Monodevelop on Ubuntu 22? Is there a simple installer?

Thanks in advance.

Tried sudo apt install monodevelop gtk-sharp2

Title: Monodevelop referces (Gtk etc.)


问:
VueRouter - scrollbehavior to hash
I'm using vueRouter on the site, but I ran into a problem. If I want to click between hashes, scrollBehavior doesn't work for me.

if you click on the Bio page on "noubtest.com" and try to go to "services" only the url will change but you won't get to the correct section in the Bio.

https://noubtest.com/home -> https://noubtest.com/home#fifthPage

Navigation

```<code> <router-link v-show="!mobile" class="link bio" :to="{ name: 'Home', hash: '#firstPage' }">Bio</router-link>
    <router-link v-show="!mobile" class="link link2" :to="{ name: 'Home', hash: '#fifthPage' }">Services</router-link>
</code>```

Router - index.js

```<code>import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [

  {
    path: "/home",
    name: "Home",
    component: Home,
    meta: {
      title: "Bio",
      requiresAuth: false,
    },
  },

const router = new VueRouter({

mode: "history",

  routes,
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
});
</code>```

I'm a newbie, could you please guide me on how to fix this? so that I can move between sections on one page using the menu?

I also use the fullpage.js module on the website (but it probably won't be a problem)

Title: VueRouter - scrollbehavior to hash

Body:
I'm using vueRouter on the site, but I ran into a problem. If I want to click between hashes, scrollBehavior doesn't work for me.

if you click on the Bio page on "noubtest.com" and try to go to "services" only the url will change but you won't get to the correct section in the Bio.

https://noubtest.com/home -> https://noubtest.com/home#fifthPage

Navigation

 <router-link v-show="!mobile" class="link bio" :to="{ name: 'Home', hash: '#firstPage' }">Bio</router-link>
    <router-link v-show="!mobile" class="link link2" :to="{ name: 'Home', hash: '#fifthPage' }">Services</router-link>

Router - index.js

import VueRouter from "vue-router";

Vue.use(VueRouter);

const routes = [

  {
    path: "/home",
    name: "Home",
    component: Home,
    meta: {
      title: "Bio",
      requiresAuth: false,
    },
  },

const router = new VueRouter({

mode: "history",

  routes,
  scrollBehavior() {
    return { x: 0, y: 0 };
  },
});

I'm a newbie, could you please guide me on how to fix this? so that I can move between sections on one page using the menu?

I also use the fullpage.js module on the website (but it probably won't be a problem)


问:
In Anki app a setTimeout function from the back of the previous card is being executed on the front of the next card. How to prevent it from hapening?
My question is related to the Anki app and the way JavaScript works in it.

I'm trying to create a card design of my own. On the back of a card, there will be 6 audio files and I want them to sound in a specific order. The first played audio will be the first one from the list, but the second played audio should be random from the 5 left ones.
As Anki doesn't support the  play() and onended() methods for audio files I have to use the click() and setTimeout() functions respectively in order to manually control the playback of the audios.

A problem occurs when I use the setTimeout() function. There should be a two-second delay after which the second audio has to be played. But if I press Good and switch to the next card before this 2 seconds has elapsed, that setTimeout function from the back of the previous card will be executed on the front of the next card. So, the audio from the back of the card will be played on the front of the next card.
Is there any way to prevent it from happening?

Here is the simplified card design:

Front:

{{Front}}
```
<p>Back:</p>
<pre class="lang-html prettyprint-override"><code>{{Audio 1}}
{{Audio 2}}

<script>
  {

    const audios = document.querySelectorAll(".soundLink");
    audios[0].click();

    setTimeout(() => {
      audios[1].click()
    }, 2000)

  }
</script>
</code>```

Here is a deck with the card design itself: https://gofile.io/d/OxbDrv

PS: The "Don't play audio automatically" option should be enabled in the deck settings.

I tried putting a clearTimeout() function on the front of the card but it didn't help.

Front:

```<code>{{Front}}

<script>
{
  clearTimeout(timer);
}
</script>
</code>```

Back:

```<code>{{Audio 1}}
{{Audio 2}}

<script>
{
  const audios = document.querySelectorAll(".soundLink");
  audios[0].click();
  let timer = setTimeout(()=>{audios[1].click()}, 2000)
}
</script>
</code>```

Body:
My question is related to the Anki app and the way JavaScript works in it.

I'm trying to create a card design of my own. On the back of a card, there will be 6 audio files and I want them to sound in a specific order. The first played audio will be the first one from the list, but the second played audio should be random from the 5 left ones.
As Anki doesn't support the  play() and onended() methods for audio files I have to use the click() and setTimeout() functions respectively in order to manually control the playback of the audios.

A problem occurs when I use the setTimeout() function. There should be a two-second delay after which the second audio has to be played. But if I press Good and switch to the next card before this 2 seconds has elapsed, that setTimeout function from the back of the previous card will be executed on the front of the next card. So, the audio from the back of the card will be played on the front of the next card.
Is there any way to prevent it from happening?

Here is the simplified card design:

Front:

{{Front}}

Back:

{{Audio 1}}
{{Audio 2}}

Here is a deck with the card design itself: https://gofile.io/d/OxbDrv

PS: The "Don't play audio automatically" option should be enabled in the deck settings.

I tried putting a clearTimeout() function on the front of the card but it didn't help.

Front:

{{Front}}

Back:

{{Audio 1}}
{{Audio 2}}


问:
React Routes not correctly rendering components
I have a very simple react app going right now. I am trying to add a static navigation bar that renders different components when links are clicked. The routes are set up in the App.jsx component, and all the links are within the Navigation.jsx component. When I click the links, the url changes but does not render any component. If I change the closing Navigation route tag to not wrap all of my routes, it works, but does not render the nav bar each component.

I would like to have the navbar constantly rendered, and the components change with each link click.

This is my App component right now.

```<code>function App() {
  return (
    <div>
      <Routes>
        <Route path='/' element={<Navigation />} >
          <Route index element={<Home />} />
          <Route path='projects' element={<Projects />} />
          <Route path='resume' element={<Resume />} />
        </Route>
      </Routes>
    </div>
  );
}

export default App;
</code>```

And this is my Navigation

```<code>export default function Navigation() {
  const [burgerClass, setBurgerClass] = useState('burger-bar unclicked');
  const [menuClass, setMenuClass] = useState('menu hidden');
  const [isMenuClicked, setIsMenuClicked] = useState(false);

  const updateMenu = () => {
    if (!isMenuClicked) {
      setBurgerClass('burger-bar clicked');
      setMenuClass('menu visable');
    } else {
      setBurgerClass('burger-bar unclicked');
      setMenuClass('menu hidden');
    }
    setIsMenuClicked(!isMenuClicked);
  }

  return (
    <div className='navigation'>
      <nav>
        <div className='burger-menu' onClick={updateMenu}>
          <div className={burgerClass}></div>
          <div className={burgerClass}></div>
          <div className={burgerClass}></div>
        </div>
        <Link className='logo-container' to='/'>
          <h1>JESSE GOODRUM</h1>
        </Link>

        <div className='social-media-links-container'>
          <a href='http://www.linkedin.com/in/jessegoodrum/'>
            <i className="fa-brands fa-linkedin"></i>
          </a>
          <a href='https://github.com/jessegoodrum/'>
            <i className="fa-brands fa-github"></i>
          </a>
        </div>
      </nav>

      <div className={menuClass}>
        <ul>
          <li>
            <Link className='nav-link' to ='/projects'>PROJECTS</Link>
          </li>
          <li>
            <Link className='nav-link' to='/resume'>RESUME</Link>
          </li>
        </ul>
      </div>
    </div>
  )
}
</code>```

Body:
I have a very simple react app going right now. I am trying to add a static navigation bar that renders different components when links are clicked. The routes are set up in the App.jsx component, and all the links are within the Navigation.jsx component. When I click the links, the url changes but does not render any component. If I change the closing Navigation route tag to not wrap all of my routes, it works, but does not render the nav bar each component.

I would like to have the navbar constantly rendered, and the components change with each link click.

This is my App component right now.

function App() {
  return (

      <Routes>
        <Route path='/' element={<Navigation />} >
          <Route index element={<Home />} />
          <Route path='projects' element={<Projects />} />
          <Route path='resume' element={<Resume />} />
        </Route>
      </Routes>

  );
}

export default App;

And this is my Navigation

export default function Navigation() {
  const [burgerClass, setBurgerClass] = useState('burger-bar unclicked');
  const [menuClass, setMenuClass] = useState('menu hidden');
  const [isMenuClicked, setIsMenuClicked] = useState(false);

  const updateMenu = () => {
    if (!isMenuClicked) {
      setBurgerClass('burger-bar clicked');
      setMenuClass('menu visable');
    } else {
      setBurgerClass('burger-bar unclicked');
      setMenuClass('menu hidden');
    }
    setIsMenuClicked(!isMenuClicked);
  }

  return (

        <Link className='logo-container' to='/'>

JESSE GOODRUM

        </Link>

            <Link className='nav-link' to ='/projects'>PROJECTS</Link>

            <Link className='nav-link' to='/resume'>RESUME</Link>

  )
}


问:
cornerRadius does not apply to swipeActions in List rows
I have a list like this:

List {
    ForEach(litters, id: \.id) { litter in
        LitterView(litter: litter)
            .confirmationDialog("Are you sure that you want to delete " + litter.name + " ?",
                                isPresented: $showingLitterDeletionConfirmation,
                                titleVisibility: .visible) {
                Button("Delete " + litter.name, role: .destructive) {
                    deleteLitter(id: litter.id)
                    litters = getAllLitters()
                }
                Button("Annuler", role: .cancel) {}
            }
            .swipeActions(edge:.leading) {
                Button(action: {
                    showingLitterDeletionConfirmation = true
                }) {
                    Image(systemName: "minus.circle")
                }
                .tint(.red)
            }
            .swipeActions(edge:.trailing) {
                Button(action: {
                    litter.clean()
                    litters = getAllLitters()
                }) {
                    Image(systemName: "paintbrush")
                }
                .tint(.green)
            }
            .listRowInsets(EdgeInsets())
            .listRowSeparator(.hidden)
            .cornerRadius(20)
        }
    }
.scrollContentBackground(.hidden)
}
```

I added a cornerRadius(20) to the LitterView. It applies correctly to the main content of the list row, but if I swipe to show my swipeActions, the corner radius follows the content, and does not apply to the swipe action:

Here is the target I am looking for:

Body:
I have a list like this:

List {
    ForEach(litters, id: \.id) { litter in
        LitterView(litter: litter)
            .confirmationDialog("Are you sure that you want to delete " + litter.name + " ?",
                                isPresented: $showingLitterDeletionConfirmation,
                                titleVisibility: .visible) {
                Button("Delete " + litter.name, role: .destructive) {
                    deleteLitter(id: litter.id)
                    litters = getAllLitters()
                }
                Button("Annuler", role: .cancel) {}
            }
            .swipeActions(edge:.leading) {
                Button(action: {
                    showingLitterDeletionConfirmation = true
                }) {
                    Image(systemName: "minus.circle")
                }
                .tint(.red)
            }
            .swipeActions(edge:.trailing) {
                Button(action: {
                    litter.clean()
                    litters = getAllLitters()
                }) {
                    Image(systemName: "paintbrush")
                }
                .tint(.green)
            }
            .listRowInsets(EdgeInsets())
            .listRowSeparator(.hidden)
            .cornerRadius(20)
        }
    }
.scrollContentBackground(.hidden)
}

I added a cornerRadius(20) to the LitterView. It applies correctly to the main content of the list row, but if I swipe to show my swipeActions, the corner radius follows the content, and does not apply to the swipe action:

Here is the target I am looking for:


问:
SQLiteCPP undefined reference to sqlite3_libversion with -lsqlite3
I've compiled SQLiteCPP with no errors.
Steps: clone SQLiteCPP, build.sh, cd build, make, make all, sudo make install

I've verified that the files have copied to
/usr/local/include

I'm including it all in my task.json:

```<code>{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-fsanitize=address",
                "-I/usr/local/include/",
                "-I/usr/local/lib/wx/include/gtk3-unicode-3.2",
                 "-I/usr/local/include/wx-3.2",
                 "-D_FILE_OFFSET_BITS=64",
                  "-DWXUSINGDLL",
                  "-D__WXGTK__",
                  "-pthread",
                "-g3",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-L/usr/local/lib",
                "-pthread",
                "-lwx_gtk3u_xrc-3.2",
                "-lwx_gtk3u_html-3.2",
                "-lwx_gtk3u_qa-3.2",
                "-lwx_gtk3u_core-3.2",
                "-lwx_baseu_xml-3.2",
                "-lwx_baseu_net-3.2",
                "-lwx_baseu-3.2",
                "-lsqlite3",
                "-lSQLiteCpp"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}
</code>```

The output of compile:

```<code>Starting build...
/usr/bin/g++ -fdiagnostics-color=always -fsanitize=address -I/usr/local/include/ -I/usr/local/lib/wx/include/gtk3-unicode-3.2 -I/usr/local/include/wx-3.2 -D_FILE_OFFSET_BITS=64 -DWXUSINGDLL -D__WXGTK__ -pthread -g3 /home/me/src/no_cmake/src/main.cpp -o /home/me/src/no_cmake/src/main -L/usr/local/lib -pthread -lwx_gtk3u_xrc-3.2 -lwx_gtk3u_html-3.2 -lwx_gtk3u_qa-3.2 -lwx_gtk3u_core-3.2 -lwx_baseu_xml-3.2 -lwx_baseu_net-3.2 -lwx_baseu-3.2 -lsqlite3 -lSQLiteCpp
/usr/bin/ld: /usr/local/lib/libSQLiteCpp.a(Database.cpp.o): in function `SQLite::getLibVersion()':
/home/me/src/SQLiteCpp/src/Database.cpp:52: undefined reference to `sqlite3_libversion'
/usr/bin/ld: /usr/local/lib/libSQLiteCpp.a(Database.cpp.o): in function `SQLite::getLibVersionNumber()':
/home/me/src/SQLiteCpp/src/Database.cpp:58: undefined reference to `sqlite3_libversion_number'
</code>```

It looks like I'm linking everything correctly? But I'm new to C++ so...

edit:
On SQLiteCPP's git, I see this in the cmake file:
set(SQLITECPP_RUN_CPPCHECK OFF CACHE BOOL "" FORCE)
set(SQLITECPP_RUN_CPPLINT OFF CACHE BOOL "" FORCE)
set(SQLITECPP_USE_STATIC_RUNTIME OFF CACHE BOOL "" FORCE)

Do I somehow need to set that during compile? I wasn't sure how and trying not to use cmake for this.

Body:
I've compiled SQLiteCPP with no errors.
Steps: clone SQLiteCPP, build.sh, cd build, make, make all, sudo make install

I've verified that the files have copied to
/usr/local/include

I'm including it all in my task.json:

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++ build active file",
            "command": "/usr/bin/g++",
            "args": [
                "-fdiagnostics-color=always",
                "-fsanitize=address",
                "-I/usr/local/include/",
                "-I/usr/local/lib/wx/include/gtk3-unicode-3.2",
                 "-I/usr/local/include/wx-3.2",
                 "-D_FILE_OFFSET_BITS=64",
                  "-DWXUSINGDLL",
                  "-D__WXGTK__",
                  "-pthread",
                "-g3",
                "${file}",
                "-o",
                "${fileDirname}/${fileBasenameNoExtension}",
                "-L/usr/local/lib",
                "-pthread",
                "-lwx_gtk3u_xrc-3.2",
                "-lwx_gtk3u_html-3.2",
                "-lwx_gtk3u_qa-3.2",
                "-lwx_gtk3u_core-3.2",
                "-lwx_baseu_xml-3.2",
                "-lwx_baseu_net-3.2",
                "-lwx_baseu-3.2",
                "-lsqlite3",
                "-lSQLiteCpp"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

The output of compile:

Starting build...
/usr/bin/g++ -fdiagnostics-color=always -fsanitize=address -I/usr/local/include/ -I/usr/local/lib/wx/include/gtk3-unicode-3.2 -I/usr/local/include/wx-3.2 -D_FILE_OFFSET_BITS=64 -DWXUSINGDLL -D__WXGTK__ -pthread -g3 /home/me/src/no_cmake/src/main.cpp -o /home/me/src/no_cmake/src/main -L/usr/local/lib -pthread -lwx_gtk3u_xrc-3.2 -lwx_gtk3u_html-3.2 -lwx_gtk3u_qa-3.2 -lwx_gtk3u_core-3.2 -lwx_baseu_xml-3.2 -lwx_baseu_net-3.2 -lwx_baseu-3.2 -lsqlite3 -lSQLiteCpp
/usr/bin/ld: /usr/local/lib/libSQLiteCpp.a(Database.cpp.o): in function `SQLite::getLibVersion()':
/home/me/src/SQLiteCpp/src/Database.cpp:52: undefined reference to `sqlite3_libversion'
/usr/bin/ld: /usr/local/lib/libSQLiteCpp.a(Database.cpp.o): in function `SQLite::getLibVersionNumber()':
/home/me/src/SQLiteCpp/src/Database.cpp:58: undefined reference to `sqlite3_libversion_number'

It looks like I'm linking everything correctly? But I'm new to C++ so...

edit:
On SQLiteCPP's git, I see this in the cmake file:
set(SQLITECPP_RUN_CPPCHECK OFF CACHE BOOL "" FORCE)
set(SQLITECPP_RUN_CPPLINT OFF CACHE BOOL "" FORCE)
set(SQLITECPP_USE_STATIC_RUNTIME OFF CACHE BOOL "" FORCE)

Do I somehow need to set that during compile? I wasn't sure how and trying not to use cmake for this.


问:
The column name <> was not found in this ResultSet
I have an entity class in hibernate + JPA that extends a base class. But I am getting the issue while fetching the extending class column. Detail provided below.

Base class:

```<code>@Getter
@MappedSuperclass
public abstract class BaseEntity {

    @Column(name = "CREATED_BY", length = 8, updatable = false)
    private String createdBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATION_DATE", updatable = false)
    private Date creationDate;

    @Column(name = "LAST_UPDATED_BY", length = 8, updatable = false)
    private String lastUpdatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "LAST_UPDATED_DATE", updatable = false)
    private Date lastUpdatedDate;
}
</code>```

User Entity Class:

```<code>public class UserClassEntity extends BaseClass {

   @Id
    @SequenceGenerator(name = "binary_seq", sequenceName = "binary_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "binary_seq")
    @Column(name = "binary_id")
    private Long id;

    @Column(name = "display_name")
    private String displayName;
}
</code>```

When I try to get the id, I get this exception:

The column name CREATED_BY was not found in this ResultSet

This is the SQL query that I am using:

```<code>EntityManager entityManager = entityManagerProvider.get();

sql = String.format("Select p.id from UserClassEntity p Order by p.CREATION_DATE")

entityManager.createNativeQuery(sql, BetaProgramTesterEntity.class);
....
....
query.getResultList();
</code>```

Any help? What I am missing here?

Body:
I have an entity class in hibernate + JPA that extends a base class. But I am getting the issue while fetching the extending class column. Detail provided below.

Base class:

@Getter
@MappedSuperclass
public abstract class BaseEntity {

    @Column(name = "CREATED_BY", length = 8, updatable = false)
    private String createdBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "CREATION_DATE", updatable = false)
    private Date creationDate;

    @Column(name = "LAST_UPDATED_BY", length = 8, updatable = false)
    private String lastUpdatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "LAST_UPDATED_DATE", updatable = false)
    private Date lastUpdatedDate;
}

User Entity Class:

public class UserClassEntity extends BaseClass {

   @Id
    @SequenceGenerator(name = "binary_seq", sequenceName = "binary_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "binary_seq")
    @Column(name = "binary_id")
    private Long id;

    @Column(name = "display_name")
    private String displayName;
}

When I try to get the id, I get this exception:

The column name CREATED_BY was not found in this ResultSet

This is the SQL query that I am using:

EntityManager entityManager = entityManagerProvider.get();

sql = String.format("Select p.id from UserClassEntity p Order by p.CREATION_DATE")

entityManager.createNativeQuery(sql, BetaProgramTesterEntity.class);
....
....
query.getResultList();

Any help? What I am missing here?


问:
How to add Sitefinity CLI path arguments to Visual Studio?
I'm trying to add the Sitefinity CLI tool to my Visual Studio Environment Variables (Tools > Options > Environment > Terminal > Arguments) . One thing I'm being asked for is the Arguments.

Github Project: https://github.com/Sitefinity/Sitefinity-CLI

I don't know where to get these arguments from.


问:
Telepresence.io cannot intercept a Nginx service running on Docker on my MacOs laptop
I installed telepresence by using the curl command on a Kind cluster on my Mac M1 laptop. I can correctly interact with other services deployed in the cluster and I can list some interceptable services when I use telepresence list but I cannot intercept any of them.

Steps to reproduce the behavior:

I start a Nginx service with the following manifest. I have created a docker image gsantoro/my-nginx:latest which is a modified version of Nginx just to expose port 3000 instead of 80

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  nginx
  labels:
    app:  nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template:
    metadata:
      labels:
        app:  nginx
    spec:
      containers:
      - name:  nginx
        image: gsantoro/my-nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: default
spec:
  selector:
    app: nginx
  type: ClusterIP
  ports:
  - protocol: TCP
    port: 3000
```
<ol start="2">
<li>When I run 'telepresence intercept my-nginx --port 3000`</li>
<li>I see the following errors</li>
</ol>
<pre class="lang-bash prettyprint-override"><code>failed to clear chain TEL_INBOUND_TCP: running [/sbin/iptables -t nat -N TEL_INBOUND_TCP --wait]: exit status 3: iptables v1.8.7 (legacy): can't initialize iptables table `nat': iptables who? (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.

Stream closed EOF for default/my-nginx-6c4489594c-pws84 (tel-agent-init)
</code>```

Output of telepresence version

❯ telepresence version
Enhanced Client: v2.9.4
Root Daemon    : v2.9.4
User Daemon    : v2.9.4
Traffic Manager: v2.9.4
```
<ul>
<li>Operating system of the workstation running <code>telepresence</code> commands. MacOs version v12.6.1, Apple M1 Max chipset</li>
</ul>
<pre class="lang-bash prettyprint-override"><code>➜ docker version
Client:
 Cloud integration: v1.0.29
 Version:           20.10.21
 API version:       1.41
 Go version:        go1.18.7
 Git commit:        baeda1f
 Built:             Tue Oct 25 18:01:18 2022
 OS/Arch:           darwin/arm64
 Context:           default
 Experimental:      true

Server: Docker Desktop 4.14.1 (91661)
 Engine:
  Version:          20.10.21
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.18.7
  Git commit:       3056208
  Built:            Tue Oct 25 17:59:41 2022
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.6.9
  GitCommit:        1c90a442489720eec95342e1789ee8a5e1b9536f
 runc:
  Version:          1.1.4
  GitCommit:        v1.1.4-0-g5fd4c4d
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0
</code>```

Kubernetes environment and version

➜ kubectl version
Client Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.4", GitCommit:"872a965c6c6526caa949f0c6ac028ef7aff3fb78", GitTreeState:"clean", BuildDate:"2022-11-09T13:28:30Z", GoVersion:"go1.19.3", Compiler:"gc", Platform:"darwin/arm64"}
Kustomize Version: v4.5.7
Server Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.3", GitCommit:"434bfd82814af038ad94d62ebe59b133fcb50506", GitTreeState:"clean", BuildDate:"2022-11-02T03:24:50Z", GoVersion:"go1.19.2", Compiler:"gc", Platform:"linux/arm64"}
```

Is there a way to upgrade the version of IpTable in the docker engine?

Body:
I installed telepresence by using the curl command on a Kind cluster on my Mac M1 laptop. I can correctly interact with other services deployed in the cluster and I can list some interceptable services when I use telepresence list but I cannot intercept any of them.

Steps to reproduce the behavior:

I start a Nginx service with the following manifest. I have created a docker image gsantoro/my-nginx:latest which is a modified version of Nginx just to expose port 3000 instead of 80

apiVersion: apps/v1
kind: Deployment
metadata:
  name:  nginx
  labels:
    app:  nginx
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 1
  template:
    metadata:
      labels:
        app:  nginx
    spec:
      containers:
      - name:  nginx
        image: gsantoro/my-nginx:latest
        imagePullPolicy: Always
        ports:
        - containerPort: 3000
---
apiVersion: v1
kind: Service
metadata:
  name: nginx
  namespace: default
spec:
  selector:
    app: nginx
  type: ClusterIP
  ports:
  - protocol: TCP
    port: 3000

When I run 'telepresence intercept my-nginx --port 3000`

I see the following errors

failed to clear chain TEL_INBOUND_TCP: running [/sbin/iptables -t nat -N TEL_INBOUND_TCP --wait]: exit status 3: iptables v1.8.7 (legacy): can't initialize iptables table `nat': iptables who? (do you need to insmod?)
Perhaps iptables or your kernel needs to be upgraded.

Stream closed EOF for default/my-nginx-6c4489594c-pws84 (tel-agent-init)

Output of telepresence version

❯ telepresence version
Enhanced Client: v2.9.4
Root Daemon    : v2.9.4
User Daemon    : v2.9.4
Traffic Manager: v2.9.4

Operating system of the workstation running telepresence commands. MacOs version v12.6.1, Apple M1 Max chipset

➜ docker version
Client:
 Cloud integration: v1.0.29
 Version:           20.10.21
 API version:       1.41
 Go version:        go1.18.7
 Git commit:        baeda1f
 Built:             Tue Oct 25 18:01:18 2022
 OS/Arch:           darwin/arm64
 Context:           default
 Experimental:      true

Server: Docker Desktop 4.14.1 (91661)
 Engine:
  Version:          20.10.21
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.18.7
  Git commit:       3056208
  Built:            Tue Oct 25 17:59:41 2022
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.6.9
  GitCommit:        1c90a442489720eec95342e1789ee8a5e1b9536f
 runc:
  Version:          1.1.4
  GitCommit:        v1.1.4-0-g5fd4c4d
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

Kubernetes environment and version

➜ kubectl version
Client Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.4", GitCommit:"872a965c6c6526caa949f0c6ac028ef7aff3fb78", GitTreeState:"clean", BuildDate:"2022-11-09T13:28:30Z", GoVersion:"go1.19.3", Compiler:"gc", Platform:"darwin/arm64"}
Kustomize Version: v4.5.7
Server Version: version.Info{Major:"1", Minor:"25", GitVersion:"v1.25.3", GitCommit:"434bfd82814af038ad94d62ebe59b133fcb50506", GitTreeState:"clean", BuildDate:"2022-11-02T03:24:50Z", GoVersion:"go1.19.2", Compiler:"gc", Platform:"linux/arm64"}

Is there a way to upgrade the version of IpTable in the docker engine?


问:
Multi-checkbox filter with AND relationship results
I am using the frameworks below for building out a multi-checkbox filter on my website. This code filters results based on an OR relationship (if has "option1" value OR "option2" value, etc. I want it to function as an AND relationship, so the only results that show would be ones that have values in all of the values selected.

var $filterCheckboxes = $('input[type="checkbox"]');
var filterFunc = function() {

  var selectedFilters = {};

  $filterCheckboxes.filter(':checked').each(function() {

    if (!selectedFilters.hasOwnProperty(this.name)) {
      selectedFilters[this.name] = [];
    }

    selectedFilters[this.name].push(this.value);
  });

  // create a collection containing all of the filterable elements
  var $filteredResults = $('.flower');

  // loop over the selected filter name -> (array) values pairs
  $.each(selectedFilters, function(name, filterValues) {

    // filter each .flower element
    $filteredResults = $filteredResults.filter(function() {

      var matched = false,
        currentFilterValues = $(this).data('category').split(' ');

      // loop over each category value in the current .flower's data-category
      $.each(currentFilterValues, function(_, currentFilterValue) {

        // if the current category exists in the selected filters array
        // set matched to true, and stop looping. as we're ORing in each
        // set of filters, we only need to match once

        if ($.inArray(currentFilterValue, filterValues) != -1) {
          matched = true;
          return false;
        }
      });

      // if matched is true the current .flower element is returned
      return matched;

    });
  });

  $('.flower').hide().filter($filteredResults).show();
}

$filterCheckboxes.on('change', filterFunc);  ```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  font-family:'Arial';
  color:#646464;
}
.continents-wrap {
  float:left;
  width:20%;
  margin:0 5% 0 0;
  padding:0;
}
.flowers-wrap {
  float:left;
  width:20%;
  margin:0 5% 0 0;
  padding:0;
  position:relative;
}
.flowers {
  float:left;
  width:50%;
}
.flowers div {
  float:left;
  width:90%;
  height:68px;
  line-height:68px;
  padding:0 5%;
  background:#eee;
  margin:0 0 1px;
  position:relative;
}   </code>```

Filter flowers by colour:

  <form>
    <input type="checkbox" name="fl-colour" value="red" id="red" /> Red

    <input type="checkbox" name="fl-colour" value="yellow" id="yellow" /> Yellow

    <input type="checkbox" name="fl-colour" value="pink" id="pink" /> Pink

    <input type="checkbox" name="fl-colour" value="purple" id="purple" /> Purple

    <input type="checkbox" name="fl-colour" value="green" id="green" /> Green

    <input type="checkbox" name="fl-colour" value="other" id="other" /> Other
  </form>

Filter flowers by size:

  <form>
    <input type="checkbox" name="fl-size" value="tiny" id="tiny" /> Tiny

    <input type="checkbox" name="fl-size" value="small" id="small" /> Small

    <input type="checkbox" name="fl-size" value="medium" id="medium" /> Medium

    <input type="checkbox" name="fl-size" value="large" id="large" /> Large

    <input type="checkbox" name="fl-size" value="giant" id="giant" /> Giant
  </form>

Filter flowers by continents:

  <form>

<input type="checkbox" name="fl-cont" value="africa" id="africa" /> Africa

<input type="checkbox" name="fl-cont" value="europe" id="europe" />
    Europe

<input type="checkbox" name="fl-cont" value="asia" id="asia" />
    Asia

<input type="checkbox" name="fl-cont" value="north-america" id="north-america" />
    North America

<input type="checkbox" name="fl-cont" value="south-america" id="south-america" />
    South America

    <input type="checkbox" name="fl-cont" value="antarctica" id="antarctica" />
    Antarctica

<input type="checkbox" name="fl-cont" value="australasia" id="australasia" />
    Australasia

  </form>

Aloe

Lavender

Stinging Nettle

Gorse

Hemp

Titan Arum

Golden Wattle

Purple Prairie Clover

Camellia

Scarlet Carnation

Indian Paintbrush

Moss Verbena

Climbing Dayflower

Antarctic Pearlwort

```
</div>
</div>
</p>
<p>There is this reference in the original notes:</p>
```        // if the current category exists in the selected filters array
        // set matched to true, and stop looping. as we're ORing in each
        // set of filters, we only need to match once

        if ($.inArray(currentFilterValue, filterValues) != -1) {
          matched = true;
          return false;
        }
```

Though I don't know how to take this information and change it to AND instead of OR.

Anyone have any tips?

Body:
I am using the frameworks below for building out a multi-checkbox filter on my website. This code filters results based on an OR relationship (if has "option1" value OR "option2" value, etc. I want it to function as an AND relationship, so the only results that show would be ones that have values in all of the values selected.

var $filterCheckboxes = $('input[type="checkbox"]');
var filterFunc = function() {

  var selectedFilters = {};

  $filterCheckboxes.filter(':checked').each(function() {

    if (!selectedFilters.hasOwnProperty(this.name)) {
      selectedFilters[this.name] = [];
    }

    selectedFilters[this.name].push(this.value);
  });

  // create a collection containing all of the filterable elements
  var $filteredResults = $('.flower');

  // loop over the selected filter name -> (array) values pairs
  $.each(selectedFilters, function(name, filterValues) {

    // filter each .flower element
    $filteredResults = $filteredResults.filter(function() {

      var matched = false,
        currentFilterValues = $(this).data('category').split(' ');

      // loop over each category value in the current .flower's data-category
      $.each(currentFilterValues, function(_, currentFilterValue) {

        // if the current category exists in the selected filters array
        // set matched to true, and stop looping. as we're ORing in each
        // set of filters, we only need to match once

        if ($.inArray(currentFilterValue, filterValues) != -1) {
          matched = true;
          return false;
        }
      });

      // if matched is true the current .flower element is returned
      return matched;

    });
  });

  $('.flower').hide().filter($filteredResults).show();
}

$filterCheckboxes.on('change', filterFunc);

body {
  font-family:'Arial';
  color:#646464;
}
.continents-wrap {
  float:left;
  width:20%;
  margin:0 5% 0 0;
  padding:0;
}
.flowers-wrap {
  float:left;
  width:20%;
  margin:0 5% 0 0;
  padding:0;
  position:relative;
}
.flowers {
  float:left;
  width:50%;
}
.flowers div {
  float:left;
  width:90%;
  height:68px;
  line-height:68px;
  padding:0 5%;
  background:#eee;
  margin:0 0 1px;
  position:relative;
}

Filter flowers by colour:

  <form>
    <input type="checkbox" name="fl-colour" value="red" id="red" /> Red

    <input type="checkbox" name="fl-colour" value="yellow" id="yellow" /> Yellow

    <input type="checkbox" name="fl-colour" value="pink" id="pink" /> Pink

    <input type="checkbox" name="fl-colour" value="purple" id="purple" /> Purple

    <input type="checkbox" name="fl-colour" value="green" id="green" /> Green

    <input type="checkbox" name="fl-colour" value="other" id="other" /> Other
  </form>

Filter flowers by size:

  <form>
    <input type="checkbox" name="fl-size" value="tiny" id="tiny" /> Tiny

    <input type="checkbox" name="fl-size" value="small" id="small" /> Small

    <input type="checkbox" name="fl-size" value="medium" id="medium" /> Medium

    <input type="checkbox" name="fl-size" value="large" id="large" /> Large

    <input type="checkbox" name="fl-size" value="giant" id="giant" /> Giant
  </form>

Filter flowers by continents:

  <form>

<input type="checkbox" name="fl-cont" value="africa" id="africa" /> Africa

<input type="checkbox" name="fl-cont" value="europe" id="europe" />
    Europe

<input type="checkbox" name="fl-cont" value="asia" id="asia" />
    Asia

<input type="checkbox" name="fl-cont" value="north-america" id="north-america" />
    North America

<input type="checkbox" name="fl-cont" value="south-america" id="south-america" />
    South America

    <input type="checkbox" name="fl-cont" value="antarctica" id="antarctica" />
    Antarctica

<input type="checkbox" name="fl-cont" value="australasia" id="australasia" />
    Australasia

  </form>

Aloe

Lavender

Stinging Nettle

Gorse

Hemp

Titan Arum

Golden Wattle

Purple Prairie Clover

Camellia

Scarlet Carnation

Indian Paintbrush

Moss Verbena

Climbing Dayflower

Antarctic Pearlwort

There is this reference in the original notes:

        // if the current category exists in the selected filters array
        // set matched to true, and stop looping. as we're ORing in each
        // set of filters, we only need to match once

        if ($.inArray(currentFilterValue, filterValues) != -1) {
          matched = true;
          return false;
        }

Though I don't know how to take this information and change it to AND instead of OR.

Anyone have any tips?


问:
Black image instead of mine when I share it
Below is part of my code, in general it works, but not for everything. If I choose to send by email or to notes, then everything is fine. But if I want to send via messenger, then instead of the desired image, a black image.

```<code>private fun share() {

val bitmap = resultLayout.drawToBitmap()

val filePath = File(cacheDir, "ratings")

var uriToImage: Uri? = null
try {
    if(!filePath.exists()) {
        filePath.mkdirs()
    }
    val file = File(filePath, "$nameOfRating.png")
    val stream = FileOutputStream(file)
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)

    stream.flush()
    stream.close()
    uriToImage = FileProvider.getUriForFile(this, "com.example.ratings.fileprovider", file)
    val intent = Intent(Intent.ACTION_SEND)
    intent.type = "image/png"
    intent.putExtra(Intent.EXTRA_STREAM, uriToImage)
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    startActivity(Intent.createChooser(intent, null))

} catch (e: Exception) {
    e.printStackTrace()
    Toast.makeText(applicationContext, "Fail to share PNG file..$e", Toast.LENGTH_LONG)
        .show()
    Log.d(TAG, "Exception: $e")
    }
}
</code>```

If anyone knows what this might be, please advise.

Body:
Below is part of my code, in general it works, but not for everything. If I choose to send by email or to notes, then everything is fine. But if I want to send via messenger, then instead of the desired image, a black image.

private fun share() {

val bitmap = resultLayout.drawToBitmap()

val filePath = File(cacheDir, "ratings")

var uriToImage: Uri? = null
try {
    if(!filePath.exists()) {
        filePath.mkdirs()
    }
    val file = File(filePath, "$nameOfRating.png")
    val stream = FileOutputStream(file)
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream)

    stream.flush()
    stream.close()
    uriToImage = FileProvider.getUriForFile(this, "com.example.ratings.fileprovider", file)
    val intent = Intent(Intent.ACTION_SEND)
    intent.type = "image/png"
    intent.putExtra(Intent.EXTRA_STREAM, uriToImage)
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
    startActivity(Intent.createChooser(intent, null))

} catch (e: Exception) {
    e.printStackTrace()
    Toast.makeText(applicationContext, "Fail to share PNG file..$e", Toast.LENGTH_LONG)
        .show()
    Log.d(TAG, "Exception: $e")
    }
}

If anyone knows what this might be, please advise.


问:
Jenkins rewrites its uri with path, specified in kubernetes ingress rule
Kind cluster with nginx ingress, 80 443 ports are extramapped. For deploying Jenkins yaml files from official tutorial where used, except from service type - i use ClusterIP k8s service. Ingress rule applies for service and Jenkins makes uri substituion, so resulted uri isn' found (404)
uri substitution
ingress rule i apply

"/" ingress rule path leads to this "login?from=%2F"

"admin" ingress rule path leads to "login?from=%2Fadmin", but it's still 404 !!!

```<code>resources: {}
env:
- name: JENKINS_OPTS
  value: --prefix=/jenkins
</code>```

this part ^ in deployment doesn't help neither
old articles about ingress rules for Jenkins read, and rules from these articles are simple but old (without pathType), doesn't work now

```<code>  annotations:
    nginx.ingress.kubernetes.io/app-root: /
    nginx.ingress.kubernetes.io/rewrite-target: /$2
</code>```

this part ^ leads to http://diploma/login?from=%2F - and still 404

curl says it's HTTP/1.1 403 Forbidden - X-Content-Type-Options: nosniff
Set-Cookie: JSESSIONID.5c694702=node0vvv1jgg0mr5w1c63m7fciri1e217.node0; Path=/; HttpOnly

Any ideas ?

Body:
Kind cluster with nginx ingress, 80 443 ports are extramapped. For deploying Jenkins yaml files from official tutorial where used, except from service type - i use ClusterIP k8s service. Ingress rule applies for service and Jenkins makes uri substituion, so resulted uri isn' found (404)
uri substitution
ingress rule i apply

"/" ingress rule path leads to this "login?from=%2F"

"admin" ingress rule path leads to "login?from=%2Fadmin", but it's still 404 !!!

resources: {}
env:
- name: JENKINS_OPTS
  value: --prefix=/jenkins

this part ^ in deployment doesn't help neither
old articles about ingress rules for Jenkins read, and rules from these articles are simple but old (without pathType), doesn't work now

  annotations:
    nginx.ingress.kubernetes.io/app-root: /
    nginx.ingress.kubernetes.io/rewrite-target: /$2

this part ^ leads to http://diploma/login?from=%2F - and still 404

curl says it's HTTP/1.1 403 Forbidden - X-Content-Type-Options: nosniff
Set-Cookie: JSESSIONID.5c694702=node0vvv1jgg0mr5w1c63m7fciri1e217.node0; Path=/; HttpOnly

Any ideas ?


问:
How can i develop android application that pulls bluetooth data of surrounding devices React-Native
With React-Native, I want to see the bluetooth signals and signal data emitted by the surrounding ibeacon devices. The data I need (macadress,rssi,major,minor,tx_power,uuid).

I want to take this data and keep it in an array and accordingly I want to compare it with other ready-made arrays. Accordingly, we will develop an application where we can give directions.

I don't know anything about React-Native and android. How can I develop such an android project using react-native?

Can you recommend up-to-date packages that work?


问:
Esp server socket disconnected
Hy guys I´m trying to send a message from my phone in a server ESP32 but any app tcp connection that I try returns me disconnected. Im doing somehing wrong? my code is missing something... I don´t know

```<code>#include <Arduino.h>
#include <WiFi.h>
#include "NetManager.hpp"

constexpr char SSID[] = "ESP32Server";
constexpr char PASSWORD[] = "12345678";
constexpr int SERVER_PORT = 80;

NetManager netManager(SERVER_PORT, SSID, PASSWORD);

int temperature = 24;

void handleCommandReceive(int command)
{
  temperature = command;
}

int handleCommandSend()
{
  return temperature;
}

void setup()
{
  Serial.begin(115200);

  netManager.setup(handleCommandReceive, handleCommandSend);
}

void loop()
{
  netManager.loop();

  delay(10);
}
</code>```

Complete code
https://github.com/ProjetosESP32/air-esp

I tried in Flutter too with a socket package but i got same error

Title: Esp server socket disconnected

Body:
Hy guys I´m trying to send a message from my phone in a server ESP32 but any app tcp connection that I try returns me disconnected. Im doing somehing wrong? my code is missing something... I don´t know

#include <Arduino.h>
#include <WiFi.h>
#include "NetManager.hpp"

constexpr char SSID[] = "ESP32Server";
constexpr char PASSWORD[] = "12345678";
constexpr int SERVER_PORT = 80;

NetManager netManager(SERVER_PORT, SSID, PASSWORD);

int temperature = 24;

void handleCommandReceive(int command)
{
  temperature = command;
}

int handleCommandSend()
{
  return temperature;
}

void setup()
{
  Serial.begin(115200);

  netManager.setup(handleCommandReceive, handleCommandSend);
}

void loop()
{
  netManager.loop();

  delay(10);
}

Complete code
https://github.com/ProjetosESP32/air-esp

I tried in Flutter too with a socket package but i got same error


问:
Python unittests one by one works well but not together under Flask
I've a test file containing some unittests. All of them looks like:

```<code>def test_something_222(self):
    with app.test_client() as c:
        response = c.get(URL)
        assert response.status_code == some_value
</code>```

. When I run them one by one, everything works well, however using python -m unittest results error.

What can be the reason for it, and how can I prevent?

Thanks.

Body:
I've a test file containing some unittests. All of them looks like:

def test_something_222(self):
    with app.test_client() as c:
        response = c.get(URL)
        assert response.status_code == some_value

. When I run them one by one, everything works well, however using python -m unittest results error.

What can be the reason for it, and how can I prevent?

Thanks.


问:
spying and mocking a function from another function is ignored in jest
I have a module exporting the object of two methods:

start()

doSomeCheckings()

When start() is called, it calls a doSomeCheckings(). I would like to test that doSomeCheckings() function has been called and eventually returned a mocked value.

I followed up a jest documentation and some duplicated questions here on SO, but it still does not work as I wish. I don't get it what am I missing here ?

Here is the full jest online playground link

```<code>// module.js
function start () {
  doSomeCheckings()

  console.log('app started')
}

function doSomeCheckings () {
  console.log('checking')
}

module.exports = { start, doSomeCheckings }
</code>```

And here is a jest test file:

```<code>it('should do some checkings on app start', () => {
  // Given
  const Module = require('./module')

  const spy = jest.spyOn(Module, 'doSomeCheckings')
  spy.mockImplementation(() => console.log('mocked checkings'))

  // When
  Module.start()

  // Then
  expect(spy).toHaveBeenCalled()
})
</code>```

So instead of console logs in this order:

mocked checkings

app started

I get this:

checkings

app started

Body:
I have a module exporting the object of two methods:

start()

doSomeCheckings()

When start() is called, it calls a doSomeCheckings(). I would like to test that doSomeCheckings() function has been called and eventually returned a mocked value.

I followed up a jest documentation and some duplicated questions here on SO, but it still does not work as I wish. I don't get it what am I missing here ?

Here is the full jest online playground link

// module.js
function start () {
  doSomeCheckings()

  console.log('app started')
}

function doSomeCheckings () {
  console.log('checking')
}

module.exports = { start, doSomeCheckings }

And here is a jest test file:

it('should do some checkings on app start', () => {
  // Given
  const Module = require('./module')

  const spy = jest.spyOn(Module, 'doSomeCheckings')
  spy.mockImplementation(() => console.log('mocked checkings'))

  // When
  Module.start()

  // Then
  expect(spy).toHaveBeenCalled()
})

So instead of console logs in this order:

mocked checkings

app started

I get this:

checkings

app started


问:
How to authenticate an API client using an OAuth token issued from another web app in ASP.net WebAPI?
I have two web applications that I've worked on in ASP.net Web API for a client.  The two applications are hosted on the same domain, but in different virtual directories.

Each application has a data source with information about authorized users.  I've been asked to set up a separate app that will allow a user to log in and issue an OAuth bearer token that can be used to access each web application.

I have the Owin stuff set up in one of my two apps with something of a boilerplate setup and it automagically makes the tokens work for me, but that's only within a single web application.

I have a general idea of how the OAuth tokens work: a user is authenticated and they receive a token that contains a user ID, a time stamp, and a cryptographic signature that says that the token came from my client's server and not somewhere else, and the Web API framework automatically checks that token for me when I decorate my API endpoints with the [Authorize] attribute.

I want to know how I can set this up so that the token is issued by one web app and consumed by another.  I know that at a minimum, I need to make the two web apps work with the same key pair for the cryptographic signatures.

Can I please get some direction about how to make this happen?


问:
extract number from string and do math operation with bash
What's proper way to extract number from a string and do math on it?
e.g.</p>
```<code>var="VmRSS: 181420 kB"
out=(numbers in $var)/1024 # expected 181420/1024 = 177.168 MB
</code>```

Body:
What's proper way to extract number from a string and do math on it?
e.g.

var="VmRSS: 181420 kB"
out=(numbers in $var)/1024 # expected 181420/1024 = 177.168 MB


问:
React Typescript "npm run build" command removed line from manifest.json file
I'm using ReactJS + Typescript to create a chrome extension, but when I use the "npm run build" the manifest.json removes one line  '"permissions": ["history" ],' when the build is finished.

Before the command "npm run build":

```<code>{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "permissions": ["history" ],
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "icons": {
    "16": "logo192.png",
    "48": "logo192.png",
    "128": "logo192.png"
  }
}
</code>```

After the command:

```<code>{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "icons": {
    "16": "logo192.png",
    "48": "logo192.png",
    "128": "logo192.png"
  }
}
</code>```

What can I do to stop this from happening?

Body:
I'm using ReactJS + Typescript to create a chrome extension, but when I use the "npm run build" the manifest.json removes one line  '"permissions": ["history" ],' when the build is finished.

Before the command "npm run build":

{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "permissions": ["history" ],
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "icons": {
    "16": "logo192.png",
    "48": "logo192.png",
    "128": "logo192.png"
  }
}

After the command:

{
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "manifest_version": 2,
  "browser_action": {
    "default_popup": "index.html",
    "default_title": "Open the popup"
  },
  "icons": {
    "16": "logo192.png",
    "48": "logo192.png",
    "128": "logo192.png"
  }
}

What can I do to stop this from happening?


问:
CORS issues Google Cloud Storage Angular project to GCF Spring boot REST API
I am ultimately just trying to get static content (Angular) in a GCP storage bucket to send a POST request to an API Gateway Endpoint which routes to a GCP Function (Spring Boot REST API).  For simplicity, I am currently just trying to get it to work without the API gateway.

Everybody is uploaded, but when my click send on my static page I get the standard CORS error message:

```<code>Access to XMLHttpRequest at 'https://my-gcf-endpoint/post' from origin
'https://storage.googleapis.com' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have HTTP ok status.
</code>```

Researching this has taken me to here to create a JSON document and set it as my CORS config using  gsutil cors set cors-json-file gs://<bucket_name> (Finally figured out that I have to do this from the Cloud SDK while in the local folder that has the file)

cors.json:

```<code>[
    {
      "origin": ["*"],
      "method": ["GET", "POST"],
      "responseHeader": ["*"],
      "maxAgeSeconds": 3600
    }
]
</code>```

I used the above gsutil command on both my front end bucket and my backend bucket, but still getting the same error.

Inside my Spring Boot app, I added both global and method based cors config:

Main:

```<code>@SpringBootApplication
public class DivrFunctionApplication {

    public static void main(String[] args) {
        SpringApplication.run(DivrFunctionApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("*");
            }
        };
    }
</code>```

Controller:

```<code>@Component
@RestController
@CrossOrigin
public class MainController {

  @PostMapping("/postData")
  public ResponseEntity<String> postText(@RequestBody String message) {
    // edited to add these headers, but it still does not work
    HttpHeaders headers = new HttpHeaders();
    headers.set("ACCESS_CONTROL_ALLOW_ORIGIN","*");
    return new ResponseEntity<>(message, headers, HttpStatus.OK);
  }

  @GetMapping("/")
  public String hello() {
    return "hello world!";
  }
}
</code>```

I have found some docs that show Java / Google Cloud Cors setups, but none are in Spring boot.

Any thoughts on what I can try next?

Front End Code & Back End Code

ETA:

Per the comment below, I also added this to my application.properties:

```<code>spring.mvc.dispatch-options-request=true
</code>```

I will also not that this is as basic of an app as possible. no spring security, authentication of any kind, the storage buckets are all marked as public with AllUser Admin access, Allow Unauthenticated on GCF...

Like if someone randomly throws a rock in Gibraltar, I want it to hit this!

Body:
I am ultimately just trying to get static content (Angular) in a GCP storage bucket to send a POST request to an API Gateway Endpoint which routes to a GCP Function (Spring Boot REST API).  For simplicity, I am currently just trying to get it to work without the API gateway.

Everybody is uploaded, but when my click send on my static page I get the standard CORS error message:

Access to XMLHttpRequest at 'https://my-gcf-endpoint/post' from origin
'https://storage.googleapis.com' has been blocked by CORS policy: Response to
preflight request doesn't pass access control check: It does not have HTTP ok status.

Researching this has taken me to here to create a JSON document and set it as my CORS config using  gsutil cors set cors-json-file gs://<bucket_name> (Finally figured out that I have to do this from the Cloud SDK while in the local folder that has the file)

cors.json:

[
    {
      "origin": ["*"],
      "method": ["GET", "POST"],
      "responseHeader": ["*"],
      "maxAgeSeconds": 3600
    }
]

I used the above gsutil command on both my front end bucket and my backend bucket, but still getting the same error.

Inside my Spring Boot app, I added both global and method based cors config:

Main:

@SpringBootApplication
public class DivrFunctionApplication {

    public static void main(String[] args) {
        SpringApplication.run(DivrFunctionApplication.class, args);
    }

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedOrigins("*")
                        .allowedHeaders("*")
                        .allowedMethods("*");
            }
        };
    }

Controller:

@Component
@RestController
@CrossOrigin
public class MainController {

  @PostMapping("/postData")
  public ResponseEntity<String> postText(@RequestBody String message) {
    // edited to add these headers, but it still does not work
    HttpHeaders headers = new HttpHeaders();
    headers.set("ACCESS_CONTROL_ALLOW_ORIGIN","*");
    return new ResponseEntity<>(message, headers, HttpStatus.OK);
  }

  @GetMapping("/")
  public String hello() {
    return "hello world!";
  }
}

I have found some docs that show Java / Google Cloud Cors setups, but none are in Spring boot.

Any thoughts on what I can try next?

Front End Code & Back End Code

ETA:

Per the comment below, I also added this to my application.properties:

spring.mvc.dispatch-options-request=true

I will also not that this is as basic of an app as possible. no spring security, authentication of any kind, the storage buckets are all marked as public with AllUser Admin access, Allow Unauthenticated on GCF...

Like if someone randomly throws a rock in Gibraltar, I want it to hit this!


问:
Bit.dev - components - How do you compile scss files on bit build, so bit exports with compiled css
Bit dev - components - How do you compile scss files on bit build, so we bit export with compiled css.
Currently we are building and exporting our bit components. On the npm install of a component, the dist output is still in scss rather than css. Meaning when we bit build the scss is not being complied into css. Any ideas on how to implement the compilation of scss step into workspace.json? (webpack is not setup, using pnpm and bit commands only)</p>