问:
How do I implement a memory arena allocator to reduce memory request calls in a trie-based spell checker?
As part of the cs50x course, I made a trie-based dictionary spell checker that passes all of check50's tests as well as valgrind so no memory errors. Now I'm trying to implement a memory bucket to reduce malloc requests.

Here's my code:

dictionary.h

```<code>// Declares a dictionary's functionality

#ifndef DICTIONARY_H
#define DICTIONARY_H

#include <stdbool.h>

// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45
#define N 27
// Trie node definition
typedef struct TrieNode
{
    struct TrieNode *children[N];
    bool isEnd;
} TrieNode;

// Prototypes
bool check(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool unload(void);

TrieNode *create_trie(void);
bool trie_insert(TrieNode **head, const char *word);
void trie_clear(TrieNode *root_ref);

#endif // DICTIONARY_H
</code>```

dictionary.c

```<code>#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dictionary.h"

// Macros
#define key(c) (c>='a'&&c<='z')?(c-'a'):(c>='A'&&c<='Z')?(c-'A'):26

// word count
unsigned int word_count = 0;

// Root trie node
TrieNode *root;

// Returns true if word is in dictionary, else false
bool check(const char *word)
{
    // Declare tmp ptr to root
    TrieNode *tmp = root;

    for (int i = 0 , n = strlen(word); i < n; i++)
    {
        int t = key(word[i]);
        if (tmp->children[t] == NULL)
        {
            return false;
        }
        tmp = tmp->children[t];
    }
    // Did index values lead to valid terminal?
    return tmp->isEnd;
}

TrieNode *create_trie(void)
{
    TrieNode *result = malloc(sizeof(*result));
    for (int i = 0; i < N; i++)
    {
        result->children[i] = NULL;
    }
    result->isEnd = false;
    return result;
}

// Double ptr allows us to alter the root node
bool trie_insert(TrieNode **head, const char *word)
{
    if (*head == NULL)
    {
        *head = create_trie();
    }

    TrieNode *tmp = *head;

    for (int i = *word++; *word; i = *word++)
    {
        unsigned int t = key(i);
        if (tmp->children[t] == NULL)
        {
            tmp->children[t] = create_trie();
        }
        tmp = tmp->children[t];
    }
    tmp->isEnd = true;
    return true;
}

// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
    // open dictionary file
    FILE *dict = fopen(dictionary, "rb");
    if (!dict)
    {
        return false;
    }
    // allocate more memory than needed for LENGTH chars
    char *word = malloc(sizeof(char) * LENGTH + 2);
    if (!word)
    {
        fclose(dict);
        return false;
    }
    // Keep reading infile word by word until NULL
    while (fgets(word, LENGTH + 2, dict))
    {
        // Skip all words that exceed length limit
        size_t word_length = strlen(word);
        if (word_length > LENGTH + 1)
        {
            break;
        }

        if (trie_insert(&root, word))
        {
            word_count++;
        }
    }

    // Free buffer and close infile
    free(word);
    fclose(dict);
    return true;
}

bool unload(void)
{
    trie_clear(root);
    return true;
}

void trie_clear(TrieNode *root_ref)
{
    TrieNode *tmp = root_ref;

    for (int i = 0; i < N; i++)
    {
        if (tmp->children[i])
        {
            trie_clear(tmp->children[i]);
        }
    }
    free(tmp);
}

// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
    return word_count;
}
</code>```

My results:

```<code>
My solution                                             Staff solution

WORDS MISSPELLED:     955                               WORDS MISSPELLED:     955
WORDS IN DICTIONARY:  143091                            WORDS IN DICTIONARY:  143091
WORDS IN TEXT:        17756                             WORDS IN TEXT:        17756
TIME IN load:         0.08                            | TIME IN load:         0.03
TIME IN check:        0.02                              TIME IN check:        0.02
TIME IN size:         0.00                              TIME IN size:         0.00
TIME IN unload:       0.04                            | TIME IN unload:       0.01
TIME IN TOTAL:        0.14                            | TIME IN TOTAL:        0.06
</code>```

CURRENT OBSTACLE:
Right now I think the most plausible explanation for my slower loading time is that I'm performing memory requests one trie node. During my research, I came across a lot of comments recommending some variation of a memory pool solution for reducing the total number of malloc requests made. The idea was to request a bunch of memory upfront and feed individual pieces of it to the insert function as needed. However, many of these comments only included a wiki article link without any further elaboration.

The only working solution I did come across was designed for a hash table spell checker. This implementation requests memory for an large array of hash nodes in a single block, and every subsequent block requested would be connected as a singly linked list.

Here's their hash node definition:

```<code>typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
    unsigned int hash;
} node;
</code>```

Their memory segment definition:

```<code>// adjust this value to suit
#define ARENASIZE       1000

// Structure for slab allocation of 1000 hash nodes as a linked list
typedef struct seg seg_t;
struct seg
{
    seg_t *seg_next;                // next segment
    int seg_count;                  // number of used nodes in this segment
    node seg_node[ARENASIZE];       // nodes in this segment
};
</code>```

If I'm adapting this structure to my dictionary by substituting the array of hashnodes with an array of trienodes, is there anything I need to do differently or can I just the datatype to TrieNode seg_node[ARENASIZE]?

UPDATE
Thanks to Craig Estey, I've successfully added the memory arena allocation function to my existing code. To my surprise this didn't actually reduce the loading time at all but the unloading times were basically reduced to zero which is still a win. Similarly, since I'm now able to use calloc instead of malloc, my lookup times are also consistently equal or faster than the staff solution. Now my spell checker is consistently slower than the staff solution by only around 0.02s to 0.04s

```<code>WORDS MISSPELLED:     12544                 WORDS MISSPELLED:     12544
WORDS IN DICTIONARY:  143091                WORDS IN DICTIONARY:  143091
WORDS IN TEXT:        265867                WORDS IN TEXT:        265867
TIME IN load:         0.07                | TIME IN load:         0.03
TIME IN check:        0.24                | TIME IN check:        0.26
TIME IN size:         0.00                  TIME IN size:         0.00
TIME IN unload:       0.00                | TIME IN unload:       0.02
TIME IN TOTAL:        0.32                | TIME IN TOTAL:        0.30
</code>```

Body:
As part of the cs50x course, I made a trie-based dictionary spell checker that passes all of check50's tests as well as valgrind so no memory errors. Now I'm trying to implement a memory bucket to reduce malloc requests.

Here's my code:

dictionary.h

// Declares a dictionary's functionality

#ifndef DICTIONARY_H
#define DICTIONARY_H

#include <stdbool.h>

// Maximum length for a word
// (e.g., pneumonoultramicroscopicsilicovolcanoconiosis)
#define LENGTH 45
#define N 27
// Trie node definition
typedef struct TrieNode
{
    struct TrieNode *children[N];
    bool isEnd;
} TrieNode;

// Prototypes
bool check(const char *word);
bool load(const char *dictionary);
unsigned int size(void);
bool unload(void);

TrieNode *create_trie(void);
bool trie_insert(TrieNode **head, const char *word);
void trie_clear(TrieNode *root_ref);

#endif // DICTIONARY_H

dictionary.c

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "dictionary.h"

// Macros
#define key(c) (c>='a'&&c<='z')?(c-'a'):(c>='A'&&c<='Z')?(c-'A'):26

// word count
unsigned int word_count = 0;

// Root trie node
TrieNode *root;

// Returns true if word is in dictionary, else false
bool check(const char *word)
{
    // Declare tmp ptr to root
    TrieNode *tmp = root;

    for (int i = 0 , n = strlen(word); i < n; i++)
    {
        int t = key(word[i]);
        if (tmp->children[t] == NULL)
        {
            return false;
        }
        tmp = tmp->children[t];
    }
    // Did index values lead to valid terminal?
    return tmp->isEnd;
}

TrieNode *create_trie(void)
{
    TrieNode *result = malloc(sizeof(*result));
    for (int i = 0; i < N; i++)
    {
        result->children[i] = NULL;
    }
    result->isEnd = false;
    return result;
}

// Double ptr allows us to alter the root node
bool trie_insert(TrieNode **head, const char *word)
{
    if (*head == NULL)
    {
        *head = create_trie();
    }

    TrieNode *tmp = *head;

    for (int i = *word++; *word; i = *word++)
    {
        unsigned int t = key(i);
        if (tmp->children[t] == NULL)
        {
            tmp->children[t] = create_trie();
        }
        tmp = tmp->children[t];
    }
    tmp->isEnd = true;
    return true;
}

// Loads dictionary into memory, returning true if successful, else false
bool load(const char *dictionary)
{
    // open dictionary file
    FILE *dict = fopen(dictionary, "rb");
    if (!dict)
    {
        return false;
    }
    // allocate more memory than needed for LENGTH chars
    char *word = malloc(sizeof(char) * LENGTH + 2);
    if (!word)
    {
        fclose(dict);
        return false;
    }
    // Keep reading infile word by word until NULL
    while (fgets(word, LENGTH + 2, dict))
    {
        // Skip all words that exceed length limit
        size_t word_length = strlen(word);
        if (word_length > LENGTH + 1)
        {
            break;
        }

        if (trie_insert(&root, word))
        {
            word_count++;
        }
    }

    // Free buffer and close infile
    free(word);
    fclose(dict);
    return true;
}

bool unload(void)
{
    trie_clear(root);
    return true;
}

void trie_clear(TrieNode *root_ref)
{
    TrieNode *tmp = root_ref;

    for (int i = 0; i < N; i++)
    {
        if (tmp->children[i])
        {
            trie_clear(tmp->children[i]);
        }
    }
    free(tmp);
}

// Returns number of words in dictionary if loaded, else 0 if not yet loaded
unsigned int size(void)
{
    return word_count;
}

My results:

My solution                                             Staff solution

WORDS MISSPELLED:     955                               WORDS MISSPELLED:     955
WORDS IN DICTIONARY:  143091                            WORDS IN DICTIONARY:  143091
WORDS IN TEXT:        17756                             WORDS IN TEXT:        17756
TIME IN load:         0.08                            | TIME IN load:         0.03
TIME IN check:        0.02                              TIME IN check:        0.02
TIME IN size:         0.00                              TIME IN size:         0.00
TIME IN unload:       0.04                            | TIME IN unload:       0.01
TIME IN TOTAL:        0.14                            | TIME IN TOTAL:        0.06

