问:
why emeded video just show html tags in react after sending body with markdown editor
why emeded video just show html tags in react after sending body with markdown editor

why every things shows ok in markdown editor and embedded video showing correctly but when sending to the server it just shows html tags

see these pictures for me it is ok when u want write in editor

but after u post it just show that plaintext html tags

i mean in preview mode is ok showing the video but after sending body to server . this just showing plain text or html tags

can u see pictures

this picture is when posting

https://postimg.cc/VSJQr1NR

and this after posting just plain html tag in website

https://postimg.cc/K1vybtSC

https://i.postimg.cc/NFy2YHQy/333.png
https://i.postimg.cc/4NW4wdGq/ccc.png

should I use npm package and install in the backend file post.js ?

why backend server does not recognize the embedded video code but in markdown editor everything is showing correctly

this is dev.to clone and people come to website using markdown editor and then post . but embeded video is not showing . just html tags like picture what is wrong with my code ?

this is my new-post.jsx file when people try to post

```<code>// import { createEditor } from 'slate'
// import { Slate, Editable, withReact } from 'slate-react'
// import "easymde/dist/easymde.min.css";

// import React, { Component } from 'react';
import { rehype } from 'rehype';

import rehypeVideo from 'rehype-video';

import MDEditor from '@uiw/react-md-editor';

// import  {  useMemo } from "react";

// import SlateEditor from "./Editorr";
// import React, { useState, useRef } from "react";
import './NewPost.css'

// import SimpleMDE from "react-simplemde-editor";

import { useContext, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import tw from 'twin.macro';
import Error from '../../common/Error';
import LoadingSpinner from '../../common/LoadingSpinner';
import RouteWrapper from '../../common/RouteWrapper';
import socketContext from '../../context/SocketContext';
import { selectCurrentUser } from '../../core/features/auth/authSlice';
import { useCreatePostMutation } from '../../core/features/posts/postsApiSlice';
import { useGetUserDashboardQuery } from '../../core/features/users/usersApiSlice';
import useBase64 from '../../hooks/useBase64';
import useRequireAuth from '../../hooks/useRequireAuth';
import { useMemo } from "react";
// import Appp from "./Editorr";
// import { Editor } from "react-draft-wysiwyg";
// import "../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
// import React, { Component } from 'react';
// import "../NewPost/react-draft-wysiwyg.css"
// import "react-draft-wysiwyg/dist/react-draft-wysiwyg.cs";

// import LiveMarkdown from '../markdowneditor/markdowneditor';
// import  EasyMDE from 'easymde';
// const [editor] = useState(() => withReact(createEditor()))
const NewPost = () => {

  // const JoditEditor = {
  //   "defaultFontSizePoints": "pt",
  //   "uploader": {
  //     "insertImageAsBase64URI": true
  //   },
  //   "language": "fa",
  //   "toolbarButtonSize": "large",
  //   "defaultMode": "1",
  //   "minHeight": 400,
  //   "inline": true,
  //   "toolbarInlineForSelection": true,
  //   "showPlaceholder": false,
  //   "buttons": "bold,italic,underline,strikethrough,eraser,ul,ol,font,fontsize,paragraph,classSpan,lineHeight,superscript,subscript,file,image,video,speechRecognize,spellcheck"
  // };

  // const editor = useRef(null);
  // const config = useMemo ({
  //   readonly: false,
  //   height: 400,
  // });
  // const handleUpdate = (event) => {
  //   const editorContent = event.target.innerHTML;
  //   setBody(setBody);
  // };

  const [title, setTitle] = useState('');
  const [file, setFile] = useState('');
  // const [editorstate, setEditorstate] = useState('');
  const [body, setBody] = useState('');

  const [tags, setTags] = useState('');
  const [isTagsFocused, setIsTagsFocused] = useState(false);
  const [inputsFilled, setInputsFilled] = useState(false);
  const filePickerRef = useRef();
  const titleRef = useRef();
  const [createPost, { isLoading, isError }] = useCreatePostMutation();
  const navigate = useNavigate();
  const currentUser = useSelector(selectCurrentUser);
  const dispatch = useDispatch();
  const previewURL = useBase64(file);
  const { isAuthed, handleAuth } = useRequireAuth();
  const { socket } = useContext(socketContext);
  const { data: user } = useGetUserDashboardQuery(currentUser.username);

  useEffect(() => titleRef.current.focus(), []);

  useEffect(() => {
    if (title
      //  && file && body
      && tags) setInputsFilled(true);
    else setInputsFilled(false);
  }, [title, file, body, tags]);

  const handleSubmit = async () => {
    if (inputsFilled) {
      if (isAuthed) {
        try {
          const { id } = await createPost({
            title,
            file: previewURL,
            body,
            tags,
            authorUsername: currentUser.username,
          }).unwrap();

          socket.emit('post', {
            sender: currentUser,
            receivers: user?.followers,
            post: { title, id },
          });

          setTitle('');
          setFile('');
          setBody('');
          setTags('');

          navigate('/');
        } catch (err) {
          console.log(err);
        }
      } else handleAuth();
    }
  };

  return (
    <RouteWrapper>
      <Wrapper>
        {isLoading && <LoadingSpinner />}
        {!isLoading && (
          <NewPostWrapper>
            <Heading>ایجاد پست جدید</Heading>
            <InputWrapper>
              <Label dir='rtl' htmlFor='title'>موضوع <p> دقت داشته باشید که موضوع بیشتر از 48 حرف نمیتواند باشد </p></Label>
              <Input
                maxLength={48}

                type="text"
                dir='rtl'
                ref={titleRef}
                id='title'
                value={title}
                onBlur={e => setTitle(prev => prev.trim())}
                onChange={e => setTitle(e.target.value)}
                required
              />
              <br></br>    <Label dir='rtl' htmlFor='title' ><p> عکس برای پست تان انتخاب نمایید . انتخاب عکس اجباری نمی باشد</p> </Label>

            </InputWrapper>
            <InputWrapper>
              <Input
                type='file'
                ref={filePickerRef}
                onChange={e => setFile(e.target.files[0])}
                style={{ display: 'none' }}

              />
              <ImagePreview src={previewURL.toString()} alt='' />
              <Button onClick={() => filePickerRef.current.click()}>انتخاب عکس</Button>
            </InputWrapper>

            {/* <p>متن خود را وارد نمایید <br /> برای اضافه کردن کد جاوااسکریپت به متن بدین شکل عمل کنید <br />
       javascript
       <br />محل قرار گیری کد جاوا اسکریپتی شما <br/>
        </p>*/}

            <InputWrapper2>

              {/* 1 */}

              {/* <SimpleMDE value={body} onChange={setBody} required /> */}

              {/* 2 */}
              {/* <Editor
              value={body}
                    // editorState={}
                    toolbarClassName="toolbarClassName"
                    wrapperClassName="wrapperClassName"
                    editorClassName="editorClassName"
                    onEditorStateChange={setBody}
                    textAlignment="right"
                    placeholder="اینجا تایپ کنید"
                />; */}

              {/* 3 */}

              <div className="md-editor-rtl ">
                <MDEditor
                  value={body}
                  style={{ padding: 15 }}
                  linkTarget="_blank"
                  onChange={setBody}
                  height={400}
                  rehypePlugins={[[rehypeVideo]]}
                  textareaProps={{
                    placeholder: "اینجا تایپ کنید",
                  }}

                />
              </div>

              <p style={{ "color": "gray", "fontSize": "0.8rem" }}>      راهنما : در سمت چپ پیش نمایش پست خودتان را میتوانید ببینید . هنگام نوشتن کدهای برنامه نویسی ملاک سمت چپ میباشد.  همچنین برای اضافه کردن کد  به متن ابتدا کد خود را درون یک ویرایشگر متن مانند  Vs Code نوشته و سپس به شکل زیر درون ادیتور بالا پیست کنید <br /> <br />   ```javascript

  محل قرار گیری کد شما

                  ```</p>     {/*  */}

              {/* <SlateEditor /> */}

{/* <JoditEditor
        ref={editor}
        value={body}
        config={config}
        // onBlur={handleSubmit}
        handleSubmit={handleSubmit}
        onChange={setBody}
        required
      /> */}
              {/* <div dangerouslySetInnerHTML={{ __html: body }} /> */}
            </InputWrapper2>
            <InputWrapper>
              <Label htmlFor='tags'>
                تگ ها
                {isTagsFocused && (
                  <Span>تگ ها را با کاما(,) از یکدیگر جدا کنید </Span>
                )}
              </Label>
              <Input
                maxLength={15}
                id='tags'
                value={tags}
                onFocus={() => setIsTagsFocused(true)}
                onBlur={() => setIsTagsFocused(false)}
                onChange={e => setTags(e.target.value.replace(/ /g, ''))}
                required
              />
            </InputWrapper>
            <Submit onClick={handleSubmit}>تایید</Submit>
            {isError && <Error>خطاا در انجام عملیات . دوباره امتحان کنید . زمان کامپیوتر خود رابررسی کنید و فقط از آی پی ایران اقدام به ارسال پست بکنید </Error>}
            {!inputsFilled && <Error>تمام فیلدها اجباری هست . زمان تقریبی ارسال پست یک دقیقه میباشد . لطفا صبور باشید عکس پست تان آپلود شود </Error>}
          </NewPostWrapper>
        )}
      </Wrapper>
    </RouteWrapper>
  );
};

const Submit = tw.button`bg-lighter-gray hover:bg-light-gray rounded-md text-center py-2 px-1 w-full text-sm`;

const ImagePreview = tw.img`w-32 h-32 mx-auto border border-gray flex justify-center items-center text-center object-cover`;

const Input = tw.input`py-1 px-2 rounded-md outline-none border-2 border-solid border-gray focus:border-blue`;

const Label = tw.label`font-bold text-dark-gray`;

const Span = tw.p`inline ml-sm`;

const InputWrapper = tw.div`flex flex-col gap-2  `;

const Button = tw.button`bg-lighter-gray hover:bg-light-gray rounded-md text-center py-2 px-1 w-28 text-sm mx-auto`;

const Heading = tw.h1`text-dark-gray text-center`;

const NewPostWrapper = tw.div`bg-white w-3/5 mob:(w-full px-4) mx-auto py-20 px-8 [&>*:not(:last-child)]:mb-md`;

const Wrapper = tw.div`flex items-center`;

const InputWrapper2 = tw.div`border border-gray`;

export default NewPost;

</code>```

and this is my post list file

