Author Archives: adminah

Xlua#: How to Call C

Call C in xlua#

1. Premise

The xlua framework is used here. You need to configure xlua in advance and set the loader path;

You can refer to the previous blog: xlua introduction;

//On the call side, all the lua code is written in the LuaCallCSharp.lua file
public class LuaCallCSharp1 : MonoBehaviour
{
    void Start()
    {
        XluaEnv.I.DoString("LuaCallCSharp");
    }

    private void OnDestroy()
    {
        XluaEnv.I.Free();
    }
}

2. Call c# class

Static class

public static class TestStatic
{
    public static void ShowName(string name, int id)
    {
        Debug.Log($"name:{name},id:{id}");
    }
}

--静态类
CS.TestStatic.ShowName("littlePerilla",1012);

Dynamic class

public class NPC
{
    public string name;
    public int attack;

    public NPC(string name,int attack)
    {
        this.name = name;
        this.attack = attack;
    }

    public int Hp { get; set; }

    public void Attack()
    {
        Debug.Log($"attack:{attack},Hp:{Hp}");
    }
}

--类对象
local hero = CS.NPC("Angel",100)
hero.Hp = 110
hero:Attack()

Call unity official API

--创建物体
local go = CS.UnityEngine.GameObject("LuaObj ")
--添加组件
go:AddComponent(typeof(CS.UnityEngine.BoxCollider))

Lua does not support generics. You need to write every possible overload where generics are used;

Call parent and child classes

public class Father
{
    public string name = "father";

    public virtual void Say()
    {
        Debug.Log($"{name}:我在被调用");
    }
}

public class Child :Father
{
    public string name = "child";

    public override void Say()
    {
        Debug.Log($"{name}:我在被调用");
    }
}

local father = CS.Father()
father:Say()

local child = CS.Child()
child:Say()

Class expansion method

The extended class must be a static class, and the class must have the attribute [luacallcsharp]; C# type expansion method;

It will be affected by xlua version and unity version, resulting in call failure. The official recommended version of xlua is 2017 (too outdated);

public class TestExtension
{
    public string Test1()
    {
        return "test";
    }
}

[LuaCallCSharp]
public static class MyExtension
{
    public static void Test2(this TestExtension obj)
    {
        Debug.Log("ExtensionFunc:"+ obj.Test1());
    }
}

local testEx = CS.TestExtension()

print(testEx:Test1())
testEx:Test2()

3. Call c# structure

Structures are similar to classes and have construction methods;

public struct TestStruct
{
    public int id;
    public string name;

    public void Output()
    {
        Debug.Log(id);
        Debug.Log(name);
    }
}

--结构体
local teststrut = CS.TestStruct()

teststrut.id = 12
teststrut.name = "littlePerilla"

teststrut:Output()

4. Call c# enumeration

Enumerate the userdate user-defined data types used;

public enum State
{
    idle = 0,
    walk,
    run,
    attack
}

--枚举使用的userdate自定义数据类型
local state = CS.State.idle

print(state)

--转换获得枚举
print(CS.State.__CastFrom(1))
print(CS.State.__CastFrom("run"))

5. Call the delegation in c#

Static delegate assignment call must be released;

Dynamic delegation is not necessary, but it is best to release it;

Make a null judgment before calling the delegate;

There is no + = or – = method in Lua. Multicast can only be realized through a = a + B;

public delegate void DelegateLua();

public class TestDelegate
{
    public static DelegateLua deStatic;

    public DelegateLua deDynamic;

    public static void Func()
    {
        Debug.Log("静态委托");
    }

    public void Func2()
    {
        Debug.Log("动态委托");
    }
}

--静态委托赋值调用必须释放
CS.TestDelegate.deStatic = CS.TestDelegate.Func
CS.TestDelegate.deStatic()
CS.TestDelegate.deStatic = nil

local func = function ()
	-- body
	print("lua函数替换委托")
end

--lua函数赋值委托
CS.TestDelegate.deStatic = func
--多播委托,确定deStatic不为空,lua没有+=和-=
if(CS.TestDelegate.deStatic ~= nil)then
	CS.TestDelegate.deStatic = CS.TestDelegate.deStatic + func
