text:
<!DOCTYPE html>

	<meta charset="utf-8">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Popup across multiple pages - jQuery Mobile Demos</title>
	<link rel="shortcut icon" href="../favicon.ico">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Open+Sans:300,400,700">
	<link rel="stylesheet" href="../../css/themes/default/jquery.mobile.css">
	<link rel="stylesheet" href="../_assets/css/jqm-demos.css">

Global Menu

Intro Page

Other Page

Third Page

 Demos

		Menu
		Search

Using the same popup across multiple pages

You can reuse the same popup on multiple pages if you declare it as a direct child of the body element. It can then appear on any page in the document.

If you define the popup outside of any page, then you must take care to instantiate the popup widget yourself. You can do this as early as DOMReady, because the popup is not on any page.

If you wish the popup to be opened from a set of links, then you must also handle that manually, because automatic handling via data-rel="popup" is restricted to popups on the active page.

The example below illustrates the setup with two pages.

			Menu

	<?php include( '../jqm-navmenu.php' ); ?>

jQuery Mobile Demos version

Copyright 2014 The jQuery Foundation

<?php include( '../jqm-search.php' ); ?>

		Menu

Another Page

This is another page that can be reached using the links in the global menu.

		Menu

Third Page

This is a third page that can be reached using the links in the global menu.


text:
__author__ = 'dimitris'

import os

basedir = os.path.abspath(os.path.dirname(__file__))
TESTING = True
DB_NAME = 'testing_database.db'
SQLALCHEMY_DATABASE_URI = 'sqlite:///' + os.path.join(basedir, DB_NAME)

redpajama_set_name: RedPajamaGithub


text:
var mongoose = require('mongoose');

/*
* Database connection
*/
var connection = mongoose.createConnection('mongodb://localhost/myapp');

module.exports = {
    connection: connection
}


text:
"""
    pyClanSphere.notifications
    ~~~~~~~~~~~~~~~~~~~~~~~~~~

    This module implements an extensible notification system.  Plugins can
    provide different kinds of notification systems (like email, jabber etc.)

    Each user can subscribe to different kinds of events.  The general design
    is inspired by Growl.

    :copyright: (c) 2009 - 2010 by the pyClanSphere Team,
                see AUTHORS for more details.
    :license: BSD, see LICENSE for more details.
"""
from datetime import datetime
from urlparse import urlsplit

from werkzeug import url_unquote

from pyClanSphere.models import NotificationSubscription
from pyClanSphere.application import get_application, get_request, render_template
from pyClanSphere.privileges import CLAN_ADMIN, ENTER_ACCOUNT_PANEL
from pyClanSphere.utils.zeml import parse_zeml
from pyClanSphere.utils.mail import send_email
from pyClanSphere.i18n import lazy_gettext

__all__ = ['DEFAULT_NOTIFICATION_TYPES', 'NotificationType']

DEFAULT_NOTIFICATION_TYPES = {}

def send_notification(type, message, user=Ellipsis):
    """Convenience function.  Get the application object and deliver the
    notification to it's NotificationManager.

    The message must be a valid ZEML formatted message.  The following
    top-level elements are available for marking up the message:

    title
        The title of the notification.  Some systems may only transmit this
        part of the message.

    summary
        An optional quick summary.  If the text is short enough it can be
        omitted and the system will try to transmit the longtext in that
        case.  The upper limit for the summary should be around 100 chars.

    details
        If given this may either contain a paragraph with textual information
        or an ordered or unordered list of text or links.  The general markup
        rules apply.

    longtext
        The full text of this notification.  May contain some formattings.

    actions
        If given this may contain an unordered list of action links.  These
        links may be transmitted together with the notification.

    Additionally if there is an associated page with the notification,
    somewhere should be a link element with a "selflink" class.  This can be
    embedded in the longtext or actions (but any other element too).

    Example markup::

        <title>New comment on "Foo bar baz"</title>
        Mr. Miracle wrote a new comment: "This is awesome."

Mr. Miracle

E-Mail

        <longtext>

This is awesome.  Keep it up!

Love your work
        </longtext>
        <actions>

all comments

delete it

approve it

        </actions>

    Example plaintext rendering (e-mail)::

        Subject: New comment on "Foo bar baz"

        Mr. Miracle             http://miracle.invalid/
        E-Mail                  mr@mircale.invalid

        > This is awesome.   Keep it up!
        > Love your work.

        Actions:
          - delete it           http://.../?action=delete
          - approve it          http://.../?action=approve

    Example IM notification rendering (jabber)::

        New comment on "Foo bar baz."  Mr. Miracle wrote anew comment:
        "This is awesome".  http://.../link
    """
    get_application().notification_manager.send(
        Notification(type, message, user)
    )

def send_notification_template(type, template_name, user=Ellipsis, **context):
    """Like `send_notification` but renders a template instead."""
    notification = render_template(template_name, **context)
    send_notification(type, notification, user)

class NotificationType(object):
    """There are different kinds of notifications. E.g. you want to
    send a special type of notification after a comment is saved.
    """

    def __init__(self, name, description, privileges):
        self.name = name
        self.description = description
        self.privileges = privileges

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self.name)

class Notification(object):
    """A notification that can be sent to a user. It contains a message.
    The message is a zeml construct.
    """

    def __init__(self, id, message, user=Ellipsis):
        self.message = parse_zeml(message, 'system')
        self.id = id
        self.sent_date = datetime.utcnow()
        if user is Ellipsis:
            self.user = get_request().user
        else:
            self.user = user

    @property
    def self_link(self):
        link = self.message.query('a[class~=selflink]').first
        if link is not None:
            return link.attributes.get('href')

    title = property(lambda x: x.message.query('/title').first)
    details = property(lambda x: x.message.query('/details').first)
    actions = property(lambda x: x.message.query('/actions').first)
    summary = property(lambda x: x.message.query('/summary').first)
    longtext = property(lambda x: x.message.query('/longtext').first)

class NotificationSystem(object):
    """Use this as a base class for specific notification systems such as
    `JabberNotificationSystem` or `EmailNotificationSystem`.

    The class must implement a method `send` that receives a notification
    object and a user object as parameter and then sends the message via
    the specific system.  The plugin is itself responsible for extracting the
    information necessary to send the message from the user object.  (Like
    extracting the email address).
    """

    def __init__(self, app):
        self.app = app

    #: subclasses have to overrides this as class attributes.
    name = None
    key = None

    def send(self, user, notification):
        raise NotImplementedError()

class EMailNotificationSystem(NotificationSystem):
    """Sends notifications to user via E-Mail."""

    key = 'email'
    name = lazy_gettext(u'E-Mail')

    def send(self, user, notification):
        title = u'[%s] %s' % (
            self.app.cfg['clan_title'],
            notification.title.to_text()
        )
        text = self.mail_from_notification(notification)
        send_email(title, text, [user.email])

    def unquote_link(self, link):
        """Unquotes some kinds of links.  For example mailto:foo links are
        stripped and properly unquoted because the mails we write are in
        plain text and nobody is interested in URLs there.
        """
        scheme, netloc, path = urlsplit(link)[:3]
        if scheme == 'mailto':
            return url_unquote(path)
        return link

    def collect_list_details(self, container):
        """Returns the information collected from a single detail list item."""
        for item in container.children:
            if len(item.children) == 1 and item.children[0].name == 'a':
                link = item.children[0]
                href = link.attributes.get('href')
                yield dict(text=link.to_text(simple=True),
                           link=self.unquote_link(href), is_textual=False)
            else:
                yield dict(text=item.to_text(multiline=False),
                           link=None, is_textual=True)

    def find_details(self, container):
        # no container given, nothing can be found
        if container is None or not container.children:
            return []

        result = []
        for child in container.children:
            if child.name in ('ul', 'ol'):
                result.extend(self.collect_list_details(child))
            elif child.name == 'p':
                result.extend(dict(text=child.to_text(),
                                   link=None, is_textual=True))
        return result

    def find_actions(self, container):
        if not container:
            return []
        ul = container.query('/ul').first
        if not ul:
            return []
        return list(self.collect_list_details(ul))

    def mail_from_notification(self, message):
        title = message.title.to_text()
        details = self.find_details(message.details)
        longtext = message.longtext.to_text(collect_urls=True,
                                            initial_indent=2)
        actions = self.find_actions(message.actions)
        return render_template('notifications/email.txt', title=title,
                               details=details, longtext=longtext,
                               actions=actions)

