text:
'use strict';

var State = require('../lib/state'),
    changeShippingAddressDefinition = require('./changeShippingAddressDefinition'),
    fakeSubflow2Test2LevelsDeepFlow = require('./fakeSubflow2Test2LevelsDeepFlow'),
    debug = require('debuglog')('flowambassador');

/**
 * Test the specification for a verbose flow definition
 * @type {*}
 */
module.exports = {

    flowDefinition: changeShippingAddressDefinition,

    authorizationDelegate:  null,

    subflows: [ fakeSubflow2Test2LevelsDeepFlow ],

    states: {

        changeShippingAddressView: {
            type: State.types.VIEW,
            onEntry: function (context, callback) {

                if(context.data.testUserRecoverableErrorCase)
                {
                    var testError = new Error('testUserRecoverableErrorCase');
                    callback(testError);
                }
                else {
                    callback(null, null);
                }
            },
            myCoolMethod: function (context, callback) {
                debug('myCoolMethod is executing');
                // possibly do something cool like translation of the context.data object

                var testError;
                if(context.data.testUserRecoverableErrorCase)
                {
                    testError  = new Error('testUserRecoverableErrorCase');
                    testError.type = 'testUserRecoverableErrorCase';
                    callback(testError);
                }
//                else if(context.data.testThrowUnknownError) {
//                    testError = new Error('testThrowUnknownErrorHandleWithGeneralErrorPageView');
//                    testError.type = 'testThrowUnknownErrorHandleWithGeneralErrorPageView';
//                    throw testError;
//                }
//                else if(context.data.testThrowUnknownErrorNoRender) {
//                    testError = new Error('testThrowUnknownErrorNoRender');
//                    testError.type = 'testThrowUnknownErrorNoRender';
//                    throw testError;
//                }
                else {
                    callback(null);
                }
            },
            error: function (context, callback, statePhase) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                var stateNameToTransitionTo;

                if(statePhase === 'onExit')
                {
                    if(context.flow.err.type === 'testThrowUnknownErrorHandleWithGeneralErrorPageView') {
                        debug('Test handling a non-user recoverable error in phase: ' + statePhase + 'changeShippingAddressView');
                        stateNameToTransitionTo = 'generalErrorPageView';
                        callback(context.flow.err, stateNameToTransitionTo);
                    }
                    else if(context.flow.err.type ===  'testUserRecoverableErrorCase')  {
                        debug('Test handling an known client error in changeShippingAddressView');
                        // do something cool like offer BML
                        context.data = {'FakeUserRecoverableMsg': 'not a valid data ... FIX IT NOW ... haha'};
                        context.data.errors = [];
                        context.data.errors.push({'User error': 'recoverable'});
                        stateNameToTransitionTo = 'changeShippingAddressView'; // stay in this view
                        callback(context.flow.err, stateNameToTransitionTo);
                    }
                    else {
                        // assume unknown error with no transition to any state so no rendering
                        // this case should test your middleware handler for next(err)
                        stateNameToTransitionTo = null;
                        callback(context.flow.err, stateNameToTransitionTo);
                    }
                }
                else {
                    // statePhase === 'onEntry'
                    stateNameToTransitionTo =  'genericPurchaseErrorState';
                    callback(context.flow.err, stateNameToTransitionTo);
                }
            }
        },

        generalErrorPageView:  {
            type: State.types.VIEW,
            onEntry: function (context, callback) {

                callback(null);
            },
            error: function (context, callback, statePhase) {
                callback(null, null);
            }
        },

        addShippingAddressView: {
            type: State.types.VIEW,
            onEntry: function (context, callback) {
                callback(null);
            },
            error: function (context, callback, statePhase) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, null);
            }
        },

        changeShippingAddress: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                // possibly do something cool like translation of the context.data object
                callback(null, 'success');
                // or
                // callback(null, 'userInfoError');

            },
            error: function (context, callback) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, 'userInfoError');
            }
        },

        testRedirectToMerchant: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                // possibly do something cool like translation of the context.data object
                callback(null, 'success');
            },
            error: function (context, callback) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, 'userInfoError');
            }
        },

        addShippingAddress: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                // possibly do something cool like translation of the context.data object
                callback(null, 'success');
            },
            error: function (context, callback) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, 'userInfoError');
            }
        },

        primeFlow: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                // possibly do something cool like translation of the context.data object
                debug('>>>>>>>>>>> Priming fake action state to test coming into subflow with action state');
                callback(null, 'success');
            },
            error: function (context, callback) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, 'userInfoError');
            }
        },

        actionStateForErrorRecovery: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                // possibly do something cool like translation of the context.data object
                debug('>>>>>>>>>>> actionStateForErrorRecovery');
                callback(null, 'success');
            },
            error: function (context, callback) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                callback(context.flow.err, 'userInfoError');
            }
        },

        actionStateForErrorTesting: {
            type: State.types.ACTION,
            onEntry: function (context, callback) {
                debug('>>>>>>>>>>> action state to use as a starting spot to test errors');

                // Normal op would be callback(null, 'success');

                var testError;
                if(context.data.testUserRecoverableErrorCase)
                {
                    testError  = new Error('testUserRecoverableErrorCase');
                    testError.type = 'testUserRecoverableErrorCase';
                    callback(testError);
                }
//                else if(context.data.testThrowUnknownError) {
//                    testError = new Error('testThrowUnknownErrorHandleWithGeneralErrorPageView');
//                    testError.type = 'testThrowUnknownErrorHandleWithGeneralErrorPageView';
//                    throw testError;
//                }
//                else if(context.data.testThrowUnknownErrorNoRender) {
//                    testError = new Error('testThrowUnknownErrorNoRender');
//                    testError.type = 'testThrowUnknownErrorNoRender';
//                    throw testError;
//                }
                else {
                    callback(null);
                }
            },
            error: function (context, callback, statePhase) {
                // framework will attach the error to the flow; context.flow.err = err, so just do custom processing
                var stateNameToTransitionTo;

                if(context.flow.err.type === 'testThrowUnknownErrorHandleWithGeneralErrorPageView') {
                    debug('Test handling a non-user recoverable error in phase: ' + statePhase + 'actionStateForErrorTesting');
                    stateNameToTransitionTo = 'generalErrorPageView';
                    callback(context.flow.err, stateNameToTransitionTo);
                }
                else if(context.flow.err.type ===  'testUserRecoverableErrorCase')  {
                    debug('Test handling an known client error in actionStateForErrorTesting');
                    // do something cool like offer BML
                    context.data = {'FakeUserRecoverableMsg': 'not a valid data ... FIX IT NOW ... haha'};
                    context.data.errors = [];
                    context.data.errors.push({'User error': 'recoverable'});
                    stateNameToTransitionTo = 'actionStateForErrorRecovery';
                    callback(context.flow.err, stateNameToTransitionTo);
                }
                else {
                    // assume unknown error with no transition to any state so no rendering
                    // this case should test your middleware handler for next(err)
                    stateNameToTransitionTo = null;
                    callback(context.flow.err, stateNameToTransitionTo);
                }
            }
        }
    }
};


text:
// Patterns: 1
// Matches: InSomeNamespace.cs
// NotMatches: Foo.cs,InSomeOtherNamespace.cs

using Castle.MicroKernel.Registration;
using Castle.MicroKernel.SubSystems.Configuration;
using Castle.Windsor;
using SomeNamespace;

