问:
Is it possible to use sub-pixel rendering, or no anti-alias for STB fonts?
I want to use sub-pixel rendering for my font. If that is not possible, I at least want to disable anti-aliasing. How could I do so?
I am using LWJGL 3.3.1.
This is my font renderer:

```<code>public class FontRenderer
{
    private final STBTTBakedChar.Buffer characterData;
    private final STBTTFontinfo fontinfo;
    private final int size, textureID;
    private final float ascent;

    public FontRenderer(File font, int size)
    {
        this.size = size;
        this.characterData = STBTTBakedChar.malloc(96);
        this.fontinfo = STBTTFontinfo.create();
        int textureID = 0;
        float ascent = 0;

        try
        {
            ByteBuffer fontData = this.loadFileToByteBuffer(font);
            ByteBuffer textureData = BufferUtils.createByteBuffer(262144);
            assert fontData != null;
            stbtt_BakeFontBitmap(fontData, size, textureData, 512, 512, 32, this.characterData);

            try (MemoryStack memoryStack = MemoryStack.stackPush())
            {
                stbtt_InitFont(this.fontinfo, fontData);
                float pixelScale = stbtt_ScaleForPixelHeight(this.fontinfo, size);
                IntBuffer ascentBuffer = memoryStack.mallocInt(1);
                IntBuffer descentBuffer = memoryStack.mallocInt(1);
                IntBuffer lineGapBuffer = memoryStack.mallocInt(1);
                stbtt_GetFontVMetrics(this.fontinfo, ascentBuffer, descentBuffer, lineGapBuffer);
                ascent = ascentBuffer.get(0) * pixelScale;
            }

            textureID = glGenTextures();
            glBindTexture(GL_TEXTURE_2D, textureID);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512, 512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureData);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glBindTexture(GL_TEXTURE_2D, 0);
        }

        catch (Exception e)
        {
            ;
        }

        this.ascent = ascent;
        this.textureID = textureID;
    }

    public int getSize()
    {
        return this.size;
    }
</code>```

Creates a new ByteBuffer:

```<code>    private ByteBuffer loadFileToByteBuffer(File file)
    {
        try (FileInputStream fileInputStream = new FileInputStream(file); FileChannel fileChannel = fileInputStream.getChannel())
        {
            return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        }

        catch (Exception e)
        {
            return null;
        }
    }
</code>```

Draws the text:

```<code>    public void drawString(String text, float x, float y, Color color)
    {
        y += this.ascent;

        try (MemoryStack memoryStack = MemoryStack.stackPush())
        {
            FloatBuffer xBuffer = memoryStack.floats(x);
            FloatBuffer yBuffer = memoryStack.floats(y);
            STBTTAlignedQuad stbttAlignedQuad = STBTTAlignedQuad.malloc(memoryStack);
            glEnable(GL_ALPHA);
            glEnable(GL_BLEND);
            GL14.glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);
            int colorRGB = color.getRGB();
            float alpha = (float)((colorRGB >> 24) & 0xFF) / 255;
            float red = (float)((colorRGB >> 16) & 0xFF) / 255;
            float green = (float)((colorRGB >> 8) & 0xFF) / 255;
            float blue = (float)((colorRGB) & 0xFF) / 255;
            glColor4f(red, green, blue, alpha);
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, this.textureID);
            glBegin(GL_TRIANGLES);

            for (int i = 0; i < text.length(); i++)
            {
                int codePoint = text.codePointAt(i);

                if (codePoint == '\n')
                {
                    xBuffer.put(0, x);
                    yBuffer.put(0, y += this.ascent);
                    continue;
                }

                else if (codePoint < 32 || codePoint > 127)
                {
                    continue;
                }

                stbtt_GetBakedQuad(this.characterData, 512, 512, codePoint - 32, xBuffer, yBuffer, stbttAlignedQuad, true);
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y0());
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());
            }

            glEnd();
            glDisable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, 0);
            glColor4f(1, 1, 1, 1);
            glDisable(GL_BLEND);
            glDisable(GL_ALPHA);
        }
    }
</code>```

Body:
I want to use sub-pixel rendering for my font. If that is not possible, I at least want to disable anti-aliasing. How could I do so?
I am using LWJGL 3.3.1.
This is my font renderer:

public class FontRenderer
{
    private final STBTTBakedChar.Buffer characterData;
    private final STBTTFontinfo fontinfo;
    private final int size, textureID;
    private final float ascent;

    public FontRenderer(File font, int size)
    {
        this.size = size;
        this.characterData = STBTTBakedChar.malloc(96);
        this.fontinfo = STBTTFontinfo.create();
        int textureID = 0;
        float ascent = 0;

        try
        {
            ByteBuffer fontData = this.loadFileToByteBuffer(font);
            ByteBuffer textureData = BufferUtils.createByteBuffer(262144);
            assert fontData != null;
            stbtt_BakeFontBitmap(fontData, size, textureData, 512, 512, 32, this.characterData);

            try (MemoryStack memoryStack = MemoryStack.stackPush())
            {
                stbtt_InitFont(this.fontinfo, fontData);
                float pixelScale = stbtt_ScaleForPixelHeight(this.fontinfo, size);
                IntBuffer ascentBuffer = memoryStack.mallocInt(1);
                IntBuffer descentBuffer = memoryStack.mallocInt(1);
                IntBuffer lineGapBuffer = memoryStack.mallocInt(1);
                stbtt_GetFontVMetrics(this.fontinfo, ascentBuffer, descentBuffer, lineGapBuffer);
                ascent = ascentBuffer.get(0) * pixelScale;
            }

            textureID = glGenTextures();
            glBindTexture(GL_TEXTURE_2D, textureID);
            glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512, 512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, textureData);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glBindTexture(GL_TEXTURE_2D, 0);
        }

        catch (Exception e)
        {
            ;
        }

        this.ascent = ascent;
        this.textureID = textureID;
    }

    public int getSize()
    {
        return this.size;
    }

Creates a new ByteBuffer:

    private ByteBuffer loadFileToByteBuffer(File file)
    {
        try (FileInputStream fileInputStream = new FileInputStream(file); FileChannel fileChannel = fileInputStream.getChannel())
        {
            return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        }

        catch (Exception e)
        {
            return null;
        }
    }

Draws the text:

    public void drawString(String text, float x, float y, Color color)
    {
        y += this.ascent;

        try (MemoryStack memoryStack = MemoryStack.stackPush())
        {
            FloatBuffer xBuffer = memoryStack.floats(x);
            FloatBuffer yBuffer = memoryStack.floats(y);
            STBTTAlignedQuad stbttAlignedQuad = STBTTAlignedQuad.malloc(memoryStack);
            glEnable(GL_ALPHA);
            glEnable(GL_BLEND);
            GL14.glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, 1, 0);
            int colorRGB = color.getRGB();
            float alpha = (float)((colorRGB >> 24) & 0xFF) / 255;
            float red = (float)((colorRGB >> 16) & 0xFF) / 255;
            float green = (float)((colorRGB >> 8) & 0xFF) / 255;
            float blue = (float)((colorRGB) & 0xFF) / 255;
            glColor4f(red, green, blue, alpha);
            glEnable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, this.textureID);
            glBegin(GL_TRIANGLES);

            for (int i = 0; i < text.length(); i++)
            {
                int codePoint = text.codePointAt(i);

                if (codePoint == '\n')
                {
                    xBuffer.put(0, x);
                    yBuffer.put(0, y += this.ascent);
                    continue;
                }

                else if (codePoint < 32 || codePoint > 127)
                {
                    continue;
                }

                stbtt_GetBakedQuad(this.characterData, 512, 512, codePoint - 32, xBuffer, yBuffer, stbttAlignedQuad, true);
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t1());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y1());
                glTexCoord2f(stbttAlignedQuad.s1(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x1(), stbttAlignedQuad.y0());
                glTexCoord2f(stbttAlignedQuad.s0(), stbttAlignedQuad.t0());
                glVertex2f(stbttAlignedQuad.x0(), stbttAlignedQuad.y0());
            }

            glEnd();
            glDisable(GL_TEXTURE_2D);
            glBindTexture(GL_TEXTURE_2D, 0);
            glColor4f(1, 1, 1, 1);
            glDisable(GL_BLEND);
            glDisable(GL_ALPHA);
        }
    }


来源: stackexchange

问:
I want to set a text view as default in my xml
I want to set a textView as default for when I start my app, the first activity starts from the following textview. How I can do this?</p>
```<code><TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/idTVMsg"
        android:layout_centerInParent="true"
        android:layout_margin="20dp"
        android:gravity="center"
        android:padding="10dp"
        android:text="TextView in Android"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold"/>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to set a textView as default for when I start my app, the first activity starts from the following textview. How I can do this?

<TextView
        android:id="@+id/idTVHeading"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@id/idTVMsg"
        android:layout_centerInParent="true"
        android:layout_margin="20dp"
        android:gravity="center"
        android:padding="10dp"
        android:text="TextView in Android"
        android:textAlignment="center"
        android:textColor="@color/black"
        android:textSize="20sp"
        android:textStyle="bold"/>


问:
How do I fill up this new column using sql >
I am a bit new to SQL.

I have a table called hotel_consent_language_code with the following columns:

```<code>hotel_consent_key varchar not null,
language_code varchar not null
</code>```

with sample values as shown below:

```<code>hotel_consent_key                       language_code
-----------------------------------------------------
"consent_key_1"                         "NL"
"00000000-0000-0000-4001-000000000001"  "EN"
"00000000-0000-0000-4001-000000000001"  "NL"
"00000000-0000-0000-4002-000000000002"  "EN"
"00000000-0000-0000-4002-000000000002"  "NL"
</code>```

I am adding another column with name hotel_uid to this table.

```<code>ALTER TABLE hotel_consent_language_code
    ADD COLUMN IF NOT EXISTS hotel_uid uuid NOT NULL;