class NotificationManager(object):
    """The NotificationManager is informed about new notifications by the
    send_notification function. It then decides to which notification
    plugins the notification is handed over by looking up a database table
    in the form:

        user_id  | notification_system | notification id
        ---------+---------------------+--------------------------
        1        | jabber              | NEW_COMMENT
        1        | email               | PYCLANSPHERE_UPGRADE_AVAILABLE
        1        | sms                 | SERVER_EXPLODED

    The NotificationManager also assures that only users interested in
    a particular type of notifications receive a message.
    """

    def __init__(self):
        self.systems = {}
        self.notification_types = DEFAULT_NOTIFICATION_TYPES.copy()

    def send(self, notification):
        # given the type of the notification, check what users want that
        # notification; via what system and call the according
        # notification system in order to finally deliver the message
        subscriptions = NotificationSubscription.query.filter_by(
            notification_id=notification.id.name
        )
        if notification.user:
            subscriptions = subscriptions.filter(
                NotificationSubscription.user!=notification.user
            )

        for subscription in subscriptions.all():
            system = self.systems.get(subscription.notification_system)
            if system is not None:
                system.send(subscription.user, notification)

    def types(self, user=None):
        if not user:
            user = get_request().user
        for notification in self.notification_types.itervalues():
            if user.has_privilege(notification.privileges):
                yield notification

    def add_notification_type(self, notification):
        self.notification_types[type.name] = type

def _register(name, description, privileges=ENTER_ACCOUNT_PANEL):
    """Register a new builtin type of notifications."""
    nottype = NotificationType(name, description, privileges)
    DEFAULT_NOTIFICATION_TYPES[name] = nottype
    globals()[name] = nottype
    __all__.append(name)

_register('SECURITY_ALERT',
          lazy_gettext(u'When pyClanSphere found an urgent security alarm.'),
          CLAN_ADMIN)
_register('PYCLANSPHERE_ERROR', lazy_gettext(u'When pyClanSphere throws errors.'), CLAN_ADMIN)

DEFAULT_NOTIFICATION_SYSTEMS = [EMailNotificationSystem]
del _register


text:
using System;
using NUnit.Framework;
using System.Threading;
using MonoTorrent.Common;
using System.Net;
using MonoTorrent.Client.Messages.Standard;
using MonoTorrent.Client.Encryption;

namespace MonoTorrent.Client
{
    [TestFixture]
    public class NetworkIOTests
    {
        byte[] buffer;
        byte[] data;
        ConnectionPair pair;

        CustomConnection Incoming {
            get { return pair.Incoming; }
        }

        CustomConnection Outgoing {
            get { return pair.Outgoing; }
        }

        [SetUp]
        public void Setup ()
        {
            if (data == null) {
                data = new byte [32768];
                new Random ().NextBytes (data);
            }
            pair = new ConnectionPair (34567);
        }

        [TearDown]
        public void Teardown ()
        {
            pair.Dispose ();
        }

        [Test]
        public void ReceiveData_SlowIncoming_SlowOutgoing ()
        {
            DoReceive (true, true);
        }

        [Test]
        public void ReceiveData_SlowIncoming ()
        {
            DoReceive (false, true);
        }

        [Test]
        public void ReceiveData_SlowOutgoing ()
        {
            DoReceive (true, false);
        }

        [Test]
        public void ReceiveData ()
        {
            DoReceive (false, false);
        }

        void DoReceive (bool slowOutgoing, bool slowIncoming)
        {
            Incoming.SlowConnection = slowIncoming;
            Outgoing.SlowConnection = slowOutgoing;

            int sent = 0;
            buffer = new byte [data.Length];

            var handle = new ManualResetEvent (false);
            NetworkIO.EnqueueReceive (Outgoing, buffer, 0, buffer.Length, null, null, null, (s, t, o) => {
                Assert.IsTrue (s, "#Receive successful");
                Assert.AreEqual (buffer.Length, t, "#data was all received");
                handle.Set ();
            }, null);

            while (sent != buffer.Length) {
                int r = Incoming.Send (data, sent, data.Length - sent);
                Assert.AreNotEqual (0, r, "#Received data");
                sent += r;
            }

            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (4)), "Data should be all received");
            for (int i = 0; i < buffer.Length; i++) {
                if (data[i] != buffer[i])
                    Assert.Fail ("Buffers differ at position " + i);
            }
        }

        [Test]
        public void SendData_SlowIncoming_SlowOutgoing ()
        {
            DoSend (true, true);
        }

        [Test]
        public void SendData_SlowOutgoing ()
        {
            DoSend (true, false);
        }

        [Test]
        public void SendData_SlowIncoming ()
        {
            DoSend (false, true);
        }

        [Test]
        public void SendData ()
        {
            DoSend (false, false);
        }

        public void DoSend (bool slowOutgoing, bool slowIncoming)
        {
            Incoming.SlowConnection = slowIncoming;
            Outgoing.SlowConnection = slowOutgoing;

            var handle = new ManualResetEvent (false);
            NetworkIO.EnqueueSend (Outgoing, data, 0, data.Length, null, null, null, delegate {
                handle.Set ();
            }, null);

            int received = 0;
            byte[] buffer = new byte [data.Length];
            while (received != buffer.Length) {
                int r = Incoming.Receive (buffer, received, buffer.Length - received);
                Assert.AreNotEqual (0, r, "#Received data");
                received += r;
            }
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (1)), "Data should be all sent");
            Assert.IsTrue (Toolbox.ByteMatch (buffer, data), "Data matches");
        }

        [Test]
        public void InvalidMessage ()
        {
            bool success = true;
            ManualResetEvent handle = new ManualResetEvent (false);
            Buffer.BlockCopy (BitConverter.GetBytes (IPAddress.HostToNetworkOrder (16)), 0, data, 0, 4);
            for (int i = 4; i < 16; i++)
                data [i] = byte.MaxValue;
            PeerIO.EnqueueReceiveMessage (Incoming, new PlainTextEncryption (), null, null, null, (successful, count, state) => {
                success = successful;
                handle.Set ();
            }, null);

            NetworkIO.EnqueueSend (Outgoing, data, 0, 20, null, null, null, delegate { }, null);
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (4)), "#Should have closed");;
            Assert.IsFalse (success, "#1");
        }

        [Test]
        public void ReceiveTwoKeepAlives ()
        {
            var message = new KeepAliveMessage ();
            var buffer = message.Encode ();
            var handle = new AutoResetEvent (false);

            NetworkIO.EnqueueSend (Outgoing, buffer, 0, buffer.Length, null, null, null, delegate { }, null);
            NetworkIO.EnqueueSend (Outgoing, buffer, 0, buffer.Length, null, null, null, delegate { }, null);

            AsyncMessageReceivedCallback callback = (s, m, state) => {
                if (s && m is KeepAliveMessage)
                    handle.Set ();
            };

            PeerIO.EnqueueReceiveMessage (Incoming, new PlainTextEncryption (), null, null, null, callback, null);
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (2)), "#Should receive first message");

            PeerIO.EnqueueReceiveMessage (Incoming, new PlainTextEncryption (), null, null, null, callback, null);
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (2)), "#Should receive second message");
        }

        [Test]
        public void ZeroReceivedClosesConnection ()
        {
            bool connectionOpen = true;
            AutoResetEvent handle = new AutoResetEvent(false);
            Incoming.ManualBytesReceived = 0;
            NetworkIO.EnqueueReceive (Incoming, data, 0, 100, null, null, null, (successful, count, state) => {
                connectionOpen = successful;
                handle.Set ();
            }, null);

            NetworkIO.EnqueueSend (Outgoing, data, 0, 100, null, null, null, delegate { }, null);
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (4)), "#1");
            Assert.IsFalse (connectionOpen, "#2");
        }

        [Test]
        public void ZeroSentClosesConnection ()
        {
            bool connectionOpen = true;
            AutoResetEvent handle = new AutoResetEvent(false);
            Incoming.ManualBytesSent = 0;
            NetworkIO.EnqueueSend (Incoming, data, 0, 100, null, null, null, (successful, count, state) => {
                connectionOpen = successful;
                handle.Set ();
            }, null);

            NetworkIO.EnqueueReceive (Outgoing, data, 0, 100, null, null, null, delegate { }, null);
            Assert.IsTrue (handle.WaitOne (TimeSpan.FromSeconds (4)), "#1");
            Assert.IsFalse (connectionOpen, "#2");
        }
    }
}


text:
pub const crypto_sign_edwards25519sha512batch_BYTES: usize = 64;
pub const crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES: usize = 32;
pub const crypto_sign_edwards25519sha512batch_SECRETKEYBYTES: usize = 64;

extern {
    pub fn crypto_sign_edwards25519sha512batch_keypair(
        pk: *mut [u8; crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES],
        sk: *mut [u8; crypto_sign_edwards25519sha512batch_SECRETKEYBYTES])
        -> c_int;
    pub fn crypto_sign_edwards25519sha512batch(
        sm: *mut u8,
        smlen: *mut c_ulonglong,
        m: *const u8,
        mlen: c_ulonglong,
        sk: *const [u8; crypto_sign_edwards25519sha512batch_SECRETKEYBYTES])
        -> c_int;
    pub fn crypto_sign_edwards25519sha512batch_open(
        m: *mut u8,
        mlen: *mut c_ulonglong,
        sm: *const u8,
        smlen: c_ulonglong,
        pk: *const [u8; crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES]) ->
        c_int;
    pub fn crypto_sign_edwards25519sha512batch_bytes() -> size_t;
    pub fn crypto_sign_edwards25519sha512batch_publickeybytes() -> size_t;
    pub fn crypto_sign_edwards25519sha512batch_secretkeybytes() -> size_t;
}

