text:
using ChinaUnion_Agent.Util;
using ChinaUnion_Agent.Wechat;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace ChinaUnion_Agent.WechatForm
{
    public partial class frmAddWechatUser : Form
    {
        private string secret = "JH40o2nk6C6Q3Ym9tjVzSl9WD3x3c5sPwP8HzE5sccNW9CjoYCEugEzI4XyHNEnj";
        public WechatJsonUser wechatJsonUser = new WechatJsonUser();
        WechatAction wechatAction = new WechatAction();
        IList<int> department = new List<int>();

        public frmAddWechatUser()
        {
            InitializeComponent();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {

            if (String.IsNullOrEmpty(this.txtName.Text.Trim()))
            {
                MessageBox.Show("姓名不能为空");
                this.txtName.Focus();
                return;
            }
            if (String.IsNullOrEmpty(this.txtUserId.Text.Trim()))
            {
                MessageBox.Show("账号不能为空");
                this.txtUserId.Focus();
                return;
            }

            if (String.IsNullOrEmpty(this.txtWeixinId.Text.Trim()) && String.IsNullOrEmpty(this.txtMobile.Text.Trim()) && String.IsNullOrEmpty(this.txtEmail.Text.Trim()))
            {
                MessageBox.Show("微信号,手机和邮箱不能同时为空");
                return;
            }

            String EmailReg = @"^\w+([\.\-]\w+)*\@\w+([\.\-]\w+)*\.\w+$";
            if (!String.IsNullOrEmpty(txtEmail.Text.Trim())&&!Regex.IsMatch(txtEmail.Text.Trim(), EmailReg))
            {
                MessageBox.Show("请输入有效的邮箱地址");
                this.txtEmail.Focus();
                return;
            }

            String MobileReg = @"^[1]+[3,5,8]+\d{9}";
            if (!String.IsNullOrEmpty(txtMobile.Text.Trim()) && !Regex.IsMatch(this.txtMobile.Text.Trim(), MobileReg))
            {
                MessageBox.Show("请输入有效的手机号码");
                this.txtMobile.Focus();
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            wechatJsonUser.name = this.txtName.Text.Trim();

            wechatJsonUser.weixinid = this.txtWeixinId.Text.Trim();
            wechatJsonUser.mobile = this.txtMobile.Text.Trim();
            wechatJsonUser.email = this.txtEmail.Text.Trim();
            wechatJsonUser.position = this.txtPosition.Text.Trim();
            IList<int> department = new List<int>();
            wechatJsonUser.department = this.getCheckedNode(this.tvOrganization.Nodes);

             String msgJson = JsonConvert.SerializeObject(wechatJsonUser, Formatting.Indented);
            HttpResult httpResult = null;
            if (this.txtUserId.Enabled)
            {
                wechatJsonUser.userid = this.txtUserId.Text.Trim();
                httpResult = wechatAction.addUserToWechat(this.secret, msgJson);
            }
            else
            {
                httpResult = wechatAction.updateUserToWechat(this.secret, msgJson);
            }
             ReturnMessage returnMessage = (ReturnMessage)JsonConvert.DeserializeObject(httpResult.Html, typeof(ReturnMessage));
             this.Cursor = Cursors.Default;
            if (returnMessage != null && returnMessage.errcode.Equals("0"))
             {
                 MessageBox.Show("操作成功!");
                 DialogResult = System.Windows.Forms.DialogResult.OK;
             }
             else
             {
                 MessageBox.Show("操作失败," + returnMessage.getErrorDescrition());
                 return;

             }

        }

        private IList<int> getCheckedNode(TreeNodeCollection nodes)
        {

            foreach (TreeNode node in nodes)
            {
                if (node.Checked)
                {
                    department.Add(int.Parse(node.Tag.ToString()));
                }
                if (node.Nodes.Count > 0)
                {
                    getCheckedNode(node.Nodes);
                }
            }
            return department;
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            this.Close();
        }

        private void frmAddWechatUser_Load(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(wechatJsonUser.userid))
            {
                this.txtUserId.Enabled = true;
            }
            else
            {
                this.txtUserId.Enabled = false;
                this.txtUserId.Text = wechatJsonUser.userid;

                HttpResult userResult = wechatAction.getUserFromWechat(wechatJsonUser.userid, this.secret);
                if (userResult.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    //表示访问成功,具体的大家就参考HttpStatusCode类
                    wechatJsonUser = JsonConvert.DeserializeObject<WechatJsonUser>(userResult.Html);

                    this.txtName.Text = wechatJsonUser.name;
                    this.txtEmail.Text = wechatJsonUser.email;
                    this.txtMobile.Text = wechatJsonUser.mobile;
                    this.txtPosition.Text = wechatJsonUser.position;
                    this.txtWeixinId.Text = wechatJsonUser.weixinid;
                }
            }

            HttpResult result = wechatAction.getDepartmentListFromWechat(secret);
            if (result.StatusCode == System.Net.HttpStatusCode.OK)
            {
                //表示访问成功,具体的大家就参考HttpStatusCode类
                DepartmentList departmentList = JsonConvert.DeserializeObject<DepartmentList>(result.Html);

                if (departmentList != null)
                {
                    DataTable tb = new DataTable();
                    DataColumn col1 = new DataColumn("id", typeof(int));
                    tb.Columns.Add(col1);

                    DataColumn col2 = new DataColumn("name", typeof(String));
                    tb.Columns.Add(col2);

                    DataColumn col3 = new DataColumn("parentid", typeof(int));
                    tb.Columns.Add(col3);
                    foreach (Department department in departmentList.department)
                    {
                        DataRow dr = tb.NewRow();
                        dr["id"] = department.id;
                        dr["name"] = department.name;
                        dr["parentid"] = department.parentid;
                        tb.Rows.Add(dr);
                    }
                    tvOrganization.Nodes.Clear();
                    //创建根节点
                    TreeNode rootNode = new TreeNode();
                    rootNode.Text = departmentList.department[0].name;
                    rootNode.Tag = departmentList.department[0].id;
                    //rootNode.ImageUrl = "~/Image/Root.gif";

                    tvOrganization.Nodes.Add(rootNode);

                    //创建其他节点
                    CreateChildNode(rootNode, tb);

                    tvOrganization.ExpandAll();

                }

            }
        }
        private void CreateChildNode(TreeNode parentNode, DataTable dataTable)
        {
            DataRow[] rowList = dataTable.Select("parentid=" + parentNode.Tag);
            foreach (DataRow row in rowList)
            {   //创建新节点
                TreeNode node = new TreeNode();
                //设置节点的属性
                node.Text = row["name"].ToString();
                node.Tag = row["id"].ToString();

                if (wechatJsonUser.department != null && wechatJsonUser.department.Contains(int.Parse(node.Tag.ToString())))
                {
                    node.Checked = true;
                }

                parentNode.Nodes.Add(node);
                //递归调用,创建其他节点
                CreateChildNode(node, dataTable);
            }
        }
    }
}


text:
package telemarketer.skittlealley.framework.annotation;

import org.springframework.stereotype.Service;

import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.TYPE;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * WebSocketHandler
 * <p>
 * Author: Hanson
 * Email: imyijie@outlook.com
 * Date: 2017/2/6
 */
@Documented
@Target(TYPE)
@Retention(RUNTIME)
@Service
public @interface WSHandler {
    String value();
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace FileProxyServer.Network
{
    public class NioNetServer
    {
        private IList<ConnectionProvider> connections = new List<ConnectionProvider>();
        private ConnectionAcceptor connectionAcceptor;
        private ConnectionListener connectionListener;

        public NioNetServer(int port, ConnectionListener connectionListener)
        {
            this.connectionListener = connectionListener;
            connectionAcceptor = new ConnectionAcceptor(port);
        }

        public void Stop()
        {
            connectionAcceptor.Close();
        }

        public void Tick()
        {
            try
            {
                Socket socketChannel = connectionAcceptor.Accept();

                if (socketChannel != null)
                {
                    ConnectionProvider client = new ConnectionProvider(socketChannel, connectionListener);
                    connectionListener.OnConnect(client);
                    connections.Add(client);
                }
            }
            catch
            {
                // TODO: it is need the decision to be or not to be
            }

            for (int i = 0; i < connections.Count; )
            {
                ConnectionProvider client = connections[i];

                try
                {
                    client.Tick();
                    i++;
                }
                catch
                {
                    connections.RemoveAt(i);
                    connectionListener.OnDisconnect(client);
                }
            }
        }

        public IList<ConnectionProvider> Connections()
        {
            return connections;
        }
    }
}


text:
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {
	entry: './gl.js',
	output: {
		path: __dirname,
		filename: '[name].js',
		chunkFilename: '[id].js'
	},
	resolve: {
		modulesDirectories: [
			'node_modules',
			'./'
		]
	},
	module: {
		loaders: [{
				test: /\.css$/,
				loader: ExtractTextPlugin.extract('style-loader', 'css-loader')
			}, {
				test: /\.less$/,
				loader: ExtractTextPlugin.extract('style-loader', 'css-loader!less-loader')
			}
			// { test: /\.css$/, loader: 'style-loader!css-loader' },
			// { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }
		]
	},
	plugins: [
		new ExtractTextPlugin('[name].css')
	]
};


text:
@interface MRNavigationBarProgressViewController : UITableViewController

@end


text:
import IBANRegExp from './IBANRegExp';
import maskIBAN from './maskIBAN';
import repeatUntilStable from '../utils/repeatUntilStable';

const IBAN = new IBANRegExp();

export default function replace(text) {
  return repeatUntilStable(text, input =>
    input.replace(IBAN, match => maskIBAN(match))
  );
}


text:
<?php
namespace tests\domain\models\StaticFileModel;
use vsc\domain\models\StaticFileModel;

/**
 * @covers \vsc\domain\models\StaticFileModel::getLastModified()
 */
class getLastModified extends \BaseUnitTest
{
	public function testGetLastModifiedMatchesFilemtimeOfFile()
	{
		$o = new StaticFileModel();
		$o->setFilePath(__FILE__);
		$this->assertEquals(date('Y-m-d G:i:s', filemtime(__FILE__)), $o->getLastModified());
	}
}


text:
var step = '
Test Purpose:
'
            +'
Verify the crosswalk support the theme-color property
'
            +'
Expected Result:
'
            +'
'
            +'
The background color of the status bar is blue
'
            +'
The background color of the status bar is blue
'
            +'
';


text:
$('.eu-cookies button').click(function () {
	var date = new Date();
	date.setFullYear(date.getFullYear() + 10);
	// Pokud používáte subdomény a cookie se má nastavit i pro ně, doplňte za path=/; ještě domain=.vasedomena.cz; (a tečka na začátku je důležitá).
	// http://phpfashion.com/jak-na-souhlas-s-cookie-v-eu
	document.cookie = 'eu-cookies=1; path=/; expires=' + date.toGMTString();
	$('.eu-cookies').hide();
});

// Enable nette.ajax.js
$.nette.init();

// Enable Tooltip
$(function () {
	$('[data-toggle="tooltip"]').tooltip()
})


text:
<?php

namespace AppBundle\Controller\Admin;

use Biz\Util\FileUtil;
use Biz\Util\SystemUtil;

class OptimizeController extends BaseController
{
    public function indexAction()
    {
        return $this->render('admin/system/optimize.html.twig', array());
    }

    public function removeCacheAction()
    {
        FileUtil::emptyDir(SystemUtil::getCachePath());

        return $this->createJsonResponse(true);
    }

    public function removeTempAction()
    {
        if (!$this->isDisabledUpgrade()) {
            FileUtil::emptyDir(SystemUtil::getDownloadPath());
        }
        FileUtil::emptyDir(SystemUtil::getUploadTmpPath());

        return $this->createJsonResponse(true);
    }

    public function removeBackupAction()
    {
        if (!$this->isDisabledUpgrade()) {
            FileUtil::emptyDir(SystemUtil::getBackUpPath());
        }

        return $this->createJsonResponse(true);
    }

    public function backupdbAction()
    {
        $db = SystemUtil::backupdb();
        $downloadFile = '/files/tmp/'.basename($db);

        return $this->createJsonResponse(array('status' => 'ok', 'result' => $downloadFile));
    }

    public function removeUnusedFilesAction()
    {
        $result = $this->getSystemUtilService()->removeUnusedUploadFiles();
        if ($result) {
            return $this->createJsonResponse(array('success' => true, 'message' => '优化文件'));
        } else {
            return $this->createJsonResponse(array('success' => false, 'message' => '无可优化文件'));
        }
    }

    public function showProgressbarAction()
    {
        return $this->render('admin/system/progressBar.html.twig');
    }

    protected function isDisabledUpgrade()
    {
        return false;
    }

    protected function getSystemUtilService()
    {
        return $this->createService('Util:SystemUtilService');
    }
}


text:
require 'rubygems'
require 'redcard/rubinius'
require 'require_relative'
require_relative 'cmd_parser'

class Trepan
  module CmdParser

    def name_fix(name)
      RedCard.check('1.9') ? name.to_sym : name
    end

    # Given a KPeg parse object, return the method of that parse or raise a
    # Name error if we can't find a method. parent_class is the parent class of
    # the object we've found so far and "binding" is used if we need
    # to use eval to find the method.
    def resolve_method(m, bind, parent_class = nil)
      name = m.name
      # DEBUG p  name
      errmsg = nil
      if m.type == :constant
        begin
          if parent_class
            klass = parent_class.const_get(m.chain[0].name)
          else
            errmsg = "Constant #{m} is not a class or module"
            raise NameError, errmsg unless m.chain[0]
            klass = eval(m.chain[0].name, bind)
          end
          errmsg = "Constant #{klass} is not a class or module" unless
          raise NameError, errmsg unless
            klass.kind_of?(Class) or klass.kind_of?(Module)
          m = m.chain[1]
          if klass.instance_methods.member?(name_fix('binding'))
            bind = klass.bind
          elsif klass.private_instance_methods.member?(name_fix('binding'))
            bind = klass.send(:binding)
          else
            bind = nil
          end
          resolve_method(m, bind, klass)
        rescue NameError
          errmsg ||= "Can't resolve constant #{name}"
          raise NameError, errmsg
        end
      else
        is_class =
          begin
            m.chain && m.chain[0] &&
              Class == eval("#{m.chain[0].name}.class", bind)
          rescue
            false
          end
        if is_class
          # Handles stuff like:
          #    x = File
          #    x.basename
          # Above, we tested we get a class back when we evalate m.chain[0]
          # below. So it is safe to run the eval.
          klass = eval("#{m.chain[0].name}", bind)
          resolve_method(m.chain[1], klass.send(:binding), klass)
        else
          begin
            errmsg = "Can't get method for #{name.inspect}"
            if m.chain && m.chain[0]
              parent_obj = eval("#{m.chain[0].name}", bind) if !parent_class && bind
            end
            parent = parent_class || parent_obj
            meth =
              if parent
                errmsg << "in #{parent}"
                lookup_name = m.chain && m.chain[1] ? m.chain[1].name : name
                if parent.respond_to?('instance_methods') &&
                    parent.instance_methods.member?(name_fix(lookup_name))
                  parent.instance_method(name_fix(lookup_name))
                elsif parent.respond_to?('methods')
                  parent.method(name_fix(lookup_name))
                end
              elsif m.chain && m.chain[1]
                eval("#{m.chain[0].name}.method(#{lookup_name.name.inspect})", bind)
              else
                eval("self.method(#{name.inspect})", bind)
              end
            return meth
          rescue
            raise NameError, errmsg
          end
        end
      end
    end

    # Return the method by evaluating parse_struct.
    # nil is returned if we can't parse str
    def meth_for_parse_struct(parse_struct, start_binding)
      resolve_method(parse_struct, start_binding)
    end

    # Parse str and return the method associated with that.
    # nil is returned if we can't parse str
    def meth_for_string(str, start_binding)
      @cp ? @cp.setup_parser(str) : @cp = CmdParse.new(str)
      begin
        if @cp._class_module_chain
          # Did we match all of it?
          if @cp.result.name == str.strip
            # require 'trepanning'; debugger
            meth_for_parse_struct(@cp.result, start_binding)
          else
            nil
          end
        else
          # FIXME: change to raise ParseError?
          nil
        end
      rescue NameError
        return nil
      end
    end

    def parse_terminal(terminal_name, loc_str, opts={})
      @cp ? @cp.setup_parser(loc_str) : @cp = CmdParse.new(loc_str, opts)
      @cp.send(terminal_name) ? @cp : nil
    end

    def parse_location(loc_str, opts={})
      parse = parse_terminal(:_location, loc_str, opts)
      parse ? parse.result : nil
    end

    def parse_breakpoint(str, opts={})
      parse = parse_terminal(:_breakpoint_stmt, str, opts)
      parse ? parse.result : nil
    end

    def parse_breakpoint_no_condition(str, opts={})
      parse = parse_terminal(:_breakpoint_stmt_no_condition, str, opts)
      parse ? parse.result : nil
    end

    def parse_list(str, opts={})
      parse = parse_terminal(:_list_stmt, str, opts)
      parse ? parse.result : nil
    end
  end
end

if __FILE__ == $0
  # Demo it.
  %w(a a1 $global __FILE__ Constant 0 1e10 a.b).each do |name|
    cp = CmdParse.new(name)
    if cp._identifier && cp.result.name == name
      p [cp.string, cp.result, 'succeeded']
    else
      puts "#{name} failed"
    end
  end

  %w(Object  A::B  A::B::C  A::B::C::D  A::B.c  A.b.c.d  A(5)
     Rubinius::VariableScope::method_visibility
     ).each do |name|
    cp = CmdParse.new(name)
    if cp._class_module_chain && cp.result.name == name
      p [cp.string, cp.result, 'succeeded']
    else
      puts "#{name} failed"
    end
  end

  def five; 5 end
  include Trepan::CmdParser
  p meth_for_string('Array.map', binding)
  p meth_for_string('Rubinius::VM.backtrace', binding)
  %w(five
     Array.map
     Rubinius::VM.backtrace
     Kernel.eval
     Kernel::eval).each do |str|
    meth = meth_for_string(str, binding)
    p meth
  end
  module Testing
    def testing; 5 end
    module_function :testing
  end
  p meth_for_string('Testing.testing', binding)
  p meth_for_string('File.basename', binding)
  x = File
  # require_relative '../lib/trepanning'
  # debugger
  p meth_for_string('x.basename', binding)
  def x.five; 5; end
  p  meth_for_string('x.five', binding)
  p x.five

  p parse_terminal(:_line_number, '5').result
  p parse_terminal(:_vm_offset, '@5').result

  # Location stuff
  ['fn', 'fn 5', 'fn @5', '@5', '5',
    '../test/example/test\ fname\ with\ blank.rb'].each do |location|
    p parse_location(location)
  end

  # require_relative '../lib/trepanning'; debugger
  # parse_location('../test/example/test\ fname\ with\ blank.rb')

  # Location stuff
  ['fn if a > b', 'fn 5 unless c > d', 'fn:5 if x', '@5', '5'].each do |str|
    p parse_breakpoint(str)
  end

end


text:
Core codebase for [FirewaterDB.org](http://firewaterdb.org)

## FirewaterDB's core concept:
To provide a clean and easy to use multi-platform interface for a cocktail database. An open API will be provided along with regular database exports. The code and database contents will be openly licensed.

## How to build
* Checkout code from Github
* Setup Meteor (if you've never used it before): https://www.meteor.com/install
* Run `$ meteor run`
* Point your browser at http://localhost:3000/


text:
class CreateUsers < ActiveRecord::Migration
  def change
    must_create_user_table = !table_exists?(:users)
    create_table(:users) { |t| t.timestamps } if must_create_user_table

    add_users_column_safe :name,      :string
    add_users_column_safe :role,      :string
    add_users_column_safe :locale,    :string
    add_users_column_safe :time_zone, :string

    add_users_column_safe :username,                   :string
    add_users_column_safe :password_digest,            :string
    add_users_column_safe :password_token_digest,      :string
    add_users_column_safe :password_token_digested_at, :datetime, default:  DateTime.new(2000, 1,1)

    add_users_column_safe :credentials_count,   :integer, default: 0
    add_users_column_safe :access_tokens_count, :integer, default: 0
  end

  private

      def add_users_column_safe(column_name, type, options={})
        return if column_exists?(:users, column_name)
        add_column(:users, column_name, type, options)
      end
end


text:
import os

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',

    'cookie_consent',

    'core',
]
SITE_ID = 1

ROOT_URLCONF = "urls"

DEBUG = True

STATIC_URL = '/static/'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                "django.contrib.auth.context_processors.auth",
                "django.template.context_processors.debug",
                "django.template.context_processors.i18n",
                "django.template.context_processors.media",
                "django.template.context_processors.static",
                "django.template.context_processors.tz",
                "django.template.context_processors.request",
                "django.contrib.messages.context_processors.messages"
            ],
        },
    },
]