</code>```

My aim is to make a composite primary key using the three columns. So I cannot leave the hotel_uid column empty.

I need to populate it using another table hotel_consent which has columns and data as given below.

```<code>key                 hotel_uid
------------------------------------------------------------
"Aconsent_4key_1"   "00000000-0000-0000-4001-000000000001"
"Aconsent_4key_3"   "00000000-0000-0000-4001-000000000001"
"Cconsent_4key_4"   "00000000-0000-0000-4001-000000000001"
"Dconsent_4key_7"   "00000000-0000-0000-4004-000000000001"
"Econsent_4key_5"   "00000000-0000-0000-4001-000000000001"
"Fconsent_4key_2"   "00000000-0000-0000-4001-000000000001"
"consent_key_1"     "00000000-0000-0000-0003-000000000001"
</code>```

The 'key' column in hotel_consent table is the same as 'hotel_consent_key' column in hotel_consent_language_code table.

How do I fill up the hotel_uid column in hotel_consent_language_code table using the data from hotel_consenttable ?

Can I actually accomplish this without mismatching any data in the hotel_consent_language_code table ?

Body:
I am a bit new to SQL.

I have a table called hotel_consent_language_code with the following columns:

hotel_consent_key varchar not null,
language_code varchar not null

with sample values as shown below:

hotel_consent_key                       language_code
-----------------------------------------------------
"consent_key_1"                         "NL"
"00000000-0000-0000-4001-000000000001"  "EN"
"00000000-0000-0000-4001-000000000001"  "NL"
"00000000-0000-0000-4002-000000000002"  "EN"
"00000000-0000-0000-4002-000000000002"  "NL"

I am adding another column with name hotel_uid to this table.

ALTER TABLE hotel_consent_language_code
    ADD COLUMN IF NOT EXISTS hotel_uid uuid NOT NULL;

My aim is to make a composite primary key using the three columns. So I cannot leave the hotel_uid column empty.

I need to populate it using another table hotel_consent which has columns and data as given below.

key                 hotel_uid
------------------------------------------------------------
"Aconsent_4key_1"   "00000000-0000-0000-4001-000000000001"
"Aconsent_4key_3"   "00000000-0000-0000-4001-000000000001"
"Cconsent_4key_4"   "00000000-0000-0000-4001-000000000001"
"Dconsent_4key_7"   "00000000-0000-0000-4004-000000000001"
"Econsent_4key_5"   "00000000-0000-0000-4001-000000000001"
"Fconsent_4key_2"   "00000000-0000-0000-4001-000000000001"
"consent_key_1"     "00000000-0000-0000-0003-000000000001"

The 'key' column in hotel_consent table is the same as 'hotel_consent_key' column in hotel_consent_language_code table.

How do I fill up the hotel_uid column in hotel_consent_language_code table using the data from hotel_consenttable ?

Can I actually accomplish this without mismatching any data in the hotel_consent_language_code table ?


问:
Highcharts - showing newly added points after selecting rangeSelector
On sample provided by Highcharts https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/plotoptions/series-datagrouping-last-anchor after clicking on rangeSelector button (YTD) the XAxis freezes and does not extend and does not move to show newly added points (despite having: lastAnchor: 'lastPoint')

```<code>    dataGrouping: {
        approximation: 'average',
        enabled: true,
        forced: true,
        units: [
            ['millisecond', [5]]
        ],
        lastAnchor: 'lastPoint'
    }
</code>```

After clicking on All it works again.

How to make the chart to show newly added points while rangeSelector is on?

Body:
On sample provided by Highcharts https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/stock/plotoptions/series-datagrouping-last-anchor after clicking on rangeSelector button (YTD) the XAxis freezes and does not extend and does not move to show newly added points (despite having: lastAnchor: 'lastPoint')

    dataGrouping: {
        approximation: 'average',
        enabled: true,
        forced: true,
        units: [
            ['millisecond', [5]]
        ],
        lastAnchor: 'lastPoint'
    }

After clicking on All it works again.

How to make the chart to show newly added points while rangeSelector is on?


问:
Revert the given permission to Storage Access API on Safari
I am working with Storage Access API on Safari.

For testing/debugging purposes, I want to take back the permission that I've previously given. Currently, I keep creating new loopback IPs which is a bit annoying (see screencap below), also I need to give instructions to the testing team once this is deployed to prod.


问:
How to intercept header "X-Total-Count" into Axios intercepter for only 1 type of requests and not all (reactJs, Json-server)?
I am using json-server as fake API, and axios to create a paginated request to a set of data .
Here's my data from json-server

```<code>[{"id" : 1, "author" : "Trever"},
 {"id" : 2, "author" : "Sonya"},
 {"id" : 3, "author" : "Mark"},
 {"id" : 4, "author" : "Bob"}, {...}, {...}, ... ]
</code>```

I have similar other resources for cars and drums too.

I created an agent file (agent.ts) to centralise all of my axios requests

```<code>axios.defaults.baseURL = 'http://localhost:3000/';
const responseBody = ( Response : AxiosResponse ) => Response.data;

const requests = {
    get : (url : string, params? : URLSearchParams ) => axios.get(url, {params}).then(responseBody),
    post : (url : string, body : {}) => axios.post(url, body).then(responseBody),
    put : (url : string, body : {}) => axios.put(url, body).then(responseBody),
    delete : (url : string) => axios.delete(url).then(responseBody)
}

// intercepting reponse header
axios.interceptors.response.use( response => {
const totalBooks = response.headers['x-total-count'];
 if (totalBooks) console.log(JSON.parse(totalBooks), 'total books in database'); //this is working fine - (i am receiving '20', into console which is correct)
 return response;
});

const Posts = {
 get : (params : URLSearchParams) => requests.get('books', params);
}

const agent = {
Posts
};

export default agent;
</code>```

Now I have created a slice for getting books into my component - i named it bookSlice.ts

here's the code to that -

```<code>bookSlice.ts

 interface BookState {
    loadedBooks : boolean;
    status : string;
    totalBooks : string | undefined;
    }

    export const booksAdapter = createEntityAdapter<Book>();

     // (i want to do something like this) - intercepting response for books only (similary I want to intercept "X-Total-Count" inside carSlice and drumSlice files as well)//
    const XTotalCountHeader = () => {
     axios.intercepters.response.use(response => {
     const totalBooks = response.headers['x-total-count'];
     if (totalBooks) thunkAPI.dispatch(JSON.parse(totalBooks));
     return response;
    });
 }