else 
	CS.TestDelegate.deStatic = func
end

--调用前判定不为空
if(CS.TestDelegate.deStatic ~= nil)then
	CS.TestDelegate.deStatic()
end

CS.TestDelegate.deStatic = nil
--动态委托
local test = CS.TestDelegate()

local func1 = function()
	print("动态委托调用")
end

test.deDynamic = func1
test.deDynamic()
test.deDynamic = nil

6. Call c# event

The call of events cannot be copied directly, but (“+”, function) must be used;

The event callback also needs to be released;

public delegate void EventLua();

public class TestEvent
{
    public event EventLua luaEvent1;
    
    public static event EventLua luaEvent2;

    public static void Func()
    {
        Debug.Log("静态事件");
    }

    public static void CallEvent2()
    {
        if (luaEvent2 != null)
            luaEvent2();
    }

    public void CallEvent1()
    {
        if (luaEvent1 != null)
            luaEvent1();
    }
}

--静态事件
CS.TestEvent.luaEvent2("+",CS.TestEvent.Func)
CS.TestEvent.CallEvent2()
CS.TestEvent.luaEvent2("-",CS.TestEvent.Func)


--动态事件
local test = CS.TestEvent()

local func = function ()
	print("动态事件")
end

test:luaEvent1("+",func)
test:CallEvent1()
test:luaEvent1("-",func)

DOM style setting methods in the four components of react

1. Inline style

To add inline styles to the virtual DOM, you need to use expressions to pass in style objects

An inline style needs to be written to a style object, which can be placed in many places

For example, in the render function, on the component prototype, and in the external chain JS file

Note: there are two parentheses here. The first indicates that we want to insert JS in JSX, and the second is the parenthesis of the object

 <p style={{color:'red', fontSize:'14px'}}>Hello world</p>

2. Use class

React recommends that we use inline style, because react thinks that each component is an independent whole

In fact, in most cases, we are still adding a lot of class names to elements, but it should be noted that class needs to be written as classname (because after all, we are writing class JS code, we will receive the current JS rules, and class is a keyword)

import React, { Component } from 'react'
import styles from './style.css'

class ClassStyle extends Component {
  render() {
    let className = cx({
      font: false
    })
    return (
      <>
        <div className={className}>hello</div>
        <p className='setstyle'>style</p>
        <DivContainer>
          world
        </DivContainer>
      <>
    )
  }
}

export default ClassStyle

3. Classnames add different styles for different conditions

Sometimes different styles need to be added according to different conditions, such as completion status, green for completion and red for unfinished. In this case, we recommend using the package class names:

Purpose:

Because react-native dynamically adds multiple class names, an error will be reported

import style from './style.css'
<div className={style.class1 style.class2}</div>

To get the final rendering effect:

<div class='class1 class2'></div>

Download and install

npm i -S classnames

use