```<code>import { useEffect } from 'react';
import { AiOutlineHeart } from 'react-icons/ai';
import { BsBookmark, BsBookmarkFill } from 'react-icons/bs';
import { MdOutlineModeComment } from 'react-icons/md';
import { useNavigate } from 'react-router-dom';
import tw, { styled, theme } from 'twin.macro';
import { createPostUrl, formatDate } from '../../../helpers/string';
import { calcReadingTime } from '../../../helpers/utils';
import useBreakpoint from '../../../hooks/useBreakpoint';
import usePostReaction from '../../../hooks/usePostReaction';
import useRequireAuth from '../../../hooks/useRequireAuth';
import LoadingController from '../../LoadingController/LoadingController';
import Tags from '../../Tags';

const Post = ({ post, isFirstPost, filteredTag, toInvalidate }) => {
  const navigate = useNavigate();
  const isSmall = useBreakpoint(theme`screens.sm.max`.replace('px', ''));
  const { isAuthed, handleAuth } = useRequireAuth(false);

  const { id, author, likes, unicorns, bookmarks } = post;
  const likesArr = [...likes];
  const unicornsArr = [...unicorns];
  const bookmarksArr = [...bookmarks];

  const { state, handleReaction, isLoading } = usePostReaction(
    id,
    author,
    likesArr,
    unicornsArr,
    bookmarksArr,
    post.title,
    toInvalidate
  );
  const { isBookmarked } = state;

  const handleSave = () => {
    const action = isBookmarked ? 'removeBookmark' : 'bookmark';
    const effect = isBookmarked ? 'negative' : 'positive';

    if (isAuthed) handleReaction(action, effect, bookmarksArr, 'isBookmarked');
    else handleAuth();
  };

  return (
    post && (
      <Wrapper>
        {/* {isFirstPost && (
          <Image
            onClick={() =>
               navigate(`/${post.author?.username}/${createPostUrl(post.title, post.id)}`)
            }
            src={post?.image?.url}
          />
        )} */}
        <Content>
          <Header onClick={() => navigate(`/${post?.author.username}`)}>
            <Author src={post.author?.picture?.url} />
            <AuthorMeta>
              <AuthorName>{post.author?.name}</AuthorName>
              <CreatedAt>{formatDate(post.createdAt)}</CreatedAt>
              {formatDate(post.updatedAt) !== formatDate(post.createdAt) && (
                <UpdatedAt>{`Updated ${formatDate(post.updatedAt)}`}</UpdatedAt>
              )}
            </AuthorMeta>
          </Header>
          <Title
            onClick={() =>
              navigate(`/${post.author.username}/${createPostUrl(post.title, post.id)}`)
            }>
            {post.title}
          </Title>
          <Tags tags={post.tags} filteredTag={filteredTag} />
          <Footer>
            <Reactions
              onClick={() =>
                navigate(`/${post.author.username}/${createPostUrl(post.title, post.id)}`)
              }>
              <SumOfReactions>
                <HeartIcon>
                  <AiOutlineHeart />
                </HeartIcon>
                <Total>
                  {isSmall
                    ? post.likes.length + post.unicorns.length + post.bookmarks.length
                    : `${
                        post.likes.length + post.unicorns.length + post.bookmarks.length
                      }  لایک`}
                </Total>
              </SumOfReactions>
              <SumOfComments>
                <CommentIcon>
                  <MdOutlineModeComment />
                </CommentIcon>
                <Total>
                  {isSmall ? post.comments?.length : `${post.comments?.length} کامنت ها`}
                </Total>
              </SumOfComments>
            </Reactions>
            <Other>
              <MinutesRead>
                {calcReadingTime(post.body)} {`دقیقه ${!isSmall ? 'زمان خواندن' : ''}`}
              </MinutesRead>
              <LoadingController isLoading={isLoading}>
                <SaveButton onClick={handleSave} isBookmarked={isBookmarked}>
                  {isBookmarked ? <BsBookmarkFill /> : <BsBookmark />}
                </SaveButton>
              </LoadingController>
            </Other>
          </Footer>
        </Content>
      </Wrapper>
    )
  );
};

const Image = styled.img`
  width: 100%;
  height: 450px;
  object-fit: cover;
  cursor: pointer;
`;
const Content = tw.div`px-sm py-md`;
const Header = tw.div`flex justify-between items-center w-max gap-sm mb-2`;
const Author = tw.img`w-12 h-12 rounded-full cursor-pointer`;
const AuthorMeta = tw.div``;
const AuthorName = tw.h4`text-darker-gray pr-1 pt-1 rounded-md hover:bg-lighter-gray cursor-pointer`;
const CreatedAt = tw.p`text-darker-gray`;
const UpdatedAt = tw.p`text-darker-gray`;
const Title = tw.h2`mb-2     hover:text-blue cursor-pointer`;
const Footer = tw.div`flex justify-between items-center`;
const Reactions = tw.div`flex justify-between items-center gap-md`;
const SumOfReactions = tw.div`flex justify-between items-center gap-2 text-darker-gray rounded-md px-2 py-1 hover:bg-lighter-gray cursor-pointer`;
const HeartIcon = styled.div`
  svg {
    font-size: 1.5rem;
  }
`;
const SumOfComments = tw.div`flex justify-between items-center gap-2 text-darker-gray rounded-md px-2 py-1 hover:bg-lighter-gray cursor-pointer`;
const CommentIcon = styled.div`
  svg {
    font-size: 1.5rem;
  }
`;
const Total = tw.p``;
const Other = tw.div`flex justify-between items-center gap-2`;
const MinutesRead = tw.p`text-darker-gray`;
const SaveButton = styled.button`
  ${tw`p-2 border text-lg border-solid border-transparent rounded-md hover:(text-blue bg-light-blue)`}
  ${({ isBookmarked }) => isBookmarked && tw`bg-light-gray`}
`;
const Wrapper = styled.div`
  ${tw`rounded-lg w-full overflow-hidden bg-white mb-2 shadow-sm hover:shadow`}
`;

export default Post;

</code>```

sorry for bad english . I just want answer . can not understand why website does not recognize embedded video code like mde editor

and this is my post.body

```<code>import { useNavigate } from 'react-router-dom';
import tw, { styled } from 'twin.macro';
import AuthorDetails from '../../../common/AuthorDetails';
import CustomMarkdown from '../../../common/CustomMarkdown';
import Tags from '../../../common/Tags';
import { formatDate } from '../../../helpers/string';
import Advertise from './Advertise';
import Comments from './Comments';
import './Post.css';

const Post = ({ post, isLaptop }) => {
  const navigate = useNavigate();
  return (

    <Wrapper>
      <Image src={post?.image?.url}
       />
      {/* <div id="pos-article-display-78271"></div> */}
      <Advertise />
      <Content>
        <Header>
          <Author
            src={post.author.picture.url}
            onClick={() => navigate(`/${post.author.username}`)}
          />
          <AuthorMeta>
            <AuthorName>{post.author.name}</AuthorName>
            <CreatedAt>{formatDate(post.createdAt)}</CreatedAt>
            {formatDate(post.updatedAt) !== formatDate(post.createdAt) && (
              <UpdatedAt>{`Updated ${formatDate(post.updatedAt)}`}</UpdatedAt>
            )}
          </AuthorMeta>
        </Header>
        <Title>{post.title}</Title>

        <Tags tags={post.tags} isColored={true} />
           <div className="postbody"> <PostBody>
          <iframe> <CustomMarkdown children={post.body} /></iframe>
        </PostBody></div>
        <CommentsContainer>
          {post.comments && (
            <Comments postTitle={post.title} postAuthor={post.author} postId={post.id} />
          )}
        </CommentsContainer>
      </Content>
      {isLaptop && <AuthorDetails post={post} />}
    </Wrapper>
  );
};

const Image = styled.img`
  width: 100%;
  height: 100%;
  margin: 0 auto;
  object-fit: contain;
  cursor: pointer;
`;

const Header = tw.div`flex justify-between items-center w-max gap-sm mt-sm`;

const Author = tw.img`w-12 h-12 rounded-full cursor-pointer`;
const AuthorMeta = tw.div``;
const AuthorName = tw.h4`text-darker-gray pr-1 pt-1 rounded-md hover:bg-lighter-gray cursor-pointer`;
const CreatedAt = tw.p`text-darker-gray`;
const UpdatedAt = tw.p`text-darker-gray`;

const Title = tw.h1`my-sm`;

const PostBody = tw.div`mt-md pb-md border-b border-light-gray border-solid`;

const CommentsContainer = styled.div`
  > *:not(:first-child) {
    ${tw`mt-sm`}
  }
  ${tw`mt-md`}
`;

const Content = tw.div`px-lg my-lg mob:(px-sm)`;

const Wrapper = tw.div`w-full h-full rounded-md overflow-hidden bg-white shadow`;

export default Post;

</code>```

Body:
why emeded video just show html tags in react after sending body with markdown editor

why every things shows ok in markdown editor and embedded video showing correctly but when sending to the server it just shows html tags

see these pictures for me it is ok when u want write in editor

but after u post it just show that plaintext html tags

i mean in preview mode is ok showing the video but after sending body to server . this just showing plain text or html tags

can u see pictures

this picture is when posting

https://postimg.cc/VSJQr1NR

and this after posting just plain html tag in website

https://postimg.cc/K1vybtSC

https://i.postimg.cc/NFy2YHQy/333.png
https://i.postimg.cc/4NW4wdGq/ccc.png

should I use npm package and install in the backend file post.js ?

why backend server does not recognize the embedded video code but in markdown editor everything is showing correctly

this is dev.to clone and people come to website using markdown editor and then post . but embeded video is not showing . just html tags like picture what is wrong with my code ?

this is my new-post.jsx file when people try to post

// import { createEditor } from 'slate'
// import { Slate, Editable, withReact } from 'slate-react'
// import "easymde/dist/easymde.min.css";

// import React, { Component } from 'react';
import { rehype } from 'rehype';

import rehypeVideo from 'rehype-video';

import MDEditor from '@uiw/react-md-editor';

// import  {  useMemo } from "react";

// import SlateEditor from "./Editorr";
// import React, { useState, useRef } from "react";
import './NewPost.css'

// import SimpleMDE from "react-simplemde-editor";