CURRENT OBSTACLE:
Right now I think the most plausible explanation for my slower loading time is that I'm performing memory requests one trie node. During my research, I came across a lot of comments recommending some variation of a memory pool solution for reducing the total number of malloc requests made. The idea was to request a bunch of memory upfront and feed individual pieces of it to the insert function as needed. However, many of these comments only included a wiki article link without any further elaboration.

The only working solution I did come across was designed for a hash table spell checker. This implementation requests memory for an large array of hash nodes in a single block, and every subsequent block requested would be connected as a singly linked list.

Here's their hash node definition:

typedef struct node
{
    char word[LENGTH + 1];
    struct node *next;
    unsigned int hash;
} node;

Their memory segment definition:

// adjust this value to suit
#define ARENASIZE       1000

// Structure for slab allocation of 1000 hash nodes as a linked list
typedef struct seg seg_t;
struct seg
{
    seg_t *seg_next;                // next segment
    int seg_count;                  // number of used nodes in this segment
    node seg_node[ARENASIZE];       // nodes in this segment
};

If I'm adapting this structure to my dictionary by substituting the array of hashnodes with an array of trienodes, is there anything I need to do differently or can I just the datatype to TrieNode seg_node[ARENASIZE]?

UPDATE
Thanks to Craig Estey, I've successfully added the memory arena allocation function to my existing code. To my surprise this didn't actually reduce the loading time at all but the unloading times were basically reduced to zero which is still a win. Similarly, since I'm now able to use calloc instead of malloc, my lookup times are also consistently equal or faster than the staff solution. Now my spell checker is consistently slower than the staff solution by only around 0.02s to 0.04s

WORDS MISSPELLED:     12544                 WORDS MISSPELLED:     12544
WORDS IN DICTIONARY:  143091                WORDS IN DICTIONARY:  143091
WORDS IN TEXT:        265867                WORDS IN TEXT:        265867
TIME IN load:         0.07                | TIME IN load:         0.03
TIME IN check:        0.24                | TIME IN check:        0.26
TIME IN size:         0.00                  TIME IN size:         0.00
TIME IN unload:       0.00                | TIME IN unload:       0.02
TIME IN TOTAL:        0.32                | TIME IN TOTAL:        0.30


来源: stackexchange

问:
Icon in picture which allows user to download the picture
I want to display four images in 2x2 style with icon on the top right hand side of each picture.

  <el-image class="image-single-mr10"
    style="height: 250px; width: 250px; display:inline-block; position:relative"
    v-for="pic in testUrls"
    :key="pic"
    :src="getTestURL(pic)"
  />

    OVERLAY

```

I am using el image in relative position. And I tried to use span to simulate the icon. However, I could not get span overlay on images. Moreover, I need to span four times to have each icon on top of the images. How should I do it?

ContentLicense: CC BY-SA 4.0

Body:
I want to display four images in 2x2 style with icon on the top right hand side of each picture.

  <el-image class="image-single-mr10"
    style="height: 250px; width: 250px; display:inline-block; position:relative"
    v-for="pic in testUrls"
    :key="pic"
    :src="getTestURL(pic)"
  />

    OVERLAY

I am using el image in relative position. And I tried to use span to simulate the icon. However, I could not get span overlay on images. Moreover, I need to span four times to have each icon on top of the images. How should I do it?


问:
Why does my function in Javascript not clear the div container I want it to?
So in this following code I tried to clear the  after
I added some Text (in this case they represent ingredients for a shopping list) to the div. Im fairly new to Javascript and dont have that much expirience yet so any help would be much appreciated!</p>
```<code><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button id="apple" onclick="apple()">Apple</button>
    <button id="tomato" onclick="tomato()">Tomato</button>
    <button id="eggs" onclick="eggs()">Eggs</button>
    <button id="clear" onclick="clear()">Clear</button>
    <div id="cart"></div>

    <script>

        const cart = document.getElementById('cart');

        function apple(){
            let div = document.createElement('div');
            let foodItem = document.getElementById('apple');
            div.textContent = 'Apple';
            cart.appendChild(div);
        }
        function tomato(){
            let divTwo = document.createElement('div');
            let foodItem = document.getElementById('tomato');
            divTwo.textContent = 'Tomatos';
            cart.appendChild(divTwo);
        }
        function eggs(){
            let divThree = document.createElement('div');
            let foodItem = document.getElementById('eggs');
            divThree.textContent = 'Eggs';
            cart.appendChild(divThree);
        }
        function clear(){
            document.getElementById('cart').innerHTML = '';
        }
    </script>
</body>
</html>
</code>```

Body:
So in this following code I tried to clear the  after
I added some Text (in this case they represent ingredients for a shopping list) to the div. Im fairly new to Javascript and dont have that much expirience yet so any help would be much appreciated!

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>

    <button id="apple" onclick="apple()">Apple</button>
    <button id="tomato" onclick="tomato()">Tomato</button>
    <button id="eggs" onclick="eggs()">Eggs</button>
    <button id="clear" onclick="clear()">Clear</button>


问:
Unable to retrieve and deploy package salesforce visual code studio
I am facing this issue: "Error deploying or retrieving source: The file or directory that you tried to deploy or retrieve isn't in a package directory that's specified in your sfdx-project.json file"
There is another post with this similar error but not able to fix with those answers.
https://salesforce.stackexchange.com/questions/380221/error-deploying-or-retrieving-source

I am using:

jdk 17

sfdx-cli/7.181.1 win32-x64 node-v18.12.1

Version: 1.74.1 (user setup)
Commit: 1ad8d514439d5077d2b0b7ee64d2ce82a9308e5a
Date: 2022-12-14T10:30:51.966Z
Electron: 19.1.8
Chromium: 102.0.5005.167
Node.js: 16.14.2
V8: 10.2.154.15-electron.0
OS: Windows_NT x64 10.0.22621
Sandboxed: No

Windows 11

Another issue is

{ "packageDirectories": [
{
"path": "force-app",
"default": true
}
],
"name": "IvannaDevs",
"namespace": "",
"sfdcLoginUrl": "https://login.salesforce.com",
"sourceApiVersion": "55.0"
}

Any ideas about what is wrong here?


问:
How to automatically wrap texts when it reaches the edge of a container in Flet?
How to automatically wrap texts when it reaches the edge of a container in Flet? Now it just extends infinitely. If i use \n, it may not fit all windows sizes.


问:
How can I inflate the layout inside ProductsAdapter extends FirestoreRecyclerAdapter in a fragment?
I would like to be able to assign the id of these TextView but I need the root that I assigned previously in onCreateView, then I don't know what to do to be able to inflate it, try the following;

```<code>View root;
        root = inflater.inflate(R.layout.fragment_products, container, false);
View.inflate(R.layout.fragment_products, null);

</code>```

I have the code as follows;

```<code>
package com.example.doit_venta_v2;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProductosFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root;
        root = inflater.inflate(R.layout.fragment_productos, container, false);

        Button buttonnew = (Button) root.findViewById(R.id.button7);

        buttonnew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogNewProductFragment DNPF = new DialogNewProductFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.ContainerView,DNPF)
                        .addToBackStack(null).commit();

            }
        });

        return root;

    }
}

class ProductosAdapter extends FirestoreRecyclerAdapter<Productos, ProductosAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView TextViewProducto;
        TextView TextViewTipo;
        TextView TextViewCantidad;
        TextView textViewUnidad;
        TextView textViewValor;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            TextViewCantidad = (TextView) View.inflate(R.layout.fragment_productos,null)
            TextViewProducto = View.findViewById(R.id.TextViewProducto);
        }
    }

}

</code>```

As you can see, in the fragment of class ProductsAdapter extends FirestoreRecyclerAdapter<Products, ProductsAdapter.ViewHolder> { I am calling a class Products that allows to take data from a database in Firebase but below I want to relate the ids of the Layout.

I get more or less the following error ;

Body:
I would like to be able to assign the id of these TextView but I need the root that I assigned previously in onCreateView, then I don't know what to do to be able to inflate it, try the following;

View root;
        root = inflater.inflate(R.layout.fragment_products, container, false);
View.inflate(R.layout.fragment_products, null);

I have the code as follows;

package com.example.doit_venta_v2;

import android.app.AlertDialog;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

public class ProductosFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View root;
        root = inflater.inflate(R.layout.fragment_productos, container, false);

        Button buttonnew = (Button) root.findViewById(R.id.button7);

        buttonnew.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogNewProductFragment DNPF = new DialogNewProductFragment();
                getActivity().getSupportFragmentManager().beginTransaction().replace(R.id.ContainerView,DNPF)
                        .addToBackStack(null).commit();

            }
        });

        return root;

    }
}

class ProductosAdapter extends FirestoreRecyclerAdapter<Productos, ProductosAdapter.ViewHolder> {

    public class ViewHolder extends RecyclerView.ViewHolder {

        TextView TextViewProducto;
        TextView TextViewTipo;
        TextView TextViewCantidad;
        TextView textViewUnidad;
        TextView textViewValor;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            TextViewCantidad = (TextView) View.inflate(R.layout.fragment_productos,null)
            TextViewProducto = View.findViewById(R.id.TextViewProducto);
        }
    }

}

As you can see, in the fragment of class ProductsAdapter extends FirestoreRecyclerAdapter<Products, ProductsAdapter.ViewHolder> { I am calling a class Products that allows to take data from a database in Firebase but below I want to relate the ids of the Layout.

I get more or less the following error ;


问:
Extract index values from groupby using numpy array
I'm trying to extract 7 rows of data grouped by the DTY column in a Dataframe. I think I need to use a numpy array to filter, but can't seem to get it working.

Here's an extract of my original CLimate_DF dataframe (note there are NaN values for the :

Year    Month   Day DTY Precip9am    MaxT    ...    Wind ms 21 hr
1989    1   1   1   0        29.7    ...    0
1989    1   2   2   0        31.1    ...    4.6
1989    1   3   3   0.4      32      ...    2.1
... ... ... ... ...      ...     ...    ...
2019    12  31  365 21.2         31.3    ...    2.1

First, I created a numpy array filter based on a given date - this works and creates the right array:

#Enter Day of Interest (DOI) yyyy, mm, dd

```<code>DOI = datetime.datetime(2020, 2, 6)
DTY = DOI.timetuple()[7]
DTYMinus3 = DTY-3
DTYPlus3 = DTY+3
DTY_Array = np.linspace(DTYMinus3, DTYPlus3,7)
DTY_Array = np.array(DTY_Array)
</code>```

I now want to extract all values from all years for columns 'Precip9am' through to 'Winds ms 21 hr' and filter those columns to just include DTY = DTY_Array

I've grouped the Climate_DF to DTY and then try to apply a filter:
ClimateDTY_DF = Climate_DF.groupby("DTY")
DTY_Climate = ClimateDTY_DF[DTY_Array]

I get the following error:
KeyError: 'Columns not found: 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0'

```<code>I'm assuming this is because the filter is trying to find the values in the ClimateDTY_DF columns, but I need **it to be filtering through the DTY column to find all the indexes from the array and extract the values from each column aftern 'Precip9am'**.