export const fetchBooksAsync = createAsyncThunk<Book[], void, {state : RootState}>(
'books/fetchBooksAsync',
async(_, thunkAPI) => {
 const booksParams = AxiosGetParams(thunkAPI.getState().books.parameters); // this is my function to append parameters to the url string
 try{
  return await agent.Posts.get(bookParams);
 } catch(error : any) { return thunkAPI.rejectWithValue({error : error.data});
});

export const bookSlice = createSlice({
name : 'books',
initialState : booksAdapter.getInitialState<BookState>({
loadedBooks : false,
status : 'idle',
totalBooks : '',
}),
reducers : {
 setTotalBooks : (state, action) => {
   state.totalBooks = action.payLoad;
 }
},
extraReducers : (builder => {
  builder.addCase(fetchBooksAsync.fulfilled, (state, action) => {
   booksAdapter.setAll(state, action);
   state.loadedBooks = true,
   state.status = 'idle'
  });

 builder.addCase(fetchBooksAsync.pending, (state) => {
   state.status = 'pending'
  });

 builder.addCase(fetchBooksAsync.rejected, (state) => {
  state.status = 'rejected';
  });
});
});

export const { setTotalBooks } =bookSlice.actions;
</code>```

// what i want is to get the value of the header "X-Total-Count" from json-server's response headers into some object (in this case - totalBooks ), so that I could use this object anywhere into my Application's components.//

```<code>Also, I have different resourses viz - books[], cars[], drums[], etc.
</code>```

And on using -

```<code>  axios.intercepters.response.use(response => {
     const totalBooks = response.headers['x-total-count'];
     if (totalBooks) thunkAPI.dispatch(JSON.parse(totalBooks));
     return response;
    });

All of the responses are intercepted , and I get different numbers into the console ,like
20 //since it is total books
3 //since it is total cars
9 //since it is total drums
</code>```

I only want the total books into my bookSlice.ts ,
similarly I only want the total cars into My carsSlice.ts
and I only want the total drums into my drumSlice.ts.

So firstly, how should I get the "X-Total-Count" from the axios.intercepters (if fetched in this way?) into the respective slices for books, cars, and drums respectively???

Secondly, I dont want to destroy the pattern I am using into my agent.ts file,
ie, I created a responseBody , for accumulating the response.data, and requests - object to centralise all the requests to the json - server in my agent.ts file.
I wanted this to be followed.

And I don't want to make something like this into my either of the slices -

```<code>try{
    axios.get('http://localhost:3000/books').then((response) => {
    thunkAPI.dispatch(setTotalBooks(response.headers['x-total-count']))
    })
    } catch(error : any) {
     return thunkAPI.rejectWithValue({error : error.data });
    }
</code>```

How either could I do this into my agent.ts file (if possible)?
I hope you have understood my problem.
Please suggest me some solutions to get this "X-Total-Count" values each for my books, cars, drums into their respective slices (and three different objects, so that I could use them into their respective UI Components).

Thank You, all suggestions are welcome!!

Body:
I am using json-server as fake API, and axios to create a paginated request to a set of data .
Here's my data from json-server

[{"id" : 1, "author" : "Trever"},
 {"id" : 2, "author" : "Sonya"},
 {"id" : 3, "author" : "Mark"},
 {"id" : 4, "author" : "Bob"}, {...}, {...}, ... ]

I have similar other resources for cars and drums too.

I created an agent file (agent.ts) to centralise all of my axios requests

axios.defaults.baseURL = 'http://localhost:3000/';
const responseBody = ( Response : AxiosResponse ) => Response.data;

const requests = {
    get : (url : string, params? : URLSearchParams ) => axios.get(url, {params}).then(responseBody),
    post : (url : string, body : {}) => axios.post(url, body).then(responseBody),
    put : (url : string, body : {}) => axios.put(url, body).then(responseBody),
    delete : (url : string) => axios.delete(url).then(responseBody)
}

// intercepting reponse header
axios.interceptors.response.use( response => {
const totalBooks = response.headers['x-total-count'];
 if (totalBooks) console.log(JSON.parse(totalBooks), 'total books in database'); //this is working fine - (i am receiving '20', into console which is correct)
 return response;
});

const Posts = {
 get : (params : URLSearchParams) => requests.get('books', params);
}

const agent = {
Posts
};

export default agent;

Now I have created a slice for getting books into my component - i named it bookSlice.ts

here's the code to that -

bookSlice.ts

 interface BookState {
    loadedBooks : boolean;
    status : string;
    totalBooks : string | undefined;
    }

    export const booksAdapter = createEntityAdapter<Book>();

     // (i want to do something like this) - intercepting response for books only (similary I want to intercept "X-Total-Count" inside carSlice and drumSlice files as well)//
    const XTotalCountHeader = () => {
     axios.intercepters.response.use(response => {
     const totalBooks = response.headers['x-total-count'];
     if (totalBooks) thunkAPI.dispatch(JSON.parse(totalBooks));
     return response;
    });
 }

export const fetchBooksAsync = createAsyncThunk<Book[], void, {state : RootState}>(
'books/fetchBooksAsync',
async(_, thunkAPI) => {
 const booksParams = AxiosGetParams(thunkAPI.getState().books.parameters); // this is my function to append parameters to the url string
 try{
  return await agent.Posts.get(bookParams);
 } catch(error : any) { return thunkAPI.rejectWithValue({error : error.data});
});

export const bookSlice = createSlice({
name : 'books',
initialState : booksAdapter.getInitialState<BookState>({
loadedBooks : false,
status : 'idle',
totalBooks : '',
}),
reducers : {
 setTotalBooks : (state, action) => {
   state.totalBooks = action.payLoad;
 }
},
extraReducers : (builder => {
  builder.addCase(fetchBooksAsync.fulfilled, (state, action) => {
   booksAdapter.setAll(state, action);
   state.loadedBooks = true,
   state.status = 'idle'
  });

 builder.addCase(fetchBooksAsync.pending, (state) => {
   state.status = 'pending'
  });

 builder.addCase(fetchBooksAsync.rejected, (state) => {
  state.status = 'rejected';
  });
});
});

export const { setTotalBooks } =bookSlice.actions;

// what i want is to get the value of the header "X-Total-Count" from json-server's response headers into some object (in this case - totalBooks ), so that I could use this object anywhere into my Application's components.//

Also, I have different resourses viz - books[], cars[], drums[], etc.

And on using -

  axios.intercepters.response.use(response => {
     const totalBooks = response.headers['x-total-count'];
     if (totalBooks) thunkAPI.dispatch(JSON.parse(totalBooks));
     return response;
    });

All of the responses are intercepted , and I get different numbers into the console ,like
20 //since it is total books
3 //since it is total cars
9 //since it is total drums

I only want the total books into my bookSlice.ts ,
similarly I only want the total cars into My carsSlice.ts
and I only want the total drums into my drumSlice.ts.

So firstly, how should I get the "X-Total-Count" from the axios.intercepters (if fetched in this way?) into the respective slices for books, cars, and drums respectively???

Secondly, I dont want to destroy the pattern I am using into my agent.ts file,
ie, I created a responseBody , for accumulating the response.data, and requests - object to centralise all the requests to the json - server in my agent.ts file.
I wanted this to be followed.

And I don't want to make something like this into my either of the slices -

try{
    axios.get('http://localhost:3000/books').then((response) => {
    thunkAPI.dispatch(setTotalBooks(response.headers['x-total-count']))
    })
    } catch(error : any) {
     return thunkAPI.rejectWithValue({error : error.data });
    }

How either could I do this into my agent.ts file (if possible)?
I hope you have understood my problem.
Please suggest me some solutions to get this "X-Total-Count" values each for my books, cars, drums into their respective slices (and three different objects, so that I could use them into their respective UI Components).

Thank You, all suggestions are welcome!!


问:
cross-origin resource error only on production server
I'm trying to do a call to a service from an angular site but for some reason I'm getting an anoying CORS error. It's weird because I can do the call from my local machine, but when I deploy the code into my server I get the error executing the same call.

Could someone explain me why this is happening?

Call from Angular:

```<code>                var externalURL = 'https://www.someDomain.com/service';
                this.http.get(externalURL).toPromise()
                .then((response: any) => {

                    //some stuff
                })
                .catch(err => {
                    console.error(err);
                });
</code>```

When I execute this call from my local machine or even if I paste the url in the browser, the call works fine. But when I upload the code to my production server, the cors errors appears.

if I'm not wrong a Cors error happens because the following:

-The client side (a web page) try to call the server side
-The server check if the request has a permission to access him, and if not he block the client.
-The client get CORS error because of the server block.

Above has sense for me, expects because I'm able to do the call from my local machine.

How can I fix that problem?

Thanks in advance!!

Body:
I'm trying to do a call to a service from an angular site but for some reason I'm getting an anoying CORS error. It's weird because I can do the call from my local machine, but when I deploy the code into my server I get the error executing the same call.

Could someone explain me why this is happening?

Call from Angular:

                var externalURL = 'https://www.someDomain.com/service';
                this.http.get(externalURL).toPromise()
                .then((response: any) => {

                    //some stuff
                })
                .catch(err => {
                    console.error(err);
                });

When I execute this call from my local machine or even if I paste the url in the browser, the call works fine. But when I upload the code to my production server, the cors errors appears.

if I'm not wrong a Cors error happens because the following:

-The client side (a web page) try to call the server side
-The server check if the request has a permission to access him, and if not he block the client.
-The client get CORS error because of the server block.

Above has sense for me, expects because I'm able to do the call from my local machine.

How can I fix that problem?

Thanks in advance!!


问:
R: Changing axis title of all graphs with grid.arrange & Forcing non-scientific notation in labels
Below is my code for 2 graphs, the current output is shown below as well. I've been trying to do 2 things:

Changing the axis label so that it is only noted once for both graphs (& centred preferrably).

Forcing non-scientific notation (Notice how it's fine everywhere apart from on the y-axi where it shows 1e-04).

My code

```<code>make_linear_regression <- function(){
  linear_scat_um <- filtered_data %>%
    ggplot(aes(x = log10(rel_wpm), y= log10(rel_um))) +
    geom_point(alpha = 0.2) +
    geom_smooth(method = lm, color = "red") +
    labs(title = "Voorkomens van 'eh'",
         x = "Relatief Aantal Woorden Per Minuut",
         y = "Hoeveel procent van spraak is 'eh'?") +
    theme_fivethirtyeight() +
    theme(axis.title = element_text(),
          plot.title = element_text(colour = "#FF0000"),
          axis.line = element_line(colour = "black")) +
    scale_x_continuous(breaks = c(-2,-1,0,1,2),
                       labels = c(0.01,0.1,1,10,100))+
    scale_y_continuous(breaks = c(-4,-3,-2,-1),
                       labels = c(0.0001,0.001,0.01,0.1))

  linear_scat_uhm <- filtered_data %>%
    ggplot(aes(x=log10(rel_wpm), y=log10(rel_uhm))) +
    geom_point(alpha = 0.2) +
    geom_smooth(method = lm, color = "blue") +
    labs(title = "Voorkomens van 'ehm'",
         x = "Relatief Aantal Woorden Per Minuut",
         y = "Hoeveel procent van spraak is 'ehm'?") +
    theme_fivethirtyeight() +
    theme(axis.title = element_text(),
          plot.title = element_text(colour = "#0000FF"),
          axis.line = element_line(colour = "black")) +
    scale_x_continuous(breaks = c(-2,-1,0,1,2),
                       labels = c(0.01,0.1,1,10,100)) +
    scale_y_continuous(breaks = c(-4,-3,-2,-1),
                       labels = c(0.0001,0.001,0.01,0.1))

  grid.arrange(linear_scat_um, linear_scat_uhm)
</code>```

Current output

Current Output

What I've already tried.

Single axis title.

I found a couple of posts using textGrub but that doesn't seem to work, I know for sure I have the library installed but it cannot find the function.

Forcing non-scientific notation.

Using label_comma() does change the notation to numbers, but it also changes the values I give. it would put the breaks in front of the decimal, leading to the y-labels: -4.0000, -3.000, -2.00, -1.0).

Body:
Below is my code for 2 graphs, the current output is shown below as well. I've been trying to do 2 things:

Changing the axis label so that it is only noted once for both graphs (& centred preferrably).

Forcing non-scientific notation (Notice how it's fine everywhere apart from on the y-axi where it shows 1e-04).

My code

make_linear_regression <- function(){
  linear_scat_um <- filtered_data %>%
    ggplot(aes(x = log10(rel_wpm), y= log10(rel_um))) +
    geom_point(alpha = 0.2) +
    geom_smooth(method = lm, color = "red") +
    labs(title = "Voorkomens van 'eh'",
         x = "Relatief Aantal Woorden Per Minuut",
         y = "Hoeveel procent van spraak is 'eh'?") +
    theme_fivethirtyeight() +
    theme(axis.title = element_text(),
          plot.title = element_text(colour = "#FF0000"),
          axis.line = element_line(colour = "black")) +
    scale_x_continuous(breaks = c(-2,-1,0,1,2),
                       labels = c(0.01,0.1,1,10,100))+
    scale_y_continuous(breaks = c(-4,-3,-2,-1),
                       labels = c(0.0001,0.001,0.01,0.1))

  linear_scat_uhm <- filtered_data %>%
    ggplot(aes(x=log10(rel_wpm), y=log10(rel_uhm))) +
    geom_point(alpha = 0.2) +
    geom_smooth(method = lm, color = "blue") +
    labs(title = "Voorkomens van 'ehm'",
         x = "Relatief Aantal Woorden Per Minuut",
         y = "Hoeveel procent van spraak is 'ehm'?") +
    theme_fivethirtyeight() +
    theme(axis.title = element_text(),
          plot.title = element_text(colour = "#0000FF"),
          axis.line = element_line(colour = "black")) +
    scale_x_continuous(breaks = c(-2,-1,0,1,2),
                       labels = c(0.01,0.1,1,10,100)) +
    scale_y_continuous(breaks = c(-4,-3,-2,-1),
                       labels = c(0.0001,0.001,0.01,0.1))

  grid.arrange(linear_scat_um, linear_scat_uhm)

Current output

Current Output

What I've already tried.

Single axis title.

I found a couple of posts using textGrub but that doesn't seem to work, I know for sure I have the library installed but it cannot find the function.

Forcing non-scientific notation.

Using label_comma() does change the notation to numbers, but it also changes the values I give. it would put the breaks in front of the decimal, leading to the y-labels: -4.0000, -3.000, -2.00, -1.0).


问:
Search query when clicking a tag
I want to get the blogs that matches a tag when its clicked.
this is a code snippet:

```<code>const [query, setQuery] = useState("")
const [isOn, setOn] = useState('google') //by default
<Input placeholder='Search Articles' onChange={event => setQuery(event.target.value)} />
<Btnn onClick={() => setOn('google')} >Google Ads</Btnn>
<Btnn onClick={() => setOn('facebook')} >Facebook Ads</Btnn>
<Btnn onClick={() => setOn('email')}>Email</Btnn>
...
{allBlogs.filter(b =>
                {

                     if (query === '') {
                      return b;
                    } else if (b.title?.toLowerCase().includes(query.toLowerCase()) ) {
                      return b;
                    }
                    else if (b.title?.toLowerCase().includes(isOn)) {
                        return b
                    }
                  }
              )
              .map((b) =>
                  (...
</code>```

The search query works perfectly and displays all the blogs I typed in the input, however when I click on a tag like Google Facebook etc this will not display the matched blogs!
Any idea?

Title: Search query when clicking a tag

Body:
I want to get the blogs that matches a tag when its clicked.
this is a code snippet:

const [query, setQuery] = useState("")
const [isOn, setOn] = useState('google') //by default
<Input placeholder='Search Articles' onChange={event => setQuery(event.target.value)} />
<Btnn onClick={() => setOn('google')} >Google Ads</Btnn>
<Btnn onClick={() => setOn('facebook')} >Facebook Ads</Btnn>
<Btnn onClick={() => setOn('email')}>Email</Btnn>
...
{allBlogs.filter(b =>
                {

                     if (query === '') {
                      return b;
                    } else if (b.title?.toLowerCase().includes(query.toLowerCase()) ) {
                      return b;
                    }
                    else if (b.title?.toLowerCase().includes(isOn)) {
                        return b
                    }
                  }
              )
              .map((b) =>
                  (...

The search query works perfectly and displays all the blogs I typed in the input, however when I click on a tag like Google Facebook etc this will not display the matched blogs!
Any idea?


问:
configuring multi-column headers infragistics
Iam sorry.How can I make a grid like this picture use ultragrid infragistics in vb.net
enter image description here

I want to make a grid


问:
Flutter get documents and return widget one by one?
I am filtering and returning the documents according to the email address of the user logged in Application. But it just gives me a document. There are 3 documents in the Firestore Repair collection. There are 2 documents belonging to the logged in user. Shouldn't this code normally return all relevant documents to me? What can I do for it?</p>
```<code>Widget getCustomerRepairLog() {
  final user = FirebaseAuth.instance.currentUser!;
  late final _repairLogs =
      FirebaseFirestore.instance.collection('Repair').get();
  return FutureBuilder<QuerySnapshot>(
      future: _repairLogs,
      builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasData) {
          List<Widget> items = [];
          final data = snapshot.data?.docs;
          if (data == null) return Text("got null");
          debugPrint(data.length.toString()); // document count 3 - true
          for (final eleman in data) {
            final currentData = eleman.data() as Map<String, dynamic>;
            if (currentData['email']! == user.email) {
              debugPrint(eleman.id);
              for (final item in currentData['title']) {
                items.add(Text("${item}"));
              }
              return Row(children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    for (final index in currentData['title'])
                      Row(
                        children: [
                          Icon(
                            Icons.done_all_rounded,
                            color: LightTheme.iconColor,
                          ),
                          Text(index),
                        ],
                      )
                  ],
                )
              ]);
            }
          }
        }
        return CircularProgressIndicator();
      });
}
</code>```

Body:
I am filtering and returning the documents according to the email address of the user logged in Application. But it just gives me a document. There are 3 documents in the Firestore Repair collection. There are 2 documents belonging to the logged in user. Shouldn't this code normally return all relevant documents to me? What can I do for it?

Widget getCustomerRepairLog() {
  final user = FirebaseAuth.instance.currentUser!;
  late final _repairLogs =
      FirebaseFirestore.instance.collection('Repair').get();
  return FutureBuilder<QuerySnapshot>(
      future: _repairLogs,
      builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
        if (snapshot.hasData) {
          List<Widget> items = [];
          final data = snapshot.data?.docs;
          if (data == null) return Text("got null");
          debugPrint(data.length.toString()); // document count 3 - true
          for (final eleman in data) {
            final currentData = eleman.data() as Map<String, dynamic>;
            if (currentData['email']! == user.email) {
              debugPrint(eleman.id);
              for (final item in currentData['title']) {
                items.add(Text("${item}"));
              }
              return Row(children: [
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    for (final index in currentData['title'])
                      Row(
                        children: [
                          Icon(
                            Icons.done_all_rounded,
                            color: LightTheme.iconColor,
                          ),
                          Text(index),
                        ],
                      )
                  ],
                )
              ]);
            }
          }
        }
        return CircularProgressIndicator();
      });
}


问:
UseParams doesn't get the id from the url but it gets the "edit" instead
This is the details component of a class:

```<code>export default observer(function ClassDetails() {
const { classesStore } = useStore();
const { loadClass, selectedClass: classR, loadingInitial } = classesStore;
const { id } = useParams<{ id: string }>();

useEffect(() => {
    if (id) loadClass(id)
}, [id, loadClass]);

if (loadingInitial || !classR) return <LoadingComponent content="Loading Class"/>;

return (
    <Card fluid>
        <Image src={`/assets/categoryImages/culture.jpg`} />
        <Card.Content>
            <Card.Header>{classR.id}</Card.Header>
            <Card.Description>
                <div>{classR.id}</div>
                <div>{classR.className}</div>
            </Card.Description>
        </Card.Content>
        <Card.Content extra>
            <Button.Group widths='2'>
                <Button as={Link} to={`/classes/edit/${classR.id}`} basic color="blue" content='Edit' />
            </Button.Group>
        </Card.Content>
    </Card>
)})
</code>```

Everything works fine when I open e certain class, the useParams get the Id from the url stores it and send it to the function loadClass with the certain id. But when I press the edit button, instead of storing the id part of the url, it stores the "edit" part of the url and then sends it to the loadClass function which returns no result of course. Why isn't it getting the id but it get the "edit" from url.

These are my routes:

```<code><Route path='/classes/:id' component={ClassDetails} />
<Route key={location.key} path={['/createClass', `/classes/edit/:id`]} component={ClassForm} />
</code>```

The first one it gets the id correctly, but for the second one it doesnt

Now if I change the routes of edit button to {/edit/${classR.id}} and the path to /edit/:id it works.

Why is that?
Thank you

Body:
This is the details component of a class:

export default observer(function ClassDetails() {
const { classesStore } = useStore();
const { loadClass, selectedClass: classR, loadingInitial } = classesStore;
const { id } = useParams<{ id: string }>();

useEffect(() => {
    if (id) loadClass(id)
}, [id, loadClass]);

if (loadingInitial || !classR) return <LoadingComponent content="Loading Class"/>;

return (
    <Card fluid>
        <Image src={`/assets/categoryImages/culture.jpg`} />
        <Card.Content>
            <Card.Header>{classR.id}</Card.Header>
            <Card.Description>

{classR.id}

{classR.className}

            </Card.Description>
        </Card.Content>
        <Card.Content extra>
            <Button.Group widths='2'>
                <Button as={Link} to={`/classes/edit/${classR.id}`} basic color="blue" content='Edit' />
            </Button.Group>
        </Card.Content>
    </Card>
)})

Everything works fine when I open e certain class, the useParams get the Id from the url stores it and send it to the function loadClass with the certain id. But when I press the edit button, instead of storing the id part of the url, it stores the "edit" part of the url and then sends it to the loadClass function which returns no result of course. Why isn't it getting the id but it get the "edit" from url.

These are my routes:

<Route path='/classes/:id' component={ClassDetails} />
<Route key={location.key} path={['/createClass', `/classes/edit/:id`]} component={ClassForm} />

The first one it gets the id correctly, but for the second one it doesnt

Now if I change the routes of edit button to {/edit/${classR.id}} and the path to /edit/:id it works.

Why is that?
Thank you


问:
SSL/TLS required on the control channel
I have created an linux instance using amazon lightsail.
After installing lftp i am getting error  Login failed: 550 SSL/TLS required on the control channel
I am using the following code

```<code>lftp -e 'pget -n 10 -c files.csv.gz -o ./test.csv.gz;bye' -u username,pass server cache flush
</code>```

Title: SSL/TLS required on the control channel

Body:
I have created an linux instance using amazon lightsail.
After installing lftp i am getting error  Login failed: 550 SSL/TLS required on the control channel
I am using the following code

lftp -e 'pget -n 10 -c files.csv.gz -o ./test.csv.gz;bye' -u username,pass server cache flush


问:
Creating a Legend Based on Marker Size with Geopandas
I'm having trouble creating a legend for the marker size of the map plot I've created.  The marker size is based on the number of electric buses used at each location.  I am trying to create a legend that has 3 entries for 1, 10, and 50 buses.

I have tried doing plt.legend(df.column_name, loc='lower left', scatterpoints=3). I expected this to make a legend with three examples from the column I specified.  Instead I got 3 points that were overlayed on top of eachother.   Below is the code I used and the result.

base = usa.plot(figsize=(20,20), edgecolor='white', linewidth=1)
points = busgp_data['geometry'].plot(ax=base,
                                     color='gold',
                                     marker='o',
                                     markersize=12 * busgp_data['num_of_ESBs'],
                                     edgecolor='black',
                                     alpha=0.7)
plt.legend(busgp_data['num_of_ESBs'], loc='lower left', scatterpoints=3)
plt.title('Location of Electric School Buses in the US', fontdict={'fontsize':20})
plt.tick_params(
    axis='both',
    which='both',
    bottom=False,
    left=False,
    labelleft=False,
    labelbottom=False)
```