import { useContext, useEffect, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { useNavigate } from 'react-router-dom';
import tw from 'twin.macro';
import Error from '../../common/Error';
import LoadingSpinner from '../../common/LoadingSpinner';
import RouteWrapper from '../../common/RouteWrapper';
import socketContext from '../../context/SocketContext';
import { selectCurrentUser } from '../../core/features/auth/authSlice';
import { useCreatePostMutation } from '../../core/features/posts/postsApiSlice';
import { useGetUserDashboardQuery } from '../../core/features/users/usersApiSlice';
import useBase64 from '../../hooks/useBase64';
import useRequireAuth from '../../hooks/useRequireAuth';
import { useMemo } from "react";
// import Appp from "./Editorr";
// import { Editor } from "react-draft-wysiwyg";
// import "../../../node_modules/react-draft-wysiwyg/dist/react-draft-wysiwyg.css";
// import React, { Component } from 'react';
// import "../NewPost/react-draft-wysiwyg.css"
// import "react-draft-wysiwyg/dist/react-draft-wysiwyg.cs";

// import LiveMarkdown from '../markdowneditor/markdowneditor';
// import  EasyMDE from 'easymde';
// const [editor] = useState(() => withReact(createEditor()))
const NewPost = () => {

  // const JoditEditor = {
  //   "defaultFontSizePoints": "pt",
  //   "uploader": {
  //     "insertImageAsBase64URI": true
  //   },
  //   "language": "fa",
  //   "toolbarButtonSize": "large",
  //   "defaultMode": "1",
  //   "minHeight": 400,
  //   "inline": true,
  //   "toolbarInlineForSelection": true,
  //   "showPlaceholder": false,
  //   "buttons": "bold,italic,underline,strikethrough,eraser,ul,ol,font,fontsize,paragraph,classSpan,lineHeight,superscript,subscript,file,image,video,speechRecognize,spellcheck"
  // };

  // const editor = useRef(null);
  // const config = useMemo ({
  //   readonly: false,
  //   height: 400,
  // });
  // const handleUpdate = (event) => {
  //   const editorContent = event.target.innerHTML;
  //   setBody(setBody);
  // };

  const [title, setTitle] = useState('');
  const [file, setFile] = useState('');
  // const [editorstate, setEditorstate] = useState('');
  const [body, setBody] = useState('');

  const [tags, setTags] = useState('');
  const [isTagsFocused, setIsTagsFocused] = useState(false);
  const [inputsFilled, setInputsFilled] = useState(false);
  const filePickerRef = useRef();
  const titleRef = useRef();
  const [createPost, { isLoading, isError }] = useCreatePostMutation();
  const navigate = useNavigate();
  const currentUser = useSelector(selectCurrentUser);
  const dispatch = useDispatch();
  const previewURL = useBase64(file);
  const { isAuthed, handleAuth } = useRequireAuth();
  const { socket } = useContext(socketContext);
  const { data: user } = useGetUserDashboardQuery(currentUser.username);

  useEffect(() => titleRef.current.focus(), []);

  useEffect(() => {
    if (title
      //  && file && body
      && tags) setInputsFilled(true);
    else setInputsFilled(false);
  }, [title, file, body, tags]);

  const handleSubmit = async () => {
    if (inputsFilled) {
      if (isAuthed) {
        try {
          const { id } = await createPost({
            title,
            file: previewURL,
            body,
            tags,
            authorUsername: currentUser.username,
          }).unwrap();

          socket.emit('post', {
            sender: currentUser,
            receivers: user?.followers,
            post: { title, id },
          });

          setTitle('');
          setFile('');
          setBody('');
          setTags('');

          navigate('/');
        } catch (err) {
          console.log(err);
        }
      } else handleAuth();
    }
  };

  return (
    <RouteWrapper>
      <Wrapper>
        {isLoading && <LoadingSpinner />}
        {!isLoading && (
          <NewPostWrapper>
            <Heading>ایجاد پست جدید</Heading>
            <InputWrapper>
              موضوع
 دقت داشته باشید که موضوع بیشتر از 48 حرف نمیتواند باشد

              <Input
                maxLength={48}

                type="text"
                dir='rtl'
                ref={titleRef}
                id='title'
                value={title}
                onBlur={e => setTitle(prev => prev.trim())}
                onChange={e => setTitle(e.target.value)}
                required
              />

 عکس برای پست تان انتخاب نمایید . انتخاب عکس اجباری نمی باشد

            </InputWrapper>
            <InputWrapper>
              <Input
                type='file'
                ref={filePickerRef}
                onChange={e => setFile(e.target.files[0])}
                style={{ display: 'none' }}

              />
              <ImagePreview src={previewURL.toString()} alt='' />
              <Button onClick={() => filePickerRef.current.click()}>انتخاب عکس</Button>
            </InputWrapper>

            {/*
متن خود را وارد نمایید
 برای اضافه کردن کد جاوااسکریپت به متن بدین شکل عمل کنید

       javascript

محل قرار گیری کد جاوا اسکریپتی شما

*/}

            <InputWrapper2>

              {/* 1 */}

              {/* <SimpleMDE value={body} onChange={setBody} required /> */}

              {/* 2 */}
              {/* <Editor
              value={body}
                    // editorState={}
                    toolbarClassName="toolbarClassName"
                    wrapperClassName="wrapperClassName"
                    editorClassName="editorClassName"
                    onEditorStateChange={setBody}
                    textAlignment="right"
                    placeholder="اینجا تایپ کنید"
                />; */}

              {/* 3 */}

                <MDEditor
                  value={body}
                  style={{ padding: 15 }}
                  linkTarget="_blank"
                  onChange={setBody}
                  height={400}
                  rehypePlugins={[[rehypeVideo]]}
                  textareaProps={{
                    placeholder: "اینجا تایپ کنید",
                  }}

                />

      راهنما : در سمت چپ پیش نمایش پست خودتان را میتوانید ببینید . هنگام نوشتن کدهای برنامه نویسی ملاک سمت چپ میباشد.  همچنین برای اضافه کردن کد  به متن ابتدا کد خود را درون یک ویرایشگر متن مانند  Vs Code نوشته و سپس به شکل زیر درون ادیتور بالا پیست کنید

   ```javascript
                <br />  محل قرار گیری کد شما <br />
                  ```
     {/*  */}

              {/* <SlateEditor /> */}

{/* <JoditEditor
        ref={editor}
        value={body}
        config={config}
        // onBlur={handleSubmit}
        handleSubmit={handleSubmit}
        onChange={setBody}
        required
      /> */}
              {/*
 */}
            </InputWrapper2>
            <InputWrapper>

                تگ ها
                {isTagsFocused && (
                  تگ ها را با کاما(,) از یکدیگر جدا کنید
                )}

              <Input
                maxLength={15}
                id='tags'
                value={tags}
                onFocus={() => setIsTagsFocused(true)}
                onBlur={() => setIsTagsFocused(false)}
                onChange={e => setTags(e.target.value.replace(/ /g, ''))}
                required
              />
            </InputWrapper>
            <Submit onClick={handleSubmit}>تایید</Submit>
            {isError && <Error>خطاا در انجام عملیات . دوباره امتحان کنید . زمان کامپیوتر خود رابررسی کنید و فقط از آی پی ایران اقدام به ارسال پست بکنید </Error>}
            {!inputsFilled && <Error>تمام فیلدها اجباری هست . زمان تقریبی ارسال پست یک دقیقه میباشد . لطفا صبور باشید عکس پست تان آپلود شود </Error>}
          </NewPostWrapper>
        )}
      </Wrapper>
    </RouteWrapper>
  );
};

const Submit = tw.button`bg-lighter-gray hover:bg-light-gray rounded-md text-center py-2 px-1 w-full text-sm`;

const ImagePreview = tw.img`w-32 h-32 mx-auto border border-gray flex justify-center items-center text-center object-cover`;

const Input = tw.input`py-1 px-2 rounded-md outline-none border-2 border-solid border-gray focus:border-blue`;

const Label = tw.label`font-bold text-dark-gray`;

const Span = tw.p`inline ml-sm`;

const InputWrapper = tw.div`flex flex-col gap-2  `;

const Button = tw.button`bg-lighter-gray hover:bg-light-gray rounded-md text-center py-2 px-1 w-28 text-sm mx-auto`;

const Heading = tw.h1`text-dark-gray text-center`;

const NewPostWrapper = tw.div`bg-white w-3/5 mob:(w-full px-4) mx-auto py-20 px-8 [&>*:not(:last-child)]:mb-md`;

const Wrapper = tw.div`flex items-center`;

const InputWrapper2 = tw.div`border border-gray`;

export default NewPost;

and this is my post list file

import { useEffect } from 'react';
import { AiOutlineHeart } from 'react-icons/ai';
import { BsBookmark, BsBookmarkFill } from 'react-icons/bs';
import { MdOutlineModeComment } from 'react-icons/md';
import { useNavigate } from 'react-router-dom';
import tw, { styled, theme } from 'twin.macro';
import { createPostUrl, formatDate } from '../../../helpers/string';
import { calcReadingTime } from '../../../helpers/utils';
import useBreakpoint from '../../../hooks/useBreakpoint';
import usePostReaction from '../../../hooks/usePostReaction';
import useRequireAuth from '../../../hooks/useRequireAuth';
import LoadingController from '../../LoadingController/LoadingController';
import Tags from '../../Tags';

const Post = ({ post, isFirstPost, filteredTag, toInvalidate }) => {
  const navigate = useNavigate();
  const isSmall = useBreakpoint(theme`screens.sm.max`.replace('px', ''));
  const { isAuthed, handleAuth } = useRequireAuth(false);

  const { id, author, likes, unicorns, bookmarks } = post;
  const likesArr = [...likes];
  const unicornsArr = [...unicorns];
  const bookmarksArr = [...bookmarks];

  const { state, handleReaction, isLoading } = usePostReaction(
    id,
    author,
    likesArr,
    unicornsArr,
    bookmarksArr,
    post.title,
    toInvalidate
  );
  const { isBookmarked } = state;

  const handleSave = () => {
    const action = isBookmarked ? 'removeBookmark' : 'bookmark';
    const effect = isBookmarked ? 'negative' : 'positive';

    if (isAuthed) handleReaction(action, effect, bookmarksArr, 'isBookmarked');
    else handleAuth();
  };

  return (
    post && (
      <Wrapper>
        {/* {isFirstPost && (
          <Image
            onClick={() =>
               navigate(`/${post.author?.username}/${createPostUrl(post.title, post.id)}`)
            }
            src={post?.image?.url}
          />
        )} */}
        <Content>
           navigate(`/${post?.author.username}`)}>
            <Author src={post.author?.picture?.url} />
            <AuthorMeta>
              <AuthorName>{post.author?.name}</AuthorName>
              <CreatedAt>{formatDate(post.createdAt)}</CreatedAt>
              {formatDate(post.updatedAt) !== formatDate(post.createdAt) && (
                <UpdatedAt>{`Updated ${formatDate(post.updatedAt)}`}</UpdatedAt>
              )}
            </AuthorMeta>

          <Title
            onClick={() =>
              navigate(`/${post.author.username}/${createPostUrl(post.title, post.id)}`)
            }>
            {post.title}
          </Title>
          <Tags tags={post.tags} filteredTag={filteredTag} />

            <Reactions
              onClick={() =>
                navigate(`/${post.author.username}/${createPostUrl(post.title, post.id)}`)
              }>
              <SumOfReactions>
                <HeartIcon>
                  <AiOutlineHeart />
                </HeartIcon>
                <Total>
                  {isSmall
                    ? post.likes.length + post.unicorns.length + post.bookmarks.length
                    : `${
                        post.likes.length + post.unicorns.length + post.bookmarks.length
                      }  لایک`}
                </Total>
              </SumOfReactions>
              <SumOfComments>
                <CommentIcon>
                  <MdOutlineModeComment />
                </CommentIcon>
                <Total>
                  {isSmall ? post.comments?.length : `${post.comments?.length} کامنت ها`}
                </Total>
              </SumOfComments>
            </Reactions>
            <Other>
              <MinutesRead>
                {calcReadingTime(post.body)} {`دقیقه ${!isSmall ? 'زمان خواندن' : ''}`}
              </MinutesRead>
              <LoadingController isLoading={isLoading}>
                <SaveButton onClick={handleSave} isBookmarked={isBookmarked}>
                  {isBookmarked ? <BsBookmarkFill /> : <BsBookmark />}
                </SaveButton>
              </LoadingController>
            </Other>

        </Content>
      </Wrapper>
    )
  );
};

const Image = styled.img`
  width: 100%;
  height: 450px;
  object-fit: cover;
  cursor: pointer;
`;
const Content = tw.div`px-sm py-md`;
const Header = tw.div`flex justify-between items-center w-max gap-sm mb-2`;
const Author = tw.img`w-12 h-12 rounded-full cursor-pointer`;
const AuthorMeta = tw.div``;
const AuthorName = tw.h4`text-darker-gray pr-1 pt-1 rounded-md hover:bg-lighter-gray cursor-pointer`;
const CreatedAt = tw.p`text-darker-gray`;
const UpdatedAt = tw.p`text-darker-gray`;
const Title = tw.h2`mb-2     hover:text-blue cursor-pointer`;
const Footer = tw.div`flex justify-between items-center`;
const Reactions = tw.div`flex justify-between items-center gap-md`;
const SumOfReactions = tw.div`flex justify-between items-center gap-2 text-darker-gray rounded-md px-2 py-1 hover:bg-lighter-gray cursor-pointer`;
const HeartIcon = styled.div`
  svg {
    font-size: 1.5rem;
  }
`;
const SumOfComments = tw.div`flex justify-between items-center gap-2 text-darker-gray rounded-md px-2 py-1 hover:bg-lighter-gray cursor-pointer`;
const CommentIcon = styled.div`
  svg {
    font-size: 1.5rem;
  }
`;
const Total = tw.p``;
const Other = tw.div`flex justify-between items-center gap-2`;
const MinutesRead = tw.p`text-darker-gray`;
const SaveButton = styled.button`
  ${tw`p-2 border text-lg border-solid border-transparent rounded-md hover:(text-blue bg-light-blue)`}
  ${({ isBookmarked }) => isBookmarked && tw`bg-light-gray`}
`;
const Wrapper = styled.div`
  ${tw`rounded-lg w-full overflow-hidden bg-white mb-2 shadow-sm hover:shadow`}
`;

