各位不是喜欢吐槽的吗?来比比代码!

mallon 发布于 2013/12/31 00:59
阅读 257
收藏 1

MySQL连接为什么挂死了?别踩坑!>>>

来段C的,作为开胃菜,大学一年级就应该能看懂

#include <stdio.h>
#include <stdlib.h>

#if defined(__GNUC__)
    #include <unistd.h>
    #define SLEEP(ms) usleep(ms * 1000)
#elif defined(_MSC_VER)
    #include <windows.h>
    #define SLEEP(ms) Sleep(ms)
#endif

const char* poem[] = {
    "THE VISION",
    "OR,",
    "HELL, PURGATORY, AND PARADISE",
    "OF",
    "DANTE ALIGHIERI",
    "",
    "TRANSLATED BY",
    "THE REV. H. F. CARY, A.M.",
    "",
    "",
    "",
    "",
    "",
    "HELL",
    "",
    "CANTO I",
    "",
    "IN the midway of this our mortal life,",
    "I found me in a gloomy wood, astray",
    "Gone from the path direct:  and e'en to tell",
    "It were no easy task, how savage wild",
    "That forest, how robust and rough its growth,",
    "Which to remember only, my dismay",
    "Renews, in bitterness not far from death.",
    "Yet to discourse of what there good befell,",
    "All else will I relate discover'd there.",
...
...
    "v. 89.  One moment.]  \"A moment seems to me more tedious, than",
    "five-and-twenty ages would have appeared to the Argonauts, when",
    "they had resolved on their expedition.",
    "",
    "v. 92.  Argo's shadow]",
    "Quae simul ac rostro ventosnm proscidit aequor,",
    "Tortaque remigio spumis incanduit unda,",
    "Emersere feri candenti e gurgite vultus",
    "Aequoreae monstrum Nereides admirantes.",
    "Catullus, De Nupt.  Pel.  et Thet.  15.",
    "",
    "v. 109.  Three orbs of triple hue, clipt in one bound.]  The",
    "Trinity.",
    "",
    "v. 118.  That circling.]  The second of the circles, \"Light of",
    "Light,\" in which he dimly beheld the mystery of the incarnation.",
    "",
    "",
    "",
    "",
    "",
    "End Paradise.",
    "",
    "",
    "",
    "",
    "",
    NULL
};

int main(int argc, char **argv) {
    int interval;
    int i;
    char* p;

    if (argc > 1) {
        interval = atoi(argv[1]);
        if (interval > 10000) {
            interval = 10000;
        } else if (interval < 1) {
            interval = 1;
        }
    } else {
        interval = 1000;
    }

    for (;;) {
        for (i = 0; (p = poem[i]) != NULL; i++) {
            printf("%05d %s\n", i, p);
            fflush(stdout);
            SLEEP(interval);
        }
    }
    return 0;
}




加载中
1
mallon
mallon

再来Java的,貌似坛子里Java高手不少啊,能看得懂是做什么的吗?

private Map<String, Map<String, Object>> cache = new HashMap<String, Map<String, Object>>() {{
        // 天线
        put("/device/antenna/pitch", new HashMap<String, Object>() {{
            put("type", "float");
            put("set_value", new SetMethod() {
                @Override
                public void set(Number value) {
                    connection.sendCommand((byte) 0x4D, value);
                    connection.sendCommand((byte) 0x1D);
                }
            });
        }});
        put("/device/antenna/size", new HashMap<String, Object>() {{
            put("type", "byte");
            put("set_value", new SetMethod() {
                @Override
                public void set(Number value) {
                    connection.sendCommand((byte) 0x80, value);
                    connection.sendCommand((byte) 0x30);
                }
            });
        }});

        // 信标机
        put("/device/beacon/agc/voltage", new HashMap<String, Object>() {{
            put("type", "float");
            put("set_value", null);
        }});
        put("/device/beacon/fault", new HashMap<String, Object>() {{
            put("type", "integer");
            put("set_value", null);
        }});
        put("/device/beacon/mode", new HashMap<String, Object>() {{
            put("type", "byte");
            put("set_value", new SetMethod() {
                @Override
                public void set(Number value) {
                    connection.sendCommand((byte) 0x44,
                            getPropertyValue("/device/satellite/number"),
                            getPropertyValue("/device/satellite/polarization"),
                            value);
                    connection.sendCommand((byte) 0x14);
                }
            });
        }});
        put("/device/beacon/noise/voltage", new HashMap<String, Object>() {{
            put("type", "float");
            put("set_value", null);
        }});
        put("/device/beacon/noise/voltage/maximum/current", new HashMap<String, Object>() {{
            put("type", "float");
            put("set_value", null);
        }});
        put("/device/beacon/noise/voltage/maximum/history", new HashMap<String, Object>() {{
            put("type", "float");
            put("set_value", null);
        }});
...
...
        // 以下是一些公共的属性
        for (String name : keySet()) {
            get(name).put("lock", new ReentrantLock());
            get(name).put("value", null);
            get(name).put("value_listeners", new HashSet<Listener>());
            get(name).put("editable", Boolean.FALSE);
            get(name).put("editable_listeners", new HashSet<Listener>());
        }
    }};



1
mallon
mallon

Python的

# 任务队列
_task_queue = queue.Queue()


def _task_handler():
    """
    任务处理线程
    """
    while True:
        try:
            function, callback, exception_callback, args, kwargs = _task_queue.get()
            try:
                if callback:
                    callback(function(*args, **kwargs))
            except Exception as ex:
                if exception_callback:
                    exception_callback(ex)
        except Exception as ex:
            logging.warning(ex)