#[test]
fn test_crypto_sign_edwards25519sha512batch_bytes() {
    assert!(unsafe {
        crypto_sign_edwards25519sha512batch_bytes() as usize
    } == crypto_sign_edwards25519sha512batch_BYTES)
}
#[test]
fn test_crypto_sign_edwards25519sha512batch_publickeybytes() {
    assert!(unsafe {
        crypto_sign_edwards25519sha512batch_publickeybytes() as usize
    } == crypto_sign_edwards25519sha512batch_PUBLICKEYBYTES)
}
#[test]
fn test_crypto_sign_edwards25519sha512batch_secretkeybytes() {
    assert!(unsafe {
        crypto_sign_edwards25519sha512batch_secretkeybytes() as usize
    } == crypto_sign_edwards25519sha512batch_SECRETKEYBYTES)
}


text:
//代码生成时,文件路径: E:/platform/myProject/qbrm/code/quickbundle-securityweb/src.open/org/quickbundle/modules/code/rmcodedata/util/IRmCodeDataConstants.java
//代码生成时,系统时间: 2010-04-08 21:15:47.109
//代码生成时,操作系统用户: Administrator

/*
 * 系统名称:单表模板 --> quickbundle-securityweb
 *
 * 文件名称: org.quickbundle.modules.code.rmcodedata.util --> IRmCodeDataConstants.java
 *
 * 功能描述:
 *
 * 版本历史: 2010-04-08 21:15:47.109 创建1.0.0版 (白小勇)
 *
 */

package org.quickbundle.modules.code.rmcodedata.util;

import org.quickbundle.project.IGlobalConstants;

/**
 * 功能、用途、现存BUG:
 *
 * @author 白小勇
 * @version 1.0.0
 * @see 需要参见的其它类
 * @since 1.0.0
 */

public interface IRmCodeDataConstants extends IGlobalConstants {

    //Service的规范化名称
    public final static String SERVICE_KEY = "IRmCodeDataService";

    //Sql语句
    public final static String SQL_INSERT = "insert into RM_CODE_DATA ( ID, CODE_TYPE_ID, DATA_KEY, ENABLE_STATUS, DATA_VALUE, TOTAL_CODE, REMARK, USABLE_STATUS, MODIFY_DATE, MODIFY_IP, MODIFY_USER_ID) values ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";

    public final static String SQL_DELETE_BY_ID = "delete from RM_CODE_DATA where ID=?";

    public final static String SQL_DELETE_MULTI_BY_IDS = "delete from RM_CODE_DATA ";

    public final static String SQL_FIND_BY_ID = "select RM_CODE_DATA.ID, RM_CODE_DATA.CODE_TYPE_ID, (SELECT RM_CODE_TYPE.TYPE_KEYWORD FROM RM_CODE_TYPE WHERE RM_CODE_TYPE.ID=RM_CODE_DATA.CODE_TYPE_ID) CODE_TYPE_ID_NAME, RM_CODE_DATA.DATA_KEY, RM_CODE_DATA.ENABLE_STATUS, RM_CODE_DATA.DATA_VALUE, RM_CODE_DATA.TOTAL_CODE, RM_CODE_DATA.REMARK, RM_CODE_DATA.USABLE_STATUS, RM_CODE_DATA.MODIFY_DATE, RM_CODE_DATA.MODIFY_IP, RM_CODE_DATA.MODIFY_USER_ID from RM_CODE_DATA where RM_CODE_DATA.ID=?";

    public final static String SQL_UPDATE_BY_ID = "update RM_CODE_DATA set CODE_TYPE_ID=?, DATA_KEY=?, ENABLE_STATUS=?, DATA_VALUE=?, TOTAL_CODE=?, REMARK=?, USABLE_STATUS=?, MODIFY_DATE=?, MODIFY_IP=?, MODIFY_USER_ID=?  where ID=?";

    public final static String SQL_COUNT = "select count(RM_CODE_DATA.ID) from RM_CODE_DATA";

    public final static String SQL_QUERY_ALL = "select RM_CODE_DATA.ID, RM_CODE_DATA.CODE_TYPE_ID, (SELECT RM_CODE_TYPE.TYPE_KEYWORD FROM RM_CODE_TYPE WHERE RM_CODE_TYPE.ID=RM_CODE_DATA.CODE_TYPE_ID) CODE_TYPE_ID_NAME, RM_CODE_DATA.DATA_KEY, RM_CODE_DATA.ENABLE_STATUS, RM_CODE_DATA.DATA_VALUE, RM_CODE_DATA.TOTAL_CODE, RM_CODE_DATA.REMARK from RM_CODE_DATA";

	public final static String SQL_QUERY_ALL_EXPORT = "select RM_CODE_DATA.ID, RM_CODE_DATA.CODE_TYPE_ID, (SELECT RM_CODE_TYPE.TYPE_KEYWORD FROM RM_CODE_TYPE WHERE RM_CODE_TYPE.ID=RM_CODE_DATA.CODE_TYPE_ID) CODE_TYPE_ID_NAME, RM_CODE_DATA.DATA_KEY, RM_CODE_DATA.ENABLE_STATUS, RM_CODE_DATA.DATA_VALUE, RM_CODE_DATA.TOTAL_CODE, RM_CODE_DATA.REMARK, RM_CODE_DATA.USABLE_STATUS, RM_CODE_DATA.MODIFY_DATE, RM_CODE_DATA.MODIFY_IP, RM_CODE_DATA.MODIFY_USER_ID from RM_CODE_DATA";

    //表名
    public final static String TABLE_NAME = "RM_CODE_DATA";

    //表名汉化
    public final static String TABLE_NAME_CHINESE = "编码数据";

    //日志类型名称
    public final static String TABLE_LOG_TYPE_NAME = TABLE_NAME_CHINESE + "管理";

    //默认启用的查询条件
    public final static String DEFAULT_SQL_WHERE_USABLE = ""; //" where " + DESC_USABLE_STATUS_EVALUATE_ENABLE

    public final static String DEFAULT_SQL_CONTACT_KEYWORD = " where ";

    //默认的排序字段
    public final static String DEFAULT_ORDER_BY_CODE = ORDER_BY_SYMBOL + "DATA_KEY";

    //子表查询条件,[0]作为默认条件查询字段
    public final static String[] DEFAULT_CONDITION_KEY_ARRAY = new String[]{"code_type_id", "code_type_id_name" };
}


text:
Refinery::Plugin.register do |plugin|
  plugin.title = "News"
  plugin.description = "Provides a blog-like news section"
  plugin.version = 1.0
  plugin.menu_match = /admin\/news(_items)?$/
  plugin.activity = {
    :class => NewsItem,
    :title => 'title',
    :url_prefix => 'edit'
  }
end