Electric Buses in US Map

Body:
I'm having trouble creating a legend for the marker size of the map plot I've created.  The marker size is based on the number of electric buses used at each location.  I am trying to create a legend that has 3 entries for 1, 10, and 50 buses.

I have tried doing plt.legend(df.column_name, loc='lower left', scatterpoints=3). I expected this to make a legend with three examples from the column I specified.  Instead I got 3 points that were overlayed on top of eachother.   Below is the code I used and the result.

base = usa.plot(figsize=(20,20), edgecolor='white', linewidth=1)
points = busgp_data['geometry'].plot(ax=base,
                                     color='gold',
                                     marker='o',
                                     markersize=12 * busgp_data['num_of_ESBs'],
                                     edgecolor='black',
                                     alpha=0.7)
plt.legend(busgp_data['num_of_ESBs'], loc='lower left', scatterpoints=3)
plt.title('Location of Electric School Buses in the US', fontdict={'fontsize':20})
plt.tick_params(
    axis='both',
    which='both',
    bottom=False,
    left=False,
    labelleft=False,
    labelbottom=False)

Electric Buses in US Map


问:
Secure multi page form process - confirm form resubmission
I am using react and typescript for a web app. I need to make a secure multi-page form process. I have seen on other sites where if you go back from any page in the form, you will get 'confirm form resubmission', and if you still go back the previous page will not load. how can i do that and what are the best practices for this. This is what i have done till now, but it doesn't accomplish what i need.</p>
```<code>useEffect(() => {
    window.onbeforeunload = () => {
      return "Confirm form resubmission";
    };

    return () => {
      window.onbeforeunload = null;
    };
  }, []);
</code>```

Body:
I am using react and typescript for a web app. I need to make a secure multi-page form process. I have seen on other sites where if you go back from any page in the form, you will get 'confirm form resubmission', and if you still go back the previous page will not load. how can i do that and what are the best practices for this. This is what i have done till now, but it doesn't accomplish what i need.

useEffect(() => {
    window.onbeforeunload = () => {
      return "Confirm form resubmission";
    };

    return () => {
      window.onbeforeunload = null;
    };
  }, []);


问:
RTK useQuery is not refetch after mutation the data
I am getting post data from database through RTK useQuery, but when i upload new post through useMutation, it dosn't update data on Screen first time. After load the page it shows data. How to do this to get data without load a page.

```<code>// this is get post RTK query function
`const getallPosts =  useGetallPostsQuery();

  const postData = async () => {
    if(getallPosts.currentData){
      getallPosts.currentData.data.posts.map(item => dispatch(setPost(item)))
      console.log(getallPosts.currentData.data)
    }
  };`
</code>```

this is my Api file

```<code>`createPost:builder.mutation({
      query: (data) => {
        return {
          url: "create_post",
          method: "POST",
          body: data,
          headers: {
            "Content-type": "application/json",
          },
        };
      },
    }),

    getallPosts: builder.query({
      query: () => ({
        url: 'get_all_posts',
        method: 'GET',
        headers : {
          "Content-type": "application/json",
        }
      }),
      providesTags : ['Posts']
    }),`
</code>```

i tried tags caching but it didn't worked