SECRET_KEY = '2n6)=vnp8@bu0om9d05vwf7@=5vpn%)97-!d*t4zq1mku%0-@j'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(os.path.dirname(__file__), 'database.db'),
    }
}
DEFAULT_AUTO_FIELD = "django.db.models.AutoField"

MIDDLEWARE_CLASSES = MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

COOKIE_CONSENT_NAME = "cookie_consent"
COOKIE_CONSENT_MAX_AGE = 60 * 60 * 24 * 365 * 1  # 1 year
COOKIE_CONSENT_LOG_ENABLED = True


text:
import is from 'is_js';
import bigNumber from 'bignumber.js';
import { isValidNumber } from '../../utils/number';
import app from '../../app';
import BaseModel from '../BaseModel';

export default class extends BaseModel {
  defaults() {
    return {
      productID: '',
      infiniteInventory: false,
      bigSurcharge: bigNumber('0'),
    };
  }

  get max() {
    return {
      productIdLength: 40,
    };
  }

  validate(attrs) {
    const errObj = {};

    const addError = (fieldName, error) => {
      errObj[fieldName] = errObj[fieldName] || [];
      errObj[fieldName].push(error);
    };

    if (attrs.productID.length > this.max.productIdLength) {
      addError('productID', `The productID cannot exceed ${this.max.productIdLength} characters.`);
    }

    if (typeof attrs.infiniteInventory !== 'undefined' &&
      typeof attrs.infiniteInventory !== 'boolean') {
      addError('infiniteInventory', 'If provided, infiniteInventory should be a boolean.');
    }

    if (attrs.infiniteInventory) {
      if (attrs.bigQuantity) {
        addError('bigQuantity', 'bigQuantity should not be provided if provided if ' +
          'infiniteInventory is truthy.');
      }
    } else {
      if (
        attrs.bigQuantity === '' ||
        attrs.bigQuantity === undefined ||
        attrs.bigQuantity === null
      ) {
        addError('bigQuantity', app.polyglot.t('skuModelErrors.provideQuantity'));
      } else if (
        !isValidNumber(attrs.bigQuantity, {
          allowNumber: false,
          allowBigNumber: true,
          allowString: false,
        })
      ) {
        addError('bigQuantity', app.polyglot.t('skuModelErrors.provideNumericQuantity'));
      } else if (!attrs.bigQuantity.isInteger()) {
        addError('bigQuantity', app.polyglot.t('skuModelErrors.quantityMustBeInteger'));
      } else if (attrs.bigQuantity.lt(0)) {
        // The listing API allows the quantity to be set to < 0, which indicates an unlimited
        // supply. This model does not allow that, but does have an infiniteInventory flag.
        // The expectation is that sync / parse of the listing model will send the quantity
        // over as "-1" if the infiniteInventory flag is set to true. Also the infiniteInventory
        // flag should not be sent to the server.

        addError('bigQuantity', app.polyglot.t('skuModelErrors.providePositiveQuantity'));
      }
    }

    // The listing API does not require a variantCombo field, since if you have no options and
    // want to assign a quantity and / or productId to an Item you would create a "dummy" Sku object
    // and set the values there. That seems like a bit of a klunky way to do it, so the client will
    // not allow such a dummy SKU. Instead, the Item model will allow quantity and productId fields
    // and convert them to / from a dummy SKU in sync / parse.
    if (!is.array(attrs.variantCombo)) {
      addError('variantCombo', 'A variantCombo field must be provided and must be an array.');
    }

    if (Object.keys(errObj).length) return errObj;

    return undefined;
  }
}