namespace TestApplication.Windsor.TestCases
{
    public class FromThisAssemblyInSameNamespaceAsNonGeneric : IWindsorInstaller
    {
        public void Install(IWindsorContainer container, IConfigurationStore store)
        {
            container.Register(
                AllTypes.FromThisAssembly().InSameNamespaceAs(typeof(IInSomeNamespace)),
                Classes.FromThisAssembly().InSameNamespaceAs(typeof(IInSomeNamespace)),
                Castle.MicroKernel.Registration.Types.FromThisAssembly().InSameNamespaceAs(typeof(IInSomeNamespace))
                );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>python几个特别的__开头的方法 - 小明明s à domicile</title>
  <meta name="author" content="Dongweiming">
  <meta name="baidu-site-verification" content="VklGG0Kd1k" />

  <meta name="description" content="douban dongweiming site">
  <meta name="keywords" content="python, ipython, emacs, github, dongweiming, django, flask, bottle, jinja2, requests, douban, httpie, jedi, mako, plim, react, develop, lisp, ruby, web development, sed, awk, linux, 运维, 运维开发, sentry, tonrado, scrapy, fabric, celery">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="canonical" href="http://dongweiming.github.com/blog/archives/pythonji-ge-te-bie-de-kai-tou-de-fang-fa">
  <link href="/favicon.png" rel="icon">
  <link href="/stylesheets/bootstrap/bootstrap.css" media="screen, projection" rel="stylesheet" type="text/css">
  <link href="/stylesheets/bootstrap/responsive.css" media="screen, projection" rel="stylesheet" type="text/css">
  <link href="/stylesheets/syntax/syntax.css" media="screen, projection" rel="stylesheet" type="text/css">

  <link href="/atom.xml" rel="alternate" title="小明明s à domicile" type="application/atom+xml">

<link href="/stylesheets/sh_ide-anjuta.css" rel="stylesheet" type="text/css">

      小明明s à domicile

博客主页

文章列表

关于本站

sed_and_awk

Expert-Python

关于我

RSS

            <form action="/search" method="get" class="pull-right navbar-search">
    <fieldset role ="search">
        <input type="text" id="search-query" name="q" placeholder="Search" autocomplete="off" class="search" />
    </fieldset>
</form>

Python几个特别的__开头的方法

<time datetime="2014-12-06T22:51:00+08:00" pubdate data-updated="true">Dec 6th, 2014</time>

前言

A Guide to Python's Magic Methodspython的绝大多数这样的特殊方法都
在这里面被提到了. 今天我来说3个他没有提到的[__dir__, __slots__, __weakref__], 再强调下他提到的2个[__missing__, __contains__]

__dir__ -> 看个小例子就知道了

<notextile>

In [1]: class T(object):
   ...:     pass
   ...:
In [2]: t = T()
In [3]: t.<Tab>
啥也没有...

</notextile>

<notextile>

In [4]: class T2(object):
   ...:     def __dir__(self):
   ...:         return ['a', 'b']
   ...:
In [5]: t = T2()
In [6]: t.
t.a  t.b
In [7]: dir(t)
Out[7]: ['a', 'b']

</notextile>

看出来了把, 不解释, 但是这个__dir__是相对于类的实例有效果的.

__slots__

这个在我初学python的时候就被模糊了, 原来的理解是它的出现替代了__dict__,也就是说你只能给__slots__
这个变量列表项的属性赋值. 对外的接口减少了,也安全了. 后来看了这篇Saving 9 GB of RAM with Python's slots.
好久不做运维了,在生产环境究竟怎么样我无法定论, <python cookbook="">也提到了,在对象实例很多的时候他能帮助减少内存, 详见https://www.safaribooksonline.com/library/view/python-cookbook-3rd/9781449357337/ch08s04.html.
这里来个小实验(在Hacker News也被讨论过https://news.ycombinator.com/item?id=6750187)</python>

代码例子(我对细节做注释):

<notextile>

# coding=utf-8
import sys
from itertools import starmap, product

class SlotTest(object):
    # __slots__ = ['x', 'y', 'z'] 主要对比去掉这句和包含这句程序内存占用

    def __init__(self, x, y, z):
            self.x = x
                    self.y = y
                            self.z = z

    def __str__(self):
            return "{} {} {}".format(self.x, self.y, self.z)

p = product(range(10000), range(20), [4]) # 创建0-1000 & 0-20 & 4 的笛卡尔积
a = list(starmap(SlotTest, p)) # 相当于对每个SlotTest实例化,实例化的格式是p的长度

print a[0]
sys.stdin.read(1)

</notextile>

结果对比:

<notextile>

$pmap -x `</span>ps -ef|grep test_slot.py|grep -v grep|awk <span class="s1">'{print $2}'</span><span class="sb">`|grep total # 未使用__slots__
  total kB          103496   76480   73728
$pmap -x `</span>ps -ef|grep test_slot.py|grep -v grep|awk <span class="s1">'{print $2}'</span><span class="sb">`|grep total # 使用了__slots__
  total kB           49960   22888   20136

</notextile>

结果很明显,内存占用减少了很多…

__weakref__ 弱引用

首先先说下weakref: 弱引用,与强引用相对,是指不能确保其引用的对象不会被垃圾回收器回收的引用。一个对象若只被弱引用所引用,则被认为是不可访问(或弱可访问)的,并因此可能在任何时刻被回收.
在Python中,当一个对象的引用数目为0的时候,才会被从内存中回收. 但是被循环引用呢?

<notextile>

In [1]: import weakref

In [2]: import gc

In [3]: class Obj(object):
   ...:     def a(self):
   ...:         return 1
   ...:
In [4]: obj = Obj()

In [5]: s = obj

In [6]: gc.collect() # 不可达引用对象的数量
Out[6]: 3

In [7]: print s is obj
True

In [8]: obj = 1 # 最初的被引用的对象改变了.

In [9]: gc.collect()
Out[9]: 0

In [10]: s is None # s还是指向了Obj 引用计数为1
Out[10]: False

In [11]: s
Out[11]: <__main__.Obj at 0x2b36510>

----华丽的分割一下

In [12]: obj = Obj()

In [13]: r = weakref.ref(obj) # 让obj变成那个弱引用

In [14]: gc.collect()
Out[14]: 211

In [15]: r() is obj
True

In [16]: obj = 1

In [17]: gc.collect()
Out[17]: 0

In [18]: r() is None # 弱引用计数器没有增加,所以当obj不在引用Obj的时候,Obj对象就被释放了
Out[18]: True

</notextile>

好吧, 我的总结是弱引用是个好东西, 但是加了__slots__就不支持弱引用了. 所以需要__weakref__

<notextile>

In [9]: class T3(object):
   ...:     __slots__ = []
      ...:

In [10]: class T4(object):
   ....:     __slots__ = '__weakref__'  # 这样就支持了weakref
      ....:

In [11]:  import weakref

In [12]: t3 = T3()

In [13]: t4 = T4()

In [14]: weakref.ref(t3)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-14-bdb7ab7ac3bc> in <module>()
----> 1 weakref.ref(t3)

TypeError: cannot create weak reference to 'T3' object

In [15]: weakref.ref(t4)
Out[15]: <weakref at 0x2766f70; to 'T4' at 0x2586fd8>

</notextile>

__contains__ 判断某值 in/not in 实例

<notextile>

In [1]: class NewList(object):
   ...:     def __init(self, values):
   ...:         self.values = values
   ...:     def __contains__(self, value):
   ...:         return value in self.values
   ...:
In [2]: l = NewList([1, 2, 3, 4])

In [3]: 4 in l
Out[3]: True

In [4]: 10 in l
Out[4]: False

</notextile>

__missing__

最初看这个特殊方法是看python标准库的源码的时候(collections#L421):

<notextile>

class Counter(dict):
    ...

    def __missing__(self, key):
        'The count of elements not in the Counter is zero.'
        # Needed so that self[missing_item] does not raise KeyError
        return 0

</notextile>

什么意思呢?

<notextile>

In [6]: c = collections.Counter({'a':1})

In [7]: c['b'] # 没有键的count设置默认值0
Out[7]: 0

</notextile>

很多人可能看过这个(关于defaultdict的ppt)[http://discorporate.us/jek/talks/defaultdict/]. 内容就不说了, 讲的非常好.

Dongweiming 发布于

<time datetime="2014-12-06T22:51:00+08:00" pubdate data-updated="true">Dec 6th, 2014</time>

    python

评论

Please enable JavaScript to view the comments powered by Disqus.

« 一个使用python的web程序员的emacs.d

博客文章

ipython的一些高级用法(一)
        »

我新建了一个QQ群

522012167

欢迎入伙

最近发布

        《Python Web开发实战》要输出到台湾了

        《Python-Web开发实战》上市一个月了

        《Python Web开发实战》预售喽

        使用Strider实现持续集成

        仿Djangobook的Markdown文章评注系统

        使用Github webhook服务实现提PR自动检查Flake8并在对应位置发评论

        最近在写一本Python Web开发的书

        CODE开源了

        12个python填空题

        我理解的python最佳实践

个人网站

带我入行的boss

小明明s Github Blog

Love story(GAE)

unixhot运维社区

Vpsee

sed_and_awk

Expert-Python

GitHub帐号

Status updating...

  @dongweiming on GitHub

标签Cloud

豆瓣阅读

  @小明明 on Douban

文章统计

本站共有 271 篇文章

  Copyright © 2016 - Dongweiming -
  Powered by Octopress


text:
package se.jsa.jles.internal.query;

import se.jsa.jles.internal.Constraint;
import se.jsa.jles.internal.FieldConstraint;
import se.jsa.jles.internal.util.Objects;

class EqualsRequirement extends Requirement {
	private final String fieldName;
	private final Object equality;

	public EqualsRequirement(Class<?> eventType, String fieldName, Object equality) {
		if (equality != null) {
			validateFieldType(eventType, fieldName, equality.getClass());
		}
		this.fieldName = Objects.requireNonNull(fieldName);
		this.equality = equality;
	}

	@Override
	public FieldConstraint createFieldConstraint() {
		return FieldConstraint.create(fieldName, new EqualsConstraint(equality));
	}

	private static class EqualsConstraint extends Constraint {
		private final Object equality;

		public EqualsConstraint(Object equality) {
			this.equality = equality;
		}

		@Override
		protected boolean isSatisfied(Object eventFieldValue) {
			return equality == null ? eventFieldValue == null : eventFieldValue.equals(equality);
		}

		@Override
		protected Object cast(Object eventFieldValue) {
			if (equality == null) {
				return eventFieldValue;
			} else {
				return super.cast(eventFieldValue);
			}
		}

		@Override
		public Class<?> getFieldType() {
			return equality.getClass();
		}
	}

	@Override
	public String toString() {
		return fieldName + "=" + equality;
	}
}


text:
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Diagnostics.Contracts;
using System;

// Disable the "this variable is not used" warning as every field would imply it.
#pragma warning disable 0414
// Disable the "this variable is never assigned to".
#pragma warning disable 0067
// Disable the "this event is never assigned to".
#pragma warning disable 0649
// Disable the "this variable is never used".
#pragma warning disable 0169
// Disable the "new keyword not required" warning.
#pragma warning disable 0109
// Disable the "extern without DllImport" warning.
#pragma warning disable 0626
// Disable the "could hide other member" warning, can happen on certain properties.
#pragma warning disable 0108

namespace System.Web.Compilation
{
  public partial interface IImplicitResourceProvider
  {
    #region Methods and constructors
    System.Collections.ICollection GetImplicitResourceKeys(string keyPrefix);

    Object GetObject(ImplicitResourceKey key, System.Globalization.CultureInfo culture);
    #endregion
  }
}


text:
hadoop fs -rm -r adult.test
hadoop fs -rm -r adult.out
if [ $1 -eq -1 ];
then
  hadoop fs -put adult.test adult.test
else
  head -$1 adult.test > temp1
  hadoop fs -put temp1 adult.test
  rm temp1
fi
export HADOOP_CMD=/usr/bin/hadoop
export HADOOP_STREAMING=/usr/lib/hadoop-mapreduce/hadoop-streaming-*.jar
Rscript bn-demo.R
hadoop fs -getmerge adult.out adult.out


text:
namespace OGLWRAP_NAMESPACE_NAME {
namespace enums {

enum class MemoryBarrierBit : GLenum {
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT)
  kVertexAttribArrayBarrierBit = GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_ELEMENT_ARRAY_BARRIER_BIT)
  kElementArrayBarrierBit = GL_ELEMENT_ARRAY_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_UNIFORM_BARRIER_BIT)
  kUniformBarrierBit = GL_UNIFORM_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_TEXTURE_FETCH_BARRIER_BIT)
  kTextureFetchBarrierBit = GL_TEXTURE_FETCH_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_SHADER_IMAGE_ACCESS_BARRIER_BIT)
  kShaderImageAccessBarrierBit = GL_SHADER_IMAGE_ACCESS_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_COMMAND_BARRIER_BIT)
  kCommandBarrierBit = GL_COMMAND_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_PIXEL_BUFFER_BARRIER_BIT)
  kPixelBufferBarrierBit = GL_PIXEL_BUFFER_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_TEXTURE_UPDATE_BARRIER_BIT)
  kTextureUpdateBarrierBit = GL_TEXTURE_UPDATE_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_BUFFER_UPDATE_BARRIER_BIT)
  kBufferUpdateBarrierBit = GL_BUFFER_UPDATE_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_FRAMEBUFFER_BARRIER_BIT)
  kFramebufferBarrierBit = GL_FRAMEBUFFER_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_TRANSFORM_FEEDBACK_BARRIER_BIT)
  kTransformFeedbackBarrierBit = GL_TRANSFORM_FEEDBACK_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_ATOMIC_COUNTER_BARRIER_BIT)
  kAtomicCounterBarrierBit = GL_ATOMIC_COUNTER_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_SHADER_STORAGE_BARRIER_BIT)
  kShaderStorageBarrierBit = GL_SHADER_STORAGE_BARRIER_BIT,
#endif
#if OGLWRAP_DEFINE_EVERYTHING || defined(GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT)
  kClientMappedBufferBarrierBit = GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT,
#endif
};

}  // namespace enums
using namespace enums;
}  // namespace oglwrap

#endif


text:
	do { \
		SIMPLCOMPILEERRORINFO e = { _err, currentCompileUnitIndex, _ln }; \
		this->errors.push_back(e); \
		return false; \
	} while (0)

#define raiseCompileErrorNoReturn(_err, _ln) \
	do { \
		SIMPLCOMPILEERRORINFO e = { _err, currentCompileUnitIndex, _ln }; \
		this->errors.push_back(e); \
	} while (0)

// ========== parser & lexer =============
extern FILE *yyin;
extern AstProgram *root;
extern KIMLUINT nSyntaxErrors;
extern KIMLCSTRING szFileName;
extern int yylineno; //simpl.lexer.cpp

struct yy_buffer_state;
typedef struct yy_buffer_state * YY_BUFFER_STATE;
extern int yyparse();
extern YY_BUFFER_STATE yy_scan_string(const char * str);
extern void yy_delete_buffer(YY_BUFFER_STATE buffer);
// =======================================

Compiler::Compiler(void)
{
	compiler = kimlCreateCompiler();
	constTable = new ConstTable();
	functionTable = new FunctionTable();
	currentFunction = nullptr;

	currentScope = nullptr;
	EnterScope();
	rootScope = currentScope;
}

Compiler::~Compiler(void)
{
	CleanUpAll();

	kimlFreeCompiler(&compiler);
	safeDelete(constTable);
	safeDelete(functionTable);
}

bool Compiler::Parse(const char *fileName, const char *fileContent)
{
	auto buffer = yy_scan_string(fileContent);
	int parseResult = yyparse();
	yy_delete_buffer(buffer);

	if (parseResult || nSyntaxErrors)
		return false;

	CompileUnit unit = { fileName, root };
	compileUnits.push_back(unit);

	return true;
}

bool Compiler::Parse(const char *fileName, FILE *fp)
{
	yyin = fp;
	int parseResult = yyparse();

	if (parseResult || nSyntaxErrors)
		return false;

	CompileUnit unit = { fileName, root };
	compileUnits.push_back(unit);

	return true;
}