How do I do this? Do I transpose first? Or do I need to create some kind of loop that creates a DF for DTY and each column from 'Precip9am' through to 'Winds ms 21 hr' and extracts just the DTY from the array for each?

</code>```

Body:
I'm trying to extract 7 rows of data grouped by the DTY column in a Dataframe. I think I need to use a numpy array to filter, but can't seem to get it working.

Here's an extract of my original CLimate_DF dataframe (note there are NaN values for the :

Year    Month   Day DTY Precip9am    MaxT    ...    Wind ms 21 hr
1989    1   1   1   0        29.7    ...    0
1989    1   2   2   0        31.1    ...    4.6
1989    1   3   3   0.4      32      ...    2.1
... ... ... ... ...      ...     ...    ...
2019    12  31  365 21.2         31.3    ...    2.1

First, I created a numpy array filter based on a given date - this works and creates the right array:

#Enter Day of Interest (DOI) yyyy, mm, dd

DOI = datetime.datetime(2020, 2, 6)
DTY = DOI.timetuple()[7]
DTYMinus3 = DTY-3
DTYPlus3 = DTY+3
DTY_Array = np.linspace(DTYMinus3, DTYPlus3,7)
DTY_Array = np.array(DTY_Array)

I now want to extract all values from all years for columns 'Precip9am' through to 'Winds ms 21 hr' and filter those columns to just include DTY = DTY_Array

I've grouped the Climate_DF to DTY and then try to apply a filter:
ClimateDTY_DF = Climate_DF.groupby("DTY")
DTY_Climate = ClimateDTY_DF[DTY_Array]

I get the following error:
KeyError: 'Columns not found: 34.0, 35.0, 36.0, 37.0, 38.0, 39.0, 40.0'

I'm assuming this is because the filter is trying to find the values in the ClimateDTY_DF columns, but I need **it to be filtering through the DTY column to find all the indexes from the array and extract the values from each column aftern 'Precip9am'**.

How do I do this? Do I transpose first? Or do I need to create some kind of loop that creates a DF for DTY and each column from 'Precip9am' through to 'Winds ms 21 hr' and extracts just the DTY from the array for each?


问:
Unable to validate Spark Installation from Shell
i tried to install spark in Mac using Homebrew. I did all the steps as mentioned in https://sparkbyexamples.com/spark/install-apache-spark-on-mac/ . However, when i want to vallidate the spark installation from shell cmd, i got this following output: How to do this, i already did reinstallation but nothing changed. Thank you.

```<code>scala> import spark.implicits._
import spark.implicits._

scala> val data = Seq(("Java", "20000"), ("Python", "100000"), ("Scala", "3000"))
data: Seq[(String, String)] = List((Java,20000), (Python,100000), (Scala,3000))