text:
from TASSELpy.java.util.Map import Map
from TASSELpy.java.lang.Integer import metaInteger
from TASSELpy.java.lang.Float import metaFloat
from TASSELpy.java.util.AbstractMap import AbstractMap
from TASSELpy.utils.Overloading import javaConstructorOverload
from TASSELpy.utils.helper import make_sig

java_imports = {'Map':'java/util/Map',
                'HashMap':'java/util/HashMap'}

class HashMap(AbstractMap):
    """
    public class HashMap<K,V>
    extends AbstractMap<K,V>
    implements Map<K,V>, Cloneable, Serializable
    Hash table based implementation of the Map interface. This implementation provides all of the optional map operations, and permits null values and the null key. (The HashMap class is roughly equivalent to Hashtable, except that it is unsynchronized and permits nulls.) This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
    This implementation provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the elements properly among the buckets. Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings). Thus, it's very important not to set the initial capacity too high (or the load factor too low) if iteration performance is important.

    An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

    As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

    If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

    Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

       Map m = Collections.synchronizedMap(new HashMap(...));
    The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

    Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

    This class is a member of the Java Collections Framework.
    """
    _java_name = java_imports['HashMap']
    ## Instantiates a HashMap
    @javaConstructorOverload(java_imports['HashMap'],
                             (make_sig([],'void'),()),
                             (make_sig(['int'],'void'),(metaInteger,)),
                             (make_sig(['int','float'],'void'),(metaInteger,metaFloat)),
                            (make_sig([java_imports['Map']],'void'),(Map,)))
    def __init__(self, *args, **kwargs):
        """
        Instantiates a HashMap

        Signatures:

        HashMap()
        HashMap(int initialCapacity)
        HashMap(int initialCapacity, float loadFactor)
        HashMap(Map<? extends K, ? extends V> m)

        Arguments:

        HashMap(int initialCapacity)
            initialCapacity -- the initial capcity
        HashMap(int initialCapacity, float loadFactor)
            initialCapacity -- the initial capcity
            loadFactor -- the load factor
        HashMap(Map<? extends K, ? extends V> m)
            The map whose mappings are to be placed in this map
        """
        super(HashMap,self).__init__(*args, **kwargs)