bool Compiler::Compile(bool hasDebugInfo)
{
	this->hasDebugInfo = hasDebugInfo;

	for (unsigned int i = 0, c = compileUnits.size(); i < c; ++i)
	{
		currentCompileUnitIndex = i;
		auto &unit = compileUnits[i];
		if (!ScanDeclarations(unit.root))
			return false;
	}

	Emit(op_fcall, kimlHashName("main"));
	Emit(op_hlt);

	for (unsigned int i = 0, c = compileUnits.size(); i < c; ++i)
	{
		currentCompileUnitIndex = i;
		auto &unit = compileUnits[i];
		if (!Emit(unit.root))
			return false;
	}

	return true;
}

bool Compiler::Finish(void)
{
	if (kimlBake(compiler) == FALSE)
		return false;
	else
		return true;
}

bool Compiler::GetByteCode(KIMLBYTE **byteCode, KIMLUINT *byteCodeSize)
{
	kimlGetByteCode(compiler, byteCode, byteCodeSize);
	return true;
}

void Compiler::CleanUpAll(void)
{
	constTable->CleanUp();
	functionTable->CleanUp();

	for (unsigned int i = 0, c = compileUnits.size(); i < c; ++i)
		delete compileUnits[i].root;
	compileUnits.clear();

	for (auto s = currentScope; s; )
	{
		auto p = s->GetParent();
		delete s;
		s = p;
	}
	currentScope = nullptr;
	rootScope = nullptr;
}

bool Compiler::ScanDeclarations(AstProgram *root)
{
	SIMPLCOMPILEERRORCODES err;

	auto &stmts = root->getStatements()->getStatements();
	for (auto it = stmts.begin(), itEnd = stmts.end(); it != itEnd; ++it)
	{
		auto stmt = *it;
		KIMLUINT line = stmt->getLocation().first_line;

		switch (stmt->getType())
		{
			case STMT_CONST:
			{
				auto stmtConst = (AstConst *)stmt;
				if (!PerformTypeCheck(stmtConst->getValue()))
					return false;
				if (!FoldExpression(stmtConst->getValue()))
					raiseCompileError(SCE_CONST_NOT_CONST, line);

				err = this->constTable->AddConst(stmtConst->getName(), *stmtConst->getValue()->getConstValue());
				if (err)
					raiseCompileError(err, line);
				break;
			}
			case STMT_FUNC:
			{
				auto stmtFunc = static_cast<AstFunc *>(stmt);
				FunctionInfo fi = FunctionInfo(stmtFunc);
				err = this->functionTable->AddFunction(fi.name, fi);
				if (err)
					raiseCompileError(err, line);

				if (stmtFunc->getStatements())
				{
					if (hasDebugInfo)
						Emit(op_trace, stmt->getLocation().first_line);

					AddLabel(fi.name);
					kimlEmitFuncDecl(compiler, fi.name);
				}

				break;
			}
			case STMT_ENUM:
			{
				auto enumdef = static_cast<AstEnum *>(stmt);

				const std::vector<KIMLCSTRING> &idents = enumdef->getIdents();
				KIMLINT idx = 0;
				for (auto it = idents.begin(); it != idents.end(); ++it)
				{
					if (this->currentScope->HasSymbol(*it))
					{
						raiseCompileErrorNoReturn(SCE_DUPLICATE_SYMBOL, line);
						continue;
					}

					Object obj(idx);
					err = this->constTable->AddConst(*it, obj);
					if (err)
					{
						raiseCompileErrorNoReturn(err, line);
						continue;
					}

					++idx;
				}
				break;
			}
			default:
			{
				raiseCompileError(SCE_DECLARE_ONLY, (KIMLUINT)stmt->getLocation().first_line);
			}
		}
	}

	return true;
}

bool Compiler::Emit(AstProgram *root)
{
	auto &stmts = root->getStatements()->getStatements();
	for (auto it = stmts.begin(), itEnd = stmts.end(); it != itEnd; ++it)
	{
		auto stmt = *it;
		if (!Emit(stmt))
			return false;
	}

	return true;
}

bool Compiler::Emit(AstStatement *statement)
{
	if (hasDebugInfo)
		Emit(op_trace, statement->getLocation().first_line);

	switch (statement->getType())
	{
		case STMT_FUNC:
			return Emit(static_cast<AstFunc *>(statement));
		case STMT_LIST:
			return Emit(static_cast<AstStatementList *>(statement));
		case STMT_VAR:
			return Emit(static_cast<AstVar *>(statement));
		case STMT_IF:
			return Emit(static_cast<AstIf *>(statement));
		case STMT_WHILE:
			return Emit(static_cast<AstWhile *>(statement));
		case STMT_DO:
			return Emit(static_cast<AstDo *>(statement));
		case STMT_BREAK:
			return Emit(static_cast<AstBreak *>(statement));
		case STMT_CONTINUE:
			return Emit(static_cast<AstContinue *>(statement));
		case STMT_RETURN:
			return Emit(static_cast<AstReturn *>(statement));
		case STMT_EXPR:
			return Emit(static_cast<AstExprStatement *>(statement));
		case STMT_ENUM:
		case STMT_CONST:
			return true;
		default:
			return false;
	}
}

bool Compiler::Emit(AstFunc *statement)
{
	if (!statement->getStatements())
		return true;

	MarkLabel(statement->getName());

	functionTable->GetFunction(statement->getName(), currentFunction);
	EnterScope();

	auto &params = statement->getParams()->getParams();
	for (auto it = params.begin(), itEnd = params.end(); it != itEnd; ++it)
	{
		auto err = currentScope->AddSymbol(it->second, it->first);
		if (err)
			raiseCompileError(err, (KIMLUINT)statement->getLocation().first_line);
	}

	for (int i = 0, c = (int)params.size(); i < c; ++i)
	{
		int offset = c - i;
		if (offset <= 4)
		{
			OpCodes opcode = op_srd1;
			switch (offset)
			{
				case 1: opcode = op_srd1; break;
				case 2: opcode = op_srd2; break;
				case 3: opcode = op_srd3; break;
				case 4: opcode = op_srd4; break;
			}
			Emit(opcode);
		}
		else
		{
			Emit(op_srd, offset);
		}
		Emit(op_new, kimlHashName(GetScopedName(params[i].second).c_str()));
	}

	auto &stmts = statement->getStatements()->getStatements();
	for (auto it = stmts.begin(), itEnd = stmts.end(); it != itEnd; ++it)
		if (!Emit(*it))
			return false;

	LeaveScope();

	switch (currentFunction->returnType)
	{
		case KIML_BOOL:
			Emit(op_ldfalse);
			break;
		case KIML_ANYTYPE:
		case KIML_INT:
			Emit(op_ldi, 0);
			break;
		case KIML_REAL:
			Emit(op_ldr, 0);
			break;
		case KIML_STRING:
			Emit(op_ldes);
			break;
		case KIML_OBJECT:
			Emit(op_ldnull);
			break;
	}

	Emit(op_twr0);
	Emit(op_ret);

	currentFunction = nullptr;

	return true;
}

bool Compiler::Emit(AstStatementList *statement)
{
	EnterScope();

	auto stmts = statement->getStatements();
	for (auto it = stmts.begin(), itEnd = stmts.end(); it != itEnd; ++it)
		if (!Emit(*it))
			return false;

	LeaveScope();

	return true;
}

bool Compiler::Emit(AstVar *statement)
{
	auto err = currentScope->AddSymbol(statement->getName(), statement->getType());
	if (err)
		raiseCompileError(err, (KIMLUINT)statement->getLocation().first_line);

	if (statement->getValue() != nullptr)
	{
		if (!PerformTypeCheck(statement->getValue()))
			return false;

		if (!Emit(statement->getValue()))
			return false;

		int typeMatchResult = TypeMatchTable[statement->getType()][statement->getValue()->getDataType()];
		if (typeMatchResult == K_TYPE_MISMATCHED)
			raiseCompileError(SCE_TYPE_MISMATCHED, (KIMLUINT)statement->getValue()->getLocation().first_line);

		EmitCast(typeMatchResult, statement->getType());
		Emit(op_new, kimlHashName(GetScopedName(statement->getName()).c_str()));
	}
	else
	{
		switch (statement->getType())
		{
			case KIML_BOOL:
				Emit(op_ldfalse);
				break;
			case KIML_ANYTYPE:
			case KIML_INT:
				Emit(op_ldi, 0);
				break;
			case KIML_REAL:
				Emit(op_ldr, 0);
				break;
			case KIML_STRING:
				Emit(op_ldes);
				break;
			case KIML_OBJECT:
				Emit(op_ldnull);
				break;
		}
		Emit(op_new, kimlHashName(GetScopedName(statement->getName()).c_str()));
	}

	return true;
}

bool Compiler::Emit(AstIf *statement)
{
	if (!PerformTypeCheck(statement->getCondition()))
		return false;

	std::string Lendif = AllocLabel();
	AddLabel(Lendif);

	Emit(statement->getCondition());
	if (statement->getCondition()->getDataType() != KIML_BOOL)
		Emit(op_cvb);

	if (statement->getFalsePart() != nullptr)
	{
		std::string Lelse = AllocLabel();
		AddLabel(Lelse);

		Emit(op_not);
		EmitJump(op_cjmp, Lelse);

		if (!Emit(statement->getTruePart()))
			return false;

		EmitJump(op_jmp, Lendif);

		MarkLabel(Lelse);
		if (!Emit(statement->getFalsePart()))
			return false;
	}
	else
	{
		Emit(op_not);
		EmitJump(op_cjmp, Lendif);

		if (!Emit(statement->getTruePart()))
			return false;
	}

	MarkLabel(Lendif);

	return true;
}

bool Compiler::Emit(AstWhile *statement)
{
	if (!PerformTypeCheck(statement->getCondition()))
		return false;

	std::string Lbeginwhile = AllocLabel();
	std::string Lendwhile = AllocLabel();

	AddLabel(Lbeginwhile);
	AddLabel(Lendwhile);
	loopBeginLabels.push(Lbeginwhile);
	loopEndLabels.push(Lendwhile);

	MarkLabel(Lbeginwhile);

	Emit(statement->getCondition());
	if (statement->getCondition()->getDataType() != KIML_BOOL)
		Emit(op_cvb);

	Emit(op_not);
	EmitJump(op_cjmp, Lendwhile);

	if (!Emit(statement->getLoopPart()))
		return false;

	EmitJump(op_jmp, Lbeginwhile);
	MarkLabel(Lendwhile);

	loopBeginLabels.pop();
	loopEndLabels.pop();

	return true;
}

bool Compiler::Emit(AstDo *statement)
{
	if (!PerformTypeCheck(statement->getCondition()))
		return false;

	std::string Lbegindo = AllocLabel();
	std::string Lcheckdo = AllocLabel();
	std::string Lenddo = AllocLabel();

	AddLabel(Lbegindo);
	AddLabel(Lcheckdo);
	AddLabel(Lenddo);

	loopBeginLabels.push(Lcheckdo);
	loopEndLabels.push(Lenddo);

	MarkLabel(Lbegindo);

	if (!Emit(statement->getLoopPart()))
		return false;

	MarkLabel(Lcheckdo);

	Emit(statement->getCondition());
	if (statement->getCondition()->getDataType() != KIML_BOOL)
		Emit(op_cvb);

	EmitJump(op_cjmp, Lbegindo);
	MarkLabel(Lenddo);

	loopBeginLabels.pop();
	loopEndLabels.pop();

	return true;
}

bool Compiler::Emit(AstBreak *statement)
{
	if (loopEndLabels.empty())
		return false;

	EmitJump(op_jmp, loopEndLabels.top());
	return true;
}

bool Compiler::Emit(AstContinue *statement)
{
	if (loopBeginLabels.empty())
		return false;

	EmitJump(op_jmp, loopBeginLabels.top());
	return true;
}