scala> val df = data.toDF()
</code>```
```<code>java.lang.NoSuchMethodError: 'boolean org.apache.spark.util.Utils$.isInRunningSparkTask()'
  at org.apache.spark.sql.internal.SQLConf$.get(SQLConf.scala:201)
  at org.apache.spark.sql.types.DataType.sameType(DataType.scala:99)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.$anonfun$haveSameType$1(TypeCoercion.scala:157)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.$anonfun$haveSameType$1$adapted(TypeCoercion.scala:157)
  at scala.collection.LinearSeqOptimized.forall(LinearSeqOptimized.scala:85)
  at scala.collection.LinearSeqOptimized.forall$(LinearSeqOptimized.scala:82)
  at scala.collection.immutable.List.forall(List.scala:91)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.haveSameType(TypeCoercion.scala:157)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataTypeCheck(Expression.scala:1124)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataTypeCheck$(Expression.scala:1119)
  at org.apache.spark.sql.catalyst.expressions.If.dataTypeCheck(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType(Expression.scala:1130)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType$(Expression.scala:1129)
  at org.apache.spark.sql.catalyst.expressions.If.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType$lzycompute(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.If.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataType(Expression.scala:1134)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataType$(Expression.scala:1134)
  at org.apache.spark.sql.catalyst.expressions.If.dataType(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.isSerializedAsStruct(ExpressionEncoder.scala:306)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.isSerializedAsStructForTopLevel(ExpressionEncoder.scala:316)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.<init>(ExpressionEncoder.scala:245)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.apply(ExpressionEncoder.scala:61)
  at org.apache.spark.sql.Encoders$.product(Encoders.scala:300)
  at org.apache.spark.sql.LowPrioritySQLImplicits.newProductEncoder(SQLImplicits.scala:261)
  at org.apache.spark.sql.LowPrioritySQLImplicits.newProductEncoder$(SQLImplicits.scala:261)
  at org.apache.spark.sql.SQLImplicits.newProductEncoder(SQLImplicits.scala:32)
  ... 49 elided

scala> df.show()
<console>:26: error: not found: value df
       df.show()
       ^

</code>```

The output of df.show().

Body:
i tried to install spark in Mac using Homebrew. I did all the steps as mentioned in https://sparkbyexamples.com/spark/install-apache-spark-on-mac/ . However, when i want to vallidate the spark installation from shell cmd, i got this following output: How to do this, i already did reinstallation but nothing changed. Thank you.

scala> import spark.implicits._
import spark.implicits._

scala> val data = Seq(("Java", "20000"), ("Python", "100000"), ("Scala", "3000"))
data: Seq[(String, String)] = List((Java,20000), (Python,100000), (Scala,3000))

scala> val df = data.toDF()

java.lang.NoSuchMethodError: 'boolean org.apache.spark.util.Utils$.isInRunningSparkTask()'
  at org.apache.spark.sql.internal.SQLConf$.get(SQLConf.scala:201)
  at org.apache.spark.sql.types.DataType.sameType(DataType.scala:99)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.$anonfun$haveSameType$1(TypeCoercion.scala:157)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.$anonfun$haveSameType$1$adapted(TypeCoercion.scala:157)
  at scala.collection.LinearSeqOptimized.forall(LinearSeqOptimized.scala:85)
  at scala.collection.LinearSeqOptimized.forall$(LinearSeqOptimized.scala:82)
  at scala.collection.immutable.List.forall(List.scala:91)
  at org.apache.spark.sql.catalyst.analysis.TypeCoercionBase.haveSameType(TypeCoercion.scala:157)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataTypeCheck(Expression.scala:1124)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataTypeCheck$(Expression.scala:1119)
  at org.apache.spark.sql.catalyst.expressions.If.dataTypeCheck(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType(Expression.scala:1130)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType$(Expression.scala:1129)
  at org.apache.spark.sql.catalyst.expressions.If.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType$lzycompute(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.If.org$apache$spark$sql$catalyst$expressions$ComplexTypeMergingExpression$$internalDataType(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataType(Expression.scala:1134)
  at org.apache.spark.sql.catalyst.expressions.ComplexTypeMergingExpression.dataType$(Expression.scala:1134)
  at org.apache.spark.sql.catalyst.expressions.If.dataType(conditionalExpressions.scala:39)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.isSerializedAsStruct(ExpressionEncoder.scala:306)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.isSerializedAsStructForTopLevel(ExpressionEncoder.scala:316)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder.<init>(ExpressionEncoder.scala:245)
  at org.apache.spark.sql.catalyst.encoders.ExpressionEncoder$.apply(ExpressionEncoder.scala:61)
  at org.apache.spark.sql.Encoders$.product(Encoders.scala:300)
  at org.apache.spark.sql.LowPrioritySQLImplicits.newProductEncoder(SQLImplicits.scala:261)
  at org.apache.spark.sql.LowPrioritySQLImplicits.newProductEncoder$(SQLImplicits.scala:261)
  at org.apache.spark.sql.SQLImplicits.newProductEncoder(SQLImplicits.scala:32)
  ... 49 elided

scala> df.show()
<console>:26: error: not found: value df
       df.show()
       ^

The output of df.show().


问:
inline specifier allowed on function declarations only
I keep getting this error: inline specifier allowed on function declarations only

Not getting the the error

I am kinda new to c++ and c

anyone know a fix for this???

I have 0 idea whats going on for my thing

code:

```<code>#include "../sdk/includes.h"
#include "module/Module.h"
#include "module/ModuleManager.h"

namespace Link
{
    class c_link
    {
    private:
        JNIEnv* env;
        JavaVM* vm;

        jmethodID findclass;
        jobject cloassloader;

    public:
        bool attach();

        void hook();

        void run();

        void unload();

        const auto getEnv() { return env; }
        const auto getJavaVM() { return vm; }

        class std::unique_ptr<moduleManager, std::default_delete<moduleManager>> moduleMngr;
    };

    namespace hooks
    {
        using swapBuffersFunction = int(__stdcall*)(HDC);

        inline swapBuffersFunction oswapBuffers = nullptr;

        int __stdcall swapBuffersHook(HDC);

        inline WNDPROC originalWndproc = nullptr;

        long __stdcall wndproc(const HWND hwnd, unsigned int usermsg, uintptr_t wparam, long lparam);
    }

    extern std::unique_ptr<c_link> instance;
}
</code>```

Body:
I keep getting this error: inline specifier allowed on function declarations only

Not getting the the error

I am kinda new to c++ and c

anyone know a fix for this???

I have 0 idea whats going on for my thing

code:

#include "../sdk/includes.h"
#include "module/Module.h"
#include "module/ModuleManager.h"

namespace Link
{
    class c_link
    {
    private:
        JNIEnv* env;
        JavaVM* vm;

        jmethodID findclass;
        jobject cloassloader;

    public:
        bool attach();

        void hook();

        void run();

        void unload();

        const auto getEnv() { return env; }
        const auto getJavaVM() { return vm; }

        class std::unique_ptr<moduleManager, std::default_delete<moduleManager>> moduleMngr;
    };

    namespace hooks
    {
        using swapBuffersFunction = int(__stdcall*)(HDC);

        inline swapBuffersFunction oswapBuffers = nullptr;

        int __stdcall swapBuffersHook(HDC);

        inline WNDPROC originalWndproc = nullptr;

        long __stdcall wndproc(const HWND hwnd, unsigned int usermsg, uintptr_t wparam, long lparam);
    }

    extern std::unique_ptr<c_link> instance;
}


问:
To findout CSR, SSR in next.js
I'm using package.json

```<code>    "next": "13.0.6",
    "react": "18.2.0",
    "react-dom": "18.2.0",
</code>```

Case 1

```<code>const [domLoaded, setDomLoaded] = useState(false);

  useEffect(() => {
    setDomLoaded(true);
  }, []);

...

{domLoaded && (
        <>
          // ...something need to be rendered after DOM loaded like below
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}
</code>```

Case2

```<code>{typeof window !== "undefined" && (
        <>
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            style={{ height: "60vh" }}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}
</code>```

I think Case 1 is same as Case 2 but, Case1 is ok, but Case2 throw an Error says that "Error: Hydration failed because the initial UI does not match what was rendered on the server."

What is difference between two cases ?
Thanks.

Entire code

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import "react-quill/dist/quill.snow.css";

const ReactQuill = typeof window === "object" ? require("react-quill") : () => false;
const Quill = typeof window === "object" ? require("react-quill").Quill : () => false;

import Toolbar from "~/@components/molecule/Editor/Toolbar";
import useInput from "~/@hooks/useInput";
import { ContentService } from "~/@services/content";

export default function QuillTest() {
  const quillRef = useRef();
  const [value, setValue] = useState();
  const [domLoaded, setDomLoaded] = useState(false);

  useEffect(() => {
    setDomLoaded(true);
  }, []);

  const imageHandler = useCallback(() => {
    const formData = new FormData();

    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.setAttribute("name", "image");
    input.click();

    input.onchange = async () => {
      if (input.files && input.files[0]) {
        console.log("input.files[0]", input.files[0]);
        formData.append("image", input.files[0]);
      }

      const url = await ContentService.imageUpload(formData);
      //@ts-ignore
      const quill = quillRef.current.getEditor();
      const range = quill.getSelection()?.index;

      if (typeof range !== "number") return;
      quill.setSelection(range, 1);
      quill.clipboard.dangerouslyPasteHTML(range, `<img src=${url} alt="image" />`);
    };
  }, [quillRef]);

  const devideHandler = useCallback(() => {
    let BlockEmbed = Quill.import("blots/block/embed");
    class DividerBlot extends BlockEmbed {}

    DividerBlot.blotName = "divider2";
    DividerBlot.tagName = "hr";

    Quill.register("formats/divider", DividerBlot);

    //@ts-ignore
    const quill = quillRef.current?.getEditor();
    let range = quill.getSelection(true);
    quill.insertText(range.index, "\n", Quill.sources.USER);
    quill.insertEmbed(range.index + 1, "divider2", true, Quill.sources.USER);
    quill.setSelection(range.index + 2, Quill.sources.SILENT);
  }, [quillRef]);

  const modules = useMemo(() => {
    return {
      toolbar: {
        container: "#toolbar",
        handlers: {
          image: imageHandler,
          divider2: devideHandler,
        },
      },
    };
  }, [imageHandler]);

  return (

      {typeof window !== "undefined" && (
        <>
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            style={{ height: "60vh" }}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}

  );
}
```

Title: To findout CSR, SSR in next.js

Body:
I'm using package.json

    "next": "13.0.6",
    "react": "18.2.0",
    "react-dom": "18.2.0",

Case 1

const [domLoaded, setDomLoaded] = useState(false);

  useEffect(() => {
    setDomLoaded(true);
  }, []);

...

{domLoaded && (
        <>
          // ...something need to be rendered after DOM loaded like below
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}

Case2

{typeof window !== "undefined" && (
        <>
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            style={{ height: "60vh" }}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}

I think Case 1 is same as Case 2 but, Case1 is ok, but Case2 throw an Error says that "Error: Hydration failed because the initial UI does not match what was rendered on the server."

What is difference between two cases ?
Thanks.

Entire code

import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import "react-quill/dist/quill.snow.css";

const ReactQuill = typeof window === "object" ? require("react-quill") : () => false;
const Quill = typeof window === "object" ? require("react-quill").Quill : () => false;

import Toolbar from "~/@components/molecule/Editor/Toolbar";
import useInput from "~/@hooks/useInput";
import { ContentService } from "~/@services/content";

export default function QuillTest() {
  const quillRef = useRef();
  const [value, setValue] = useState();
  const [domLoaded, setDomLoaded] = useState(false);

  useEffect(() => {
    setDomLoaded(true);
  }, []);

  const imageHandler = useCallback(() => {
    const formData = new FormData();

    const input = document.createElement("input");
    input.setAttribute("type", "file");
    input.setAttribute("accept", "image/*");
    input.setAttribute("name", "image");
    input.click();

    input.onchange = async () => {
      if (input.files && input.files[0]) {
        console.log("input.files[0]", input.files[0]);
        formData.append("image", input.files[0]);
      }

      const url = await ContentService.imageUpload(formData);
      //@ts-ignore
      const quill = quillRef.current.getEditor();
      const range = quill.getSelection()?.index;

      if (typeof range !== "number") return;
      quill.setSelection(range, 1);
      quill.clipboard.dangerouslyPasteHTML(range, `<img src=${url} alt="image" />`);
    };
  }, [quillRef]);

  const devideHandler = useCallback(() => {
    let BlockEmbed = Quill.import("blots/block/embed");
    class DividerBlot extends BlockEmbed {}

    DividerBlot.blotName = "divider2";
    DividerBlot.tagName = "hr";

    Quill.register("formats/divider", DividerBlot);

    //@ts-ignore
    const quill = quillRef.current?.getEditor();
    let range = quill.getSelection(true);
    quill.insertText(range.index, "\n", Quill.sources.USER);
    quill.insertEmbed(range.index + 1, "divider2", true, Quill.sources.USER);
    quill.setSelection(range.index + 2, Quill.sources.SILENT);
  }, [quillRef]);

  const modules = useMemo(() => {
    return {
      toolbar: {
        container: "#toolbar",
        handlers: {
          image: imageHandler,
          divider2: devideHandler,
        },
      },
    };
  }, [imageHandler]);

  return (

      {typeof window !== "undefined" && (
        <>
          <Toolbar />
          <ReactQuill
            ref={quillRef}
            style={{ height: "60vh" }}
            value={value}
            modules={modules}
            onChange={setValue}
            theme="snow"
          />
        </>
      )}

  );
}


问:
GCP App Engine whatsapp-web.js not generating QR code
I have a node.js app that uses whatsapp-web.js, I'm using Cloud Shell Editor to execute my app, when I see it in Web Preview everything it's okay, but when I execute: gcloud app deploy and I see my url, the QR code is not generated.

I executed: gcloud app logs tail -s default, and I found this error in console:

```<code>/workspace/node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:230
error: new Errors_js_1.ProtocolError(),
ProtocolError: Protocol error (Runtime.callFunctionOn): Target closed.
</code>```

Node version: 18.12.1

This is my code

const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
var cors = require('cors')

const config = require("./config.json");
const { Client, LocalAuth } = require("whatsapp-web.js");

process.title = "whatsapp-node-api";
global.client = new Client({
  authStrategy: new LocalAuth({clientId: "my-client", dataPath: "/tmp"}),
  puppeteer: {
      headless: true,
      ignoreHTTPSErrors: true,
      args: ['--no-sandbox','--disable-setuid-sandbox']
    },
});

global.authed = false;

const app = express();

app.use(cors());

const port = process.env.PORT || config.port;

app.use(bodyParser.json({ limit: "50mb" }));

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

client.on("qr", (qr) => {
  console.log("qr");
  process.last_qr = qr;
});

client.on("authenticated", () => {
  console.log("AUTH!");
  authed = true;
  process.last_qr = undefined;
});

client.on("ready", () => {
  console.log("Client is ready!");
});

client.on("disconnected", () => {
  console.log("disconnected");
});
client.initialize();

const chatRoute = require("./components/chatting");
const authRoute = require("./components/auth");

app.use(function (req, res, next) {
  console.log(req.method + " : " + req.path);
  next();
});
app.use("/chat", chatRoute);
app.use("/auth", authRoute);

app.listen(port, () => {
  console.log("Server Running Live on Port : " + port);
});
```
<p>My app.yaml</p>
```runtime: nodejs18
env: standard
instance_class: F4_1G
```

Body:
I have a node.js app that uses whatsapp-web.js, I'm using Cloud Shell Editor to execute my app, when I see it in Web Preview everything it's okay, but when I execute: gcloud app deploy and I see my url, the QR code is not generated.

I executed: gcloud app logs tail -s default, and I found this error in console:

/workspace/node_modules/puppeteer/lib/cjs/puppeteer/common/Connection.js:230
error: new Errors_js_1.ProtocolError(),
ProtocolError: Protocol error (Runtime.callFunctionOn): Target closed.

Node version: 18.12.1

This is my code

const express = require("express");
const bodyParser = require("body-parser");
const axios = require("axios");
var cors = require('cors')

const config = require("./config.json");
const { Client, LocalAuth } = require("whatsapp-web.js");

process.title = "whatsapp-node-api";
global.client = new Client({
  authStrategy: new LocalAuth({clientId: "my-client", dataPath: "/tmp"}),
  puppeteer: {
      headless: true,
      ignoreHTTPSErrors: true,
      args: ['--no-sandbox','--disable-setuid-sandbox']
    },
});

global.authed = false;

const app = express();

app.use(cors());

const port = process.env.PORT || config.port;

app.use(bodyParser.json({ limit: "50mb" }));

app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

client.on("qr", (qr) => {
  console.log("qr");
  process.last_qr = qr;
});

client.on("authenticated", () => {
  console.log("AUTH!");
  authed = true;
  process.last_qr = undefined;
});

client.on("ready", () => {
  console.log("Client is ready!");
});

client.on("disconnected", () => {
  console.log("disconnected");
});
client.initialize();

const chatRoute = require("./components/chatting");
const authRoute = require("./components/auth");

app.use(function (req, res, next) {
  console.log(req.method + " : " + req.path);
  next();
});
app.use("/chat", chatRoute);
app.use("/auth", authRoute);

app.listen(port, () => {
  console.log("Server Running Live on Port : " + port);
});

My app.yaml

runtime: nodejs18
env: standard
instance_class: F4_1G


问:
ROOT style plotting in python

I would like to plot in this style. I have seen people using this type of plot in ROOT(CERN) but i would like to do in python.

Title: ROOT style plotting in python


问:
Mongoose calculate field values
I have the following mongoose schema:

const saleSchema = new Schema({
  clientId: String,
  items: {[
    name: String,
    quantity: Number,
    price: Number,
  ]},
  totalValue: Number
})
```

I want to calculate the sum of all item prices and put that result in the totalValue field.

I need to do this both the first time a document is created and every time it is updated.

Title: Mongoose calculate field values

Body:
I have the following mongoose schema:

const saleSchema = new Schema({
  clientId: String,
  items: {[
    name: String,
    quantity: Number,
    price: Number,
  ]},
  totalValue: Number
})

I want to calculate the sum of all item prices and put that result in the totalValue field.

I need to do this both the first time a document is created and every time it is updated.


问:
Table data is break into new page, even though it still fits

few days ago, it returns normally, the table data doesn't break into new page, but recently it return like this. Is there any cause for this to happen?


问:
Syntax error or access violation In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'dbnam.users.id';
Hie, am facing problems when i try to login into my php website online ,but when i login am getting this error

There is some problem in connection: SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'database_name.users.id'; this is incompatible with sql_mode=only_full_group_by

SO my code layout
When you login the action button takes you to verify.php and code inside verify.php is attached below

```<code><?php
    include 'includes/session.php';
    $conn = $pdo->open();

    if(isset($_POST['login'])){

        $email = $_POST['email'];
        $password = $_POST['password'];

        try{

            $stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM users WHERE email = :email");
            $stmt->execute(['email'=>$email]);
            $row = $stmt->fetch();
            if($row['numrows'] > 0){
                if($row['status']){
                    if(password_verify($password, $row['password'])){
                        if($row['type']){
                            $_SESSION['admin'] = $row['id'];
                        }
                        else{
                            $_SESSION['user'] = $row['id'];
                        }
                    }
                    else{
                        $_SESSION['error'] = 'Incorrect Password';
                    }
                }
                else{
                    $_SESSION['error'] = 'Account not activated.';
                }
            }
            else{
                $_SESSION['error'] = 'Email not found';
            }
        }
        catch(PDOException $e){
            echo "There is some problem in connection: " . $e->getMessage();
        }

    }
    else{
        $_SESSION['error'] = 'Input login credentails error';
    }

    $pdo->close();

    header('location: login.php');

?>
</code>```

am assuming i need to separate these queries .

I would appreciate if anyone could show me the right way to go around that error and fix it .

any help will be appreciated

Body:
Hie, am facing problems when i try to login into my php website online ,but when i login am getting this error

There is some problem in connection: SQLSTATE[42000]: Syntax error or access violation: 1140 In aggregated query without GROUP BY, expression #1 of SELECT list contains nonaggregated column 'database_name.users.id'; this is incompatible with sql_mode=only_full_group_by

SO my code layout
When you login the action button takes you to verify.php and code inside verify.php is attached below

<?php
    include 'includes/session.php';
    $conn = $pdo->open();

    if(isset($_POST['login'])){

        $email = $_POST['email'];
        $password = $_POST['password'];

        try{

            $stmt = $conn->prepare("SELECT *, COUNT(*) AS numrows FROM users WHERE email = :email");
            $stmt->execute(['email'=>$email]);
            $row = $stmt->fetch();
            if($row['numrows'] > 0){
                if($row['status']){
                    if(password_verify($password, $row['password'])){
                        if($row['type']){
                            $_SESSION['admin'] = $row['id'];
                        }
                        else{
                            $_SESSION['user'] = $row['id'];
                        }
                    }
                    else{
                        $_SESSION['error'] = 'Incorrect Password';
                    }
                }
                else{
                    $_SESSION['error'] = 'Account not activated.';
                }
            }
            else{
                $_SESSION['error'] = 'Email not found';
            }
        }
        catch(PDOException $e){
            echo "There is some problem in connection: " . $e->getMessage();
        }

    }
    else{
        $_SESSION['error'] = 'Input login credentails error';
    }

    $pdo->close();

    header('location: login.php');

?>

am assuming i need to separate these queries .

I would appreciate if anyone could show me the right way to go around that error and fix it .

any help will be appreciated


问:
What does this mean to process src in rector?
I am trying to follow the instructions below using Windows CMD and/or Linux Sub on Windows Ubuntu using commands below.

Just setup Rector and run it:

```<code>composer require rector/rector --dev
</code>```
```<code>use Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector;
use Rector\Config\RectorConfig;

return function (RectorConfig $rectorConfig): void {
    $rectorConfig->rule(CreateFunctionToAnonymousFunctionRector::class);
};
</code>```

But when I use this command below

```<code>vendor/bin/rector process src
</code>```

These are the errors below.

Windows error

```<code>'process' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Linux error

```<code>/vendor/bin$ process src
process: command not found
</code>```

Tried everything above..

Body:
I am trying to follow the instructions below using Windows CMD and/or Linux Sub on Windows Ubuntu using commands below.

Just setup Rector and run it:

composer require rector/rector --dev

use Rector\Php72\Rector\FuncCall\CreateFunctionToAnonymousFunctionRector;
use Rector\Config\RectorConfig;

return function (RectorConfig $rectorConfig): void {
    $rectorConfig->rule(CreateFunctionToAnonymousFunctionRector::class);
};

But when I use this command below

vendor/bin/rector process src

These are the errors below.

Windows error

'process' is not recognized as an internal or external command,
operable program or batch file.

Linux error

/vendor/bin$ process src
process: command not found

Tried everything above..


问:
Converting reports made with QRDesign (.qr2) to .dfm
I need to use my reports on FastReport, but all of them were made in QRDesign (.qr2). I couldn't find a way to convert these reports. QRDesign was made based on QuickReport. How can I convert them to .dfm?

I tried to use FRConverter, but it didn'd succeed.


问:
python selenium refuses to scroll down page, how to force / fix?
I need selenium using the firefox driver to scroll down the page to the very bottom, but my code no longer works. Its like the page recognizes I am trying to scroll with selenium and forces the scroll back to the top of the screen...

```<code>def scroll_to_bottom():
    '''
    Scroll down the page the whole way. This must be done to show all images on page to download.
    '''

    print("[+] Starting scroll down of page. This needs to be performed to view all images.")
    count = 0
    start_time = time.perf_counter()
    try:
        last_height = driver.execute_script("return document.body.scrollHeight")
        while True:
            if count % 10 == 0:
                elapsed_time = time.perf_counter() - start_time
                elapsed_time_clean = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
                print("[i] Still scrolling, its been " + str(elapsed_time_clean) + ", please continue to standby... C: " + str(count))
            time.sleep(3)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(3)

            # Check if hight has changed
            new_height = driver.execute_script("return document.body.scrollHeight")
            vprint("last_height: " + str(last_height) + ", new_height: " + str(new_height))
            if new_height == last_height:
                break
            last_height = new_height
            count += 1

    except Exception as exception:
        print('[!] Exception exception: '+str(exception))
        pass

    print("[i] Scroll down of whole page complete.")
    return
</code>```

It will go to the page, start to scroll once, then pop up to the top of the screen and no longer scroll. Then my code thinks its at the bottom of the page because the page size did not change. This worked about 3 weeks ago but no longer works. I cant figure out why.

Is there a way to force scrolling?
BTw I tried using "DOWN" and "Page DOWN" key presses, that does not work either. Anyone have any ideas?

Body:
I need selenium using the firefox driver to scroll down the page to the very bottom, but my code no longer works. Its like the page recognizes I am trying to scroll with selenium and forces the scroll back to the top of the screen...

def scroll_to_bottom():
    '''
    Scroll down the page the whole way. This must be done to show all images on page to download.
    '''

    print("[+] Starting scroll down of page. This needs to be performed to view all images.")
    count = 0
    start_time = time.perf_counter()
    try:
        last_height = driver.execute_script("return document.body.scrollHeight")
        while True:
            if count % 10 == 0:
                elapsed_time = time.perf_counter() - start_time
                elapsed_time_clean = time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
                print("[i] Still scrolling, its been " + str(elapsed_time_clean) + ", please continue to standby... C: " + str(count))
            time.sleep(3)
            driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
            time.sleep(3)

            # Check if hight has changed
            new_height = driver.execute_script("return document.body.scrollHeight")
            vprint("last_height: " + str(last_height) + ", new_height: " + str(new_height))
            if new_height == last_height:
                break
            last_height = new_height
            count += 1

    except Exception as exception:
        print('[!] Exception exception: '+str(exception))
        pass

    print("[i] Scroll down of whole page complete.")
    return

It will go to the page, start to scroll once, then pop up to the top of the screen and no longer scroll. Then my code thinks its at the bottom of the page because the page size did not change. This worked about 3 weeks ago but no longer works. I cant figure out why.

Is there a way to force scrolling?
BTw I tried using "DOWN" and "Page DOWN" key presses, that does not work either. Anyone have any ideas?


问:
How to do a login method? It has to return an object "User"?
I'm struggling to build a simple login method. (the worst thing is that I think the answer may be pretty obvious, so sorry for anything)

I have a type Client that has the client properties (name, email, username, password, age, etc.), that is storaged in a ClientRepository class. My idea is to compare the user and password til I have the right match and return the object Client logged, so I can access its properties outside.

I have two questions:

1 - The method below must have to return a Client type so I can access its properties later, right? Or theres a better way of doing a login method?

2 - What do I return in the "elses" below (when the login fails)?

Thanks

```<code>public Client logIn(String user, String password){
    Cliente logged;
    for(int i = 0; i < clients.size(); i++){
        if(clients.get(i).getUser().equals(user)){
            if(clients.get(i).getPassword().equals(password)){
                logged = clients.get(i);
                System.out.println("LOGIN SUCCESFULL");
                return logged;
            }else{
                System.out.println("WRONG PASSWORD!");
            }
        }else{
            System.out.println("USER DOESNT EXISTS");
        }

    }
}
</code>```

Body:
I'm struggling to build a simple login method. (the worst thing is that I think the answer may be pretty obvious, so sorry for anything)

I have a type Client that has the client properties (name, email, username, password, age, etc.), that is storaged in a ClientRepository class. My idea is to compare the user and password til I have the right match and return the object Client logged, so I can access its properties outside.

I have two questions:

1 - The method below must have to return a Client type so I can access its properties later, right? Or theres a better way of doing a login method?

2 - What do I return in the "elses" below (when the login fails)?

Thanks

public Client logIn(String user, String password){
    Cliente logged;
    for(int i = 0; i < clients.size(); i++){
        if(clients.get(i).getUser().equals(user)){
            if(clients.get(i).getPassword().equals(password)){
                logged = clients.get(i);
                System.out.println("LOGIN SUCCESFULL");
                return logged;
            }else{
                System.out.println("WRONG PASSWORD!");
            }
        }else{
            System.out.println("USER DOESNT EXISTS");
        }

    }
}


问:
How can i make any URI authorized as Redirect URI for my Google Cloud APP?
Redirect URI adding section

Hi there :)

Thanks in advance, actually i was making a wordpress plugin which requries Google OAuth verification and i am making this plugin for all users. But i found that in the Authentiation URL i need to pass a Redirect URI and that needs to be added previously in my Google Cloud app, otherwise that Redirect URI will be considered as Unauthorized.

And Google doesn't allow me to add any wildcard entry as Authorized redirect URI. So, in this case how can any user use my plugin, because i can't know everyones site url and add them into my Cloud App manually.

So, do anyone knows that how can i make any URL authorized as Redirect URI or dynamically add Authorized URI into my Google Cloud app.

I tried adding wildcard URL entries, and also tried removing all URL entries from that list thinking that removing all might be considered as all urls are allowed, but nothing worked for me :(


问:
If user-agent lands on specific pages, then redirect user agent to homepage with htaccess
I am trying to redirect a search engine user-agents that land on specific pages to my homepage.

Anytime one of these user agents lands on one of the RewriteRule pages, I want the search engine user-agent to be redirected to my homepage. I've tried several variations of this, but I just cannot seem to get it to work.

This version redirects all user-agents to the homepage. Another version I tried only worked for the first RewriteRule.

Any help would be appreciated.

```<code>RewriteCond %{HTTP_USER_AGENT} !^(googlebot|Googlebot|Googlebot-News|Googlebot-Video|Googlebot-Image|Mediapartners-Google|Mediapartners-Google|AdsBot-Google|AdsBot-Google-Mobile-Apps|Bingbot|MSNBot|MSNBot-Media|AdIdxBot|BingPreview|YandexBot|YandexMobileBot|Yandex|YandexDirect|YandexDirectDyn|YandexMedia|YandexImages|YaDirectFetcher|YandexBlogs|YandexNews|YandexPagechecker|YandexMetrika|YandexCalendar|YandexScreenshotBot|YandexFavicons|YandexWebmaster|YandexImageResizer|YandexSitelinks|YandexAntivirus|YandexVertis|Slurp|DuckDuckBot|ia_archiver|aolbuild|teoma|Baiduspider|Baiduspider-news|Baiduspider-video|Baiduspider-image|facebot|facebookexternalhit/1.0|facebookexternalhit/1.1|Applebot) [NC]
RewriteRule !^ - [S=3]

RewriteRule ^post-new$ / [R=301,L]
RewriteRule ^post-old$ / [R=301,L]
RewriteRule ^post-future$ / [R=301,L]
</code>```

Body:
I am trying to redirect a search engine user-agents that land on specific pages to my homepage.

Anytime one of these user agents lands on one of the RewriteRule pages, I want the search engine user-agent to be redirected to my homepage. I've tried several variations of this, but I just cannot seem to get it to work.

This version redirects all user-agents to the homepage. Another version I tried only worked for the first RewriteRule.

Any help would be appreciated.

RewriteCond %{HTTP_USER_AGENT} !^(googlebot|Googlebot|Googlebot-News|Googlebot-Video|Googlebot-Image|Mediapartners-Google|Mediapartners-Google|AdsBot-Google|AdsBot-Google-Mobile-Apps|Bingbot|MSNBot|MSNBot-Media|AdIdxBot|BingPreview|YandexBot|YandexMobileBot|Yandex|YandexDirect|YandexDirectDyn|YandexMedia|YandexImages|YaDirectFetcher|YandexBlogs|YandexNews|YandexPagechecker|YandexMetrika|YandexCalendar|YandexScreenshotBot|YandexFavicons|YandexWebmaster|YandexImageResizer|YandexSitelinks|YandexAntivirus|YandexVertis|Slurp|DuckDuckBot|ia_archiver|aolbuild|teoma|Baiduspider|Baiduspider-news|Baiduspider-video|Baiduspider-image|facebot|facebookexternalhit/1.0|facebookexternalhit/1.1|Applebot) [NC]
RewriteRule !^ - [S=3]

RewriteRule ^post-new$ / [R=301,L]
RewriteRule ^post-old$ / [R=301,L]
RewriteRule ^post-future$ / [R=301,L]


问:
Integrating Another Message Queue with IIS Hosted Workflow Service
Currently, I am using MSMQ to queue messages for IIS hosted workflow services to handle. However, I would like to use another message queuing system instead (eg - RabbitMQ).

I know RabbitMQ already has WCF bindings, but are there more components required for this to work with IIS hosted workflow services (perhaps some hook into WAS)? How would I go abouts switching from MSMQ to RabbitMQ, or another message queue product?

ContentLicense: CC BY-SA 3.0


问:
How to change font-size of dependencies list in Eclipse IDE 2022-12?
I am using Windows 10 x64, Java language level / JDK 19, Eclipse IDE 2022-12 . How to change font-size of dependencies list in Eclipse IDE 2022-12? I need it bigger due to my eyes cannot see.


问:
Trying to redirect requests to a web application with different versions behind nginx as reverse proxy?
```<code>I have an off-the-shelf web application with version, say v1, running behind a nginx server.

  URL for web app say https://web-app/

I want to run v2 version of the same application as test pilot with few users in the same environment as the above one. This version of the application sits behind the same nginx server.

  URL for web app version v2  https://web-app/v2

The requirement is that the request should be redirected to the right instance.
</code>```

Please note that the off-the-shelf web-app does not have the version in the URL. So, I need to find a way to redirect all the requests to the correct instance. After a bit of research I observed that one of the option is to use a cookie.

For instance when a user accesses either of the url then in the nginx server checks for the existence of "v2" at the end of it. In case the URL contains v2 then nginx server sends the request to new version and sets a cookie with a value say "version:v2" in the response to the browser. The browser then onwards sends the cookie in the requests. The nginx server will use the cookie to redirect the request to the right instance.

I have bit of experience in server side programming but did work on frontend and browser. so not sure if the above approach is right or not. So request you help/advise.

Body:
I have an off-the-shelf web application with version, say v1, running behind a nginx server.

  URL for web app say https://web-app/

I want to run v2 version of the same application as test pilot with few users in the same environment as the above one. This version of the application sits behind the same nginx server.

  URL for web app version v2  https://web-app/v2

The requirement is that the request should be redirected to the right instance.

Please note that the off-the-shelf web-app does not have the version in the URL. So, I need to find a way to redirect all the requests to the correct instance. After a bit of research I observed that one of the option is to use a cookie.

For instance when a user accesses either of the url then in the nginx server checks for the existence of "v2" at the end of it. In case the URL contains v2 then nginx server sends the request to new version and sets a cookie with a value say "version:v2" in the response to the browser. The browser then onwards sends the cookie in the requests. The nginx server will use the cookie to redirect the request to the right instance.

I have bit of experience in server side programming but did work on frontend and browser. so not sure if the above approach is right or not. So request you help/advise.


问:
Is there a better method of waiting instead of asyncio.sleep? discord.py
So I setup a vote only system that if the user votes it'll give them access to vote only commands but using asyncio.sleep() to wait 12 hours isn't a good thing at all since if I restart the bot, The  timer will basically stop. Is there  a better way to make it wait 12 hours?


问:
OSError: SavedModel file does not exist when Deployed through heroku
I receive the following error when trying to run the app through heroku"

This the model

```<code>def load_model_and_predict(my_image, version):
    model = load_model("/workspace/project5Ver2/")

    # Returns the probability that the leaf contains mildew
    pred_proba = model.predict(my_image)[0, 0]

    target_map = {v: k for k, v in {'Healthy': 0, 'Mildew': 1}.items()}
    pred_class = target_map[pred_proba > 0.5]
    if pred_class == target_map[0]:
        pred_proba = 1 - pred_proba

    return pred_proba, pred_class
</code>```

I made sure that there are no typos in my code, but I cannot think of anything else.

Here a link to my repo.

Body:
I receive the following error when trying to run the app through heroku"

This the model

def load_model_and_predict(my_image, version):
    model = load_model("/workspace/project5Ver2/")

    # Returns the probability that the leaf contains mildew
    pred_proba = model.predict(my_image)[0, 0]

    target_map = {v: k for k, v in {'Healthy': 0, 'Mildew': 1}.items()}
    pred_class = target_map[pred_proba > 0.5]
    if pred_class == target_map[0]:
        pred_proba = 1 - pred_proba

    return pred_proba, pred_class

I made sure that there are no typos in my code, but I cannot think of anything else.

Here a link to my repo.


问:
How do I keep the track playing even switching app or hibernating the device when using expo-av library (React Native)
I am new in React Native, so I don't master all related to background tasks, when I have to keep the app track playing even the user locks or hibernates his device.

Actually I achieved in a project that just plays a bundle track, like you can see:

```<code>import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [sound, setSound] = React.useState();

  async function playSound() {
    console.log('Loading Sound');

    //On function below, could be used the following line below to get some file from ./assets folder, from device storage using require()
    //method, or using loadAsync({uri:url}) to get the file from web by its url, what can be noticed in the delimited block with "*** ***"
    //const { sound } = await Audio.Sound.createAsync( require('./assets/Hello.mp3')

    //***
    const sound = new Audio.Sound();
    await sound.loadAsync({
      uri: 'https://sound-library.net/wp-content/uploads/2022/08/oneheart-reidenshi-snowfall.mp3',
    });
    //***
    setSound(sound);

    console.log('Playing Sound');
    await sound.playAsync();
  }

  React.useEffect(() => {
    return sound
      ? () => {
        console.log('Unloading Sound');
        sound.unloadAsync();
      }
      : undefined;
  }, [sound]);

  return (
    <View style={styles.container}>
      <Button title="Play Sound" onPress={playSound} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
</code>```

I would like to know how I could do that with this feature.

Body:
I am new in React Native, so I don't master all related to background tasks, when I have to keep the app track playing even the user locks or hibernates his device.

Actually I achieved in a project that just plays a bundle track, like you can see:

import * as React from 'react';
import { Text, View, StyleSheet, Button } from 'react-native';
import { Audio } from 'expo-av';

export default function App() {
  const [sound, setSound] = React.useState();

  async function playSound() {
    console.log('Loading Sound');

    //On function below, could be used the following line below to get some file from ./assets folder, from device storage using require()
    //method, or using loadAsync({uri:url}) to get the file from web by its url, what can be noticed in the delimited block with "*** ***"
    //const { sound } = await Audio.Sound.createAsync( require('./assets/Hello.mp3')

    //***
    const sound = new Audio.Sound();
    await sound.loadAsync({
      uri: 'https://sound-library.net/wp-content/uploads/2022/08/oneheart-reidenshi-snowfall.mp3',
    });
    //***
    setSound(sound);

    console.log('Playing Sound');
    await sound.playAsync();
  }

  React.useEffect(() => {
    return sound
      ? () => {
        console.log('Unloading Sound');
        sound.unloadAsync();
      }
      : undefined;
  }, [sound]);

  return (
    <View style={styles.container}>
      <Button title="Play Sound" onPress={playSound} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

I would like to know how I could do that with this feature.


问:
looking for the best way to connect to an SSH server with ReactJS
I have a website running on Node built from ReactJS and I want to have an option to send a file to an SSH remote server by entering IP, username and password.

I have been looking at large number of options but kept getting errors. I tried npm i ssh2 and node-ssh but both doesn't seem to be working well with React..

The simplest thing I tried was building a fresh website using npx create-react-app and adding node-ssh to it. I then tried adding the simple line of code

```<code>const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();
</code>```

But I kept getting these errors and after a lot of digging it seems like this is not the right way of approaching this.
This is why I need your help.. I believe there has to be a way to access SSH server from a node webserver..

Thank you

Body:
I have a website running on Node built from ReactJS and I want to have an option to send a file to an SSH remote server by entering IP, username and password.

I have been looking at large number of options but kept getting errors. I tried npm i ssh2 and node-ssh but both doesn't seem to be working well with React..

The simplest thing I tried was building a fresh website using npx create-react-app and adding node-ssh to it. I then tried adding the simple line of code

const { NodeSSH } = require('node-ssh');
const ssh = new NodeSSH();

But I kept getting these errors and after a lot of digging it seems like this is not the right way of approaching this.
This is why I need your help.. I believe there has to be a way to access SSH server from a node webserver..

Thank you


问:
DBPedia FactExtractor: fails on extract-pacges
I'm using the fact-extractor (link) to run their example of extracting info from the football wiki pages. I've installed and tested all dependencies on windows and when I execute "make extract-pages", i get the following error:

```<code>(dbpenv) C:\dbpedia\fact-extractor-master>make extract-pages
mkdir workspace-en
bzcat enwiki-latest-pages-articles.xml.bz2 | python lib/WikiExtractor.py -o workspace-en/pages
  File "lib/WikiExtractor.py", line 598
    print id, title.encode('utf-8')
           ^
SyntaxError: invalid syntax

bzcat: I/O or other error, bailing out.  Possible reason follows.
bzcat: Invalid argument
        Input file = enwiki-latest-pages-articles.xml.bz2, output file = (stdout)
make: *** [Makefile:39: extract-pages] Error 1
</code>```

I can't make sense of the error. This is an as-is codebase from their repo so I'm not really sure how to fix this.

Body:
I'm using the fact-extractor (link) to run their example of extracting info from the football wiki pages. I've installed and tested all dependencies on windows and when I execute "make extract-pages", i get the following error:

(dbpenv) C:\dbpedia\fact-extractor-master>make extract-pages
mkdir workspace-en
bzcat enwiki-latest-pages-articles.xml.bz2 | python lib/WikiExtractor.py -o workspace-en/pages
  File "lib/WikiExtractor.py", line 598
    print id, title.encode('utf-8')
           ^
SyntaxError: invalid syntax

bzcat: I/O or other error, bailing out.  Possible reason follows.
bzcat: Invalid argument
        Input file = enwiki-latest-pages-articles.xml.bz2, output file = (stdout)
make: *** [Makefile:39: extract-pages] Error 1

I can't make sense of the error. This is an as-is codebase from their repo so I'm not really sure how to fix this.


问:
Error with exported function having a "simple" argument and and calling the function with a field entry
Here's the situation:

In a library:

export fctn( simple int m )
...

In the calling code:

type Test
int n

inst = Test.new( n = 1 )
y = Library.fctn( inst.n )
...

This produces an error message that the function is being called with a "series int" when it must be called with a "simple int".

I may be missing something here, and it may be dealing with the simple input to the function. There were no errors when I avoided the object approach.


问:
Extracting text from image - OCR
I'm using cv2 and pytesseract library to extract text from image. Here is the image (image3_3.png) and the python code:

```<code>def threshold_image(img_src):
    """Grayscale image and apply Otsu's threshold"""
    # Grayscale
    img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
    # Binarisation and Otsu's threshold
    img_thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    return img_thresh

img = np.array(Image.open('image3_3.png'))
# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)

# normalise the image
norm_img = np.zeros((img.shape[0], img.shape[1]))
img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)
# Apply blur to smooth out the edges
img = cv2.GaussianBlur(img, (5, 5), 0)
string_ocr = pytesseract.image_to_string(threshold_image(img), lang = 'eng', config = '--psm 6')
print(string_ocr)
</code>```

Here is the result:

```<code>Image A3. This is image A3 with more texts.

ISAS Visual Analytics

INow everyone can easily discover and share powerful
Nsights that inspire action

</code>```

Why am I not getting the same exact text? Any help highly appreciated.

Title: Extracting text from image - OCR

Body:
I'm using cv2 and pytesseract library to extract text from image. Here is the image (image3_3.png) and the python code:

def threshold_image(img_src):
    """Grayscale image and apply Otsu's threshold"""
    # Grayscale
    img_gray = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
    # Binarisation and Otsu's threshold
    img_thresh = cv2.threshold(img_gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]
    return img_thresh

img = np.array(Image.open('image3_3.png'))
# Apply dilation and erosion to remove some noise
kernel = np.ones((1, 1), np.uint8)
img = cv2.dilate(img, kernel, iterations=1)
img = cv2.erode(img, kernel, iterations=1)

# normalise the image
norm_img = np.zeros((img.shape[0], img.shape[1]))
img = cv2.normalize(img, norm_img, 0, 255, cv2.NORM_MINMAX)
# Apply blur to smooth out the edges
img = cv2.GaussianBlur(img, (5, 5), 0)
string_ocr = pytesseract.image_to_string(threshold_image(img), lang = 'eng', config = '--psm 6')
print(string_ocr)

Here is the result:

Image A3. This is image A3 with more texts.

ISAS Visual Analytics

INow everyone can easily discover and share powerful
Nsights that inspire action

Why am I not getting the same exact text? Any help highly appreciated.


问:
Post a complex object using RestTemplate in Java
I want to post a complex object (CustomResponse) using RestTemplate

class CustomResponse { String name; Map<String, Employee> employeeMap; }

How can I accomplish it?

tried using postForEntity and postForObject. it doesn't work


问:
Declare custom DNS name for Fargate using CDK
I am creating a C# CDK stack that deploys both a Fargate service and an Elastic Beanstalk service.

Both these services will have a custom domain pointing to them using a third party domain service (i.e. non AWS).

For elastic beanstalk, I can simply set the CnamePrefix below, and AWS will generate something like http://beanstalk-dev.ap-southeast-2.elasticbeanstalk.com/ which I can then point my custom domain to (after adding some listeners to the load balancer).

 var elasticBeanstalkEnv = new CfnEnvironment(this, "ElbsEnv", new CfnEnvironmentProps
            {
                EnvironmentName = "beanstalk-dev",
                ApplicationName =  appName,
                SolutionStackName = "64bit Amazon Linux 2 v2.4.1 running .NET Core",
                OptionSettings = optionSettingProperties,
                VersionLabel = version.Ref,
                CnamePrefix = "beanstalk-dev", <--- This property
                Tier = new CfnEnvironment.TierProperty
                {
                    Name = "WebServer",
                    Type = "Standard"
                }
            });
```
<p>I am also trying to do something similar with Fargate. But I can not find any settings like the one for elastic beanstalk.</p>
<p>Below is what I have so far, which will deploy a DNS name like <code>LB-71455902.ap-southeast-2.elb.amazonaws.com</code></p>
<pre class="lang-cs prettyprint-override"><code> var fargate = new ApplicationLoadBalancedFargateService(this, "reportviewer-server",
                new ApplicationLoadBalancedFargateServiceProps
                {
                    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                    {
                        Image = ContainerImage.FromRegistry("myImage",
                            new RepositoryImageProps { Credentials = mycreds})
                    },
                    PublicLoadBalancer = true,
                    LoadBalancerName = "LB",
                    ServiceName = "frontend",
                    RecordType = ApplicationLoadBalancedServiceRecordType.CNAME
                });

            fargate.LoadBalancer.AddListener("ecs-https-listener", new ApplicationListenerProps
            {
                SslPolicy = SslPolicy.RECOMMENDED,
                Protocol = ApplicationProtocol.HTTPS,
                Open = true,
                Port = 443,
                Certificates = new IListenerCertificate[]
                {
                    ListenerCertificate.FromArn(
                        "myArn")
                },
                DefaultTargetGroups = new IApplicationTargetGroup[]
                {
                    fargate.TargetGroup
                }
            });
</code>```

How would I setup my stack to create a "static" DNS name that wont be different each time I create/destroy my stack?

Body:
I am creating a C# CDK stack that deploys both a Fargate service and an Elastic Beanstalk service.

Both these services will have a custom domain pointing to them using a third party domain service (i.e. non AWS).

For elastic beanstalk, I can simply set the CnamePrefix below, and AWS will generate something like http://beanstalk-dev.ap-southeast-2.elasticbeanstalk.com/ which I can then point my custom domain to (after adding some listeners to the load balancer).

 var elasticBeanstalkEnv = new CfnEnvironment(this, "ElbsEnv", new CfnEnvironmentProps
            {
                EnvironmentName = "beanstalk-dev",
                ApplicationName =  appName,
                SolutionStackName = "64bit Amazon Linux 2 v2.4.1 running .NET Core",
                OptionSettings = optionSettingProperties,
                VersionLabel = version.Ref,
                CnamePrefix = "beanstalk-dev", <--- This property
                Tier = new CfnEnvironment.TierProperty
                {
                    Name = "WebServer",
                    Type = "Standard"
                }
            });

I am also trying to do something similar with Fargate. But I can not find any settings like the one for elastic beanstalk.

Below is what I have so far, which will deploy a DNS name like LB-71455902.ap-southeast-2.elb.amazonaws.com

 var fargate = new ApplicationLoadBalancedFargateService(this, "reportviewer-server",
                new ApplicationLoadBalancedFargateServiceProps
                {
                    TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                    {
                        Image = ContainerImage.FromRegistry("myImage",
                            new RepositoryImageProps { Credentials = mycreds})
                    },
                    PublicLoadBalancer = true,
                    LoadBalancerName = "LB",
                    ServiceName = "frontend",
                    RecordType = ApplicationLoadBalancedServiceRecordType.CNAME
                });

            fargate.LoadBalancer.AddListener("ecs-https-listener", new ApplicationListenerProps
            {
                SslPolicy = SslPolicy.RECOMMENDED,
                Protocol = ApplicationProtocol.HTTPS,
                Open = true,
                Port = 443,
                Certificates = new IListenerCertificate[]
                {
                    ListenerCertificate.FromArn(
                        "myArn")
                },
                DefaultTargetGroups = new IApplicationTargetGroup[]
                {
                    fargate.TargetGroup
                }
            });

How would I setup my stack to create a "static" DNS name that wont be different each time I create/destroy my stack?


问:
What's torch._C._infer_size() means?
when I leran the kl_divergence of MultivariateNormal, I can't understand torch._C._infer_size(), so I ask for help, Thanks!

location: torch.distributions.kl.py

```<code>combined_batch_shape = torch._C._infer_size(q._unbroadcasted_scale_tril.shape[:-2],
                                            p._unbroadcasted_scale_tril.shape[:-2])
</code>```

total code:

```<code>@register_kl(MultivariateNormal, MultivariateNormal)
def _kl_multivariatenormal_multivariatenormal(p, q):
    # From https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Kullback%E2%80%93Leibler_divergence
    if p.event_shape != q.event_shape:
        raise ValueError("KL-divergence between two Multivariate Normals with\
                          different event shapes cannot be computed")

    half_term1 = (q._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) -
                  p._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1))
    combined_batch_shape = torch._C._infer_size(q._unbroadcasted_scale_tril.shape[:-2],
                                                p._unbroadcasted_scale_tril.shape[:-2])
    n = p.event_shape[0]
    q_scale_tril = q._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n))
    p_scale_tril = p._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n))
    term2 = _batch_trace_XXT(torch.linalg.solve_triangular(q_scale_tril, p_scale_tril, upper=False))
    term3 = _batch_mahalanobis(q._unbroadcasted_scale_tril, (q.loc - p.loc))
    return half_term1 + 0.5 * (term2 + term3 - n)
</code>```

I hope understand this method.

Title: What's torch._C._infer_size() means?

Body:
when I leran the kl_divergence of MultivariateNormal, I can't understand torch._C._infer_size(), so I ask for help, Thanks!

location: torch.distributions.kl.py

combined_batch_shape = torch._C._infer_size(q._unbroadcasted_scale_tril.shape[:-2],
                                            p._unbroadcasted_scale_tril.shape[:-2])

total code:

@register_kl(MultivariateNormal, MultivariateNormal)
def _kl_multivariatenormal_multivariatenormal(p, q):
    # From https://en.wikipedia.org/wiki/Multivariate_normal_distribution#Kullback%E2%80%93Leibler_divergence
    if p.event_shape != q.event_shape:
        raise ValueError("KL-divergence between two Multivariate Normals with\
                          different event shapes cannot be computed")

    half_term1 = (q._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1) -
                  p._unbroadcasted_scale_tril.diagonal(dim1=-2, dim2=-1).log().sum(-1))
    combined_batch_shape = torch._C._infer_size(q._unbroadcasted_scale_tril.shape[:-2],
                                                p._unbroadcasted_scale_tril.shape[:-2])
    n = p.event_shape[0]
    q_scale_tril = q._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n))
    p_scale_tril = p._unbroadcasted_scale_tril.expand(combined_batch_shape + (n, n))
    term2 = _batch_trace_XXT(torch.linalg.solve_triangular(q_scale_tril, p_scale_tril, upper=False))
    term3 = _batch_mahalanobis(q._unbroadcasted_scale_tril, (q.loc - p.loc))
    return half_term1 + 0.5 * (term2 + term3 - n)

I hope understand this method.


问:
RDLC header duplicates when no data is available
Here is my report

At first I wondered if it was because there were too many columns in a page, so the header overflowed to the bottom, causing it to repeat. I tried by paging it less data. After doing it, it still seems to be the same.

What am i missing?
Could you guys help me?


问:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null object reference
I have an activity that has a button that calling a random activity, but I always encounter this error. I'm still learning, so I really have no idea.

java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null
object reference

```<code>button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ArrayList<Class> activityList = new ArrayList<>();
        activityList.add(eleven14.class);
        activityList.add(fourth10.class);
        activityList.add(MainActivity15.class);
        activityList.add(MainActivity16.class);
        activityList.add(nine15.class);
        activityList.add(sixth8.class);
        activityList.add(ten14.class);
        activityList.add(twelve15.class);

        Random generator = new Random();
        int number = generator.nextInt(8) + 1;

        Class activity = null;

        // Here, we are checking to see what the output of the random was
        switch(number) {
            case 1:
                activity = eleven14.class;
                // We are adding the number of the activity to the list
                activityList.remove(eleven14.class);
                break;
            case 2:
                activity = fourth10.class;
                activityList.remove(fourth10.class);
                break;
            case 3:
                activity = MainActivity16.class;
                activityList.remove(MainActivity16.class);
                break;
            case 4:
                activity = nine15.class;
                activityList.remove(nine15.class);
                break;
            case 5:
                activity = sixth8.class;
                activityList.remove(sixth8.class);
                break;
            case 6:
                activity = ten14.class;
                activityList.remove(ten14.class);
                break;
            case 7:
                activity = twelve15.class;
                activityList.remove(twelve15.class);
                break;
            default:
                activity = MainActivity15.class;
                activityList.remove(MainActivity15.class);
                break;
        }
        // We use intents to start activities
        Intent intent = new Intent(getBaseContext(), activity);
        // `intent.putExtra(...)` is used to pass on extra information to the next activity
        intent.putExtra("LIST_A", activityList);
        startActivity(intent);
    }
});
</code>```

I put this to other activity

```<code>ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("LIST_A");