import classnames from 'classnames'
<div className=classnames({
    'class1': true,
    'class2': true
    )>
</div>

4.css-in-js

styled components is a CSS in JS framework written for react, which is simply to write CSS in JS. NPM link

The traditional front-end scheme advocates the principle of “separation of concerns”. HTML, CSS and JavaScript should perform their respective duties and be separated.

In the react project, component-based scheme is advocated, which naturally forms a way of centralized writing and management of HTML, CSS and JavaScript.

styled components

should be the most popular library of CSS in JS. Through styled components, you can use the tag template string syntax of ES6 to define a series of CSS properties for the component to be styled. When the JS code of the component is parsed and executed, styled components will dynamically generate a CSS selector, The corresponding CSS style is inserted into the head tag in the form of style tag. The dynamically generated CSS selector will have a small hash value to ensure global uniqueness and avoid style conflicts.

install

npm i -S styled-components

Define style

Style JS file

import styled from 'styled-components'
const Title = styled.div`
    color:red;
    font-size:16px;
    h3{
        color:blue;
        font-size:20px;
    }
`
export {
    Title
}

Display

Use the title just as you would with a regular react component

import React, { Component } from 'react'
import { Title } from './Styles'
class App extends Component {
render() {
    return (
        <div>
            <Title>
            I'm a Title
            <h3>Hello World!</h3>
            </Title>
        </div >
        );
    }
}
export default App

Style inheritance

style

import styled from 'styled-components'
const Button = styled.button`
    font-size: 20px;
    border: 1px solid red;
    border-radius: 3px;
`;

const Button2 = styled(Button)`
    color: blue;
    border-color: yellow;
`;

export {
    Button,
    Button2
}

display

import React, { Component } from 'react'
import {
Button,
Button2
} from './Styles'
class App extends Component {
render() {
    return (
    <div>
        <Button>Button1</Button>
        <Button2>Button2</Button2>
    </div >
    );
}
}
export default App

Attribute transfer

style

import styled from 'styled-components'
const Input = styled.input`
    color: ${props => props.inputColor || "blue"};
    border-radius: 3px;
`;
export {
    Input
}

display

import React, { Component } from 'react'
import { Input } from './Styles'
class App extends Component {
render() {
    return (
    <div>
        <Input defaultValue="Hello" inputColor="red"></Input>
    </div >
    );
}
}
export default App

Seata Starup Error: nettyServer init error:ErrCode:500, ErrMsg:failed to req API:/nacos/v1/ns/instance after all servers([127.0.0.1:30099]) tried: ErrCode:503, ErrMsg:server is DOWN now, please try again later!

nettyServer init error:ErrCode:500, ErrMsg:failed to req API:/nacos/v1/ns/instance after all servers([127.0.0.1:30099]) tried: ErrCode:503, ErrMsg:server is DOWN now, please try again later!

After analysis, it may be related to the network. After disabling VMware’s virtual network card, the registration was started successfully

How to Solve MySQL Secure file priv error

Problem description

When I want to export data in mysql, I find an error. The error contents are as follows

The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

Principle interpretation

secure file priv is a system variable in MySQL that controls the operation of importing and exporting data, such as load data or select... Into output or load_FILE()

Use show global variables like 'secure_File% ' view the set value of this variable, which may have the following three values

  1. no value. That is, this variable has no effect

2﹥ point to a path. That is, import and export can only use this path

three ⃣ ️ NULL。 Import and export operations are prohibited

The default value of this system variable is different for different platforms

terms of settlement

Environment: MySQL 8.0.26 (installed with homebrew ), macbook pro 2020 Intel Edition

one ⃣ Create corresponding files, ~ /.My.CNF , and use your customary text editor. I use nano , which contains the following contents

[mysqld]
secure_file_priv = ''

two ⃣ Restart the MySQL service and log in

brew services stop mysql
brew services start mysql

mysql -uroot -p           

3﹥ check whether the modification is successful in MySQL,

show global variables like 'secure_file%';

# If the modification is successful it should display the following, showing a null value
+------------------+-------+
| Variable_name    | Value |
+------------------+-------+
| secure_file_priv |       |
+------------------+-------+
1 row in set (0.00 sec)

Done!

Link:
https://stackoverflow.com/questions/7973927/for-homebrew-mysql-installs-wheres-my-cnf
https://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html#sysvar_secure_file_priv

[Solved] Spring Boot Error: “jdbcUrl is required with driverClassName.”

Question:

After spring boot is upgraded to 2.0, an error is reported when configuring multiple data sources:

“Jdbcurl is required with driverclassname.” or cause: java.lang.illegalargumentexception: datasource or datasourceclassname or jdbcurl is required.] with root cause

The solution is as follows:

Spring boot 1.0 configures the data source as spring.datasource.url and spring.datasource.driverclassname.

Spring boot 2.0 needs to be changed to spring.datasource.jdbc-url and spring.datasource.driver-class-name

Note: use the default data source of spring boot 2.0, and configure the following spring.datasource.url and spring.datasource.driver-class-name.

The second parameter of openfit duplicate mapping and openfit interface method is bindingresult Error

Openalign duplicate mapping

Ambiguous mapping

As long as there is a controller annotation or requestmapping annotation on the class, it will be registered on both sides