def initialize():
    """
    初始化
    """
    task_handler_thread = threading.Thread(target=_task_handler)
    task_handler_thread.daemon = True
    task_handler_thread.start()


def call(function, callback, exception_callback, *args, **kwargs):
    """
    异步调用
    """
    _task_queue.put((function, callback, exception_callback, args, kwargs))



1
mallon
mallon

Node.JS的,随便贴

"use strict";

(function () {

    var net = require('net');
    var util = require('util');
    var log = require('./log');
    var protocol = require('./protocol');
    var exchange = require('./exchange');

    // create TCP server, returns server instance
    exports.createServer = function (port, maxFrameSize) {
        var tcpServer = net.createServer();

        tcpServer.on('listening', function () {
            log.info(
                'TCP server listening at %s:%d',
                tcpServer.address().address,
                tcpServer.address().port
            );
        });

        tcpServer.on('connection', function (socket) {
            socket.setEncoding('utf8');

            // get client address and port
            var address = util.format('%s:%d', socket.remoteAddress, socket.remotePort);
            log.info('TCP connection established from %s', address);

            // the message frame
            var frame = '';

            // subscriptions' destination/id pair
            var subscriptions = {};

            // answer the client
            var answer = function (frame) {
                socket.write(frame + '\0', 'utf8');
            };

            // send back message frame to client
            var deliver = function (content, match) {
                answer(protocol.messageFrame(content, match));
            };

            // handle the message frame
            var handle = function (frame) {
                // log.info('Received from %s: %s', address, frame);

                // parse frame
                try {
                    var parsed = JSON.parse(frame);
                    switch (parsed.type) {
                        case 'publish':
                            handlePublish(parsed);
                            break;
                        case 'subscribe':
                            handleSubscribe(parsed);
                            break;
                        case 'unsubscribe':
                            handleUnsubscribe(parsed);
                            break;
                        default:
                            throw new Error(util.format('Unknown message type \'%s\'', parsed.type));
                            break;
                    }
                } catch (e) {
                    log.warn(e);
                    answer(protocol.errorFrame(e.toString()));
                }
            };

            // handle 'publish' frame
            var handlePublish = function (parsed) {
                exchange.push(parsed.content, parsed.destination);
            };

            // handle 'subscribe' frame
            var handleSubscribe = function (parsed) {
                var destination = parsed.destination;
                if (destination in subscriptions) {
                    throw new Error(util.format('Destination \'%s\' already exists', destination));
                } else {
                    log.info('TCP subscribe \'%s\' from %s', destination, address);
                    var id = exchange.add(destination, deliver);
                    subscriptions[destination] = id;
                }
            };

            // handle 'unsubscribe' frame
            var handleUnsubscribe = function (parsed) {
                var destination = parsed.destination;
                if (destination in subscriptions) {
                    log.info('TCP unsubscribe \'%s\' of %s', destination, address);
                    var id = subscriptions[destination];
                    exchange.remove(id);
                    delete subscriptions[destination];
                } else {
                    throw new Error(util.format('Destination \'%s\' does not exist', destination));
                }
            };

            // 2012.04.11 socket could be reset while writing a lot of data back to client in a short time
            // will raise: "Error: write ECONNRESET"
            // or: "Error: write Unknown system errno 10055"
            socket.on('error', function (exception) {
                log.warn(exception);
                socket.end();
            });

            socket.on('data', function (data) {
                /*
                 split the data by '\0'
                 for example, '\0\0hello\0\0world\0\0' will be splited into:
                 ['', '', 'hello', '', 'world', '', '']
                 to handle this array, the rule is:
                 1. the first to the (last - 1) item:
                 -- append to the frame
                 -- handle the frame
                 -- clear the frame
                 2. the last item:
                 -- append to the frame
                 */
                var fragments = data.split(/\0/);
                for (var i = 0; i < fragments.length; i++) {
                    frame += fragments[i];
                    if (frame.length > maxFrameSize) {
                        // test whether the frame exceeded the max size
                        answer(protocol.error(
                            null, 'Maximum frame size exceeded',
                            util.format('The frame is restricted to %d characters due to server config', config.maxFrameSize)));
                        socket.end();
                        break;
                    }
                    if (i < (fragments.length - 1)) {
                        // handle the frame
                        handle(frame);
                        frame = '';
                    }
                }
            });

            // 'close' event will always happened at last while 'end' probably not
            socket.on('close', function () {
                log.info('TCP Connection closed from %s', address);
                // cleanup
                log.info('TCP cleaning up all subscriptions of %s', address);
                for (var destination in subscriptions) {
                    var id = subscriptions[destination];
                    exchange.remove(id);
                }
                subscriptions = {};
            });
        });

        tcpServer.on('error', function (exception) {
            log.error('TCP Server encountered error: %j', exception);
            tcpServer.close();
        });

        tcpServer.on('close', function () {
            log.info('TCP Server closed');
        });

        tcpServer.listen(port);

        return tcpServer;
    };
}());



1
mallon
mallon
洗洗睡觉
0
爆炸
爆炸
<?php

echo 'Hello World!';



0
黄亿华
黄亿华
原来Java还可以写两个花括号!
0
mallon
mallon

引用来自“黄亿华”的答案

原来Java还可以写两个花括号!
我敢保证坛子里绝大部分Java卫道士都不会。且不说功能,他们能把语法看懂就不错了。
0
_flowers
_flowers

引用来自“Mallon”的答案

引用来自“黄亿华”的答案

原来Java还可以写两个花括号!
我敢保证坛子里绝大部分Java卫道士都不会。且不说功能,他们能把语法看懂就不错了。
刚刚测试了一下,原来类里面除了static的代码块外,还可以有{}代码块,只有在实例化对象的时候执行。涨姿势了
返回顶部
顶部