Popular New Releases in Code Editor
vscode
March 2022 Recovery 2
atom
1.61.0-beta0
coc.nvim
v0.0.80 Better float support
cascadia-code
Cascadia Code 2110.31
roslyn
.NET 7.0 Preview 2
Popular Libraries in Code Editor
by microsoft typescript
130477 MIT
Visual Studio Code
by atom javascript
57308 MIT
:atom: The hackable text editor
by neoclide typescript
19503 NOASSERTION
Nodejs extension host for vim & neovim, load extensions like VSCode and host language servers.
by microsoft python
18637 OFL-1.1
This is a fun, new monospaced font that includes programming ligatures and is designed to enhance the modern look and feel of the Windows Terminal.
by dotnet csharp
15780 MIT
The Roslyn .NET compiler provides C# and Visual Basic languages with rich code analysis APIs.
by VSCodium shell
15512 MIT
binary releases of VS Code without MS branding/telemetry/licensing
by jupyterlab typescript
11994 NOASSERTION
JupyterLab computational environment.
by daylerees html
9284 NOASSERTION
Colour schemes for a variety of editors created by Dayle Rees.
by bobthecow php
9206 MIT
A REPL for PHP
Trending New libraries in Code Editor
by valinet c
4732 GPL-2.0
This project aims to enhance the working environment on Windows
by LeekHub typescript
2286 BSD-3-Clause
:chart_with_upwards_trend: 韭菜盒子——VSCode 里也可以看股票 & 基金实时数据,做最好用的投资插件 🐥
by devMEremenko swift
1604 MIT
XcodeBenchmark measures the compilation time of a large codebase on iMac, MacBook, and Mac Pro
by rohit-px2 c++
1486 MIT
A modern frontend for Neovim.
by ms-jpq python
907
File manager for Neovim. Better than NERDTree.
by gzuidhof typescript
831 MPL-2.0
In-browser literate notebooks
by zthxxx javascript
753 MIT
傲 娇 钉 宫,鞭 写 鞭 骂 - 钉宫理惠 vscode-rainbow-fart 扩展语音包
by michaelb rust
598 MIT
A neovim plugin to run lines/blocs of code (independently of the rest of the file), supporting multiples languages
by raxod502 javascript
497 MIT
⚡ Extremely fast online playground for every programming language.
Top Authors in Code Editor
1
74 Libraries
10635
2
71 Libraries
3071
3
70 Libraries
168392
4
39 Libraries
24989
5
38 Libraries
63994
6
22 Libraries
487
7
22 Libraries
16907
8
19 Libraries
2208
9
18 Libraries
280
10
18 Libraries
1262
1
74 Libraries
10635
2
71 Libraries
3071
3
70 Libraries
168392
4
39 Libraries
24989
5
38 Libraries
63994
6
22 Libraries
487
7
22 Libraries
16907
8
19 Libraries
2208
9
18 Libraries
280
10
18 Libraries
1262
Trending Kits in Code Editor
No Trending Kits are available at this moment for Code Editor
Trending Discussions on Code Editor
What's the connection of string_view and basic_string<char> and why does string_view example code not work?
The method 'map' was called on null. & Tried calling: map<Answer>(Closure: (String) => Answer)
Android Studio strange code sub-windows after upgrade to Arctic Fox (2020.3.1)
Does anyone know how to get argument name automatically in Visual Studio Code?
Is it possible to wrap lines when viewing code for a branch in the browser on Azure DevOps?
How to remove extra spaces from VS Code Editor?
GIFs not animating in the Android version of my React Native app
Decorators and Private fields javascript
Zooming in does not adapt date axis when using Julia's PlotlyJS in VSCode
TypeScript errors when editing old Vue 3 components but not on new components
QUESTION
What's the connection of string_view and basic_string<char> and why does string_view example code not work?
Asked 2022-Feb-10 at 05:11I have copied code from Bjarne Stroustrup's A Tour of C++ to test out string views but I keep getting error:
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2
I am using VS Code WSL 2
with Ubuntu 20.04
and gcc-11
in main.cpp
, I have:
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11
in strings.h
, I have the following. The function is copied as in the text book. I typed it out to avoid the peculiar *
character that had a different encoding.
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25
Using the Ctrl+F5
command gives this error.
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25In file included from main.cpp:2:
26strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
27strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
28 7 | string res(sv1.length()+sv2.length());
29 | ^
30In file included from /usr/include/c++/11/string:55,
31 from /usr/include/c++/11/bits/locale_classes.h:40,
32 from /usr/include/c++/11/bits/ios_base.h:41,
33 from /usr/include/c++/11/ios:42,
34 from /usr/include/c++/11/ostream:38,
35 from /usr/include/c++/11/iostream:39,
36 from main.cpp:1:
37/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
38 650 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
39 | ^~~~~~~~~~~~
40/usr/include/c++/11/bits/basic_string.h:650:9: note: template argument deduction/substitution failed:
41In file included from /usr/include/c++/11/bits/move.h:57,
42 from /usr/include/c++/11/bits/nested_exception.h:40,
43 from /usr/include/c++/11/exception:148,
44 from /usr/include/c++/11/ios:39,
45 from /usr/include/c++/11/ostream:38,
46 from /usr/include/c++/11/iostream:39,
47 from main.cpp:1:
48
I took a screenshot of what I see from Visual Studio code to indicate the underlined code, which doesn't makes
I thought it might have been the code editor but Godbolt shows similar errors.
Since this is related to Vs Code, here are my
launch.json
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25In file included from main.cpp:2:
26strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
27strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
28 7 | string res(sv1.length()+sv2.length());
29 | ^
30In file included from /usr/include/c++/11/string:55,
31 from /usr/include/c++/11/bits/locale_classes.h:40,
32 from /usr/include/c++/11/bits/ios_base.h:41,
33 from /usr/include/c++/11/ios:42,
34 from /usr/include/c++/11/ostream:38,
35 from /usr/include/c++/11/iostream:39,
36 from main.cpp:1:
37/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
38 650 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
39 | ^~~~~~~~~~~~
40/usr/include/c++/11/bits/basic_string.h:650:9: note: template argument deduction/substitution failed:
41In file included from /usr/include/c++/11/bits/move.h:57,
42 from /usr/include/c++/11/bits/nested_exception.h:40,
43 from /usr/include/c++/11/exception:148,
44 from /usr/include/c++/11/ios:39,
45 from /usr/include/c++/11/ostream:38,
46 from /usr/include/c++/11/iostream:39,
47 from main.cpp:1:
48{
49 // Use IntelliSense to learn about possible attributes.
50 // Hover to view descriptions of existing attributes.
51 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
52 "version": "0.2.0",
53 "configurations": [
54 {
55 "name": "g++-11 - Build and debug active file",
56 "type": "cppdbg",
57 "request": "launch",
58 "program": "${fileDirname}/${fileBasenameNoExtension}",
59 "args": [],
60 "stopAtEntry": false,
61 "cwd": "${fileDirname}",
62 "environment": [],
63 "externalConsole": false,
64 "MIMode": "gdb",
65 "setupCommands": [
66 {
67 "description": "Enable pretty-printing for gdb",
68 "text": "-enable-pretty-printing",
69 "ignoreFailures": true
70 },
71 {
72 "description": "Set Disassembly Flavor to Intel",
73 "text": "-gdb-set disassembly-flavor intel",
74 "ignoreFailures": true
75 }
76 ],
77 "preLaunchTask": "C/C++: g++-11 build active file",
78 "miDebuggerPath": "/usr/bin/gdb"
79 }
80 ]
81}
82
and c_cpp_properties.json
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25In file included from main.cpp:2:
26strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
27strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
28 7 | string res(sv1.length()+sv2.length());
29 | ^
30In file included from /usr/include/c++/11/string:55,
31 from /usr/include/c++/11/bits/locale_classes.h:40,
32 from /usr/include/c++/11/bits/ios_base.h:41,
33 from /usr/include/c++/11/ios:42,
34 from /usr/include/c++/11/ostream:38,
35 from /usr/include/c++/11/iostream:39,
36 from main.cpp:1:
37/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
38 650 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
39 | ^~~~~~~~~~~~
40/usr/include/c++/11/bits/basic_string.h:650:9: note: template argument deduction/substitution failed:
41In file included from /usr/include/c++/11/bits/move.h:57,
42 from /usr/include/c++/11/bits/nested_exception.h:40,
43 from /usr/include/c++/11/exception:148,
44 from /usr/include/c++/11/ios:39,
45 from /usr/include/c++/11/ostream:38,
46 from /usr/include/c++/11/iostream:39,
47 from main.cpp:1:
48{
49 // Use IntelliSense to learn about possible attributes.
50 // Hover to view descriptions of existing attributes.
51 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
52 "version": "0.2.0",
53 "configurations": [
54 {
55 "name": "g++-11 - Build and debug active file",
56 "type": "cppdbg",
57 "request": "launch",
58 "program": "${fileDirname}/${fileBasenameNoExtension}",
59 "args": [],
60 "stopAtEntry": false,
61 "cwd": "${fileDirname}",
62 "environment": [],
63 "externalConsole": false,
64 "MIMode": "gdb",
65 "setupCommands": [
66 {
67 "description": "Enable pretty-printing for gdb",
68 "text": "-enable-pretty-printing",
69 "ignoreFailures": true
70 },
71 {
72 "description": "Set Disassembly Flavor to Intel",
73 "text": "-gdb-set disassembly-flavor intel",
74 "ignoreFailures": true
75 }
76 ],
77 "preLaunchTask": "C/C++: g++-11 build active file",
78 "miDebuggerPath": "/usr/bin/gdb"
79 }
80 ]
81}
82{
83 "configurations": [
84 {
85 "name": "Linux",
86 "includePath": [
87 "${workspaceFolder}/**"
88 ],
89 "defines": [],
90 "compilerPath": "/usr/bin/gcc",
91 "cStandard": "gnu17",
92 "cppStandard": "gnu++20",
93 "intelliSenseMode": "linux-gcc-x64"
94 }
95 ],
96 "version": 4
97}
98
ANSWER
Answered 2022-Feb-10 at 05:11Yes, this seems to be wrong.
The line
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25In file included from main.cpp:2:
26strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
27strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
28 7 | string res(sv1.length()+sv2.length());
29 | ^
30In file included from /usr/include/c++/11/string:55,
31 from /usr/include/c++/11/bits/locale_classes.h:40,
32 from /usr/include/c++/11/bits/ios_base.h:41,
33 from /usr/include/c++/11/ios:42,
34 from /usr/include/c++/11/ostream:38,
35 from /usr/include/c++/11/iostream:39,
36 from main.cpp:1:
37/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
38 650 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
39 | ^~~~~~~~~~~~
40/usr/include/c++/11/bits/basic_string.h:650:9: note: template argument deduction/substitution failed:
41In file included from /usr/include/c++/11/bits/move.h:57,
42 from /usr/include/c++/11/bits/nested_exception.h:40,
43 from /usr/include/c++/11/exception:148,
44 from /usr/include/c++/11/ios:39,
45 from /usr/include/c++/11/ostream:38,
46 from /usr/include/c++/11/iostream:39,
47 from main.cpp:1:
48{
49 // Use IntelliSense to learn about possible attributes.
50 // Hover to view descriptions of existing attributes.
51 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
52 "version": "0.2.0",
53 "configurations": [
54 {
55 "name": "g++-11 - Build and debug active file",
56 "type": "cppdbg",
57 "request": "launch",
58 "program": "${fileDirname}/${fileBasenameNoExtension}",
59 "args": [],
60 "stopAtEntry": false,
61 "cwd": "${fileDirname}",
62 "environment": [],
63 "externalConsole": false,
64 "MIMode": "gdb",
65 "setupCommands": [
66 {
67 "description": "Enable pretty-printing for gdb",
68 "text": "-enable-pretty-printing",
69 "ignoreFailures": true
70 },
71 {
72 "description": "Set Disassembly Flavor to Intel",
73 "text": "-gdb-set disassembly-flavor intel",
74 "ignoreFailures": true
75 }
76 ],
77 "preLaunchTask": "C/C++: g++-11 build active file",
78 "miDebuggerPath": "/usr/bin/gdb"
79 }
80 ]
81}
82{
83 "configurations": [
84 {
85 "name": "Linux",
86 "includePath": [
87 "${workspaceFolder}/**"
88 ],
89 "defines": [],
90 "compilerPath": "/usr/bin/gcc",
91 "cStandard": "gnu17",
92 "cppStandard": "gnu++20",
93 "intelliSenseMode": "linux-gcc-x64"
94 }
95 ],
96 "version": 4
97}
98string res(sv1.length()+sv2.length());
99
should be
1error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type
2#include <iostream>
3#include "strings.h"
4
5using namespace std;
6
7int main () {
8 string king = "Harold";
9 auto s1 = cat(king, "William");
10}
11#pragma once
12#include <string>
13
14using namespace std;
15
16string cat(string_view sv1, string_view sv2) {
17 string res(sv1.length()+sv2.length());
18 char* p = &res[0];
19
20 for (char c : sv1) // one way
21 *p++ = c;
22 copy(sv2.begin(), sv2.end(), p); // another way
23 return res;
24}
25In file included from main.cpp:2:
26strings.h: In function ‘std::string cat(std::string_view, std::string_view)’:
27strings.h:7:41: error: no matching function for call to ‘std::__cxx11::basic_string<char>::basic_string(std::basic_string_view<char>::size_type)’
28 7 | string res(sv1.length()+sv2.length());
29 | ^
30In file included from /usr/include/c++/11/string:55,
31 from /usr/include/c++/11/bits/locale_classes.h:40,
32 from /usr/include/c++/11/bits/ios_base.h:41,
33 from /usr/include/c++/11/ios:42,
34 from /usr/include/c++/11/ostream:38,
35 from /usr/include/c++/11/iostream:39,
36 from main.cpp:1:
37/usr/include/c++/11/bits/basic_string.h:650:9: note: candidate: ‘template<class _Tp, class> std::__cxx11::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _Tp&, const _Alloc&) [with _Tp = _Tp; <template-parameter-2-2> = <template-parameter-1-2>; _CharT = char; _Traits = std::char_traits<char>; _Alloc = std::allocator<char>]’
38 650 | basic_string(const _Tp& __t, const _Alloc& __a = _Alloc())
39 | ^~~~~~~~~~~~
40/usr/include/c++/11/bits/basic_string.h:650:9: note: template argument deduction/substitution failed:
41In file included from /usr/include/c++/11/bits/move.h:57,
42 from /usr/include/c++/11/bits/nested_exception.h:40,
43 from /usr/include/c++/11/exception:148,
44 from /usr/include/c++/11/ios:39,
45 from /usr/include/c++/11/ostream:38,
46 from /usr/include/c++/11/iostream:39,
47 from main.cpp:1:
48{
49 // Use IntelliSense to learn about possible attributes.
50 // Hover to view descriptions of existing attributes.
51 // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
52 "version": "0.2.0",
53 "configurations": [
54 {
55 "name": "g++-11 - Build and debug active file",
56 "type": "cppdbg",
57 "request": "launch",
58 "program": "${fileDirname}/${fileBasenameNoExtension}",
59 "args": [],
60 "stopAtEntry": false,
61 "cwd": "${fileDirname}",
62 "environment": [],
63 "externalConsole": false,
64 "MIMode": "gdb",
65 "setupCommands": [
66 {
67 "description": "Enable pretty-printing for gdb",
68 "text": "-enable-pretty-printing",
69 "ignoreFailures": true
70 },
71 {
72 "description": "Set Disassembly Flavor to Intel",
73 "text": "-gdb-set disassembly-flavor intel",
74 "ignoreFailures": true
75 }
76 ],
77 "preLaunchTask": "C/C++: g++-11 build active file",
78 "miDebuggerPath": "/usr/bin/gdb"
79 }
80 ]
81}
82{
83 "configurations": [
84 {
85 "name": "Linux",
86 "includePath": [
87 "${workspaceFolder}/**"
88 ],
89 "defines": [],
90 "compilerPath": "/usr/bin/gcc",
91 "cStandard": "gnu17",
92 "cppStandard": "gnu++20",
93 "intelliSenseMode": "linux-gcc-x64"
94 }
95 ],
96 "version": 4
97}
98string res(sv1.length()+sv2.length());
99string res(sv1.length()+sv2.length(), '\0');
100
std::string
doesn't have a constructor which takes only a size argument, in contrast to std::vector
. The value with which the elements are to be initialized must be provided explicitly.
I couldn't find this mistake in the list of errata here, though.
QUESTION
The method 'map' was called on null. & Tried calling: map<Answer>(Closure: (String) => Answer)
Asked 2022-Jan-20 at 16:07Error:
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6
my code:
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6import 'package:flutter/material.dart';
7
8
9import './qestion.dart';
10import 'answer.dart';
11
12void main() {
13 runApp(MyApp());
14}
15
16
17
18class MyApp extends StatefulWidget {
19 @override
20 State<StatefulWidget> createState() {
21 return _MyAppState();
22 }
23}
24
25class _MyAppState extends State<MyApp> {
26 var _questionIndex = 0;
27
28 void _answerQuestion() {
29 setState(() {
30 _questionIndex = _questionIndex + 1;
31 });
32 print(_questionIndex);
33 //print('Answer choosen');
34 }
35
36 Widget build(BuildContext context) {
37 var questions = [
38 {
39 'questionText': 'what\'s your favorite color?',
40 'answers': ['red', 'black', 'brown'],
41 },
42 {
43 'questionText': 'what\s your favorite animal ?',
44 'answers': ['lion', 'horse'],
45 },
46 ];
47
48 return MaterialApp(
49 home: Scaffold(
50 appBar: AppBar(
51 title: Text('My First Application'),
52 ),
53 body: Column(
54 children: [
55 Question(
56 questions[_questionIndex]['questionText'],
57 ),
58
59 ...(questions[_questionIndex]['answer'] as List<String>)
60 . map((answer) {
61 return Answer(_answerQuestion, answer);
62 }).toList()
63 [],
64 // RaisedButton(
65 // child: Text('Answer 2'),
66 // onPressed: () => {print('it is a =anonymus ans')},
67 // ),
68 ],
69 ),
70 ),
71 );
72 }
73}
74
Problematic part may be:
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6import 'package:flutter/material.dart';
7
8
9import './qestion.dart';
10import 'answer.dart';
11
12void main() {
13 runApp(MyApp());
14}
15
16
17
18class MyApp extends StatefulWidget {
19 @override
20 State<StatefulWidget> createState() {
21 return _MyAppState();
22 }
23}
24
25class _MyAppState extends State<MyApp> {
26 var _questionIndex = 0;
27
28 void _answerQuestion() {
29 setState(() {
30 _questionIndex = _questionIndex + 1;
31 });
32 print(_questionIndex);
33 //print('Answer choosen');
34 }
35
36 Widget build(BuildContext context) {
37 var questions = [
38 {
39 'questionText': 'what\'s your favorite color?',
40 'answers': ['red', 'black', 'brown'],
41 },
42 {
43 'questionText': 'what\s your favorite animal ?',
44 'answers': ['lion', 'horse'],
45 },
46 ];
47
48 return MaterialApp(
49 home: Scaffold(
50 appBar: AppBar(
51 title: Text('My First Application'),
52 ),
53 body: Column(
54 children: [
55 Question(
56 questions[_questionIndex]['questionText'],
57 ),
58
59 ...(questions[_questionIndex]['answer'] as List<String>)
60 . map((answer) {
61 return Answer(_answerQuestion, answer);
62 }).toList()
63 [],
64 // RaisedButton(
65 // child: Text('Answer 2'),
66 // onPressed: () => {print('it is a =anonymus ans')},
67 // ),
68 ],
69 ),
70 ),
71 );
72 }
73}
74 ...(questions[_questionIndex]['answer'] as List<String>)
75 . map((answer) {
76 return Answer(_answerQuestion, answer);
77 }).toList()
78
Question.dart:
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6import 'package:flutter/material.dart';
7
8
9import './qestion.dart';
10import 'answer.dart';
11
12void main() {
13 runApp(MyApp());
14}
15
16
17
18class MyApp extends StatefulWidget {
19 @override
20 State<StatefulWidget> createState() {
21 return _MyAppState();
22 }
23}
24
25class _MyAppState extends State<MyApp> {
26 var _questionIndex = 0;
27
28 void _answerQuestion() {
29 setState(() {
30 _questionIndex = _questionIndex + 1;
31 });
32 print(_questionIndex);
33 //print('Answer choosen');
34 }
35
36 Widget build(BuildContext context) {
37 var questions = [
38 {
39 'questionText': 'what\'s your favorite color?',
40 'answers': ['red', 'black', 'brown'],
41 },
42 {
43 'questionText': 'what\s your favorite animal ?',
44 'answers': ['lion', 'horse'],
45 },
46 ];
47
48 return MaterialApp(
49 home: Scaffold(
50 appBar: AppBar(
51 title: Text('My First Application'),
52 ),
53 body: Column(
54 children: [
55 Question(
56 questions[_questionIndex]['questionText'],
57 ),
58
59 ...(questions[_questionIndex]['answer'] as List<String>)
60 . map((answer) {
61 return Answer(_answerQuestion, answer);
62 }).toList()
63 [],
64 // RaisedButton(
65 // child: Text('Answer 2'),
66 // onPressed: () => {print('it is a =anonymus ans')},
67 // ),
68 ],
69 ),
70 ),
71 );
72 }
73}
74 ...(questions[_questionIndex]['answer'] as List<String>)
75 . map((answer) {
76 return Answer(_answerQuestion, answer);
77 }).toList()
78import 'package:flutter/material.dart';
79
80class Question extends StatelessWidget {
81 // const Question({ Key? key }) : super(key: key);
82 final String questionText;
83 Question(this.questionText);
84
85 @override
86 Widget build(BuildContext context) {
87 return Container(
88 margin: EdgeInsets.all(10),
89 width: double.infinity,
90 child: Text(
91 questionText,
92 style: TextStyle(fontSize: 25),
93 textAlign: TextAlign.center,
94 ),
95 );
96 }
97}
98
Answer.dart
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6import 'package:flutter/material.dart';
7
8
9import './qestion.dart';
10import 'answer.dart';
11
12void main() {
13 runApp(MyApp());
14}
15
16
17
18class MyApp extends StatefulWidget {
19 @override
20 State<StatefulWidget> createState() {
21 return _MyAppState();
22 }
23}
24
25class _MyAppState extends State<MyApp> {
26 var _questionIndex = 0;
27
28 void _answerQuestion() {
29 setState(() {
30 _questionIndex = _questionIndex + 1;
31 });
32 print(_questionIndex);
33 //print('Answer choosen');
34 }
35
36 Widget build(BuildContext context) {
37 var questions = [
38 {
39 'questionText': 'what\'s your favorite color?',
40 'answers': ['red', 'black', 'brown'],
41 },
42 {
43 'questionText': 'what\s your favorite animal ?',
44 'answers': ['lion', 'horse'],
45 },
46 ];
47
48 return MaterialApp(
49 home: Scaffold(
50 appBar: AppBar(
51 title: Text('My First Application'),
52 ),
53 body: Column(
54 children: [
55 Question(
56 questions[_questionIndex]['questionText'],
57 ),
58
59 ...(questions[_questionIndex]['answer'] as List<String>)
60 . map((answer) {
61 return Answer(_answerQuestion, answer);
62 }).toList()
63 [],
64 // RaisedButton(
65 // child: Text('Answer 2'),
66 // onPressed: () => {print('it is a =anonymus ans')},
67 // ),
68 ],
69 ),
70 ),
71 );
72 }
73}
74 ...(questions[_questionIndex]['answer'] as List<String>)
75 . map((answer) {
76 return Answer(_answerQuestion, answer);
77 }).toList()
78import 'package:flutter/material.dart';
79
80class Question extends StatelessWidget {
81 // const Question({ Key? key }) : super(key: key);
82 final String questionText;
83 Question(this.questionText);
84
85 @override
86 Widget build(BuildContext context) {
87 return Container(
88 margin: EdgeInsets.all(10),
89 width: double.infinity,
90 child: Text(
91 questionText,
92 style: TextStyle(fontSize: 25),
93 textAlign: TextAlign.center,
94 ),
95 );
96 }
97}
98import 'package:flutter/material.dart';
99
100class Answer extends StatelessWidget {
101 //const Answer({ Key? key }) : super(key: key);
102 final Function selectHandler;
103 final String answerText;
104 Answer(this.selectHandler, this.answerText);
105
106 @override
107 Widget build(BuildContext context) {
108 return Container(
109 width: double.infinity,
110 child: RaisedButton(
111 textColor: Colors.black,
112 color: Colors.cyan,
113 child: Text(answerText),
114 onPressed: selectHandler,
115 ));
116 }
117}
118
how can i solve this error in VScode editor?
ANSWER
Answered 2022-Jan-20 at 06:50You have typo. In place where you declare variable there is answers
field, but you are accessing answer
field.
Change following line and see again.
1The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#ad714):
2
3 The method 'map' was called on null.
4 Receiver: null
5 Tried calling: map<Answer>(Closure: (String) => Answer)
6import 'package:flutter/material.dart';
7
8
9import './qestion.dart';
10import 'answer.dart';
11
12void main() {
13 runApp(MyApp());
14}
15
16
17
18class MyApp extends StatefulWidget {
19 @override
20 State<StatefulWidget> createState() {
21 return _MyAppState();
22 }
23}
24
25class _MyAppState extends State<MyApp> {
26 var _questionIndex = 0;
27
28 void _answerQuestion() {
29 setState(() {
30 _questionIndex = _questionIndex + 1;
31 });
32 print(_questionIndex);
33 //print('Answer choosen');
34 }
35
36 Widget build(BuildContext context) {
37 var questions = [
38 {
39 'questionText': 'what\'s your favorite color?',
40 'answers': ['red', 'black', 'brown'],
41 },
42 {
43 'questionText': 'what\s your favorite animal ?',
44 'answers': ['lion', 'horse'],
45 },
46 ];
47
48 return MaterialApp(
49 home: Scaffold(
50 appBar: AppBar(
51 title: Text('My First Application'),
52 ),
53 body: Column(
54 children: [
55 Question(
56 questions[_questionIndex]['questionText'],
57 ),
58
59 ...(questions[_questionIndex]['answer'] as List<String>)
60 . map((answer) {
61 return Answer(_answerQuestion, answer);
62 }).toList()
63 [],
64 // RaisedButton(
65 // child: Text('Answer 2'),
66 // onPressed: () => {print('it is a =anonymus ans')},
67 // ),
68 ],
69 ),
70 ),
71 );
72 }
73}
74 ...(questions[_questionIndex]['answer'] as List<String>)
75 . map((answer) {
76 return Answer(_answerQuestion, answer);
77 }).toList()
78import 'package:flutter/material.dart';
79
80class Question extends StatelessWidget {
81 // const Question({ Key? key }) : super(key: key);
82 final String questionText;
83 Question(this.questionText);
84
85 @override
86 Widget build(BuildContext context) {
87 return Container(
88 margin: EdgeInsets.all(10),
89 width: double.infinity,
90 child: Text(
91 questionText,
92 style: TextStyle(fontSize: 25),
93 textAlign: TextAlign.center,
94 ),
95 );
96 }
97}
98import 'package:flutter/material.dart';
99
100class Answer extends StatelessWidget {
101 //const Answer({ Key? key }) : super(key: key);
102 final Function selectHandler;
103 final String answerText;
104 Answer(this.selectHandler, this.answerText);
105
106 @override
107 Widget build(BuildContext context) {
108 return Container(
109 width: double.infinity,
110 child: RaisedButton(
111 textColor: Colors.black,
112 color: Colors.cyan,
113 child: Text(answerText),
114 onPressed: selectHandler,
115 ));
116 }
117}
118...(questions[_questionIndex]['answers'] as List<String>)
119 . map((answer) {
120 return Answer(_answerQuestion, answer);
121 }).toList()
122
QUESTION
Android Studio strange code sub-windows after upgrade to Arctic Fox (2020.3.1)
Asked 2022-Jan-14 at 09:18After Android Studio upgraded itself to version Arctic Fox, I now get these strange sub-windows in my code editor that I can't get rid of. If I click in either of the 2 sub-windows (a one-line window at the top or a 5-line window underneath it (see pic below), it scrolls to the code in question and the sub-windows disappear. But as soon as I navigate away from that code, these sub-windows mysteriously reappear. I can't figure out how to get rid of this.
I restarted Studio and it seemed to go away. Then I refactored a piece of code (Extract to Method Ctrl+Alt+M) and then these windows appeared again. Sometimes these windows appear on a 2nd monitor instead of on top of the code area on the monitor with Android Studio. But eventually they end up back on top of my code editor window.
I have searched hi and low for what this is. Studio help, new features, blog, etc. I am sure that I am just using the wrong terminology to find the answer, so hoping someone else knows.
ANSWER
Answered 2021-Aug-15 at 15:29Just stumbled upon the same thing (strange windows upon attempting to refactor some code after updating to Arctic Fox). After a lot of searching around the options/menus/internet this fixed it for me:
Navigate to:
File > Settings... > Editor > Code Editing
under
Refactorings > Specify refactoring options:
select
In modal dialogs
Press OK.
Fingers crossed refactoring works.
🤞
Further step: Restart Android Studio
QUESTION
Does anyone know how to get argument name automatically in Visual Studio Code?
Asked 2021-Dec-20 at 11:10Look at the below-given image of Intellij IDEA -
When we use a function it automatically provides the argument name and when we copy a code-snippet then that argument name is not copied(it is just for our reference).
I want to do the same in my vs-code editor but, I can't find any way to do it.
ANSWER
Answered 2021-Dec-20 at 11:10Looks like Inline Parameters for VSCode extension you looking for.
QUESTION
Is it possible to wrap lines when viewing code for a branch in the browser on Azure DevOps?
Asked 2021-Dec-04 at 02:09On small screen of a laptop it gets tedious to see code on Azure DevOps when the line length is large.
The workaround I use instead of using the scrollbar located way down below, is to click and drag mouse cursor from the end of line to the right. But this moves the cursor too fast and using the arrow keys is too slow.
Code editors and IDEs we have the ability to wrap lines (Word wrap) when the lines are large .
The code review UI has the option for word wrap. Cannnot find it for viewing code UI.
Is it possible to do that in Azure DevOps?
ANSWER
Answered 2021-Dec-04 at 02:09QUESTION
How to remove extra spaces from VS Code Editor?
Asked 2021-Dec-03 at 23:22I was working on VS Code Editor and suddenly I pressed some key which created this space around window
How can I remove this space?
ANSWER
Answered 2021-Dec-03 at 23:22Navigate to View/Appearance/Centered Layout as shown in the image and disable it:
QUESTION
GIFs not animating in the Android version of my React Native app
Asked 2021-Nov-23 at 14:57I am struggling to get my GIFs to animate on the Android version of my RN application. The iOS version is animating the looping GIFs as expected but I only see a stuck "single frame" image from the GIF on the Android device.
According to the debugging and RN-documentation it's required to add a few lines of implementation
to the dependencies
within the /android/app/build.gradle, but even after cleaning the gradle (running ./gradlew clean
in the /android folder) and deleting the cache of the RN app (running react-native start --reset-cache
in the project root folder), I do not see any difference in my application.
I have googled and tried a lot. Based on my debugging adventure, I have tried and double-checked these suggestions, that seems to work for others but it doesn't seem to work for me...
- I have tried several versions of the fresco-libraries that seems to
be required and I have also tried placing the lines in both the
bottom as well as the top of the
dependencies
. - Some answers also suggest to add one or more lines of code to the android/app/proguard-rules.pro but this doesn't change anything either.
- I use GIFs in different ways of my application but it always has
width
andheight
included to thestyle
property on the<Image />
. - I have tried with GIF-uris from different CDNs and domains.
- Reinstalled the app on my test devices.
- Closed and reopened my code editors.
I'm using the following versions:
- Java: 11.0.12
- React Native: 0.65
- Android SDK: 30.0.2
- npm: 6.14.4
This is my full /android/app/build.gradle:
1apply plugin: "com.android.application"
2
3import com.android.build.OutputFile
4
5
6project.ext.react = [
7 enableHermes: false, // clean and rebuild if changing
8]
9
10apply from: "../../node_modules/react-native/react.gradle"
11
12
13def enableSeparateBuildPerCPUArchitecture = false
14def enableProguardInReleaseBuilds = false
15def jscFlavor = 'org.webkit:android-jsc:+'
16def enableHermes = project.ext.react.get("enableHermes", false);
17
18android {
19 ndkVersion rootProject.ext.ndkVersion
20
21 compileSdkVersion rootProject.ext.compileSdkVersion
22
23 defaultConfig {
24 applicationId "com.example.app"
25 minSdkVersion rootProject.ext.minSdkVersion
26 targetSdkVersion rootProject.ext.targetSdkVersion
27 versionCode 1
28 versionName "1.0"
29 }
30 splits {
31 abi {
32 reset()
33 enable enableSeparateBuildPerCPUArchitecture
34 universalApk false // If true, also generate a universal APK
35 include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
36 }
37 }
38 signingConfigs {
39 debug {
40 storeFile file('debug.keystore')
41 storePassword 'android'
42 keyAlias 'androiddebugkey'
43 keyPassword 'android'
44 }
45 }
46 buildTypes {
47 debug {
48 signingConfig signingConfigs.debug
49 }
50 release {
51 // Caution! In production, you need to generate your own keystore file.
52 // see https://reactnative.dev/docs/signed-apk-android.
53 signingConfig signingConfigs.debug
54 minifyEnabled enableProguardInReleaseBuilds
55 proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
56 }
57 }
58
59 // applicationVariants are e.g. debug, release
60 applicationVariants.all { variant ->
61 variant.outputs.each { output ->
62 // For each separate APK per architecture, set a unique version code as described here:
63 // https://developer.android.com/studio/build/configure-apk-splits.html
64 // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
65 def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
66 def abi = output.getFilter(OutputFile.ABI)
67 if (abi != null) { // null for the universal-debug, universal-release variants
68 output.versionCodeOverride =
69 defaultConfig.versionCode * 1000 + versionCodes.get(abi)
70 }
71
72 }
73 }
74}
75
76dependencies {
77
78 implementation fileTree(dir: "libs", include: ["*.jar"])
79 //noinspection GradleDynamicVersion
80 implementation "com.facebook.react:react-native:+" // From node_modules
81
82 implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
83
84 debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
85 exclude group:'com.facebook.fbjni'
86 }
87
88 debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
89 exclude group:'com.facebook.flipper'
90 exclude group:'com.squareup.okhttp3', module:'okhttp'
91 }
92
93 debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
94 exclude group:'com.facebook.flipper'
95 }
96
97 if (enableHermes) {
98 def hermesPath = "../../node_modules/hermes-engine/android/";
99 debugImplementation files(hermesPath + "hermes-debug.aar")
100 releaseImplementation files(hermesPath + "hermes-release.aar")
101 } else {
102 implementation jscFlavor
103 }
104
105
106 implementation project(':react-native-notifications')
107 implementation 'com.google.firebase:firebase-core:16.0.0'
108 implementation 'com.google.android.gms:play-services-ads:19.8.0'
109 implementation "androidx.appcompat:appcompat:1.0.0"
110
111 implementation 'com.facebook.fresco:fresco:2.4.0'
112 implementation 'com.facebook.fresco:animated-gif:2.4.0'
113 implementation 'com.facebook.fresco:webpsupport:2.4.0'
114}
115
116// Run this once to be able to run the application with BUCK
117// puts all compile dependencies into folder libs for BUCK to use
118task copyDownloadableDepsToLibs(type: Copy) {
119 from configurations.compile
120 into 'libs'
121}
122
123apply plugin: 'com.google.gms.google-services'
124
125apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
126
Let me know if I've missed something obvious. I am definitely more experienced in iOS-development, so it is very possible that I missed something :-)
ANSWER
Answered 2021-Aug-24 at 17:29How do I display an animated gif in React Native?
add android/app/build.gradle
1apply plugin: "com.android.application"
2
3import com.android.build.OutputFile
4
5
6project.ext.react = [
7 enableHermes: false, // clean and rebuild if changing
8]
9
10apply from: "../../node_modules/react-native/react.gradle"
11
12
13def enableSeparateBuildPerCPUArchitecture = false
14def enableProguardInReleaseBuilds = false
15def jscFlavor = 'org.webkit:android-jsc:+'
16def enableHermes = project.ext.react.get("enableHermes", false);
17
18android {
19 ndkVersion rootProject.ext.ndkVersion
20
21 compileSdkVersion rootProject.ext.compileSdkVersion
22
23 defaultConfig {
24 applicationId "com.example.app"
25 minSdkVersion rootProject.ext.minSdkVersion
26 targetSdkVersion rootProject.ext.targetSdkVersion
27 versionCode 1
28 versionName "1.0"
29 }
30 splits {
31 abi {
32 reset()
33 enable enableSeparateBuildPerCPUArchitecture
34 universalApk false // If true, also generate a universal APK
35 include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
36 }
37 }
38 signingConfigs {
39 debug {
40 storeFile file('debug.keystore')
41 storePassword 'android'
42 keyAlias 'androiddebugkey'
43 keyPassword 'android'
44 }
45 }
46 buildTypes {
47 debug {
48 signingConfig signingConfigs.debug
49 }
50 release {
51 // Caution! In production, you need to generate your own keystore file.
52 // see https://reactnative.dev/docs/signed-apk-android.
53 signingConfig signingConfigs.debug
54 minifyEnabled enableProguardInReleaseBuilds
55 proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
56 }
57 }
58
59 // applicationVariants are e.g. debug, release
60 applicationVariants.all { variant ->
61 variant.outputs.each { output ->
62 // For each separate APK per architecture, set a unique version code as described here:
63 // https://developer.android.com/studio/build/configure-apk-splits.html
64 // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc.
65 def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4]
66 def abi = output.getFilter(OutputFile.ABI)
67 if (abi != null) { // null for the universal-debug, universal-release variants
68 output.versionCodeOverride =
69 defaultConfig.versionCode * 1000 + versionCodes.get(abi)
70 }
71
72 }
73 }
74}
75
76dependencies {
77
78 implementation fileTree(dir: "libs", include: ["*.jar"])
79 //noinspection GradleDynamicVersion
80 implementation "com.facebook.react:react-native:+" // From node_modules
81
82 implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"
83
84 debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
85 exclude group:'com.facebook.fbjni'
86 }
87
88 debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
89 exclude group:'com.facebook.flipper'
90 exclude group:'com.squareup.okhttp3', module:'okhttp'
91 }
92
93 debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
94 exclude group:'com.facebook.flipper'
95 }
96
97 if (enableHermes) {
98 def hermesPath = "../../node_modules/hermes-engine/android/";
99 debugImplementation files(hermesPath + "hermes-debug.aar")
100 releaseImplementation files(hermesPath + "hermes-release.aar")
101 } else {
102 implementation jscFlavor
103 }
104
105
106 implementation project(':react-native-notifications')
107 implementation 'com.google.firebase:firebase-core:16.0.0'
108 implementation 'com.google.android.gms:play-services-ads:19.8.0'
109 implementation "androidx.appcompat:appcompat:1.0.0"
110
111 implementation 'com.facebook.fresco:fresco:2.4.0'
112 implementation 'com.facebook.fresco:animated-gif:2.4.0'
113 implementation 'com.facebook.fresco:webpsupport:2.4.0'
114}
115
116// Run this once to be able to run the application with BUCK
117// puts all compile dependencies into folder libs for BUCK to use
118task copyDownloadableDepsToLibs(type: Copy) {
119 from configurations.compile
120 into 'libs'
121}
122
123apply plugin: 'com.google.gms.google-services'
124
125apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
126 // For animated GIF support
127 compile 'com.facebook.fresco:animated-gif:1.+'
128
QUESTION
Decorators and Private fields javascript
Asked 2021-Oct-31 at 15:14I find myself trying to use decorators with the native javascript private properties (#) and these first 'recognize' that are in use do not work.
I identified this by using the class-validator decorators on the private properties of my value objects.
The error I get in my code editor is: Decorators are not valid here
Example:
1import { IsString } from 'class-validator';
2
3Class Person {
4 @IsString()
5 #name: string;
6
7 constructor(name: string) {
8 this.#name = name;
9 }
10
11 get name(): string {
12 return this.#name;
13 }
14}
15
ANSWER
Answered 2021-Oct-31 at 15:14Okey as suggested by VLAZ:
Private fields in JS are completely private and inaccessible to anything from outside. Thus it makes sense they cannot be decorated - there is no way for the decorator to access them.
This is completely correct, so when I took a closer look at the value object I realized that it does have public get
properties, so by testing it is possible to use decorators on those properties.
Leaving something like:
1import { IsString } from 'class-validator';
2
3Class Person {
4 @IsString()
5 #name: string;
6
7 constructor(name: string) {
8 this.#name = name;
9 }
10
11 get name(): string {
12 return this.#name;
13 }
14}
15import { IsString } from 'class-validator';
16
17Class Person {
18 #name: string;
19
20 constructor(name: string) {
21 this.#name = name;
22 }
23
24 @IsString()
25 get name(): string {
26 return this.#name;
27 }
28}
29
QUESTION
Zooming in does not adapt date axis when using Julia's PlotlyJS in VSCode
Asked 2021-Oct-15 at 23:06I am using Plots.plot
along with PlotlyJS to display a time-series in the VSCode editor as follows:
1using Plots
2using PlotlyJS
3...
4plotlyjs()
5plot = Plots.plot(dates, y)
6display(plot)
7
So while the plot is "interactive" the dates do not adapt dynamically to the selected region. Here is a quick video of the issue I'm facing. Ideally I want the dates to display in a nice way every time I am zooming in (or out), and not just being fixed once at initial creation.
How can this be achieved?
ANSWER
Answered 2021-Oct-15 at 23:06Your problem is close to Github issue 1382. The issue was that Plots
calculates the ticks before sending it to the backend via plotlyjs()
, so the ticks end up "frozen" even if the backend is normally adaptive. They implemented an argument ticks = :native
(issue 1395) to fix this, but be aware that it doesn't work well with some arguments, which is why it's not the default (issue 1425, issue 3263).
An example of its usage from issue 1395:
1using Plots
2using PlotlyJS
3...
4plotlyjs()
5plot = Plots.plot(dates, y)
6display(plot)
7using Plots; plotly()
8plot(rand(10), ticks = :native)
9
QUESTION
TypeScript errors when editing old Vue 3 components but not on new components
Asked 2021-Oct-15 at 04:23I'm trying to convert my Vue 3 single page component scripts to use TypeScript.
When I create a brand new Test.vue
component that looks like this, I get no TypeScript errors my Visual Studio Code editor:
1<script lang="ts">
2import { defineComponent, inject, ref } from "vue";
3export default defineComponent({
4 //Some code here
5});
6</script>
7
This is as expected because my code conforms to the Vue 3 TypeScipt docs.
But when I convert my other existing ExternalApi.vue
component to the same thing I am seeing errors on defineComponent
, inject
, and ref
:
Module '"vue"' has no exported member 'XXXX'. Did you mean to use 'import XXXX from "vue"' instead?
So why does a brand new Test.vue
component work but not the edited ExternalApi.vue
component?
Here is the full ExternalApi.vue
component I am trying to convert to TypeScript:
1<script lang="ts">
2import { defineComponent, inject, ref } from "vue";
3export default defineComponent({
4 //Some code here
5});
6</script>
7<template>
8 <div>
9 <div class="mb-5">
10 <h1>External API</h1>
11 <p>
12 Call Fauna.
13 </p>
14
15 <button class="btn btn-primary m-5" @click.prevent="callApi">
16 Call API
17 </button>
18 <label for="product-name">Product Name:</label>
19 <input
20 type="text"
21 v-model="productValue"
22 id="product-name"
23 name="product-name"
24 /><br /><br />
25 <button class="btn btn-primary m-5" @click.prevent="createProduct">
26 Create Product
27 </button>
28 </div>
29
30 <div class="result-block-container">
31 <div :class="['result-block', executed ? 'show' : '']">
32 <h6 class="muted">Result</h6>
33 {{ JSON.stringify(apiMessage, null, 2) }}
34 </div>
35 </div>
36 </div>
37</template>
38
39<script lang="ts">
40import { defineComponent, inject, ref } from "vue";
41import { query as q, Client } from "faunadb";
42
43export default defineComponent({
44 name: "Api",
45 setup() {
46 let productValue = ref("");
47 let apiMessage = ref(null);
48 let executed = ref(false);
49 const auth = inject("Auth");
50
51 const callApi = async () => {
52 const accessToken = await auth.getTokenSilently();
53 try {
54 const client = new Client({
55 secret: accessToken,
56 domain: "db.us.fauna.com",
57 port: 443,
58 scheme: "https",
59 });
60 const { Paginate, Documents, Collection } = q;
61
62 const data = await client.query(
63 Paginate(Documents(Collection("products")))
64 );
65 console.log(accessToken);
66 console.log(data);
67 apiMessage.value = data;
68 executed.value = true;
69 } catch (e) {
70 console.log(e);
71 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
72 }
73 };
74
75 const createProduct = async () => {
76 const accessToken = await auth.getTokenSilently();
77 try {
78 const client = new Client({
79 secret: accessToken,
80 domain: "db.us.fauna.com",
81 port: 443,
82 scheme: "https",
83 });
84 const { Create, Collection, CurrentIdentity } = q;
85
86 const data = await client.query(
87 Create(Collection("products"), {
88 data: {
89 name: productValue.value,
90 owner: CurrentIdentity(),
91 },
92 })
93 );
94 console.log("productValue data", data);
95 } catch (e) {
96 console.log(e);
97 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
98 }
99 };
100
101 return {
102 callApi,
103 createProduct,
104 apiMessage,
105 executed,
106 productValue,
107 };
108 },
109});
110</script>
111
On top of that, when compiling via npm run serve
the terminal throws the same errors for both Test.vue
and ExternalApi.vue
.
But it should not be showing errors at all because both of them conform to the Vue docs.
So what is going on here?
UPDATE:
This is what my shims-vue.d.ts
file contains. I'm not actually sure what this file does, but it was in the cloned repo:
1<script lang="ts">
2import { defineComponent, inject, ref } from "vue";
3export default defineComponent({
4 //Some code here
5});
6</script>
7<template>
8 <div>
9 <div class="mb-5">
10 <h1>External API</h1>
11 <p>
12 Call Fauna.
13 </p>
14
15 <button class="btn btn-primary m-5" @click.prevent="callApi">
16 Call API
17 </button>
18 <label for="product-name">Product Name:</label>
19 <input
20 type="text"
21 v-model="productValue"
22 id="product-name"
23 name="product-name"
24 /><br /><br />
25 <button class="btn btn-primary m-5" @click.prevent="createProduct">
26 Create Product
27 </button>
28 </div>
29
30 <div class="result-block-container">
31 <div :class="['result-block', executed ? 'show' : '']">
32 <h6 class="muted">Result</h6>
33 {{ JSON.stringify(apiMessage, null, 2) }}
34 </div>
35 </div>
36 </div>
37</template>
38
39<script lang="ts">
40import { defineComponent, inject, ref } from "vue";
41import { query as q, Client } from "faunadb";
42
43export default defineComponent({
44 name: "Api",
45 setup() {
46 let productValue = ref("");
47 let apiMessage = ref(null);
48 let executed = ref(false);
49 const auth = inject("Auth");
50
51 const callApi = async () => {
52 const accessToken = await auth.getTokenSilently();
53 try {
54 const client = new Client({
55 secret: accessToken,
56 domain: "db.us.fauna.com",
57 port: 443,
58 scheme: "https",
59 });
60 const { Paginate, Documents, Collection } = q;
61
62 const data = await client.query(
63 Paginate(Documents(Collection("products")))
64 );
65 console.log(accessToken);
66 console.log(data);
67 apiMessage.value = data;
68 executed.value = true;
69 } catch (e) {
70 console.log(e);
71 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
72 }
73 };
74
75 const createProduct = async () => {
76 const accessToken = await auth.getTokenSilently();
77 try {
78 const client = new Client({
79 secret: accessToken,
80 domain: "db.us.fauna.com",
81 port: 443,
82 scheme: "https",
83 });
84 const { Create, Collection, CurrentIdentity } = q;
85
86 const data = await client.query(
87 Create(Collection("products"), {
88 data: {
89 name: productValue.value,
90 owner: CurrentIdentity(),
91 },
92 })
93 );
94 console.log("productValue data", data);
95 } catch (e) {
96 console.log(e);
97 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
98 }
99 };
100
101 return {
102 callApi,
103 createProduct,
104 apiMessage,
105 executed,
106 productValue,
107 };
108 },
109});
110</script>
111/* eslint-disable */
112declare module '*.vue' {
113 import type { DefineComponent } from 'vue'
114 const component: DefineComponent<{}, {}, any>
115 export default component
116}
117
And this is my package.json
file:
1<script lang="ts">
2import { defineComponent, inject, ref } from "vue";
3export default defineComponent({
4 //Some code here
5});
6</script>
7<template>
8 <div>
9 <div class="mb-5">
10 <h1>External API</h1>
11 <p>
12 Call Fauna.
13 </p>
14
15 <button class="btn btn-primary m-5" @click.prevent="callApi">
16 Call API
17 </button>
18 <label for="product-name">Product Name:</label>
19 <input
20 type="text"
21 v-model="productValue"
22 id="product-name"
23 name="product-name"
24 /><br /><br />
25 <button class="btn btn-primary m-5" @click.prevent="createProduct">
26 Create Product
27 </button>
28 </div>
29
30 <div class="result-block-container">
31 <div :class="['result-block', executed ? 'show' : '']">
32 <h6 class="muted">Result</h6>
33 {{ JSON.stringify(apiMessage, null, 2) }}
34 </div>
35 </div>
36 </div>
37</template>
38
39<script lang="ts">
40import { defineComponent, inject, ref } from "vue";
41import { query as q, Client } from "faunadb";
42
43export default defineComponent({
44 name: "Api",
45 setup() {
46 let productValue = ref("");
47 let apiMessage = ref(null);
48 let executed = ref(false);
49 const auth = inject("Auth");
50
51 const callApi = async () => {
52 const accessToken = await auth.getTokenSilently();
53 try {
54 const client = new Client({
55 secret: accessToken,
56 domain: "db.us.fauna.com",
57 port: 443,
58 scheme: "https",
59 });
60 const { Paginate, Documents, Collection } = q;
61
62 const data = await client.query(
63 Paginate(Documents(Collection("products")))
64 );
65 console.log(accessToken);
66 console.log(data);
67 apiMessage.value = data;
68 executed.value = true;
69 } catch (e) {
70 console.log(e);
71 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
72 }
73 };
74
75 const createProduct = async () => {
76 const accessToken = await auth.getTokenSilently();
77 try {
78 const client = new Client({
79 secret: accessToken,
80 domain: "db.us.fauna.com",
81 port: 443,
82 scheme: "https",
83 });
84 const { Create, Collection, CurrentIdentity } = q;
85
86 const data = await client.query(
87 Create(Collection("products"), {
88 data: {
89 name: productValue.value,
90 owner: CurrentIdentity(),
91 },
92 })
93 );
94 console.log("productValue data", data);
95 } catch (e) {
96 console.log(e);
97 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
98 }
99 };
100
101 return {
102 callApi,
103 createProduct,
104 apiMessage,
105 executed,
106 productValue,
107 };
108 },
109});
110</script>
111/* eslint-disable */
112declare module '*.vue' {
113 import type { DefineComponent } from 'vue'
114 const component: DefineComponent<{}, {}, any>
115 export default component
116}
117{
118 "name": "replicator",
119 "version": "0.1.0",
120 "private": true,
121 "scripts": {
122 "serve": "vue-cli-service serve --port 3000",
123 "build": "vue-cli-service build"
124 },
125 "dependencies": {
126 "@auth0/auth0-spa-js": "^1.13.6",
127 "@fortawesome/fontawesome-svg-core": "^1.2.32",
128 "@fortawesome/free-solid-svg-icons": "^5.15.1",
129 "@fortawesome/vue-fontawesome": "3.0.0-3",
130 "ansi-html": "^0.0.7",
131 "axios": "^0.21.1",
132 "core-js": "^3.6.5",
133 "element-plus": "^1.0.2-beta.28",
134 "faunadb": "^4.4.1",
135 "glob-parent": "^6.0.2",
136 "set-value": "^4.1.0",
137 "vue": "^3.2.20",
138 "vue-router": "^4.0.11",
139 "vue-template-compiler": "^2.6.14",
140 "vuex": "^4.0.0-0"
141 },
142 "devDependencies": {
143 "@vue/cli-plugin-babel": "^4.5.13",
144 "@vue/cli-plugin-router": "4.5.13",
145 "@vue/cli-plugin-typescript": "^4.5.13",
146 "@vue/cli-plugin-vuex": "~4.5.0",
147 "@vue/cli-service": "^4.5.13",
148 "@vue/compiler-sfc": "^3.0.0",
149 "sass": "^1.32.7",
150 "sass-loader": "7.3.1",
151 "stylus": "^0.54.7",
152 "stylus-loader": "^3.0.2",
153 "typescript": "~3.9.3",
154 "vue-cli-plugin-element-plus": "~0.0.13"
155 }
156}
157
ANSWER
Answered 2021-Oct-15 at 03:13This error can appear if you're trying to use the Vue 3 composition API, but you have Vue 2 installed. Currently if you run npm install vue
you'll get version 2; you need to run npm install vue@next
to get version 3.
If you want to use version 2, the basic TypeScript approach for component definition is instead like this:
1<script lang="ts">
2import { defineComponent, inject, ref } from "vue";
3export default defineComponent({
4 //Some code here
5});
6</script>
7<template>
8 <div>
9 <div class="mb-5">
10 <h1>External API</h1>
11 <p>
12 Call Fauna.
13 </p>
14
15 <button class="btn btn-primary m-5" @click.prevent="callApi">
16 Call API
17 </button>
18 <label for="product-name">Product Name:</label>
19 <input
20 type="text"
21 v-model="productValue"
22 id="product-name"
23 name="product-name"
24 /><br /><br />
25 <button class="btn btn-primary m-5" @click.prevent="createProduct">
26 Create Product
27 </button>
28 </div>
29
30 <div class="result-block-container">
31 <div :class="['result-block', executed ? 'show' : '']">
32 <h6 class="muted">Result</h6>
33 {{ JSON.stringify(apiMessage, null, 2) }}
34 </div>
35 </div>
36 </div>
37</template>
38
39<script lang="ts">
40import { defineComponent, inject, ref } from "vue";
41import { query as q, Client } from "faunadb";
42
43export default defineComponent({
44 name: "Api",
45 setup() {
46 let productValue = ref("");
47 let apiMessage = ref(null);
48 let executed = ref(false);
49 const auth = inject("Auth");
50
51 const callApi = async () => {
52 const accessToken = await auth.getTokenSilently();
53 try {
54 const client = new Client({
55 secret: accessToken,
56 domain: "db.us.fauna.com",
57 port: 443,
58 scheme: "https",
59 });
60 const { Paginate, Documents, Collection } = q;
61
62 const data = await client.query(
63 Paginate(Documents(Collection("products")))
64 );
65 console.log(accessToken);
66 console.log(data);
67 apiMessage.value = data;
68 executed.value = true;
69 } catch (e) {
70 console.log(e);
71 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
72 }
73 };
74
75 const createProduct = async () => {
76 const accessToken = await auth.getTokenSilently();
77 try {
78 const client = new Client({
79 secret: accessToken,
80 domain: "db.us.fauna.com",
81 port: 443,
82 scheme: "https",
83 });
84 const { Create, Collection, CurrentIdentity } = q;
85
86 const data = await client.query(
87 Create(Collection("products"), {
88 data: {
89 name: productValue.value,
90 owner: CurrentIdentity(),
91 },
92 })
93 );
94 console.log("productValue data", data);
95 } catch (e) {
96 console.log(e);
97 apiMessage = `Error: the server responded with '${e.response.status}: ${e.response.statusText}'`;
98 }
99 };
100
101 return {
102 callApi,
103 createProduct,
104 apiMessage,
105 executed,
106 productValue,
107 };
108 },
109});
110</script>
111/* eslint-disable */
112declare module '*.vue' {
113 import type { DefineComponent } from 'vue'
114 const component: DefineComponent<{}, {}, any>
115 export default component
116}
117{
118 "name": "replicator",
119 "version": "0.1.0",
120 "private": true,
121 "scripts": {
122 "serve": "vue-cli-service serve --port 3000",
123 "build": "vue-cli-service build"
124 },
125 "dependencies": {
126 "@auth0/auth0-spa-js": "^1.13.6",
127 "@fortawesome/fontawesome-svg-core": "^1.2.32",
128 "@fortawesome/free-solid-svg-icons": "^5.15.1",
129 "@fortawesome/vue-fontawesome": "3.0.0-3",
130 "ansi-html": "^0.0.7",
131 "axios": "^0.21.1",
132 "core-js": "^3.6.5",
133 "element-plus": "^1.0.2-beta.28",
134 "faunadb": "^4.4.1",
135 "glob-parent": "^6.0.2",
136 "set-value": "^4.1.0",
137 "vue": "^3.2.20",
138 "vue-router": "^4.0.11",
139 "vue-template-compiler": "^2.6.14",
140 "vuex": "^4.0.0-0"
141 },
142 "devDependencies": {
143 "@vue/cli-plugin-babel": "^4.5.13",
144 "@vue/cli-plugin-router": "4.5.13",
145 "@vue/cli-plugin-typescript": "^4.5.13",
146 "@vue/cli-plugin-vuex": "~4.5.0",
147 "@vue/cli-service": "^4.5.13",
148 "@vue/compiler-sfc": "^3.0.0",
149 "sass": "^1.32.7",
150 "sass-loader": "7.3.1",
151 "stylus": "^0.54.7",
152 "stylus-loader": "^3.0.2",
153 "typescript": "~3.9.3",
154 "vue-cli-plugin-element-plus": "~0.0.13"
155 }
156}
157<script lang="ts">
158import Vue from 'vue'
159
160export default Vue.extend({
161 // type inference enabled
162})
163</script>
164
I recommend trying vue-class-component and vue-property-decorator if you want to use TypeScript with Vue 2, they're really great!
Community Discussions contain sources that include Stack Exchange Network