Body:
I am getting post data from database through RTK useQuery, but when i upload new post through useMutation, it dosn't update data on Screen first time. After load the page it shows data. How to do this to get data without load a page.

// this is get post RTK query function
`const getallPosts =  useGetallPostsQuery();

  const postData = async () => {
    if(getallPosts.currentData){
      getallPosts.currentData.data.posts.map(item => dispatch(setPost(item)))
      console.log(getallPosts.currentData.data)
    }
  };`

this is my Api file

`createPost:builder.mutation({
      query: (data) => {
        return {
          url: "create_post",
          method: "POST",
          body: data,
          headers: {
            "Content-type": "application/json",
          },
        };
      },
    }),

    getallPosts: builder.query({
      query: () => ({
        url: 'get_all_posts',
        method: 'GET',
        headers : {
          "Content-type": "application/json",
        }
      }),
      providesTags : ['Posts']
    }),`

i tried tags caching but it didn't worked


问:
The bot should sent a message but it doesn't
So I got this script, and it doesn't work but does not write any errors in console. Just doesn't send message at all.

```<code>

async def run(ctx,channel,arg1,arg2,arg3):
    color = arg3
    if color in color_table:
      actual_color = getattr(discord.Colour, color)()
      embed=discord.Embed(title=arg1, description=arg2, color=actual_color)
      embed.set_footer(text="Powered by T.A.D.S.")
      channel_id = channel.id
      channel = discord.utils.get(ctx.guild.text_channels, id=int(channel_id))
      await channel.send(embed=embed)
    else:
      await ctx.channel.send("This color doesn't exist in discord databeses. Type !colours to show all colors that are available.")
</code>```

I want the bot to send a message to specified channel but it does nothing.

Body:
So I got this script, and it doesn't work but does not write any errors in console. Just doesn't send message at all.

async def run(ctx,channel,arg1,arg2,arg3):
    color = arg3
    if color in color_table:
      actual_color = getattr(discord.Colour, color)()
      embed=discord.Embed(title=arg1, description=arg2, color=actual_color)
      embed.set_footer(text="Powered by T.A.D.S.")
      channel_id = channel.id
      channel = discord.utils.get(ctx.guild.text_channels, id=int(channel_id))
      await channel.send(embed=embed)
    else:
      await ctx.channel.send("This color doesn't exist in discord databeses. Type !colours to show all colors that are available.")

I want the bot to send a message to specified channel but it does nothing.


问:
python error : codec can't decode byte 0xe4 in position 2857: invalid continuation byte
I am reading a latex file using

```<code>with open(inputFileName, 'r', encoding="utf8") as inputFileHandle:
    for lineInput in inputFileHandle:
</code>```

It fails with lineInput showing "% Declare common style"
with the error

```<code>can't decode byte 0xe4 in position 2857: invalid continuation byte
</code>```

I can not see any strange characters in the latex file. What is the byte 0xe4 and how can I identify it in the tex file?

Body:
I am reading a latex file using

with open(inputFileName, 'r', encoding="utf8") as inputFileHandle:
    for lineInput in inputFileHandle:

It fails with lineInput showing "% Declare common style"
with the error

can't decode byte 0xe4 in position 2857: invalid continuation byte

I can not see any strange characters in the latex file. What is the byte 0xe4 and how can I identify it in the tex file?


问:
What data format is this and how do I import it to python
I am trying to read a JSON like format from logs. It is different from JSON:

It doesn't have quotation marks around the name

There are "=" signs instead of ":"

What is this format called and how do I import it cleanly into python. Here is a small sample:

```<code>{
    accumulator = {
        animation_speed = 0.5,
        ingredients = {
            {
              "processing-unit",
              20
            },
            {
              "copper-plate",
              20
            },
            {
              "steel-plate",
              20
            },
            {
              "electric-engine-unit",
              10
            }
          },
    }
}
</code>```

Body:
I am trying to read a JSON like format from logs. It is different from JSON:

It doesn't have quotation marks around the name

There are "=" signs instead of ":"

What is this format called and how do I import it cleanly into python. Here is a small sample:

{
    accumulator = {
        animation_speed = 0.5,
        ingredients = {
            {
              "processing-unit",
              20
            },
            {
              "copper-plate",
              20
            },
            {
              "steel-plate",
              20
            },
            {
              "electric-engine-unit",
              10
            }
          },
    }
}


问:
Sequlize bulkCreate with updateOnDuplicates return all values(duplicated and not duplicated)
I have this code

```<code>const users = await User.bulkCreate(newUsers, {
        updateOnDuplicate: ['name'],
      });
</code>```

Its query return all values in response like

```<code>[
{
  id:1,
  name: 'Andrew'
},
{
  id:2,
  name: 'John'
},
{
  id:3,
  name: 'Andrew'
},
]
</code>```

But in database that query writes only unique value. Only 1 Andrew and 1 John.

I need to return only 2 records not 3

Body:
I have this code

const users = await User.bulkCreate(newUsers, {
        updateOnDuplicate: ['name'],
      });

Its query return all values in response like

[
{
  id:1,
  name: 'Andrew'
},
{
  id:2,
  name: 'John'
},
{
  id:3,
  name: 'Andrew'
},
]

But in database that query writes only unique value. Only 1 Andrew and 1 John.

I need to return only 2 records not 3


问:
reloading a function in javascript
I'm initializing three functions on loading the page and then performing some events on click so I want that when a click event is pressed I just reload those functions completely in the given code it loads the function again but the previous one remains there so I want that when I load the function again it should remove the previously loaded one.

```<code>$('#locationdeleteconfirm').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: "php/deleteLocationByID.php",
        type: 'POST',
        dataType: 'json',

        data: {
            name: $('#dname').val(),

            locationID: $('#dlocation').val(),
            id: $('#editlocationid').val(),
        },
        //if user enters correct data and api gives back the data then we run success funtion
        success: function(result) {

            console.log(result);

            //if status of data is ok we fetch the data from fields and put them in results table in html
            if (result.status.name == "ok") {

                //fetching fields from api and showing them in html table
                Swal.fire({
                    title: "Deleted",
                    text: "Deleted",
                    type: "success"
                }).then(function() {
                    $("#locdeleteconfirm").modal("hide");
                    $("#editlocationmodal2").modal("hide");
                    $('.modal-backdrop').removeClass('modal-backdrop');
                    $('#locationtable').load(location.href + " #locationtable>*")
                    getlocations();
                    getdepartments();
                    getallemployees();

                });

            } else {
                //if the upper condition  fails
                console.log("error");

            }

        },
        //if there is no success in retrieving data from api
        error: function(jqXHR, textStatus, errorThrown) {

            console.log("error");
            $('#txterror').html("Enter Valid Id");
        }
    });
})
</code>```

getloactions();
getdepartments();
getallemployees();

these are the three functions that are loading on the page load event I want them to reload once the click event is performed

Title: reloading a function in javascript

Body:
I'm initializing three functions on loading the page and then performing some events on click so I want that when a click event is pressed I just reload those functions completely in the given code it loads the function again but the previous one remains there so I want that when I load the function again it should remove the previously loaded one.

$('#locationdeleteconfirm').click(function(e) {
    e.preventDefault();
    $.ajax({
        url: "php/deleteLocationByID.php",
        type: 'POST',
        dataType: 'json',

        data: {
            name: $('#dname').val(),

            locationID: $('#dlocation').val(),
            id: $('#editlocationid').val(),
        },
        //if user enters correct data and api gives back the data then we run success funtion
        success: function(result) {

            console.log(result);

            //if status of data is ok we fetch the data from fields and put them in results table in html
            if (result.status.name == "ok") {

                //fetching fields from api and showing them in html table
                Swal.fire({
                    title: "Deleted",
                    text: "Deleted",
                    type: "success"
                }).then(function() {
                    $("#locdeleteconfirm").modal("hide");
                    $("#editlocationmodal2").modal("hide");
                    $('.modal-backdrop').removeClass('modal-backdrop');
                    $('#locationtable').load(location.href + " #locationtable>*")
                    getlocations();
                    getdepartments();
                    getallemployees();

                });

            } else {
                //if the upper condition  fails
                console.log("error");

            }

        },
        //if there is no success in retrieving data from api
        error: function(jqXHR, textStatus, errorThrown) {

            console.log("error");
            $('#txterror').html("Enter Valid Id");
        }
    });
})

getloactions();
getdepartments();
getallemployees();

these are the three functions that are loading on the page load event I want them to reload once the click event is performed


问:
From .NET 4.0 add reference to assembly in .NET 4.6
Visual Studio 2019 allows in the .NET 4.0 project Tests.Test_4_0.vbproj to add a reference to the .NET 4.6 assembly Tests.Test_4_6.dll. The editor allows to call methods of class Test1 in the .NET 4.6 assembly. However, when I build the project, I get the error:

```<code>C:\temp\Test_4_0.vb(327,35): error BC30002: Type 'Tests.Test_4_6.Test1' is not defined.
</code>```

Is there some way to call .NET 4.6 functions from .NET 4.0?

Body:
Visual Studio 2019 allows in the .NET 4.0 project Tests.Test_4_0.vbproj to add a reference to the .NET 4.6 assembly Tests.Test_4_6.dll. The editor allows to call methods of class Test1 in the .NET 4.6 assembly. However, when I build the project, I get the error:

C:\temp\Test_4_0.vb(327,35): error BC30002: Type 'Tests.Test_4_6.Test1' is not defined.

Is there some way to call .NET 4.6 functions from .NET 4.0?


问:
Mapping data error while connecting facebook ads to aws appflow
I am trying to connect facebook ads toaws appflow . Following thos dochttps://docs.aws.amazon.com/appflow/latest/userguide/connectors-facebook-ads.html
Successfully configured the flow but in the third step it gives me an error

An error occurred while retrieving fields
Error while communicating to connector: The request failed because the service Source Facebook Ads returned the following error: Details: Invalid EntityId selection, ErrorCode: InvalidArgument.

Attaching screenshot of the same


问:
InvalidOperationException Ellipse not Found after Binding "IsChecked"
I am using a Togglebutton Style from here after Binding the IsChecked Property to my ViewModel the Program crashes with a System.InvalidOperationException Ellipse not found in  "System.Windows.Controls.ControlTemplate".

The Style looks like this:

```<code><Style TargetType="{x:Type ToggleButton}">
   <Setter Property="Template">
      <Setter.Value>
         <ControlTemplate TargetType="{x:Type ToggleButton}">
            <Viewbox>
               <Border x:Name="Border"
                  CornerRadius="10"
                  Background="#FFE2E2E2"
                  Width="40"
                  Height="20">
                  <Border.Effect>
                      <DropShadowEffect ShadowDepth="0.5"
                         Direction="0"
                         Opacity="0.3" />
                   </Border.Effect>
                   <Ellipse x:Name="Ellipse"
                      Fill="#FF909090"
                      Stretch="Uniform"
                      Margin="-8 -4"
                      Stroke="Gray"
                      StrokeThickness="0.2"
                      HorizontalAlignment="Stretch">
                   <Ellipse.Effect>
                      <DropShadowEffect BlurRadius="10"
                         ShadowDepth="1"
                         Opacity="0.3"
                         Direction="260" />
                   </Ellipse.Effect>
                </Ellipse>
             </Border>
          </Viewbox>
          <ControlTemplate.Triggers>
             <EventTrigger RoutedEvent="Checked">
                <BeginStoryboard>
                   <Storyboard>
                      <ColorAnimation Storyboard.TargetName="Ellipse"
                         Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
                         To="#00facc"
                         Duration="0:0:0.05"
                         AccelerationRatio="0.7"
                         DecelerationRatio="0.3" />
                      <ThicknessAnimation Storyboard.TargetName="Ellipse"
                         Storyboard.TargetProperty="Margin"
                         To="20 -4 -8 -4"
                         Duration="0:0:0.15"
                         AccelerationRatio="0.7"
                         DecelerationRatio="0.3" />
                      </Storyboard>
                   </BeginStoryboard>
                </EventTrigger>
                <EventTrigger RoutedEvent="Unchecked">
                  <BeginStoryboard>
                    <Storyboard>
                      <ColorAnimation Storyboard.TargetName="Ellipse"
                        Storyboard.TargetProperty="(Ellipse.Fill).(SolidColorBrush.Color)"
                        To="#00facc"
                        Duration="0:0:0.05"
                        AccelerationRatio="0.7"
                        DecelerationRatio="0.3" />
                     <ThicknessAnimation
                        Storyboard.TargetName="Ellipse"
                        Storyboard.TargetProperty="Margin"
                        To="-8 -4"
                        Duration="0:0:0.15"
                        AccelerationRatio="0.7"
                        DecelerationRatio="0.3" />
                     </Storyboard>
                  </BeginStoryboard>
               </EventTrigger>
            </ControlTemplate.Triggers>
         </ControlTemplate>
      </Setter.Value>
   </Setter>
</Style>
</code>```

And my usage like this:

```<code><ToggleButton Grid.Column="0"
   Grid.Row="2"
   IsChecked="{Binding IsAutostop}"/>
</code>```

I'd like to use the style AND be able to use the "IsChecked" Property.

EDIT

Thanks for the comments.

I open the window with a Service bound to a command in a taskbaricon.

The Service:

```<code>    class WindowService
    {
        public void OpenOptionsView(MainViewModel mvm)
        {
            OptionsView optionsView = new OptionsView { DataContext = mvm };
            optionsView.Show();
        }
    }
</code>```

The important parts of the MainviewModel:

```<code>public ICommand OpenOptionsViewCommand { get; private set; }
public bool IsAutostop { get { return Settings.Default.Autostop; } set { Settings.Default.Autostop = value; Settings.Default.Save(); OnPropertyChanged(); } }

public MainViewModel()
{
   OpenOptionsViewCommand = new RelayCommand(OpenOptionsView, param => true);
}

private void OpenOptionsView(object o)
{
   WindowService ws = new WindowService();
   ws.OpenOptionsView(this);
}
</code>```

I stored my TaskbarIcon in a seperated View:

```<code>   <tb:TaskbarIcon>
      <tb:TaskbarIcon.ContextMenu>
         <ContextMenu Background="#1e1e1e">
            <MenuItem Header="Programm öffnen"
                      Foreground="White"
                      Command="{Binding OpenOptionsViewCommand}"/>
         </ContextMenu>
      </tb:TaskbarIcon.ContextMenu>
   </tb:TaskbarIcon>
</code>```

EDIT II:

I just found out, that the problem occurs when the bound value is True and the window should be opened with a checked Togglebutton.

Body:
I am using a Togglebutton Style from here after Binding the IsChecked Property to my ViewModel the Program crashes with a System.InvalidOperationException Ellipse not found in  "System.Windows.Controls.ControlTemplate".

The Style looks like this:

And my usage like this:

<ToggleButton Grid.Column="0"
   Grid.Row="2"
   IsChecked="{Binding IsAutostop}"/>

I'd like to use the style AND be able to use the "IsChecked" Property.

EDIT

Thanks for the comments.

I open the window with a Service bound to a command in a taskbaricon.

The Service:

    class WindowService
    {
        public void OpenOptionsView(MainViewModel mvm)
        {
            OptionsView optionsView = new OptionsView { DataContext = mvm };
            optionsView.Show();
        }
    }

The important parts of the MainviewModel:

public ICommand OpenOptionsViewCommand { get; private set; }
public bool IsAutostop { get { return Settings.Default.Autostop; } set { Settings.Default.Autostop = value; Settings.Default.Save(); OnPropertyChanged(); } }

public MainViewModel()
{
   OpenOptionsViewCommand = new RelayCommand(OpenOptionsView, param => true);
}

private void OpenOptionsView(object o)
{
   WindowService ws = new WindowService();
   ws.OpenOptionsView(this);
}

I stored my TaskbarIcon in a seperated View:

   <tb:TaskbarIcon>
      <tb:TaskbarIcon.ContextMenu>
         <ContextMenu Background="#1e1e1e">
            <MenuItem Header="Programm öffnen"
                      Foreground="White"
                      Command="{Binding OpenOptionsViewCommand}"/>
         </ContextMenu>
      </tb:TaskbarIcon.ContextMenu>
   </tb:TaskbarIcon>

EDIT II:

I just found out, that the problem occurs when the bound value is True and the window should be opened with a checked Togglebutton.


问:
I am using rsa-pem-to-jwk But the result gives me Undefined
```<code>const fs = require("fs")
const rsaPemToJwk = require('rsa-pem-to-jwk')
const pem = fs.readFileSync('./certs/private.pem');
var jwk = rsaPemToJwk(pem, {use: 'sig'}, 'public');
console.log(jwk)
</code>```

this result:

Node.js v18.12.1
PS D:\ppp\JWKS-tutorial\auth-server> node covermtion.js
undefined

I added the private key instead of asking for it but it gave me the same result

```<code>const fs = require("fs")// fs.readFileSync('./certs/private.pem');
const rsaPemToJwk = require('rsa-pem-to-jwk')
const pem =
"-----BEGIN RSA PRIVATE KEY-----\n\
    MIIG4wIBAAKCAYEAxzZZa6MCLR/rYmQ9BRKK/tpJ736j8QFR3RrUC8TZKvhx6QIB\
    CULWvehctkjxkqREmfPbtQ1EkeoAfT68AeRd5CYpeucQrL1auZa6A0Wfjn5kRLIf\
    5U8e7G+0eOd93GZ7BOLV5OgfkgX5Q4RYxAiHKc6zKqmFIBgj57oM00TcHF0lw7rv\
    wvLzF3lDpEkS9ib/XlqpyHBgKrcjdVhD5V6GAgEv6TJpd/HtrV4CKC3prZIIilAF\
    IUvVkHKT/F91XE6zo7IAyoFB+z/bTut7RQ4Eg1U3CtFxTjnBYxmPMIrqoUJDSdGt\
    hBoG1uprNzdSupY1dIwpVDEXWqaOnzePsOYQnLgnV5sPgZOC85UgszfUu+bHuFtb\
    tc+WZ7zBYYJzHGwraW/Jq5r9QwJ+8pJTh7ksS2ugV86s6Jxdg0dk6wMSd0NwQqfO\
    iehqNw7w/TbayrtXl7ZCtHCErtMsnJEwVFRYsW7XB85piRcOEih30Yrx40oLfYUD\
    mpAfdrUSuaAN9AR3AgMBAAECggGBAJVDmtK0q//Fp+fsNXBkiXMVekqRuCLvmzgx\
    TuqWjyXMTAWLs90NkLtwrG8EzsTSgnhcKKZLD7LJA57Ub6h3RQaatX/aPDtCEgV2\
    819aPohVGaoDUTTPCNudgzsIMN0AiHKLyDqg1m7iPPei5aPUw/nGX6a6p/35OIX7\

   \n -----END RSA PRIVATE KEY-----";

var jwk = rsaPemToJwk(pem, {use: 'sig'}, 'public');
console.log(jwk)
</code>```

this result:

Node.js v18.12.1
PS D:\ppp\JWKS-tutorial\auth-server> node covermtion.js
undefined

I want to transfer the private key via rsapemtojwk which gives me unknown result

Body:
const fs = require("fs")
const rsaPemToJwk = require('rsa-pem-to-jwk')
const pem = fs.readFileSync('./certs/private.pem');
var jwk = rsaPemToJwk(pem, {use: 'sig'}, 'public');
console.log(jwk)

this result:

Node.js v18.12.1
PS D:\ppp\JWKS-tutorial\auth-server> node covermtion.js
undefined

I added the private key instead of asking for it but it gave me the same result

const fs = require("fs")// fs.readFileSync('./certs/private.pem');
const rsaPemToJwk = require('rsa-pem-to-jwk')
const pem =
"-----BEGIN RSA PRIVATE KEY-----\n\
    MIIG4wIBAAKCAYEAxzZZa6MCLR/rYmQ9BRKK/tpJ736j8QFR3RrUC8TZKvhx6QIB\
    CULWvehctkjxkqREmfPbtQ1EkeoAfT68AeRd5CYpeucQrL1auZa6A0Wfjn5kRLIf\
    5U8e7G+0eOd93GZ7BOLV5OgfkgX5Q4RYxAiHKc6zKqmFIBgj57oM00TcHF0lw7rv\
    wvLzF3lDpEkS9ib/XlqpyHBgKrcjdVhD5V6GAgEv6TJpd/HtrV4CKC3prZIIilAF\
    IUvVkHKT/F91XE6zo7IAyoFB+z/bTut7RQ4Eg1U3CtFxTjnBYxmPMIrqoUJDSdGt\
    hBoG1uprNzdSupY1dIwpVDEXWqaOnzePsOYQnLgnV5sPgZOC85UgszfUu+bHuFtb\
    tc+WZ7zBYYJzHGwraW/Jq5r9QwJ+8pJTh7ksS2ugV86s6Jxdg0dk6wMSd0NwQqfO\
    iehqNw7w/TbayrtXl7ZCtHCErtMsnJEwVFRYsW7XB85piRcOEih30Yrx40oLfYUD\
    mpAfdrUSuaAN9AR3AgMBAAECggGBAJVDmtK0q//Fp+fsNXBkiXMVekqRuCLvmzgx\
    TuqWjyXMTAWLs90NkLtwrG8EzsTSgnhcKKZLD7LJA57Ub6h3RQaatX/aPDtCEgV2\
    819aPohVGaoDUTTPCNudgzsIMN0AiHKLyDqg1m7iPPei5aPUw/nGX6a6p/35OIX7\

   \n -----END RSA PRIVATE KEY-----";

var jwk = rsaPemToJwk(pem, {use: 'sig'}, 'public');
console.log(jwk)

this result:

Node.js v18.12.1
PS D:\ppp\JWKS-tutorial\auth-server> node covermtion.js
undefined