text:
import {assumeFreeze} from '../../../detect/assume-freeze.js';
import {assumePreventExtensions} from '../../../detect/assume-prevent-extensions.js';
import {assumeSeal} from '../../../detect/assume-seal.js';
import '../../../../src/index.js';

describe('toBeExtensible', () => {
  it('should not pass with primitive values', () => {
    expect(null).not.toBeExtensible();
    expect(undefined).not.toBeExtensible();
    expect('').not.toBeExtensible();
    expect(1).not.toBeExtensible();
    expect(true).not.toBeExtensible();
  });

  it('should pass with non frozen objects and array', () => {
    expect({}).toBeExtensible();
    expect([]).toBeExtensible();
  });

  it('should not pass with frozen objects and array', () => {
    assumeFreeze();

    expect(Object.freeze({})).not.toBeExtensible();
    expect(Object.freeze([])).not.toBeExtensible();
  });

  it('should not pass with sealed objects and array', () => {
    assumeSeal();

    expect(Object.seal({})).not.toBeExtensible();
    expect(Object.seal([])).not.toBeExtensible();
  });

  it('should not pass with non extensible objects and array', () => {
    assumePreventExtensions();

    expect(Object.preventExtensions({})).not.toBeExtensible();
    expect(Object.preventExtensions([])).not.toBeExtensible();
  });
});


text:
dojo.provide("dojo.charting.svg.Axis");
dojo.require("dojo.lang.common");

