问:
Update Comments state in Redux Toolkit
I'm creating a CRUD project with React and Redux toolkit and the problem is I can't update Comments after creating a new one.

I structured Comment Slice like that:

```<code>import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import commentsService from "./commentService";

const initialState = {
  comments: [],
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

export const createComment = createAsyncThunk(
  "api/newcomment",
  async (commentData, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await commentsService.createComment(commentData, token);
    } catch (error) {
      console.log(error);
    }
  }
);

export const getAllComments = createAsyncThunk(
  "api/comments",
  async (PostId, thunkAPI) => {
    const token = thunkAPI.getState().auth.user.token;
    return await commentsService.getAllComments(PostId, token);
  }
);

export const deleteComment = createAsyncThunk(
  "api/:id",
  async (id, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await commentsService.deleteComment(id, token);
    } catch (error) {
      console.log(error);
    }
  }
);

export const commentsSlice = createSlice({
  name: "comment",
  initialState,
  reducers: {
    reset: (state) => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(createComment.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(createComment.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.comments = state.comments.push(action.payload);
      })
      .addCase(createComment.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })
      .addCase(getAllComments.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getAllComments.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        const comments = state.comments.filter(
          (comment) => comment.PostId === action.payload.PostId
        );
        if (comments.length === 0) {
          state.comments.push(action.payload);
        }
      })
      .addCase(getAllComments.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })
      .addCase(deleteComment.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(deleteComment.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.comments = state.comments.filter(
          (comment) => comment.id !== action.payload.id
        );
      })
      .addCase(deleteComment.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      });
  },
});

</code>```

And CardPost where I dispatch comments:

```<code>const CardPost = ({ post }) => {
  const [show, setShow] = useState(false);
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);

  const PostId = post.id;

  const { comments, isLoading, isError, message } = useSelector(
    (state) => state.comments
  );

  useEffect(() => {
    if (isError) {
      console.log(message);
    }
    dispatch(getAllComments(PostId));
  }, [dispatch, PostId, isError, message]);

//// Show Comments
   <div>
              <div>
                <FormComment PostId={PostId} />
              </div>
              <div>
                {comments.length > 0 ? (
                  <div className="comments">
                    {comments.map((id) => (
                      <div key={id}>
                        <CardComment post={post} />
                      </div>
                    ))}
                  </div>
                ) : (
                  <Typography>No Comment..</Typography>
                )}
              </div>
            </div>

</code>```

When there are several comments on a Post that are displayed and I create a new one, it shows me the message "No comment.." but all the messages appear well when the page is refreshed.
Where did I make it wrong?
Is it the .addCase that I built wrong and the state is not updated or is it the useEffect dispatch?

Title: Update Comments state in Redux Toolkit

Body:
I'm creating a CRUD project with React and Redux toolkit and the problem is I can't update Comments after creating a new one.

I structured Comment Slice like that:

import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
import commentsService from "./commentService";

const initialState = {
  comments: [],
  isError: false,
  isSuccess: false,
  isLoading: false,
  message: "",
};

export const createComment = createAsyncThunk(
  "api/newcomment",
  async (commentData, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await commentsService.createComment(commentData, token);
    } catch (error) {
      console.log(error);
    }
  }
);

export const getAllComments = createAsyncThunk(
  "api/comments",
  async (PostId, thunkAPI) => {
    const token = thunkAPI.getState().auth.user.token;
    return await commentsService.getAllComments(PostId, token);
  }
);

export const deleteComment = createAsyncThunk(
  "api/:id",
  async (id, thunkAPI) => {
    try {
      const token = thunkAPI.getState().auth.user.token;
      return await commentsService.deleteComment(id, token);
    } catch (error) {
      console.log(error);
    }
  }
);

export const commentsSlice = createSlice({
  name: "comment",
  initialState,
  reducers: {
    reset: (state) => initialState,
  },
  extraReducers: (builder) => {
    builder
      .addCase(createComment.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(createComment.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.comments = state.comments.push(action.payload);
      })
      .addCase(createComment.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })
      .addCase(getAllComments.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(getAllComments.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        const comments = state.comments.filter(
          (comment) => comment.PostId === action.payload.PostId
        );
        if (comments.length === 0) {
          state.comments.push(action.payload);
        }
      })
      .addCase(getAllComments.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      })
      .addCase(deleteComment.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(deleteComment.fulfilled, (state, action) => {
        state.isLoading = false;
        state.isSuccess = true;
        state.comments = state.comments.filter(
          (comment) => comment.id !== action.payload.id
        );
      })
      .addCase(deleteComment.rejected, (state, action) => {
        state.isLoading = false;
        state.isError = true;
        state.message = action.payload;
      });
  },
});

And CardPost where I dispatch comments:

const CardPost = ({ post }) => {
  const [show, setShow] = useState(false);
  const dispatch = useDispatch();
  const { user } = useSelector((state) => state.auth);

  const PostId = post.id;

  const { comments, isLoading, isError, message } = useSelector(
    (state) => state.comments
  );

  useEffect(() => {
    if (isError) {
      console.log(message);
    }
    dispatch(getAllComments(PostId));
  }, [dispatch, PostId, isError, message]);

//// Show Comments

                <FormComment PostId={PostId} />

                {comments.length > 0 ? (

                    {comments.map((id) => (

                        <CardComment post={post} />

                    ))}

                ) : (
                  <Typography>No Comment..</Typography>
                )}

When there are several comments on a Post that are displayed and I create a new one, it shows me the message "No comment.." but all the messages appear well when the page is refreshed.
Where did I make it wrong?
Is it the .addCase that I built wrong and the state is not updated or is it the useEffect dispatch?


来源: stackexchange

问:
i want to change 'add cart' button to 'plus' ,'value', and 'minus' when click on "add cart" in shopping cart
```<code> $(".cart").click(function () {
    var idstr = this.id.toString();
    console.log(idstr);
    if (cart[idstr] != undefined) {
      console.log("exist");
      qty = cart[idstr][0] + 1;
      console.log(qty);
      console.log(cart[idstr][0]);
    } else {
      qty = 1;
      price = document.getElementById("price" + idstr).innerHTML;
      image = document.getElementById("img" + idstr).src;
      aname = document.getElementById("name" + idstr).innerHTML;
      console.log("not");
      cart[idstr] = [qty, aname, image, price];
    }

    console.log(cart);

  updateCart(cart);

    localStorage.setItem("cart", JSON.stringify(cart));
  });

  function updateCart(cart) {
    for (var item in cart) {
      document.getElementById("div" + item).innerHTML =
        "<button id='minus" +
        item +
        "' class='btn btn-primary minus'>-</button> <span id='val" +
        item +
        "''>" +
        cart[item][0] +
        "</span> <button id='plus" +
        item +
        "' class ='btn btn-primary plus'>+</button>";
    }
  }
</code>```

this happened when i try
i am expecting this

when i clicked on add cart button it didnt change to my expected buttons its means my function updateCart not working

ContentLicense: CC BY-SA 4.0

Body:
 $(".cart").click(function () {
    var idstr = this.id.toString();
    console.log(idstr);
    if (cart[idstr] != undefined) {
      console.log("exist");
      qty = cart[idstr][0] + 1;
      console.log(qty);
      console.log(cart[idstr][0]);
    } else {
      qty = 1;
      price = document.getElementById("price" + idstr).innerHTML;
      image = document.getElementById("img" + idstr).src;
      aname = document.getElementById("name" + idstr).innerHTML;
      console.log("not");
      cart[idstr] = [qty, aname, image, price];
    }

    console.log(cart);

  updateCart(cart);

    localStorage.setItem("cart", JSON.stringify(cart));
  });

  function updateCart(cart) {
    for (var item in cart) {
      document.getElementById("div" + item).innerHTML =
        "<button id='minus" +
        item +
        "' class='btn btn-primary minus'>-</button> " +
        cart[item][0] +
        " <button id='plus" +
        item +
        "' class ='btn btn-primary plus'>+</button>";
    }
  }

this happened when i try
i am expecting this

when i clicked on add cart button it didnt change to my expected buttons its means my function updateCart not working


问:
Rails - Dragonfly image upload to OCI using angular frontend
I am uploading a file in angular and returning rails params in imageData and imageContent variable. Then in rails controller, I try to create a temp file using those parameters and assign it to the dragonfly accessor attribute but it doesn't get uploaded on save. Though I've verified the file upload to OCI Object storage in rails console, its working fine.</p>
```<code>  dragonfly_accessor :logo do
    storage_options do |attachment|
      {
        path: "brand_logos/"
      }
    end
  end
</code>```
```<code>    decoded_data = Base64.decode64(params[:brand][:logo][:imageData]) # json parameter set in directive scope
    file_name = params[:brand][:logo][:imagePath]
    File.open(file_path, 'wb+') { |file| file.write(decoded_data) }
    params[:brand][:logo][:tempfile] = file_path # json parameter set in directive scope
</code>```

Body:
I am uploading a file in angular and returning rails params in imageData and imageContent variable. Then in rails controller, I try to create a temp file using those parameters and assign it to the dragonfly accessor attribute but it doesn't get uploaded on save. Though I've verified the file upload to OCI Object storage in rails console, its working fine.

  dragonfly_accessor :logo do
    storage_options do |attachment|
      {
        path: "brand_logos/"
      }
    end
  end

    decoded_data = Base64.decode64(params[:brand][:logo][:imageData]) # json parameter set in directive scope
    file_name = params[:brand][:logo][:imagePath]
    File.open(file_path, 'wb+') { |file| file.write(decoded_data) }
    params[:brand][:logo][:tempfile] = file_path # json parameter set in directive scope


问:
can we customize hash code in react build file
When we create our build with react script, (CRA boilerplate), we get some hash value in bundle.js file, can we customize it according to some uniqeTImestamp value,

we can do this while we configuring in webpack.config.js but how we do that while project is configured with create-react-app

currently  :

wanted to  :


问:
Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'vertical') - PDF VIEWER
TypeError: Cannot read properties of undefined (reading 'vertical') at appendText.
Version using -