export default Post;

sorry for bad english . I just want answer . can not understand why website does not recognize embedded video code like mde editor

and this is my post.body

import { useNavigate } from 'react-router-dom';
import tw, { styled } from 'twin.macro';
import AuthorDetails from '../../../common/AuthorDetails';
import CustomMarkdown from '../../../common/CustomMarkdown';
import Tags from '../../../common/Tags';
import { formatDate } from '../../../helpers/string';
import Advertise from './Advertise';
import Comments from './Comments';
import './Post.css';

const Post = ({ post, isLaptop }) => {
  const navigate = useNavigate();
  return (

    <Wrapper>
      <Image src={post?.image?.url}
       />
      {/*

 */}
      <Advertise />
      <Content>

          <Author
            src={post.author.picture.url}
            onClick={() => navigate(`/${post.author.username}`)}
          />
          <AuthorMeta>
            <AuthorName>{post.author.name}</AuthorName>
            <CreatedAt>{formatDate(post.createdAt)}</CreatedAt>
            {formatDate(post.updatedAt) !== formatDate(post.createdAt) && (
              <UpdatedAt>{`Updated ${formatDate(post.updatedAt)}`}</UpdatedAt>
            )}
          </AuthorMeta>

        <Title>{post.title}</Title>

        <Tags tags={post.tags} isColored={true} />

 <PostBody>
           <CustomMarkdown children={post.body} />
        </PostBody>

        <CommentsContainer>
          {post.comments && (
            <Comments postTitle={post.title} postAuthor={post.author} postId={post.id} />
          )}
        </CommentsContainer>
      </Content>
      {isLaptop && <AuthorDetails post={post} />}
    </Wrapper>
  );
};

const Image = styled.img`
  width: 100%;
  height: 100%;
  margin: 0 auto;
  object-fit: contain;
  cursor: pointer;
`;

const Header = tw.div`flex justify-between items-center w-max gap-sm mt-sm`;

const Author = tw.img`w-12 h-12 rounded-full cursor-pointer`;
const AuthorMeta = tw.div``;
const AuthorName = tw.h4`text-darker-gray pr-1 pt-1 rounded-md hover:bg-lighter-gray cursor-pointer`;
const CreatedAt = tw.p`text-darker-gray`;
const UpdatedAt = tw.p`text-darker-gray`;

const Title = tw.h1`my-sm`;

const PostBody = tw.div`mt-md pb-md border-b border-light-gray border-solid`;

const CommentsContainer = styled.div`
  > *:not(:first-child) {
    ${tw`mt-sm`}
  }
  ${tw`mt-md`}
`;

const Content = tw.div`px-lg my-lg mob:(px-sm)`;

const Wrapper = tw.div`w-full h-full rounded-md overflow-hidden bg-white shadow`;

export default Post;


来源: stackexchange

问:
Pass headers in Debezium http sink
I am using http sink as in doc. I need to pass headers to http sink url, is there a way to do that? TIA</p>

ContentLicense: CC BY-SA 4.0

Title: Pass headers in Debezium http sink


问:
How to unit test a function that uses leaderelection.RunOrDie
Here's a (somewhat simplified) bit of code that exposes a boolean if we've become leader via K8s leader election and false otherwise:

```<code>type SimpleLeader struct {
    amLeader atomic.Value
}

func (s *SimpleLeader) run(ctx context.Context, client coordinationv1client.LeasesGetter) {

    lock := &resourcelock.LeaseLock{
        LeaseMeta: metav1.ObjectMeta{
            Name:      "testname",
            Namespace: "testnamespace",
        },
        Client: client,
        LockConfig: resourcelock.ResourceLockConfig{
            Identity: "testidentity",
        },
    }

    leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
        Lock:            lock,
        ReleaseOnCancel: true,
        LeaseDuration:   15 * time.Second,
        RenewDeadline:   10 * time.Second,
        RetryPeriod:     2 * time.Second,
        Callbacks: leaderelection.LeaderCallbacks{
            OnStartedLeading: func(c context.Context) {
                s.amLeader.Store(true)
            },
            OnStoppedLeading: func() {
                s.amLeader.Store(false)
            },
        },
    })
}
</code>```

My question is how one would go about unit testing this? I'm aware of client-go/fake which does at least allow me to call run.  What's not clear is how to manipulate the fake client go so as to deterministically control whether I hold the lock at any given point in time.

Body:
Here's a (somewhat simplified) bit of code that exposes a boolean if we've become leader via K8s leader election and false otherwise:

type SimpleLeader struct {
    amLeader atomic.Value
}

func (s *SimpleLeader) run(ctx context.Context, client coordinationv1client.LeasesGetter) {

    lock := &resourcelock.LeaseLock{
        LeaseMeta: metav1.ObjectMeta{
            Name:      "testname",
            Namespace: "testnamespace",
        },
        Client: client,
        LockConfig: resourcelock.ResourceLockConfig{
            Identity: "testidentity",
        },
    }

    leaderelection.RunOrDie(ctx, leaderelection.LeaderElectionConfig{
        Lock:            lock,
        ReleaseOnCancel: true,
        LeaseDuration:   15 * time.Second,
        RenewDeadline:   10 * time.Second,
        RetryPeriod:     2 * time.Second,
        Callbacks: leaderelection.LeaderCallbacks{
            OnStartedLeading: func(c context.Context) {
                s.amLeader.Store(true)
            },
            OnStoppedLeading: func() {
                s.amLeader.Store(false)
            },
        },
    })
}

My question is how one would go about unit testing this? I'm aware of client-go/fake which does at least allow me to call run.  What's not clear is how to manipulate the fake client go so as to deterministically control whether I hold the lock at any given point in time.


问:
How do i extract certain information from a prolog database of a taxi company?
I'm working with a database or knowledge base, whatever you call it in Prolog.
It is filled with facts about clients and jobs of a taxi company:
client(id, name, surname, list_of_jobs).

The list of jobs is filled with facts in this form:
job(from, to, price_per_km, date(day,month,year), no_of_car).

If there is a direct link between 2 locations, there can be in the database a fact as such:
distance(Loc_a, loc_b, Km).

The drivers always choose the shortest path from point A to point B.

We need:
count_loc(Loc_ N) - A predicate which counts how many times a location has been arrival or departure point in the whole database, stores that number in N and returns N.

most_km(X,Y) - Returns the name and surname of the client which has accumulated the most mileage while driving with this company.

most_money_made(X) - Returns the no_of_car of the taxi car which has made the most money in the month of december 2015.

This is way out of my league but i need to solve it, so if anyone knows and wants to i'd be thrilled.


问:
0 or 1 is not appearing in the boolean field in the database
I have a problem regarding bit data in mysql when I store a boolean value in the base this value appears 00x

```<code>@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean inactive;
</code>```

I put this in attribute, but is not working! Comes the same problem.

Body:
I have a problem regarding bit data in mysql when I store a boolean value in the base this value appears 00x

@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean inactive;

I put this in attribute, but is not working! Comes the same problem.


问:
Serenity-Cucumber PageObject @DefaultURL no longer getting url from serenity.config file after upgrading to version 3.4.2
After upgrading my Serenity-Cucumber project to version 3.4.2 I receive this error when running.

```<code>java.lang.AssertionError: Invalid URL: page:signin.url
at net.serenitybdd.core.pages.PageUrls.verified(PageUrls.java:80)
</code>```

It was working prior to the update and all of my syntax looks correct, I wonder if this feature changed or the syntax changed. After trying to google search around for some answers I have come here.

Page file

```<code>@DefaultUrl("page:signin.url")
public class SigninPage extends PageObject { ... }
</code>```

serenity.config file

```<code>environments {
prod { signin.url = "https://signin.com" }
dev { signin.url = "https://dev-signin.com" }
default { signin.url = "https://dev-signin.com" }
all { admin.signin.url = "#{signin.url}/admin" }
}
</code>```

If I instead change the Page file to contain a static url, that works and I don't get an error.

```<code>@DefaultUrl("https://dev-signin.com")
</code>```

But, I need it to reference my serenity.config file instead.

Body:
After upgrading my Serenity-Cucumber project to version 3.4.2 I receive this error when running.

java.lang.AssertionError: Invalid URL: page:signin.url
at net.serenitybdd.core.pages.PageUrls.verified(PageUrls.java:80)

It was working prior to the update and all of my syntax looks correct, I wonder if this feature changed or the syntax changed. After trying to google search around for some answers I have come here.

Page file

@DefaultUrl("page:signin.url")
public class SigninPage extends PageObject { ... }

serenity.config file

environments {
prod { signin.url = "https://signin.com" }
dev { signin.url = "https://dev-signin.com" }
default { signin.url = "https://dev-signin.com" }
all { admin.signin.url = "#{signin.url}/admin" }
}

If I instead change the Page file to contain a static url, that works and I don't get an error.

@DefaultUrl("https://dev-signin.com")

But, I need it to reference my serenity.config file instead.


问:
How to prevent the mirror imaging issue on Xamarin UWP
Hi I have a Xamarin application, I need to scan some items(Debit card, Id card) through camera and upload the same to server. Implemented the camera functionality through Xamarin.Essential.Media and it's working on iOS back camera. But in UWP am facing the camera mirroring issue, is there any solution for this. And also how to prevent the iOS front camera. Here is my code.

```<code> var photo = await MediaPicker.CapturePhotoAsync();
 if (photo == null)
 { return;}

 byte[] imgByte;
 using (var bytestream = await photo.OpenReadAsync())
  {
 MemoryStream ms = new MemoryStream();
 bytestream.CopyTo(ms);

 imgByte = ms.ToArray()
   }
</code>```

While Capturing

After Taking, how to avoid the mirroring while capturing the image

Body:
Hi I have a Xamarin application, I need to scan some items(Debit card, Id card) through camera and upload the same to server. Implemented the camera functionality through Xamarin.Essential.Media and it's working on iOS back camera. But in UWP am facing the camera mirroring issue, is there any solution for this. And also how to prevent the iOS front camera. Here is my code.

 var photo = await MediaPicker.CapturePhotoAsync();
 if (photo == null)
 { return;}

 byte[] imgByte;
 using (var bytestream = await photo.OpenReadAsync())
  {
 MemoryStream ms = new MemoryStream();
 bytestream.CopyTo(ms);

 imgByte = ms.ToArray()
   }

While Capturing

After Taking, how to avoid the mirroring while capturing the image


问:
Vue.JS 3, Bootstrap 5, Laravel 9 - Modal Not Displaying
I am building a registration form. It contains a button which opens a Bootstrap 5 modal over the top of the form. I intent to use it to allow the potential user to verify their account ownership.

