问:
Neo4J - CSV import - Neo.ClientError.Statement.ExternalResourceFailed
Sorry for this redundant post but no one else resolves my problem.

My goal

Import a CSV file on Neo4J.

My Problem

Neo.ClientError.Statement.ExternalResourceFailed

Couldn't load the external resource at: file:/AFG-ADM1.csv ()

My Environment

I work on my computer and install Neo4J with a docker-compose file as follows:

version: "3.1"
services:
  neo4j:
    image: neo4j:5.3.0
    restart: unless-stopped
    container_name: neo4j
    # The ports that will be accessible from outside the container - HTTP (7474) and Bolt (7687).
    ports:
      - "7474:7474"
      - "7687:7687"
    # Uncomment the volumes to be mounted to make them accessible from outside the container.
    volumes:
      - ~/Documents/neo4j/neo4j.conf:/conf/neo4j.conf
      - ~/Documents/neo4j/data:/var/lib/neo4j/data
      - ~/Documents/neo4j/logs:/var/lib/neo4j/logs
      - ~/Documents/neo4j/conf:/var/lib/neo4j/conf
      - ~/Documents/neo4j/import:/var/lib/neo4j/import
      # - ./metrics/server1:/var/lib/neo4j/metrics
      # - ./licenses/server1:/var/lib/neo4j/licenses
      # - ./ssl/server1:/var/lib/neo4j/ssl
    environment:
      - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes
      - NEO4J_AUTH=neo4j/password
      - EXTENDED_CONF=yes
      - NEO4J_EDITION=docker_compose
      - NEO4J_initial_server_mode__constraint=PRIMARY
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider localhost:7474 || exit 1"]
    user: 1000:1000
```
<p>In my "~/Documents/neo4j/import" directory, I have the file "AFG-ADM1.csv".
To be sure, I went to look in my container:
<img src="https://i.stack.imgur.com/viTHM.png" alt="enter image description here" /></p>
<p>My neo4j config file, neo4j.conf</p>
```# Setting that specifies how much memory Neo4j is allowed to use for the page cache.
server.memory.pagecache.size=100M

# Setting that specifies the initial JVM heap size.
server.memory.heap.initial_size=100M

# Enable server-side routing
dbms.routing.enabled=true

# Use server-side routing for neo4j:// protocol connections.
dbms.routing.default_router=SERVER

server.config.strict_validation.enabled=false

dbms.max_databases=$(my_setting.bat)
#dbms.security.allow_csv_import_from_file_urls=true
```
<p>I try with and without opt dbms.security.allow_csv_import_from_file_urls to true</p>
<h2>My cmd</h2>
```LOAD CSV WITH HEADERS FROM "file:///AFG-ADM1.csv" AS csvLine
CREATE (p:Pipeline {name: csvLine.name, level: csvLine.Level, shapeGroup: csvLine.shapeGroup})
```

And get this error:

Body:
Sorry for this redundant post but no one else resolves my problem.

My goal

Import a CSV file on Neo4J.

My Problem

Neo.ClientError.Statement.ExternalResourceFailed

Couldn't load the external resource at: file:/AFG-ADM1.csv ()

My Environment

I work on my computer and install Neo4J with a docker-compose file as follows:

version: "3.1"
services:
  neo4j:
    image: neo4j:5.3.0
    restart: unless-stopped
    container_name: neo4j
    # The ports that will be accessible from outside the container - HTTP (7474) and Bolt (7687).
    ports:
      - "7474:7474"
      - "7687:7687"
    # Uncomment the volumes to be mounted to make them accessible from outside the container.
    volumes:
      - ~/Documents/neo4j/neo4j.conf:/conf/neo4j.conf
      - ~/Documents/neo4j/data:/var/lib/neo4j/data
      - ~/Documents/neo4j/logs:/var/lib/neo4j/logs
      - ~/Documents/neo4j/conf:/var/lib/neo4j/conf
      - ~/Documents/neo4j/import:/var/lib/neo4j/import
      # - ./metrics/server1:/var/lib/neo4j/metrics
      # - ./licenses/server1:/var/lib/neo4j/licenses
      # - ./ssl/server1:/var/lib/neo4j/ssl
    environment:
      - NEO4J_ACCEPT_LICENSE_AGREEMENT=yes
      - NEO4J_AUTH=neo4j/password
      - EXTENDED_CONF=yes
      - NEO4J_EDITION=docker_compose
      - NEO4J_initial_server_mode__constraint=PRIMARY
    healthcheck:
      test: ["CMD-SHELL", "wget --no-verbose --tries=1 --spider localhost:7474 || exit 1"]
    user: 1000:1000

In my "~/Documents/neo4j/import" directory, I have the file "AFG-ADM1.csv".
To be sure, I went to look in my container:

My neo4j config file, neo4j.conf

# Setting that specifies how much memory Neo4j is allowed to use for the page cache.
server.memory.pagecache.size=100M

# Setting that specifies the initial JVM heap size.
server.memory.heap.initial_size=100M

# Enable server-side routing
dbms.routing.enabled=true

# Use server-side routing for neo4j:// protocol connections.
dbms.routing.default_router=SERVER

server.config.strict_validation.enabled=false

dbms.max_databases=$(my_setting.bat)
#dbms.security.allow_csv_import_from_file_urls=true

I try with and without opt dbms.security.allow_csv_import_from_file_urls to true

My cmd

LOAD CSV WITH HEADERS FROM "file:///AFG-ADM1.csv" AS csvLine
CREATE (p:Pipeline {name: csvLine.name, level: csvLine.Level, shapeGroup: csvLine.shapeGroup})

And get this error:


来源: stackexchange

问:
"Show Execution Point" JetBrains debugging action keyboard shortcut equivalent for Visual Studio Code VSCode
I can't find in Visual Studio Code equivalent debugging action for "Show Execution Point". Shortcut/function to navigate back to file and place in that file where debugger currently is).

Sometimes (actually all the time) while debugging it is necessary to look around, navigate to different source code files but then you have to come back where debugger is.

It works perfectly in all JetBrains products, you just have to trigger "Show Execution Point" (Option+F10 on Mac by default, I usually have it remapped to different shortcut) action but I can't find equivalent of that in Visual Studio Code.

Is that the case of different name? or it is simply not there?

Or maybe there is a plugin for this then?

Just to recap what I'm asking is:
Is there any possible way to replicate this behaviour under keyboard shortcut -> when you press that shortcut I would like IDE to re-navigate back to the file where currently debugger is and scroll to that point in the source file in order to show where currently debugger is.

ContentLicense: CC BY-SA 4.0


问:
How do I check a byte representation to an enumeration member in python?
In C# I can check a byte representation to an enum number like this:

using System;

namespace HelloWorld {
    class Hello {
        public enum Types {
            NONE = 0x01,
            TRUE = 0x02,
            FALSE = 0x03,
            STRING_8 = 0x30
        };

        static void Main() {
            // 3 would be the byte number -> FALSE
            // 48 would be the byte number -> STRING_8
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 3));
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 48));
        }
    }
}
```

How can I replicate this in Python? I don't know what function to look for to make this work, I need this to parse binary files in Python that contain json data.

I looked up on google and found out enumeration classes do exist in Python, but couldn't find a function that fits & answers my problem.

Body:
In C# I can check a byte representation to an enum number like this:

using System;

namespace HelloWorld {
    class Hello {
        public enum Types {
            NONE = 0x01,
            TRUE = 0x02,
            FALSE = 0x03,
            STRING_8 = 0x30
        };

        static void Main() {
            // 3 would be the byte number -> FALSE
            // 48 would be the byte number -> STRING_8
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 3));
            Console.WriteLine((Types)Enum.ToObject(typeof(Types), 48));
        }
    }
}

How can I replicate this in Python? I don't know what function to look for to make this work, I need this to parse binary files in Python that contain json data.

I looked up on google and found out enumeration classes do exist in Python, but couldn't find a function that fits & answers my problem.


问:
NextJs opening slug from link not working in production
Hi I have recently developed a nextJS blog it works as it should, but the only thing is that when I try to go to a blog post from the link it goes to the 404 page. When I have tried this with the local host it works, but then when I try it in production it doesn't. In the console I get the error "Failed to load resource: the server responded with a status of 404 ()" If anyone wants to try and see here is the link to the blog post: https://fischi-blog.web.app/posts/comparison-of-cross-platform-app-development-flutter-react-native-and-xamarin

Here is my [slug].js file

```<code>import { GraphQLClient, gql } from "graphql-request";
import styles from "../../styles/Slug.module.css";
import moment from "moment";
import Nav from "../../components/Navbar/Nav2";
import BottomPart from "../bottomPart";
import {FacebookShareButton, LinkedinShareButton, TwitterShareButton,} from "react-share";
import {FacebookIcon, LinkedinIcon, TwitterIcon} from "react-share";

const graphcms = new GraphQLClient(
  "*"
);

const QUERY = gql`
  query Post($slug: String!) {
    post(where: { slug: $slug  }) {
      id
      title
      slug
      date
      category
      content {
        html
      }
      coverPhoto {
        id
        url
      }
    }
  }
`;
const SLUGLIST = gql`
  {
    posts {
      slug
    }
  }
`;

export async function getStaticPaths() {
  const { posts } = await graphcms.request(SLUGLIST);
  return {
    paths: posts.map((post) => ({ params: { slug: post.slug } })),
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const slug = params.slug;
  const data = await graphcms.request(QUERY, { slug });
  const post = data.post;
  return {
    props: {
      post,
    },
    revalidate: 30,
  };
}

export default function BlogPost({ post }) {

}
</code>```

Here is my next.config.js file

```<code>/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
}

module.exports = {
  images: {
    domains: ['media.graphassets.com'],
    loader: 'akamai',
    path: '',
  },
  distDir: "_next",
  generateBuildId: async () => {
    if (process.env.BUILD_ID) {
      return process.env.BUILD_ID;
    } else {
      return `${new Date().getTime()}`;
    }
  },
}
</code>```

Body:
Hi I have recently developed a nextJS blog it works as it should, but the only thing is that when I try to go to a blog post from the link it goes to the 404 page. When I have tried this with the local host it works, but then when I try it in production it doesn't. In the console I get the error "Failed to load resource: the server responded with a status of 404 ()" If anyone wants to try and see here is the link to the blog post: https://fischi-blog.web.app/posts/comparison-of-cross-platform-app-development-flutter-react-native-and-xamarin

Here is my [slug].js file

import { GraphQLClient, gql } from "graphql-request";
import styles from "../../styles/Slug.module.css";
import moment from "moment";
import Nav from "../../components/Navbar/Nav2";
import BottomPart from "../bottomPart";
import {FacebookShareButton, LinkedinShareButton, TwitterShareButton,} from "react-share";
import {FacebookIcon, LinkedinIcon, TwitterIcon} from "react-share";

const graphcms = new GraphQLClient(
  "*"
);