APIs and subclasses are registered multiple times

Solution: move requsstmapping to a subclass method

The feign interface can use the path parameter

The second parameter of openalign interface method is bindingresult, and an error is reported

The reason is that if the second parameter is not annotated, it defaults to @requestbody

    @ApiOperation(value = "user-information-update", notes = "user-information-update", httpMethod = "POST")
    @PostMapping("/updateUserInfo")
    public GraceJSONResult updateUserInfo(@RequestBody @Valid UpdateUserBO updateUserBO, BindingResult bindingResult);

Equivalent to

    @ApiOperation(value = "user-information-update", notes = "user-information-update", httpMethod = "POST")
    @PostMapping("/updateUserInfo")
    public GraceJSONResult updateUserInfo(@RequestBody @Valid UpdateUserBO updateUserBO, @RequestBody BindingResult bindingResult);

Openalign does not allow two requestbodies

Activemq Console Error: java.lang.SecurityException: User name [system] or password is invalid.

Authentication is configured for producers and consumers in activemq.xml

<plugins>
    <simpleAuthenticationPlugin>
      <users>
          <authenticationUser username="user1" password="pas1" groups="users,admins"/>
      </users>
    </simpleAuthenticationPlugin>
</plugins>

Log in to the ActiveMQ console to view the queue, and an error is reported in the background

The error is as follows:

javax.jms.JMSSecurityException: User name [system] or password is invalid.

Screenshot of official website description

We open the configuration file webapps \ admin \ WEB-INF \ webconsole-embedded.xml to see

The user name and password used by the connection factory are stored in credentials.properties, so we add this group of accounts to the authentication list

        <plugins>
            <simpleAuthenticationPlugin>
                <users>
                    <authenticationUser username="user1" password="pas1" groups="users,admins"/>
                    <authenticationUser username="system" password="manager" groups="users,admins"/>
                </users>
            </simpleAuthenticationPlugin>
        </plugins>

Restart the service and no error will be reported

SQL Error: Table is specified twice, both as a target for ‘UPDATE’ and as a separate source for data

For example, SQL reports an error: table is specified twice, both as a target for 'Update' and as a separate source for data . The table is specified twice as both an update object and an independent data source.

Error reporting scenario: query the difference set of two tables and update the records. For example: perform an associated query on tables a and B to find out the records in table a that exist but not in table B, and then update a field in table a to mark.

Error reporting SQL:

UPDATE company AS f SET related = 0 WHERE uid IN 
(
select c.uid FROM company AS c 
LEFT JOIN member AS m ON m.uid=c.uid 
WHERE m.uid IS NULL
)

Solution:

Since a table cannot be both an update object and an independent data source, change one of them. Update is the main sentence, which cannot be removed, so you can only modify the table as the data source part. Take the results of the two table joint query as a temporary table and add a layer to the outer layer for query. In this way, the data source becomes a temporary table instead of the two tables for the previous associated query.

UPDATE company AS f SET related = 0 WHERE uid IN (
SELECT * FROM 
(
select c.uid FROM company AS c 
LEFT JOIN member AS m ON m.uid=c.uid 
WHERE m.uid IS NULL
) AS d
)

Thinkphp6 Error: constraint violation: 1052 Column ‘id’ in where clause is ambiguous

Cause

Show a column model

<?php
declare (strict_types=1);

namespace app\model;

use think\Model;

/**
 * @mixin \think\Model
 */
class Column extends Model
{

    public function articles()
    {

        return $this->belongsToMany(Article::class, 'column_article', 'article_id', 'column_id');
    }


    public function hasArt($article_id)
    {
        return $this->articles()->where('id', $article_id)->count();
    }

}

Wrong package when using

constraint violation: 1052 Column 'id' in where clause is ambiguous...

The reason for the error is that the relationship model of ThinkPHP does not know which table ID it is,

Here, we need to know which table it belongs to when sorting, so we also need to specify the table name when using it (Note: it needs to be prefixed)

    public function hasArt($article_id)
    {
        return $this->articles()->where('lu_article.id', $article_id)->count();
    }