However, the Modal it doesn't display at all.

Troubleshooting performed so far

I have added a console.log to the openmodal method and it's logging correctly.
I have also attempted to load the modal on mount, however this also did not work.

Code

<template>

Verify Summoner Account

          <button
            type="button"
            class="btn-close"
            data-dismiss="modal"
            aria-label="Close"
            @click="closeModal"
          ></button>

            Please change your summoner account icon to the following image:

          <button type="button" class="btn btn-primary" @click="verifySummoner">
            Verify
          </button>
          <button
            type="button"
            class="btn btn-secondary"
            data-dismiss="modal"
            @click="closeModal"
          >
            Close
          </button>

    <form @submit.prevent="submitForm">

        Username
        <input
          v-model="form.username"
          type="text"
          class="form-control"
          id="username"
          aria-describedby="usernameHelp"
          placeholder="Enter username"
        />

          {{ errors.username[0] }}

        Password
        <input
          v-model="form.password"
          type="password"
          class="form-control"
          id="password"
          placeholder="Enter password"
        />

          {{ errors.password[0] }}

        Email
        <input
          v-model="form.email"
          type="email"
          class="form-control"
          id="email"
          aria-describedby="emailHelp"
          placeholder="Enter email"
        />

          {{ errors.email[0] }}

        Summoner Name
        <input
          v-model="form.summoner_name"
          type="text"
          class="form-control"
          id="summoner_name"
          placeholder="Enter summoner name"
        />

          {{ errors.summoner_name[0] }}

      <button
        type="submit"
        v-if="form.summoner_verified"
        class="btn btn-primary"
      >
        Submit
      </button>
    </form>
    <button
      v-if="!form.summoner_verified"
      @click="openModal"
      class="btn btn-secondary"
    >
      Verify Summoner
    </button>

</template>

```


问:
How can I mock a nested 'this' function in Jest for Vue?
I'm testing a Vue component which is outside a normal Vue project structure (so for the purposes of this question it can be imagined as a standalone .vue file).

In the mounted() lifecycle hook I am calling a function which follows the following format:

this.$parent.$someValue.$getSomeData();

This would ordinarily be passed down the context when the file is in its proper place, but as it is standalone, how do I mock this with Jest?

I've tried adding it into mocks when mounting, spyOn and directly assigning it, such as by using wrapper.vm.$parent.$someValue.$getSomeData = jest.fn().mockReturnValue('');


问:
properly configuring an npm library that uses typescript
I'm creating an npm library and running into a couple issues that I think maybe all stem from a misconception I have about the configuration. I've seen numerous blog posts and they've helped somewhat but they tend to be at a level that don't answer my questions.

Here's what I'm trying to build:

pure typescript code

compiles to a single minimized js file

has a source map back to the original code

convenient imports in my library with @ pointing towards src

Don't require the consumer to need tslib.

can be imported with a


问:
Editable vuetify stepper with validation
Is there any way to make an editable Vuetify stepper where I can make a validation that prevents the event of clicking on another step if the validation is incorrect?

I tried to modify the default event of the editable stepper-step with some event modifiers, like making an event I made before the Vuetify event and saying inside if I want to continue with the default event.


问:
NodeJS express redirect page after login
i have a weird problem and i could't solve it. First of all here is my code;

```<code>    exports.postLogin = async (req, res, next) => {
  try {
    const inputs = await loginSchema.validateAsync(req.body);
    pool.connect(async (error, client, release) => {
      if (error) {
        return console.error("ERROR", error.stack);
      }
      const isExisting = await client.query(
        `SELECT * FROM users WHERE email = '${inputs.email}'`
      );
      if (isExisting.rowCount == 0) {
        release();
        return next(Boom.notFound("User not found!"));
      } else {
        const isCorrectPwd = await bcrypt.compare(
          inputs.password,
          isExisting.rows[0].password
        );
        if (!isCorrectPwd) {
          return next(Boom.unauthorized("Wrong password!"));
        }
        const accessToken = await signAccessToken(isExisting.rows[0].userid);
        const refreshToken = await signRefreshToken(isExisting.rows[0].userid);
        if (accessToken.length !== 0) {

          res.cookie("jwt", refreshToken, {
            httpOnly: true,
            maxAge: 31556952000
          });

          // res.header("Authorization", "Bearer " + accessToken);
          res.redirect(303, '/');

        }

      }
    });
  } catch (error) {
    if (error.isJoi === true)
      return next(createError.BadRequest("Invalid username/password"));
    next(error);
  }
};
</code>```

This is my login controller for post request. It works perfectly when i finalise it with res.json(accessToken,refreshToken). But i want to redirect user to homepage when login process succesfull. With this code nodejs tries to do POST request to "/" my homepage. I have no idea why my redirect request appear to be a post request. What's wrong with my code? Thanks in advance...

here is homepage controller;

```<code>exports.getHomePage = async (req, res, next) => {
  res.render("home", { path: "/" });
};
</code>```

and here is it's route;

```<code>const express = require("express");
const protectController = require("../controller/protect");
const { verifyAccessToken } = require("../helpers/jwt_helper");
const router = express.Router();

router.get("/secretpage", verifyAccessToken, protectController.getPage);
router.get("/", protectController.getHomePage);

module.exports = router;
</code>```

and here is my terminal logs;

```<code>Express server listening on port 3000
Client connected to redis
Client connected to redis and ready to use
POST /auth/login 303 761.269 ms - 36
POST / 404 7.056 ms - 69
</code>```

Body:
i have a weird problem and i could't solve it. First of all here is my code;

    exports.postLogin = async (req, res, next) => {
  try {
    const inputs = await loginSchema.validateAsync(req.body);
    pool.connect(async (error, client, release) => {
      if (error) {
        return console.error("ERROR", error.stack);
      }
      const isExisting = await client.query(
        `SELECT * FROM users WHERE email = '${inputs.email}'`
      );
      if (isExisting.rowCount == 0) {
        release();
        return next(Boom.notFound("User not found!"));
      } else {
        const isCorrectPwd = await bcrypt.compare(
          inputs.password,
          isExisting.rows[0].password
        );
        if (!isCorrectPwd) {
          return next(Boom.unauthorized("Wrong password!"));
        }
        const accessToken = await signAccessToken(isExisting.rows[0].userid);
        const refreshToken = await signRefreshToken(isExisting.rows[0].userid);
        if (accessToken.length !== 0) {

          res.cookie("jwt", refreshToken, {
            httpOnly: true,
            maxAge: 31556952000
          });

          // res.header("Authorization", "Bearer " + accessToken);
          res.redirect(303, '/');

        }

      }
    });
  } catch (error) {
    if (error.isJoi === true)
      return next(createError.BadRequest("Invalid username/password"));
    next(error);
  }
};

This is my login controller for post request. It works perfectly when i finalise it with res.json(accessToken,refreshToken). But i want to redirect user to homepage when login process succesfull. With this code nodejs tries to do POST request to "/" my homepage. I have no idea why my redirect request appear to be a post request. What's wrong with my code? Thanks in advance...

here is homepage controller;

exports.getHomePage = async (req, res, next) => {
  res.render("home", { path: "/" });
};

and here is it's route;

const express = require("express");
const protectController = require("../controller/protect");
const { verifyAccessToken } = require("../helpers/jwt_helper");
const router = express.Router();

router.get("/secretpage", verifyAccessToken, protectController.getPage);
router.get("/", protectController.getHomePage);

module.exports = router;

and here is my terminal logs;

Express server listening on port 3000
Client connected to redis
Client connected to redis and ready to use
POST /auth/login 303 761.269 ms - 36
POST / 404 7.056 ms - 69


问:
What steps can I take to troubleshoot and fix errors when trying to run an assembly language program on DOS BOX?
code error

proteus program

Need help to fix the code because I want to run that code in program 'Analog to Digital Conversion using 8086 microprocessor and here I don't get the proper output as DOS BOX not able to link the object file to executable fie as it has errors in the following code;

```<code>DATA SEGMENT
 PORTA EQU 00H
 PORTB EQU 02H
 PORTC EQU 04H
 PORT_CON EQU 06H
DATA ENDS
CODE SEGMENT
 MOV AX,DATA
 MOV DS, AX

ORG 0000H
START:

 MOV DX, PORT_CON
 MOV AL, 10010000B
 OUT DX, AL

 MOV AL,00H

XX:
 MOV DX,PORTA
 IN AL,DX
 MOV DX, PORTC
 OUT DX,AL
 MOV DX, PORTB
 MOV AL, 00000000B
 OUT DX,AL

 MOV cx, 0ffH
D1: LOOP D1
   MOV DX, PORTB
 MOV AL, 00000001B
 OUT DX,AL

           MOV cx, 0ffH
D2: LOOP D2
 JMP XX

CODE ENDS
END
</code>```

Here's the Assembler LST file hope this thing helps solving

```<code>Microsoft (R) Macro Assembler Version 5.00                  1/5/23 20:55:25
                                                             Page     1-1

       1 0000               DATA SEGMENT
       2 = 0000              PORTA EQU 00H
       3 = 0002              PORTB EQU 02H
       4 = 0004              PORTC EQU 04H
       5 = 0006              PORT_CON EQU 06H
       6 0000               DATA ENDS
       7 0000               CODE SEGMENT
       8 0000  B8 ---- R         MOV AX,DATA
       9 0003  8E D8             MOV DS, AX
      10
      11 0000               ORG 0000H
      12 0000               START:
adc.asm(12): error A2062: Missing or unreachable CS
      13
      14 0000  BA 0006           MOV DX, PORT_CON
      15 0003  B0 90             MOV AL, 10010000B
      16 0005  EE            OUT DX, AL
      17
      18 0006  B0 00             MOV AL,00H
      19
      20
      21 0008               XX:
adc.asm(21): error A2062: Missing or unreachable CS
      22 0008  BA 0000           MOV DX,PORTA
      23 000B  EC            IN AL,DX
      24 000C  BA 0004           MOV DX, PORTC
      25 000F  EE            OUT DX,AL
      26 0010  BA 0002           MOV DX, PORTB
      27 0013  B0 00             MOV AL, 00000000B
      28 0015  EE            OUT DX,AL
      29
      30 0016  B9 00FF           MOV cx, 0ffH
      31 0019  E2 FE            D1: LOOP D1
adc.asm(31): error A2062: Missing or unreachable CS
      32 001B  BA 0002             MOV DX, PORTB
      33 001E  B0 01             MOV AL, 00000001B
      34 0020  EE            OUT DX,AL
      35
      36 0021  B9 00FF                     MOV cx, 0ffH
      37 0024  E2 FE            D2: LOOP D2
adc.asm(37): error A2062: Missing or unreachable CS
      38 0026  EB E0             JMP XX
      39
      40 0028               CODE ENDS
      41                END
Microsoft (R) Macro Assembler Version 5.00                  1/5/23 20:55:25
                                                             Symbols-1

Segments and Groups:

                N a m e             Length   Align  Combine Class

CODE . . . . . . . . . . . . . .    0028    PARA    NONE
DATA . . . . . . . . . . . . . .    0000    PARA    NONE

Symbols:

                N a m e             Type     Value   Attr

D1 . . . . . . . . . . . . . . .    L NEAR  0019    CODE
D2 . . . . . . . . . . . . . . .    L NEAR  0024    CODE