const QUERY = gql`
  query Post($slug: String!) {
    post(where: { slug: $slug  }) {
      id
      title
      slug
      date
      category
      content {
        html
      }
      coverPhoto {
        id
        url
      }
    }
  }
`;
const SLUGLIST = gql`
  {
    posts {
      slug
    }
  }
`;

export async function getStaticPaths() {
  const { posts } = await graphcms.request(SLUGLIST);
  return {
    paths: posts.map((post) => ({ params: { slug: post.slug } })),
    fallback: false,
  };
}

export async function getStaticProps({ params }) {
  const slug = params.slug;
  const data = await graphcms.request(QUERY, { slug });
  const post = data.post;
  return {
    props: {
      post,
    },
    revalidate: 30,
  };
}

export default function BlogPost({ post }) {

}

Here is my next.config.js file

/** @type {import('next').NextConfig} */
const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
}

module.exports = {
  images: {
    domains: ['media.graphassets.com'],
    loader: 'akamai',
    path: '',
  },
  distDir: "_next",
  generateBuildId: async () => {
    if (process.env.BUILD_ID) {
      return process.env.BUILD_ID;
    } else {
      return `${new Date().getTime()}`;
    }
  },
}


问:
Flutter: How do I implement sign up with a profile picture using flutter_bloc and freezed in DDD?
I am trying to implement sign up feature for an app using the Domain Driven Design and I am having issues emitting the state for the profile image.

I am using the image_picker plugin. The image gets picked successfully but the bloc fails to emit the state with the image.

`

```<code>class MediaService {
  final ImagePicker _picker;

  MediaService(this._picker);

  Future<XFile?> getImage({required bool fromGallery}) async {
    return await _picker.pickImage(
      source: fromGallery ? ImageSource.gallery : ImageSource.camera,
    );
  }
}
</code>```

`

Here is my sign up bloc:
SignUpState
`

```<code>@freezed
class SignUpState with _$SignUpState {
  const factory SignUpState({
    required IFullName fullName,
    required IEmail email,
    required IPassword password,
    IAvatar? avatar,
    required bool showError,
    required bool loading,
    required Option<Either<AuthError, Unit>> option,
  }) = _SignUpState;

  factory SignUpState.initial() => SignUpState(
        fullName: IFullName(''),
        email: IEmail(''),
        password: IPassword(''),
        avatar: IAvatar(null),
        showError: false,
        loading: false,
        option: none(),
      );
}
</code>```

`

SignUpEvent
`

```<code>@freezed
class SignUpEvent with _$SignUpEvent {
  const factory SignUpEvent.fullNameChanged(String fullName) = _FullNameChanged;
  const factory SignUpEvent.emailChanged(String email) = _EmailChanged;
  const factory SignUpEvent.passwordChanged(String password) = _PasswordChanged;
  const factory SignUpEvent.avatarPicked(bool fromGallery) = _AvatarPicked;
  const factory SignUpEvent.signUpPressed() = _SignUpPressed;
}
</code>```

`

SignUpBloc
`

```<code>class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
  final IAuthFacade _authFacade;
  final MediaService _mediaService;

  SignUpBloc(this._authFacade, this._mediaService) : super(SignUpState.initial()) {
    on<_FullNameChanged>((event, emit) => _fullNameChanged(event, emit));
    on<_EmailChanged>((event, emit) => _emailChanged(event, emit));
    on<_PasswordChanged>((event, emit) => _passwordChanged(event, emit));
    on<_AvatarPicked>((event, emit) => _avatarPicked(event, emit));
    on<_SignUpPressed>((event, emit) => _signUpPressed(event, emit));
  }

  _emailChanged(_EmailChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(email: IEmail(e.email), option: none()));
  }

  _fullNameChanged(_FullNameChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(fullName: IFullName(e.fullName), option: none()));
  }

  _avatarPicked(_AvatarPicked e, Emitter<SignUpState> emit) async {
    final file = await _mediaService.getImage(fromGallery: e.fromGallery);
    if (file != null) {
      emit(state.copyWith(avatar: IAvatar(File(file.path)), option: none()));
    }
  }

  _passwordChanged(_PasswordChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(password: IPassword(e.password), option: none()));
  }

  _signUpPressed(_SignUpPressed e, Emitter<SignUpState> emit) async {
    Either<AuthError, Unit> r;

    final isNameValid = state.fullName.isValid();
    final isEmailValid = state.email.isValid();
    final isPasswordValid = state.password.isValid();

    if (isNameValid && isEmailValid && isPasswordValid) {
      emit(state.copyWith(loading: true, option: none()));

      r = await _authFacade.signUp(
        fullName: state.fullName,
        email: state.email,
        password: state.password,
        avatar: state.avatar,
      );

      emit(state.copyWith(loading: false, option: some(r)));
    }

    emit(state.copyWith(loading: false, showError: true, option: none()));
  }
}
</code>```

`

UploadImageWidget
`

```<code>class UploadImageWidget extends StatelessWidget {
  const UploadImageWidget({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final bloc = di<SignUpBloc>();
    return GestureDetector(
      onTap: () async {
        await showModalBottomSheet(
          context: context,
          backgroundColor: Colors.transparent,
          builder: (context) => const ImageSourceBottomSheet(),
        );
      },
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(shape: BoxShape.circle),
            child: BlocListener<SignUpBloc, SignUpState>(
              bloc: bloc,
              listener: (context, state) => bloc.state.avatar,
              listenWhen: (p, c) => p.avatar != c.avatar,
              child: CircleAvatar(
                radius: SizeUtil.r(20),
                backgroundColor: Colors.transparent,
                foregroundImage: bloc.state.avatar?.getOrCrash() != null
                    ? FileImage(bloc.state.avatar!.getOrCrash()!)
                    : null,
                child: bloc.state.avatar?.getOrCrash() == null
                    ? const Icon(MIcons.camera)
                    : null,
              ),
            ),
          ),
          SizeUtil.vS(4),
          const Text('Upload Image'),
        ],
      ),
    );
  }
}
</code>```

`