if(dojo.render.svg.capable){
	dojo.extend(dojo.charting.Axis, {
		renderLines: function(
			/* dojo.charting.PlotArea */plotArea,
			/* dojo.charting.Plot */plot,
			/* string */plane
		){
			//	summary
			//	Renders any reference lines for this axis.
			if(this.nodes.lines){
				while(this.nodes.lines.childNodes.length > 0){
					this.nodes.lines.removeChild(this.nodes.lines.childNodes[0]);
				}
				if(this.nodes.lines.parentNode){
					this.nodes.lines.parentNode.removeChild(this.nodes.lines);
					this.nodes.lines = null;
				}
			}

			var area = plotArea.getArea();
			var g = this.nodes.lines = document.createElementNS(dojo.svg.xmlns.svg, "g");
			g.setAttribute("id", this.getId()+"-lines");
			for(var i=0; i<this._labels.length; i++){
				if (this._labels[i].value == this.origin){ continue; }

				var v = this.getCoord(this._labels[i].value, plotArea, plot);
				var l=document.createElementNS(dojo.svg.xmlns.svg, "line");
				l.setAttribute("style","stroke:#999;stroke-width:1px;stroke-dasharray:1,4;");
				if(plane == "x"){
					l.setAttribute("y1",area.top);
					l.setAttribute("y2",area.bottom);
					l.setAttribute("x1",v);
					l.setAttribute("x2",v);
				}
				else if (plane == "y"){
					l.setAttribute("y1",v);
					l.setAttribute("y2",v);
					l.setAttribute("x1",area.left);
					l.setAttribute("x2",area.right);
				}
				g.appendChild(l);
			}
			return g;	//	SVGGElement
		},
		renderTicks: function(
			/* dojo.charting.PlotArea */plotArea,
			/* dojo.charting.Plot */plot,
			/* string */plane,
			/* float */coord
		){
			//	summary
			//	Renders any tick lines for this axis.
			if(this.nodes.ticks){
				while(this.nodes.ticks.childNodes.length > 0){
					this.nodes.ticks.removeChild(this.nodes.ticks.childNodes[0]);
				}
				if(this.nodes.ticks.parentNode){
					this.nodes.ticks.parentNode.removeChild(this.nodes.ticks);
					this.nodes.ticks = null;
				}
			}

			var g = this.nodes.ticks = document.createElementNS(dojo.svg.xmlns.svg, "g");
			g.setAttribute("id", this.getId()+"-ticks");
			for(var i=0; i<this._labels.length; i++){
				var v = this.getCoord(this._labels[i].value, plotArea, plot);

				var l=document.createElementNS(dojo.svg.xmlns.svg, "line");
				l.setAttribute("style","stroke:#000;stroke-width:1pt;");
				if(plane == "x"){
					l.setAttribute("y1",coord);
					l.setAttribute("y2",coord+3);
					l.setAttribute("x1",v);
					l.setAttribute("x2",v);
				}
				else if (plane == "y"){
					l.setAttribute("y1",v);
					l.setAttribute("y2",v);
					l.setAttribute("x1",coord-2);
					l.setAttribute("x2",coord+2);
				}
				g.appendChild(l);
			}
			return g;	//	SVGGElement
		},
		renderLabels: function(
			/* dojo.charting.PlotArea */plotArea,
			/* dojo.charting.Plot */plot,
			/* string */plane,
			/* float */coord,
			/* int */textSize,
			/* string */anchor
		){
			//	summary
			//	Render all labels for this axis.
			function createLabel(label, x, y, textSize, anchor){
				var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
				text.setAttribute("x", x);
				text.setAttribute("y", (plane=="x"?y:y+2));
				text.setAttribute("style", "text-anchor:"+anchor+";font-family:sans-serif;font-size:"+textSize+"px;fill:#000;");
				text.appendChild(document.createTextNode(label));
				return text;
			};

			//	wipe if needed
			if(this.nodes.labels){
				while(this.nodes.labels.childNodes.length > 0){
					this.nodes.labels.removeChild(this.nodes.labels.childNodes[0]);
				}
				if(this.nodes.labels.parentNode){
					this.nodes.labels.parentNode.removeChild(this.nodes.labels);
					this.nodes.labels = null;
				}
			}
			var g = this.nodes.labels = document.createElementNS(dojo.svg.xmlns.svg, "g");
			g.setAttribute("id", this.getId()+"-labels");

			for(var i=0; i<this._labels.length; i++){
				var v = this.getCoord(this._labels[i].value, plotArea, plot);
				if(plane == "x"){
					g.appendChild(createLabel(this._labels[i].label, v, coord, textSize, anchor));
				}
				else if (plane == "y"){
					g.appendChild(createLabel(this._labels[i].label, coord, v, textSize, anchor));
				}
			}
			return g;	//	SVGGelement
		},
		render: function(
			/* dojo.charting.PlotArea */plotArea,
			/* dojo.charting.Plot */plot,
			/* dojo.charting.Axis */drawAgainst,
			/* string */plane
		){
			//	summary
			//	Renders this axis to the given plot.

			//	get the origin plot point.
			var area = plotArea.getArea();
			var stroke = 1;
			var style = "stroke:#000;stroke-width:"+stroke+"px;";
			var textSize=10;
			var coord = drawAgainst.getCoord(this.origin, plotArea, plot);

			//	draw the axis.
			this.nodes.main = document.createElementNS(dojo.svg.xmlns.svg, "g");
			var g = this.nodes.main;
			g.setAttribute("id", this.getId());	//	need a handle if we have to kill parts of the axis def.
			var line = this.nodes.axis = document.createElementNS(dojo.svg.xmlns.svg, "line");
			if(plane == "x"){
				line.setAttribute("y1", coord);
				line.setAttribute("y2", coord);
				line.setAttribute("x1", area.left-stroke);
				line.setAttribute("x2", area.right+stroke);
				line.setAttribute("style", style);

				//	set up the labels
				var y = coord+textSize+2;
				if(this.showLines){
					g.appendChild(this.renderLines(plotArea, plot, plane, y));
				}
				if(this.showTicks){
					g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
				}
				if(this.showLabels){
					g.appendChild(this.renderLabels(plotArea, plot, plane, y, textSize, "middle"));
				}
				if(this.showLabel && this.label){
					var x = plotArea.size.width/2;
					var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
					text.setAttribute("x", x);
					text.setAttribute("y", (coord + (textSize*2) + (textSize/2)));
					text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:"+(textSize+2)+"px;fill:#000;");
					text.appendChild(document.createTextNode(this.label));
					g.appendChild(text);
				}
			} else {
				line.setAttribute("x1", coord);
				line.setAttribute("x2", coord);
				line.setAttribute("y1", area.top);
				line.setAttribute("y2", area.bottom);
				line.setAttribute("style", style);

				//	set up the labels
				var isMax = this.origin == drawAgainst.range.upper;
				var x = coord + (isMax?4:-4);
				var anchor = isMax?"start":"end";
				if(this.showLines){
					g.appendChild(this.renderLines(plotArea, plot, plane, x));
				}
				if(this.showTicks){
					g.appendChild(this.renderTicks(plotArea, plot, plane, coord));
				}
				if(this.showLabels){
					g.appendChild(this.renderLabels(plotArea, plot, plane, x, textSize, anchor));
				}
				if(this.showLabel && this.label){
					var x = isMax?(coord+(textSize*2)+(textSize/2)):(coord-(textSize*4));
					var y = plotArea.size.height / 2;
					var text = document.createElementNS(dojo.svg.xmlns.svg, "text");
					text.setAttribute("x", x);
					text.setAttribute("y", y);
					text.setAttribute("transform", "rotate(90, " + x + ", " + y + ")");
					text.setAttribute("style", "text-anchor:middle;font-family:sans-serif;font-weight:bold;font-size:"+(textSize+2)+"px;fill:#000;");
					text.appendChild(document.createTextNode(this.label));
					g.appendChild(text);
				}
			}
			g.appendChild(line);
			return g;	// 	SVGGElement
		}
	});
}


text:
package org.apache.ambari.shell.completion;

/**
 * Base class for completions.
 */
public abstract class AbstractCompletion {

  private final String name;

  protected AbstractCompletion(String name) {
    this.name = name;
  }

  public String getName() {
    return name;
  }
}


text:
import stainless.lang._
import stainless.collection._
import stainless._

object RemainderByZero {