text:
/**
 *    @file
 *      This file implements the command handler for the 'weave' tool
 *      that converts a Weave certificate between TLV and X.509
 *      formats.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include <errno.h>
#include <unistd.h>

#include "weave-tool.h"

using namespace nl::Weave::Profiles::Security;

#define CMD_NAME "weave convert-cert"

static bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg);
static bool HandleNonOptionArgs(const char *progName, int argc, char *argv[]);

static OptionDef gCmdOptionDefs[] =
{
    { "x509",       kNoArgument, 'p' },
    { "x509-pem",   kNoArgument, 'p' }, // alias for --x509
    { "x509-der",   kNoArgument, 'x' },
    { "weave",      kNoArgument, 'w' },
    { "weave-b64",  kNoArgument, 'b' },
    { }
};

static const char *const gCmdOptionHelp =
    "  -p, --x509, --x509-pem\n"
    "\n"
    "       Output an X.509 certificate in PEM format.\n"
    "\n"
    "  -x, --x509-der\n"
    "\n"
    "       Output an X.509 certificate in DER format.\n"
    "\n"
    "  -w, --weave\n"
    "\n"
    "       Output a Weave certificate in raw TLV format.\n"
    "\n"
    "  -b --weave-b64\n"
    "\n"
    "       Output a Weave certificate in base-64 format.\n"
    "\n"
    ;

static OptionSet gCmdOptions =
{
    HandleOption,
    gCmdOptionDefs,
    "COMMAND OPTIONS",
    gCmdOptionHelp
};

static HelpOptions gHelpOptions(
    CMD_NAME,
    "Usage: " CMD_NAME " [ <options...> ] <in-file> <out-file>\n",
    WEAVE_VERSION_STRING "\n" COPYRIGHT_STRING,
    "Convert a certificate between Weave and X509 forms.\n"
    "\n"
    "ARGUMENTS\n"
    "\n"
    "  <in-file>\n"
    "\n"
    "       The input certificate file name, or - to read from stdin. The\n"
    "       format of the input certificate is auto-detected and can be any\n"
    "       of: X.509 PEM, X.509 DER, Weave base-64 or Weave raw TLV.\n"
    "\n"
    "  <out-file>\n"
    "\n"
    "       The output certificate file name, or - to write to stdout.\n"
    "\n"
);

static OptionSet *gCmdOptionSets[] =
{
    &gCmdOptions,
    &gHelpOptions,
    NULL
};

static const char *gInFileName = NULL;
static const char *gOutFileName = NULL;
static CertFormat gOutCertFormat = kCertFormat_Weave_Base64;

bool Cmd_ConvertCert(int argc, char *argv[])
{
    static uint8_t inCert[MAX_CERT_SIZE];
    static uint8_t outCert[MAX_CERT_SIZE];

    bool res = true;
    WEAVE_ERROR err;
    FILE *inFile = NULL;
    FILE *outFile = NULL;
    uint32_t inCertLen = 0;
    CertFormat inCertFormat;
    uint32_t outCertLen = 0;
    bool outFileCreated = false;

    if (argc == 1)
    {
        gHelpOptions.PrintBriefUsage(stderr);
        ExitNow(res = true);
    }

    if (!ParseArgs(CMD_NAME, argc, argv, gCmdOptionSets, HandleNonOptionArgs))
    {
        ExitNow(res = false);
    }

    if (strcmp(gInFileName, "-") != 0)
    {
        inFile = fopen(gInFileName, "rb");
        if (inFile == NULL)
        {
            fprintf(stderr, "weave: Unable to open %s\n%s\n", gInFileName, strerror(errno));
            ExitNow(res = false);
        }
    }
    else
        inFile = stdin;

    inCertLen = fread(inCert, 1, sizeof(inCert), inFile);
    if (ferror(inFile))
    {
        fprintf(stderr, "weave: Error reading %s\n%s\n", gInFileName, strerror(errno));
        ExitNow(res = false);
    }

    if (inCertLen == sizeof(inCert))
    {
        fprintf(stderr, "weave: Input certificate too big\n");
        ExitNow(res = false);
    }

    if (!InitOpenSSL())
        ExitNow(res = false);

    inCertFormat = DetectCertFormat(inCert, inCertLen);

    if (inCertFormat == gOutCertFormat)
    {
        memcpy(outCert, inCert, inCertLen);
        outCertLen = inCertLen;
    }

    else
    {
        if (inCertFormat == kCertFormat_X509_PEM)
        {
            if (!X509PEMToDER(inCert, inCertLen))
                ExitNow(res = false);
            inCertFormat = kCertFormat_X509_DER;
        }
        else if (inCertFormat == kCertFormat_Weave_Base64)
        {
            if (!Base64Decode(inCert, inCertLen, inCert, sizeof(inCert), inCertLen))
                ExitNow(res = false);
            inCertFormat = kCertFormat_Weave_Raw;
        }

        if (inCertFormat == kCertFormat_X509_DER && (gOutCertFormat == kCertFormat_Weave_Raw || gOutCertFormat == kCertFormat_Weave_Base64))
        {
            err = ConvertX509CertToWeaveCert(inCert, inCertLen, outCert, sizeof(outCert), outCertLen);
            if (err != WEAVE_NO_ERROR)
            {
                fprintf(stderr, "weave: Error converting certificate: %s\n", nl::ErrorStr(err));
                ExitNow(res = false);
            }
        }
        else if (inCertFormat == kCertFormat_Weave_Raw && (gOutCertFormat == kCertFormat_X509_DER || gOutCertFormat == kCertFormat_X509_PEM))
        {
            err = ConvertWeaveCertToX509Cert(inCert, inCertLen, outCert, sizeof(outCert), outCertLen);
            if (err != WEAVE_NO_ERROR)
            {
                fprintf(stderr, "weave: Error converting certificate: %s\n", nl::ErrorStr(err));
                ExitNow(res = false);
            }
        }
        else
        {
            memcpy(outCert, inCert, inCertLen);
            outCertLen = inCertLen;
        }

        if (gOutCertFormat == kCertFormat_X509_PEM)
        {
            if (!X509DERToPEM(outCert, outCertLen, sizeof(outCert)))
                ExitNow(res = false);
        }
        else if (gOutCertFormat == kCertFormat_Weave_Base64)
        {
            if (!Base64Encode(outCert, outCertLen, outCert, sizeof(outCert), outCertLen))
                ExitNow(res = false);
        }
    }

    if (strcmp(gOutFileName, "-") != 0)
    {
        outFile = fopen(gOutFileName, "w+b");
        if (outFile == NULL)
        {
            fprintf(stderr, "weave: ERROR: Unable to create %s\n%s\n", gOutFileName, strerror(errno));
            ExitNow(res = false);
        }
        outFileCreated = true;
    }
    else
        outFile = stdout;

    if (fwrite(outCert, 1, outCertLen, outFile) != outCertLen)
    {
        fprintf(stderr, "weave: ERROR: Unable to write to %s\n%s\n", gOutFileName, strerror(ferror(outFile) ? errno : ENOSPC));
        ExitNow(res = false);
    }

exit:
    if (inFile != NULL && inFile != stdin)
        fclose(inFile);
    if (outFile != NULL && outFile != stdout)
        fclose(outFile);
    if (gOutFileName != NULL && outFileCreated && !res)
        unlink(gOutFileName);
    return res;
}

bool HandleOption(const char *progName, OptionSet *optSet, int id, const char *name, const char *arg)
{
    switch (id)
    {
    case 'p':
        gOutCertFormat = kCertFormat_X509_PEM;
        break;
    case 'x':
        gOutCertFormat = kCertFormat_X509_DER;
        break;
    case 'b':
        gOutCertFormat = kCertFormat_Weave_Base64;
        break;
    case 'w':
        gOutCertFormat = kCertFormat_Weave_Raw;
        break;
    default:
        PrintArgError("%s: INTERNAL ERROR: Unhandled option: %s\n", progName, name);
        return false;
    }

    return true;
}

bool HandleNonOptionArgs(const char *progName, int argc, char *argv[])
{
    if (argc == 0)
    {
        PrintArgError("%s: Please specify the name of the input certificate file, or - for stdin.\n", progName);
        return false;
    }

    if (argc == 1)
    {
        PrintArgError("%s: Please specify the name of the output certificate file, or - for stdout\n", progName);
        return false;
    }

    if (argc > 2)
    {
        PrintArgError("%s: Unexpected argument: %s\n", progName, argv[2]);
        return false;
    }

    gInFileName = argv[0];
    gOutFileName = argv[1];

    return true;
}


text:
package net.violet.platform.api.maps;

import net.violet.platform.journal.JournalEntry;
import net.violet.platform.util.CCalendar;

public class LoggerEntryMap extends AbstractAPIMap {

	public static final String WHEN = "when";
	public static final String WHAT = "what";

	public LoggerEntryMap(JournalEntry entry, boolean useDate) {
		super(2);
		put(LoggerEntryMap.WHAT, entry.getWhat());
		put(LoggerEntryMap.WHEN, useDate ? new CCalendar(entry.getWhen()).getUTCDateTimeFormated() : entry.getWhen());
	}

}


text:
import scrapy

class HouseItem(scrapy.Item):
    name = scrapy.Field()
    size = scrapy.Field()
    price = scrapy.Field()
    sold = scrapy.Field()

class BaseInfoItem(scrapy.Item):
    name = scrapy.Field()
    num = scrapy.Field()

class CompanyItem(BaseInfoItem):
    company_name = scrapy.Field()
    vocation = scrapy.Field()
    province = scrapy.Field()
    web_home = scrapy.Field()
    start_date = scrapy.Field()

class FinanceItem(BaseInfoItem):
    # define the fields for your item here like:
    benefit = scrapy.Field()
    debt = scrapy.Field()
    cash = scrapy.Field()
    # main = scrapy.Field()
    # each = scrapy.Field()
    # operate = scrapy.Field()
    # grow = scrapy.Field()
    # pay = scrapy.Field()
    pass

class CapitalItem(BaseInfoItem):
    date = scrapy.Field()
    count = scrapy.Field()

class HistoryPriceItem(BaseInfoItem):
    date = scrapy.Field()
    start_price = scrapy.Field()
    max_price = scrapy.Field()
    min_price = scrapy.Field()
    end_price = scrapy.Field()
    total_count = scrapy.Field()
    total_price = scrapy.Field()
    change_rate = scrapy.Field()

if __name__ == '__main__':
    stock_count = 0.9472
    # pe = 18.0
    price = 35.41
    rad_year = 0.25
    in_per_last = 0.77
    in_per = (in_per_last*(1+rad_year)) # price / pe
    years = 10
    total_price = stock_count * price

    print total_price
    print "pe0=", price/in_per_last
    print "pe1=", price/(0.35*(in_per_last/0.14))
    print "pe2=", price/(in_per_last*(1+rad_year))

    for i in range(years):
        if i > 0:
            in_per = in_per * (1 + rad_year)
        price = price + in_per
        print i, price, in_per, price / in_per

    # print price


text:
// staticchecking/petspeak.go
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
package main
import "fmt"

type Cat struct {}
func (this Cat) speak() { fmt.Printf("meow!\n")}

type Dog struct {}
func (this Dog) speak() { fmt.Printf("woof!\n")}

type Bob struct {}
func (this Bob) bow() {
  fmt.Printf("thank you, thank you!\n")
}
func (this Bob) speak() {
  fmt.Printf("Welcome to the neighborhood!\n")
}
func (this Bob) drive() {
  fmt.Printf("beep, beep!\n")
}

type Speaker interface {
  speak()
}

func command(s Speaker) { s.speak() }

// If "Speaker" is never used
// anywhere else, it can be anonymous:
func command2(s interface { speak() }) { s.speak() }

func main() {
  command(Cat{})
  command(Dog{})
  command(Bob{})
  command2(Cat{})
  command2(Dog{})
  command2(Bob{})
}

/* Output:
meow!
woof!
Welcome to the neighborhood!
meow!
woof!
Welcome to the neighborhood!
*/