```<code>"ng2-pdf-viewer": "^7.0.1"
</code>```

I'm getting this error while viewing a pdf. I've implemented pdf viewer inside a modal and while user click on view button this modal will appear. I've got the result and I can view it but getting this error on my console.

How can I handle this situation.

Body:
TypeError: Cannot read properties of undefined (reading 'vertical') at appendText.
Version using -

"ng2-pdf-viewer": "^7.0.1"

I'm getting this error while viewing a pdf. I've implemented pdf viewer inside a modal and while user click on view button this modal will appear. I've got the result and I can view it but getting this error on my console.

How can I handle this situation.


问:
Evaluate expression using printf in bash
I am on a bash and I am trying two commands with printf, but getting different results

```<code>[bhavukg@XYZ unixTutorial]$ printf "Result is %.3f\n", 8/3

Output:
bash: printf: 8/3: invalid number
Result is 0.000
</code>```
```<code>[bhavukg@XYZ unixTutorial]$ awk 'BEGIN {printf "result is %.3f", 8/3}'

Output:
result is 2.667
</code>```

My questions is why first printf not able to evaluate the expression. What other changes exist in both printf statements

Body:
I am on a bash and I am trying two commands with printf, but getting different results

[bhavukg@XYZ unixTutorial]$ printf "Result is %.3f\n", 8/3

Output:
bash: printf: 8/3: invalid number
Result is 0.000

[bhavukg@XYZ unixTutorial]$ awk 'BEGIN {printf "result is %.3f", 8/3}'

Output:
result is 2.667

My questions is why first printf not able to evaluate the expression. What other changes exist in both printf statements


问:
I'm having problems installing Diffuse on Ubuntu 20
I need a good "compare and merge" utility.
I though that Diffuse would be good since it has 3-way compare and is GIT compatible - but I can't figure out how to install it. I tried with python2 and with python3.

after apt-get update, I tried sudo apt-get install diffuse
and received the following:

Package diffuse is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source

E: Package 'diffuse' has no installation candidate

I'd appreciate any help - or suggestion for a good GUI compare that does 3-way comparison.

Thanks,
Mechi


问:
yarn jest "/folder1/test1.tsx|folder2/test2.tsx/gi" runs only first test
I want to run multiple tests with jest regex, but it only runs the first one

The yarn jest "/folder1/test1.tsx|folder2/test2.tsx/gi" command runs only folder1/test1.tsx test suite


问:
Issue with focus in Tiny MCE editor
We are using Tiny MCE editor and we are not able to access following UI elements using keyboard -

After adding table into the editor and upon navigating to each cell of the table using tab button, the cell is not getting highlighted which is becoming very difficult for visually impaired people to identify where the control is on.

After adding table into the editor, if we go to table->table properties->general tab->unable to see keyboard focus on checkbox next to ‘show caption’.

Upon analysing, got to know that the UI elements with property data-allow-tabstop as True are accessible using tabs which I tried adding to all its UI elements programmatically and failed.

Title: Issue with focus in Tiny MCE editor


问:
Serverless Cannot Run Simple Example Query Using Node.JS
I am trying to run a simple query locally in Node JS using serverless - for the eventual purpose of uploading an Apollo Server API onto AWS Lambda.

However, I am not able to get anywhere near the deployment step as it appears that Node is unable to run a single instance of Apollo Server/Serverless locally in the first place due to a multitude of errors which shall be explained below:

Steps I have taken:

git clone the example API and follow all instructions here: https://github.com/fullstack-hy2020/rate-repository-api (I ensured everything works perfectly)

Follow all instructions on Apollographql up to "Running Server Locally": https://www.apollographql.com/docs/apollo-server/deployment/lambda/ - then run following command: serverless invoke local -f graphql -p query.json

ERROR - cannot use import statement outside module .... Solution - add "type": "module" to package.json - run command: serverless invoke local -f graphql -p query.json

ERROR - Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js... Solution - install webpack as per solution here: Serverless does not recognise subdirectories in Node then run serverless invoke local -f graphql -p query.json

ERROR - Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js

I do not know how to proceed from here, I am hoping that someone can point me in the right direction.

File Structure:

apolloServer.js:

```<code>import { ApolloServer, toApolloError, ApolloError } from '@apollo/server';
import { ValidationError } from 'yup';
import { startServerAndCreateLambdaHandler } from '@as-integrations/aws-lambda';
import AuthService from './utils/authService';
import createDataLoaders from './utils/createDataLoaders';
import logger from './utils/logger';
import { resolvers, typeDefs } from './graphql/schema';

const apolloErrorFormatter = (error) => {
  logger.error(error);

  const { originalError } = error;
  const isGraphQLError = !(originalError instanceof Error);

  let normalizedError = new ApolloError(
    'Something went wrong',
    'INTERNAL_SERVER_ERROR',
  );

  if (originalError instanceof ValidationError) {
    normalizedError = toApolloError(error, 'BAD_USER_INPUT');
  } else if (error.originalError instanceof ApolloError || isGraphQLError) {
    normalizedError = error;
  }

  return normalizedError;
};

const createApolloServer = () => {
  return new ApolloServer({
    resolvers,
    typeDefs,
    formatError: apolloErrorFormatter,
    context: ({ req }) => {
      const authorization = req.headers.authorization;

      const accessToken = authorization
        ? authorization.split(' ')[1]
        : undefined;
      const dataLoaders = createDataLoaders();

      return {
        authService: new AuthService({
          accessToken,
          dataLoaders,
        }),
        dataLoaders,
      };
    },
  });
};

export const graphqlHandler = startServerAndCreateLambdaHandler(createApolloServer());

export default createApolloServer;
</code>```

Serverless.yml:

```<code>service: apollo-lambda

provider:
  name: aws
  runtime: nodejs16.x
  httpApi:
    cors: true
functions:
  graphql:
    # Make sure your file path is correct!
    # (e.g., if your file is in the root folder use server.graphqlHandler )
    # The format is: <FILENAME>.<HANDLER>
    handler: src/apolloServer.graphqlHandler
    events:
      - httpApi:
          path: /
          method: POST
      - httpApi:
          path: /
          method: GET
custom:
  webpack:
    packager: 'npm'
    webpackConfig: 'webpack.config.js' # Name of webpack configuration file
    includeModules:
      forceInclude:
        - pg
</code>```

Webpack.config.js

const path = require('path');

```<code>module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'foo.bundle.js',
  },
};
</code>```

Body:
I am trying to run a simple query locally in Node JS using serverless - for the eventual purpose of uploading an Apollo Server API onto AWS Lambda.

However, I am not able to get anywhere near the deployment step as it appears that Node is unable to run a single instance of Apollo Server/Serverless locally in the first place due to a multitude of errors which shall be explained below:

Steps I have taken:

git clone the example API and follow all instructions here: https://github.com/fullstack-hy2020/rate-repository-api (I ensured everything works perfectly)

Follow all instructions on Apollographql up to "Running Server Locally": https://www.apollographql.com/docs/apollo-server/deployment/lambda/ - then run following command: serverless invoke local -f graphql -p query.json

ERROR - cannot use import statement outside module .... Solution - add "type": "module" to package.json - run command: serverless invoke local -f graphql -p query.json

ERROR - Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js... Solution - install webpack as per solution here: Serverless does not recognise subdirectories in Node then run serverless invoke local -f graphql -p query.json

ERROR - Error [ERR_MODULE_NOT_FOUND]: Cannot find module 'C:\Users\Julius\Documents\Web Development\rate-repository-api\src\utils\authService' imported from C:\Users\Julius\Documents\Web Development\rate-repository-api\src\apolloServer.js

I do not know how to proceed from here, I am hoping that someone can point me in the right direction.

File Structure:

apolloServer.js:

import { ApolloServer, toApolloError, ApolloError } from '@apollo/server';
import { ValidationError } from 'yup';
import { startServerAndCreateLambdaHandler } from '@as-integrations/aws-lambda';
import AuthService from './utils/authService';
import createDataLoaders from './utils/createDataLoaders';
import logger from './utils/logger';
import { resolvers, typeDefs } from './graphql/schema';

const apolloErrorFormatter = (error) => {
  logger.error(error);

  const { originalError } = error;
  const isGraphQLError = !(originalError instanceof Error);

  let normalizedError = new ApolloError(
    'Something went wrong',
    'INTERNAL_SERVER_ERROR',
  );

  if (originalError instanceof ValidationError) {
    normalizedError = toApolloError(error, 'BAD_USER_INPUT');
  } else if (error.originalError instanceof ApolloError || isGraphQLError) {
    normalizedError = error;
  }

  return normalizedError;
};

const createApolloServer = () => {
  return new ApolloServer({
    resolvers,
    typeDefs,
    formatError: apolloErrorFormatter,
    context: ({ req }) => {
      const authorization = req.headers.authorization;

      const accessToken = authorization
        ? authorization.split(' ')[1]
        : undefined;
      const dataLoaders = createDataLoaders();

      return {
        authService: new AuthService({
          accessToken,
          dataLoaders,
        }),
        dataLoaders,
      };
    },
  });
};

export const graphqlHandler = startServerAndCreateLambdaHandler(createApolloServer());

export default createApolloServer;

Serverless.yml:

service: apollo-lambda

provider:
  name: aws
  runtime: nodejs16.x
  httpApi:
    cors: true
functions:
  graphql:
    # Make sure your file path is correct!
    # (e.g., if your file is in the root folder use server.graphqlHandler )
    # The format is: <FILENAME>.<HANDLER>
    handler: src/apolloServer.graphqlHandler
    events:
      - httpApi:
          path: /
          method: POST
      - httpApi:
          path: /
          method: GET
custom:
  webpack:
    packager: 'npm'
    webpackConfig: 'webpack.config.js' # Name of webpack configuration file
    includeModules:
      forceInclude:
        - pg

Webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'build'),
    filename: 'foo.bundle.js',
  },
};


问:
Clustering the characters (alphabets/digits) based on bounding boxes into appropriate words
Following is the image of medicine.