I want to transfer the private key via rsapemtojwk which gives me unknown result


问:
Thymeleaf, not getting the title and input in the same line
Here is the Thymeleaf code for taking user inputs and then put it into their respective square boxes, the title and user input is coming in different lines, how can I make it in single line.

<!DOCTYPE html>

BANK USE SECTION

        Sourcing Channel

        Branch

        DST

        DSA

        PBK

        Web

        ReferSales

            Other Channel (Specify)

        Source 1

        Source 2

        Source 3

        Source 4

        Branch Code

        LTS/CRMN No

        Sales Promo Code

        SM Emp Code

        SE Code

        DSA/DDSA Name

        ASM Emp Code

        TSE Code

        DSA /DDSA Vendor Code

        Dealer SE Code

        RSM Emp Code

        TL Code

        Village Name

        RBI Code

CUSTOMER SECTION (to be filled by the Customer in CAPITAL LETTERS)

                I wish to apply for below ticked (a) loan and request you to process the loan application as per details provided in the form

                Branch

                <th th:if="${someVariable<4}">

Welcome, Guest

        <div th:if="${#lists.size(item.branchDate)<0}">

Hi, User

        Personal

        Business

        Large Ticket Business

        Self Employed Professional

```

I want the out to be like this

But I am getting like this

I am new to Thymeleaf.

Body:
Here is the Thymeleaf code for taking user inputs and then put it into their respective square boxes, the title and user input is coming in different lines, how can I make it in single line.

<!DOCTYPE html>

BANK USE SECTION

        Sourcing Channel

        Branch

        DST

        DSA

        PBK

        Web

        ReferSales

            Other Channel (Specify)

        Source 1

        Source 2

        Source 3

        Source 4

        Branch Code

        LTS/CRMN No

        Sales Promo Code

        SM Emp Code

        SE Code

        DSA/DDSA Name

        ASM Emp Code

        TSE Code

        DSA /DDSA Vendor Code

        Dealer SE Code

        RSM Emp Code

        TL Code

        Village Name

        RBI Code

CUSTOMER SECTION (to be filled by the Customer in CAPITAL LETTERS)

                I wish to apply for below ticked (a) loan and request you to process the loan application as per details provided in the form

                Branch

                <th th:if="${someVariable<4}">

Welcome, Guest

        <div th:if="${#lists.size(item.branchDate)<0}">

Hi, User

        Personal

        Business

        Large Ticket Business

        Self Employed Professional

I want the out to be like this

But I am getting like this

I am new to Thymeleaf.


问:
TypeORM: How to order by a relation count
Mu question is similar as this but with a bit difference.

I have a Singer entity and a related Song entity

Singer entity

```<code>export class Singer {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany( type => Song, Song => Song.user )
    songs: Song[];

}
</code>```

Song entity

```<code>export class Song {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToOne( type => Singer, Singer => Singer.songs )
    singer: Singer;

}
</code>```

I want to get all Songs ordered by Singer count

I also searched the a lot but can't find an answer... I just found how to order by the relation field like this:

```<code>songRepository.find({
    order: {
        singer: {
            name: "ASC"
        }
    }
})
</code>```

There's a way to solve this without QueryBuilder?

Body:
Mu question is similar as this but with a bit difference.

I have a Singer entity and a related Song entity

Singer entity

export class Singer {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @OneToMany( type => Song, Song => Song.user )
    songs: Song[];

}

Song entity

export class Song {

    @PrimaryGeneratedColumn()
    id: number;

    @Column()
    name: string;

    @ManyToOne( type => Singer, Singer => Singer.songs )
    singer: Singer;

}

I want to get all Songs ordered by Singer count

I also searched the a lot but can't find an answer... I just found how to order by the relation field like this:

songRepository.find({
    order: {
        singer: {
            name: "ASC"
        }
    }
})

There's a way to solve this without QueryBuilder?


问:
how to deploy my express (node) + vue app on VPS-hosting with Hestia CP?
I want to deploy my app (node, vue, mysql) on VPS with Hestia CP. I already have a domain and want my app to work with it. How to do it? Read that nginx is required but didn't get clearly how to use it.

app.js (entry)

    import express, { urlencoded } from "express";

    import path from "path";

    import routes from "./routes/router.js"

    const __dirname = path.resolve();
    const router = express.Router();
    const app = express();
    const PORT = process.env.port ?? 5000;

    app.use(express.json())
    app.use(express.urlencoded({extended: false}))
    app.use(express.static(path.resolve(__dirname, "public")));
    app.use("/css", express.static(__dirname + "/node_modules/bootstrap/dist/css"));
    app.use(routes)

    app.set("view engine", "ejs");
    app.set("views", path.resolve(__dirname, "views"));

    app.listen(PORT, () => {
      console.log(`Server is running on ${PORT}`);
    });

```

I tried to use node app (before that provided files on hosting via file manager). Before depolying I used to launch my app with nodemon or node app.

Body:
I want to deploy my app (node, vue, mysql) on VPS with Hestia CP. I already have a domain and want my app to work with it. How to do it? Read that nginx is required but didn't get clearly how to use it.

app.js (entry)

    import express, { urlencoded } from "express";

    import path from "path";

    import routes from "./routes/router.js"

    const __dirname = path.resolve();
    const router = express.Router();
    const app = express();
    const PORT = process.env.port ?? 5000;

    app.use(express.json())
    app.use(express.urlencoded({extended: false}))
    app.use(express.static(path.resolve(__dirname, "public")));
    app.use("/css", express.static(__dirname + "/node_modules/bootstrap/dist/css"));
    app.use(routes)

    app.set("view engine", "ejs");
    app.set("views", path.resolve(__dirname, "views"));

    app.listen(PORT, () => {
      console.log(`Server is running on ${PORT}`);
    });

I tried to use node app (before that provided files on hosting via file manager). Before depolying I used to launch my app with nodemon or node app.


问:
Flutter speech to text plugin continuous listening problem
Currently, I am developing an application which can connect an Arduino toy car and control it by voice commands using Bluetooth. For a better user experience, I display all the commands in a chat application user interface, so the user can see the commands he spoke (see the picture). But the problem is when the user spoke a sentence (more than 2 words), it split those words and adds them to the chat messages list separately while speaking. I need to hold this until the user finishes his speaking, and then add it to the chat messages list as a sentence. Not as separate words. I used flutter speech_to_text plugin. Let me know If you need additional information.

Here is the listening function

```<code>bool _isListening = false;
  String _text = '';
  late stt.SpeechToText _speech;

void _listen() async {
    if (!_isListening) {
      bool available = await _speech.initialize(
        onStatus: (val) => print('onStatus: $val'),
        onError: (val) => print('onError: $val'),
      );
      if (available) {
        setState(() => _isListening = true);
        _speech.listen(
            onResult: (val) {
              setState(() {
                _text = val.recognizedWords.toLowerCase();
                if (val.recognizedWords
                    .toLowerCase()
                    .contains('come back')) {
                  _cocoCommandInput = 7;

                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                  _isListening = false;
                } else if (val.recognizedWords.toLowerCase().contains('coco')) {
                  _cocoCommandInput = 8;

                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                  _isListening = false;
                } else {
                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                }
              });
            });
      }
    } else {
      setState(() => _isListening = false);
      _speech.stop();
      _text = 'Press the button and start speaking';
    }
  }
</code>```

Here is the function for adding the messages to the chat messages list

```<code>void _addVoiceTextToChat(String text, String date) async {
    if (text.isNotEmpty) {
      try {
        // connection!.output.add(Uint8List.fromList(utf8.encode("$text\r\n")));
        // await connection!.output.allSent;
        setState(() {
          messages.add(_Message(text: text, date: date));
        });

        Future.delayed(const Duration(milliseconds: 300)).then((_) {
          listScrollController.animateTo(
              listScrollController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut);
        });
      } catch (e) {
        print('shit something is wrong');
        // setState(() {});
      }
    }
  }
</code>```

Here is the chat bubble list

```<code>Widget build(BuildContext context) {
    final List<Row> list = messages.map((message) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                message.date,
                style: greyText,
              ),
              Container(
                padding: const EdgeInsets.all(12.0),
                margin: const EdgeInsets.only(bottom: 8.0, right: 8.0),
                decoration: const BoxDecoration(
                  color: Colors.deepOrange,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(6),
                    topRight: Radius.circular(25),
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25),
                  ),
                ),
                child: Text(
                    (text) {
                      return text == '/shrug' ? '¯\\_(ツ)_/¯' : text;
                    }(message.text.trim()),
                    style: whiteText),
              ),
            ],
          ),
        ],
      );
    }).toList();
</code>```

Body:
Currently, I am developing an application which can connect an Arduino toy car and control it by voice commands using Bluetooth. For a better user experience, I display all the commands in a chat application user interface, so the user can see the commands he spoke (see the picture). But the problem is when the user spoke a sentence (more than 2 words), it split those words and adds them to the chat messages list separately while speaking. I need to hold this until the user finishes his speaking, and then add it to the chat messages list as a sentence. Not as separate words. I used flutter speech_to_text plugin. Let me know If you need additional information.

Here is the listening function

bool _isListening = false;
  String _text = '';
  late stt.SpeechToText _speech;

void _listen() async {
    if (!_isListening) {
      bool available = await _speech.initialize(
        onStatus: (val) => print('onStatus: $val'),
        onError: (val) => print('onError: $val'),
      );
      if (available) {
        setState(() => _isListening = true);
        _speech.listen(
            onResult: (val) {
              setState(() {
                _text = val.recognizedWords.toLowerCase();
                if (val.recognizedWords
                    .toLowerCase()
                    .contains('come back')) {
                  _cocoCommandInput = 7;

                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                  _isListening = false;
                } else if (val.recognizedWords.toLowerCase().contains('coco')) {
                  _cocoCommandInput = 8;

                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                  _isListening = false;
                } else {
                  _addVoiceTextToChat(
                      _text, DateFormat.jms().format(DateTime.now()));
                }
              });
            });
      }
    } else {
      setState(() => _isListening = false);
      _speech.stop();
      _text = 'Press the button and start speaking';
    }
  }

Here is the function for adding the messages to the chat messages list

void _addVoiceTextToChat(String text, String date) async {
    if (text.isNotEmpty) {
      try {
        // connection!.output.add(Uint8List.fromList(utf8.encode("$text\r\n")));
        // await connection!.output.allSent;
        setState(() {
          messages.add(_Message(text: text, date: date));
        });

        Future.delayed(const Duration(milliseconds: 300)).then((_) {
          listScrollController.animateTo(
              listScrollController.position.maxScrollExtent,
              duration: const Duration(milliseconds: 300),
              curve: Curves.easeOut);
        });
      } catch (e) {
        print('shit something is wrong');
        // setState(() {});
      }
    }
  }

Here is the chat bubble list