  def remByZero(x: BigInt): Boolean = {
    (x % BigInt(0) == BigInt(10))
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="Content-Style-Type" content="text/css" />
  <meta name="generator" content="pandoc" />
  <title>Corona Docs: Plugins > zip > list</title>
  <meta name="revised" content="04-Jun-2013" />
  <meta name="description" content="Whether you're new to Corona or want to take your app to the next level, we've got a wealth of resources for you including extensive documentation, API reference, sample code, and videos.  Plugins > zip > list" />

  <link rel="stylesheet" href="../../css/style.css" type="text/css" />

SDK APIs

Enterprise APIs

Plugins

Guides

Tutorials

Corona Resources ▹

  <form action="http://www.google.com/cse" id="cse-search-box">
  <input type="hidden" name="cx" value="009283852522218786394:g40gqt2m6rq" />
  <input type="hidden" name="ie" value="UTF-8" />
  <input type="text" name="q" id="q" autocomplete="off" size="40" style="width:150px;float:left" />
  <input type="submit" name="sa" value="Search" style="float:right; font-size: 13px;" />
  </form>

zip.list()

Overview

Syntax

Required Settings

options.zipFile (required)

options.zipBaseDir (required)

options.listener (required)

Examples

Zip List

Ξ  ▸  Plugins  ▸  zip  ▸  list

zip.list()

<col width="19%" />
<col width="80%" />

Type Library Return value Revision Keywords Sample code See also
Function zip.* NONE Current Public Release (2013.2076) zip
zip.compress()

Overview

Lists all files in a zip archive

Syntax

zip.list( options )

Required Settings

    plugins =
    {
        -- key is the name passed to Lua's 'require()'
        ["plugin.zip"] =
        {
            -- required
            publisherId = "com.coronalabs",
        },
    },

options.zipFile (required)

String. The filename of the zip archive

options.zipBaseDir (required)

String. The source folder containing the zip archive

options.listener (required)

Listener. The listener function invoked at various phases of the zip operation. It is passed a [Listener][api.event.list] event.

The listener function can receive events of the following phases:

Examples

Zip List

The following sample code lists all files from test.zip with additional file info

local function zipListener( event )
        if ( event.isError ) then
                print( "Unzip Error")
        else

          -- Example list response
          --event.response = {
          --[1] =
          --{
          --  ratio: 98
          --  size: 2188295440
          --  file: space.jpg
          --},
          --[2] =
          --{
          --  ratio: 98
          --  size: 2188295440
          --  file: space1.jpg
          --},

        end
end

-- Extraction routine

local options = {
        zipFile = "test.zip",
        zipBaseDir = system.DocumentsDirectory,
        listener = zipListener
}

zip.list( options )

© 2013 Corona Labs Inc. All Rights Reserved. (Last updated: 04-Jun-2013)

Help us help you! Give us feedback on this page:

Love it

Like it, but...

Hate it


text:
/**
 *
  Package: MAG - VistA Imaging
  WARNING: Per VHA Directive 2004-038, this routine should not be modified.
  Date Created: Jul 28, 2009
  Site Name:  Washington OI Field Office, Silver Spring, MD
  Developer:  vhaiswwerfej
  Description:

        ;; +--------------------------------------------------------------------+
        ;; Property of the US Government.
        ;; No permission to copy or redistribute this software is given.
        ;; Use of unreleased versions of this software requires the user
        ;;  to execute a written test agreement with the VistA Imaging
        ;;  Development Office of the Department of Veterans Affairs,
        ;;  telephone (301) 734-0100.
        ;;
        ;; The Food and Drug Administration classifies this software as
        ;; a Class II medical device.  As such, it may not be changed
        ;; in any way.  Modifications to this software may result in an
        ;; adulterated medical device under 21CFR820, the use of which
        ;; is considered to be a violation of US Federal Statutes.
        ;; +--------------------------------------------------------------------+

 */
package gov.va.med.imaging.proxy.exceptions;

import gov.va.med.imaging.core.interfaces.exceptions.ConnectionException;
import gov.va.med.imaging.proxy.services.ProxyServiceType;

/**
 * Exception occurs if a ProxyServices object does not contain a specified ProxyServiceType.
 * This exception implies the proxy cannot complete the specified operation.
 *
 * @author vhaiswwerfej
 *
 */
public class ProxyServiceNotFoundException
extends ConnectionException
{

	private static final long serialVersionUID = 1908339680927821356L;

	public ProxyServiceNotFoundException(String msg)
	{
		super(msg);
	}

	public ProxyServiceNotFoundException(ProxyServiceType proxyServiceType)
	{
		super("Cannot find service type '"+  proxyServiceType.getIdsOperationType() + "'");
	}

}


text:
function viewMessage(id, url) {
	var request = {'id':id};
	$('#bbii-message').toggleClass('spinner');
	$('#bbii-message').html('');
	$.post(url, request, function(data) {
		if(data.success == 'yes') {
			$("#bbii-message").html(data.html);
			$('#bbii-message').toggleClass('spinner');
		} else {
			alert(data.message);
			$('#bbii-message').toggleClass('spinner');
		}
	}, 'json');
	$('a').closest('tr').removeClass('selected');
	$("a[href='" + id + "']").closest('tr').addClass('selected');
}

function viewPost(id, url) {
	var request = {'id':id};
	$('#bbii-message').toggleClass('spinner');
	$('#bbii-message').html('');
	$.post(url, request, function(data) {
		if(data.success == 'yes') {
			$("#bbii-message").html(data.html);
			$('#bbii-message').toggleClass('spinner');
		} else {
			alert(data.message);
			$('#bbii-message').toggleClass('spinner');
		}
	}, 'json');
}

function deletePost(url) {
	var request = {'ajax': '1'};
	$.ajax({
		url: url,
		type: "GET",
		dataType: "json",
		data: request
	});
}

function reportPost(id) {
	$('#BbiiMessage_post_id').val(id);
	$('#dlgReportForm').dialog('open');
}

function sendReport() {
	var formdata = $('#report-form').serialize();
	var url = $('#url').val();
	$.post(url, formdata, function(data) {
		if(data.success == 'yes') {
			alert(data.message);
			$("#dlgReportForm").dialog('close');
		} else {
			alert(data.message);
			$("#dlgReportForm").dialog('close');
		}
	}, 'json');
}

function banIp(id, url) {
	url = url + /id/ + id;
	$.get(url);
}

function refreshTopics(obj, url) {
	$.post(url, {'id': obj.value}, function(data) {
		if(data.success == 'yes') {
			$('#BbiiTopic_merge').html(data.option);
		} else {
			alert(data.message);
		}
	}, 'json');
	return false;
}

function upvotePost(id, url) {
	$.post(url, {'id': id}, function(data) {
		if(data.success == 'yes') {
			$('#upvote_'+id).replaceWith(data.html);
		}
	}, 'json');
	return false;
}

// Poll functions
function showPoll() {
	togglePoll();
	$('#addPoll').val('yes');
}

function hidePoll() {
	togglePoll();
	$('#addPoll').val('no');
}

function togglePoll() {
	$('#poll-button').toggle();
	$('#poll-form').toggle();
}

function pollChange(obj) {
	var id = obj.id;
	var text = obj.value;
	if(text.length > 0) {
		addChoice();
	} else {
		removeChoice(id);
	}
}

function addChoice() {
	var allfilled = true;
	$('#poll-choices').children('input').each(function(){
		if(this.value.length == 0) {
			allfilled = false;
		}
	});
	if(allfilled) {
		var last_id = $('#poll-choices input:last').attr('id');
		var id = last_id.split('_')[1];
		id++;
		var html = '<input id="choice_'+id+'" type="text" name="choice['+id+']" value="" onchange="pollChange(this)" style="width:99%;" maxlength="80">';
		$('#poll-choices').append(html);
		$('#poll-choices input:last').focus();
	}
}

function removeChoice(id) {
	var n = $('#poll-choices').children('input').size();
	if(n > 2) {
		$('#'+id).remove();
		addChoice();
	}
}

function vote(url) {
	var formdata = $('#bbii-poll-form').serialize();
	$.post(url, formdata, function(data) {
		if(data.success == 'yes') {
			$("#poll").html(data.html);
		}
	}, 'json');
}

function changeVote(poll_id, url) {
	var formdata = {'poll_id':poll_id};
	$.post(url, formdata, function(data) {
		if(data.success == 'yes') {
			$("#poll").html(data.html);
		}
	}, 'json');
}

function editPoll(poll_id, url) {
	var formdata = {'poll_id':poll_id};
	$.post(url, formdata, function(data) {
		if(data.success == 'yes') {
			$("#poll").html(data.html);
			$('#expiredate').datepicker($.extend({showMonthAfterYear:false},$.datepicker.regional[language],
				{'altField':'#BbiiPoll_expire_date','altFormat':'yy-mm-dd','showAnim':'fold','defaultDate':7,'minDate':1}
			));
		}
	}, 'json');
}

var BBii = {
	changeTopic: function(url) {
		var formdata = $('#update-topic-form').serialize();
		$.post(url, formdata, function(data) {
			if(data.success == 'yes') {
				$("#dlgTopicForm").dialog('close');
				$.fn.yiiListView.update('bbiiTopic');
			} else {
				settings = $('#update-topic-form').data('settings');
				$.each(settings.attributes, function () {
					$.fn.yiiactiveform.updateInput(this, data.error, $('#update-topic-form'));
				});
			}
		}, 'json');
	},
	toggleForumGroup: function(id, url) {
		if($('#category_'+id).css('display') == 'none') {
			action = 'unset';
		} else {
			action = 'set';
		}
		$('#category_'+id).toggle('fold',{size:1},'fast');
		var data = {id:id,action:action};
		$.post(url, data, function(data) {}, 'json');

	},
	updateTopic: function(id, url) {
		$.post(url, {'id': id}, function(data) {
			if(data.success == 'yes') {
				$('#BbiiTopic_id').val(id);
				$('#BbiiTopic_forum_id').val(data.forum_id);
				$('#BbiiTopic_title').val(data.title);
				$('#BbiiTopic_locked').val(data.locked);
				$('#BbiiTopic_sticky').val(data.sticky);
				$('#BbiiTopic_global').val(data.global);
				$('#BbiiTopic_merge').html(data.option);
				$("#dlgTopicForm").dialog('open');
			} else {
				alert(data.message);
				$("#dlgTopicForm").dialog('close');
			}
		}, 'json');
	},
	watchTopic: function(topicId, postId, url) {
		$.post(url, {'topicId': topicId, 'postId': postId}, function(data) {
			if(data.success == 'yes') {
				$('#watch').toggle();
				$('#unwatch').toggle();
			} else {

			}
		}, 'json');
	}
}


text:
"""
Compute Engine definitions for the Pipeline API.
"""
from abc import (
    ABCMeta,
    abstractmethod,
)
from uuid import uuid4

from six import (
    iteritems,
    with_metaclass,
)
from six.moves import zip_longest
from numpy import array

from pandas import (
    DataFrame,
    date_range,
    MultiIndex,
)

from zipline.lib.adjusted_array import ensure_ndarray
from zipline.errors import NoFurtherDataError
from zipline.utils.numpy_utils import repeat_first_axis, repeat_last_axis
from zipline.utils.pandas_utils import explode

from .term import AssetExists

class PipelineEngine(with_metaclass(ABCMeta)):

    @abstractmethod
    def run_pipeline(self, pipeline, start_date, end_date):
        """
        Compute values for `pipeline` between `start_date` and `end_date`.

        Returns a DataFrame with a MultiIndex of (date, asset) pairs

        Parameters
        ----------
        pipeline : zipline.pipeline.Pipeline
            The pipeline to run.
        start_date : pd.Timestamp
            Start date of the computed matrix.
        end_date : pd.Timestamp
            End date of the computed matrix.

        Returns
        -------
        result : pd.DataFrame
            A frame of computed results.

            The columns `result` correspond wil be the computed results of
            `pipeline.columns`, which should be a dictionary mapping strings to
            instances of `zipline.pipeline.term.Term`.

            For each date between `start_date` and `end_date`, `result` will
            contain a row for each asset that passed `pipeline.screen`.  A
            screen of None indicates that a row should be returned for each
            asset that existed each day.
        """
        raise NotImplementedError("run_pipeline")

class NoOpPipelineEngine(PipelineEngine):
    """
    A PipelineEngine that doesn't do anything.
    """
    def run_pipeline(self, pipeline, start_date, end_date):
        return DataFrame(
            index=MultiIndex.from_product(
                [date_range(start=start_date, end=end_date, freq='D'), ()],
            ),
            columns=sorted(pipeline.columns.keys()),
        )

class SimplePipelineEngine(object):
    """
    PipelineEngine class that computes each term independently.

    Parameters
    ----------
    loader : PipelineLoader
        A loader to use to retrieve raw data for atomic terms.
    calendar : DatetimeIndex
        Array of dates to consider as trading days when computing a range
        between a fixed start and end.
    asset_finder : zipline.assets.AssetFinder
        An AssetFinder instance.  We depend on the AssetFinder to determine
        which assets are in the top-level universe at any point in time.
    """
    __slots__ = [
        '_loader',
        '_calendar',
        '_finder',
        '_root_mask_term',
        '__weakref__',
    ]

    def __init__(self, loader, calendar, asset_finder):
        self._loader = loader
        self._calendar = calendar
        self._finder = asset_finder
        self._root_mask_term = AssetExists()

    def run_pipeline(self, pipeline, start_date, end_date):
        """
        Compute a pipeline.

        Parameters
        ----------
        pipeline : zipline.pipeline.Pipeline
            The pipeline to run.
        start_date : pd.Timestamp
            Start date of the computed matrix.
        end_date : pd.Timestamp
            End date of the computed matrix.

        The algorithm implemented here can be broken down into the following
        stages:

        0. Build a dependency graph of all terms in `terms`.  Topologically
        sort the graph to determine an order in which we can compute the terms.

        1. Ask our AssetFinder for a "lifetimes matrix", which should contain,
        for each date between start_date and end_date, a boolean value for each
        known asset indicating whether the asset existed on that date.

        2. Compute each term in the dependency order determined in (0), caching
        the results in a a dictionary to that they can be fed into future
        terms.

        3. For each date, determine the number of assets passing **all**
        filters. The sum, N, of all these values is the total number of rows in
        our output frame, so we pre-allocate an output array of length N for
        each factor in `terms`.

        4. Fill in the arrays allocated in (3) by copying computed values from
        our output cache into the corresponding rows.

        5. Stick the values computed in (4) into a DataFrame and return it.

        Step 0 is performed by `zipline.pipeline.graph.TermGraph`.
        Step 1 is performed in `self._compute_root_mask`.
        Step 2 is performed in `self.compute_chunk`.
        Steps 3, 4, and 5 are performed in self._format_factor_matrix.

        See Also
        --------
        PipelineEngine.run_pipeline
        """
        if end_date <= start_date:
            raise ValueError(
                "start_date must be before end_date \n"
                "start_date=%s, end_date=%s" % (start_date, end_date)
            )

        screen_name = uuid4().hex
        graph = pipeline.to_graph(screen_name, self._root_mask_term)
        extra_rows = graph.extra_rows[self._root_mask_term]
        root_mask = self._compute_root_mask(start_date, end_date, extra_rows)
        dates, assets, root_mask_values = explode(root_mask)

        outputs = self.compute_chunk(
            graph,
            dates,
            assets,
            initial_workspace={self._root_mask_term: root_mask_values},
        )

        out_dates = dates[extra_rows:]
        screen_values = outputs.pop(screen_name)

        return self._to_narrow(outputs, screen_values, out_dates, assets)

    def _compute_root_mask(self, start_date, end_date, extra_rows):
        """
        Compute a lifetimes matrix from our AssetFinder, then drop columns that
        didn't exist at all during the query dates.

        Parameters
        ----------
        start_date : pd.Timestamp
            Base start date for the matrix.
        end_date : pd.Timestamp
            End date for the matrix.
        extra_rows : int
            Number of extra rows to compute before `start_date`.
            Extra rows are needed by terms like moving averages that require a
            trailing window of data.

        Returns
        -------
        lifetimes : pd.DataFrame
            Frame of dtype `bool` containing dates from `extra_rows` days
            before `start_date`, continuing through to `end_date`.  The
            returned frame contains as columns all assets in our AssetFinder
            that existed for at least one day between `start_date` and
            `end_date`.
        """
        calendar = self._calendar
        finder = self._finder
        start_idx, end_idx = self._calendar.slice_locs(start_date, end_date)
        if start_idx < extra_rows:
            raise NoFurtherDataError(
                msg="Insufficient data to compute Pipeline mask: "
                "start date was %s, "
                "earliest known date was %s, "
                "and %d extra rows were requested." % (
                    start_date, calendar[0], extra_rows,
                ),
            )

        # Build lifetimes matrix reaching back to `extra_rows` days before
        # `start_date.`
        lifetimes = finder.lifetimes(
            calendar[start_idx - extra_rows:end_idx],
            include_start_date=False
        )

        assert lifetimes.index[extra_rows] == start_date
        assert lifetimes.index[-1] == end_date
        if not lifetimes.columns.unique:
            columns = lifetimes.columns
            duplicated = columns[columns.duplicated()].unique()
            raise AssertionError("Duplicated sids: %d" % duplicated)

        # Filter out columns that didn't exist between the requested start and
        # end dates.
        existed = lifetimes.iloc[extra_rows:].any()
        return lifetimes.loc[:, existed]

    def _mask_and_dates_for_term(self, term, workspace, graph, dates):
        """
        Load mask and mask row labels for term.
        """
        mask = term.mask
        offset = graph.extra_rows[mask] - graph.extra_rows[term]
        return workspace[mask][offset:], dates[offset:]

    def _inputs_for_term(self, term, workspace, graph):
        """
        Compute inputs for the given term.

        This is mostly complicated by the fact that for each input we store as
        many rows as will be necessary to serve **any** computation requiring
        that input.
        """
        offsets = graph.offset
        if term.windowed:
            # If term is windowed, then all input data should be instances of
            # AdjustedArray.
            return [
                workspace[input_].traverse(
                    window_length=term.window_length,
                    offset=offsets[term, input_]
                )
                for input_ in term.inputs
            ]

        # If term is not windowed, input_data may be an AdjustedArray or
        # np.ndarray.  Coerce the former to the latter.
        out = []
        for input_ in term.inputs:
            input_data = ensure_ndarray(workspace[input_])
            offset = offsets[term, input_]
            # OPTIMIZATION: Don't make a copy by doing input_data[0:] if
            # offset is zero.
            if offset:
                input_data = input_data[offset:]
            out.append(input_data)
        return out

    def compute_chunk(self, graph, dates, assets, initial_workspace):
        """
        Compute the Pipeline terms in the graph for the requested start and end
        dates.

        Parameters
        ----------
        graph : zipline.pipeline.graph.TermGraph
        dates : pd.DatetimeIndex
            Row labels for our root mask.
        assets : pd.Int64Index
            Column labels for our root mask.
        initial_workspace : dict
            Map from term -> output.
            Must contain at least entry for `self._root_mask_term` whose shape
            is `(len(dates), len(assets))`, but may contain additional
            pre-computed terms for testing or optimization purposes.

        Returns
        -------
        results : dict
            Dictionary mapping requested results to outputs.
        """
        self._validate_compute_chunk_params(dates, assets, initial_workspace)
        loader = self._loader

        # Copy the supplied initial workspace so we don't mutate it in place.
        workspace = initial_workspace.copy()

        for term in graph.ordered():
            # `term` may have been supplied in `initial_workspace`, and in the
            # future we may pre-compute atomic terms coming from the same
            # dataset.  In either case, we will already have an entry for this
            # term, which we shouldn't re-compute.
            if term in workspace:
                continue

            # Asset labels are always the same, but date labels vary by how
            # many extra rows are needed.
            mask, mask_dates = self._mask_and_dates_for_term(
                term, workspace, graph, dates
            )
            if term.atomic:
                # FUTURE OPTIMIZATION: Scan the resolution order for terms in
                # the same dataset and load them here as well.
                to_load = [term]
                loaded = loader.load_adjusted_array(
                    to_load, mask_dates, assets, mask,
                )
                assert len(to_load) == len(loaded)
                for loaded_term, adj_array in zip_longest(to_load, loaded):
                    workspace[loaded_term] = adj_array
            else:
                workspace[term] = term._compute(
                    self._inputs_for_term(term, workspace, graph),
                    mask_dates,
                    assets,
                    mask,
                )
                assert(workspace[term].shape == mask.shape)

        out = {}
        graph_extra_rows = graph.extra_rows
        for name, term in iteritems(graph.outputs):
            # Truncate off extra rows from outputs.
            out[name] = workspace[term][graph_extra_rows[term]:]
        return out

    def _to_narrow(self, data, mask, dates, assets):
        """
        Convert raw computed pipeline results into a DataFrame for public APIs.

        Parameters
        ----------
        data : dict[str -> ndarray[ndim=2]]
            Dict mapping column names to computed results.
        mask : ndarray[bool, ndim=2]
            Mask array of values to keep.
        dates : ndarray[datetime64, ndim=1]
            Row index for arrays `data` and `mask`
        assets : ndarray[int64, ndim=2]
            Column index for arrays `data` and `mask`

        Returns
        -------
        results : pd.DataFrame
            The indices of `results` are as follows:

            index : two-tiered MultiIndex of (date, asset).
                Contains an entry for each (date, asset) pair corresponding to
                a `True` value in `mask`.
            columns : Index of str
                One column per entry in `data`.

        If mask[date, asset] is True, then result.loc[(date, asset), colname]
        will contain the value of data[colname][date, asset].
        """
        resolved_assets = array(self._finder.retrieve_all(assets))
        dates_kept = repeat_last_axis(dates.values, len(assets))[mask]
        assets_kept = repeat_first_axis(resolved_assets, len(dates))[mask]
        return DataFrame(
            data={name: arr[mask] for name, arr in iteritems(data)},
            index=MultiIndex.from_arrays([dates_kept, assets_kept]),
        ).tz_localize('UTC', level=0)

    def _validate_compute_chunk_params(self, dates, assets, initial_workspace):
        """
        Verify that the values passed to compute_chunk are well-formed.
        """
        root = self._root_mask_term
        clsname = type(self).__name__
        # Writing this out explicitly so this errors in testing if we change
        # the name without updating this line.
        compute_chunk_name = self.compute_chunk.__name__
        if root not in initial_workspace:
            raise AssertionError(
                "root_mask values not supplied to {cls}.{method}".format(
                    cls=clsname,
                    method=compute_chunk_name,
                )
            )

        shape = initial_workspace[root].shape
        implied_shape = len(dates), len(assets)
        if shape != implied_shape:
            raise AssertionError(
                "root_mask shape is {shape}, but received dates/assets "
                "imply that shape should be {implied}".format(
                    shape=shape,
                    implied=implied_shape,
                )
            )