cocos-lua 多重继承的iskindof的BUG

封神台靶场,为了小芳,冲之——cookie注入 第二个靶场 打开网站 找一下注入点 一般在新闻这种里面点开看看 先判断是否存在注入 有waf 尝试了很多方法绕过都没成功,/and/,aandnd,AnD等一系列都没绕过去,乌鸡鲅鱼 删掉id=169 发现 然后判断cookie注入 在搜索框输入 Javascript:alert(document.cookie=”id=”+escape(‘169’)); 然后弹窗了(其中 “id=” 取决URL中的id= escape中的数值也是URL中id=的值)返回刚刚的页面,把ID删除后一样能正常显示。说明服务器能 阅读详情

cocos-lua的iskindof在多重继承时有一个BUG,如下:

    local A=class("ClassA")
    local B=class("ClassB",A)
    local binst= B.new()
    print(   iskindof(binst,"ClassA")  )

ClassB继承自ClassA,因此B的对象理应也是ClassA的对象。但是输出结果却是false. (如果你已经知道这个BUG,想知道怎么解决,直接跳到最后;如果你想看是什么原因,则往下看。)

iskindof源码

那么就要看下iskindof的代码了。源码如下:

    function iskindof(obj, classname)
        local t = type(obj)
        if t ~= "table" and t ~= "userdata" then return false end

        local mt
        if t == "userdata" then
            if tolua.iskindof(obj, classname) then return true end
            mt = tolua.getpeer(obj)
        else       
            mt = getmetatable(obj)   --我传进来的binst是走到这个分支
        end
        if mt then
            --最后调用这个,mt就是binst的metatable,classname就是传进来的"ClassA"
            return iskindof_(mt, classname) 
        end
        return false
    end

略有点复杂,iskindof流程大概是先判断传进来的obj什么类型,如果是table类型的则取它的元表metatable;如果是userdata类型的,则用tolua的方式来判断。

我们的传进去的是binst,是个table类型;所以执行getmetatable。然后再去调用iskindof_。单纯按照kindof这个函数的意图来讲,这个貌似没什么问题:“传进来如果是个table,那么我们就去查它的metatable是个什么类就可以了。”

那再看看最后一步iskindof_是个什么函数,源码如下:

local iskindof_
iskindof_ = function(cls, name)
    local __index = rawget(cls, "__index")
    if type(__index) == "table" and rawget(__index, "__cname") == name then return true end

    if rawget(cls, "__cname") == name then return true end
    local __supers = rawget(cls, "__supers")  --获取的__supers为空
    if not __supers then return false end
    for _, super in ipairs(__supers) do
        if iskindof_(super, name) then return true end
    end
    return false
end

(程序中rawget意思是只找当前表里的内容,避免lua自动去找这个表的元表的内容)

其大致的流程是:
1.先找cls的__index,看看__index的类名是不是我们要的。
2.如果不是,看看cls本身是不是我们要的。
3.如果不是,那么我们看看cls的父类有没有我们要的。找父类的过程是个迭代的过程,只要找到了,则return true;没有找到,则继续找下一个父类。

按照这个函数的意思,如果当前类找不到类名,会去找父类。但是我运行了一下,当把binst的元表传进去之后,__supers为空!这显然是不对的,binst明明是有父类的,怎么会没有__supers呢?肯定哪里错误了。
所以接下来我们要解决的问题是,也是本文的中心:

为什么iskindof\_找不到binst的__supers?

不过,我承认iskindof_这个函数有点不好消化,因为一下子来了那么多新的域,什么__index、__supers、__cname等等。这就涉及到class的内部结构了。
再粘一下class的源码,不要被吓到。吓到了,直接跳过看我的研究成果吧。

class的结构