Widget build(BuildContext context) {
    final List<Row> list = messages.map((message) {
      return Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                message.date,
                style: greyText,
              ),
              Container(
                padding: const EdgeInsets.all(12.0),
                margin: const EdgeInsets.only(bottom: 8.0, right: 8.0),
                decoration: const BoxDecoration(
                  color: Colors.deepOrange,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(6),
                    topRight: Radius.circular(25),
                    bottomLeft: Radius.circular(25),
                    bottomRight: Radius.circular(25),
                  ),
                ),
                child: Text(
                    (text) {
                      return text == '/shrug' ? '¯\\_(ツ)_/¯' : text;
                    }(message.text.trim()),
                    style: whiteText),
              ),
            ],
          ),
        ],
      );
    }).toList();


问:
Docker volume plugin: Where are the logs?
I am trying to learn how to utilize the RClone Docker plugin to declutter my mounting strategy. Since most of my storage is remote and not on-device, I had previously just used bind mounts to the actual Linux mounts which were provided via RClone through fstab.

So in order to make that a little cleaner and store configurations better, I am largely using Docker Compose and now I am starting to add the RClone plugin to the configurations.

Problem is: How do I get the logs? So far, I couldn't interact with the RClone plugin at all aside from en- or disabling it and setting a few default arguments. That said, passing --log-file ... caused an error. However, docker logs is already a command and I am pretty sure I am able to query plugin logs too.

But how? I installed the plugin by aliasing it as rclone.


问:
Attribute error, cant use a imported library function in class object
```<code>from machine import Pin,SPI,PWM
import framebuf
import time
import os
import random

BL = 13
DC = 8
RST = 12
MOSI = 11
SCK = 10
CS = 9

class LCD_1inch3(framebuf.FrameBuffer): # For 320x240 display
    framebuf =__import__('framebuf')
    def __init__(self):
        self.width = 320
        self.height = 240

        self.cs = Pin(CS,Pin.OUT)
        self.rst = Pin(RST,Pin.OUT)

        self.cs(1)
        self.spi = SPI(1)
        self.spi = SPI(1,1000_000)
        self.spi = SPI(1,100000_000,polarity=0, phase=0,sck=Pin(SCK),mosi=Pin(MOSI),miso=None)
        self.dc = Pin(DC,Pin.OUT)
        self.dc(1)
        self.buffer = bytearray(self.height * self.width * 2)
        super().__init__(self.buffer, self.width, self.height, framebuf.RGB565)
        self.init_display()

        self.RED   =   0x07E0
        self.GREEN =   0x001f
        self.BLUE  =   0xf800
        self.WHITE =   0xffff
        self.BLACK =   0x0000
        self.YELLOW=   0x07FF
</code>```
```<code>    def eyes2(self):
        self.ellipse(10,10, 10, 10, LCD.BLACK)
</code>```

I keep getting "AttributeError: 'LCD_1inch3' object has no attribute 'poly'" and idk y.

I can use the other ones in the framebuffer imported library like vline(), hline(), line(), rect(), fill() and text() but thats around it. Ive been trying to be able to use poly() and ellipse() but no success

Body:
from machine import Pin,SPI,PWM
import framebuf
import time
import os
import random

BL = 13
DC = 8
RST = 12
MOSI = 11
SCK = 10
CS = 9

class LCD_1inch3(framebuf.FrameBuffer): # For 320x240 display
    framebuf =__import__('framebuf')
    def __init__(self):
        self.width = 320
        self.height = 240

        self.cs = Pin(CS,Pin.OUT)
        self.rst = Pin(RST,Pin.OUT)

        self.cs(1)
        self.spi = SPI(1)
        self.spi = SPI(1,1000_000)
        self.spi = SPI(1,100000_000,polarity=0, phase=0,sck=Pin(SCK),mosi=Pin(MOSI),miso=None)
        self.dc = Pin(DC,Pin.OUT)
        self.dc(1)
        self.buffer = bytearray(self.height * self.width * 2)
        super().__init__(self.buffer, self.width, self.height, framebuf.RGB565)
        self.init_display()

        self.RED   =   0x07E0
        self.GREEN =   0x001f
        self.BLUE  =   0xf800
        self.WHITE =   0xffff
        self.BLACK =   0x0000
        self.YELLOW=   0x07FF

    def eyes2(self):
        self.ellipse(10,10, 10, 10, LCD.BLACK)

I keep getting "AttributeError: 'LCD_1inch3' object has no attribute 'poly'" and idk y.

I can use the other ones in the framebuffer imported library like vline(), hline(), line(), rect(), fill() and text() but thats around it. Ive been trying to be able to use poly() and ellipse() but no success


问:
How can I remove form-control class?
I need to remove the form-control class on an element of a form because it applies padding. This class is automatically added when creating the form.
And I don't want padding on any of these form lines...But how to do it ?
Here is my code :

Form : only the part of the form on which I don't want "form-control" class.

```<code>->add('progress', RangeType::class, [
                'label' => 'kpi.form.progress',
                'attr' => [
                    'min' => 0,
                    'max' => 100,
                ],
            ])

</code>```

Twig :

```<code>{% for formTeamOKR in formCompanyOKR.teamOKRs %}
   {% for formKPI in formTeamOKR.KPIs %}
       {% if formKPI.vars.data.id == kpi.id %}
          {{ form_row(formKPI) }}
       {% endif %}
    {% endfor %}
{% endfor %}
</code>```

I tried to use this :
How to prevent Twig from adding form-control class to the fields it generates?

and this : Symfony Add bootstrap form-control class

and to add this in my twig :

```<code>{% set attr = {class: (attr.class|default(''))|trim} %}
</code>```

just before :

```<code>{{ form_row(formKPI) }}
</code>```

Thanks!!!

Title: How can I remove form-control class?

Body:
I need to remove the form-control class on an element of a form because it applies padding. This class is automatically added when creating the form.
And I don't want padding on any of these form lines...But how to do it ?
Here is my code :

Form : only the part of the form on which I don't want "form-control" class.

->add('progress', RangeType::class, [
                'label' => 'kpi.form.progress',
                'attr' => [
                    'min' => 0,
                    'max' => 100,
                ],
            ])

Twig :

{% for formTeamOKR in formCompanyOKR.teamOKRs %}
   {% for formKPI in formTeamOKR.KPIs %}
       {% if formKPI.vars.data.id == kpi.id %}
          {{ form_row(formKPI) }}
       {% endif %}
    {% endfor %}
{% endfor %}

I tried to use this :
How to prevent Twig from adding form-control class to the fields it generates?

and this : Symfony Add bootstrap form-control class

and to add this in my twig :

{% set attr = {class: (attr.class|default(''))|trim} %}

just before :

{{ form_row(formKPI) }}

Thanks!!!


问:
MUI Select selection with keyboard doesn't work as expected with Turkish letter "ı"
I'am using Material UI v5(Select Component) in my NextJS application. I have encountered a problem when i try to make a selection with my keyboard.

1- user types "o" and the input focus matches the city "Ordu" **CORRECT **
2- user types "ı" and the input focus doesn't match with "Iğdır" or "Istanbul" NOT CORRECT
3- user types "i" and the input focus matches with "Iğdır" and "İstanbul" NOT CORRECT

in the scenario when user types "ı" it should only match with "Iğdır" and "i" should match with "İstanbul"

I tried to find the solution in MUI's Select API documentation but it didn't help me with my problem. Can someone help me with this problem?


问:
EKS and IRSA temporary credentials duration validity
I am facing a challenge with my EKS cluster and IRSA.

I have created a service account in K8 associated with an AWS role, via the eksctl create iamserviceaccount.. command. After that, I have modified the maximum session duration of the role in the AWS console, setting it to 12 hours.

I then used said service account in my deployment. Everything looks good once the workload runs in the cluster and my pod is able to assume the associated AWS role.

Whenever the pod executes an action that requires IAM auth, boto3 issues a AssumeRoleWithWebIdentity call and a set of temporary credentials are returned by AWS IAM (point 4 and 5 in the diagram below, source https://aws.amazon.com/blogs/containers/diving-into-iam-roles-for-service-accounts/). These credentials (by looking in CloudTrail) last 1 hour, and this is in line with the default duration_seconds for such call (see here https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithWebIdentity.html).

I want those credentials to last more than 1 hour, I'd like for those to last 12 hours. The only way to achieve so, as far as I understood, is to specify durations_seconds in the $HOME/.aws/config file within the pod. After implementing that and testing again, I saw that the temporary credentials still last 1 hour. At this point, I have no idea how to change the duration behaviour. Has anyone ever encountered this situation? If yes, how was this solved?

Note: The OIDC JWT token lasts 24 hours, as I specified in the annotation eks.amazonaws.com/token-expiration: 86400

Thanks!
Alessio


问:
How to write df.query to select all columns from a dataframe with NaN?
I have the following code which returns a df with all columns having NaN values:

```<code>df.loc[:, df.isna().any()]
</code>```

How would I write this code using df.query?

Body:
I have the following code which returns a df with all columns having NaN values:

df.loc[:, df.isna().any()]

How would I write this code using df.query?


问:
AWS Cognito: How to assign the Group memberships to the user using amazon-cognito-identity-js?
I am using AWS-Cognito for authentication in the React.js application. I am using hosted UI of AWS-Cognito to get the access_token and id_token. I want to add selective Group memberships like "cognito:manage_menu" etc in AWS-Cognito when the user sign-up into the application using 'amazon-cognito-identity-js'.

Kindly guide me. Thanks


问:
Installing Brew On Mac Not Working And Returns Error
I went to this website https://brew.sh and copied the command from there and paste that into my terminal:

```<code>/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
</code>```

But after some moments, I get this response:

So what's going wrong here?

Body:
I went to this website https://brew.sh and copied the command from there and paste that into my terminal:

/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

But after some moments, I get this response:

So what's going wrong here?


问:
How to pass the path of a file to a Python script in a different directory
I have a script in a different folder: a/b/c/my_script.py

I need to execute it in x/y/z/ so that my_script.py will take the path of x/y/z/my_file.txt, modify it and open the same file in another folder: x/y/q/w/e/my_file.txt

How can I do that in Python?

I can do

# my_script.py
import sys
argv = sys.argv[1]
// change the path
// open the file in the other path
```
<p>then call <code>my_script.py</code> this way:</p>
```pwd
x/y/z/
python a/b/c/my_script.py $(pwd) my_file.txt
```

but I wonder if there's a better way.

Note: I've tried using bash function but it seems more complicated to parse strings.

Body:
I have a script in a different folder: a/b/c/my_script.py

I need to execute it in x/y/z/ so that my_script.py will take the path of x/y/z/my_file.txt, modify it and open the same file in another folder: x/y/q/w/e/my_file.txt

How can I do that in Python?

I can do

# my_script.py
import sys
argv = sys.argv[1]
// change the path
// open the file in the other path

then call my_script.py this way:

pwd
x/y/z/
python a/b/c/my_script.py $(pwd) my_file.txt

but I wonder if there's a better way.

Note: I've tried using bash function but it seems more complicated to parse strings.