bool Compiler::Emit(AstReturn *statement)
{
	if (statement->getExpression() != nullptr)
	{
		if (!PerformTypeCheck(statement->getExpression()))
			return false;

		auto typeMatchResult = TypeMatchTable[currentFunction->returnType][statement->getExpression()->getDataType()];

		if (typeMatchResult == K_TYPE_MISMATCHED)
			raiseCompileError(SCE_TYPE_MISMATCHED, (KIMLUINT)statement->getLocation().first_line);

		Emit(statement->getExpression());
		EmitCast(typeMatchResult, currentFunction->returnType);
	}
	else
	{
		switch (currentFunction->returnType)
		{
			case KIML_BOOL:
				Emit(op_ldfalse);
				break;
			case KIML_ANYTYPE:
			case KIML_INT:
				Emit(op_ldi, 0);
				break;
			case KIML_REAL:
				Emit(op_ldr, 0);
				break;
			case KIML_STRING:
				Emit(op_ldes);
				break;
			case KIML_OBJECT:
				Emit(op_ldnull);
				break;
		}
	}

	Emit(op_twr0);
	Emit(op_ret);

	return true;
}

bool Compiler::Emit(AstExprStatement *statement)
{
	switch (statement->getExpression()->getType())
	{
		case EXPR_BIN:
		{
			if (static_cast<AstBinExpr*>(statement->getExpression())->getOperator() != BINOP_ASN)
				raiseCompileError(SCE_ASSIGN_OR_FUNC_CALL_ONLY, (KIMLUINT)statement->getLocation().first_line);
			break;
		}
		case EXPR_FUNC:
			break;
		default:
			raiseCompileError(SCE_ASSIGN_OR_FUNC_CALL_ONLY, (KIMLUINT)statement->getLocation().first_line);
	}

	if (!PerformTypeCheck(statement->getExpression()))
		return false;

	if (!Emit(statement->getExpression()))
		return false;

	Emit(op_twr0);
	return true;
}

bool Compiler::Emit(AstExpression *expression)
{
	if (this->FoldExpression(expression))
	{
		Object *constval = expression->getConstValue();
		switch (constval->getDataType())
		{
			case KIML_BOOL:
				Emit((constval->getBool() ? op_ldtrue : op_ldfalse));
				break;
			case KIML_INT:
				Emit(op_ldi, constval->getInt());
				break;
			case KIML_REAL:
				Emit(op_ldr, constval->getFloat());
				break;
			case KIML_STRING:
			{
				KIMLCSTRING s = constval->getString();
				if (s[0] == 0)
				{
					Emit(op_ldes);
				}
				else
				{
					Emit(op_lds, s);
				}
				delete[]s;
				break;
			}
			case KIML_OBJECT:
				Emit(op_ldnull); // as the only constval for object type is null
				break;
		}

		return true; //no more things to do
	}

	switch (expression->getType())
	{
		case EXPR_IDENT:
		{
			Object obj;
			if (this->constTable->GetConst(static_cast<AstIdent *>(expression)->getIdent(), obj))
			{
				switch (obj.getDataType())
				{
					case KIML_BOOL:
						Emit(obj.getBool() ? op_ldtrue : op_ldfalse);
						break;
					case KIML_INT:
						Emit(op_ldi, obj.getInt());
						break;
					case KIML_REAL:
						Emit(op_ldr, obj.getFloat());
						break;
					case KIML_STRING:
					{
						KIMLCSTRING s = obj.getString();
						if (s[0] == 0)
						{
							Emit(op_ldes);
						}
						else
						{
							Emit(op_lds, s);
						}
						delete[]s;
						break;
					}
				}
			}
			else
			{
				auto exprIdent = static_cast<AstIdent *>(expression);
				auto name = GetScopedName(exprIdent->getIdent(), exprIdent->getScopeDepth());
				Emit(op_ldvar, kimlHashName(name.c_str()));
			}
		}
		break;

		case EXPR_TRUE:
			Emit(op_ldtrue);
			break;

		case EXPR_FALSE:
			Emit(op_ldfalse);
			break;

		case EXPR_NULL:
			Emit(op_ldnull);
			break;

		case EXPR_INT:
			Emit(op_ldi, static_cast<AstConstInt *>(expression)->getValue());
			break;

		case EXPR_REAL:
			Emit(op_ldr, static_cast<AstConstReal *>(expression)->getValue());
			break;

		case EXPR_STRING:
		{
			auto litstring = static_cast<AstConstString *>(expression);
			if (litstring->getValue()[0] == 0)
			{
				Emit(op_ldes);
			}
			else
			{
				Emit(op_lds, litstring->getValue());
			}
		}
		break;

		case EXPR_BIN:
		{
			auto binexpr = static_cast<AstBinExpr *>(expression);
			if (binexpr->getOperator() == BINOP_ASN)
			{
				int typeMatchResult = TypeMatchTable[binexpr->getLeft()->getDataType()][binexpr->getRight()->getDataType()];

				Emit(binexpr->getRight());
				EmitCast(typeMatchResult, binexpr->getDataType());

				auto ident = static_cast<AstIdent *>(binexpr->getLeft());
				auto name = GetScopedName(ident->getIdent(), ident->getScopeDepth());
				Emit(op_stvar, kimlHashName(name.c_str()));
				Emit(op_ldvar, kimlHashName(name.c_str()));
			}
			else
			{
				this->Emit(binexpr->getLeft());
				this->Emit(binexpr->getRight());

				switch (binexpr->getOperator())
				{
					case BINOP_EQU:
						Emit(op_equ);
						break;
					case BINOP_NEQ:
						Emit(op_neq);
						break;
					case BINOP_LES:
						Emit(op_lt);
						break;
					case BINOP_LEQ:
						Emit(op_lte);
						break;
					case BINOP_GRT:
						Emit(op_gt);
						break;
					case BINOP_GEQ:
						Emit(op_gte);
						break;
					case BINOP_ADD:
						Emit(op_add);
						break;
					case BINOP_SUB:
						Emit(op_sub);
						break;
					case BINOP_MUL:
						Emit(op_mul);
						break;
					case BINOP_DIV:
						Emit(op_div);
						break;
					case BINOP_MOD:
						Emit(op_mod);
						break;
					case BINOP_AND:
						Emit(op_and);
						break;
					case BINOP_OR:
						Emit(op_or);
						break;
					case BINOP_XOR:
						Emit(op_xor);
						break;
				}
			}
		}
		break;

		case EXPR_UN:
		{
			auto unexpr = static_cast<AstUnExpr *>(expression);
			this->Emit(unexpr->getExpression());
			switch (unexpr->getOperator())
			{
				case UNOP_NEG:
					Emit(op_neg);
					break;
				case UNOP_NOT:
					Emit(op_not);
					break;
			}
		}
		break;

		case EXPR_FUNC:
		{
			auto exprfunc = static_cast<AstExprFunc *>(expression);
			const FunctionInfo *fi = nullptr;

			KIMLUINT fidx;
			const FunctionInfo *builtinFI = FunctionTable::GetBuiltinFunctionInfo(exprfunc->getName(), fidx);
			if (builtinFI)
				fi = builtinFI;
			else
				this->functionTable->GetFunction(exprfunc->getName(), fi);

			auto args = exprfunc->getArgs()->getExpressions();
			int idx = 0;
			for (auto it = args.begin(); it != args.end(); ++it, ++idx)
			{
				AstExpression *arg = *it;
				Emit(arg);
				EmitCast(TypeMatchTable[fi->params[idx].first][arg->getDataType()], fi->params[idx].first);

				if (!builtinFI)
					Emit(op_push);
			}

			if (builtinFI)
			{
				Emit(op_func, fidx);
			}
			else
			{
				Emit(op_fcall, kimlHashName(fi->name));
				Emit(op_trd0);
			}
		}
		break;

		case EXPR_CAST:
		{
			auto exprcast = static_cast<AstCast *>(expression);
			this->Emit(exprcast->getValue());
			switch (exprcast->getCastType())
			{
				case KIML_BOOL:
					Emit(op_cvb);
					break;
				case KIML_INT:
					Emit(op_cvin);
					break;
				case KIML_REAL:
					Emit(op_cvrn);
					break;
				case KIML_STRING:
					Emit(op_cvs);
					break;
				case KIML_OBJECT:
					Emit(op_cvo);
					break;
			}
		}
		break;
	}
	return true;
}

void Compiler::EmitCast(int typeMatchResult, KIMLTYPES toType)
{
	if (typeMatchResult != K_TYPE_CAST)
		return;

	switch (toType)
	{
		case KIML_BOOL:
			Emit(op_cvb);
			break;
		case KIML_INT:
			Emit(op_cvi);
			break;
		case KIML_REAL:
			Emit(op_cvr);
			break;
		case KIML_STRING:
			Emit(op_cvs);
			break;
		case KIML_OBJECT:
			Emit(op_cvo);
			break;
	}
}

void Compiler::Emit(OpCodes opcode)
{
	kimlEmit(compiler, opcode);
}

void Compiler::Emit(OpCodes opcode, KIMLINT value)
{
	kimlEmitInt(compiler, opcode, value);
}

void Compiler::Emit(OpCodes opcode, KIMLUINT value)
{
	kimlEmitUInt(compiler, opcode, value);
}

void Compiler::Emit(OpCodes opcode, KIMLFLOAT value)
{
	kimlEmitFloat(compiler, opcode, value);
}

void Compiler::Emit(OpCodes opcode, KIMLCSTRING value)
{
	kimlEmitString(compiler, opcode, value);
}

void Compiler::AddLabel(const std::string &label)
{
	kimlAddLabel(compiler, label.c_str());
}

void Compiler::MarkLabel(const std::string &label)
{
	kimlMarkLabel(compiler, label.c_str());
}

void Compiler::EmitJump(OpCodes opcode, const std::string &label)
{
	kimlEmitJump(compiler, opcode, label.c_str());
}