ImageSourceBottomSheet
`

```<code>class ImageSourceBottomSheet extends StatelessWidget {
  const ImageSourceBottomSheet({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final bloc = di<SignUpBloc>();
    return Wrap(
      alignment: WrapAlignment.end,
      children: [
        GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          child: Container(
            height: SizeUtil.w(35),
            width: SizeUtil.w(35),
            margin: SizeUtil.pSymmetric(h: 25, v: 10),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Theme.of(context).primaryColorLight,
            ),
            child: const Icon(Icons.close),
          ),
        ),
        Container(
          margin: SizeUtil.pFromLTRB(25, 0, 25, 25),
          padding: SizeUtil.pSymmetric(v: 13),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(SizeUtil.r(15)),
          ),
          child: Wrap(
            children: [
              _Button(
                title: 'Pick from Gallery',
                icon: MIcons.image,
                onPressed: () {
                  bloc.add(const SignUpEvent.avatarPicked(true));
                },
              ),
              const Divider(),
              _Button(
                title: 'Use Camera',
                icon: MIcons.camera,
                onPressed: () {
                  bloc.add(const SignUpEvent.avatarPicked(false));
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}
</code>```

`

Please, what am I doing wrong and how can I fix it? Thank you.

Body:
I am trying to implement sign up feature for an app using the Domain Driven Design and I am having issues emitting the state for the profile image.

I am using the image_picker plugin. The image gets picked successfully but the bloc fails to emit the state with the image.

`

class MediaService {
  final ImagePicker _picker;

  MediaService(this._picker);

  Future<XFile?> getImage({required bool fromGallery}) async {
    return await _picker.pickImage(
      source: fromGallery ? ImageSource.gallery : ImageSource.camera,
    );
  }
}

`

Here is my sign up bloc:
SignUpState
`

@freezed
class SignUpState with _$SignUpState {
  const factory SignUpState({
    required IFullName fullName,
    required IEmail email,
    required IPassword password,
    IAvatar? avatar,
    required bool showError,
    required bool loading,
    required Option<Either<AuthError, Unit>> option,
  }) = _SignUpState;

  factory SignUpState.initial() => SignUpState(
        fullName: IFullName(''),
        email: IEmail(''),
        password: IPassword(''),
        avatar: IAvatar(null),
        showError: false,
        loading: false,
        option: none(),
      );
}

`

SignUpEvent
`

@freezed
class SignUpEvent with _$SignUpEvent {
  const factory SignUpEvent.fullNameChanged(String fullName) = _FullNameChanged;
  const factory SignUpEvent.emailChanged(String email) = _EmailChanged;
  const factory SignUpEvent.passwordChanged(String password) = _PasswordChanged;
  const factory SignUpEvent.avatarPicked(bool fromGallery) = _AvatarPicked;
  const factory SignUpEvent.signUpPressed() = _SignUpPressed;
}

`

SignUpBloc
`

class SignUpBloc extends Bloc<SignUpEvent, SignUpState> {
  final IAuthFacade _authFacade;
  final MediaService _mediaService;

  SignUpBloc(this._authFacade, this._mediaService) : super(SignUpState.initial()) {
    on<_FullNameChanged>((event, emit) => _fullNameChanged(event, emit));
    on<_EmailChanged>((event, emit) => _emailChanged(event, emit));
    on<_PasswordChanged>((event, emit) => _passwordChanged(event, emit));
    on<_AvatarPicked>((event, emit) => _avatarPicked(event, emit));
    on<_SignUpPressed>((event, emit) => _signUpPressed(event, emit));
  }

  _emailChanged(_EmailChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(email: IEmail(e.email), option: none()));
  }

  _fullNameChanged(_FullNameChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(fullName: IFullName(e.fullName), option: none()));
  }

  _avatarPicked(_AvatarPicked e, Emitter<SignUpState> emit) async {
    final file = await _mediaService.getImage(fromGallery: e.fromGallery);
    if (file != null) {
      emit(state.copyWith(avatar: IAvatar(File(file.path)), option: none()));
    }
  }

  _passwordChanged(_PasswordChanged e, Emitter<SignUpState> emit) async {
    emit(state.copyWith(password: IPassword(e.password), option: none()));
  }

  _signUpPressed(_SignUpPressed e, Emitter<SignUpState> emit) async {
    Either<AuthError, Unit> r;

    final isNameValid = state.fullName.isValid();
    final isEmailValid = state.email.isValid();
    final isPasswordValid = state.password.isValid();

    if (isNameValid && isEmailValid && isPasswordValid) {
      emit(state.copyWith(loading: true, option: none()));

      r = await _authFacade.signUp(
        fullName: state.fullName,
        email: state.email,
        password: state.password,
        avatar: state.avatar,
      );

      emit(state.copyWith(loading: false, option: some(r)));
    }

    emit(state.copyWith(loading: false, showError: true, option: none()));
  }
}

`

UploadImageWidget
`

class UploadImageWidget extends StatelessWidget {
  const UploadImageWidget({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final bloc = di<SignUpBloc>();
    return GestureDetector(
      onTap: () async {
        await showModalBottomSheet(
          context: context,
          backgroundColor: Colors.transparent,
          builder: (context) => const ImageSourceBottomSheet(),
        );
      },
      child: Column(
        children: [
          Container(
            decoration: const BoxDecoration(shape: BoxShape.circle),
            child: BlocListener<SignUpBloc, SignUpState>(
              bloc: bloc,
              listener: (context, state) => bloc.state.avatar,
              listenWhen: (p, c) => p.avatar != c.avatar,
              child: CircleAvatar(
                radius: SizeUtil.r(20),
                backgroundColor: Colors.transparent,
                foregroundImage: bloc.state.avatar?.getOrCrash() != null
                    ? FileImage(bloc.state.avatar!.getOrCrash()!)
                    : null,
                child: bloc.state.avatar?.getOrCrash() == null
                    ? const Icon(MIcons.camera)
                    : null,
              ),
            ),
          ),
          SizeUtil.vS(4),
          const Text('Upload Image'),
        ],
      ),
    );
  }
}

`

ImageSourceBottomSheet
`

class ImageSourceBottomSheet extends StatelessWidget {
  const ImageSourceBottomSheet({Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    final bloc = di<SignUpBloc>();
    return Wrap(
      alignment: WrapAlignment.end,
      children: [
        GestureDetector(
          onTap: () => Navigator.of(context).pop(),
          child: Container(
            height: SizeUtil.w(35),
            width: SizeUtil.w(35),
            margin: SizeUtil.pSymmetric(h: 25, v: 10),
            alignment: Alignment.center,
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: Theme.of(context).primaryColorLight,
            ),
            child: const Icon(Icons.close),
          ),
        ),
        Container(
          margin: SizeUtil.pFromLTRB(25, 0, 25, 25),
          padding: SizeUtil.pSymmetric(v: 13),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(SizeUtil.r(15)),
          ),
          child: Wrap(
            children: [
              _Button(
                title: 'Pick from Gallery',
                icon: MIcons.image,
                onPressed: () {
                  bloc.add(const SignUpEvent.avatarPicked(true));
                },
              ),
              const Divider(),
              _Button(
                title: 'Use Camera',
                icon: MIcons.camera,
                onPressed: () {
                  bloc.add(const SignUpEvent.avatarPicked(false));
                },
              ),
            ],
          ),
        ),
      ],
    );
  }
}

`

Please, what am I doing wrong and how can I fix it? Thank you.


问:
Typescript error want to map dto to entity but there is error -> not a function
Hi I want to make signUp logic with typescript + express + nodeJs + typeORM

If client send request , request.body will be dto.I want to make Dto map to Entity
But my compiler said function is not a function.

```<code> const newUser = createUserDto.createUser();
                                  ^
TypeError: createUserDto.createUser is not a function
</code>```

How can I fix it..to map dto to entity?

this is my code
[Controller]

```<code>import { Request, Response } from "express";
import { CreateUserDto } from "../service/dto/CreateUserDto";
import  userService from "../service/UserService";

export class UserController{

  async createUser(request: Request, response: Response) {
    const createUserRequest: CreateUserDto = request.body;
    userService.createUser(createUserRequest);
    response.status(201).json();
  }

}
</code>```

[Service]

```<code>import userRepository from "../repository/UserRepository";
import { CreateUserDto } from "../service/dto/CreateUserDto";

export class UserService{
    async createUser(createUserDto : CreateUserDto){
    const newUser = createUserDto.createUser();
    await userRepository.createUser(newUser);
    }

}

let userService = new UserService();
export default userService;
</code>```

[DTO]

```<code>
import { User } from "../../entity/User"

export class CreateUserDto{

    private userId: string;
    private password: string;
    private email: string;

    createUser() {
    return User.from(
        this.userId,
        this.password,
        this.email,
        );

}
}

</code>```

I am beginner at typescript so please help me

Body:
Hi I want to make signUp logic with typescript + express + nodeJs + typeORM

If client send request , request.body will be dto.I want to make Dto map to Entity
But my compiler said function is not a function.

 const newUser = createUserDto.createUser();
                                  ^
TypeError: createUserDto.createUser is not a function

How can I fix it..to map dto to entity?

this is my code
[Controller]

import { Request, Response } from "express";
import { CreateUserDto } from "../service/dto/CreateUserDto";
import  userService from "../service/UserService";

export class UserController{

  async createUser(request: Request, response: Response) {
    const createUserRequest: CreateUserDto = request.body;
    userService.createUser(createUserRequest);
    response.status(201).json();
  }

}

[Service]

import userRepository from "../repository/UserRepository";
import { CreateUserDto } from "../service/dto/CreateUserDto";

export class UserService{
    async createUser(createUserDto : CreateUserDto){
    const newUser = createUserDto.createUser();
    await userRepository.createUser(newUser);
    }

}

let userService = new UserService();
export default userService;

[DTO]

import { User } from "../../entity/User"

export class CreateUserDto{

    private userId: string;
    private password: string;
    private email: string;

    createUser() {
    return User.from(
        this.userId,
        this.password,
        this.email,
        );

}
}

I am beginner at typescript so please help me


问:
I want to combine audio and video then trim output video using node.js (ffmpeg or any libary)
I combined video and audio using "ffmpeg-static" And trim the video using "fluent-ffmpeg" successfully.

I did it by first combining the video and audio using "ffmpeg-static" and getting the output and then trim it using "fluent-ffmpeg".

But I want to combine video and audio and get the final output after trimming.

please help me...

```<code>const ffmpegStatic = require('ffmpeg-static');

var ffmpegPath = './ffmpeg.exe'
const fluentffmpeg = require('fluent-ffmpeg');
fluentffmpeg.setFfmpegPath(ffmpegPath);
</code>```

Body:
I combined video and audio using "ffmpeg-static" And trim the video using "fluent-ffmpeg" successfully.

I did it by first combining the video and audio using "ffmpeg-static" and getting the output and then trim it using "fluent-ffmpeg".

But I want to combine video and audio and get the final output after trimming.

please help me...

const ffmpegStatic = require('ffmpeg-static');

var ffmpegPath = './ffmpeg.exe'
const fluentffmpeg = require('fluent-ffmpeg');
fluentffmpeg.setFfmpegPath(ffmpegPath);


问:
Linker error while building OpenSAR software
Kindly help to build OpenSAR software in AWS Ubuntu VM.

I am trying to build OpenSAR software
git clone https://github.com/parai/OpenSAR.git

using the following make command
make BOARDDIR=stm32_stm3210c CROSS_COMPILE="arm-none-eabi-" BDIR=boards/stm32_stm3210c/examples/com_simple CFLAGS=-D__GNUC__ all

But getting the following errors:

LD com_simple_stm3210c.elf
arm-none-eabi-ld: Mcu.o: in function NVIC_SystemReset': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1334: undefined reference to __DSB'
arm-none-eabi-ld: Mcu.o: in function Mcu_Init': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/drivers/Mcu.c:355: undefined reference to __enable_irq'
arm-none-eabi-ld: Can.o: in function _Irq_Save': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq'
arm-none-eabi-ld: event.o: in function _Irq_Save': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq'
arm-none-eabi-ld: init.o: in function os_start': /home/ubuntu/OpenSAR/system/kernel/init.c:162: undefined reference to __disable_irq'
arm-none-eabi-ld: init.o: in function ShutdownOS': /home/ubuntu/OpenSAR/system/kernel/init.c:387: undefined reference to __disable_irq'
arm-none-eabi-ld: arch.o: in function Os_ArchFirstCall': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/arch.c:31: undefined reference to __enable_irq'
arm-none-eabi-ld: task.o: in function _Irq_Save': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq'
arm-none-eabi-ld: task.o: in function Os_TaskStartExtended': /home/ubuntu/OpenSAR/system/kernel/task.c:145: undefined reference to __disable_irq'
arm-none-eabi-ld: task.o: in function Os_TaskStartBasic': /home/ubuntu/OpenSAR/system/kernel/task.c:182: undefined reference to __disable_irq'
arm-none-eabi-ld: resource.o: in function _Irq_Save': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq'
arm-none-eabi-ld: alarm.o: in function _Irq_Save': /home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq'
arm-none-eabi-ld: sched_table.o:/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: more undefined references to __disable_irq' follow arm-none-eabi-ld: isr.o: in function Os_Isr_cm3':
/home/ubuntu/OpenSAR/system/kernel/isr.c:250: undefined reference to __enable_irq' arm-none-eabi-ld: /home/ubuntu/OpenSAR/system/kernel/isr.c:252: undefined reference to __disable_irq'
arm-none-eabi-ld: isr.o: in function Os_Isr': /home/ubuntu/OpenSAR/system/kernel/isr.c:379: undefined reference to __enable_irq'
arm-none-eabi-ld: /home/ubuntu/OpenSAR/system/kernel/isr.c:381: undefined reference to __disable_irq' arm-none-eabi-ld: Det.o: in function _Irq_Save':
/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq' arm-none-eabi-ld: Com_Com.o: in function _Irq_Save':
/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq' arm-none-eabi-ld: Com_Sched.o: in function _Irq_Save':
/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq' arm-none-eabi-ld: Com.o: in function _Irq_Save':
/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: undefined reference to __disable_irq' arm-none-eabi-ld: Com_misc.o:/home/ubuntu/OpenSAR/arch/arm/arm_cm3/kernel/core_cm3.h:1371: more undefined references to __disable_irq' follow
make[1]: *** [/home/ubuntu/OpenSAR/scripts/rules.mk:326: com_simple_stm3210c.elf] Error 1
make[1]: Leaving directory '/home/ubuntu/OpenSAR/boards/stm32_stm3210c/examples/com_simple/obj_stm32_stm3210c'
make: *** [makefile:190: boards/stm32_stm3210c/examples/com_simple] Error 2


问:
can not read utf-8 charter from stdin with MINGW64
I am doing a C language project with MINGW64 \ GCC 10.2.0 on windows.
when i read a UTF-8 or gbk string from stdin ( fgets(buf, QUERYBUF_LEN, stdin) ), it just read the top 1 byte of UTF-8 or gbk charter
i tried to add GCC paramters like

```<code>  "-finput-charset=utf-8",
  "-fexec-charset=utf-8",
  "-fwide-exec-charset=utf-8"
</code>```

but it does not work.
And my code works well on linux
How can i fix it

Body:
I am doing a C language project with MINGW64 \ GCC 10.2.0 on windows.
when i read a UTF-8 or gbk string from stdin ( fgets(buf, QUERYBUF_LEN, stdin) ), it just read the top 1 byte of UTF-8 or gbk charter
i tried to add GCC paramters like

  "-finput-charset=utf-8",
  "-fexec-charset=utf-8",
  "-fwide-exec-charset=utf-8"

but it does not work.
And my code works well on linux
How can i fix it


问:
Error with twinx: 'PlotAccessor' object has no attribute 'twinx'
I'm using a for loop with a list of variables to create multiple plots against one variable each plot has an item in the list iterated in the for loop against the variable "PUMP FAILURE (1 or 0)"

ATTEMPT

```<code>ListOfVariables = ['Volumetric Flow Meter 1',  'Volumetric Flow Meter 2',  'Pump Speed (RPM)', 'Pump Torque',   'Ambient Temperature',  'Horse Power',  'Pump Efficiency']

for item in ListOfVariables:
    first_axis = dataframe_raw[item].plot
    second_axis = first_axis.twinx()
    second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
    plt.title(item)
    plt.show()
</code>```

ERROR

```<code>      3 for item in ListOfVariables:
      4     first_axis = dataframe_raw[item].plot
----> 5     second_axis = first_axis.twinx()
      6     second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
      7     plt.title(item)

AttributeError: 'PlotAccessor' object has no attribute 'twinx'
</code>```

Body:
I'm using a for loop with a list of variables to create multiple plots against one variable each plot has an item in the list iterated in the for loop against the variable "PUMP FAILURE (1 or 0)"

ATTEMPT

ListOfVariables = ['Volumetric Flow Meter 1',  'Volumetric Flow Meter 2',  'Pump Speed (RPM)', 'Pump Torque',   'Ambient Temperature',  'Horse Power',  'Pump Efficiency']

for item in ListOfVariables:
    first_axis = dataframe_raw[item].plot
    second_axis = first_axis.twinx()
    second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
    plt.title(item)
    plt.show()

ERROR

      3 for item in ListOfVariables:
      4     first_axis = dataframe_raw[item].plot
----> 5     second_axis = first_axis.twinx()
      6     second_axis.plot(dataframe_raw['PUMP FAILURE (1or 0)'], color='teal')
      7     plt.title(item)

AttributeError: 'PlotAccessor' object has no attribute 'twinx'


问:
Flask Javascript delete-note button not wokring
Can anyone help me with this flask deleteNote button issue?  I'm just starting learning flask. Really appreciate.

I try to describe this problem clearly.  Everything works perfect until I add the deleteNote button. Now i can

notes, but cannot delete note one by one.

```<code>Here is my home.html.   I add a deleteNote button here with JavaScript.
</code>```

```<code><ul class="list-group list-group-flush" id="notes">
    <!-- do a for loop to loop all of the notes -->
    {% for note in user.notes %}
    <li class="list-group-item">
        {{ note.data }}
        <button type="but ton" class="close" onClick="deleteNote('{{ note.id }}')">
            <span aria-hidden="true">×</span>
        </button>
    </li>
    {% endfor %}
</ul>
</code>```

Here is my index.js file.  I wrote a deleteNote function.

```<code>function deleteNote(noteId) {
    fetch('/delete-note', {
        method: 'POST',
        body: JSON.stringify({ noteId: noteId })
    }).then((_res) => {
        window.location.href = "/";
    });
}
</code>```

Here is the views.py file, with homepage Blueprint. Copy the part associate with the deleteNote:

```<code>@views.route('/delete-note', methods=['POST'])
def delete_note():
    note = json.loads(request.data)
    noteId = note['noteId']
    note = Note.query.get(noteId)
    if note:
        if note.user_id == current_user.id:
            db.session.delete(note)
            db.session.commit()

    return jsonify({})
</code>```

How to fix this deleteNote button?

Body:
Can anyone help me with this flask deleteNote button issue?  I'm just starting learning flask. Really appreciate.

I try to describe this problem clearly.  Everything works perfect until I add the deleteNote button. Now i can

notes, but cannot delete note one by one.

Here is my home.html.   I add a deleteNote button here with JavaScript.

    {% for note in user.notes %}

        {{ note.data }}
        <button type="but ton" class="close" onClick="deleteNote('{{ note.id }}')">
            ×
        </button>

    {% endfor %}

Here is my index.js file.  I wrote a deleteNote function.

function deleteNote(noteId) {
    fetch('/delete-note', {
        method: 'POST',
        body: JSON.stringify({ noteId: noteId })
    }).then((_res) => {
        window.location.href = "/";
    });
}

Here is the views.py file, with homepage Blueprint. Copy the part associate with the deleteNote:

@views.route('/delete-note', methods=['POST'])
def delete_note():
    note = json.loads(request.data)
    noteId = note['noteId']
    note = Note.query.get(noteId)
    if note:
        if note.user_id == current_user.id:
            db.session.delete(note)
            db.session.commit()

    return jsonify({})

How to fix this deleteNote button?


问:
Constantly Calling JS File Crashes React App
I want to have a main title, centred in the screen, that plays a morphing transition that loops indefinitely. However, when loading my animation file (morph.js) the entire app crashes/goes white. Not sure if I am loading the file wrong or calling it wrong. The morph.js file is not a javascript element, but a file which calls its functions with animate() as the last executed line.

Title.js:

```<code>import React from "react";
import morph from "./morph";

function Title() {
    return (
        <section className="flex h-screen">
            <div className="mx-auto blurContainer">
                <span id="text1" className="text-green text-center text-9xl absolute">
                    title
                </span>
                <span id="text2" className="text-green text-center text-9xl absolute">
                    title
                </span>
            </div>
        </section>
    );
}
export default Title;
</code>```

morph.js

```<code>const elts = {

    text1: document.getElementById("text1"),
    text2: document.getElementById("text2"),
};
// The fonts to switch to
const fonts = [
    "Typewriter",
    "Sentient-Bold",
    "GeneralSans-Bold",
    "Quatro",
    "Gothic",
];

// Controls the speed of morphing.
const morphTime = 1;
const cooldownTime = 0.25;
let textIndex = fonts.length - 1;
let time = new Date();
let morph = 0;
let cooldown = cooldownTime;
elts.text1.style.fontFamily = fonts[textIndex % fonts.length];
elts.text2.style.fontFamily = fonts[(textIndex + 1) % fonts.length];
function doMorph() {
    morph -= cooldown;
    cooldown = 0;
    let fraction = morph / morphTime;
    if (fraction > 1) {
        cooldown = cooldownTime;
        fraction = 1;
    }
    setMorph(fraction);
}

function setMorph(fraction) {
    // fraction = Math.cos(fraction * Math.PI) / -2 + .5;
    elts.text2.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
    elts.text2.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;
    fraction = 1 - fraction;
    elts.text1.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
    elts.text1.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;
    elts.text1.style.fontFamily = fonts[textIndex % fonts.length];
    elts.text2.style.fontFamily = fonts[(textIndex + 1) % fonts.length];
}
function doCooldown() {
    morph = 0;
    elts.text2.style.filter = "";
    elts.text2.style.opacity = "100%";
    elts.text1.style.filter = "";
    elts.text1.style.opacity = "0%";
}

function animate() {
    requestAnimationFrame(animate);
    let newTime = new Date();
    let shouldIncrementIndex = cooldown > 0;
    let dt = (newTime - time) / 1000;
    time = newTime;
    cooldown -= dt;
    if (cooldown <= 0) {
        if (shouldIncrementIndex) {
            textIndex++;
        }
        doMorph();
    } else {
        doCooldown();
    }
}
// Start the animation.
animate();
</code>```

I know that the animation works, but upon a refresh, the entire body disappears. Do I need to use useEffect? How can I import the morph.js file and call it within the Title file?

Body:
I want to have a main title, centred in the screen, that plays a morphing transition that loops indefinitely. However, when loading my animation file (morph.js) the entire app crashes/goes white. Not sure if I am loading the file wrong or calling it wrong. The morph.js file is not a javascript element, but a file which calls its functions with animate() as the last executed line.

Title.js:

import React from "react";
import morph from "./morph";

function Title() {
    return (

                    title

                    title

    );
}
export default Title;

morph.js

const elts = {

    text1: document.getElementById("text1"),
    text2: document.getElementById("text2"),
};
// The fonts to switch to
const fonts = [
    "Typewriter",
    "Sentient-Bold",
    "GeneralSans-Bold",
    "Quatro",
    "Gothic",
];

// Controls the speed of morphing.
const morphTime = 1;
const cooldownTime = 0.25;
let textIndex = fonts.length - 1;
let time = new Date();
let morph = 0;
let cooldown = cooldownTime;
elts.text1.style.fontFamily = fonts[textIndex % fonts.length];
elts.text2.style.fontFamily = fonts[(textIndex + 1) % fonts.length];
function doMorph() {
    morph -= cooldown;
    cooldown = 0;
    let fraction = morph / morphTime;
    if (fraction > 1) {
        cooldown = cooldownTime;
        fraction = 1;
    }
    setMorph(fraction);
}

function setMorph(fraction) {
    // fraction = Math.cos(fraction * Math.PI) / -2 + .5;
    elts.text2.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
    elts.text2.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;
    fraction = 1 - fraction;
    elts.text1.style.filter = `blur(${Math.min(8 / fraction - 8, 100)}px)`;
    elts.text1.style.opacity = `${Math.pow(fraction, 0.4) * 100}%`;
    elts.text1.style.fontFamily = fonts[textIndex % fonts.length];
    elts.text2.style.fontFamily = fonts[(textIndex + 1) % fonts.length];
}
function doCooldown() {
    morph = 0;
    elts.text2.style.filter = "";
    elts.text2.style.opacity = "100%";
    elts.text1.style.filter = "";
    elts.text1.style.opacity = "0%";
}

function animate() {
    requestAnimationFrame(animate);
    let newTime = new Date();
    let shouldIncrementIndex = cooldown > 0;
    let dt = (newTime - time) / 1000;
    time = newTime;
    cooldown -= dt;
    if (cooldown <= 0) {
        if (shouldIncrementIndex) {
            textIndex++;
        }
        doMorph();
    } else {
        doCooldown();
    }
}
// Start the animation.
animate();

I know that the animation works, but upon a refresh, the entire body disappears. Do I need to use useEffect? How can I import the morph.js file and call it within the Title file?


问:
Problem plotting a raster (GeoTIFF) on top of a basemap (Google Maps / Mapbox) with Python
I've been stuck for a few days trying to plot a TIF file over a basemap (Google Maps or Mapbox) using Python. I don't know if this is actually possible because I didn't find examples and nothing very clear about it, the most I found is how to plot vector files (shp) on top of basemaps, but nothing about raster.

I have a raster (rainfall_clipped.tif) that is in EPSG:4326 and I'm trying to plot it on top of a MapBox map using the Contextily package. At first I suspected that it could be a projection problem, but even doing the conversions to EPSG:3857, it didn't work. In the documentation Contextily says that it accepts both projections.

Contextily seems to understand the projections, even because it generates the map with the correct axes, the big problem is that it doesn't plot the TIF file on the map. And it's also reading the raster because it loaded the colorbar with the correct values. I don't know if the layer order is wrong or what else it could be.

Below is the code I am using and then the image that is being generated:

```<code>data = rasterio.open("rainfall_clipped.tif")

# Read the bounds
left, bottom, right, top = data.bounds

# Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 10))

# Add the raster data to the plot using imshow
im = ax.imshow(data.read(1), extent=[left, right, bottom, top], cmap="Blues")

# Add a colorbar
fig.colorbar(im, ax=ax)

# Add a basemap using contextily
ctx.add_basemap(ax, crs=data.crs, source=ctx.providers.MapBox(accessToken="my_key", id="mapbox/satellite-v9"))

# Show the plot
plt.show()

</code>```

This code is generating this image:
Output image

What I'm trying to do is something like below:
Expected image

Any suggestions what I can do?

Body:
I've been stuck for a few days trying to plot a TIF file over a basemap (Google Maps or Mapbox) using Python. I don't know if this is actually possible because I didn't find examples and nothing very clear about it, the most I found is how to plot vector files (shp) on top of basemaps, but nothing about raster.

I have a raster (rainfall_clipped.tif) that is in EPSG:4326 and I'm trying to plot it on top of a MapBox map using the Contextily package. At first I suspected that it could be a projection problem, but even doing the conversions to EPSG:3857, it didn't work. In the documentation Contextily says that it accepts both projections.

Contextily seems to understand the projections, even because it generates the map with the correct axes, the big problem is that it doesn't plot the TIF file on the map. And it's also reading the raster because it loaded the colorbar with the correct values. I don't know if the layer order is wrong or what else it could be.

Below is the code I am using and then the image that is being generated:

data = rasterio.open("rainfall_clipped.tif")

# Read the bounds
left, bottom, right, top = data.bounds

# Create a figure and axes
fig, ax = plt.subplots(figsize=(10, 10))

# Add the raster data to the plot using imshow
im = ax.imshow(data.read(1), extent=[left, right, bottom, top], cmap="Blues")

# Add a colorbar
fig.colorbar(im, ax=ax)

# Add a basemap using contextily
ctx.add_basemap(ax, crs=data.crs, source=ctx.providers.MapBox(accessToken="my_key", id="mapbox/satellite-v9"))

# Show the plot
plt.show()

This code is generating this image:
Output image

What I'm trying to do is something like below:
Expected image

Any suggestions what I can do?


问:
Swap/Re-map multiple colors in texture created from image in WebGL shader
I'm pretty new to WebGL and have a page i'm making that does the following:

Loads a .GIF image into a texture

Displays this image on a canvas along with a table that lists the colors in the image with an <input type="color"> for each

Replaces the selected color in the texture when you pick a color through one of the <input>'s

I have this working for a single color change but i can't figure out how to expand it to change multiple colors (the goal being to change as many colors in the image as you want).

My first thought was based on this idea and create a 2px-wide palette texture of the old colors and new colors, then in the shader look up the current pixel's color in it then get the neighbouring color for the substitution.

However i couldn't figure out how to find a color's coordinates from a value, so i started with a simpler approach of passing the old and new colors to the shader, checking for a match and swapping.

This is the shader code that works for 1x color:

```<code><script  id="fragment-shader-2d" type="x-shader/x-fragment">
    precision mediump float;

    //GIF Image Texture
    uniform sampler2D u_image0;

    //texCoords passed in from the vertex shader.
    varying vec2 v_texCoord;

    //Color to look for, e.g. [255,0,0] for red
    uniform float old_color[3];

    //Color to replace it with e.g. [0,255,0] for green
    uniform float new_color[3];

    void main()
    {
        vec4 current_gif_color = texture2D(u_image0, v_texCoord);

        float current_gif_red = current_gif_color[0];
        float current_gif_green = current_gif_color[1];
        float current_gif_blue = current_gif_color[2];

        float red_difference = abs((current_gif_red - old_color[0]/255.0)*100.0);
        float green_difference = abs((current_gif_green - old_color[1]/255.0)*100.0);
        float blue_difference = abs((current_gif_blue - old_color[2]/255.0)*100.0);

        //To avoid differences from rounding check if the match is within a small margin
        if((red_difference < 0.1) && (green_difference < 0.1) && (blue_difference < 0.1))
        {
            //Use the replacement color for this pixel
            current_gif_red = new_color[0]/255.0;
            current_gif_green = new_color[1]/255.0;
            current_gif_blue = new_color[2]/255.0;
        }

        vec4 output_color = vec4( current_gif_red,  current_gif_green,  current_gif_blue, 1.0);
        gl_FragColor = output_color;
    }
</script>
</code>```

The code on the Javascript side is taken from this page on WebGL fundamentals but the relevant piece to this question executes from the color pick on the <input> and redraws the canvas as follows.

The <input>s are like this:

```<code><input class="new_color_picker_input" type = "color" data-r="255" data-g="0" data-b="0"/>
</code>```

And the JS:

```<code>$('.new_color_picker_input').on('change', function(){

    var existing_r = $(this).data('r');
    var existing_g = $(this).data('g');
    var existing_b = $(this).data('b');

    var new_color_hex = $(this).val();
    var new_color_rgb = new_color_hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(m, r, g, b) => '#' + r + r + g + g + b + b).substring(1).match(/.{2}/g).map(x => parseInt(x, 16));

   var old_color = new Float32Array( [ existing_r, existing_g, existing_b ] );
   var new_color = new Float32Array( [ new_color_rgb[0], new_color_rgb[1], new_color_rgb[2] ] );

    //Set the Uniforms in the Shader to the old RGB and the new RGB
    var shader_var_old_color = gl.getUniformLocation(program, "old_color");
    gl.uniform1fv(shader_var_old_color, old_color);

    var shader_var_new_color = gl.getUniformLocation(program, "new_color");
    gl.uniform1fv(shader_var_new_color, new_color);

    //Trigger the redraw
    gl.drawArrays(gl.TRIANGLES, 0, 6);

});
</code>```

How could i achieve this for multiple color changes or use a palette approach?

Body:
I'm pretty new to WebGL and have a page i'm making that does the following:

Loads a .GIF image into a texture

Displays this image on a canvas along with a table that lists the colors in the image with an <input type="color"> for each

Replaces the selected color in the texture when you pick a color through one of the <input>'s

I have this working for a single color change but i can't figure out how to expand it to change multiple colors (the goal being to change as many colors in the image as you want).

My first thought was based on this idea and create a 2px-wide palette texture of the old colors and new colors, then in the shader look up the current pixel's color in it then get the neighbouring color for the substitution.

However i couldn't figure out how to find a color's coordinates from a value, so i started with a simpler approach of passing the old and new colors to the shader, checking for a match and swapping.

This is the shader code that works for 1x color:

The code on the Javascript side is taken from this page on WebGL fundamentals but the relevant piece to this question executes from the color pick on the <input> and redraws the canvas as follows.

The <input>s are like this:

<input class="new_color_picker_input" type = "color" data-r="255" data-g="0" data-b="0"/>

And the JS:

$('.new_color_picker_input').on('change', function(){

    var existing_r = $(this).data('r');
    var existing_g = $(this).data('g');
    var existing_b = $(this).data('b');

    var new_color_hex = $(this).val();
    var new_color_rgb = new_color_hex.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,(m, r, g, b) => '#' + r + r + g + g + b + b).substring(1).match(/.{2}/g).map(x => parseInt(x, 16));

   var old_color = new Float32Array( [ existing_r, existing_g, existing_b ] );
   var new_color = new Float32Array( [ new_color_rgb[0], new_color_rgb[1], new_color_rgb[2] ] );

    //Set the Uniforms in the Shader to the old RGB and the new RGB
    var shader_var_old_color = gl.getUniformLocation(program, "old_color");
    gl.uniform1fv(shader_var_old_color, old_color);

    var shader_var_new_color = gl.getUniformLocation(program, "new_color");
    gl.uniform1fv(shader_var_new_color, new_color);

    //Trigger the redraw
    gl.drawArrays(gl.TRIANGLES, 0, 6);

});

How could i achieve this for multiple color changes or use a palette approach?


问:
How to automate reactions on instagram stories with python?
These days I was using selenium to make automations on instagram with python and I noticed that the stories reaction button does not appear as an element in the instagram HTML for me to get the xpath, and when I clicked on the comment tab, the reactions appeared quick but when I went to inspect it disappeared in the document. These days I was using selenium to make automations on instagram with python and I noticed that the stories reaction button does not appear as an element in the instagram HTML for me to get the xpath, and when I clicked on the comment. I would like to know how I could do this automation with python and selenium. If not using these resources, I would also like recommendations on how I could proceed. tab, the reactions appeared quick but when I went to inspect it disappeared in the document.

I tried to use the inspect tab on the quick react element to use selenium, as well as I tried to inspect the button inside the stories field and I couldn't get the element.


问:
Error CS0234 The type or namespace name 'Budget_Done2_Msg' does not exist in the namespace 'FirstCWeb' (are you missing an assemb
When I create a new form in C# I get the following error:

I am getting error Error    CS0234  The type or namespace name 'Budget_Done2_Msg' does not exist in the namespace 'FirstCWeb' (are you missing an assembly reference?)  76_Budget_Done2_Msg.aspx    C:\Users\edben\OneDrive\Desktop\Projects\MyFirstCWeb_Solution\FirstCWeb\Budget_Done2_Msg.aspx   1   Active
What must I do to create new form without getting this error?

I get this after I create a new form in C# using VS 2022.


问:
How do I customize a Gravity Forms upload file error message such as "There was an problem while verifying your file."
My goal is to customize the error message that may occur immediately after attempting to upload a file to a Gravity Forms "File Upload" filed. In particular I would like to modify the error message that occurs when you upload a file with the wrong file extension such as uploading a PNG file with a file name that ends with '.jpg' instead of '.png'.

The following represents what I'm trying to do, but it obviously doesn't work since the AJAX error message is displayed right after the file upload has completed and before Gravity Form has even been submitted or validated.

```<code>/////////////////////////////
// CUSTOM GRAVITY FORM FILTERS
//

add_filter( 'gform_field_validation',
  /**
   * Fixes Gravity Forms Custom validation message.
   *
   * @link https://docs.gravityforms.com/gform_field_validation/
   *
   * @param array  $result  The result array.
   * @param string $value   The value of the field.
   * @param array  $form    The Gravity Form array.
   * @param object $field   The form field object.
   *
   * @return array  The result array.
   */
  function( $result, $value, $form, $field ) {
    GFCommon::log_debug( __METHOD__ . '(): Running custom gform_field_validation...' );

    if ( $field->type == 'file') {
      if (!$result['is_valid'] && str_contains($result['message'], 'There was an problem while verifying your file.')) {
        $result['message'] = str_replace(
          'was an problem',
          'was a problem',
          $result['message'] // e.g., "Photo.jpg - There was an problem while verifying your file."
        )
        . ' Please make sure that your file extension (e.g., \'.jpg\')  is correct. '
        .'For example a PNG file should be saved with a \'.png\' extension and not with a \'.jpg\' file extension.';
      }
    }
    return $result;
  }
  , 10, 4
);
</code>```

Body:
My goal is to customize the error message that may occur immediately after attempting to upload a file to a Gravity Forms "File Upload" filed. In particular I would like to modify the error message that occurs when you upload a file with the wrong file extension such as uploading a PNG file with a file name that ends with '.jpg' instead of '.png'.

The following represents what I'm trying to do, but it obviously doesn't work since the AJAX error message is displayed right after the file upload has completed and before Gravity Form has even been submitted or validated.

/////////////////////////////
// CUSTOM GRAVITY FORM FILTERS
//

add_filter( 'gform_field_validation',
  /**
   * Fixes Gravity Forms Custom validation message.
   *
   * @link https://docs.gravityforms.com/gform_field_validation/
   *
   * @param array  $result  The result array.
   * @param string $value   The value of the field.
   * @param array  $form    The Gravity Form array.
   * @param object $field   The form field object.
   *
   * @return array  The result array.
   */
  function( $result, $value, $form, $field ) {
    GFCommon::log_debug( __METHOD__ . '(): Running custom gform_field_validation...' );

    if ( $field->type == 'file') {
      if (!$result['is_valid'] && str_contains($result['message'], 'There was an problem while verifying your file.')) {
        $result['message'] = str_replace(
          'was an problem',
          'was a problem',
          $result['message'] // e.g., "Photo.jpg - There was an problem while verifying your file."
        )
        . ' Please make sure that your file extension (e.g., \'.jpg\')  is correct. '
        .'For example a PNG file should be saved with a \'.png\' extension and not with a \'.jpg\' file extension.';
      }
    }
    return $result;
  }
  , 10, 4
);


问:
R gives this error: "Error in hmax - lmin : non-numeric argument to binary operator" but doesn't after RStudio is restarted
While calculating SMI() function from TTR Package in R using RStudio, often this error is given: "Error in hmax - lmin : non-numeric argument to binary operator". But after simply closing RStudio - and saving all the workspace - and starting it again, when this function is run, No error is given.

Sample Data:-

```<code>> head(a)
# A tibble: 6 × 7
  Date       Time   Open  High   Low Close Volume
  <chr>      <chr> <dbl> <dbl> <dbl> <dbl>  <dbl>
1 2012.06.19 14     1.26  1.26  1.26  1.26   4518
2 2012.06.19 15     1.26  1.26  1.26  1.26   5668
3 2012.06.19 16     1.26  1.27  1.26  1.27   5696
4 2012.06.19 17     1.27  1.27  1.27  1.27   5742
5 2012.06.19 18     1.27  1.27  1.27  1.27   3477
6 2012.06.19 19     1.27  1.27  1.27  1.27   4751
</code>```

The line of code that gives this error (often):-

```<code>c = as.data.frame(SMI(a[, c("High", "Low", "Close")]))
</code>```

Error:-

```<code>Error in hmax - lmin : non-numeric argument to binary operator
</code>```

Body:
While calculating SMI() function from TTR Package in R using RStudio, often this error is given: "Error in hmax - lmin : non-numeric argument to binary operator". But after simply closing RStudio - and saving all the workspace - and starting it again, when this function is run, No error is given.

Sample Data:-

> head(a)
# A tibble: 6 × 7
  Date       Time   Open  High   Low Close Volume
  <chr>      <chr> <dbl> <dbl> <dbl> <dbl>  <dbl>
1 2012.06.19 14     1.26  1.26  1.26  1.26   4518
2 2012.06.19 15     1.26  1.26  1.26  1.26   5668
3 2012.06.19 16     1.26  1.27  1.26  1.27   5696
4 2012.06.19 17     1.27  1.27  1.27  1.27   5742
5 2012.06.19 18     1.27  1.27  1.27  1.27   3477
6 2012.06.19 19     1.27  1.27  1.27  1.27   4751

The line of code that gives this error (often):-

c = as.data.frame(SMI(a[, c("High", "Low", "Close")]))

Error:-

Error in hmax - lmin : non-numeric argument to binary operator


问:
How can I customize palette for dark mode in MUI?
I am learning Theming in material UI. Since, I need to customize palette to get the dark mode, I am actually not sure in which way I have to customize that will trigger affect on system's background, buttons, text and stuff. I expect, your suggestion will guide me towards right direction.

My theme.palette.js

```<code>import {
  amber, grey, green, indigo, red, common, blue,
} from '@mui/material/colors';

const colors = {
  white: common.white,
  background: grey[50],
  primary: indigo[900],
  tertiary: blue[500],
  secondary: green[500],
  positive: green[500],
  medium: amber[700],
  negative: red[500],
  neutral: grey[500],
  geometry: '#3bb2d0',
  dark: grey[800],
};

export default {
  background: {
    default: colors.background,
  },
  primary: {
    main: colors.primary,
  },
  secondary: {
    main: colors.secondary,
    contrastText: colors.white,
  },
  tertiary: {
    main: colors.tertiary,
  },
  colors,
};
</code>```

Another thing is, How can I add switch to settings page and change state for the whole system. Or exactly where should I place the <Switch /> component?

My index.js

```<code>import 'typeface-roboto';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import {
  CssBaseline,
  ThemeProvider,
  StyledEngineProvider,
} from '@mui/material';
import store from './store';
import { LocalizationProvider } from './common/components/LocalizationProvider';
import ErrorHandler from './common/components/ErrorHandler';
import theme from './common/theme';
import Navigation from './Navigation';
import preloadImages from './map/core/preloadImages';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import NativeInterface from './common/components/NativeInterface';
import ServerProvider from './ServerProvider';

preloadImages();

const root = createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <LocalizationProvider>
      <StyledEngineProvider injectFirst>
        <ThemeProvider theme={theme}>
          <CssBaseline />
          <ServerProvider>
            <BrowserRouter>
              <Navigation />
            </BrowserRouter>
          </ServerProvider>
          <ErrorHandler />
          <NativeInterface />
        </ThemeProvider>
      </StyledEngineProvider>
    </LocalizationProvider>
  </Provider>,
);

serviceWorkerRegistration.register();
</code>```

Body:
I am learning Theming in material UI. Since, I need to customize palette to get the dark mode, I am actually not sure in which way I have to customize that will trigger affect on system's background, buttons, text and stuff. I expect, your suggestion will guide me towards right direction.

My theme.palette.js

import {
  amber, grey, green, indigo, red, common, blue,
} from '@mui/material/colors';

const colors = {
  white: common.white,
  background: grey[50],
  primary: indigo[900],
  tertiary: blue[500],
  secondary: green[500],
  positive: green[500],
  medium: amber[700],
  negative: red[500],
  neutral: grey[500],
  geometry: '#3bb2d0',
  dark: grey[800],
};

export default {
  background: {
    default: colors.background,
  },
  primary: {
    main: colors.primary,
  },
  secondary: {
    main: colors.secondary,
    contrastText: colors.white,
  },
  tertiary: {
    main: colors.tertiary,
  },
  colors,
};

Another thing is, How can I add switch to settings page and change state for the whole system. Or exactly where should I place the <Switch /> component?

My index.js

import 'typeface-roboto';
import React from 'react';
import { createRoot } from 'react-dom/client';
import { BrowserRouter } from 'react-router-dom';
import { Provider } from 'react-redux';
import {
  CssBaseline,
  ThemeProvider,
  StyledEngineProvider,
} from '@mui/material';
import store from './store';
import { LocalizationProvider } from './common/components/LocalizationProvider';
import ErrorHandler from './common/components/ErrorHandler';
import theme from './common/theme';
import Navigation from './Navigation';
import preloadImages from './map/core/preloadImages';
import * as serviceWorkerRegistration from './serviceWorkerRegistration';
import NativeInterface from './common/components/NativeInterface';
import ServerProvider from './ServerProvider';

preloadImages();

const root = createRoot(document.getElementById('root'));
root.render(
  <Provider store={store}>
    <LocalizationProvider>

    </LocalizationProvider>
  </Provider>,
);

serviceWorkerRegistration.register();


问:
VBA Common Control On Others PC
I need information.
I am work on Microsoft Excel 365 (2016 32 Bit) and I have registered and installed mscomctl.ocx sp6 to get some additional control on my VBA project such as Date Picker, Listview Control, etc.
So far all works just fine on my PC.

My question, if my excel VBA project run on others computer that mscomctl.ocx sp6 not installed and registered, should my excel VBA project work fine too?.
If not, then I will considering to use any common control own by mscomctl.ocx sp6 and use only the excel 365 controls default. Or any others way to make it works fine on others computer as mentioned?.

Thank you.

Title: VBA Common Control On Others PC


问:
Resolving Entity Framework DbContext from child scope
In short why the second method is faster and more memory efficient than the first one?

```<code>public class HomeController : Controller
{
    private const int SamuraiCount = 10000;

    private readonly SamuraiContext _samuraiContext;
    private readonly IServiceProvider _serviceProvider;

    public HomeController(SamuraiContext samuraiContext, IServiceProvider serviceProvider)
    {
        _samuraiContext = samuraiContext;
        _serviceProvider = serviceProvider;
    }

    [HttpPost("Create")]
    public async Task<IActionResult> Create()
    {
        for (int i = 0; i < SamuraiCount; i++)
        {
            var samurai = new Samurai() { Name = "Ank" };
            _samuraiContext.Samurais.Add(samurai);
            await _samuraiContext.SaveChangesAsync();
        }

        return Ok();
    }

    [HttpPost("Create1")]
    public async Task<IActionResult> Create1()
    {
        for (int i = 0; i < SamuraiCount; i++)
        {
            using var childScope = _serviceProvider.CreateScope();
            var samuraiContext = childScope.ServiceProvider.GetRequiredService<SamuraiContext>();
            var samurai = new Samurai() { Name = "Ank" };
            samuraiContext.Samurais.Add(samurai);
            await samuraiContext.SaveChangesAsync();
        }

        return Ok();
    }

}
</code>```

So, the first method takes ~4min, allocates ~600mb (10 000 Samurai objects)

And the second one takes ~40sec and allocates ~360mb (and only 1 Samurai object has been allocated on the heap. Why?)

I simply don't get it. I expected the second one to allocate more memory (basically on each iteration I am asking for a new DbContext instance) and to take the same amount of time ~4 min. I checked the MSSQL server and in both methods, only 1 connection is used. I thought it could be related to Change Tracker, so I decided to disable it for the first method but at the end result was the same.

So, What am I missing? Why resolving DbCOntext from child scope looks more efficient?

Cheers!

Body:
In short why the second method is faster and more memory efficient than the first one?

public class HomeController : Controller
{
    private const int SamuraiCount = 10000;

    private readonly SamuraiContext _samuraiContext;
    private readonly IServiceProvider _serviceProvider;

    public HomeController(SamuraiContext samuraiContext, IServiceProvider serviceProvider)
    {
        _samuraiContext = samuraiContext;
        _serviceProvider = serviceProvider;
    }

    [HttpPost("Create")]
    public async Task<IActionResult> Create()
    {
        for (int i = 0; i < SamuraiCount; i++)
        {
            var samurai = new Samurai() { Name = "Ank" };
            _samuraiContext.Samurais.Add(samurai);
            await _samuraiContext.SaveChangesAsync();
        }

        return Ok();
    }

    [HttpPost("Create1")]
    public async Task<IActionResult> Create1()
    {
        for (int i = 0; i < SamuraiCount; i++)
        {
            using var childScope = _serviceProvider.CreateScope();
            var samuraiContext = childScope.ServiceProvider.GetRequiredService<SamuraiContext>();
            var samurai = new Samurai() { Name = "Ank" };
            samuraiContext.Samurais.Add(samurai);
            await samuraiContext.SaveChangesAsync();
        }

        return Ok();
    }

}

So, the first method takes ~4min, allocates ~600mb (10 000 Samurai objects)

And the second one takes ~40sec and allocates ~360mb (and only 1 Samurai object has been allocated on the heap. Why?)

I simply don't get it. I expected the second one to allocate more memory (basically on each iteration I am asking for a new DbContext instance) and to take the same amount of time ~4 min. I checked the MSSQL server and in both methods, only 1 connection is used. I thought it could be related to Change Tracker, so I decided to disable it for the first method but at the end result was the same.

So, What am I missing? Why resolving DbCOntext from child scope looks more efficient?

Cheers!


问:
Is it possible to use PowerShell to automate interactions with installed programs in windows 10?
Is it possible, from a PowerShell script, to for example automate text box population, automate striking of the enter key inside of an installed program in Windows 10?  Could anyone point me in the direction of relevant documentation?

Would a different alternative to PowerShell be more appropriate?

Thanks!

I know how to execute the program from PowerShell (PS C:> 'filepath\program.exe'). I also know how to kill the program from PowerShell (PS C:> stop-process -Name "program_name").

In trying to figure out how events are identified, I tried:

```<code>PS C:> $Events = Get-Event
PS C:> $Events[0] | Format-List -Property *
</code>```

But it returns an error message: "Cannot index into a null array"

Body:
Is it possible, from a PowerShell script, to for example automate text box population, automate striking of the enter key inside of an installed program in Windows 10?  Could anyone point me in the direction of relevant documentation?

Would a different alternative to PowerShell be more appropriate?

Thanks!

I know how to execute the program from PowerShell (PS C:> 'filepath\program.exe'). I also know how to kill the program from PowerShell (PS C:> stop-process -Name "program_name").

In trying to figure out how events are identified, I tried:

PS C:> $Events = Get-Event
PS C:> $Events[0] | Format-List -Property *

But it returns an error message: "Cannot index into a null array"


问:
Am I including npm modules in my chrome extension correctly?
I'm working on a chrome extension that grabs data from Rate My Professor's GraphQL API using the @mtucourses/rate-my-professors module, and then putting that rating on my universities courses portal. When I attempt to use the module in VS Code:

```<code>const ratings = require('@mtucourses/rate-my-professors').default;

(async () => {

    const profName = 'Hossein Kassiri';
    const basicProfInfo = await ratings.searchTeacher(profName, 'U2Nob29sLTE0OTU=');

    const id = basicProfInfo[0].id;
    console.log(basicProfInfo);
    //console.log(id);

    // get the profs avg rating
    const profInfo = await ratings.getTeacher(id);
    const avgRating = profInfo.avgRating;

    //console.log(profInfo);
    console.log(avgRating);
    console.log("https://www.ratemyprofessors.com/professor?tid=" + profInfo.legacyId);

})();

</code>```

It works as expected (returns professor info/rating).

However, if I try to mimic the same functionality in a chrome extension, it does not work (basicProfInfo is an empty object). I am using browserify to pack background.js, as it imports the @mtucourses/rate-my-professors module.

My content.js:

```<code>const professorLinks = document.querySelectorAll('td[width="15%"] a');

professorLinks.forEach(link => {
  const professorName = link.textContent;
  console.log(professorName);

  chrome.runtime.sendMessage({ professorName }, (response) => {

    console.log(response);

    if (response.error) {
      link.insertAdjacentHTML('afterend', `<div>Error: ${response.error}</div>`);
    } else {
      link.insertAdjacentHTML('afterend', `<div>${response}/5</div>`);
    }

  });
});

</code>```

and my background.js:

```<code>const ratings = require('@mtucourses/rate-my-professors').default;
console.log("background.js loaded");

async function getAvgRating(profName) {

  const basicProfInfo = await ratings.searchTeacher(profName, 'U2Nob29sLTE0OTU=');

  console.log(basicProfInfo);
  if (!basicProfInfo || basicProfInfo.length === 0) {
    return { error: 'Professor not found' };
  }

  const id = basicProfInfo[0].id;
  const profInfo = await ratings.getTeacher(id);
  const avgRating = profInfo.avgRating;
  console.log(avgRating);

  return avgRating;
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('received message from content script:', request);
  console.log(request.professorName);

  getAvgRating(request.professorName).then(response => {
    sendResponse(response);
  });
  return true;
});

</code>```

I tried using other tools to pack my extension instead of browserify (like extension CLI), but basicProfInfo still returns an empty object.

The expected output for basicProfInfo is:
test.js, in Visual Studio Code

but the actual output (in Google Chrome) is an empty object:
content.js/background.js, in google chrome

Body:
I'm working on a chrome extension that grabs data from Rate My Professor's GraphQL API using the @mtucourses/rate-my-professors module, and then putting that rating on my universities courses portal. When I attempt to use the module in VS Code:

const ratings = require('@mtucourses/rate-my-professors').default;

(async () => {

    const profName = 'Hossein Kassiri';
    const basicProfInfo = await ratings.searchTeacher(profName, 'U2Nob29sLTE0OTU=');

    const id = basicProfInfo[0].id;
    console.log(basicProfInfo);
    //console.log(id);

    // get the profs avg rating
    const profInfo = await ratings.getTeacher(id);
    const avgRating = profInfo.avgRating;

    //console.log(profInfo);
    console.log(avgRating);
    console.log("https://www.ratemyprofessors.com/professor?tid=" + profInfo.legacyId);

})();

It works as expected (returns professor info/rating).

However, if I try to mimic the same functionality in a chrome extension, it does not work (basicProfInfo is an empty object). I am using browserify to pack background.js, as it imports the @mtucourses/rate-my-professors module.

My content.js:

const professorLinks = document.querySelectorAll('td[width="15%"] a');

professorLinks.forEach(link => {
  const professorName = link.textContent;
  console.log(professorName);

  chrome.runtime.sendMessage({ professorName }, (response) => {

    console.log(response);

    if (response.error) {
      link.insertAdjacentHTML('afterend', `<div>Error: ${response.error}</div>`);
    } else {
      link.insertAdjacentHTML('afterend', `<div>${response}/5</div>`);
    }

  });
});

and my background.js:

const ratings = require('@mtucourses/rate-my-professors').default;
console.log("background.js loaded");

async function getAvgRating(profName) {

  const basicProfInfo = await ratings.searchTeacher(profName, 'U2Nob29sLTE0OTU=');

  console.log(basicProfInfo);
  if (!basicProfInfo || basicProfInfo.length === 0) {
    return { error: 'Professor not found' };
  }

  const id = basicProfInfo[0].id;
  const profInfo = await ratings.getTeacher(id);
  const avgRating = profInfo.avgRating;
  console.log(avgRating);

  return avgRating;
}

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('received message from content script:', request);
  console.log(request.professorName);

  getAvgRating(request.professorName).then(response => {
    sendResponse(response);
  });
  return true;
});

I tried using other tools to pack my extension instead of browserify (like extension CLI), but basicProfInfo still returns an empty object.

The expected output for basicProfInfo is:
test.js, in Visual Studio Code

but the actual output (in Google Chrome) is an empty object:
content.js/background.js, in google chrome


问:
Plotting line graph from pandas DataFrame - does not work if I do not include .mean(), .sum() or even .median(). Very confused
I have a DataFrame that has list of date, city, country, and average temperature in Celcius.
Here is the .info() of this DataFrame:

```<code><class 'pandas.core.frame.DataFrame'>
RangeIndex: 16500 entries, 0 to 16499
Data columns (total 4 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   date        16500 non-null  object
 1   city        16500 non-null  object
 2   country     16500 non-null  object
 3   avg_temp_c  16407 non-null  float64
dtypes: float64(1), object(3)
</code>```

I only want to plot the avg_temp_c for the cities of Toronto and Rome, both lines on one graph. This was actually a practice problem that has the solution, so here is the code for that:

```<code>toronto = temperatures[temperatures["city"] == "Toronto"]
rome = temperatures[temperatures["city"] == "Rome"]
toronto.groupby("date")["avg_temp_c"].mean().plot(kind="line", color="blue")
rome.groupby("date")["avg_temp_c"].mean().plot(kind="line", color="green")
</code>```

My question is: why do I need to include .mean() in lines 3 and 4? I thought the numbers were already in avg_temp_c. Also, I experimented by replacing .mean() with .sum() and .median(), and it gives the same values. However, removing .mean() altogether for both lines just gives a blank plot. I tried to figure why, but I am very confused and I want to understand. Why doesn't it work without .mean() when the values are already listed in avg_temp_c?

I tried removing .mean(). I tried replacing .mean() with .median() and .sum(), which give the exact same values for some reason. I tried just printing toronto["avg_temp_c"] and rome["avg_temp_c"], which gives me the values, but when I plot it without .mean(), .sum(), or .median(), it does not work. I am just trying to figure why this is the case, and how does all three of those methods give me the same values as if I were just to print the avg_temp_c list?

Hope my question was clear. Thank you!

Body:
I have a DataFrame that has list of date, city, country, and average temperature in Celcius.
Here is the .info() of this DataFrame:

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 16500 entries, 0 to 16499
Data columns (total 4 columns):
 #   Column      Non-Null Count  Dtype
---  ------      --------------  -----
 0   date        16500 non-null  object
 1   city        16500 non-null  object
 2   country     16500 non-null  object
 3   avg_temp_c  16407 non-null  float64
dtypes: float64(1), object(3)

I only want to plot the avg_temp_c for the cities of Toronto and Rome, both lines on one graph. This was actually a practice problem that has the solution, so here is the code for that:

toronto = temperatures[temperatures["city"] == "Toronto"]
rome = temperatures[temperatures["city"] == "Rome"]
toronto.groupby("date")["avg_temp_c"].mean().plot(kind="line", color="blue")
rome.groupby("date")["avg_temp_c"].mean().plot(kind="line", color="green")

My question is: why do I need to include .mean() in lines 3 and 4? I thought the numbers were already in avg_temp_c. Also, I experimented by replacing .mean() with .sum() and .median(), and it gives the same values. However, removing .mean() altogether for both lines just gives a blank plot. I tried to figure why, but I am very confused and I want to understand. Why doesn't it work without .mean() when the values are already listed in avg_temp_c?

I tried removing .mean(). I tried replacing .mean() with .median() and .sum(), which give the exact same values for some reason. I tried just printing toronto["avg_temp_c"] and rome["avg_temp_c"], which gives me the values, but when I plot it without .mean(), .sum(), or .median(), it does not work. I am just trying to figure why this is the case, and how does all three of those methods give me the same values as if I were just to print the avg_temp_c list?

Hope my question was clear. Thank you!


问:
Docker shows me an error of COPY of to fix?
I'm using this container to set up X11 in GitPod.

```<code>ARG base
FROM ${base}

# Dazzle does not rebuild a layer until one of its lines are changed. Increase this counter to rebuild this layer.
ENV TRIGGER_REBUILD=1

# Install Xvfb, JavaFX-helpers and Openbox window manager
RUN sudo install-packages xvfb x11vnc xterm openjfx libopenjfx-java openbox

# Overwrite this env variable to use a different window manager
ENV WINDOW_MANAGER="openbox"

USER root

# Change the default number of virtual desktops from 4 to 1 (footgun)
RUN sed -ri "s/<number>4<\/number>/<number>1<\/number>/" /etc/xdg/openbox/rc.xml

# Install novnc
RUN git clone --depth 1 https://github.com/novnc/noVNC.git /opt/novnc \
    && git clone --depth 1 https://github.com/novnc/websockify /opt/novnc/utils/websockify
COPY novnc-index.html /opt/novnc/index.html

# Add VNC startup script
COPY start-vnc-session.sh /usr/bin/
RUN chmod +x /usr/bin/start-vnc-session.sh

USER gitpod
# This is a bit of a hack. At the moment we have no means of starting background
# tasks from a Dockerfile. This workaround checks, on each bashrc eval, if the X
# server is running on screen 0, and if not starts Xvfb, x11vnc and novnc.
RUN echo "export DISPLAY=:0" >> /home/gitpod/.bashrc.d/300-vnc
RUN echo "[ ! -e /tmp/.X0-lock ] && (/usr/bin/start-vnc-session.sh &> /tmp/display-\${DISPLAY}.log)" >> /home/gitpod/.bashrc.d/300-vnc

USER root
### checks ###
# no root-owned files in the home directory
RUN notOwnedFile=$(find . -not "(" -user gitpod -and -group gitpod ")" -print -quit) \
    && { [ -z "$notOwnedFile" ] \
        || { echo "Error: not all files/dirs in $HOME are owned by 'gitpod' user & group"; exit 1; } }

USER gitpod

</code>```

This is where it gets sketchy :

```<code># Install novnc
RUN git clone --depth 1 https://github.com/novnc/noVNC.git /opt/novnc \
    && git clone --depth 1 https://github.com/novnc/websockify /opt/novnc/utils/websockify
COPY novnc-index.html /opt/novnc/index.html
</code>```

I get this output please help !

```<code>COPY failed: file not found in build context or excluded by .dockerignore: stat novnc-index.html: file does not exist
</code>```

Knowing that my dockerfile is in /src and i'm building in /src . I tried to rebuild with the --no-cache flag and use export DOCKER_BUILDKIT=1 . But still I'm stuck with this problem .

Body:
I'm using this container to set up X11 in GitPod.

ARG base
FROM ${base}

# Dazzle does not rebuild a layer until one of its lines are changed. Increase this counter to rebuild this layer.
ENV TRIGGER_REBUILD=1

# Install Xvfb, JavaFX-helpers and Openbox window manager
RUN sudo install-packages xvfb x11vnc xterm openjfx libopenjfx-java openbox

# Overwrite this env variable to use a different window manager
ENV WINDOW_MANAGER="openbox"

USER root

# Change the default number of virtual desktops from 4 to 1 (footgun)
RUN sed -ri "s/<number>4<\/number>/<number>1<\/number>/" /etc/xdg/openbox/rc.xml

# Install novnc
RUN git clone --depth 1 https://github.com/novnc/noVNC.git /opt/novnc \
    && git clone --depth 1 https://github.com/novnc/websockify /opt/novnc/utils/websockify
COPY novnc-index.html /opt/novnc/index.html

# Add VNC startup script
COPY start-vnc-session.sh /usr/bin/
RUN chmod +x /usr/bin/start-vnc-session.sh

USER gitpod
# This is a bit of a hack. At the moment we have no means of starting background
# tasks from a Dockerfile. This workaround checks, on each bashrc eval, if the X
# server is running on screen 0, and if not starts Xvfb, x11vnc and novnc.
RUN echo "export DISPLAY=:0" >> /home/gitpod/.bashrc.d/300-vnc
RUN echo "[ ! -e /tmp/.X0-lock ] && (/usr/bin/start-vnc-session.sh &> /tmp/display-\${DISPLAY}.log)" >> /home/gitpod/.bashrc.d/300-vnc

USER root
### checks ###
# no root-owned files in the home directory
RUN notOwnedFile=$(find . -not "(" -user gitpod -and -group gitpod ")" -print -quit) \
    && { [ -z "$notOwnedFile" ] \
        || { echo "Error: not all files/dirs in $HOME are owned by 'gitpod' user & group"; exit 1; } }

USER gitpod

This is where it gets sketchy :

# Install novnc
RUN git clone --depth 1 https://github.com/novnc/noVNC.git /opt/novnc \
    && git clone --depth 1 https://github.com/novnc/websockify /opt/novnc/utils/websockify
COPY novnc-index.html /opt/novnc/index.html

I get this output please help !

COPY failed: file not found in build context or excluded by .dockerignore: stat novnc-index.html: file does not exist

Knowing that my dockerfile is in /src and i'm building in /src . I tried to rebuild with the --no-cache flag and use export DOCKER_BUILDKIT=1 . But still I'm stuck with this problem .


问:
ChromeProxyService - flutter
When I run my app using Chrome, this error appears.
This is the code:
`

```<code>void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}
</code>```

`

the error
main.dart

I have tried to upgrade flutter, but it didn´t worked.

Title: ChromeProxyService - flutter

Body:
When I run my app using Chrome, this error appears.
This is the code:
`

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(const MyApp());
}

`

the error
main.dart

I have tried to upgrade flutter, but it didn´t worked.


问:
WARNING:tensorflow:Gradients do not exist for variables
I've build a model and tried to compile but ended up with the following warning message.

```<code>def create_model_xlnet(xlnet_model):
    word_inputs = tf.keras.Input(shape=(4096,), name='word_inputs', dtype='int32')

    xlnet = TFXLNetModel.from_pretrained(xlnet_model)
    xlnet.classifier = None
    xlnet_encodings = xlnet(word_inputs)[0]

    # Collect last step from last hidden state (CLS)
    doc_encoding = tf.squeeze(xlnet_encodings[:, -1:, :], axis=1)

    doc_encoding = tf.keras.layers.Dropout(.1)(doc_encoding)

    outputs = tf.keras.layers.Dense(10, activation='softmax', name='outputs')(doc_encoding)

    model = tf.keras.Model(inputs=[word_inputs], outputs=[outputs])
    model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

    return model
</code>```

WARNING:tensorflow:Gradients do not exist for variables ['tfxl_net_model/transformer/mask_emb:0', 'tfxl_net_model/transformer/layer_.0/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.0/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.1/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.1/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.2/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.2/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.3/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.3/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.4/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.4/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.5/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.5/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.6/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.6/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.7/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.7/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.8/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.8/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.9/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.9/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.10/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.10/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.11/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer._11/rel_attn/seg_embed:0'] when minimizing the loss. If you're using model.compile(), did you forget to provide a loss argument?

Body:
I've build a model and tried to compile but ended up with the following warning message.

def create_model_xlnet(xlnet_model):
    word_inputs = tf.keras.Input(shape=(4096,), name='word_inputs', dtype='int32')

    xlnet = TFXLNetModel.from_pretrained(xlnet_model)
    xlnet.classifier = None
    xlnet_encodings = xlnet(word_inputs)[0]

    # Collect last step from last hidden state (CLS)
    doc_encoding = tf.squeeze(xlnet_encodings[:, -1:, :], axis=1)

    doc_encoding = tf.keras.layers.Dropout(.1)(doc_encoding)

    outputs = tf.keras.layers.Dense(10, activation='softmax', name='outputs')(doc_encoding)

    model = tf.keras.Model(inputs=[word_inputs], outputs=[outputs])
    model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])

    return model

WARNING:tensorflow:Gradients do not exist for variables ['tfxl_net_model/transformer/mask_emb:0', 'tfxl_net_model/transformer/layer_.0/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.0/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.1/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.1/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.2/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.2/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.3/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.3/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.4/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.4/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.5/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.5/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.6/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.6/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.7/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.7/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.8/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.8/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.9/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.9/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.10/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer.10/rel_attn/seg_embed:0', 'tfxl_net_model/transformer/layer.11/rel_attn/r_s_bias:0', 'tfxl_net_model/transformer/layer._11/rel_attn/seg_embed:0'] when minimizing the loss. If you're using model.compile(), did you forget to provide a loss argument?


问:
Hide Matdatepucker icon button based on date bselection from date picker
I have a Matdatepickertoggle icon once click on the icon one datepicker picker will open and after date selection toogle icon button should be hide .
And with that date i have to show another Matdatepicker icon.

Please hep me on that..TIA

```<code><mat-radio-button value="1">Daily Consumption</mat-radio-button>
    <inpu matInput class="date-input" [matDatepicker]="picker1"  readonly='true' required />
    <mat-datepicker-toggle matSuffix [for]="picker1">
      <mat-label matDatepickerToggleIcon>Select Date</mat-label>
    </mat-datepicker-toggle>
    <mat-datepicker #picker1></mat-datepicker>
</code>```

inside image you can see clearly that select date will hide and with selected date we have to add update date button same way .

Body:
I have a Matdatepickertoggle icon once click on the icon one datepicker picker will open and after date selection toogle icon button should be hide .
And with that date i have to show another Matdatepicker icon.

Please hep me on that..TIA

<mat-radio-button value="1">Daily Consumption</mat-radio-button>
    <inpu matInput class="date-input" [matDatepicker]="picker1"  readonly='true' required />
    <mat-datepicker-toggle matSuffix [for]="picker1">
      <mat-label matDatepickerToggleIcon>Select Date</mat-label>
    </mat-datepicker-toggle>
    <mat-datepicker #picker1></mat-datepicker>

inside image you can see clearly that select date will hide and with selected date we have to add update date button same way .


问:
Maya Python can only concatenate list (not "str") to list
I'm a Python beginner. I'm trying to write a Maya script to create and connect a new locator to the nodes that I've selected. I'm getting an error - TypeError: file <maya console> line 21: can only concatenate list (not "str") to list, on the line where I connectAttr.

Here is what I have so far:

I assign variables from the nodes that I've selected
I create a locator with the name from the joint, group it, parent constrain it so it moves to the correct location, and then I want to connect it to the existing nodes. This is the 3rd script I've ever written, please explain like I'm 5.

import maya.cmds as cmds

sel= cmds.ls(sl=True)

for s in sel:

    jntn=sel[0]
    cntrl=sel[1]
    gradientMult=sel[2]
    trans=sel[3]
    orient=sel[4]

    print sel

    loc = cmds.spaceLocator(n=jntn+"_LOC")
    grp = cmds.group(empty=True, n=jntn+"_LOC_offset")
    cmds.parent (loc,grp)
    cmds.parentConstraint(jntn, grp, mo=False)
    cmds.delete(const)
    cmds.connectAttr(loc+".translateX",gradientMult+"input1x",f)
    cmds.connectAttr(cntrl+".translate",orient+".input1",f)
    cmds.pointConstraint(cntrl,loc, mo=False)
```