I have trained an object detection (Yolov4) model to identify the characters (numbers/alphabets) in the image. In the above image the green dots represent the center coordinates of the bounding boxes of individual digits (I haven't drawn the bounding boxes as it looks very cluttered but I am getting proper boxes). My end goal is to detect text from the images, ie to group the digits into words. Can someone think of an algorithm to cluster the individual digits into words based on the bounding box coordinates of the digits. The correct word representation of above image would be:

Word1 : 'BNOE2IAT016'

WORD2 : 'MFG112020'

WORD3 :  'EXP10'

I was able to correctly get the words by incorporating a text detection model like CRAFT. After getting the bounding box of words I simply checked whether the center coordinate of digit is inside the box or not. But CRAFT model adds huge overhead in terms of time complexity (7 secs). How to do it without any text detection model?


问:
how can I connect mongoose with migrate-mongo
I want to do db migration with  migrate-mongo and I want to connect mongoose in migrate-mongo-config.js file. how can I do it?

I want to do db migration with  migrate-mongo and I want to connect mongoose in migrate-mongo-config.js file. how can I do it?


问:
Mac M1 assembly bus error with Sample Hello World display program
I am new to assembly and would like to learn arm assembly on Mac M1, which is my dev environment.
I need help finding many online resources, so I'm here.
My code is as follows (the file is called Test5.s).

When I executed the program, I got the following error:

bus error  ./Test5

Here below is the code of the program

```<code>`// Assembler program to print " Hello World!"
// to stdout
// X0-X2 - parameters to linux functions services
// x16 - linux function number
// syscall write(int fd, const void *buf, size_t count)

.text

// Our application's entry points.

.global _main
.align  2

_main:
    mov     X0, #1                      ; arg [0] = 1 = StdOut
    ldr     X1, =helloworld             ; arg [1] = String to print
    mov     X2, #16                     ; arg [2] = lenght of our string

    mov     X16, #4                 ; Unix write system call
    svc     #0x80                   ; Call kernel to output the string program

// Setup the parameters to exit the program
// and then call the kernet to do it.
    mov     X0,     #0                  ; Use 0 return code
    mov     X16,    #1                  ; Unit exit system call
    svc     #0x80                       ; Call kernel to end program

.data
helloworld: .ascii  "Hello M1-World!\n";`

</code>```

Here is the command used for the compilation and the linking in my makefile

```<code>Test5: Test5.o
    ld -o Test5 Test5.o -lSystem -syslibroot `xcrun -sdk macosx --show-sdk-path` -e _main -arch arm64

Test5.o: Test5.s
    as -arch arm64 -o Test5.o Test5.s

clean:
    rm -f *.o
    rm -f Test5

</code>```

Body:
I am new to assembly and would like to learn arm assembly on Mac M1, which is my dev environment.
I need help finding many online resources, so I'm here.
My code is as follows (the file is called Test5.s).

When I executed the program, I got the following error:

bus error  ./Test5

Here below is the code of the program

`// Assembler program to print " Hello World!"
// to stdout
// X0-X2 - parameters to linux functions services
// x16 - linux function number
// syscall write(int fd, const void *buf, size_t count)

.text

// Our application's entry points.

.global _main
.align  2

_main:
    mov     X0, #1                      ; arg [0] = 1 = StdOut
    ldr     X1, =helloworld             ; arg [1] = String to print
    mov     X2, #16                     ; arg [2] = lenght of our string

    mov     X16, #4                 ; Unix write system call
    svc     #0x80                   ; Call kernel to output the string program

// Setup the parameters to exit the program
// and then call the kernet to do it.
    mov     X0,     #0                  ; Use 0 return code
    mov     X16,    #1                  ; Unit exit system call
    svc     #0x80                       ; Call kernel to end program

.data
helloworld: .ascii  "Hello M1-World!\n";`

Here is the command used for the compilation and the linking in my makefile

Test5: Test5.o
    ld -o Test5 Test5.o -lSystem -syslibroot `xcrun -sdk macosx --show-sdk-path` -e _main -arch arm64

Test5.o: Test5.s
    as -arch arm64 -o Test5.o Test5.s

clean:
    rm -f *.o
    rm -f Test5


问:
Find x and y coordinates from real world coordinates and euler angles and camera intrinsics
I have a large file with CAN detections and in this file I have head pose coordinates which are x, y, z in meters, and Roll, Pitch and Yaw parameters in Euler angles. I also have camera matrix from camera intrinsics.

I want to project 2D points (x,y in pixels).

Could someone check and tell me what is wrong with my approach?
Keep in mind that I'm completely newbie in programming so I probably did lost of silly things like creating the same loop few times etc.

Maybe there is better approach? I'm not used to work with large data files

I find rotation matrix for every detection in datalist using this function (listrange is length of datalist):

```<code>def Rx(theta):
    return np.matrix([
                      [1, 0           , 0             ],
                      [0, m.cos(theta), -m.sin(theta) ],
                      [0, m.sin(theta), m.cos(theta)  ]
                                                       ])
def Ry(theta):
    return np.matrix([
                      [m.cos(theta) , 0, m.sin(theta)  ],
                      [0            , 1, 0             ],
                      [-m.sin(theta), 0, m.cos(theta)  ]
                                                       ])
def Rz(theta):
    return np.matrix([
                      [m.cos(theta) , -m.sin(theta), 0],
                      [m.sin(theta) ,  m.cos(theta), 0],
                      [0            , 0            , 1]
                                                       ])
rmatrix = []
for i in range(listrange):
    r_temp = Rz(datalist[i]['HeadPose']['Orientation']['Yaw']) * Ry(datalist[i]['HeadPose']['Orientation']['Pitch']) * Rx(datalist[i]['HeadPose']['Orientation']['Roll'])
    rmatrix.append(r_temp)
</code>```

then I find rotation vector for every point in the list. rvec1 and jacobian1 are created for later

```<code>rvec = []
jacobian = []
for i in rmatrix:
    rvec_temp, jacobian_temp = cv2.Rodrigues(i)
    rvec.append(rvec_temp)
    jacobian.append(jacobian_temp)

rvec1 = np.array(rvec)
jacobian1 = np.array(jacobian)
</code>```

after that I'm trying to extract object points from my datalist. x y z are in meters

```<code>objectPoints = []
for i in range(0,listrange):
    objectpoints_temp = np.float32([[datalist[i]['HeadPose']['Position']['x']*100, 0, 0], [0, datalist[i]['HeadPose']['Position']['y']*100, 0], [0, 0, datalist[i]['HeadPose']['Position']['z']*100]])
    objectPoints.append(objectpoints_temp)

objectPoints1 = np.array(objectPoints, dtype = object)
</code>```

And after that I have translation vector which should be (0,0,0) for every point and I want to use projectPoints function in openCV to extract image points. Camera matrix and DistCoeffs parameters are from producer of camera.

```<code>for g in range(listrange):
    imagePoints_temp, _ = cv2.projectPoints(objectPoints[g], rvec1[g], tvec, cameramatrix, distCoeffs)
    imagePoints_temp1 = cv2.projectPoints(objectPoints[g], rvec1[g], tvec, cameramatrix, distCoeffs)
    imagePoints.append(imagePoints_temp)
    imagePoints_.append(imagePoints_temp1)

imagePoints1 = np.array(imagePoints, dtype = object)
imagePoints_1 = np.array(imagePoints_, dtype = object)
</code>```

And in my opinion I should get an output of list of x and y coordinates in pixels.
What I got is imagePoints indeed, but in debug mode I see that coordinates looks random, and they are not in pixels for sure.

what is inside imagePoints variable

Body:
I have a large file with CAN detections and in this file I have head pose coordinates which are x, y, z in meters, and Roll, Pitch and Yaw parameters in Euler angles. I also have camera matrix from camera intrinsics.

I want to project 2D points (x,y in pixels).

Could someone check and tell me what is wrong with my approach?
Keep in mind that I'm completely newbie in programming so I probably did lost of silly things like creating the same loop few times etc.

Maybe there is better approach? I'm not used to work with large data files

I find rotation matrix for every detection in datalist using this function (listrange is length of datalist):

def Rx(theta):
    return np.matrix([
                      [1, 0           , 0             ],
                      [0, m.cos(theta), -m.sin(theta) ],
                      [0, m.sin(theta), m.cos(theta)  ]
                                                       ])
def Ry(theta):
    return np.matrix([
                      [m.cos(theta) , 0, m.sin(theta)  ],
                      [0            , 1, 0             ],
                      [-m.sin(theta), 0, m.cos(theta)  ]
                                                       ])
def Rz(theta):
    return np.matrix([
                      [m.cos(theta) , -m.sin(theta), 0],
                      [m.sin(theta) ,  m.cos(theta), 0],
                      [0            , 0            , 1]
                                                       ])
rmatrix = []
for i in range(listrange):
    r_temp = Rz(datalist[i]['HeadPose']['Orientation']['Yaw']) * Ry(datalist[i]['HeadPose']['Orientation']['Pitch']) * Rx(datalist[i]['HeadPose']['Orientation']['Roll'])
    rmatrix.append(r_temp)

then I find rotation vector for every point in the list. rvec1 and jacobian1 are created for later

rvec = []
jacobian = []
for i in rmatrix:
    rvec_temp, jacobian_temp = cv2.Rodrigues(i)
    rvec.append(rvec_temp)
    jacobian.append(jacobian_temp)

rvec1 = np.array(rvec)
jacobian1 = np.array(jacobian)

after that I'm trying to extract object points from my datalist. x y z are in meters

objectPoints = []
for i in range(0,listrange):
    objectpoints_temp = np.float32([[datalist[i]['HeadPose']['Position']['x']*100, 0, 0], [0, datalist[i]['HeadPose']['Position']['y']*100, 0], [0, 0, datalist[i]['HeadPose']['Position']['z']*100]])
    objectPoints.append(objectpoints_temp)

objectPoints1 = np.array(objectPoints, dtype = object)

And after that I have translation vector which should be (0,0,0) for every point and I want to use projectPoints function in openCV to extract image points. Camera matrix and DistCoeffs parameters are from producer of camera.

for g in range(listrange):
    imagePoints_temp, _ = cv2.projectPoints(objectPoints[g], rvec1[g], tvec, cameramatrix, distCoeffs)
    imagePoints_temp1 = cv2.projectPoints(objectPoints[g], rvec1[g], tvec, cameramatrix, distCoeffs)
    imagePoints.append(imagePoints_temp)
    imagePoints_.append(imagePoints_temp1)

imagePoints1 = np.array(imagePoints, dtype = object)
imagePoints_1 = np.array(imagePoints_, dtype = object)

And in my opinion I should get an output of list of x and y coordinates in pixels.
What I got is imagePoints indeed, but in debug mode I see that coordinates looks random, and they are not in pixels for sure.

what is inside imagePoints variable


问:
Opencv is not working in wsgi apache server
```<code>jpg_original = base64.b64decode(img_str.encode("utf-8"))
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img_matlab = cv2.imdecode(jpg_as_np, flags=1)

</code>```

I am trying decode base64 image in apache server,numy operation is working control is stucked at imdecode part. I am new in apache wsgi. Dont know what I am missing. I am sharing apache2.conf

```<code><VirtualHost *:80>

    # Python application integration
    WSGIDaemonProcess /apache-flask processes=1 threads=4 python-path=/var/www/apache-flask/:/usr/bin/python
    WSGIProcessGroup /apache-flask
    WSGIScriptAlias / /var/www/apache-flask/apache-flask.wsgi

    <Directory "/var/www/apache-flask/app/">
        Header set Access-Control-Allow-Origin "*"
        WSGIProcessGroup /apache-flask
        WSGIApplicationGroup %{GLOBAL}
        Options +ExecCGI
        Order deny,allow
        Allow from all
    </Directory>
    Alias /static /var/www/apache-flask/app/static
    <Directory /var/www/apache-flask/app/static/>
        Order allow,deny
        Allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

</code>```

I have build docker image for apache server. Below is the Dockerfile.

```<code># Set the base image
FROM debian:latest

# File Author / Maintainer
MAINTAINER nitinashu1995@gmail.com

RUN apt-get update -y
RUN apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 -y
RUN apt-get -y  install libapache2-mod-wsgi-py3
RUN apt-get install -y apache2
RUN pip3 install -U Flask
RUN pip3 install pymongo
RUN apt-get install iputils-ping -y
RUN apt-get install vim -y
RUN pip3 install pytz
RUN pip3 install -U flask-cors
RUN apt update

# Copy over and install the requirements
COPY ./app/requirements.txt /var/www/apache-flask/app/requirements.txt
RUN pip install -r /var/www/apache-flask/app/requirements.txt

# Copy over the apache configuration file and enable the site
COPY ./apache-flask.conf /etc/apache2/sites-available/apache-flask.conf
RUN a2ensite apache-flask
RUN a2enmod headers

# Copy over the wsgi file
COPY ./apache-flask.wsgi /var/www/apache-flask/apache-flask.wsgi

COPY ./run.py /var/www/apache-flask/run.py
COPY ./app /var/www/apache-flask/app/

RUN a2dissite 000-default.conf
RUN a2ensite apache-flask.conf

# LINK apache config to docker logs.
RUN ln -sf /proc/self/fd/1 /var/log/apache2/access.log && \
    ln -sf /proc/self/fd/1 /var/log/apache2/error.log

EXPOSE 80

WORKDIR /var/www/apache-flask
RUN pip install opencv-python-headless==4.5.3.56 numpy
RUN apt install cmake -y
RUN pip install face_recognition
CMD  /usr/sbin/apache2ctl -D FOREGROUND

</code>```

I am not able to run opencv with apache2, I am getting timeout.

```<code>
[Tue Dec 27 10:15:03.701128 2022] [wsgi:error] [pid 11:tid 140363481642752] [client 192.168.0.138:41568] Timeout when reading response headers from daemon process '/apache-flask':
/var/www/apache-flask/apache-flask.wsgi

</code>```

I am able to run opencv within container seems some configuration is missing.

Not able to find whats wrong.

Body:
jpg_original = base64.b64decode(img_str.encode("utf-8"))
jpg_as_np = np.frombuffer(jpg_original, dtype=np.uint8)
img_matlab = cv2.imdecode(jpg_as_np, flags=1)

I am trying decode base64 image in apache server,numy operation is working control is stucked at imdecode part. I am new in apache wsgi. Dont know what I am missing. I am sharing apache2.conf

<VirtualHost *:80>

    # Python application integration
    WSGIDaemonProcess /apache-flask processes=1 threads=4 python-path=/var/www/apache-flask/:/usr/bin/python
    WSGIProcessGroup /apache-flask
    WSGIScriptAlias / /var/www/apache-flask/apache-flask.wsgi

    <Directory "/var/www/apache-flask/app/">
        Header set Access-Control-Allow-Origin "*"
        WSGIProcessGroup /apache-flask
        WSGIApplicationGroup %{GLOBAL}
        Options +ExecCGI
        Order deny,allow
        Allow from all
    </Directory>
    Alias /static /var/www/apache-flask/app/static
    <Directory /var/www/apache-flask/app/static/>
        Order allow,deny
        Allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

I have build docker image for apache server. Below is the Dockerfile.

# Set the base image
FROM debian:latest

# File Author / Maintainer
MAINTAINER nitinashu1995@gmail.com

RUN apt-get update -y
RUN apt-get install python3-pip apache2 libapache2-mod-wsgi-py3 -y
RUN apt-get -y  install libapache2-mod-wsgi-py3
RUN apt-get install -y apache2
RUN pip3 install -U Flask
RUN pip3 install pymongo
RUN apt-get install iputils-ping -y
RUN apt-get install vim -y
RUN pip3 install pytz
RUN pip3 install -U flask-cors
RUN apt update

# Copy over and install the requirements
COPY ./app/requirements.txt /var/www/apache-flask/app/requirements.txt
RUN pip install -r /var/www/apache-flask/app/requirements.txt

# Copy over the apache configuration file and enable the site
COPY ./apache-flask.conf /etc/apache2/sites-available/apache-flask.conf
RUN a2ensite apache-flask
RUN a2enmod headers

# Copy over the wsgi file
COPY ./apache-flask.wsgi /var/www/apache-flask/apache-flask.wsgi

COPY ./run.py /var/www/apache-flask/run.py
COPY ./app /var/www/apache-flask/app/

RUN a2dissite 000-default.conf
RUN a2ensite apache-flask.conf

# LINK apache config to docker logs.
RUN ln -sf /proc/self/fd/1 /var/log/apache2/access.log && \
    ln -sf /proc/self/fd/1 /var/log/apache2/error.log

EXPOSE 80

WORKDIR /var/www/apache-flask
RUN pip install opencv-python-headless==4.5.3.56 numpy
RUN apt install cmake -y
RUN pip install face_recognition
CMD  /usr/sbin/apache2ctl -D FOREGROUND

I am not able to run opencv with apache2, I am getting timeout.

[Tue Dec 27 10:15:03.701128 2022] [wsgi:error] [pid 11:tid 140363481642752] [client 192.168.0.138:41568] Timeout when reading response headers from daemon process '/apache-flask':
/var/www/apache-flask/apache-flask.wsgi

I am able to run opencv within container seems some configuration is missing.

Not able to find whats wrong.


问:
I want to create custom menu & also add submenu in it. In sub menu, I want to add my all sheet name automatically in google sheet
I'm trying to all sheet name add automatically in sub menu of my custom menu. Please solve this. I tried too many times.</p>
```<code>

installFunctions(); // This is required to run the function. So please don't remove this.
function onOpen_panda() {} // This can be used as the simple trigger.

function installFunctions() {
  const menu = SpreadsheetApp.getUi().createMenu('sample menu').addSubMenu('Sheet List');
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getSheets().forEach(s => {
    if (!s.isSheetHidden()) {
      const name = s.getSheetName();
      const functionName = `sample${Utilities.base64Encode(name).replace(/[=+\/]/g, "")}`;
      this[functionName] = () => ss.getSheetByName(name).activate();
      menu.addItem(name, functionName);
    }
  })
  menu.addToUi();
}

</code>```

Body:
I'm trying to all sheet name add automatically in sub menu of my custom menu. Please solve this. I tried too many times.

installFunctions(); // This is required to run the function. So please don't remove this.
function onOpen_panda() {} // This can be used as the simple trigger.

function installFunctions() {
  const menu = SpreadsheetApp.getUi().createMenu('sample menu').addSubMenu('Sheet List');
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  ss.getSheets().forEach(s => {
    if (!s.isSheetHidden()) {
      const name = s.getSheetName();
      const functionName = `sample${Utilities.base64Encode(name).replace(/[=+\/]/g, "")}`;
      this[functionName] = () => ss.getSheetByName(name).activate();
      menu.addItem(name, functionName);
    }
  })
  menu.addToUi();
}


问:
Python Poetry Plugins with spaces (0x20) in their name
I want to port my project from flit to poetry and I run into this issue (which is probably a TOML issue at its core: https://github.com/toml-lang/toml/issues/185).

The plugin section (or rather entrypoints) used to look like this:

[tool.flit.entrypoints."rmtoo.input.requirement_status"]
"not done" = "rmtoo.lib.RequirementStatus:RequirementStatusNotDone"
"assigned" = "rmtoo.lib.RequirementStatus:RequirementStatusAssigned"
"finished" = "rmtoo.lib.RequirementStatus:RequirementStatusFinished"
```
<p>Now with poetry it looks like this:</p>
<pre class="lang-ini prettyprint-override"><code>[tool.poetry.plugins."rmtoo.input.requirement_status"]
"not done" = "rmtoo.lib.RequirementStatus:RequirementStatusNotDone"
"assigned" = "rmtoo.lib.RequirementStatus:RequirementStatusAssigned"
"finished" = "rmtoo.lib.RequirementStatus:RequirementStatusFinished"
</code>```

From what I could determine, the space in "not done" is ignored and all my tests fail.

Does anybody know a way around this?

Body:
I want to port my project from flit to poetry and I run into this issue (which is probably a TOML issue at its core: https://github.com/toml-lang/toml/issues/185).

The plugin section (or rather entrypoints) used to look like this:

[tool.flit.entrypoints."rmtoo.input.requirement_status"]
"not done" = "rmtoo.lib.RequirementStatus:RequirementStatusNotDone"
"assigned" = "rmtoo.lib.RequirementStatus:RequirementStatusAssigned"
"finished" = "rmtoo.lib.RequirementStatus:RequirementStatusFinished"

Now with poetry it looks like this:

[tool.poetry.plugins."rmtoo.input.requirement_status"]
"not done" = "rmtoo.lib.RequirementStatus:RequirementStatusNotDone"
"assigned" = "rmtoo.lib.RequirementStatus:RequirementStatusAssigned"
"finished" = "rmtoo.lib.RequirementStatus:RequirementStatusFinished"

From what I could determine, the space in "not done" is ignored and all my tests fail.

Does anybody know a way around this?


问:
QML MediaPlayer sound with turned on silent mode on iOS
I'm using QML MediaPlayer with VideoRole audioRole. And currently, if user tirning on silent mode, audio of video became muted. How I can avoid that?


问:
Adding Counter on repeated pairs
I'm trying to put a counter on pair of every mac and ip received . while debugging the counter showing how many times i got an entry but printing it showing 0 everytime

import pyshark
from collections import Counter

# Creating a file capture, give path of your captured file, adding display filter
capture = pyshark.LiveCapture(interface='Wi-Fi', display_filter='arp or udp.port eq 67')
capture.sniff_continuously()
d = dict()
count1 = Counter()
empty_mac = ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff')

# Running for loop for extracting fields from captured packets
for packet in capture:
    try:
        d["Arp_IP"] = packet.arp.dst_proto_ipv4
        d["Arp_Mac"] = packet.arp.dst_hw_mac
        #milli_time = packet.sniff_timestamp

    except AttributeError:
        pass

    count1.update([(d['Arp_IP'], d['Arp_Mac'])])
    if d["Arp_Mac"] not in empty_mac:
        print(packet.sniff_timestamp, count1[(d['Arp_Mac'], d['Arp_IP'])], d['Arp_Mac'], d['Arp_IP'])

```
<p>current OP:</p>
```1672138792.786440000 0 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 0 14:13:3x:42:xx:xx 192.168.1.10
1672138792.786440000 0 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 0 14:13:3x:42:xx:xx 192.168.1.10
```
<p>Expected OP:</p>
```1672138792.786440000 1 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 1 14:13:3x:42:xx:xx 192.168.1.10
1672138792.786440000 2 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 2 14:13:3x:42:xx:xx 192.168.1.10
```

Title: Adding Counter on repeated pairs

Body:
I'm trying to put a counter on pair of every mac and ip received . while debugging the counter showing how many times i got an entry but printing it showing 0 everytime

import pyshark
from collections import Counter

# Creating a file capture, give path of your captured file, adding display filter
capture = pyshark.LiveCapture(interface='Wi-Fi', display_filter='arp or udp.port eq 67')
capture.sniff_continuously()
d = dict()
count1 = Counter()
empty_mac = ('00:00:00:00:00:00', 'ff:ff:ff:ff:ff:ff')

# Running for loop for extracting fields from captured packets
for packet in capture:
    try:
        d["Arp_IP"] = packet.arp.dst_proto_ipv4
        d["Arp_Mac"] = packet.arp.dst_hw_mac
        #milli_time = packet.sniff_timestamp

    except AttributeError:
        pass

    count1.update([(d['Arp_IP'], d['Arp_Mac'])])
    if d["Arp_Mac"] not in empty_mac:
        print(packet.sniff_timestamp, count1[(d['Arp_Mac'], d['Arp_IP'])], d['Arp_Mac'], d['Arp_IP'])

current OP:

1672138792.786440000 0 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 0 14:13:3x:42:xx:xx 192.168.1.10
1672138792.786440000 0 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 0 14:13:3x:42:xx:xx 192.168.1.10

Expected OP:

1672138792.786440000 1 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 1 14:13:3x:42:xx:xx 192.168.1.10
1672138792.786440000 2 14:13:3x:42:xx:xx 192.168.1.5
1672138793.365195000 2 14:13:3x:42:xx:xx 192.168.1.10


问:
Add new collection in the existing user in firebase using android studio

how can I add a new collection in '57uGiwFdiKZsbn.....' name product and giving timestamp as my unique id in android studio

```<code>firebaseFirestore.collection("Users").document(user.getUid()).collection("Product").document(timestamp)
                                    .set(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            //added to db
                                            progressDialog.dismiss();
                                            Toast.makeText(d1.this, "Product added...", Toast.LENGTH_SHORT).show();
                                            clearData();
                                        }
                                    })
</code>```

Body:
how can I add a new collection in '57uGiwFdiKZsbn.....' name product and giving timestamp as my unique id in android studio

firebaseFirestore.collection("Users").document(user.getUid()).collection("Product").document(timestamp)
                                    .set(hashMap).addOnSuccessListener(new OnSuccessListener<Void>() {
                                        @Override
                                        public void onSuccess(Void aVoid) {
                                            //added to db
                                            progressDialog.dismiss();
                                            Toast.makeText(d1.this, "Product added...", Toast.LENGTH_SHORT).show();
                                            clearData();
                                        }
                                    })


问:
Why call rows.Close() could take long time in pgx?
Why call rows.Close() takes too long time when I call it after I exit from loop rows.Next() before processing all elements of loop.

Its happen when I make request which returns huge amount of data (around 300 000 rows).

This problem doesn't exists when amount of rows is not so big.

```<code>func SelectHugeAmountOfRows() {
    query := `SELECT * FROM big_table`
    rows, _ := Conn.Query(context.Background(), query)
    defer func() {
        fmt.Println("Start close rows")
        start := time.Now()
        rows.Close()
        duration := time.Since(start)
        fmt.Println("rowsClose duration:", duration)
    }()

    for rows.Next() {
        rowValues, err := rows.Values()
        if err != nil {
            fmt.Println(err)
            return
        }

        // do something with rowValues and get error in process
        err = func() error {
            fmt.Println(rowValues)
            return errors.New("some error")
        }()

        if err != nil {
            return
        }
    }

    if err := rows.Err(); err != nil {
        fmt.Println(err)
        return
    }
}
</code>```

rowsClose duration: 1m2.5488669s

Interesting that duration of rows.Close() in this case in same as duration which I will have if will process all elements of rows.Next() loop without break it.

Body:
Why call rows.Close() takes too long time when I call it after I exit from loop rows.Next() before processing all elements of loop.

Its happen when I make request which returns huge amount of data (around 300 000 rows).

This problem doesn't exists when amount of rows is not so big.

func SelectHugeAmountOfRows() {
    query := `SELECT * FROM big_table`
    rows, _ := Conn.Query(context.Background(), query)
    defer func() {
        fmt.Println("Start close rows")
        start := time.Now()
        rows.Close()
        duration := time.Since(start)
        fmt.Println("rowsClose duration:", duration)
    }()

    for rows.Next() {
        rowValues, err := rows.Values()
        if err != nil {
            fmt.Println(err)
            return
        }

        // do something with rowValues and get error in process
        err = func() error {
            fmt.Println(rowValues)
            return errors.New("some error")
        }()

        if err != nil {
            return
        }
    }

    if err := rows.Err(); err != nil {
        fmt.Println(err)
        return
    }
}

rowsClose duration: 1m2.5488669s

Interesting that duration of rows.Close() in this case in same as duration which I will have if will process all elements of rows.Next() loop without break it.


问:
How to knit Rmd with runtime:shiny to html?
My teacher in R would like us to submit .Rmd and .html files of our homework to our repo in github.

And He recommends to use shiny in our homework.

But I found when I use runtime:shiny , there is no .html file generated.

Is there some way to match his need?

Our teacher does not answer questions now. but we need to submit soon.

That's why I ask for help here.

Thx a lot!!


问:
Is there a function to trigger elements when i enter value in input?
I need to figure it is there a function to trigger a button when i add value on input? Like i have buttons and they are not visible i want to make trigger that buttons when user inputs the exect value of button id or button text doesnt matter.

I will describe it more below

I have too many buttons and they are adding balance to system and i dont want to user sees all of it and they have text and id's like (from 1 to 100). I want to make them clicked when user inputs that value.

I tried to improve that function but i cant.

```<code><div>
      <a class="balance"
        href="checkout.js">
        Add 1$ Balance
      </a>
          </div>
      has more 99 button like this.
</code>```
```<code><form>
        <input type="text">
      </form>

      <div id="container">
        <button onclick="text()" id="button">Add that amoun of balance.</button>
        <h1 class="output"></h1>
      </div>
</code>```
```<code>const input = document.querySelector("input");
        const output = document.querySelector(".output");

        function text() {
          output.textContent = input.value;
        };
</code>```

Body:
I need to figure it is there a function to trigger a button when i add value on input? Like i have buttons and they are not visible i want to make trigger that buttons when user inputs the exect value of button id or button text doesnt matter.

I will describe it more below

I have too many buttons and they are adding balance to system and i dont want to user sees all of it and they have text and id's like (from 1 to 100). I want to make them clicked when user inputs that value.

I tried to improve that function but i cant.

        Add 1$ Balance

      has more 99 button like this.

<form>
        <input type="text">
      </form>

        <button onclick="text()" id="button">Add that amoun of balance.</button>

const input = document.querySelector("input");
        const output = document.querySelector(".output");

        function text() {
          output.textContent = input.value;
        };


问:
AWS Code Pipeline Stage takes 32 seconds even on the most simple LambdaInvokeAction
I am using a LambdaInvokeAction (https://docs.aws.amazon.com/cdk/api/v2/docs/aws-cdk-lib.aws_codepipeline_actions.LambdaInvokeAction.html) with my AWS codepipeline.

What ever I do, the stages take exactly 32 seconds, even though even the most basic invocation takes only 200ms.

How do I get this time down? Is there any way to accelerate the SUCCESS notification back to the codepipeline service?

my lambda for testing:

import boto3

codepipeline = boto3.client('codepipeline')

def lambda_handler(event, context):
    job = event['CodePipeline.job']['id']
    print('Event:')
    print(f'event={event}')

    codepipeline.put_job_success_result(jobId=job)

```


问:
VPN IKEv2 connection problems on Android, IKE_SA failed
I have big problem with connecting to my VPN server from 50% of Android devices.
Cannot resolve it 2 weeks with network and android developers

VPN server based on IKEv2 with Charon and Strongswan libs, and it works stable with iPhone devices
But on Android devices it fails with error “IKE_SA failed, peer not responding” after 3 retransmits of sending IKE_SA_INIT requests

I tried to gether information what was tested, and some hypotheses we had:

Android app used to connect is problematic:
No, it is most popular Strongswan application for VPN connection, that advised by many respective VPN services

Network providers is problematic and cut some traffic:
No, because iPhone device can connect to this VPN through standard settings. iPhone was connected to the same Wi-Fi and was in airplane mode for disable cellular network (I doublechecked that cellular network was disabled)

Android devices that was on manual tests is problematic:
No, because when I using not Wi-Fi from my home provider, but using wi-fi from my iPhone hotspot the connection is Successful.
Also another GooglePlay IKEv2 free VPNs is failed to connect

So based on this 3 points I have very strange situation.
Screenshots of android logs will be attached at bottom, with error connection(through wifi) and success connection(through iPhone hotspot)
Also screenshot of VPN server error connection log will be attached

I am android developer, and have network developer in my team, so any additional questions please

Dear developers, please give me some advices what I can do to test and understand what problem we have?
Very need it, because based on this VPN serves android free VPN app will be created

Logs:
Error logs #1
Error logs #2


问:
I want to bypass the age restriction on a youtube video
```<code>from pytube import YouTube
youtubeObject = YouTube(link,on_progress_callback=self.Download_Progress)
title = youtubeObject.title
if youtubeObject.age_restricted:
    youtubeObject.bypass_age_gate()
</code>```

Tried to bypass the age restriction with the code above, didn't work.
Is there something i'm missing? when i print out the youtubeObject.bypass_age_gate() it returns None

Body:
from pytube import YouTube
youtubeObject = YouTube(link,on_progress_callback=self.Download_Progress)
title = youtubeObject.title
if youtubeObject.age_restricted:
    youtubeObject.bypass_age_gate()

Tried to bypass the age restriction with the code above, didn't work.
Is there something i'm missing? when i print out the youtubeObject.bypass_age_gate() it returns None


问:
Class-static field zeroed when virtual member called inside a DLL using instance from caller program
Hi all and sorry for the cryptic title.

I have an executable which loads a DLL using WinAPI LoadLibrary/GetProcAddress. The program calls an exported function with C linkage with a custom class as parameter (as a reference but I will come back later on this). The exported function is defined as follow (GGen will be defined just after):

```<code>// LIB_API is __declspec(dllexport) in DLL context and
// __declspec(dllimport) in executable context
LIB_API void dbgt_generate(IRFile& cr) {
  GGen::generate(cr);
}
</code>```

My custom class is defined as follow and is header-only:

```<code>class IRFile {
public:
  std::string identifier;

  using callback_t = std::string(*)(IRFile*, void*);
  static callback_t _callback;

  virtual std::string buildFile(void* genData) {
    assert(IRFile::_callback);
    return IRFile::_callback(this, genData);
  }
};

inline IRFile::callback_t IRFile::_callback = nullptr;
</code>```

The exported function calls a singleton class by the way of a static member (the generate method):

```<code>static std::string cbFile(IRFile* _this, void* r) {
  return "irfile";
}

class GGen {
public:
  GGen() noexcept {
    IRFile::_callback = cbFile;
  }

  static void generate(IRFile& cr) {
    static GGen ggen;
    assert(IRFile::_callback);
    auto data = cr.buildFile(nullptr);
    assert(!data.empty());
  }
};
</code>```

The executable simply initializes an IRFile instance on the stack and calls the exported function. My problem is that GGen::generate works well and assert pass without any problem but when buildFile is called during GGen::generate, the assert in it does not pass. At the precise cr.buildFile call moment, IRFile::_callback appears to be NULL.

After investigations, it appears that IRFile::_callback "has another address when in the virtual function compared to before" (I know this sound weird). I have figured out that removing virtual does fix the problem but in my complete program, I need it even if not used here. Another point is that when I pass the IRFile instance to the exported function as a copy (pass-by-value) the problem is also gone. But I don't understand why this last point fixes the problem as even if memory sharing was problematic, IRFile::_callback is initialized inside and by the DLL itself... I have added the identifier field to ensure correct memory is used and it is the case (in other words, this is correct).

Is it stack corruption? Why does removing virtual changes anything as, in my knowledges, static has nothing to do with vtables? Is this the effect of an undefined behavior with coincidences?

Please don't mind ugly C++ or naming conventions, I had to rewrite parts for testing to simplify.

[Edit 1] Clarified that the problem occurs after IRFile::_callback is initialized by GGen::generate and indirectly GGen ctor.

[Edit 2] As suggested in comments, I have tried to inline IRFile::_callback and export it as DLL symbol without success. I have also tried to put IRFile in a separate project (.lib and .dll tested) inlined or not, defined in a .cpp or not. I have also tried to encapsulate calls to _callback with setters/getters without success event when in a separate project (.lib/.dll).

[Edit 3] Added inline specifier to the _callback definition in header file to avoid multiple definition of _callback according to C++17:

What's the difference between static constexpr and static inline variables in C++17?

How do inline variables work?

https://en.cppreference.com/w/cpp/language/inline

Body:
Hi all and sorry for the cryptic title.

I have an executable which loads a DLL using WinAPI LoadLibrary/GetProcAddress. The program calls an exported function with C linkage with a custom class as parameter (as a reference but I will come back later on this). The exported function is defined as follow (GGen will be defined just after):

// LIB_API is __declspec(dllexport) in DLL context and
// __declspec(dllimport) in executable context
LIB_API void dbgt_generate(IRFile& cr) {
  GGen::generate(cr);
}

My custom class is defined as follow and is header-only:

class IRFile {
public:
  std::string identifier;

  using callback_t = std::string(*)(IRFile*, void*);
  static callback_t _callback;

  virtual std::string buildFile(void* genData) {
    assert(IRFile::_callback);
    return IRFile::_callback(this, genData);
  }
};

inline IRFile::callback_t IRFile::_callback = nullptr;

The exported function calls a singleton class by the way of a static member (the generate method):

static std::string cbFile(IRFile* _this, void* r) {
  return "irfile";
}

class GGen {
public:
  GGen() noexcept {
    IRFile::_callback = cbFile;
  }

  static void generate(IRFile& cr) {
    static GGen ggen;
    assert(IRFile::_callback);
    auto data = cr.buildFile(nullptr);
    assert(!data.empty());
  }
};

The executable simply initializes an IRFile instance on the stack and calls the exported function. My problem is that GGen::generate works well and assert pass without any problem but when buildFile is called during GGen::generate, the assert in it does not pass. At the precise cr.buildFile call moment, IRFile::_callback appears to be NULL.

After investigations, it appears that IRFile::_callback "has another address when in the virtual function compared to before" (I know this sound weird). I have figured out that removing virtual does fix the problem but in my complete program, I need it even if not used here. Another point is that when I pass the IRFile instance to the exported function as a copy (pass-by-value) the problem is also gone. But I don't understand why this last point fixes the problem as even if memory sharing was problematic, IRFile::_callback is initialized inside and by the DLL itself... I have added the identifier field to ensure correct memory is used and it is the case (in other words, this is correct).

Is it stack corruption? Why does removing virtual changes anything as, in my knowledges, static has nothing to do with vtables? Is this the effect of an undefined behavior with coincidences?

Please don't mind ugly C++ or naming conventions, I had to rewrite parts for testing to simplify.

[Edit 1] Clarified that the problem occurs after IRFile::_callback is initialized by GGen::generate and indirectly GGen ctor.

[Edit 2] As suggested in comments, I have tried to inline IRFile::_callback and export it as DLL symbol without success. I have also tried to put IRFile in a separate project (.lib and .dll tested) inlined or not, defined in a .cpp or not. I have also tried to encapsulate calls to _callback with setters/getters without success event when in a separate project (.lib/.dll).

[Edit 3] Added inline specifier to the _callback definition in header file to avoid multiple definition of _callback according to C++17:

What's the difference between static constexpr and static inline variables in C++17?

How do inline variables work?

https://en.cppreference.com/w/cpp/language/inline


问:
expo-notification on Sumni V2 device not working
I recently purchased a Sunmi V2 device for a client, and I am trying to print something when I receive a notification from expo-notification using react-native. I have successfully implemented this in another application, but I am having difficulty getting it to work on the Sunmi V2 device.

Here is the approach I took: On my StackNavigator.js component, I have...

const { user } = useAuth();

const { registerForPushNotificationsAsync, handleNotifications, handleNotificationsResponse } = useNotifications();

useEffect(() => {
    registerForPushNotificationsAsync();

    Notifications.setNotificationHandler({
        handleNotification: async () => ({
            shouldShowAlert: true,
            shouldPlaySound: true,
            shouldSetBadge: false,
        }),
    });

    const responseListener =
        Notifications.addNotificationResponseReceivedListener(
            handleNotificationsResponse
        );

    return () => {
        if (responseListener)
            Notifications.removeNotificationSubscription(responseListener)
    }

}, [user])
```
<p>Here is the useNotification component:</p>
<pre class="lang-js prettyprint-override"><code>export const useNotifications = () => {

    const { user } = useAuth();

    const registerForPushNotificationsAsync = async () => {
        if (Device.isDevice) {

            const { status: existingStatus } = await Notifications.getPermissionsAsync();
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Notifications.requestPermissionsAsync();
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                alert('Failed to get push token for push notification!');
                // console.log('Failed to get push token for push notification!')
                return;
            }
            try {
                const token = (await Notifications.getExpoPushTokenAsync()).data;

                Alert.alert("TOKEN: ", token);

                if (user) {
                    const useRef = doc(db, "users", user.uid);

                    if (token !== undefined) {
                        updateDoc(useRef, {
                            pushTokenExpo: token
                        });
                    }
                }
            } catch (error) {
                Alert.alert(error)
            }

        } else {
            if (user) {
                alert('Must use physical device for Push Notifications', user.uid)
            }
            alert('Must use physical device for Push Notifications');
            console.log('Must use physical device for Push Notifications')
        }

        if (Platform.OS === 'android') {
            Notifications.setNotificationChannelAsync('default', {
                name: 'default',
                importance: Notifications.AndroidImportance.MAX,
                vibrationPattern: [0, 250, 250, 250],
                lightColor: '#FF231F7C',
            });
        }
    };

    const handleNotifications = (notification: Notifications.Notification) => {
        console.log('NEW NOTIFICACTION')
    };

    const handleNotificationsResponse = (
        response: Notifications.NotificationResponse
    ) => {
        console.log(response.notification.request.content.data)
        // HERE DO WHAT YOU WHAT AFTER CLICK ON NOTIF
    }

    return { registerForPushNotificationsAsync, handleNotifications, handleNotificationsResponse }
}
</code>```

When I run this code on my device, it either crashes the app or does not update the Firebase collection 'user'. How can I fix this issue?

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

Body:
I recently purchased a Sunmi V2 device for a client, and I am trying to print something when I receive a notification from expo-notification using react-native. I have successfully implemented this in another application, but I am having difficulty getting it to work on the Sunmi V2 device.

Here is the approach I took: On my StackNavigator.js component, I have...

const { user } = useAuth();

const { registerForPushNotificationsAsync, handleNotifications, handleNotificationsResponse } = useNotifications();

useEffect(() => {
    registerForPushNotificationsAsync();

    Notifications.setNotificationHandler({
        handleNotification: async () => ({
            shouldShowAlert: true,
            shouldPlaySound: true,
            shouldSetBadge: false,
        }),
    });

    const responseListener =
        Notifications.addNotificationResponseReceivedListener(
            handleNotificationsResponse
        );

    return () => {
        if (responseListener)
            Notifications.removeNotificationSubscription(responseListener)
    }

}, [user])

Here is the useNotification component:

export const useNotifications = () => {

    const { user } = useAuth();

    const registerForPushNotificationsAsync = async () => {
        if (Device.isDevice) {

            const { status: existingStatus } = await Notifications.getPermissionsAsync();
            let finalStatus = existingStatus;
            if (existingStatus !== 'granted') {
                const { status } = await Notifications.requestPermissionsAsync();
                finalStatus = status;
            }
            if (finalStatus !== 'granted') {
                alert('Failed to get push token for push notification!');
                // console.log('Failed to get push token for push notification!')
                return;
            }
            try {
                const token = (await Notifications.getExpoPushTokenAsync()).data;

                Alert.alert("TOKEN: ", token);

                if (user) {
                    const useRef = doc(db, "users", user.uid);

                    if (token !== undefined) {
                        updateDoc(useRef, {
                            pushTokenExpo: token
                        });
                    }
                }
            } catch (error) {
                Alert.alert(error)
            }

        } else {
            if (user) {
                alert('Must use physical device for Push Notifications', user.uid)
            }
            alert('Must use physical device for Push Notifications');
            console.log('Must use physical device for Push Notifications')
        }

        if (Platform.OS === 'android') {
            Notifications.setNotificationChannelAsync('default', {
                name: 'default',
                importance: Notifications.AndroidImportance.MAX,
                vibrationPattern: [0, 250, 250, 250],
                lightColor: '#FF231F7C',
            });
        }
    };

    const handleNotifications = (notification: Notifications.Notification) => {
        console.log('NEW NOTIFICACTION')
    };

    const handleNotificationsResponse = (
        response: Notifications.NotificationResponse
    ) => {
        console.log(response.notification.request.content.data)
        // HERE DO WHAT YOU WHAT AFTER CLICK ON NOTIF
    }

    return { registerForPushNotificationsAsync, handleNotifications, handleNotificationsResponse }
}

When I run this code on my device, it either crashes the app or does not update the Firebase collection 'user'. How can I fix this issue?


问:
Why cant I write to a socket's input stream java
So I Have two Similar classes to test Sockets that are the same from the lines down.

```<code>public class Server {
    public static void main(String args[]) throws IOException, InterruptedException {
        ServerSocket socket =new ServerSocket(80);
        Socket client = socket.accept();
        InputStream in = client.getInputStream();
        OutputStream out = client.getOutputStream();
//-----------------------------------------------------------------------------------
        Scanner s = new Scanner(in);
        InputStream txt = System.in;
        Scanner text = new Scanner(txt);
        while (true) {
            if (text.hasNext()) {
                out.write((text.next()+"\n").getBytes());
                out.flush();
                System.out.println("Sent");
            }
            if (s.hasNext()) {
                System.out.println(s.next());
                System.out.println("Received");

            }
        }
    }
}
</code>```
```<code>public class Client {
    public static void main(String args[]) throws IOException, InterruptedException {
        Socket socket =new Socket("localhost",80);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
//-----------------------------------------------------------------------------------
        Scanner s = new Scanner(in);
        InputStream txt = System.in;
        Scanner text = new Scanner(txt);
        while (true) {
            if (text.hasNext()) {
                out.write((text.next()+"\n").getBytes());
                out.flush();
                System.out.println("Sent");
            }
            if (s.hasNext()) {
                System.out.println(s.next());
                System.out.println("Received");

            }
        }
    }
}
</code>```

The goal is two way messaging.
When I type in either shell it says sent, however no text shows on the other shell.
Why are they not sending or receiving any text?

Any help is greatly appreciated.

Body:
So I Have two Similar classes to test Sockets that are the same from the lines down.

public class Server {
    public static void main(String args[]) throws IOException, InterruptedException {
        ServerSocket socket =new ServerSocket(80);
        Socket client = socket.accept();
        InputStream in = client.getInputStream();
        OutputStream out = client.getOutputStream();
//-----------------------------------------------------------------------------------
        Scanner s = new Scanner(in);
        InputStream txt = System.in;
        Scanner text = new Scanner(txt);
        while (true) {
            if (text.hasNext()) {
                out.write((text.next()+"\n").getBytes());
                out.flush();
                System.out.println("Sent");
            }
            if (s.hasNext()) {
                System.out.println(s.next());
                System.out.println("Received");

            }
        }
    }
}

public class Client {
    public static void main(String args[]) throws IOException, InterruptedException {
        Socket socket =new Socket("localhost",80);
        InputStream in = socket.getInputStream();
        OutputStream out = socket.getOutputStream();
//-----------------------------------------------------------------------------------
        Scanner s = new Scanner(in);
        InputStream txt = System.in;
        Scanner text = new Scanner(txt);
        while (true) {
            if (text.hasNext()) {
                out.write((text.next()+"\n").getBytes());
                out.flush();
                System.out.println("Sent");
            }
            if (s.hasNext()) {
                System.out.println(s.next());
                System.out.println("Received");

            }
        }
    }
}

The goal is two way messaging.
When I type in either shell it says sent, however no text shows on the other shell.
Why are they not sending or receiving any text?

Any help is greatly appreciated.


问:
Multiple languages and keyboard layout web support
I have Web Page and global search in it, I want to make the text-box of the global search to be able to search by languages and by keyboard layout.

lets say I'm typing the letter D I want to find the result with the letter D and with the keyboard layout of the specific country ( In case the user was on English but intend to write in its local language)
the layout is can be hard coded prefer no too.


问:
How to check whether a HDFS path containing regex exists or not through scala
I want to check wheter a HDFS path exist or not trough scala
paths are like this :-

/raw/data/\*/product/datehr=20221203\*/data

I have tried this

```<code>val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
fs.exists(new Path("/raw/data/\*/product/datehr=20221203\*/data"))
</code>```

but it returns false
I was expecting true

if i run

```<code>fs.exists(new Path("/raw/data/country/product/datehr=2022120310/data"))
</code>```

it returns true

Is there a way to check whether a hdfs path containing * exist or not through scala

Body:
I want to check wheter a HDFS path exist or not trough scala
paths are like this :-

/raw/data/\*/product/datehr=20221203\*/data

I have tried this

val fs = FileSystem.get(spark.sparkContext.hadoopConfiguration)
fs.exists(new Path("/raw/data/\*/product/datehr=20221203\*/data"))

but it returns false
I was expecting true

if i run

fs.exists(new Path("/raw/data/country/product/datehr=2022120310/data"))

it returns true

Is there a way to check whether a hdfs path containing * exist or not through scala


问:
csv file stored in Django members directory loaded as directory instead of csv file
I am working in a Django app in a directory myworld. In this directory, I have a members directory with a templates directory with an html file myfirst.html. In the html file, I have this code:

```
<p>And the contents of <code>employees.csv</code> is:</p>
```Name, Age
John, 30
Jane, 32
```
<p>(I'm following an example here). However instead of getting the output that they get on that link, namely:</p>
```John
30
Jane
32
```
<p>I only get many lines of <code>Undefined</code>.</p>
<p>On the django side, the terminal says:</p>
```Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 27, 2022 - 11:14:57
Django version 4.1.2, using settings 'myworld.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP GET /members/ 200 [0.16, 127.0.0.1:51510]
HTTP GET /static/myfirst.css 200 [0.01, 127.0.0.1:51510]
HTTP GET /static/myfirst.jss 200 [0.00, 127.0.0.1:51510]
HTTP GET /members/employees 301 [0.00, 127.0.0.1:51510]
HTTP GET /members/employees/ 200 [0.00, 127.0.0.1:51510]
```
<p>I tried seeing if the data was even loaded from the file correctly, but something altogether seems to be happening; when I instead do this:</p>
<pre class="lang-js prettyprint-override"><code><script src="https://d3js.org/d3.v7.min.js"></script>
<script>

    const loadData = () => {
        return d3.csv("/members/employees").then((data) => {
            console.log(data);
           /* for (var i = 0; i < data.length; i++) {
                    console.log(data[i].Name);
                    console.log(data[i].Age);
                }*/
        }                                     )
    };

    loadData();
</script>
</code>```

I get this console output:

```<code>0 {<!-- members/templates/room.html -->: "<!DOCTYPE html>"}
1 {<!-- members/templates/room.html -->: "<html>"}
2 {<!-- members/templates/room.html -->: "<head>"}
3 {<!-- members/templates/room.html -->: "    <meta charset=\"utf-8\"/>"}
4 {<!-- members/templates/room.html -->: "    <title>Chat Room</title>"}
5 {<!-- members/templates/room.html -->: "</head>"}
6 {<!-- members/templates/room.html -->: "<body>"}
7 {<!-- members/templates/room.html -->: "    <textarea id=\"chat-log\" cols=\"100\" rows=\"20\"></textarea><br>"}
8 {<!-- members/templates/room.html -->: "    <input id=\"chat-message-input\" type=\"text\" size=\"100\"><br>"}
9 {<!-- members/templates/room.html -->: "    <input id=\"chat-message-submit\" type=\"button\" value=\"Send\">"}
10 {<!-- members/templates/room.html -->: "    <script id=\"room-name\" type=\"application/json\">\"employees\"</script> <br/>"}
11 {<!-- members/templates/room.html -->: "    <script>"}
12 {<!-- members/templates/room.html -->: "        const roomName = JSON.parse(document.getElementById('room-name').textContent);"}
13 {<!-- members/templates/room.html -->: ""}
14 {<!-- members/templates/room.html -->: "        const chatSocket = new WebSocket("}
15 {<!-- members/templates/room.html -->: "            'ws://'"}
16 {<!-- members/templates/room.html -->: "            + window.location.host"}
17 {<!-- members/templates/room.html -->: "            + '/ws/members/'"}
18 {<!-- members/templates/room.html -->: "            + roomName"}
19 {<!-- members/templates/room.html -->: "            + '/'"}
20 {<!-- members/templates/room.html -->: "        );"}
21 {<!-- members/templates/room.html -->: ""}
22 {<!-- members/templates/room.html -->: "        chatSocket.onmessage = function(e) {"}
23 {<!-- members/templates/room.html -->: "            const data = JSON.parse(e.data);"}
24 {<!-- members/templates/room.html -->: "            document.querySelector('#chat-log').value += (data.message + \"!\" + '\\n');"}
25 {<!-- members/templates/room.html -->: "        };"}
26 {<!-- members/templates/room.html -->: ""}
27 {<!-- members/templates/room.html -->: "        chatSocket.onclose = function(e) {"}
28 {<!-- members/templates/room.html -->: "            console.error('Chat socket closed unexpectedly');"}
29 {<!-- members/templates/room.html -->: "        };"}
30 {<!-- members/templates/room.html -->: ""}
31 {<!-- members/templates/room.html -->: "        document.querySelector('#chat-message-input').focus();"}
32 {<!-- members/templates/room.html -->: "        document.querySelector('#chat-message-input').onkeyup = function(e) {"}
33 {<!-- members/templates/room.html -->: "            if (e.keyCode === 13) {  // enter"}
34 {<!-- members/templates/room.html -->: "                document.querySelector('#chat-message-submit').click();"}
35 {<!-- members/templates/room.html -->: "            }"}
36 {<!-- members/templates/room.html -->: "        };"}
37 {<!-- members/templates/room.html -->: ""}
38 {<!-- members/templates/room.html -->: "        document.querySelector('#chat-message-submit').onclick = function(e) {"}
39 {<!-- members/templates/room.html -->: "            const messageInputDom = document.querySelector('#chat-message-input');"}
40 {<!-- members/templates/room.html -->: "            const message = messageInputDom.value+\"!!!\";"}
41 {<!-- members/templates/room.html -->: "            alert(message)"}
42 {<!-- members/templates/room.html -->: "            chatSocket.send(JSON.stringify({"}
43 {<!-- members/templates/room.html -->: "                'message': message"}
44 {<!-- members/templates/room.html -->: "            }));"}
45 {<!-- members/templates/room.html -->: ""}
46 {<!-- members/templates/room.html -->: "            messageInputDom.value = '';"}
47 {<!-- members/templates/room.html -->: "        };"}
48 {<!-- members/templates/room.html -->: "    </script>"}
49 {<!-- members/templates/room.html -->: "</body>"}
50 {<!-- members/templates/room.html -->: "</html>"}
</code>```

So it seems it's not reading in the file but somehow storing lines of another html file in the same directory as myfirst.html... How can I get it to read the csv file instead?

Body:
I am working in a Django app in a directory myworld. In this directory, I have a members directory with a templates directory with an html file myfirst.html. In the html file, I have this code:

And the contents of employees.csv is:

Name, Age
John, 30
Jane, 32

(I'm following an example here). However instead of getting the output that they get on that link, namely:

John
30
Jane
32

I only get many lines of Undefined.

On the django side, the terminal says:

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
December 27, 2022 - 11:14:57
Django version 4.1.2, using settings 'myworld.settings'
Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
HTTP GET /members/ 200 [0.16, 127.0.0.1:51510]
HTTP GET /static/myfirst.css 200 [0.01, 127.0.0.1:51510]
HTTP GET /static/myfirst.jss 200 [0.00, 127.0.0.1:51510]
HTTP GET /members/employees 301 [0.00, 127.0.0.1:51510]
HTTP GET /members/employees/ 200 [0.00, 127.0.0.1:51510]

I tried seeing if the data was even loaded from the file correctly, but something altogether seems to be happening; when I instead do this:

I get this console output:

0 {: "<!DOCTYPE html>"}
1 {: ""}
2 {: ""}
3 {: "    <meta charset=\"utf-8\"/>"}
4 {: "    <title>Chat Room</title>"}
5 {: ""}
6 {: ""}
7 {: "    <textarea id=\"chat-log\" cols=\"100\" rows=\"20\"></textarea>
"}
8 {: "    <input id=\"chat-message-input\" type=\"text\" size=\"100\">
"}
9 {: "    <input id=\"chat-message-submit\" type=\"button\" value=\"Send\">"}
10 {: "
"}
11 {: "    "}
49 {: ""}
50 {: ""}

So it seems it's not reading in the file but somehow storing lines of another html file in the same directory as myfirst.html... How can I get it to read the csv file instead?


问:
package is not in GOROOT
I'm making some mini project with golang. I defined global variable and make it as a separated package. so, my directory status like below. but when I import this in 'image.go'it says 'package comento/works/internal/global is not in GOROOT'. Additionary, global's variables in image.go works well.but jsut import occures error. I also made go.mod file and tried to command 'go mod tidy' either.  How can I resolve this?

directory tree
(/usr/local/go/src/comento/works/internal/global)

```<code>works
.
├── README.md
├── file
├── go.mod
├── go.sum
├── index
│   └── index.html
├── internal
│   └── global.go
├── main.go
└── pkg
    ├── api
    │   └── image.go
    └── router
        └── router.go
</code>```

image.go

```<code>import "comento/works/internal/global".
</code>```

go.mod

```<code>module comento/works

go 1.19

require github.com/gin-gonic/gin v1.8.2
</code>```

Title: package is not in GOROOT

Body:
I'm making some mini project with golang. I defined global variable and make it as a separated package. so, my directory status like below. but when I import this in 'image.go'it says 'package comento/works/internal/global is not in GOROOT'. Additionary, global's variables in image.go works well.but jsut import occures error. I also made go.mod file and tried to command 'go mod tidy' either.  How can I resolve this?

directory tree
(/usr/local/go/src/comento/works/internal/global)

works
.
├── README.md
├── file
├── go.mod
├── go.sum
├── index
│   └── index.html
├── internal
│   └── global.go
├── main.go
└── pkg
    ├── api
    │   └── image.go
    └── router
        └── router.go

image.go

import "comento/works/internal/global".

go.mod

module comento/works

go 1.19

require github.com/gin-gonic/gin v1.8.2


问:
Google Kubernetes Engine: Can't create a node pool with A100 80Gb GPU type
I want to create a nodepool with A100 80Gb GPU type from the console. But this type does not appear in the drop-down menu. I've already submitted quota increase request and got my approval, but it didn't work. I checked the available GPUs in my region through the CLI and found that the A100 80Gb is there. I don't want to risk creating a nodepool through the CLI in this situation.</p>


问:
import several modules during compile from a directory of files for object literal
I have a structure like this:

```<code>.
├── fileTypes.ts
├── fileData.ts
└── fileTypes
    ├── fileA.ts
    └── fileB.ts
</code>```

fileData.ts base file:

```<code>export default abstract class FileData {
  abstract functionA;
  abstract functionB;
}
</code>```

I'd like to enable object literales like this:
{
FileA: FileA
FileB: FileB
}
to avoid switch, and to do have a scalable code so adding a new file type to FileTypes folder will be added during compile to the object,

how can I do that please?

I've tried this so far but doesn't seem to work:

```<code>import * as types from './fileTypes';
import FileData from './fileData';

export const fileTypes: { [x: string]: FileData } = { ...types };
</code>```

It didn't find the objects in FileTypes at all when calling it (fileTypes["FileA"])
thanks in advance

Body:
I have a structure like this:

.
├── fileTypes.ts
├── fileData.ts
└── fileTypes
    ├── fileA.ts
    └── fileB.ts

fileData.ts base file:

export default abstract class FileData {
  abstract functionA;
  abstract functionB;
}

I'd like to enable object literales like this:
{
FileA: FileA
FileB: FileB
}
to avoid switch, and to do have a scalable code so adding a new file type to FileTypes folder will be added during compile to the object,

how can I do that please?

I've tried this so far but doesn't seem to work:

import * as types from './fileTypes';
import FileData from './fileData';

export const fileTypes: { [x: string]: FileData } = { ...types };

It didn't find the objects in FileTypes at all when calling it (fileTypes["FileA"])
thanks in advance