text:
<?xml version="1.0" encoding="utf-8"?>
<executable>
  <category>;Segmentation.Bender</category>
  <index>3</index>
  <title>Compute Armature Weight</title>
  <description><![CDATA[Compute the weight of the Input Armature edges for each voxel of the Input Rest Labelmap using heat diffusion.
This module outputs a serie of files named "weight_i.mha" in the Weight Output Directory, where each voxel has the weight associated to the armature edge #i from the Input Armature.

When computing non-binary weight, the skeleton voxels of the Input Rest Labelmap (inside the partition given by the Input Skinned Labelmap) are used as hot source for the heat-diffusion process. This means that any bone within the weight partition will have a weight of 1. This implies that if that edge is posed, the bone will move completely with that edge. The other voxels weight is determined by diffusing the weight from the hot sources (i.e. bones).
]]>
  </description>
  <version>1.1.0</version>
  <documentation-url>http://public.kitware.com/Wiki/Bender/Documentation/1.1/Modules/ComputeArmatureWeight</documentation-url>
  <license/>
  <contributor>Yuanxin Liu (Kitware), Julien Finet (Kitware), Johan Andruejol (Kitware)</contributor>
  <acknowledgements><![CDATA[Air Force Research Laboratories]]></acknowledgements>
  <parameters>
    IO
    <description><![CDATA[Input/output parameters]]></description>

    <image type="label">
      <name>RestLabelmap</name>
      Input Rest Labelmap
      <description><![CDATA[Labelmap for which the weights will be computed. This should be the labelmap for which the Input Armature was created and the Input Skinned Labelmap computed.]]></description>
      <channel>input</channel>
      <index>0</index>
    </image>

    <geometry fileExtensions=".vtk">
      <name>ArmaturePoly</name>
      Input Armature
      <description><![CDATA[Armature in rest position. This should be the armature associated with the Input Skinned Labelmap.]]></description>
      <channel>input</channel>
      <index>1</index>
    </geometry>

    <image type="label">
      <name>SkinnedVolume</name>
      Input Skinned Labelmap
      <description><![CDATA[Volume skinning associated with the Input Armature. This volume represents which voxel of the Input Rest Labelmap is associated to which Input Rest Armature's edge.
For a given edge i of the Input Rest Armature, the volume region associated with it will have the label i + 2. The label 0 is reserved for the outside of the <Input Rest Labelmap body and the label 1 for invalid areas.
]]></description>
      <channel>input</channel>
      <index>2</index>
    </image>

    <directory>
      <name>WeightDirectory</name>
      Weight Output Directory
      <description><![CDATA[The directory used to store the weight files.
This directory needs write access and enough space.
]]></description>
      <channel>output</channel>
      <index>3</index>
      <default>./</default>
    </directory>

  </parameters>

  <parameters>
    Labels
    <description><![CDATA[Set the input necessary labels value here.]]></description>
    <double>
      <name>BackgroundValue</name>
      Background Value
      <description><![CDATA[The voxel value considered as background. All the other voxel values will be treated as foreground.]]></description>
      <longflag>--backgroundValue</longflag>
      <default>0.</default>
    </double>
    <integer>
      <name>BoneLabel</name>
      Bone Label
      <description><![CDATA[The bone label is used as the source of the weight heat-diffusion process.
This means that the structure in the Input Rest Labelmap with this label will act as a bone for the other pixels. Any pixel within this structure will be posed exactly as its associated armature's edge. The other voxels will move according to the computed weight obtained from the heat diffusion process.

In a human model, it is advised to set the Bone Label to the Input Rest Labelmap bone label in order to mimick the human anatomy as closely as possible when posing the Input Rest Labelmap.
]]></description>
      <longflag>--boneLabel</longflag>
      <default>1</default>
    </integer>
  </parameters>

  <parameters>
    Controls
    <description><![CDATA[Control how the module operates.]]></description>
    <integer>
      <name>FirstEdge</name>
      Start Edge
      <description><![CDATA[The first Input Armature egde to process. This specifies the start of the continuous range of bones for which the weights will be generated.]]></description>
      <longflag>--first</longflag>
      <default>0</default>
    </integer>

    <integer>
      <name>LastEdge</name>
      <description><![CDATA[The last Input Armature egde to process. This specifies the end of the continuous range of bones for which the weights will be generated. If -1 is specifed, all the bones starting from Start Edge will be processed.]]></description>
      End edge
      <longflag>--last</longflag>
      <default>-1</default>
    </integer>

    <integer>
      <name>SmoothingIteration</name>
      <longflag>--smooth</longflag>
      Smoothing Iteration Number
      <description><![CDATA[Number of iterations used for smoothing the weights locally. This is only necessary because we restrict the solving to a local region]]></description>
      <default>10</default>
    </integer>

    <double>
      <name>ScaleFactor</name>
      <longflag>--scaleFactor</longflag>
      Computation Scale Factor
      <description><![CDATA[Scale factor applied to the input images to speed up the processing.
When different from 1, the input images will be downsampled before any processing. Then the weights are computed on the downsampled images. After the computation, the weights are upsampled back to the original input image spacing. It is highly encouraged to use a sparser spacing than the input image to prevent very slow computation.
]]></description>
      <default>2</default>
    </double>

    <integer>
      <name>Padding</name>
      <longflag>--padding</longflag>
      Padding
      <description><![CDATA[How far (in voxel units) outside the body the weight region will be computed. If any padding is precised, the weight will be computed using a dilated version of the input images.]]></description>
      <default>1</default>
    </integer>

  </parameters>
  <parameters advanced="true">
    Advanced
    <description><![CDATA[Advanced properties]]></description>

    <boolean>
      <name>Debug</name>
      Debug Mode
      <longflag>--debug</longflag>
      <description><![CDATA[Print debug logs and dump intermediate images. The debug information will be outputed to a "Debug" folder in the Weight Output Directory.]]></description>
      <default>false</default>
    </boolean>

    <boolean>
      <name>IsArmatureInRAS</name>
      Armature in RAS
      <description><![CDATA[Whether input armature is already in the RAS(Right, Anterior, Superior) coordinate system (true) or in LPS (Left, Posterior, Superior) coordinate system (false, default). If not, it will be internally transformed into RAS.]]></description>
      <longflag>--armatureInRAS</longflag>
      <default>false</default>
    </boolean>

    <boolean>
      <name>BinaryWeight</name>
      Use Binary Weight
      <flag>-b</flag>
      <longflag>--binary</longflag>
      <description><![CDATA[For Debugging only. Outputs binary weight instead of normal weights. Binary weights are simply the Input Skinned Labelmap region associated with each edge of the Input Armature.]]></description>
      <default>false</default>
    </boolean>

    <boolean>
      <name>RunSequential</name>
      Run Sequential
      <longflag>--sequential</longflag>
      <description><![CDATA[Runs the computation of each bone sequentially instead of multi-threaded. By default, the module starts parallel threads to compute the weights. In this case the module consumes considerably more memory which may be an issue.]]></description>
      <default>false</default>
    </boolean>

    <integer>
      <name>MaximumParenthoodDistance</name>
      Maximum Parenthood Distance
      <longflag>--distance</longflag>
      <description><![CDATA[Use this parameter to automatically prevent the propagation of the weight heat diffusion in region that belongs to bones too far in the family tree. For example, with Maximum Parenthood Distance set to 1, the diffusion will be limited to the bone's parent and children. The default (-1) means any distance is allowed, i.e. the weight can diffuse in any regions.]]></description>
      <default>-1</default>
    </integer>

  </parameters>

</executable>


text:
<?php
namespace Controllers;

use Core\View;
use Core\Controller;

use Helpers\Session;
use Helpers\Url;
use Helpers\Gump;
use Helpers\Auth;

use Models\User;
use Models\Post;

/*
 * Welcome controller
 *
 * @author David Carr - dave@simplemvcframework.com
 * @version 2.2
 * @date June 27, 2014
 * @date updated May 18 2015
 */
class Home extends Controller
{

    /**
     * Call the parent construct
     */
    public function __construct()
    {
        parent::__construct();
        $this->language->load('Welcome');
    }

    /**
     * Define Index page title and load template files
     */
    public function index()
    {
        $this->data['title'] = 'Home';

        // $albumModel = new \Models\Album;
        // $albumitemModel = new \Models\Albumitem;

        // $this->data['slider'] = $albumModel->name('homes');

        View::renderTemplate('header2', $this->data);
        View::render('home/home.index', $this->data);
        View::renderTemplate('footer2', $this->data);
    }

}


text:
<?php

namespace Blogger\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity
 * @UniqueEntity(fields="email", message="Este email ja existe. Por favor registe outro.")
 */
class User implements UserInterface, \Serializable
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Email()
     */
    protected $email;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(max = 4096)
     */
    protected $username;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\NotBlank()
     * @Assert\Length(max = 4096)
     */
    protected $password;

    public function getId()
    {
        return $this->id;
    }

    public function getEmail()
    {
        return $this->email;
    }

    public function setEmail($email)
    {
        $this->email = $email;
    }

    public function getUsername()
    {
        return $this->username;
    }

    public function setUsername($username)
    {
        $this->username = $username;
    }

    public function getPassword()
    {
        return $this->password;
    }

    public function setPassword($password)
    {
        $this->password = $password;
    }

    /**
     * @ORM\Column(type="string", length=32)
    */
    private $salt;

    public function setSalt($salt)
    {
        $this->salt = $salt;
    }

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    public function __construct()
    {
        $this->isActive = true;
        $this->salt = md5(uniqid(null, true));
    }

    /**
     * @inheritDoc
     */
    public function getSalt()
    {
        return $this->salt;
    }

    /**
     * @inheritDoc
     */
    public function getRoles()
    {
        return array('ROLE_USER');
    }

    /**
     * @inheritDoc
     */
    public function eraseCredentials()
    {
    }

    /**
     * @see \Serializable::serialize()
     */
    public function serialize()
    {
        return serialize(array(
            $this->id,
        ));
    }

    /**
     * @see \Serializable::unserialize()
     */
    public function unserialize($serialized)
    {
        list (
            $this->id,
        ) = unserialize($serialized);
    }
}


text:
ROOT_PASSWORD=$1
MYSQL_CMD="mysql --protocol tcp -h mysql -P 3306"

echo | $MYSQL_CMD -u root -p$ROOT_PASSWORD << END_OF_SCRIPT
CREATE DATABASE commentbox;
GRANT ALL PRIVILEGES ON commentbox.* TO 'comments'@'%' IDENTIFIED BY 'comments';
END_OF_SCRIPT

echo 'show tables;' | $MYSQL_CMD -u comments -pcomments commentbox


text: installBiocDataPackage.sh "bcellviper-1.34.0"


text:
/* exported APP */
var APP = window.APP || {};
APP.namespace('modules.Twitter');
APP.modules.Twitter = (function() {
  'use strict';

  var // Default module variables / dependencies
    app = window.APP,
    $ = window.jQuery,

    module = $.extend(app.modules.Twitter, {
      // Public PROPERTIES and METHODS
      'NAME': 'APP.modules.Twitter'
    }),
    PATH_SERVICE = 'http://twitter.com/intent/tweet?url={{url}}&text={{text}}';

  module.share = function(url, text, useRedirect) {
    if (!url) {
      throw new Error('[Twitter error:: Required parameter @url is missing.');
    }

    var urlApi = PATH_SERVICE.replace('{{url}}', encodeURIComponent(url)).replace('{{text}}', (text ? encodeURIComponent(text) : ''));

    if (!useRedirect) {
      window.open(urlApi, '_blank');
      return;
    }

    window.location.href = urlApi;
  };

  return module;
}());


text:
def sum_numbers(x):
    '''
    x is a string, search for all numbers and sum them
    '''
    total = 0
    current_num = ""
    for char in x:
        if char.isdigit():
            current_num += char
        else:
            if current_num:
                total += int(current_num)
                current_num = ""
    current_num = 0 if not current_num else current_num
    return total + int(current_num) # case where num was @ end of string

print(sum_numbers("abc123xyz"))
print(sum_numbers("aa11b33"))
print(sum_numbers("7 11"))


text:
function load(swipe, prevState) {
  const str = JSON.stringify(swipe, undefined, 2);
  console.log(str);
  const sceneElements = swipe.templates.pages.s0.elements;
  const elementMap = sceneElements.reduce((map, element)=>{
    map[element.id] = element;
    return map;
  }, {});
  const pages = swipe.pages.map((page) => {
    if (page.elements) {
      return page.elements.reduce((ret, element)=>{
        var value = {};
        const sceneElement = elementMap[element.id];
        //console.log("load.map", sceneElement);
        if (element.to) {
          //console.log('load:element=', JSON.stringify(element.to));
          if (element.to.translate) {
            value.translate = element.to.translate;
          }
          if (element.to.opacity) {
            value.opacity = element.to.opacity;
          }
          if (element.to.rotate) {
            value.rotate = element.to.rotate;
            if (sceneElement.rotate) {
              value.rotate -= sceneElement.rotate;
            }
          }
          if (element.to.scale) {
            value.scale = element.to.scale;
            if (sceneElement.scale) {
              value.scale[0] /= sceneElement.scale[0];
              value.scale[1] /= sceneElement.scale[1];
            }
          }
          if (element.to.timing) {
            console.log('loader:element:timing', JSON.stringify(element.to.timing));
            value.timing = element.to.timing;
          }
        }
        if (element.loop) {
          console.log('loader:element:loop', JSON.stringify(element.loop));
          value.loop = element.loop;
        }
        ret[element.id] = value;
        return ret;
      }, {});
    }
    return {}
  });
  var state = {
    selection:{ids:new Set()},
    pageIndex:pages.length > 0 ? 0 : -1,
    preview:false,
    dimension:{ width:swipe.dimension[0] || 320, height:swipe.dimension[1] || 320 },
    elements:sceneElements,
    pages:pages,
    nextIndex:sceneElements.length
  };
  return state;
}

module.exports = { load };


text:
import type { Comment, CommentReply, CommentsState } from '../state/comments';

const remoteReply: CommentReply = {
  localId: 2,
  remoteId: 2,
  mode: 'default',
  author: { id: 1, name: 'test user' },
  date: 0,
  text: 'a reply',
  originalText: 'a reply',
  newText: '',
  deleted: false,
};

const localReply: CommentReply = {
  localId: 3,
  remoteId: null,
  mode: 'default',
  author: { id: 1, name: 'test user' },
  date: 0,
  text: 'another reply',
  originalText: 'another new reply',
  newText: '',
  deleted: false,
};

const remoteComment: Comment = {
  contentpath: 'test_contentpath',
  position: '',
  localId: 1,
  annotation: null,
  remoteId: 1,
  mode: 'default',
  deleted: false,
  resolved: false,
  author: { id: 1, name: 'test user' },
  date: 0,
  text: 'test text',
  originalText: 'test text',
  newReply: '',
  newText: '',
  remoteReplyCount: 1,
  replies: new Map([[remoteReply.localId, remoteReply], [localReply.localId, localReply]]),
};

const localComment: Comment = {
  contentpath: 'test_contentpath_2',
  position: '',
  localId: 4,
  annotation: null,
  remoteId: null,
  mode: 'default',
  deleted: false,
  resolved: false,
  author: { id: 1, name: 'test user' },
  date: 0,
  text: 'unsaved comment',
  originalText: 'unsaved comment',
  newReply: '',
  newText: '',
  replies: new Map(),
  remoteReplyCount: 0,
};

export const basicCommentsState: CommentsState = {
  focusedComment: 1,
  forceFocus: false,
  pinnedComment: 1,
  remoteCommentCount: 1,
  comments: new Map([[remoteComment.localId, remoteComment], [localComment.localId, localComment]]),
};


text:
package com.intellij.ide.bookmarks;

import com.intellij.codeInsight.daemon.GutterMark;
import com.intellij.icons.AllIcons;
import com.intellij.ide.IdeBundle;
import com.intellij.ide.structureView.StructureViewBuilder;
import com.intellij.ide.structureView.StructureViewModel;
import com.intellij.ide.structureView.TreeBasedStructureViewBuilder;
import com.intellij.lang.LanguageStructureViewBuilder;
import com.intellij.navigation.ItemPresentation;
import com.intellij.navigation.NavigationItem;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.colors.CodeInsightColors;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.colors.EditorFontType;
import com.intellij.openapi.editor.ex.MarkupModelEx;
import com.intellij.openapi.editor.ex.RangeHighlighterEx;
import com.intellij.openapi.editor.impl.DocumentMarkupModel;
import com.intellij.openapi.editor.markup.GutterIconRenderer;
import com.intellij.openapi.editor.markup.HighlighterLayer;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Ref;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.pom.Navigatable;
import com.intellij.psi.PsiFile;
import com.intellij.psi.PsiManager;
import com.intellij.reference.SoftReference;
import com.intellij.ui.ColorUtil;
import com.intellij.ui.JBColor;
import com.intellij.ui.RetrievableIcon;
import com.intellij.util.IconUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.PlatformIcons;
import com.intellij.util.ui.JBUI;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.geom.Rectangle2D;
import java.lang.ref.Reference;
import java.lang.ref.WeakReference;

public class Bookmark implements Navigatable, Comparable<Bookmark> {
  public static final Icon DEFAULT_ICON = new MyCheckedIcon();

  private final VirtualFile myFile;
  @NotNull private OpenFileDescriptor myTarget;
  private final Project myProject;
  private Reference<RangeHighlighterEx> myHighlighterRef;

  private String myDescription;
  private char myMnemonic = 0;

  public Bookmark(@NotNull Project project, @NotNull VirtualFile file, int line, @NotNull String description) {
    myFile = file;
    myProject = project;
    myDescription = description;

    myTarget = new OpenFileDescriptor(project, file, line, -1, true);

    addHighlighter();
  }

  @NotNull
  public static Font getBookmarkFont() {
    return EditorColorsManager.getInstance().getGlobalScheme().getFont(EditorFontType.PLAIN);
  }

  @Override
  public int compareTo(Bookmark o) {
    int i = myMnemonic != 0 ? o.myMnemonic != 0 ? myMnemonic - o.myMnemonic : -1: o.myMnemonic != 0 ? 1 : 0;
    if (i != 0) return i;
    i = myProject.getName().compareTo(o.myProject.getName());
    if (i != 0) return i;
    i = myFile.getName().compareTo(o.getFile().getName());
    if (i != 0) return i;
    return getTarget().compareTo(o.getTarget());
  }

  public void updateHighlighter() {
    release();
    addHighlighter();
  }

  private void addHighlighter() {
    Document document = FileDocumentManager.getInstance().getCachedDocument(getFile());
    if (document != null) {
      createHighlighter((MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true));
    }
  }

  public RangeHighlighter createHighlighter(@NotNull MarkupModelEx markup) {
    final RangeHighlighterEx highlighter;
    int line = getLine();
    if (line >= 0) {
      highlighter = markup.addPersistentLineHighlighter(line, HighlighterLayer.ERROR + 1, null);
      if (highlighter != null) {
        highlighter.setGutterIconRenderer(new MyGutterIconRenderer(this));

        TextAttributes textAttributes =
          ObjectUtils.notNull(EditorColorsManager.getInstance().getGlobalScheme().getAttributes(CodeInsightColors.BOOKMARKS_ATTRIBUTES),
                              new TextAttributes());
        Color stripeColor = ObjectUtils.notNull(textAttributes.getErrorStripeColor(), new JBColor(0x000000, 0xdbdbdb));
        highlighter.setErrorStripeMarkColor(stripeColor);
        highlighter.setErrorStripeTooltip(getBookmarkTooltip());

        TextAttributes attributes = highlighter.getTextAttributes();
        if (attributes == null) {
          attributes = new TextAttributes();
        }
        attributes.setBackgroundColor(textAttributes.getBackgroundColor());
        attributes.setForegroundColor(textAttributes.getForegroundColor());
        highlighter.setTextAttributes(attributes);
      }
    }
    else {
      highlighter = null;
    }
    myHighlighterRef = highlighter == null ? null : new WeakReference<>(highlighter);
    return highlighter;
  }

  @Nullable
  public Document getDocument() {
    return FileDocumentManager.getInstance().getCachedDocument(getFile());
  }

  public void release() {
      int line = getLine();
      if (line < 0) {
        return;
      }
      final Document document = getDocument();
      if (document == null) return;
      MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);
      final Document markupDocument = markup.getDocument();
      if (markupDocument.getLineCount() <= line) return;
      RangeHighlighterEx highlighter = findMyHighlighter();
      if (highlighter != null) {
        myHighlighterRef = null;
        highlighter.dispose();
      }
  }

  private RangeHighlighterEx findMyHighlighter() {
    final Document document = getDocument();
    if (document == null) return null;
    RangeHighlighterEx result = SoftReference.dereference(myHighlighterRef);
    if (result != null) {
      return result;
    }
    MarkupModelEx markup = (MarkupModelEx)DocumentMarkupModel.forDocument(document, myProject, true);
    final Document markupDocument = markup.getDocument();
    final int startOffset = 0;
    final int endOffset = markupDocument.getTextLength();

    final Ref<RangeHighlighterEx> found = new Ref<>();
    markup.processRangeHighlightersOverlappingWith(startOffset, endOffset, highlighter -> {
      GutterMark renderer = highlighter.getGutterIconRenderer();
      if (renderer instanceof MyGutterIconRenderer && ((MyGutterIconRenderer)renderer).myBookmark == this) {
        found.set(highlighter);
        return false;
      }
      return true;
    });
    result = found.get();
    myHighlighterRef = result == null ? null : new WeakReference<>(result);
    return result;
  }

  public Icon getIcon() {
    return myMnemonic == 0 ? DEFAULT_ICON : MnemonicIcon.getIcon(myMnemonic);
  }

  public String getDescription() {
    return myDescription;
  }

  public void setDescription(String description) {
    myDescription = description;
  }

  public char getMnemonic() {
    return myMnemonic;
  }

  public void setMnemonic(char mnemonic) {
    myMnemonic = Character.toUpperCase(mnemonic);
  }

  @NotNull
  public VirtualFile getFile() {
    return myFile;
  }

  @Nullable
  public String getNotEmptyDescription() {
    return StringUtil.isEmpty(myDescription) ? null : myDescription;
  }

  public boolean isValid() {
    if (!getFile().isValid()) {
      return false;
    }
    if (getLine() ==-1) {
      return true;
    }
    RangeHighlighterEx highlighter = findMyHighlighter();
    return highlighter != null && highlighter.isValid();
  }

  @Override
  public boolean canNavigate() {
    return getTarget().canNavigate();
  }

  @Override
  public boolean canNavigateToSource() {
    return getTarget().canNavigateToSource();
  }

  @Override
  public void navigate(boolean requestFocus) {
    getTarget().navigate(requestFocus);
  }

  public int getLine() {
    int targetLine = myTarget.getLine();
    if (targetLine == -1) return targetLine;
    //What user sees in gutter
    RangeHighlighterEx highlighter = findMyHighlighter();
    if (highlighter != null && highlighter.isValid()) {
      Document document = getDocument();
      if (document != null) {
        return document.getLineNumber(highlighter.getStartOffset());
      }
    }
    RangeMarker marker = myTarget.getRangeMarker();
    if (marker != null && marker.isValid()) {
      Document document = marker.getDocument();
      return document.getLineNumber(marker.getStartOffset());
    }
    return targetLine;
  }

  private OpenFileDescriptor getTarget() {
    int line = getLine();
    if (line != myTarget.getLine()) {
      myTarget = new OpenFileDescriptor(myProject, myFile, line, -1, true);
    }
    return myTarget;
  }

  @Override
  public String toString() {
    StringBuilder result = new StringBuilder(getQualifiedName());
    String description = StringUtil.escapeXml(getNotEmptyDescription());
    if (description != null) {
      result.append(": ").append(description);
    }
    return result.toString();
  }

  public String getQualifiedName() {
    String presentableUrl = myFile.getPresentableUrl();
    if (myFile.isDirectory()) return presentableUrl;

    final PsiFile psiFile = PsiManager.getInstance(myProject).findFile(myFile);

    if (psiFile == null) return presentableUrl;

    StructureViewBuilder builder = LanguageStructureViewBuilder.INSTANCE.getStructureViewBuilder(psiFile);
    if (builder instanceof TreeBasedStructureViewBuilder) {
      StructureViewModel model = ((TreeBasedStructureViewBuilder)builder).createStructureViewModel(null);
      Object element;
      try {
        element = model.getCurrentEditorElement();
      }
      finally {
        model.dispose();
      }
      if (element instanceof NavigationItem) {
        ItemPresentation presentation = ((NavigationItem)element).getPresentation();
        if (presentation != null) {
          presentableUrl = ((NavigationItem)element).getName() + " " + presentation.getLocationString();
        }
      }
    }

    return IdeBundle.message("bookmark.file.X.line.Y", presentableUrl, getLine() + 1);
  }

  private String getBookmarkTooltip() {
    StringBuilder result = new StringBuilder("Bookmark");
    if (myMnemonic != 0) {
      result.append(" ").append(myMnemonic);
    }
    String description = StringUtil.escapeXml(getNotEmptyDescription());
    if (description != null) {
      result.append(": ").append(description);
    }
    return result.toString();
  }

  static class MnemonicIcon extends JBUI.CachingScalableJBIcon<MnemonicIcon> {
    private static final MnemonicIcon[] cache = new MnemonicIcon[36];//0..9  + A..Z
    private final char myMnemonic;

    @NotNull
    @Override
    protected MnemonicIcon copy() {
      return new MnemonicIcon(myMnemonic);
    }

    @NotNull
    static MnemonicIcon getIcon(char mnemonic) {
      int index = mnemonic - 48;
      if (index > 9)
        index -= 7;
      if (index < 0 || index > cache.length-1)
        return new MnemonicIcon(mnemonic);
      if (cache[index] == null)
        cache[index] = new MnemonicIcon(mnemonic);
      return cache[index];
    }

    private MnemonicIcon(char mnemonic) {
      myMnemonic = mnemonic;
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
      int width = getIconWidth();
      int height = getIconHeight();

      g.setColor(new JBColor(() -> {
        //noinspection UseJBColor
        return !darkBackground() ? new Color(0xffffcc) : new Color(0x675133);
      }));
      g.fillRect(x, y, width, height);

      g.setColor(JBColor.GRAY);
      g.drawRect(x, y, width, height);

      g.setColor(EditorColorsManager.getInstance().getGlobalScheme().getDefaultForeground());

      float startingFontSize = 40f;  // large font for smaller rounding error
      Font font = getBookmarkFont().deriveFont(startingFontSize);
      FontRenderContext fontRenderContext = ((Graphics2D)g).getFontRenderContext();
      double height40 = font.createGlyphVector(fontRenderContext, new char[]{'A'}).getVisualBounds().getHeight();
      font = font.deriveFont((float)(startingFontSize * height / height40 * 0.7));

      GlyphVector gv = font.createGlyphVector(fontRenderContext, new char[]{myMnemonic});
      Rectangle2D bounds = gv.getVisualBounds();
      ((Graphics2D)g).drawGlyphVector(gv, (float)(x + (width - bounds.getWidth())/2 - bounds.getX()),
                                      (float)(y + (height - bounds.getHeight())/2 - bounds.getY()));
    }

    @Override
    public int getIconWidth() {
      return scaleVal(DEFAULT_ICON.getIconWidth(), Scale.INSTANCE);
    }

    @Override
    public int getIconHeight() {
      return scaleVal(DEFAULT_ICON.getIconHeight(), Scale.INSTANCE);
    }

    @Override
    public boolean equals(Object o) {
      if (this == o) return true;
      if (o == null || getClass() != o.getClass()) return false;

      MnemonicIcon that = (MnemonicIcon)o;

      return myMnemonic == that.myMnemonic;
    }

    @Override
    public int hashCode() {
      return (int)myMnemonic;
    }
  }

  private static class MyCheckedIcon extends JBUI.CachingScalableJBIcon<MyCheckedIcon> implements RetrievableIcon {
    @Nullable
    @Override
    public Icon retrieveIcon() {
      return IconUtil.scale(PlatformIcons.CHECK_ICON, null, getScale());
    }

    @Override
    public void paintIcon(Component c, Graphics g, int x, int y) {
      IconUtil.scale((darkBackground() ? AllIcons.Actions.CheckedGrey : AllIcons.Actions.CheckedBlack), c, getScale()).paintIcon(c, g, x, y);
    }

    @Override
    public int getIconWidth() {
      return scaleVal(PlatformIcons.CHECK_ICON.getIconWidth(), Scale.INSTANCE);
    }

    @Override
    public int getIconHeight() {
      return scaleVal(PlatformIcons.CHECK_ICON.getIconHeight(), Scale.INSTANCE);
    }

    @NotNull
    @Override
    protected MyCheckedIcon copy() {
      return new MyCheckedIcon();
    }
  }

  private static boolean darkBackground() {
    Color gutterBackground = EditorColorsManager.getInstance().getGlobalScheme().getColor(EditorColors.GUTTER_BACKGROUND);
    if (gutterBackground == null) {
      gutterBackground = EditorColors.GUTTER_BACKGROUND.getDefaultColor();
    }
    return ColorUtil.isDark(gutterBackground);
  }

  private static class MyGutterIconRenderer extends GutterIconRenderer implements DumbAware {
    private final Bookmark myBookmark;

    public MyGutterIconRenderer(@NotNull Bookmark bookmark) {
      myBookmark = bookmark;
    }

    @Override
    @NotNull
    public Icon getIcon() {
      return myBookmark.getIcon();
    }

    @Override
    public String getTooltipText() {
      return myBookmark.getBookmarkTooltip();
    }

    @Override
    public boolean equals(Object obj) {
      return obj instanceof MyGutterIconRenderer &&
             Comparing.equal(getTooltipText(), ((MyGutterIconRenderer)obj).getTooltipText()) &&
             Comparing.equal(getIcon(), ((MyGutterIconRenderer)obj).getIcon());
    }

    @Override
     public int hashCode() {
      return getIcon().hashCode();
    }
  }
}