PORTA  . . . . . . . . . . . . .    NUMBER  0000
PORTB  . . . . . . . . . . . . .    NUMBER  0002
PORTC  . . . . . . . . . . . . .    NUMBER  0004
PORT_CON . . . . . . . . . . . .    NUMBER  0006

START  . . . . . . . . . . . . .    L NEAR  0000    CODE

XX . . . . . . . . . . . . . . .    L NEAR  0008    CODE

@FILENAME  . . . . . . . . . . .    TEXT  adc

     41 Source  Lines
     41 Total   Lines
     12 Symbols

  50730 + 465814 Bytes symbol space free

      0 Warning Errors
      4 Severe  Errors
</code>```

Body:
code error

proteus program

Need help to fix the code because I want to run that code in program 'Analog to Digital Conversion using 8086 microprocessor and here I don't get the proper output as DOS BOX not able to link the object file to executable fie as it has errors in the following code;

DATA SEGMENT
 PORTA EQU 00H
 PORTB EQU 02H
 PORTC EQU 04H
 PORT_CON EQU 06H
DATA ENDS
CODE SEGMENT
 MOV AX,DATA
 MOV DS, AX

ORG 0000H
START:

 MOV DX, PORT_CON
 MOV AL, 10010000B
 OUT DX, AL

 MOV AL,00H

XX:
 MOV DX,PORTA
 IN AL,DX
 MOV DX, PORTC
 OUT DX,AL
 MOV DX, PORTB
 MOV AL, 00000000B
 OUT DX,AL

 MOV cx, 0ffH
D1: LOOP D1
   MOV DX, PORTB
 MOV AL, 00000001B
 OUT DX,AL

           MOV cx, 0ffH
D2: LOOP D2
 JMP XX

CODE ENDS
END

Here's the Assembler LST file hope this thing helps solving

Microsoft (R) Macro Assembler Version 5.00                  1/5/23 20:55:25
                                                             Page     1-1

       1 0000               DATA SEGMENT
       2 = 0000              PORTA EQU 00H
       3 = 0002              PORTB EQU 02H
       4 = 0004              PORTC EQU 04H
       5 = 0006              PORT_CON EQU 06H
       6 0000               DATA ENDS
       7 0000               CODE SEGMENT
       8 0000  B8 ---- R         MOV AX,DATA
       9 0003  8E D8             MOV DS, AX
      10
      11 0000               ORG 0000H
      12 0000               START:
adc.asm(12): error A2062: Missing or unreachable CS
      13
      14 0000  BA 0006           MOV DX, PORT_CON
      15 0003  B0 90             MOV AL, 10010000B
      16 0005  EE            OUT DX, AL
      17
      18 0006  B0 00             MOV AL,00H
      19
      20
      21 0008               XX:
adc.asm(21): error A2062: Missing or unreachable CS
      22 0008  BA 0000           MOV DX,PORTA
      23 000B  EC            IN AL,DX
      24 000C  BA 0004           MOV DX, PORTC
      25 000F  EE            OUT DX,AL
      26 0010  BA 0002           MOV DX, PORTB
      27 0013  B0 00             MOV AL, 00000000B
      28 0015  EE            OUT DX,AL
      29
      30 0016  B9 00FF           MOV cx, 0ffH
      31 0019  E2 FE            D1: LOOP D1
adc.asm(31): error A2062: Missing or unreachable CS
      32 001B  BA 0002             MOV DX, PORTB
      33 001E  B0 01             MOV AL, 00000001B
      34 0020  EE            OUT DX,AL
      35
      36 0021  B9 00FF                     MOV cx, 0ffH
      37 0024  E2 FE            D2: LOOP D2
adc.asm(37): error A2062: Missing or unreachable CS
      38 0026  EB E0             JMP XX
      39
      40 0028               CODE ENDS
      41                END
Microsoft (R) Macro Assembler Version 5.00                  1/5/23 20:55:25
                                                             Symbols-1

Segments and Groups:

                N a m e             Length   Align  Combine Class

CODE . . . . . . . . . . . . . .    0028    PARA    NONE
DATA . . . . . . . . . . . . . .    0000    PARA    NONE

Symbols:

                N a m e             Type     Value   Attr

D1 . . . . . . . . . . . . . . .    L NEAR  0019    CODE
D2 . . . . . . . . . . . . . . .    L NEAR  0024    CODE

PORTA  . . . . . . . . . . . . .    NUMBER  0000
PORTB  . . . . . . . . . . . . .    NUMBER  0002
PORTC  . . . . . . . . . . . . .    NUMBER  0004
PORT_CON . . . . . . . . . . . .    NUMBER  0006

START  . . . . . . . . . . . . .    L NEAR  0000    CODE

XX . . . . . . . . . . . . . . .    L NEAR  0008    CODE

@FILENAME  . . . . . . . . . . .    TEXT  adc

     41 Source  Lines
     41 Total   Lines
     12 Symbols

  50730 + 465814 Bytes symbol space free

      0 Warning Errors
      4 Severe  Errors


问:
I am trying to calculate the fiscal year months ending with the last month for the current fiscal year in Tableau
I have created a parameter in Tableau called Fiscal Start Month and it represents an integer for the beginning month of my fiscal year which is May. The integer is set to -8. I created this calculation to show the dates in the relative time frame which should be May 1 - December 31, 2022. The "DOS" is a date field for Date of Service, and I created another calculated field called "date" for today's date:

```<code>IF [DOS] >=DATE(DATEADD('month',[Fiscal Year Start],[Date])) AND [DOS] <=DATE(DATEADD('month',1,DATETRUNC('month',[Date])))
   THEN 'Show'
   ELSE 'Hide'
   END
</code>```

When I filter my data I am getting items from May 5th and it is hiding May 1 - 4. Can someone help me understand why this calculation might not bring in the appropriate dates?

I tried the formula above and this is what I am expecting
enter image description here

Body:
I have created a parameter in Tableau called Fiscal Start Month and it represents an integer for the beginning month of my fiscal year which is May. The integer is set to -8. I created this calculation to show the dates in the relative time frame which should be May 1 - December 31, 2022. The "DOS" is a date field for Date of Service, and I created another calculated field called "date" for today's date:

IF [DOS] >=DATE(DATEADD('month',[Fiscal Year Start],[Date])) AND [DOS] <=DATE(DATEADD('month',1,DATETRUNC('month',[Date])))
   THEN 'Show'
   ELSE 'Hide'
   END

When I filter my data I am getting items from May 5th and it is hiding May 1 - 4. Can someone help me understand why this calculation might not bring in the appropriate dates?

I tried the formula above and this is what I am expecting
enter image description here


问:
Same command broadcasts OK from command line, but not in a script
I'm relying on broadcasting in the following element-by-element multiplication of a 2x2x2 matrix by a 1x2 matrix (broadcasting means the smaller matrix is repeated as many times as necessary to match the size of the larger one - see end for more explanation). One command gives a "nonconformant arguments" error when in a script run from the octave command line. But exactly the same command runs fine if typed at the octave command line.

Occasionally, the script doesn't give the error, but I haven't worked out exactly what arrangement the Universe has to be in to avoid the error (see later) -- whatever, running it within a script is as robust as a cheap garden strimmer.

I give a workround below, but I'd like to understand what's behind this error.

Here's my script file mwe_bcast.m:

```<code># Minimum working example of broadcasting an element-by-element multiplication.
#  The last line errors when run from octave as a script,
#  but not when typed at the octave command line.
clear
test = [0,1;2,3];
test(:,:,2) = 3 - test;
test .*= 2;
factors = [1,2;3,4];
test .*= factors(1,:)
</code>```

But here's the error when run as a script:

```<code>>> mwe_bcast
error: mwe_bcast: .*=: nonconformant arguments (op1 is 2x2x2, op2 is 1x2)
error: called from
    mwe_bcast at line 9 column 6
</code>```

Nonetheless, when I then type the last line at the command line there is no error, and the following output shows that the broadcasting has worked as expected:

```<code>>> test .*= factors(1,:)
test =

ans(:,:,1) =

    0    4
    4   12

ans(:,:,2) =

   6   8
   2   0
</code>```

Even weirder: I checked whether this is repeatable after restarting octave. It is and it isn't! Sometimes, if I run the script any amount of times straight after starting octave (after just a cd to the appropriate directory), it runs without errors. But as soon as I edit the script in any way (just changing a comment, and sometimes even just opening it in the octave editor), then re-run the script, I get the error. But, other times, I get the error the first time I run the script after restarting octave.

Workround: I get no error from the script if I don't use the abbreviated assignment (.*=) for this broadcast element-by-element multiplication, i.e. replace the last line with:
test = test .* factors(1,:);
However, just as weirdly, note that the earlier use of .*= in the script to multiply the same matrix by a scalar always works without an error, even though it also relies on broadcasting.

Explanation of broadcasting: Essentially, the last line multiplies the matrix

```<code>test(:,:,1) = 0,1
              2,3
test(:,:,2) = 3,2
              1,0
</code>```

element-by-element by [1,2] which broadcasts as if it were the matrix:

```<code>factors(:,:,1) = 1,2
                 1,2
factors(:,:,2) = 1,2
                 1,2
</code>```

System:

```<code>GNU Octave, version 5.2.0
Ubuntu 20.04 LTE
Linux 5.15
</code>```

Body:
I'm relying on broadcasting in the following element-by-element multiplication of a 2x2x2 matrix by a 1x2 matrix (broadcasting means the smaller matrix is repeated as many times as necessary to match the size of the larger one - see end for more explanation). One command gives a "nonconformant arguments" error when in a script run from the octave command line. But exactly the same command runs fine if typed at the octave command line.

Occasionally, the script doesn't give the error, but I haven't worked out exactly what arrangement the Universe has to be in to avoid the error (see later) -- whatever, running it within a script is as robust as a cheap garden strimmer.

I give a workround below, but I'd like to understand what's behind this error.

Here's my script file mwe_bcast.m:

# Minimum working example of broadcasting an element-by-element multiplication.
#  The last line errors when run from octave as a script,
#  but not when typed at the octave command line.
clear
test = [0,1;2,3];
test(:,:,2) = 3 - test;
test .*= 2;
factors = [1,2;3,4];
test .*= factors(1,:)

But here's the error when run as a script:

>> mwe_bcast
error: mwe_bcast: .*=: nonconformant arguments (op1 is 2x2x2, op2 is 1x2)
error: called from
    mwe_bcast at line 9 column 6

Nonetheless, when I then type the last line at the command line there is no error, and the following output shows that the broadcasting has worked as expected:

>> test .*= factors(1,:)
test =

ans(:,:,1) =

    0    4
    4   12

ans(:,:,2) =

   6   8
   2   0

Even weirder: I checked whether this is repeatable after restarting octave. It is and it isn't! Sometimes, if I run the script any amount of times straight after starting octave (after just a cd to the appropriate directory), it runs without errors. But as soon as I edit the script in any way (just changing a comment, and sometimes even just opening it in the octave editor), then re-run the script, I get the error. But, other times, I get the error the first time I run the script after restarting octave.

Workround: I get no error from the script if I don't use the abbreviated assignment (.*=) for this broadcast element-by-element multiplication, i.e. replace the last line with:
test = test .* factors(1,:);
However, just as weirdly, note that the earlier use of .*= in the script to multiply the same matrix by a scalar always works without an error, even though it also relies on broadcasting.

Explanation of broadcasting: Essentially, the last line multiplies the matrix

test(:,:,1) = 0,1
              2,3
test(:,:,2) = 3,2
              1,0

element-by-element by [1,2] which broadcasts as if it were the matrix:

factors(:,:,1) = 1,2
                 1,2
factors(:,:,2) = 1,2
                 1,2

System:

GNU Octave, version 5.2.0
Ubuntu 20.04 LTE
Linux 5.15


问:
Using libav (ffmpeg), how to decode a video file directly to a GPU texture?
I'm using ffmpeg's libav to decode video files on Mac. For supported codecs, it says it can use the Mac VideoToolbox framework to hardware-accelerate the decoding.
Can I get the result of that decode directly as a Metal or CoreVideo buffer or texture, in GPU memory? My plan is to process it with compute shaders before sending it to the screen and I'd like to maximize framerate by removing CPU<->GPU transfers.

Is there an example of doing this anywhere?


问:
Automat Print PDF in other PDF file with 'Microsoft Print to PDF'
in a post by Sebastian Wiszowaty, contains a similar subject what I need.

I need to print multiple PDFs from a directory like 'Microsoft Print to PDF'
In the scri below it is crashing.
Who can help me please

```<code>$orders = "C:\Users\username\Downloads\PDF\"
$newext = '_1.pdf'
$items = Get-ChildItem -Path $orders -Filter "*.pdf"
$focus = 2000