bool Compiler::PerformTypeCheck(AstExpression *expression)
{
	KIMLUINT line = (KIMLUINT)expression->getLocation().first_line;
	SIMPLCOMPILEERRORCODES err;

	switch (expression->getType())
	{
		case EXPR_NONE:
			return true;

		case EXPR_IDENT:
		{
			auto exprident = static_cast<AstIdent *>(expression);
			KIMLTYPES vartype;

			Object obj;
			if (this->constTable->GetConst(exprident->getIdent(), obj))
			{
				vartype = obj.getDataType();
			}
			else
			{
				int depth;
				err = this->currentScope->GetSymbol(exprident->getIdent(), vartype, depth);
				if (err)
					raiseCompileError(err, line);

				exprident->setScopeDepth(depth);
			}

			expression->setDataType(vartype);
		}
		return true;

		case EXPR_TRUE:
		case EXPR_FALSE:
		case EXPR_NULL:
		case EXPR_INT:
		case EXPR_REAL:
		case EXPR_STRING:
			return true;

		case EXPR_BIN:
		{
			auto exprbin = static_cast<AstBinExpr *>(expression);
			if (!this->PerformTypeCheck(exprbin->getLeft()))
				return false;
			if (!this->PerformTypeCheck(exprbin->getRight()))
				return false;

			switch (exprbin->getOperator())
			{
				case BINOP_EQU:
				case BINOP_NEQ:
				{
					expression->setDataType(KIML_BOOL);
					return true;
				}
				case BINOP_LES:
				case BINOP_LEQ:
				case BINOP_GRT:
				case BINOP_GEQ:
				{
					KIMLTYPES t = HigherType(exprbin->getLeft()->getDataType(), exprbin->getRight()->getDataType());
					if (!IsValidArithmetic(t))
						raiseCompileError(SCE_TYPE_MISMATCHED, line);

					expression->setDataType(KIML_BOOL);
					return true;
				}
				case BINOP_ADD:
				{
					KIMLTYPES t = HigherType(exprbin->getLeft()->getDataType(), exprbin->getRight()->getDataType());
					if (t == KIML_STRING)
					{
						expression->setDataType(KIML_STRING);
					}
					else
					{
						if (!IsValidArithmetic(t))
							raiseCompileError(SCE_TYPE_MISMATCHED, line);

						expression->setDataType(t);
					}
					return true;
				}
				case BINOP_SUB:
				case BINOP_MUL:
				case BINOP_DIV:
				case BINOP_MOD:
				{
					KIMLTYPES t = HigherType(exprbin->getLeft()->getDataType(), exprbin->getRight()->getDataType());
					if (!IsValidArithmetic(t))
						raiseCompileError(SCE_TYPE_MISMATCHED, line);

					expression->setDataType(t);
					return true;
				}
				case BINOP_AND:
				case BINOP_OR:
				case BINOP_XOR:
				{
					expression->setDataType(KIML_BOOL);
					return true;
				}
				case BINOP_ASN:
				{
					if (exprbin->getLeft()->getType() != EXPR_IDENT)
						raiseCompileError(SCE_ASSIGN_WRONG_LHS, line);

					int typeMatchResult = TypeMatchTable[exprbin->getLeft()->getDataType()][exprbin->getRight()->getDataType()];
					if (typeMatchResult == K_TYPE_MISMATCHED)
						raiseCompileError(SCE_TYPE_MISMATCHED, line);

					expression->setDataType(exprbin->getLeft()->getDataType());
					return true;
				}
			}
		}
		return true;

		case EXPR_UN:
		{
			auto exprun = static_cast<AstUnExpr *>(expression);
			if (!this->PerformTypeCheck(exprun->getExpression()))
				return false;

			switch (exprun->getOperator())
			{
				case UNOP_NEG:
					if (!IsValidArithmetic(exprun->getExpression()->getDataType()))
						raiseCompileError(SCE_TYPE_MISMATCHED, line);

					expression->setDataType(exprun->getExpression()->getDataType());
					return true;

				case UNOP_NOT:
					expression->setDataType(KIML_BOOL);
					return true;
			}
		}
		return true;

		case EXPR_FUNC:
		{
			auto exprfunc = static_cast<AstExprFunc *>(expression);
			auto args = exprfunc->getArgs()->getExpressions();
			const FunctionInfo *fi = nullptr;

			KIMLUINT fidx;
			const FunctionInfo *builtinFI = FunctionTable::GetBuiltinFunctionInfo(exprfunc->getName(), fidx);
			if (builtinFI)
			{
				fi = builtinFI;
			}
			else
			{
				err = this->functionTable->GetFunction(exprfunc->getName(), fi);
				if (err)
					raiseCompileError(err, line);
			}

			if (fi->params.size() != args.size())
				raiseCompileError(SCE_INCONSISTENT_ARG_COUNT, line);

			bool result = true;
			int idx = 0;
			for (auto it = args.begin(); it != args.end(); ++it, ++idx)
			{
				AstExpression *arg = *it;
				if (!this->PerformTypeCheck(arg))
				{
					result = false;
					continue;
				}

				if (TypeMatchTable[fi->params[idx].first][arg->getDataType()] == K_TYPE_MISMATCHED)
				{
					result = false;
					raiseCompileErrorNoReturn(SCE_TYPE_MISMATCHED, line);
				}
			}

			expression->setDataType(fi->returnType);
			return result;
		}

		case EXPR_CAST:
		{
			auto exprcast = static_cast<AstCast *>(expression);
			if (!this->PerformTypeCheck(exprcast->getValue()))
				return false;
		}
		return true;

		default:
			return true;
	}
}

bool Compiler::FoldExpression(AstExpression *expression)
{
	if (expression->getConstValue())
		return true;

	switch (expression->getType())
	{
		case EXPR_TRUE:
			expression->setConstValue(new Object(true));
			return true;

		case EXPR_FALSE:
			expression->setConstValue(new Object(false));
			return true;

		case EXPR_NULL:
			expression->setConstValue(new Object((KIMLOBJECT)nullptr));
			return true;

		case EXPR_INT:
			expression->setConstValue(new Object(static_cast<AstConstInt *>(expression)->getValue()));
			return true;

		case EXPR_REAL:
			expression->setConstValue(new Object(static_cast<AstConstReal *>(expression)->getValue()));
			return true;

		case EXPR_STRING:
			expression->setConstValue(new Object(static_cast<AstConstString *>(expression)->getValue()));
			return true;

		case EXPR_IDENT:
		{
			auto exprident = static_cast<AstIdent *>(expression);
			Object obj;
			if (this->constTable->GetConst(exprident->getIdent(), obj))
			{
				expression->setConstValue(new Object(std::move(obj)));
				return true;
			}
			else
			{
				return false;
			}
		}

		case EXPR_BIN:
		{
			auto binexpr = static_cast<AstBinExpr *>(expression);
			auto left = binexpr->getLeft();
			auto right = binexpr->getRight();

			if (!this->FoldExpression(left) || !this->FoldExpression(right))
				return false;

			switch (binexpr->getOperator())
			{
				case BINOP_EQU:
					expression->setConstValue(new Object(*left->getConstValue() == *right->getConstValue()));
					return true;
				case BINOP_NEQ:
					expression->setConstValue(new Object(*left->getConstValue() != *right->getConstValue()));
					return true;
				case BINOP_LES:
					expression->setConstValue(new Object(*left->getConstValue() < *right->getConstValue()));
					return true;
				case BINOP_LEQ:
					expression->setConstValue(new Object(*left->getConstValue() <= *right->getConstValue()));
					return true;
				case BINOP_GRT:
					expression->setConstValue(new Object(*left->getConstValue() > *right->getConstValue()));
					return true;
				case BINOP_GEQ:
					expression->setConstValue(new Object(*left->getConstValue() >= *right->getConstValue()));
					return true;
				case BINOP_ADD:
					expression->setConstValue(new Object(*left->getConstValue() + *right->getConstValue()));
					return true;
				case BINOP_SUB:
					expression->setConstValue(new Object(*left->getConstValue() - *right->getConstValue()));
					return true;
				case BINOP_MUL:
					expression->setConstValue(new Object(*left->getConstValue() * *right->getConstValue()));
					return true;
				case BINOP_DIV:
					expression->setConstValue(new Object(*left->getConstValue() / *right->getConstValue()));
					return true;
				case BINOP_MOD:
					expression->setConstValue(new Object(*left->getConstValue() % *right->getConstValue()));
					return true;
				case BINOP_AND:
					expression->setConstValue(new Object(*left->getConstValue() && *right->getConstValue()));
					return true;
				case BINOP_OR:
					expression->setConstValue(new Object(*left->getConstValue() || *right->getConstValue()));
					return true;
				case BINOP_XOR:
					expression->setConstValue(new Object(*left->getConstValue() ^ *right->getConstValue()));
					return true;
				default:
					return false;
			}
		}

		case EXPR_UN:
		{
			auto unexpr = static_cast<AstUnExpr *>(expression);
			auto expr = unexpr->getExpression();

			if (!this->FoldExpression(expr))
				return false;

			switch (unexpr->getOperator())
			{
				case UNOP_NOT:
					expression->setConstValue(new Object(!*expr->getConstValue()));
					return true;
				case UNOP_NEG:
					expression->setConstValue(new Object(-*expr->getConstValue()));
					return true;
				default:
					return false;
			}
		}

		case EXPR_CAST:
		{
			auto exprcast = static_cast<AstCast *>(expression);
			auto expr = exprcast->getValue();

			if (!this->FoldExpression(expr))
				return false;

			switch (exprcast->getDataType())
			{
				case KIML_BOOL:
					expression->setConstValue(new Object(expr->getConstValue()->getBool() == TRUE));
					return true;
				case KIML_INT:
					expression->setConstValue(new Object(expr->getConstValue()->getInt()));
					return true;
				case KIML_REAL:
					expression->setConstValue(new Object(expr->getConstValue()->getFloat()));
					return true;
				case KIML_STRING:
				{
					KIMLCSTRING s = expr->getConstValue()->getString();
					expression->setConstValue(new Object(s));
					delete[]s;
					return true;
				}
			}
		}

		default:
			return false;
	}
}

void Compiler::EnterScope(void)
{
	auto scope = new Scope(currentScope);
	currentScope = scope;
}

void Compiler::LeaveScope(void)
{
	auto scope = currentScope;
	currentScope = scope->GetParent();

	auto symbols = scope->GetAllSymbols();
	for (auto it = symbols.begin(), itEnd = symbols.end(); it != itEnd; ++it)
	{
		Emit(op_free, kimlHashName(GetScopedName(it->first.c_str()).c_str()));
	}

	delete scope;
}

std::string Compiler::GetScopedName(const char *name)
{
	std::ostringstream oss;
	oss << "%" << currentScope->GetDepth() << "%" << name;
	return oss.str();
}

std::string Compiler::GetScopedName(const char *name, int depth)
{
	std::ostringstream oss;
	oss << "%" << depth << "%" << name;
	return oss.str();
}

std::string Compiler::AllocLabel(void)
{
	int labelOrdinal = currentScope->IncrementLabelCounter();

	std::ostringstream oss;
	oss << ":" << currentScope->GetDepth() << "^" << currentScope->GetOrdinal() << ":L" << labelOrdinal;
	return oss.str();
}


text:
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Kanapa.Primitives
{
  public interface ICouchClient
  {
    Task<IEnumerable<string>> GetDatabaseNames();
    Task<CouchDatabaseMetadata> GetDatabaseMetadata(string db);
    Task<IEnumerable<CouchDocumentMetadata>> GetAllDocuments(string db, string fromKey = null, string toKey = null);
    Task<CouchEntityInfo> CreateDesign(string db, string name, IEnumerable<CouchViewDefinition> views);
    Task<CouchEntityInfo> DeleteDesign(string db, string name, string etag);
    Task<CouchDesignDocument> GetDesign(string db, string name);
    Task<CouchEntityInfo> PutDesign(string db, CouchDesignDocument couchDesign);
    Task<CouchDesignDocument> CreateView(string db, string designName, CouchViewDefinition couchView);
    Task<CouchEntityInfo> DeleteView(string db, string designName, string viewName);
    Task<CouchEntityInfo> PutView(string db, string designName, CouchViewDefinition couchView);
    Task<CouchEntityInfo> Put<T>(string db, string documentId, T item);
    Task<CouchEntityInfo> CreateDatabase(string db);
    Task<CouchEntityInfo> DeleteDatabase(string db);
    Task<CouchView<T>> CreateAndQueryTemporaryView<T>(string db, CouchMapReduce couchMapReduce, string fromKey = null, string toKey = null);
    Task<CouchView<T>> QueryView<T>(string db, string designName, string viewName, string fromKey = null, string toKey = null);
    Task<CouchEntityInfo> Create<T>(string db, T content);
    Task<T> Get<T>(string db, string documentId);
    Task<CouchEntityInfo> Delete(string db, string docid, string etag);
  }
}


text:
package com.anttoolkit.hadoop.tasks.mapred.util;

import org.apache.tools.ant.*;
import org.apache.hadoop.fs.*;
import org.apache.hadoop.mapreduce.*;
import org.apache.hadoop.mapreduce.lib.input.*;

import com.anttoolkit.general.common.*;

public class InputPath
{
	private Class<? extends InputFormat> formatClass;
	private Class<? extends Mapper> mapperClass;
	private String path;

	public void setFormatClass(String clazz)
	{
		try
		{
			Object obj = ReflectionHelper.forName(clazz);
			this.formatClass = (Class<? extends InputFormat>)obj;
		}
		catch (ClassNotFoundException e)
		{
			throw new BuildException("Failed to find input format class '" + clazz + "'", e);
		}
	}