text:
package studio.androiddev.puzzle;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;

import com.squareup.leakcanary.LeakCanary;

import cn.bmob.v3.Bmob;
import studio.androiddev.puzzle.dish.DishManager;
import studio.androiddev.puzzle.model.User;
import studio.androiddev.puzzle.utils.StaticValue;

/**
 * Puzzle
 * Created by ZQ on 2016/3/21.
 */
public class PuzzleApplication extends Application{

    private static Context mContext;

    private static User mUser;

    private static DishManager dm;

    public static int getLevel() {
        return level;
    }

    public static void setLevel(int level) {
        if(level < 3) return;
        PuzzleApplication.level = level;
        initDishManager();
    }

    private static int level = 4;

    @Override
    public void onCreate(){
        super.onCreate();
        LeakCanary.install(this);
        Bmob.initialize(this, StaticValue.bmobId);
        if(mContext == null) mContext = getApplicationContext();
        SharedPreferences pref = getSharedPreferences(StaticValue.SP_NAME, MODE_PRIVATE);
        setLevel(pref.getInt(StaticValue.SP_LEVEL, 4));
    }

    public static User getmUser() {
        return mUser;
    }

    public static void setmUser(User mUser) {
        PuzzleApplication.mUser = mUser;
    }

    public static Context getAppContext(){
        return mContext;
    }