if (activityList.size() == 0) {
    showDialog();
} else {
    int r = new Random().nextInt(activityList.size());
    Class<? extends Activity> activity = activityList.remove(r);

    Intent intent = new Intent(getBaseContext(), activity);
    intent.putExtra("LIST_A", activityList);
    startActivity(intent);
}
</code>```

Body:
I have an activity that has a button that calling a random activity, but I always encounter this error. I'm still learning, so I really have no idea.

java.lang.NullPointerException: Attempt to invoke virtual method
'java.lang.Object android.os.Bundle.get(java.lang.String)' on a null
object reference

button = (Button) findViewById(R.id.play);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        ArrayList<Class> activityList = new ArrayList<>();
        activityList.add(eleven14.class);
        activityList.add(fourth10.class);
        activityList.add(MainActivity15.class);
        activityList.add(MainActivity16.class);
        activityList.add(nine15.class);
        activityList.add(sixth8.class);
        activityList.add(ten14.class);
        activityList.add(twelve15.class);

        Random generator = new Random();
        int number = generator.nextInt(8) + 1;

        Class activity = null;

        // Here, we are checking to see what the output of the random was
        switch(number) {
            case 1:
                activity = eleven14.class;
                // We are adding the number of the activity to the list
                activityList.remove(eleven14.class);
                break;
            case 2:
                activity = fourth10.class;
                activityList.remove(fourth10.class);
                break;
            case 3:
                activity = MainActivity16.class;
                activityList.remove(MainActivity16.class);
                break;
            case 4:
                activity = nine15.class;
                activityList.remove(nine15.class);
                break;
            case 5:
                activity = sixth8.class;
                activityList.remove(sixth8.class);
                break;
            case 6:
                activity = ten14.class;
                activityList.remove(ten14.class);
                break;
            case 7:
                activity = twelve15.class;
                activityList.remove(twelve15.class);
                break;
            default:
                activity = MainActivity15.class;
                activityList.remove(MainActivity15.class);
                break;
        }
        // We use intents to start activities
        Intent intent = new Intent(getBaseContext(), activity);
        // `intent.putExtra(...)` is used to pass on extra information to the next activity
        intent.putExtra("LIST_A", activityList);
        startActivity(intent);
    }
});

I put this to other activity

ArrayList<Class> activityList = new ArrayList<>();
Bundle extras = getIntent().getExtras();
activityList = (ArrayList<Class>) extras.get("LIST_A");

if (activityList.size() == 0) {
    showDialog();
} else {
    int r = new Random().nextInt(activityList.size());
    Class<? extends Activity> activity = activityList.remove(r);

    Intent intent = new Intent(getBaseContext(), activity);
    intent.putExtra("LIST_A", activityList);
    startActivity(intent);
}