	public void setMapperClass(String clazz)
	{
		try
		{
			Object obj = ReflectionHelper.forName(clazz);
			this.mapperClass = (Class<? extends Mapper>)obj;
		}
		catch (ClassNotFoundException e)
		{
			throw new BuildException("Failed to find mapper class '" + clazz + "'", e);
		}
	}

	public void setPath(String path)
	{
		this.path = path;
	}

	public void addText(String path)
	{
		this.setPath(path.trim());
	}

	public void addInputPath(Job job)
	{
		if (mapperClass != null)
		{
			MultipleInputs.addInputPath(job, new Path(path), formatClass, mapperClass);
		}
		else
		{
			MultipleInputs.addInputPath(job, new Path(path), formatClass);
		}
	}

	private void validate()
	{
		if (path == null || path.trim().isEmpty())
		{
			throw new BuildException("Path should be specified for MapReduce job input");
		}

		if (formatClass == null)
		{
			throw new BuildException("Format class should be specified for MapReduce multiple job input");
		}
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="author" content="Site Team">
    <title>Blog 1</title>
    <link rel="stylesheet" href="/styles/styles.css">

Foobar baz


text:
//
//  BDGScreenshot.h
//
//  Created by Bob de Graaf on 31-05-12.
//  Copyright (c) 2014 GraafICT. All rights reserved.
//

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

typedef NS_ENUM(NSInteger, ScreenshotSide) {
    kScreenshotSideTop,
    kScreenshotSideBottom,
    kScreenshotSideLeft,
    kScreenshotSideRight
};

@interface BDGScreenshot : NSObject

/* Take screenshot of all windows (thus including keyboard) */
+(UIImage *)screenshotFromAllWindows;

/* Take screenshot of different types */
+(UIImage *)screenshotFromView:(UIView *)view;
+(UIImage *)screenshotFromView:(UIView *)view side:(ScreenshotSide)screenshotSide;
+(UIImage *)screenshotFromView:(UIView *)view renderInContext:(BOOL)renderInContext;
+(UIImage *)screenshotFromView:(UIView *)view afterScreenUpdates:(BOOL)afterScreenUpdates;
+(UIImage *)screenshotFromView:(UIView *)view renderInContext:(BOOL)renderInContext afterScreenUpdates:(BOOL)afterScreenUpdates;

/* Take screenshot and get halfs of the screenshot back in a NSArray */
+(NSArray *)screenshotVerticalsFromView:(UIView *)view;
+(NSArray *)screenshotHorizontalsFromView:(UIView *)view;

/* Simply divide the given image into halfs */
+(NSArray *)verticalHalfsFromImage:(UIImage *)image;
+(NSArray *)horizontalHalfsFromImage:(UIImage *)image;

@end


text:
package java.io;

public class StampInputStream extends java.io.InputStream {

	public int read() throws java.io.IOException {
		return 0;
	}
}


text:
/* $Id$ */

package org.apache.fop.fo;

import java.util.NoSuchElementException;

/**
 * Class providing an (FO flavored) char iterator for a string.
 */
public class StringCharIterator extends CharIterator {

    private int index;
    private String str;

    /**
     * Constructor
     * @param c the character that this iterator should iterate.
     */
    public StringCharIterator(String s) {
        this.index = -1;
        this.str = s;
    }

    /**
     * @return true if there is another element in the collection over which to
     * iterate (since this iterator only handles one character, this will return
     * false if it is past that character).
     */
    public boolean hasNext() {
        return (index + 1) < str.length();
    }

    /**
     * @return the next character, if there is one (since there is only one
     * character over which to iterate, it must be the first character).
     * @throws NoSuchElementException if past the first character
     */
    public char nextChar() throws NoSuchElementException {
        if ((index + 1) < str.length()) {
            return str.charAt(++index);
        } else {
            throw new NoSuchElementException();
        }
    }

}


text:
{{<unbranded}}

{{$pageTitle}}
	Create a new fleet operator
{{/pageTitle}}

{{$content}}
{{#vars}}
	<input type="hidden" name="username" value="{{username}}">
{{/vars}}
{{>includes/fleets_head}}

Create a new fleet operator

		<form action="/basic-flow2" method="get" class="form">
			<input type="hidden" name="nextlink" value="new-user-summary">

				<input type="hidden" name="count" value="1" />

		            Fleet number

		                <form class="input-append">

		                    	<input autocomplete="off" class="form-control input" id="field1" name="prof1" type="text" placeholder="333567123789001" data-items="8"/>
		                    	<button id="b1" class="btn add-more dummyLink" type="button">Add another fleet number</button>

		                </form>

					Name
					<input class="form-control" id="fleetname" name="fleetname" type="text" value="John Smith" autocomplete="on">

					Email address
					<input class="form-control" id="fleetemail" name="fleetemail" type="text" value="john.smith@aol.com" autocomplete="on">

					Phone
					<input class="form-control" id="fleetphone" name="fleetphone" type="text" value="07890654987" autocomplete="on">

					Business name
					<input class="form-control" id="fleetbusname" name="fleetbusname" type="text" value="Smiths Buns" autocomplete="on">

					Address
					<input class="form-control" id="address1" name="address1" type="text" value="5 Richardson Street" autocomplete="on">

					<input class="form-control" id="address2" name="address2" type="text" value="Town Centre" autocomplete="on">

					<input class="form-control" id="address3" name="address3" type="text" value="Swansea" autocomplete="on">

					Post town
					<input class="form-control" id="posttown" name="posttown" type="text" value="Swansea" autocomplete="on">

					Postcode
					<input class="form-control" id="postcode" name="postcode" type="text" value="SA1 3JF" autocomplete="on" style="text-transform: uppercase;">

				<input class="button" type="submit" value="Continue">

			Back
		</form>

{{/content}}

{{/unbranded}}


text:
from __future__ import unicode_literals

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('events', '0006_event_twitter_hashtag'),
    ]

    operations = [
        migrations.AddField(
            model_name='event',
            name='decsription',
            field=models.TextField(blank=True, null=True),
        ),
    ]


text:
using base::win::RegKey;

class TriggeredProfileResetterTest : public testing::Test {
 protected:
  void SetUp() override {
    override_manager_.OverrideRegistry(HKEY_CURRENT_USER);

    // Activate the triggered reset field trial for these tests.
    field_trial_list_.reset(
        new base::FieldTrialList(new metrics::SHA1EntropyProvider("foo")));
    base::FieldTrial* trial = base::FieldTrialList::CreateFieldTrial(
        "TriggeredResetFieldTrial", "On");
    trial->group();
  }

  content::TestBrowserThreadBundle thread_bundle_;
  TestingProfile profile_;

  void SetRegTimestampAndToolName(const base::string16& toolname,
                                  FILETIME* file_time) {
    RegKey trigger_key(HKEY_CURRENT_USER, kTriggeredResetRegistryPath,
                       KEY_ALL_ACCESS);
    ASSERT_TRUE(trigger_key.Valid());
    FILETIME ft;
    ::GetSystemTimeAsFileTime(&ft);
    ASSERT_TRUE(trigger_key.WriteValue(kTriggeredResetTimestamp, &ft,
                                       sizeof(ft), REG_QWORD) == ERROR_SUCCESS);
    ASSERT_TRUE(trigger_key.WriteValue(kTriggeredResetToolName,
                                       toolname.c_str()) == ERROR_SUCCESS);
    if (file_time)
      *file_time = ft;
  }

 private:
  registry_util::RegistryOverrideManager override_manager_;
  scoped_ptr<base::FieldTrialList> field_trial_list_;
};

TEST_F(TriggeredProfileResetterTest, HasResetTriggerAndClear) {
  SetRegTimestampAndToolName(base::string16(), nullptr);
  TriggeredProfileResetter triggered_profile_resetter(&profile_);
  triggered_profile_resetter.Activate();
  EXPECT_TRUE(triggered_profile_resetter.HasResetTrigger());
  triggered_profile_resetter.ClearResetTrigger();
  EXPECT_FALSE(triggered_profile_resetter.HasResetTrigger());
}

TEST_F(TriggeredProfileResetterTest, HasDuplicateResetTrigger) {
  FILETIME ft = {};
  SetRegTimestampAndToolName(base::string16(), &ft);
  profile_.GetPrefs()->SetInt64(prefs::kLastProfileResetTimestamp,
                                bit_cast<int64_t, FILETIME>(ft));

  TriggeredProfileResetter triggered_profile_resetter(&profile_);
  triggered_profile_resetter.Activate();
  EXPECT_FALSE(triggered_profile_resetter.HasResetTrigger());
}

TEST_F(TriggeredProfileResetterTest, HasToolName) {
  const wchar_t kToolName[] = L"ToolyMcTool";
  SetRegTimestampAndToolName(kToolName, nullptr);
  TriggeredProfileResetter triggered_profile_resetter(&profile_);
  triggered_profile_resetter.Activate();
  EXPECT_TRUE(triggered_profile_resetter.HasResetTrigger());
  EXPECT_STREQ(kToolName,
               triggered_profile_resetter.GetResetToolName().c_str());
}

TEST_F(TriggeredProfileResetterTest, HasLongToolName) {
  const wchar_t kLongToolName[] =
      L"ToolMcToolToolMcToolToolMcToolToolMcToolToolMcToolToolMcToolToolMcTool"
      L"ToolMcToolToolMcToolToolMcToolThisIsTheToolThatNeverEndsYesItGoesOnAnd"
      L"OnMyFriend";
  const wchar_t kExpectedToolName[] =
      L"ToolMcToolToolMcToolToolMcToolToolMcToolToolMcToolToolMcToolToolMcTool"
      L"ToolMcToolToolMcToolToolMcTool";
  SetRegTimestampAndToolName(kLongToolName, nullptr);
  TriggeredProfileResetter triggered_profile_resetter(&profile_);
  triggered_profile_resetter.Activate();
  EXPECT_TRUE(triggered_profile_resetter.HasResetTrigger());
  EXPECT_STREQ(kExpectedToolName,
               triggered_profile_resetter.GetResetToolName().c_str());
}


text:
copyright:
 years: 2015, 2017

---

{:new_window: target="_blank"}
{:shortdesc: .shortdesc}
{:screen:.screen}
{:codeblock:.codeblock}

#Abilitazione delle notifiche di push avanzate
Ultimo aggiornamento: 28 febbraio 2017
{: .last-updated}

Configura un badge iOS, audio, payload JSON aggiuntivo, notifiche operative e notifiche messe in pausa.

## Configurazione di audio e payload e badge iOS
{: #badge-sound-payload}

Configura un badge, l'audio e del payload JSON aggiuntivo iOS.

1. Nel dashboard {{site.data.keyword.mobilepushshort}}, vai alla scheda **Notifications**.
2. Vai alla sezione **Optional Fields** per configurare le funzioni di {{site.data.keyword.mobilepushshort}}.
	- **Sound File** - immetti una stringa per puntare al file audio nella tua applicazione mobile. Nel payload, specifica
                            il nome stringa del file audio da utilizzare.
	- **iOS Badge** - per i dispositivi iOS, il numero da visualizzare come badge dell'icona
                            applicazione. Se questa proprietà
                            non è presente, il badge non viene modificato. Per rimuovere il badge, imposta
                            il valore di questa proprietà su 0.

### Android
{: #badge-sound-payload_android}

Aggiungi il file audio nella directory `res/raw` della tua applicazione android. Mentre invii le notifiche aggiungi il nome del file audio nel campo audio di {{site.data.keyword.mobilepushshort}}.

```
"settings": {
     "gcm" : {
     "sound":"tt.wav",
	  }
 }
```
    {: codeblock}

### iOS
{: #badge-sound-payload_ios}

```
"settings": {
     "apns" : {
      "badge": 10,
	      "sound": "tt.wav",
	  }
}
```
	{: codeblock}

**Additional Payload** - This payload can be any key-value pair and must be a JSON object that you want to send with th**Additional Payload** - questo payload può essere qualsiasi coppia chiave-valore e deve essere un oggetto JSON che vuoi inviare con {{site.data.keyword.mobilepushshort}}.

```
{"chiave":"valore", "chiave2":"valore2"}
```
	{: codeblock}

## Messa in pausa delle notifiche Android
{: #hold-notifications-android}

Quando la tua applicazione va in background, probabilmente vuoi che {{site.data.keyword.mobilepushshort}} metta in pausa le notifiche inviate alla tua applicazione. Per mettere in pausa le notifiche, richiama il metodo hold() nel metodo onPause() dell'attività che sta gestendo {{site.data.keyword.mobilepushshort}}.

```
@Override
protected void onPause() {
    super.onPause();
    if (push != null) {
        push.hold();
    }
}
```
	{: codeblock}


text:
var $$ = React.createElement;
var EntityMixin = require("./entity_mixin");

// Toponym view
// ----------------

var Toponym = React.createClass({
  displayName: "Toponym",
  mixins: [EntityMixin],
  handleEdit: function(e) {
    e.stopPropagation();
  },
  render: function() {
    var className = ["entity toponym"];
    if (this.props.active) className.push("active");

    return $$("div", {className: className.join(" "), onClick: this.handleToggle},
      $$("div", {className: "type"}, "Toponym"),
      $$("div", {className: "name"}, this.props.name),
      $$("div", {className: "synonyms"}, "Known as: " + this.props.synonyms.join(', ')),
      $$("div", {className: "country"}, "Country: " + this.props.country),
      $$("div", {
        className: "description",
        dangerouslySetInnerHTML: {__html: this.props.description }
      }),
      $$("a", {className: "edit", target: "_blank", href: '../toponyms/' + this.props.id, onClick: this.handleEdit},
        $$("i", {className: "fa fa-pencil-square-o"})
      )
    );
  }
});

module.exports = Toponym;


text:
import * as React from 'react';
import { shallow } from 'enzyme';
import TargetLabels from './TargetLabels';
import { Tooltip, Badge } from 'reactstrap';
import toJson from 'enzyme-to-json';

describe('targetLabels', () => {
  const defaultProps = {
    discoveredLabels: {
      __address__: 'localhost:9100',
      __metrics_path__: '/metrics',
      __scheme__: 'http',
      job: 'node_exporter',
    },
    labels: {
      instance: 'localhost:9100',
      job: 'node_exporter',
      foo: 'bar',
    },
    idx: 1,
    scrapePool: 'cortex/node-exporter_group/0',
  };
  const targetLabels = shallow(<TargetLabels {...defaultProps} />);

  it('renders a div of series labels', () => {
    const div = targetLabels.find('div').filterWhere((elem) => elem.hasClass('series-labels-container'));
    expect(div).toHaveLength(1);
    expect(div.prop('id')).toEqual('series-labels-cortex/node-exporter_group/0-1');
  });

  it('wraps each label in a label badge', () => {
    const l: { [key: string]: string } = defaultProps.labels;
    Object.keys(l).forEach((labelName: string): void => {
      const badge = targetLabels
        .find(Badge)
        .filterWhere((badge) => badge.children().text() === `${labelName}="${l[labelName]}"`);
      expect(badge).toHaveLength(1);
    });
    expect(targetLabels.find(Badge)).toHaveLength(3);
  });

  it('renders a tooltip for discovered labels', () => {
    const tooltip = targetLabels.find(Tooltip);
    expect(tooltip).toHaveLength(1);
    expect(tooltip.prop('isOpen')).toBe(false);
    expect(tooltip.prop('target')).toEqual('series-labels-cortex\\/node-exporter_group\\/0-1');
  });

  it('renders discovered labels', () => {
    expect(toJson(targetLabels)).toMatchSnapshot();
  });
});


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

<link   rel="stylesheet"
        href="../../../css/style.min.0a7442460ca45a8d1ffa9d4f0a0163976899fc7820ce2bb76f693ba0527afb57.css"
        integrity="sha256-CnRCRgykWo0f+p1PCgFjl2iZ/Hggziu3b2k7oFJ6+1c="
        type="text/css"
        media="screen">

<link   rel="stylesheet"
        href="../../../css/mobile.min.9d1271f82d33327493aaf7c1818ceac101a822559d694bd14a222d686e28c391.css"
        integrity="sha256-nRJx+C0zMnSTqvfBgYzqwQGoIlWdaUvRSiItaG4ow5E="
        type="text/css"
        media="handheld, only screen and (max-device-width: 960px)">

    <link href="https://unwiredcouch.com/atom.xml" type="application/atom+xml" rel="alternate" title="unwiredcouch.com: All Posts" />

    <title>Testing couchapps with cucumber on unwiredcouch.com</title>

Writing

Reading

Setup

About

Drawing

Mastodon

 Dec 30, 2010

  Testing couchapps with cucumber

Couchapps overview

[Couchapps][2] are a great way to build web apps hosted directly on a
CouchDB. This is due to the integrated HTTP server, so if you can
fit your application into the constraints of HTML/CSS/JavaScript, you
get the storage (almost) for free. The heart of couchapps is [evently][3],
a JavaScript framework simplifying the development of event based web
applications. The development process is accompanied by the
[couchapp python script][4], which maps a certain directory structure
to the evently application layout. This makes it easy to develop the source
code, which is normally stored as attachments in the design document, in your
favourite editor.  However this difference in how the application is developed
and how it is deployed, makes it a bit more difficult to automatically test the
application.

Enter cucumber

Fortunately the ruby world has provided us with a great tool for
acceptance testing web applications: [Cucumber][5]. Cucumber is a
testing framework, which encourages [BDD][6] style development. It
features different drivers for (headless) browser testing and supports
an easy, natural language like, syntax for creating tests (scenarios as they
are called in BDD world). If you don’t use it already, give it a try, it is
really great. However to fully embrace an automated testing approach we need
some helpers to do additional work, for example create and destroy the
testing environments.

We have the technology, we can make him stronger

The first problem was the CouchDB native authentication db used by couchapps to
profit from the already existing user management. Fortunately there is [a
way][7] to change the db used for authentication to an arbitrary one. The next
nice-to-have is an easy setup for choosing databases for different environments
like tests. Fortunately rails already provides a clean setup for this, which we
can copy. Now we only have to bundle a [simple CouchDB library][8] and some
helper methods and we are ready to go.  This is what [couchapp-cucumber][9] is
about. I bundled all these steps as a simple cucumber drop-in. I’m sure it can
be improved in a lot of ways.

So fork it. Hack away. And happy testing.

[1]: {{ page.url }}
[2]: http://couchapp.org
[3]: http://couchapp.org/page/evently
[4]: https://github.com/couchapp/couchapp
[5]: http://cukes.info
[6]: http://en.wikipedia.org/wiki/Behavior_Driven_Development
[7]: http://lenaherrmann.net/2010/04/29/security-in-couchdb-changing-the-authentication-db
[8]: https://gist.github.com/738128
[9]: https://github.com/mrtazz/couchapp-cucumber

Imprint


text:
/*@polyfill #container > * */
g-tabpanels > * {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  -webkit-transform: translateZ(0);
  transform: translateZ(0);
}

/*@polyfill #container > g-panels */
g-tabpanels > g-panels {
  position: absolute;
}

/*@polyfill #container > .transition */
g-tabpanels > .transition {
  -webkit-transition: all 0.218s ease-in-out;
  transition: all 0.218s ease-in-out;
}

/*@polyfill #container > .animate */
g-tabpanels > .animate {
  -webkit-animation-duration: 0.218s;
  -webkit-animation-fill-mode: both;
  animation-duration: 0.218s;
  animation-fill-mode: both;
}

/* fade */
/*@polyfill #container > .panels-ascending-from, #container > .panels-descending-from */
g-tabpanels > .panels-ascending-from, g-tabpanels > .panels-descending-from {
  -webkit-animation: 0.218s both;
  -webkit-animation-name: g-panels-fadeOut;
  animation: 0.218s both;
  animation-name: g-panels-fadeOut;
}

/*@polyfill #container > .panels-ascending-to, #container > .panels-descending-to */
g-tabpanels > .panels-ascending-to, g-tabpanels > .panels-descending-to {
  -webkit-animation: 0.218s both;
  -webkit-animation-name: g-panels-fadeIn;
  animation: 0.218s both;
  animation-name: g-panels-fadeIn;
}


text:
DEFINE_EXT_INIT_COMPRESSED(UUID, //name of the extension
    script_bytes, // REBOL script for the extension in the source form
    {
        // init all modules in this extension
        int init = CALL_MODULE_INIT(UUID);
        if (init < 0) return init;
    }
)

DEFINE_EXT_QUIT(UUID,
{
    return CALL_MODULE_QUIT(UUID);
}
)


text:
package org.rabix.engine.store.model;

import java.util.UUID;

public class JobStatsRecord {

  private UUID rootId;
  private int completed;
  private int running;
  private int total;

  public JobStatsRecord(final UUID rootId, int completed, int running, int total) {
    this.rootId = rootId;
    this.completed = completed;
    this.running = running;
    this.total = total;
  }

  public UUID getRootId() {
    return rootId;
  }

  public void setRootId(UUID rootId) {
    this.rootId = rootId;
  }

  public int getCompleted() {
    return completed;
  }

  public void setCompleted(int completed) {
    this.completed = completed;
  }

  public int getRunning() {
    return running;
  }

  public int getTotal() {
    return total;
  }

  public void setTotal(int total) {
    this.total = total;
  }

  public void setRunning(int running) {
    this.running = running;
  }
  public void increaseRunning() {
    running++;
  }
  public void increaseCompleted() {
    completed++;
  }

  @Override public String toString() {
    return "JobStatsRecord{" + "rootId=" + rootId + ", completed=" + completed + ", running=" + running + ", total="
        + total + '}';
  }
}


text:
import { Emitter } from 'vs/base/common/event';
import { Disposable } from 'vs/base/common/lifecycle';
import { Schemas } from 'vs/base/common/network';
import { withNullAsUndefined } from 'vs/base/common/types';
import { localize } from 'vs/nls';
import { ILogService } from 'vs/platform/log/common/log';
import { INotificationHandle, INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification';
import { ICrossVersionSerializedTerminalState, IPtyHostController, ISerializedTerminalState } from 'vs/platform/terminal/common/terminal';
import { IWorkspaceContextService } from 'vs/platform/workspace/common/workspace';
import { IConfigurationResolverService } from 'vs/workbench/services/configurationResolver/common/configurationResolver';
import { IHistoryService } from 'vs/workbench/services/history/common/history';

export abstract class BaseTerminalBackend extends Disposable {
	private _isPtyHostUnresponsive: boolean = false;

	protected readonly _onPtyHostRestart = this._register(new Emitter<void>());
	readonly onPtyHostRestart = this._onPtyHostRestart.event;
	protected readonly _onPtyHostUnresponsive = this._register(new Emitter<void>());
	readonly onPtyHostUnresponsive = this._onPtyHostUnresponsive.event;
	protected readonly _onPtyHostResponsive = this._register(new Emitter<void>());
	readonly onPtyHostResponsive = this._onPtyHostResponsive.event;

	constructor(
		eventSource: IPtyHostController,
		protected readonly _logService: ILogService,
		notificationService: INotificationService,
		historyService: IHistoryService,
		configurationResolverService: IConfigurationResolverService,
		protected readonly _workspaceContextService: IWorkspaceContextService
	) {
		super();

		// Attach pty host listeners
		if (eventSource.onPtyHostExit) {
			this._register(eventSource.onPtyHostExit(() => {
				this._logService.error(`The terminal's pty host process exited, the connection to all terminal processes was lost`);
			}));
		}
		let unresponsiveNotification: INotificationHandle | undefined;
		if (eventSource.onPtyHostStart) {
			this._register(eventSource.onPtyHostStart(() => {
				this._logService.info(`ptyHost restarted`);
				this._onPtyHostRestart.fire();
				unresponsiveNotification?.close();
				unresponsiveNotification = undefined;
				this._isPtyHostUnresponsive = false;
			}));
		}
		if (eventSource.onPtyHostUnresponsive) {
			this._register(eventSource.onPtyHostUnresponsive(() => {
				const choices: IPromptChoice[] = [{
					label: localize('restartPtyHost', "Restart pty host"),
					run: () => eventSource.restartPtyHost!()
				}];
				unresponsiveNotification = notificationService.prompt(Severity.Error, localize('nonResponsivePtyHost', "The connection to the terminal's pty host process is unresponsive, the terminals may stop working."), choices);
				this._isPtyHostUnresponsive = true;
				this._onPtyHostUnresponsive.fire();
			}));
		}
		if (eventSource.onPtyHostResponsive) {
			this._register(eventSource.onPtyHostResponsive(() => {
				if (!this._isPtyHostUnresponsive) {
					return;
				}
				this._logService.info('The pty host became responsive again');
				unresponsiveNotification?.close();
				unresponsiveNotification = undefined;
				this._isPtyHostUnresponsive = false;
				this._onPtyHostResponsive.fire();
			}));
		}
		if (eventSource.onPtyHostRequestResolveVariables) {
			this._register(eventSource.onPtyHostRequestResolveVariables(async e => {
				// Only answer requests for this workspace
				if (e.workspaceId !== this._workspaceContextService.getWorkspace().id) {
					return;
				}
				const activeWorkspaceRootUri = historyService.getLastActiveWorkspaceRoot(Schemas.file);
				const lastActiveWorkspaceRoot = activeWorkspaceRootUri ? withNullAsUndefined(this._workspaceContextService.getWorkspaceFolder(activeWorkspaceRootUri)) : undefined;
				const resolveCalls: Promise<string>[] = e.originalText.map(t => {
					return configurationResolverService.resolveAsync(lastActiveWorkspaceRoot, t);
				});
				const result = await Promise.all(resolveCalls);
				eventSource.acceptPtyHostResolvedVariables?.(e.requestId, result);
			}));
		}
	}

	protected _deserializeTerminalState(serializedState: string | undefined): ISerializedTerminalState[] | undefined {
		if (serializedState === undefined) {
			return undefined;
		}
		const parsedUnknown = JSON.parse(serializedState);
		if (!('version' in parsedUnknown) || !('state' in parsedUnknown) || !Array.isArray(parsedUnknown.state)) {
			this._logService.warn('Could not revive serialized processes, wrong format', parsedUnknown);
			return undefined;
		}
		const parsedCrossVersion = parsedUnknown as ICrossVersionSerializedTerminalState;
		if (parsedCrossVersion.version !== 1) {
			this._logService.warn(`Could not revive serialized processes, wrong version "${parsedCrossVersion.version}"`, parsedCrossVersion);
			return undefined;
		}
		return parsedCrossVersion.state as ISerializedTerminalState[];
	}
}


text:
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE PolyKinds #-}
module T14579 where

import Data.Kind
import Data.Proxy

newtype Wat (x :: Proxy (a :: Type)) = MkWat (Maybe a)
  deriving Eq

newtype Glurp a = MkGlurp (Wat ('Proxy :: Proxy a))
  deriving Eq


text:
sdk.ralcr is a framework for building Haxe applications for Mac, iOS, Android, Flash or Javascript. It's syntax and structure is similar with the Apple frameworks, so:
* The classes are grouped into categories which are physical folders on the disk
* The classes do not require imports because they are all on the root level with very few exceptions. The name collisions with possible custom classes is avoided by few prefixes: RC for most of the classes, CA for the Animation engine, EV for Signal events, SK for skins

## Installation

sdk.ralcr is in the process of becoming a haxelib, but in the meantime you can clone this repository

	git clone git@github.com:ralcr/sdk.ralcr.git

## Getting started

Because the framework is a collection of organised root level classes it is not possible to use it from haxelib with -lib, you need to add each collection path as a classpath in your hxml. This can be done by the Run script provided. Go to the sdk root and type

	neko run

This will produce a sdk.ralcr.hxml file in the same location. Copy this file to your project and include it's name on a new line in your hxml. By doing this your project will have the classpaths to the sdk.ralcr framework.
The run script for haxelib has a new command to build a template with all the basic files in the right place. So, go into your sistem and create a folder for you project

	mkdir MyProject
	cd MyProject
	haxelib run ralcr new

Voila, open the project with your preferred editor and compile. By now you should be able to compile for flash and javascript by running compile.hxml, and for Mac, iOS and Android by running compile.nmml with nme

	haxe compile.hxml
	nme test mac
	nme test ios
	nme test android

The framework can be compiled to flash or javascript, but is also compatible with the NME library which makes possible to compile for mac, ios, android.


text:
namespace rpc {

Encoder* CreateEncoder(CodecId codec);
Decoder* CreateDecoder(CodecId codec);

// Helper methods for easy encoding/decoding when only the codec Type is known.

template <typename T>
void EncodeBy(CodecId codec, const T& in, io::MemoryStream* out) {
  switch ( codec ) {
    case kCodecIdBinary: BinaryEncoder().Encode(in,out); return;
    case kCodecIdJson: JsonEncoder().Encode(in,out); return;
  }
  LOG_FATAL << "Illegal codec id: " << codec;
}
template <typename T>
DECODE_RESULT DecodeBy(CodecId codec, io::MemoryStream& in, T* out) {
  switch ( codec ) {
    case kCodecIdBinary: return BinaryDecoder().Decode(in, out);
    case kCodecIdJson: return JsonDecoder().Decode(in, out);
  }
  LOG_FATAL << "Illegal codec id: " << codec;
  return DECODE_RESULT_ERROR;
}

}

#endif   // __NET_RPC_LIB_CODEC_RPC_CODEC_H__


text:
.org-jasig-portlet-newsreader .portlet-rss-scrollable-content { overflow: auto; height: 20em; border: 1px solid #CCCCCC; padding: 0 0.5em 0 0.5em; }
.org-jasig-portlet-newsreader .portlet-rss-scrollable-content dl { margin:0.5em; padding:0; }
.org-jasig-portlet-newsreader .portlet-rss-scrollable-content dd { margin:0; padding:0em 0em 0.5em 0em; }


text:
CWAC RichEditText: Letting Users Make Text Pretty
=================================================

Android's `EditText` widget supports formatted (a.k.a.,
"rich text") editing. It just lacks any way for the user
to supply formatting, and it does not provide much in the
way of convenience methods for a developer to, say, tie
in some sort of toolbar to allow users to format selections.

That's where `RichEditText` comes in.

`RichEditText` is a drop-in replacement for `EditText` that:

- Provides an action mode on Android 2.1+ that allows
users to format selected pieces of text
- Provides convenience methods to allow developers to
trigger formatting for selected text via other means

This widget is packaged as an Android library project, with
a `demo/` subdirectory containing a regular Android project
with a couple of activities demonstrating the use of
`RichEditText`.

Usage
-----
Add the project as a library project to your main project.
Then, simply add `com.commonsware.cwac.richedit.RichEditText`
widgets to your layout as needed:

```xml
<?xml version="1.0" encoding="utf-8"?>
<com.commonsware.cwac.richedit.RichEditText xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/editor"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:gravity="top|left"
  android:inputType="textMultiLine">

  <requestFocus/>

</com.commonsware.cwac.richedit.RichEditText>
```
At this time, there are no custom attributes used by
`RichEditText`.

On its own, by default, `RichEditText` provides one means of users
applying formatting: the standard `<Ctrl>-<B>` for bold,
`<Ctrl>-<I>` for italics, and `<Ctrl>-<U>` for underline work if there
is a selection. You can disable this by calling
`setKeyboardShortcutsEnabled(false)`.

If you want an on-screen UI for formatting, you have two choices.

First, you can call
`enableActionModes()` on the `RichEditText`. This will add a "FORMAT"
entry on the action mode that comes up when the user highlights some
prose in the editor. Tapping that will allow the user to toggle various
effects. This is easy to set up, but there are two significant limitations:

1. If you intend to run on devices prior to API Level 11, you need to be
using ActionBarSherlock, and your activity hosting the `RichEditText` needs
to inherit from one of the Sherlock-flavored activiy classes.

2. The action modes work so-so on phones at this time —
tablets work better. To get it to work on phones at all, you will need
to include `android:imeOptions="flagNoExtractUi"` as an attribute on the
`RichEditText`.

Alternatively, you can have
your own toolbar or gesture interface or
whatever to allow users to format text. In that case, here are the two key
methods to call on `RichEditText`:

- `applyEffect()` changes the current selection, applying
or removing an effect (e.g., making the selection bold). The
first parameter is the effect to apply (e.g., `RichEditText.BOLD`).
The second parameter is the new value for the effect. Many
effects take boolean values, so `applyEffect(RichEditText.BOLD, true)`
would format the current selection as bold.

- `setOnSelectionChangedListener()` is where you register a
`RichEditText.OnSelectionChangedListener` object, which will
be called with `onSelectionChanged()` whenever the user changes
the selection in the widget (i.e., highlights text or taps
to un-select the highlight). You are provided the start and
end positions of the selection (as were supplied to `onSelectionChanged()`
to `RichEditText` itself by Android), plus a list of effects
that are active on that selection. This will allow you to
update your toolbar to indicate what is and is not in use,
and so you know what to do when the user taps on one of
those toolbar buttons again.

### Supported Effects

At the time of this writing, here are the `RichEditText`
static data members for each supported effect:

- `BOLD`
- `ITALIC`
- `UNDERLINE`
- `STRIKETHROUGH`
- `SUPERSCRIPT`
- `SUBSCRIPT`
- `TYPEFACE`

There are other effects presently implemented, but they
will be revised shortly, including name and data type
changes, so don't mess with them yet.

Dependencies
------------
This project depends upon [ActionBarSherlock](http://actionbarsherlock.com).
If you check out this project, you will need to update your local configuration
to point to your own copy of ActionBarSherlock.

(as the world patiently awaits Android library projects being able to be
packaged as JARs...)

Version
-------
This is version v0.2.0 of this module, meaning it is out of its months-long
slumber and is proceeding apace.

Demo
----
In the `demo/` sub-project you will find
a sample activity that demonstrates the use of `RichEditor`.

In the `tests/` sub-project you will find a small unit test suite for
exercising some of the effects.

License
-------
The code in this project is licensed under the Apache
Software License 2.0, per the terms of the included LICENSE
file.

Questions
---------
If you have questions regarding the use of this code, please post a question
on [StackOverflow](http://stackoverflow.com/questions/ask) tagged with `commonsware` and `android`. Be sure to indicate
what CWAC module you are having issues with, and be sure to include source code
and stack traces if you are encountering crashes.

If you have encountered what is clearly a bug, or if you have a feature request,
please post an [issue](https://github.com/commonsguy/cwac-richedit/issues).
Be certain to include complete steps for reproducing the issue.

Do not ask for help via Twitter.

Also, if you plan on hacking
on the code with an eye for contributing something back,
please open an issue that we can use for discussing
implementation details. Just lobbing a pull request over
the fence may work, but it may not.

Release Notes
-------------
- v0.2.0: added keyboard shortcuts for bold/italic/underline and test suite, bug fixes
- v0.1.1: added `disableActionModes()` and fixed bug related to conditional action mode usage
- v0.1: added action mode support using ActionBarSherlock for pre-Honeycomb devices
- v0.0.3: removed `RichEditor`, replaced it with custom action modes
- v0.0.2: added `RichEditor` and made various fixes
- v0.0.1: initial release