foreach ($item in $items) {
    $newfile = $file.BaseName + $newext
    Start-Process -FilePath $orders\$item -verb Print | out-printer -name "Microsoft Print to PDF" #| %{sleep 2;$_} | kill
    start-sleep -Milliseconds $focus
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
    start-sleep -Milliseconds 250
    [System.Windows.Forms.SendKeys]::SendWait($(Join-Path $rootdir $newfile))
    start-sleep -Milliseconds 250
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
    start-sleep -Milliseconds 1500
    $focus = 250

}

Write-Verbose "Print Files Generated"
</code>```

Thanks.

I tried using the the script command powershell
Expected is that every file in the directory is opened and saved and/or printed as 'Microsoft Print to PDF' in the same directory.

When saving, Acrobat is unresponsive and crashes

Body:
in a post by Sebastian Wiszowaty, contains a similar subject what I need.

I need to print multiple PDFs from a directory like 'Microsoft Print to PDF'
In the scri below it is crashing.
Who can help me please

$orders = "C:\Users\username\Downloads\PDF\"
$newext = '_1.pdf'
$items = Get-ChildItem -Path $orders -Filter "*.pdf"
$focus = 2000

foreach ($item in $items) {
    $newfile = $file.BaseName + $newext
    Start-Process -FilePath $orders\$item -verb Print | out-printer -name "Microsoft Print to PDF" #| %{sleep 2;$_} | kill
    start-sleep -Milliseconds $focus
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
    start-sleep -Milliseconds 250
    [System.Windows.Forms.SendKeys]::SendWait($(Join-Path $rootdir $newfile))
    start-sleep -Milliseconds 250
    [System.Windows.Forms.SendKeys]::SendWait("{ENTER}")
    start-sleep -Milliseconds 1500
    $focus = 250

}

Write-Verbose "Print Files Generated"

Thanks.

I tried using the the script command powershell
Expected is that every file in the directory is opened and saved and/or printed as 'Microsoft Print to PDF' in the same directory.

When saving, Acrobat is unresponsive and crashes


问:
Where can I initialize Firebase analytics in a Deno Fresh project?
By default Fresh only ships static pages to the browsers. Only Islands add interactivity. How can I add Firebase analytics to my Fresh App to collect data on all routes?

Usually it would work like this:

```<code>import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAnalytics, isSupported } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
import "dotenv/load.ts";

const firebaseConfig = {
  apiKey: Deno.env.get("apiKey"),
  authDomain: Deno.env.get("authDomain"),
  projectId: Deno.env.get("projectId"),
  storageBucket: Deno.env.get("storageBucket"),
  messagingSenderId: Deno.env.get("messagingSenderId"),
  appId: Deno.env.get("appId"),
  measurementId: Deno.env.get("measurementId"),
};

const firebase = initializeApp(firebaseConfig);

let analytics;
if (await isSupported()) {
  analytics = getAnalytics(firebase);
  console.log("Analytics initialized!");
} else {
  analytics = null
  console.warn("Analytics is not supported...");
}

export { firebase, analytics };
</code>```

But since the isSupported() and getAnalytics(firebase) has to be run on the client in the browser I don't know where to call them.

Body:
By default Fresh only ships static pages to the browsers. Only Islands add interactivity. How can I add Firebase analytics to my Fresh App to collect data on all routes?

Usually it would work like this:

import { initializeApp } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-app.js";
import { getAnalytics, isSupported } from "https://www.gstatic.com/firebasejs/9.15.0/firebase-analytics.js";
import "dotenv/load.ts";

const firebaseConfig = {
  apiKey: Deno.env.get("apiKey"),
  authDomain: Deno.env.get("authDomain"),
  projectId: Deno.env.get("projectId"),
  storageBucket: Deno.env.get("storageBucket"),
  messagingSenderId: Deno.env.get("messagingSenderId"),
  appId: Deno.env.get("appId"),
  measurementId: Deno.env.get("measurementId"),
};

const firebase = initializeApp(firebaseConfig);

let analytics;
if (await isSupported()) {
  analytics = getAnalytics(firebase);
  console.log("Analytics initialized!");
} else {
  analytics = null
  console.warn("Analytics is not supported...");
}

export { firebase, analytics };

But since the isSupported() and getAnalytics(firebase) has to be run on the client in the browser I don't know where to call them.


问:
How I upload an image file from a form in React to an Express api?
I try to modify an user profile Image, but my file seems to not arrive in my backend.
I was able to do so with Postman, but not with my frontend.

I use Express with Mongoose and MongoDB for backend. In frontend I use React, js, Redux and Axios.

In my schema, the profile Image is like this:

```<code>profileImg: {
    data: Buffer,
    contentType: String
}
</code>```

Later, I use the buffer to make the link for image in frontend.
For working with files, I use Multer. This is what I use for my middleware:

```<code>const multer = require('multer');

    const fileFilter = (req, file, cb) => {
    // reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true)
    } else {
        cb(null, false)
    }
    }

    const storage = (location) => multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, `./uploads/${location}`);
    },
    filename: function(req, file, cb) {
        cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
    }
    })

    const uploadImg = (location) => multer({
    storage: storage(location),
    limits: {
    fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
    })

    module.exports = uploadImg
</code>```

This is where I make the update of the user in backend. You can change the name if you comment the section for profileImg section inside updatedUser.
In profileImg I have 2 data lines:

The commented one is what I tried for my file object

The active one is working for image files that are sent with Postman

```<code>const updatedUser = await User.findByIdAndUpdate(
    req.user.id,
    {
      name: req.body.name,

      profileImg: {
        data: fs.readFileSync("uploads/profile/" + req.file.filename),
        //data: fs.readFileSync("uploads/profile" + req.body.profileImg.name)
        contentType: "image/jpeg",
      },

    },
    { new: true }
    );

    res
    .status(200)
    .json({
      _id: updatedUser.id,
      name: updatedUser.name,
      email: updatedUser.email,
      profileImg: updatedUser.profileImg,
      token: generateToken(updatedUser._id),
      // body: req.body,
      // file: req.file
    });
    });
</code>```

In frontend I save the changes of the inputs in a variable called changedUser and it looks like this:

```<code>    const handleChange = (e) => {
    if (e.target.name === "profileImg") {
      // changeuser({ ...userChanged, [e.target.name]: fileUploadHandler(e.target.id) });
      changeuser({ ...userChanged     [e.target.name]:document.getElementById('profileImg').files[0]});
    } else {
      changeuser({ ...userChanged, [e.target.name]: e.target.value });
    }
    };
</code>```

This is my submit function (I use dispatch because my project is using redux):

```<code>    const handleSubmit = (e) => {
    e.preventDefault();
    initialData.name = userChanged.name;
    initialData.address = userChanged.address;
    initialData.profileImg = userChanged.profileImg
    dispatch(update(userChanged))
    changeVisibility("hidden-buttons");
    };
</code>```

I'll also put here the form with the section in which is found the file input

```<code><Container fluid className="body-loginPage">
      <form onSubmit={handleSubmit} id="formElem" encType="multipart/form-data">
        <Row className="custom-row mb-5">
          <Col xs={6} className="custom-column">
            {/* <img src={`${profile_pic}`}></img> */}
            <Image
              thumbnail
              rounded
              src={`data:image/png;base64,${base64_String()}`}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>
            <div>Nume: </div>
          </Col>
          <Col xs={7}>
            <input
              name="name"
              value={userChanged.name}
              onChange={handleChange}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>
            <div>Email: </div>
          </Col>
          <Col xs={7}>
            <input
              disabled
              name="address"
              value={email}
              onChange={handleChange}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>
            <div>Change picture: </div>
          </Col>
          <Col xs={7}>
            <input
              id="profileImg"
              type="file"
              name="profileImg"
              //value={userChanged.picture !== [] ? userChanged.picture : ""}
              ref={inputRef}
              onChange={handleChange}
            />
            {/* <input type="file" onChange={fileSelectedHandler} /> */}
          </Col>
        </Row>

        <Row className="m-1 custom-row">
          <Col xs={3}>
            <div>Telefon: </div>
          </Col>
          <Col xs={7}>
            <input
              name="phone"
              value={userChanged.phone}
              onChange={handleChange}
            />
          </Col>
        </Row>

        <Row className="m-1 custom-row">
          <Col xs={6} />
          <Col xs={2}>
            <Button
              variant="danger"
              onClick={cancelEdit}
              className={`${visible}`}
            >
              Cancel
            </Button>
          </Col>
          <Col xs={3}>
            <Button
              variant="success"

              className={visible}
              type="submit"
            >
              Actualizeaza
            </Button>
          </Col>
        </Row>
      </form>
      <button onClick={getInfo}>click</button>

    </Container>