function class(classname, ...)
    local cls = {__cname = classname}

    local supers = {...}
    for _, super in ipairs(supers) do
        local superType = type(super)
        assert(superType == "nil" or superType == "table" or superType == "function",
            string.format("class() - create class \"%s\" with invalid super class type \"%s\"",
                classname, superType))

        if superType == "function" then
            assert(cls.__create == nil,
                string.format("class() - create class \"%s\" with more than one creating function",
                    classname));
            -- if super is function, set it to __create
            cls.__create = super
        elseif superType == "table" then
            if super[".isclass"] then
                -- super is native class
                assert(cls.__create == nil,
                    string.format("class() - create class \"%s\" with more than one creating function or native class",
                        classname));
                cls.__create = function() return super:create() end
            else
                -- super is pure lua class
                cls.__supers = cls.__supers or {}
                cls.__supers[#cls.__supers + 1] = super
                if not cls.super then
                    -- set first super pure lua class as class.super
                    cls.super = super
                end
            end
        else
            error(string.format("class() - create class \"%s\" with invalid super type",
                        classname), 0)
        end
    end

    cls.__index = cls
    if not cls.__supers or #cls.__supers == 1 then
        setmetatable(cls, {__index = cls.super})
    else
        setmetatable(cls, {__index = function(_, key)
            local supers = cls.__supers
            for i = 1, #supers do
                local super = supers[i]
                if super[key] then return super[key] end
            end
        end})
    end

    if not cls.ctor then
        -- add default constructor
        cls.ctor = function() end
    end
    cls.new = function(...)
        local instance
        if cls.__create then
            instance = cls.__create(...)
        else
            instance = {}
        end
        setmetatableindex(instance, cls)
        instance.class = cls
        instance:ctor(...)
        return instance
    end
    cls.create = function(_, ...)
        return cls.new(...)
    end

    return cls
end

好吧,我承认我自己也被吓到了。其实,其大致思想是先建个local表,再在这个local表添加各种各样的东西(什么__index, __supers, __cname都放进去),接着设置下它的metatable,最后返回这个local表就ok了。人生就是这样,因为考虑得周全了,东西也会变多。

为了解释iskindof,除去所有冗余的判断,我们只挑iskindof需要的域。

    --__cname就是传进来的classname字符串
    local cls = {__cname = classname}

    --因为我们传进来的supers只有一个,所以
    --cls.__supers={YOURSUPERCLASS},
    --cls.super=YOURSUPERCLASS.

    cls.__supers = cls.__supers or {}
    cls.__supers[#cls.__supers + 1] = super
    if not cls.super then
        -- set first super pure lua class as class.super
        cls.super = super
    end

    --cls的__index就是它自己
    cls.__index = cls

    --设置元表
    --如果有supers且只有一个super,则cls的元表很简单就是一个有__index域的表,{__index = YOURSUPERCLASS}
    --如果没有supers或有好多个supers,则__index是个函数。这个函数会去遍历所有的Super;如果没有supers,那么这个__index就相当于一个 一直返回nil的函数。
    if not cls.__supers or #cls.__supers == 1 then
        setmetatable(cls, {__index = cls.super})
    else
        setmetatable(cls, {__index = function(_, key)
            local supers = cls.__supers
            for i = 1, #supers do
                local super = supers[i]
                if super[key] then return super[key] end
            end
        end})
    end

好,有了上面的分析,我们就可以画出我在一开始定义的那两个类的结构啦。再看下我之前定义的两个类:

    local A=class("ClassA")
    local B=class("ClassB",A)
    local binst= B.new()
A
__cname“ClassA”
__supersnil
supernil
__indexA
metatable{ __index=一个总是返回nil的function }

再看看B的结构:

B
__cname“ClassB”
__supers{A}
superA
__indexB
metatable{ __index=A }

根据上面的结构,binst按道理是有__supers的,那iskindof_ 执行下来为啥没有呢?难道binst的结构有问题?
我们就得研究下再来看看binst的结构。

我们的实例——binst的结构

看例子,binst是通过B.new()来创建的。new函数是定义在class下的,代码如下:

    --定义cls的new函数,我们创建类的实例就用这个函数。
    cls.new = function(...)
        local instance
        if cls.__create then
            instance = cls.__create(...)
        else
            instance = {}
        end
        --又多出一个不认识的函数setmetatableindex,汗汗汗,待会儿讲
        setmetatableindex(instance, cls)
        instance.class = cls
        instance:ctor(...)
        return instance
    end

我们的cls是没有__create的,所以一开始instance为{}。然后为这个instance添加域class,并执行ctor函数。这过程还多了个新的函数setmetatableindex,按字面意思就是为instance添加元表。

看看函数的源码吧:

local setmetatableindex_
setmetatableindex_ = function(t, index)
    if type(t) == "userdata" then
        local peer = tolua.getpeer(t)
        if not peer then
            peer = {}
            tolua.setpeer(t, peer)
        end
        setmetatableindex_(peer, index)
    else
        local mt = getmetatable(t)
        if not mt then mt = {} end
        if not mt.__index then
            mt.__index = index
            setmetatable(t, mt)
        elseif mt.__index ~= index then
            setmetatableindex_(mt, index)
        end
    end
end
setmetatableindex = setmetatableindex_

我们传进去instance给t, index为类本身。setmetatableindex先判断t的类型,如果是userdata,则执行userdata那一套;否则执行table的那一套。
我们是table类型,所以先取instance的metatable。由于我们传进去的instance为{},最后会执行下面的两条语句:mt.__index = index和setmetatable(t,mt)。意思是将instance的metatable设成{__index=index}。

综上,得到binst的结构:

binst
classB
metatable{ __index=B }

原来binst也是有metatable:{__index=B}。看上去还蛮简单的嘛。

说了那么多,最后返回来看我们的iskindof到底有什么问题?

再来看iskindof

iskindof的大致流程为:

Created with Raphaël 2.1.0传入obj, classnameobj类型为table?取table的metatable为mt返回iskindof_(mt,classname)结束userdata那一套 yesno

我们传入的obj为binst,classname为”CLassA”。而binst的metatable为{__index=B},意思是iskindof_的传入的是{__index=B}和"ClassB"。
隐隐约约感觉到{__index=B}貌似有些问题。

再看看iskindof_的源码:

local iskindof_
iskindof_ = function(cls, name)

    --cls={__index=B},
    --name="ClassA"

    local __index = rawget(cls, "__index")
    if type(__index) == "table" and rawget(__index, "__cname") == name then return true end

    if rawget(cls, "__cname") == name then return true end

    local __supers = rawget(cls, "__supers")  
    --{__index=B},这个表有__supers么?肯定没有。所以问题就是出在传入的cls有问题。

    if not __supers then return false end
    for _, super in ipairs(__supers) do
        if iskindof_(super, name) then return true end
    end
    return false
end

可以看到iskindof_用rawget找{__index=B}里的__supers域,那肯定没有。那传什么参数给iskindof_呢?
再看看binst的结构,一个__class和一个{__index=B}。看看iskindof_的两个参数:cls和name。这个函数本来就是去查class的,我们却把一个元表{__index=B}传了进去。那何不把class本身传进去呢?

    function iskindof(obj, classname)
        local t = type(obj)
        if t ~= "table" and t ~= "userdata" then return false end

        local mt
        if t == "userdata" then
            if tolua.iskindof(obj, classname) then return true end
            mt = tolua.getpeer(obj)
        else       
            -- mt = getmetatable(obj)  
            -- 修改后
            mt = rawget(obj,"class")
        end
        if mt then
            return iskindof_(mt, classname) 
        end
        return false
    end

经过测试,iskindof(binst,"ClassA")就返回了true。

那这样改会不会有问题呢?觉得可能会有些问题。问题就是这个iskindof函数跟class耦合性变高了。不过,函数的最后iskindof_本身就是跟class息息相关的。所以这样改,个人觉得没什么问题。

其实知道这个原因,还有很多其他改法:比如我们也可以把binst的结构改掉,把它的metatable {__index=B}改成B。这样也是没有问题的。因为B的__index就是B本身。

这是cocos2d-x-3.8.1版本,算是最新的,但我疑问为什么这么明显的BUG没有人纠正呢?至今还不解。

Android Studio无法启动,Failed to create JVM:error code -1. JVM Path 完美解决方案 Android Studio无法启动,Failed to create JVM:error code -1. JVM Path 完美解决方案。 找到Android studio的启动文件bin目录,把studio64.exe.vmoptions 删除或改名(推荐改名,方便恢复),如果你是32位系统这个文件就是 studio.exe.vmoptions 阅读详情

相关推荐

AI Agent在营销领域的实战策略

本文从第一性原理出发,系统性拆解AI Agent在营销领域的落地逻辑、技术架构、实现方案与实战策略。全文覆盖从基础概念到高级优化的全层级知识:底层理论层面推导营销Agent的效用函数与决策框架;技术架构层面提出"感知-记忆-规划-行动-反思"五组件可落地架构;实践层面提供生产级代码实现、多行业案例与ROI提升方法论;前沿层面探讨多Agent协同、世界模型仿真等下一代技术方向。

操作系统内核探秘的博客 227

cocos2dx lua class 继承问题

版本:cocos2dx v3.10 local BaseClass = class("BaseClass ") function BaseClass:ctor() ....... end local SubClass = class(“SubClass ”,require(“BaseClass”)) function SubClass:ctor() -- 子类如果覆盖了基类的

硕嘉的Blog 492

CloudCompare里那个CSF地面滤波插件,到底怎么用?手把手教你分离点云里的地面

本文详细介绍了如何在CloudCompare中使用CSF地面滤波插件分离点云中的地面数据。通过解析布料模拟滤波算法的核心参数,如布料刚度和网格分辨率,并提供不同地形(城市、丘陵、山地)的适配策略,帮助用户高效处理复杂点云数据。文章还包含实战案例和优化技巧,确保滤波结果的精度和可靠性。

weixin_42548708的博客 221

Lua面向对象 -- 多重继承、私密性

1. 多重继承之在多个类中查找一个字段 其实多重继承没什么特别的,除非两个将要被继承的类有相同的函数名和属性,否则,处理起来很简单。   无非就是在多个table中查找某个字段而已,不简单吗?Lua里的继承就是在别人的table里查找自己不存在的字段罢了。 那么,单继承与多重继承的差别也在这里,一个是只查找一个table,另一个是查找两个或以上的table。

小天 专栏 588

IMU数据处理避坑指南:从理论到实践的加速度计重力消除方案

本文详细解析了IMU数据处理中的重力消除技术,从理论基础到实践应用,涵盖了加速度计和陀螺仪的核心问题。通过ROS2实战案例,介绍了静态标定与动态校准的技术对比,以及多传感器融合的进阶策略,帮助开发者避免常见陷阱,提升IMU数据处理的精度和效率。

purple的博客 741

Linux单独编译设备树,开发者分享 | Petalinux 工程中设备树的介绍

本文来自XILINX嵌入式产品应用工程师 Terry Ni设备树是 Petalinux kernel 的关键组件,接下来以 2020.1 版本为例,为大家介绍一下在Xilinx Petalinux 工程中的设备树是如何产生,配置以及修改的。Petalinux 工程中设备树的位置当我们创建了一个 petalinux 工程后(以zcu102为例),在编译的时候,会自动生成对应的设备树文件。这些设备树的...

weixin_28877107的博客 2589

Lua(3) ——Cocos之_语法糖class

【唠叨】在使用Lua的时候,cocos2d-x为我们提供了一个class(classname, super)这个函数。它可以让我们很方便的定义一个类,或者继承cocos2d-x的某个类。PS:class()是cocos2d-x为我们封装的函数,本身Lua没有这个函数。基于Lua 5.1。【Demo下载】https://github....

weixin_34290000的博客 239

UltraScale+ FPGA中GTY收发器参考时钟的跨Bank共享机制解析

本文深入解析了UltraScale+ FPGA中GTY收发器参考时钟的跨Bank共享机制,详细介绍了时钟布线架构、SLR区域限制及Vivado工程配置要点。通过实际案例和优化建议,帮助工程师解决高速串行通信中的时钟共享问题,提升系统性能。

weixin_29280219的博客 630

Lua自己实现如果对象是指定类或其子类的实例,返回 true

Lua自己实现如果对象是指定类或其子类的实例,返回 true,否则返回 false

heyuchang666的专栏 2604

STM32Cube高效开发教程<高级篇><FreeRTOS>(十八)-----软件定时器

一、 软件定时器概述声明:本人水平有限,博客可能存在部分错误的地方,请广大读者谅解并向本人反馈错误。本专栏博客参考《STM32Cube高效开发教程(高级篇)》,有意向的读者可以购买正版书籍辅助学习,本书籍由王维波老师、鄢志丹老师、王钊老师倾力打造,书籍内容干货满满。在FreeRTOS中,自动创建的任务有空闲任务和定时器服务任务。FreeRTOS可以通过定时器服务任务提供软件定时器功能。在某些对定时精度要求不太高,无须使用硬件定时器的情况下,我们可以使用FreeRTOS的软件定时器。

我的博客 157

【WRF教程第3.5期】预处理系统 WPS 详解:以4.5版本为例

预处理系统 WPS 详解:以4.5版本为例

WW、forever的博客 1422

Lua 实现单例 (userdata) 多继承单例

–region *.lua –Date –Author WikiChen–[[ * 单例 * 类似 c/c++ 单例模式 * 实现类可以 继承它,实现单例 * Note 需要实现 初始化函数 Init –]]–local Singleton = class(“Singleton”) local Singleton = {}–function Singleton:ctor() –

cwq水域 的专栏 1082

Flink Gauss CDC:深度剖析存量与增量同步的创新设计

开发Flink Gauss CDC是为了适配华为自研GaussDB的特殊日志格式和逻辑复制机制,解决Flink CDC无法直接支持的问题,同时优化存量与增量同步的效率和一体化读取能力,满足GaussDB复合主键处理、数据落库等定制化需求,以实现高效、准确的数据同步。

数据与算法架构提升之路专栏 1985

Lua面向对象之多重继承、私密性详解

在Lua中的多重继承和私密性可能用得比较少,也可能只是我个人用得比较少。 本来想偷懒不写这文章的,因为我今天刚买了个漂移板,连起步都还没学会啊,想多学一会。 咳咳,本着坚持不懈、负责到底的态度,我还是决定随便写几句~(小若:随便写几句是几吨意思啊?!) 1.多重继承之在多个类中查找一个字段 我发现这些高(shen)智(jing)商(bing)人群真的很厉害,这种技巧都能想到,很佩服。 其实多...

qq_31629063的博客 245

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

Cocos2d-x Lua库函数剖析(六)functions

这部分主要是封装了一些会常用的函数,比如printLog,等。 先上源码 --[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated docu...

qq_39218906的博客 574

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Lua该如何实现一个类,实现继承

Lua该如何实现一个类,实现继承 Lua是一门解释型语言,C++,C#,Java等高级语言都属于编译型语言,编译型语言同解释型语言有着很大差别。(看官请自行百度) Lua没有类和继承的概念,但是很多业务场景中,我们会需要自行实现类与继承的概念,以方便开发工作:Lua中table 是一个很强大的东西。 不多说无关紧要的:进入正题: 1 --@param string classname 类名 2 --@param [mixed super] 父类或者创建对象实例的函数 3 ...

huawei12341的博客 870

visio安装包

Microsoft Office Visio 是一款专业的制图软件。利用经过更新的形状、协作工具和数据链接图表,创建专业级图表以简化复杂的信息。

IsKindOf()函数

<br /> 知道有IsKindOf这么个函数,用来检测:(1)对象是否属于指定的类,(2)对象是否属于指定类派生的类,但是一直没用过,今天用了下,提示错误error C2039: 'classXXX' : is not a member of 'XXX',查了很多资料,才把它搞明白,记录如下:<br />1、对使用IsKindOf这个函数的类要在.h文件夹里定义DECLARE_DYNAMIC或DECLARE_SERIAL宏<br />class CDlgTest : public CDialog {

吖吖狼 的专栏 7691

IsKindOf(类型识别)

在CObject中添加一个IsKindOf函数,此函数将被所有的类继承,它把参数所指定的某个CRuntimeClass对象拿来与类别型录中的元素一一比较。比较成功(在型录中有发现)就传回TRUE,否则就返回FALSE。 //in head file class CObject { public: ...cpp BOOL IsKindOf(const CRuntimeClass* pClass) c...

l93919861的博客 2430

入手cocos2dx3.9笔记 3 tolua++解析

因为需求,最近又重新回忆了下tolua++的相关流程, 以 3.9的 lua stack 的初始化相关代码开始解析: _state = lua_open(); luaL_openlibs(_state); toluafix_open(_state); // Register our version of the global "print" function

阿祖的博客 4721

cocos2d tolua C++对象使用lua对象的变量,函数

C++对象绑定到lua通常是创建一个userdata用来存放cpp对象。在tolua库中维护了一张表:tolua_ubox表,它是个弱表,用来缓存所有cppobj的ptr->userdata映射。 userdata对象的生成过程和cpp对象到userdata的映射的生成。 void tolua_pushusertype_internal (lua_State* L, void* value

keep_moving_cqu的专栏 2474

Cocos2D-X shader(五) cocostudio导出界面置灰及复原lua实现版

利用cocostudio导出的界面,实现界面置灰与复原效果: 需要变色的有三种类型控件:普通图片(ImageView),九宫格切图(Scale9Sprite)以及文字(Text) 普通图片 普通图片比较容易处理,可以直接使用shader来实现。先来看shader代码: -- 默认vert local vertDefaultSource = "\n"..

operhero1990的专栏 4675

tolua++分析

int lua_isusertable (lua_State* L, int lo, const char* type)

john_crash的专栏 2921

cocos2dx lua 多重继承例子

今天接到任务,需要写个多重继承的demo,代码如下: A = class("A") function A:init() cclog("A:init()") end function A:getNameA() return "class A" end --//============================= B = class("B") function B:init() cc

民ming 1514

Lua中多重继承的简单实现

--多个table表中寻找对应key的值 function search(classes, key)     for i = 1, #classes do         local value = classes[i][key];         if value ~= nil then             return value;         end     end

upbins的专栏 1003
上一篇: lua metatable及其相关方法的简述
下一篇: 解决protobuf-lua导入其他proto的BUG
wonbit
博客等级 码龄17年 5粉丝 3原创
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值