    public static void initDishManager(){
        dm = new DishManager(level);
    }

    public static DishManager getDishManager(){
        return dm;
    }
}


text:
module.exports = contentMapper;

var request = require('request'),
    _ = require('underscore'),
    jsdom = require('jsdom'),
    fs = require('fs'),
    jquery = 'http://code.jquery.com/jquery-1.5.min.js';

function contentMapper (config, cb) {
  if (!config || typeof config !== 'object' || config.length === 0){
    throw new Error("Invalid config argument.");
  }
  if (typeof config.inputfile !== 'function' && (typeof config.inputfile !== 'string' || config.inputfile.length === 0)){
    throw new Error("must provide a valid input filepath,url, or function");
  }
  if (typeof config.mappingFn !== 'function'){
    throw new Error("must provide a valid mapping function");
  }
  if (typeof config.template !== 'function' && (typeof config.template !== 'string' || config.template.length === 0)){
    throw new Error("must provide a valid template filepath,url, or function");
  }

  var inputfile = config.inputfile,
      mappingFn = config.mappingFn,
      templatefile = config.template;
  //read
  function read(inpath,next){
    var loader;
    //if it starts with http:// we use request to load the web content
    loader = inpath.match(/^http:\/{2}/) ? networkloader : fileloader;
    loader(inpath,function(err,data){
      if (err){
        cb(err);
        return;
      }
      next(data);
    });
  }

  //parse
  function parse(data){
    var unDOMed = data;
    //parse
    jsdom.env(data, [jquery],
      function(errors, window) {
        if (errors){
          cb(errors);
          return;
        }
        var newData =mappingFn(window.$,unDOMed);
        //do the parsing
        map(newData);
    });
  }

  //map
  function map(data){
    //read template and write new data to callback
    if (templatefile.call){
      cb(null,_.template(templatefile(),data));
    }else{
      read(templatefile,function(template){
        cb(null,_.template(template,data));
      });
    }
  }
  //let's do it
  if (inputfile.call){
    parse(inputfile());
  }else{
    read(inputfile,parse);
  }
}

//file or network loader
var networkloader = function(url,callback){
  request(url,function(error,response,body){
    callback(!response ? error : response.statusCode == 200 ?
      error : new Error("bad network response:"+response.statusCode),
      body
    );
  });
};

var fileloader = function(fpath,callback){
  fs.readFile(__dirname+fpath,'utf8',callback);
};