</code>```

I've tried many variants. I had success using Postman, but I can't reproduce the same result from my project. I am not very experienced with forms and maybe this is where my problem is. I also tried formData for my first time and it didn't work very well.

I am opened to make changes in backend if necessary. I am struggling with this problem for 2 days, any help is appreciated.

If my question is unclear, please ask me for more details. I am quite new here, on stackoverflow.

Body:
I try to modify an user profile Image, but my file seems to not arrive in my backend.
I was able to do so with Postman, but not with my frontend.

I use Express with Mongoose and MongoDB for backend. In frontend I use React, js, Redux and Axios.

In my schema, the profile Image is like this:

profileImg: {
    data: Buffer,
    contentType: String
}

Later, I use the buffer to make the link for image in frontend.
For working with files, I use Multer. This is what I use for my middleware:

const multer = require('multer');

    const fileFilter = (req, file, cb) => {
    // reject a file
    if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/png') {
        cb(null, true)
    } else {
        cb(null, false)
    }
    }

    const storage = (location) => multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, `./uploads/${location}`);
    },
    filename: function(req, file, cb) {
        cb(null, new Date().toISOString().replace(/:/g, '-') + file.originalname)
    }
    })

    const uploadImg = (location) => multer({
    storage: storage(location),
    limits: {
    fileSize: 1024 * 1024 * 5
    },
    fileFilter: fileFilter
    })

    module.exports = uploadImg

This is where I make the update of the user in backend. You can change the name if you comment the section for profileImg section inside updatedUser.
In profileImg I have 2 data lines:

The commented one is what I tried for my file object

The active one is working for image files that are sent with Postman

const updatedUser = await User.findByIdAndUpdate(
    req.user.id,
    {
      name: req.body.name,

      profileImg: {
        data: fs.readFileSync("uploads/profile/" + req.file.filename),
        //data: fs.readFileSync("uploads/profile" + req.body.profileImg.name)
        contentType: "image/jpeg",
      },

    },
    { new: true }
    );

    res
    .status(200)
    .json({
      _id: updatedUser.id,
      name: updatedUser.name,
      email: updatedUser.email,
      profileImg: updatedUser.profileImg,
      token: generateToken(updatedUser._id),
      // body: req.body,
      // file: req.file
    });
    });

In frontend I save the changes of the inputs in a variable called changedUser and it looks like this:

    const handleChange = (e) => {
    if (e.target.name === "profileImg") {
      // changeuser({ ...userChanged, [e.target.name]: fileUploadHandler(e.target.id) });
      changeuser({ ...userChanged     [e.target.name]:document.getElementById('profileImg').files[0]});
    } else {
      changeuser({ ...userChanged, [e.target.name]: e.target.value });
    }
    };

This is my submit function (I use dispatch because my project is using redux):

    const handleSubmit = (e) => {
    e.preventDefault();
    initialData.name = userChanged.name;
    initialData.address = userChanged.address;
    initialData.profileImg = userChanged.profileImg
    dispatch(update(userChanged))
    changeVisibility("hidden-buttons");
    };

I'll also put here the form with the section in which is found the file input

<Container fluid className="body-loginPage">
      <form onSubmit={handleSubmit} id="formElem" encType="multipart/form-data">
        <Row className="custom-row mb-5">
          <Col xs={6} className="custom-column">
            {/* <img src={`${profile_pic}`}> */}
            <Image
              thumbnail
              rounded
              src={`data:image/png;base64,${base64_String()}`}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>

Nume:

          </Col>
          <Col xs={7}>
            <input
              name="name"
              value={userChanged.name}
              onChange={handleChange}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>

Email:

          </Col>
          <Col xs={7}>
            <input
              disabled
              name="address"
              value={email}
              onChange={handleChange}
            />
          </Col>
        </Row>
        <Row className="m-1 custom-row mb-3">
          <Col xs={3}>

Change picture:

          </Col>
          <Col xs={7}>
            <input
              id="profileImg"
              type="file"
              name="profileImg"
              //value={userChanged.picture !== [] ? userChanged.picture : ""}
              ref={inputRef}
              onChange={handleChange}
            />
            {/* <input type="file" onChange={fileSelectedHandler} /> */}
          </Col>
        </Row>

        <Row className="m-1 custom-row">
          <Col xs={3}>

Telefon:

          </Col>
          <Col xs={7}>
            <input
              name="phone"
              value={userChanged.phone}
              onChange={handleChange}
            />
          </Col>
        </Row>

        <Row className="m-1 custom-row">
          <Col xs={6} />
          <Col xs={2}>
            <Button
              variant="danger"
              onClick={cancelEdit}
              className={`${visible}`}
            >
              Cancel
            </Button>
          </Col>
          <Col xs={3}>
            <Button
              variant="success"

              className={visible}
              type="submit"
            >
              Actualizeaza
            </Button>
          </Col>
        </Row>
      </form>
      <button onClick={getInfo}>click</button>

    </Container>

I've tried many variants. I had success using Postman, but I can't reproduce the same result from my project. I am not very experienced with forms and maybe this is where my problem is. I also tried formData for my first time and it didn't work very well.

I am opened to make changes in backend if necessary. I am struggling with this problem for 2 days, any help is appreciated.

If my question is unclear, please ask me for more details. I am quite new here, on stackoverflow.


问:
An item with the same key - throwArgumentexception
I hope this question doesn't exist yet, because I already searched and couldn't find it... I have a function that scans the windows processes, and it worked very well, but I started to receive an error "An item with the same key", but the error is not caused all the time, Below is my function that is causing the error

```<code>Private Function enumWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean
    Try
        If hWnd <> hShellWindow Then
            Dim windowPid As UInt32
            If Not IsWindowVisible(hWnd) Then
                Return True
            End If
            Dim length As Integer = GetWindowTextLength(hWnd)
            If length = 0 Then
                Return True
            End If
            GetWindowThreadProcessId(hWnd, windowPid)
            If windowPid <> currentProcessID Then
                Return True
            End If
            Dim stringBuilder As New StringBuilder(length)
            GetWindowText(hWnd, stringBuilder, length + 1)
            dictWindows.Add(hWnd, stringBuilder.ToString)
        End If
        Return True
    Catch ex As Exception
        writeExeption(ex)
    End Try
    Return False
End Function
</code>```

I have already reviewed my code, but I still haven't found the solution....

Body:
I hope this question doesn't exist yet, because I already searched and couldn't find it... I have a function that scans the windows processes, and it worked very well, but I started to receive an error "An item with the same key", but the error is not caused all the time, Below is my function that is causing the error

Private Function enumWindowsInternal(ByVal hWnd As IntPtr, ByVal lParam As Integer) As Boolean
    Try
        If hWnd <> hShellWindow Then
            Dim windowPid As UInt32
            If Not IsWindowVisible(hWnd) Then
                Return True
            End If
            Dim length As Integer = GetWindowTextLength(hWnd)
            If length = 0 Then
                Return True
            End If
            GetWindowThreadProcessId(hWnd, windowPid)
            If windowPid <> currentProcessID Then
                Return True
            End If
            Dim stringBuilder As New StringBuilder(length)
            GetWindowText(hWnd, stringBuilder, length + 1)
            dictWindows.Add(hWnd, stringBuilder.ToString)
        End If
        Return True
    Catch ex As Exception
        writeExeption(ex)
    End Try
    Return False
End Function

I have already reviewed my code, but I still haven't found the solution....


问:
Generate BigQuery schema based on a provided NEWLINE_DELIMITED_JSON?
Is there a way to quickly generate BigQuery table schema based on a provided NEWLINE_DELIMITED_JSON file?

Right now I'm just uploading the file as a new table with schema autodetection and run bq show --format=prettyjson my-project:my-dataset.my-table | jq '.schema.fields' to get the schema.

This method is limited, especially when I'm working with a large input file.


问:
I am trying to append every tr to a div but it doesnt work
I want to append every tr to a div, but it doesnt seem to work.
if I go with $(someTableRow).clone().appendTo(theDiv) it doesnt do nothing when I click the button.
if I go with $(theDiv).append(someTableRow) it appends but it goes, 3 table rows instead to the div, then one, and one, since it has only 5, why does this happen?

```<code>@model IEnumerable<webAplikacijaScafolding.Models.Album>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Genre.Name)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Title)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.ArtistId)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.Price)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.AlbumArtUrl)
        </th>
        <th></th>
    </tr>

    @foreach (var item in Model)
    {
        <tr class="tRows">
            <td>
                @Html.DisplayFor(modelItem => item.Genre.Name)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Title)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.ArtistId)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.Price)
            </td>
            <td>

                <img width="200" height="100" src="@Url.Content(item.AlbumArtUrl)" />
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id = item.AlbumId }) |
                @Html.ActionLink("Details", "Details", new { id = item.AlbumId }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })
            </td>
        </tr>
    }

</table>
<button id="button">Click for Day offer</button>

<div id="discount">

</div>

@section Scripts {
    <script>

        $(function () {
            $("#button ").click(function () {
                var b = document.getElementsByClassName('tRows');

                /*  $(b[2]).clone().appendTo("#discount");*/

                for (var i = 0; i < b.length; i++) {
                    $(b[i]).clone().appendTo("#discount");

                }

            })

        })

    </script>

}
</code>```

Body:
I want to append every tr to a div, but it doesnt seem to work.
if I go with $(someTableRow).clone().appendTo(theDiv) it doesnt do nothing when I click the button.
if I go with $(theDiv).append(someTableRow) it appends but it goes, 3 table rows instead to the div, then one, and one, since it has only 5, why does this happen?

@model IEnumerable<webAplikacijaScafolding.Models.Album>

@{
    ViewBag.Title = "Index";
}

Index

    @Html.ActionLink("Create New", "Create")

            @Html.DisplayNameFor(model => model.Genre.Name)

            @Html.DisplayNameFor(model => model.Title)

            @Html.DisplayNameFor(model => model.ArtistId)

            @Html.DisplayNameFor(model => model.Price)

            @Html.DisplayNameFor(model => model.AlbumArtUrl)

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Genre.Name)

                @Html.DisplayFor(modelItem => item.Title)

                @Html.DisplayFor(modelItem => item.ArtistId)

                @Html.DisplayFor(modelItem => item.Price)

                @Html.ActionLink("Edit", "Edit", new { id = item.AlbumId }) |
                @Html.ActionLink("Details", "Details", new { id = item.AlbumId }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.AlbumId })

    }

<button id="button">Click for Day offer</button>

@section Scripts {

}


问:
Can't reach Opentelemetry Collector Service from SDK
After creating a service for my colllector deployment. I want to use the service endpoint as the jaegar endpoint in the SDK but it seems it cant be reached

const OPEN_TELEMETRY_COLLECTOR_URL = "http://otel-collector-service.telemetry.svc:14278/api/traces"

func exporterToJaeger() (*jaeger.Exporter, error) {
    return jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(OPEN_TELEMETRY_COLLECTOR_URL)))
}
```
<p>I'm getting this error
<code>2023/01/02 23:22:42 Post "http://otel-collector-service.telemetry.svc:14278/api/traces": dial tcp: lookup otel-collector-service.telemetry.svc: no such host</code></p>
<p>I have tried to lookup solutions online and tried changing the endpoint to
<code>"http://otel-collector-service.telemetry.svc.cluster.local:14278/api/traces"</code></p>
<p>I also tried port-forwarding</p>
```kubectl port-forward -n telemetry service/otel-collector-service :14278

Forwarding from 127.0.0.1:54957 -> 14278
Forwarding from [::1]:54957 -> 14278
```

And changed the endpoint to
"http://otel-collector-service.telemetry.svc:54957/api/traces"

and

"http://otel-collector-service.telemetry.svc.cluster.local:54957/api/traces"

But i'm getting the same error? What could possibly be the issue?

Body:
After creating a service for my colllector deployment. I want to use the service endpoint as the jaegar endpoint in the SDK but it seems it cant be reached

const OPEN_TELEMETRY_COLLECTOR_URL = "http://otel-collector-service.telemetry.svc:14278/api/traces"

func exporterToJaeger() (*jaeger.Exporter, error) {
    return jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(OPEN_TELEMETRY_COLLECTOR_URL)))
}

I'm getting this error
2023/01/02 23:22:42 Post "http://otel-collector-service.telemetry.svc:14278/api/traces": dial tcp: lookup otel-collector-service.telemetry.svc: no such host

I have tried to lookup solutions online and tried changing the endpoint to
"http://otel-collector-service.telemetry.svc.cluster.local:14278/api/traces"

I also tried port-forwarding

kubectl port-forward -n telemetry service/otel-collector-service :14278

Forwarding from 127.0.0.1:54957 -> 14278
Forwarding from [::1]:54957 -> 14278

And changed the endpoint to
"http://otel-collector-service.telemetry.svc:54957/api/traces"

and

"http://otel-collector-service.telemetry.svc.cluster.local:54957/api/traces"

But i'm getting the same error? What could possibly be the issue?