Syntax Error: TypeError: Cannot read property 'kind' of null for Enum using Vue 3 and TypeScript - node.js

I'm defining an enum within a Vue 3 component like so:
<script lang="ts">
import { defineComponent } from 'vue'
export enum PieceType
{
None,
Pawn,
Rook,
Knight,
Bishop,
Queen,
King
}
export interface Piece
{
position: Position,
type: PieceType,
}
export interface Position
{
row: number,
col: number
}
export default defineComponent({
props: {
type: String,
row: Number,
col: Number
},
setup(props) {
const getPiece = (piece: string) =>
{
console.log("Piece is:", piece)
switch(piece)
{
case "R": return PieceType.Rook;
case "K": return PieceType.Knight;
case "B": return PieceType.Bishop;
case "Q": return PieceType.Queen;
case "K": return PieceType.King;
case "P": return PieceType.Pawn;
case "-": return PieceType.None;
default: throw new Error("Invalid piece.")
}
}
return {
type: getPiece(props.type),
position: {row: props.row, col: props.col}
}
}
})
</script>
When I import the component into another component (the component equals Piece):
<script lang="ts">
import { defineComponent } from '#vue/composition-api';
import { Piece } from "../components/Piece";
export default defineComponent({
components: [Piece],
props: {
},
setup() {
const board =
[
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['-', '-', '-', '-', '-', '-', '-', '-'],
['P', 'P', 'P', 'P', 'P', 'P', 'P', 'P'],
['R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
];
return { board }
}
})
</script>
I get the following error:
Syntax Error: TypeError: Cannot read property 'kind' of null
Occurred while linting > .\components\Piece.vue:39
at Array.forEach (<anonymous>)
at Array.forEach (<anonymous>)
# ./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/components/Board.vue?vue&type=script&lang=ts 3:0-44 6:15-20
# ./src/components/Board.vue?vue&type=script&lang=ts
# ./src/components/Board.vue
# ./node_modules/cache-loader/dist/cjs.js??ref--12-0!./node_modules/babel-loader/lib!./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader-v16/dist??ref--0-1!./src/App.vue?vue&type=script&lang=js
# ./src/App.vue?vue&type=script&lang=js
# ./src/App.vue
# ./src/main.js
# multi (webpack)-dev-server/client?http://192.168.3.235:8080&sockPath=/sockjs-node (webpack)/hot/dev-server.js ./src/main.js
The error is occurring at the line:
case "R": return PieceType.Rook
I noticed that if I get rid of the Enum and replace it with strings then it works, but I don't see why the Enum isn't working. The error isn't showing up in my intellisense in vscode and I'm not using the component in a for loop anywhere to trigger the "Array.ForEach" in the error. Any help would be appreciated!

My issue was I didn't run "vue add typescript" to add typescript to the project. I had other issues with how I declared the components, but that was ultimately the issue.

Related

password generator with logging

import random, logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
file_handler = logging.FileHandler('student.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
mylist = ['Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Gg', 'Hh', 'Ii', 'Jj', 'Kk', 'Ll', 'Mm', 'Nn',
'Oo', 'Pp', 'Qq', 'Rr', 'Ss', 'Tt', 'Uu', 'Vv', 'Ww', 'Xx', 'Yy', 'Zz', '1', '2', '3', '4', '5', '6', '7', '8',
'9', '0', '!', '#', '#', '$', '%', '^', '&', '*', '~']
def generatePassword(num):
password = ''
for x in range(mylist):
return password
logging.debug(generatePassword,16)
When I execute the code, complier says that x is an unused variable. Is there a way to fix this? Also, is there any error with how I wrote the logging functions?
You are currently not using x inside your loop, hence the unused variable warning.
Regardless, consider using random.choices if you want to allow the password to possibly contain the same character twice or or random.sample if you don't:
import random
def generate_password(length, unique_chars_ignore_case=False):
my_list = [
'Aa', 'Bb', 'Cc', 'Dd', 'Ee', 'Ff', 'Gg', 'Hh', 'Ii', 'Jj', 'Kk', 'Ll',
'Mm', 'Nn', 'Oo', 'Pp', 'Qq', 'Rr', 'Ss', 'Tt', 'Uu', 'Vv', 'Ww', 'Xx',
'Yy', 'Zz', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '!', '#',
'#', '$', '%', '^', '&', '*', '~'
]
random_func = random.choices if not unique_chars_ignore_case else random.sample
return ''.join([
x if len(x) == 1 else x[random.randint(0, 1)]
for x in random_func(my_list, k=length)
])
Example Usage allows repeats:
>>> generate_password(6)
C9#cs2
Example Usage only unique characters ignore case:
>>> generate_password(6, unique_chars_ignore_case=True))
k*065#

How to fetch the action value from AWS policy document and store it as list?

I need to fetch "Action" values from the AWS policy document.
In some policies, the action values are having a list of values(like Policy 1) and in some policies, the action is having a single value which is a string (like Policy 2).
What I need is:
I want to get the action value from the policy and store it as a list.
(Here, Policy 1 is giving expected output but policy 2 is failing.)
Policy 1:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
Output - Policy 1:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed','iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
Policy 2:
document_values:
[{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*"}]}]
Output-Policy2:
['s', 't', 's', ':', 'A', 's', 's', 'u', 'm', 'e', 'R', 'o', 'l', 'e']
Expected output from policy2:
['sts:AsseumeRole']
Python-Code:
I'm executing the same code for both the policies.
inline_services = [j for i in [i['Action'] for i in document_values[0]['Statement']] for j in i]
print(inline_services)
How to fetch the action value from the policy document irrespective of string or list..?
Instead of writing long list comprehension, you could just create simple function:
p1 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': ['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed'],'Resource': ['arn:aws:iam::*:policy/*','arn:aws:iam::*:instance-profile/*']}, {'Sid': 'VisualEditor1', 'Effect': 'Allow', 'Action': ['iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups'],'Resource': '*'}]}]
p2 = [{'Version': '2012-10-17', 'Statement': [{'Sid': 'VisualEditor0', 'Effect': 'Allow', 'Action': 'sts:AssumeRole', 'Resource':'*'}]}]
def get_actions(policy_doc):
actions_list = []
for i in policy_doc[0]['Statement']:
actions_list += i['Action'] if isinstance(i['Action'], list) else [i['Action']]
return actions_list
print(get_actions(p1))
print(get_actions(p2))
Output:
['iam:CreateInstanceProfile', 'iam:DeleteInstanceProfile', 'iam:GetRole', 'iam:GetInstanceProfile', 'iam:GetPolicy', 'iam:ListGroupPolicies', 'iam:GetAccessKeyLastUsed', 'iam:ListPolicies', 'iam:ListRoles', 'iam:ListGroups']
['sts:AssumeRole']

AWK + gsub - how to round floating number

Do you have an idea of how I can round float numbers after multiplying?
I have the following SQL dump:
INSERT INTO
`honzavolfcz_product` (`product_id`, `feed_product_id`, `import_id`,
`import_active_product`, `model`, `sku`, `upc`, `ean`, `jan`, `isbn`, `mpn`,
`location`, `quantity`, `stock_status_id`, `product_status_id`, `image`,
`manufacturer_id`, `shipping`, `price`, `points`, `tax_class_id`,
`date_available`, `weight`, `weight_class_id`, `length`, `width`, `height`,
`length_class_id`, `subtract`, `minimum`, `sort_order`, `status`, `date_added`,
`date_modified`, `viewed`)
VALUES ('10', '0', '1',
'1', 'model', '', '', '', '', '', '',
'', '1', '1', '0', 'catalog/zbozi/bozi_laska_obal.jpg',
'0', '1', '**112.50**', '0', '1',
'2019-01-15', '0.00', '1', '0.00', '0.00', '0.00',
'1', '0', '1', '0', '1', '2019-02-15 16:16:29',
'2019-02-15 16:16:29', '293');
And I want to multiply the price value (112.50) by 1.21 (taxes) and the round-up or down. I wrote the following command which does the multiplication but I do not know how to round it:
awk '{a=substr($58,2,length($58)-3);gsub(a,a*1.21);print}' a > b
The result:
INSERT INTO
`honzavolfcz_product` (`product_id`, `feed_product_id`, `import_id`,
`import_active_product`, `model`, `sku`, `upc`, `ean`, `jan`, `isbn`, `mpn`,
`location`, `quantity`, `stock_status_id`, `product_status_id`, `image`,
`manufacturer_id`, `shipping`, `price`, `points`, `tax_class_id`,
`date_available`, `weight`, `weight_class_id`, `length`, `width`, `height`,
`length_class_id`, `subtract`, `minimum`, `sort_order`, `status`, `date_added`,
`date_modified`, `viewed`)
VALUES ('10', '0', '1',
'1', 'model', '', '', '', '', '', '',
'', '1', '1', '0', 'catalog/zbozi/bozi_laska_obal.jpg',
'0', '1', '**136.125**', '0', '1',
'2019-01-15', '0.00', '1', '0.00', '0.00', '0.00',
'1', '0', '1', '0', '1', '2019-02-15 16:16:29',
'2019-02-15 16:16:29', '293');
I would like to have there 136 instead of 136.125. Of course, 137 if it would be 136.555.
Thank you in advance.
This may be what you want:
$ awk '{a=substr($58,2); $58=sprintf("\047%d\047,",a*1.21)} 1' file
INSERT INTO honzavolfcz_product (product_id, feed_product_id, import_id, import_active_product, model, sku, upc, ean, jan, isbn, mpn, location, quantity, stock_status_id, product_status_id, image, manufacturer_id, shipping, price, points, tax_class_id, date_available, weight, weight_class_id, length, width, height, length_class_id, subtract, minimum, sort_order, status, date_added, date_modified, viewed) VALUES ('10', '0', '1', '1', 'model', '', '', '', '', '', '', '', '1', '1', '0', 'catalog/zbozi/bozi_laska_obal.jpg', '0', '1', '136', '0', '1', '2019-01-15', '0.00', '1', '0.00', '0.00', '0.00', '1', '0', '1', '0', '1', '2019-02-15 16:16:29', '2019-02-15 16:16:29', '293');
but the rounding probably won't go quite as you'd like by default. See https://www.gnu.org/software/gawk/manual/gawk.html#Round-Function and https://www.gnu.org/software/gawk/manual/gawk.html#Setting-the-rounding-mode for how to control it with GNU awk.

how to make parse of list(string) not list(char) in parse argument of list?

I use flask_restful in flask
My code like:
from flask_restful import Resource, reqparse
apilink_parser = reqparse.RequestParser()
apilink_parser.add_argument('provider_id', type=int,required=True)
apilink_parser.add_argument('name', type=str, required=True)
apilink_parser.add_argument('func_id', type=int)
apilink_parser.add_argument('method', type=str)
apilink_parser.add_argument('url', type=str)
apilink_parser.add_argument('parameter',type=list)
apilink_parser.add_argument("expectreturn", type=list)
#marshal_with(apilink_fields)
def post(self):
args = apilink_parser.parse_args()
print(args)
# user owns the task
task = APILink.create(**args)
return task, 201
My json post data like:
{
"name":"riskiqwhois",
"provider_id":1,
"func_id":1,
"url":"myurl",
"parameter":["query"], //******//
"expectreturn":[],
"method":"post"
}
but when I print the arrgs the result is:
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['q', 'u', 'e', 'r', 'y'], //******//
'expectreturn': None
}
I want
You can see I want parameter is list of string which is only one element named "query", but the real parameter tranlate into the database is ['q', 'u', 'e', 'r', 'y'], How to make the parameter is list of string not list of char? how to make sure the data is list(string)?
Well, you forgot to set action="append" and you should change from type=list to type=str.
If not, you will still be getting a result like [['q', 'u', 'e', 'r', 'y']].
...
apilink_parser.add_argument('parameter',type=str, action='append')
apilink_parser.add_argument("expectreturn", type=str, action='append')
You can solve this problem by adding action="append" to your request parser
like below
apilink_parser.add_argument('parameter',type=str,action="append")
apilink_parser.add_argument("expectreturn", type=list,action="append")
this will return you below output
{
'provider_id': 1,
'name': 'riskiqwhois',
'func_id': 1,
'method': 'post',
'url': 'myurl',
'parameter': ['query'],
'expectreturn': None
}

ANTLR4 extraneous input

I have a problem with my ANTLR4. I'm trying to print AST from python 3 code but there are some errors and I don't know how to fix them.
I wrote simple code for test:
a=(1,2,3)
print(a)
I ran the program but this errors appeared:
line 1:1 extraneous input '=' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
line 2:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
line 3:0 extraneous input '\n' expecting {<EOF>, '.', '*', '(', '**', '[', '|', '^', '&', '<<', '>>', '+', '-', '/', '%', '//', '#'}
My main class :
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;
import org.antlr.v4.*;
public class Main {
public static void main(String[] args) {
try {
ANTLRInputStream input = new ANTLRFileStream("/home/grzegorz/Desktop/Python3/input.txt");
Python3Lexer lexer = new Python3Lexer(input);
CommonTokenStream token = new CommonTokenStream(lexer);
Python3Parser parser = new Python3Parser(token);
ParseTree parseTree = parser.expr();
System.out.println(parseTree.toStringTree(parser));
}catch (Exception ex){
ex.printStackTrace();
}
}
}
I have the grammar from this site:
https://github.com/antlr/grammars-v4/tree/master/python3
Explanation
Your input file consists of two statements and you are parsing the file as if it was an expression (with line ParseTree parseTree = parser.expr();; rule expr from Python 3 grammar).
This also exaplains the first error: an identificator a is accepted as a part of expression but = sign is not. That's because = is a part of assignment statement.
Solution
Parse the input using another grammar rule for example file_input rule which will accept many statements. Change the abovementioned line to ParseTree parseTree = parser.file_input();.

Resources