text:
import pytest

from . import normalize_ret

pytestmark = [
    pytest.mark.windows_whitelisted,
]

def test_requisites_full_sls_prereq(state, state_tree):
    """
    Test the sls special command in requisites
    """
    full_sls_contents = """
    B:
      cmd.run:
        - name: echo B
    C:
      cmd.run:
        - name: echo C
    """
    sls_contents = """
    include:
      - fullsls
    A:
      cmd.run:
        - name: echo A
        - prereq:
          - sls: fullsls
    """
    expected_result = {
        "cmd_|-A_|-echo A_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo A" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo B" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C_|-run": {
            "__run_num__": 2,
            "comment": 'Command "echo C" run',
            "result": True,
            "changes": True,
        },
    }
    with pytest.helpers.temp_file(
        "requisite.sls", sls_contents, state_tree
    ), pytest.helpers.temp_file("fullsls.sls", full_sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_1(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # B --+
    #     |
    # C <-+ ----+
    #           |
    # A <-------+

    # runs after C
    A:
      cmd.run:
        - name: echo A third
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
          - cmd: C

    # runs before C
    B:
      cmd.run:
        - name: echo B first
        # will test C and be applied only if C changes,
        # and then will run before C
        - prereq:
          - cmd: C
    C:
      cmd.run:
        - name: echo C second

    # will fail with "The following requisites were not found"
    I:
      cmd.run:
        - name: echo I
        - prereq:
          - cmd: Z
    J:
      cmd.run:
        - name: echo J
        - prereq:
          - foobar: A
    """
    expected_result = {
        "cmd_|-A_|-echo A third_|-run": {
            "__run_num__": 2,
            "comment": 'Command "echo A third" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B first_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo B first" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C second_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo C second" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-I_|-echo I_|-run": {
            "__run_num__": 3,
            "comment": "The following requisites were not found:\n"
            + "                   prereq:\n"
            + "                       cmd: Z\n",
            "result": False,
            "changes": False,
        },
        "cmd_|-J_|-echo J_|-run": {
            "__run_num__": 4,
            "comment": "The following requisites were not found:\n"
            + "                   prereq:\n"
            + "                       foobar: A\n",
            "result": False,
            "changes": False,
        },
    }
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_2(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    # same test, but not using lists in yaml syntax
    sls_contents = """
    # B --+
    #     |
    # C <-+ ----+
    #           |
    # A <-------+

    # runs after C
    A:
      cmd.run:
        - name: echo A third
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
           cmd: C

    # runs before C
    B:
      cmd.run:
        - name: echo B first
        # will test C and be applied only if C changes,
        # and then will run before C
        - prereq:
            cmd: C
    C:
      cmd.run:
        - name: echo C second
    """
    errmsg = (
        "The prereq statement in state 'B' in SLS 'requisite' needs to be formed as a"
        " list"
    )
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret.failed
        assert ret.errors == [errmsg]

def test_requisites_prereq_simple_ordering_and_errors_3(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # B --+
    #     |
    # C <-+ ----+
    #           |
    # A <-------+

    # runs after C
    A:
      cmd.run:
        - name: echo A third
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
          - C

    # runs before C
    B:
      cmd.run:
        - name: echo B first
        # will test C and be applied only if C changes,
        # and then will run before C
        - prereq:
          - C
    C:
      cmd.run:
        - name: echo C second

    # will fail with "The following requisites were not found"
    I:
      cmd.run:
        - name: echo I
        - prereq:
          - Z
        """
    expected_result = {
        "cmd_|-A_|-echo A third_|-run": {
            "__run_num__": 2,
            "comment": 'Command "echo A third" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B first_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo B first" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C second_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo C second" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-I_|-echo I_|-run": {
            "__run_num__": 3,
            "comment": "The following requisites were not found:\n"
            + "                   prereq:\n"
            + "                       id: Z\n",
            "result": False,
            "changes": False,
        },
    }

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_4(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # Theory:
    #
    # C <--+ <--+ <-+ <-+
    #      |    |   |   |
    # A ---+    |   |   |
    #           |   |   |
    # B --------+   |   |
    #               |   |
    # D-------------+   |
    #                   |
    # E-----------------+

    # runs after C
    A:
      cmd.run:
        - name: echo A
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
          - cmd: C

    B:
      cmd.run:
        - name: echo B

    # runs before D and B
    C:
      cmd.run:
        - name: echo C
        # will test D and be applied only if D changes,
        # and then will run before D. Same for B
        - prereq:
          - cmd: B
          - cmd: D

    D:
      cmd.run:
        - name: echo D

    E:
      cmd.run:
        - name: echo E
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
          - cmd: C
    """
    expected_result = {
        "cmd_|-A_|-echo A_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo A" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B_|-run": {
            "__run_num__": 2,
            "comment": 'Command "echo B" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo C" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-D_|-echo D_|-run": {
            "__run_num__": 3,
            "comment": 'Command "echo D" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-E_|-echo E_|-run": {
            "__run_num__": 4,
            "comment": 'Command "echo E" run',
            "result": True,
            "changes": True,
        },
    }

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_5(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # A --+
    #     |
    # B <-+ ----+
    #           |
    # C <-------+

    # runs before A and/or B
    A:
      cmd.run:
        - name: echo A first
        # is running in test mode before B/C
        - prereq:
          - cmd: B
          - cmd: C

    # always has to run
    B:
      cmd.run:
        - name: echo B second

    # never has to run
    C:
      cmd.wait:
        - name: echo C third
    """
    expected_result = {
        "cmd_|-A_|-echo A first_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo A first" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B second_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo B second" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C third_|-wait": {
            "__run_num__": 2,
            "comment": "",
            "result": True,
            "changes": False,
        },
    }

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_6(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # issue #8211
    #             expected rank
    # B --+             1
    #     |
    # C <-+ ----+       2/3
    #           |
    # D ---+    |       3/2
    #      |    |
    # A <--+ <--+       4
    #
    #             resulting rank
    # D --+
    #     |
    # A <-+ <==+
    #          |
    # B --+    +--> unrespected A prereq_in C (FAILURE)
    #     |    |
    # C <-+ ===+

    # runs after C
    A:
      cmd.run:
        - name: echo A fourth
        # is running in test mode before C
        # C gets executed first if this states modify something
        - prereq_in:
          - cmd: C

    # runs before C
    B:
      cmd.run:
        - name: echo B first
        # will test C and be applied only if C changes,
        # and then will run before C
        - prereq:
          - cmd: C

    C:
      cmd.run:
        - name: echo C second
        # replacing A prereq_in C by theses lines
        # changes nothing actually
        #- prereq:
        #  - cmd: A

    # Removing D, A gets executed after C
    # as described in (A prereq_in C)
    # runs before A
    D:
      cmd.run:
        - name: echo D third
        # will test A and be applied only if A changes,
        # and then will run before A
        - prereq:
          - cmd: A
    """
    expected_result = {
        "cmd_|-A_|-echo A fourth_|-run": {
            "__run_num__": 3,
            "comment": 'Command "echo A fourth" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-B_|-echo B first_|-run": {
            "__run_num__": 0,
            "comment": 'Command "echo B first" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-C_|-echo C second_|-run": {
            "__run_num__": 1,
            "comment": 'Command "echo C second" run',
            "result": True,
            "changes": True,
        },
        "cmd_|-D_|-echo D third_|-run": {
            "__run_num__": 2,
            "comment": 'Command "echo D third" run',
            "result": True,
            "changes": True,
        },
    }

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        result = normalize_ret(ret.raw)
        assert result == expected_result

def test_requisites_prereq_simple_ordering_and_errors_7(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    # will fail with 'Cannot extend ID Z (...) not part of the high state.'
    # and not "The following requisites were not found" like in yaml list syntax
    I:
      cmd.run:
        - name: echo I
        - prereq:
          - cmd: Z
    """
    errmsg = (
        "The following requisites were not found:\n"
        "                   prereq:\n"
        "                       cmd: Z\n"
    )
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret["cmd_|-I_|-echo I_|-run"].comment == errmsg

def test_requisites_prereq_simple_ordering_and_errors_8(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    A:
      cmd.run:
        - name: echo A

    B:
      cmd.run:
        - name: echo B
        - prereq:
          - foobar: A
    """
    errmsg = (
        "The following requisites were not found:\n"
        "                   prereq:\n"
        "                       foobar: A\n"
    )
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret["cmd_|-B_|-echo B_|-run"].comment == errmsg

def test_requisites_prereq_simple_ordering_and_errors_9(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    A:
      cmd.run:
        - name: echo A

    B:
      cmd.run:
        - name: echo B
        - prereq:
          - foobar: C
    """
    errmsg = (
        "The following requisites were not found:\n"
        "                   prereq:\n"
        "                       foobar: C\n"
    )
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret["cmd_|-B_|-echo B_|-run"].comment == errmsg

@pytest.mark.skip("issue #8210 : prereq recursion undetected")
def test_requisites_prereq_simple_ordering_and_errors_10(state, state_tree):
    """
    Call sls file containing several prereq_in and prereq.

    Ensure that some of them are failing and that the order is right.
    """
    sls_contents = """
    A:
      cmd.run:
        - name: echo A
        - prereq_in:
          - cmd: B
    B:
      cmd.run:
        - name: echo B
        - prereq_in:
          - cmd: A
    """
    errmsg = (
        'A recursive requisite was found, SLS "requisites.prereq_recursion_error" ID'
        ' "B" ID "A"'
    )
    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret.failed
        assert ret.errors == [errmsg]

def test_infinite_recursion_sls_prereq(state, state_tree):
    sls_contents = """
    include:
      - requisite2
    A:
      test.succeed_without_changes:
        - name: A
        - prereq:
          - sls: requisite2
    """
    sls_2_contents = """
    B:
      test.succeed_without_changes:
        - name: B
    """
    with pytest.helpers.temp_file(
        "requisite.sls", sls_contents, state_tree
    ), pytest.helpers.temp_file("requisite2.sls", sls_2_contents, state_tree):
        ret = state.sls("requisite")
        for state_return in ret:
            assert state_return.result is True

def test_infinite_recursion_prereq(state, state_tree):
    sls_contents = """
    A:
      test.nop:
        - prereq:
          - test: B
    B:
      test.nop:
        - require:
          - name: non-existant
    C:
      test.nop:
        - require:
          - test: B
    """

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        for state_return in ret:
            assert state_return.result is False

def test_infinite_recursion_prereq2(state, state_tree):
    sls_contents = """
    A:
      test.nop:
        - prereq:
          - test: B
    B:
      test.nop:
        - require:
          - test: D
    C:
      test.nop:
        - require:
          - test: B
    D:
      test.nop: []
    """

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        for state_return in ret:
            assert state_return.result is True

def test_requisites_prereq_fail_in_prereq(state, state_tree):
    sls_contents = """
    State A:
      test.configurable_test_state:
        - result: True
        - changes: True
        - name: fail

    State B:
      test.configurable_test_state:
        - changes: True
        - result: False
        - prereq:
          - test: State A

    State C:
      test.nop:
        - onchanges:
          - test: State A
    """

    with pytest.helpers.temp_file("requisite.sls", sls_contents, state_tree):
        ret = state.sls("requisite")
        assert ret["test_|-State A_|-fail_|-configurable_test_state"].result is None
        assert (
            ret["test_|-State A_|-fail_|-configurable_test_state"].full_return[
                "changes"
            ]
            == {}
        )

        assert not ret["test_|-State B_|-State B_|-configurable_test_state"].result

        assert ret["test_|-State C_|-State C_|-nop"].result
        assert not ret["test_|-State C_|-State C_|-nop"].full_return["__state_ran__"]
        assert (
            ret["test_|-State C_|-State C_|-nop"].full_return["comment"]
            == "State was not run because none of the onchanges reqs changed"
        )

redpajama_set_name: RedPajamaGithub


text:
'use strict';

var _      = require('underscore');
var expect = require('chai').expect;
var uint   = require('../uint');

describe('Utility funciton testing', function() {

  it('padZeros', function() {
    expect(uint.padZeros('0', 4)).to.equal('0000');
    expect(uint.padZeros('00', 4)).to.equal('0000');
    expect(uint.padZeros('000', 4)).to.equal('0000');
    expect(uint.padZeros('0000', 4)).to.equal('0000');
    expect(uint.padZeros('000000', 6)).to.equal('000000');
  });

  it('isInteger Positive tests', function() {
    expect(uint.isInteger(0)).to.be.true;
    expect(uint.isInteger(0x0)).to.be.true;
    expect(uint.isInteger(Math.pow(2, 52))).to.be.true;
    expect(uint.isInteger(-1)).to.be.true;
  });

  it('isInteger Negative tests', function() {
    expect(uint.isInteger(1.1)).to.be.false;
    expect(uint.isInteger(false)).to.be.false;
    expect(uint.isInteger([])).to.be.false;
    expect(uint.isInteger(undefined)).to.be.false;
    expect(uint.isInteger(null)).to.be.false;
    expect(uint.isInteger([0])).to.be.false;
    expect(uint.isInteger('0')).to.be.false;
  });

  it('isNatural Positive tests', function() {
    expect(uint.isNatural(0)).to.be.true;
    expect(uint.isNatural(0x0)).to.be.true;
    expect(uint.isNatural(Math.pow(2, 52))).to.be.true;
  });

  it('isNatural Negative tests', function() {
    expect(uint.isNatural(-1)).to.be.false;
  });

  it('howManyBits', function() {
    expect(uint.howManyBits(0)).to.equal(1);
    expect(uint.howManyBits(0x0)).to.equal(1);

    var tmp = 1;
    _.each(_.range(31), function(i) {
      expect(uint.howManyBits(tmp)).to.equal(i+1);
      tmp <<= 1;
    });
  });

  it('maxFromBits', function() {
    _.each(_.range(31), function(i) {
      expect(uint.maxFromBits(i+1)).to.equal(Math.pow(2, i+1)-1);
    });
  });

  it('howManyBytes', function() {
    expect(uint.howManyBytes(0)).to.equal(1);
    expect(uint.howManyBytes(0x0)).to.equal(1);

    var tmp = 1;
     _.each(_.range(31), function(i) {
       expect(uint.howManyBytes(tmp)).to.equal(Math.ceil((i+1)/8));
       tmp <<= 1;
     });
  });

  it('maxFromBytes', function() {
    _.each(_.range(4), function(i) {
      expect(uint.maxFromBytes(i+1)).to.equal(Math.pow(2, (8*(i+1)))-1);
    });
  });
});


text:
Released 2022-08-03

- Move `version.py` file into `common` folder
([#1143](https://github.com/census-instrumentation/opencensus-python/pull/1143))

## 0.8.0
Released 2022-04-20

- Add support for Flask 2
([#1032](https://github.com/census-instrumentation/opencensus-python/pull/1032))

## 0.7.5
Released 2021-05-13

- Restrict `flask` version `1.1.3` as it throws an exception on `Python v2.7` - https://github.com/pallets/flask/issues/4050
([#1032](https://github.com/census-instrumentation/opencensus-python/pull/1032))

## 0.7.4
Released 2021-01-14

- Change blacklist to excludelist
([#977](https://github.com/census-instrumentation/opencensus-python/pull/977))

## 0.7.3
Released 2019-10-01

- Check that `url_rule` is not `None` before dereferencing property.
  ([#781](https://github.com/census-instrumentation/opencensus-python/pull/781))

## 0.7.2
Released 2019-08-26

- Updated `http.status_code` attribute to be an int.
  ([#755](https://github.com/census-instrumentation/opencensus-python/pull/755))
- Fixes value for `http.route` in Flask middleware
  ([#759](https://github.com/census-instrumentation/opencensus-python/pull/759))

## 0.7.1
Released 2019-08-05

- Update for core library changes

## 0.7.0
Released 2019-07-31

- Make ProbabilitySampler default
- Updated span attributes to include some missing attributes listed
  [here](https://github.com/census-instrumentation/opencensus-specs/blob/master/trace/HTTP.md#attributes)
  ([#735](https://github.com/census-instrumentation/opencensus-python/pull/735))

## 0.3.0
Released 2019-04-24

- Decoupled exporter specific logic from configuration

## 0.2.0
Released 2019-04-08

- Update for package changes in core library

## 0.1.0
Released 2019-03-19

- Initial version


text:
<!DOCTYPE animal [
<!ELEMENT animal ANY>
<?_঄ an only legal per 5th edition char #x0984
 in PITarget ?>
]>
<animal/>


text:
<!DOCTYPE html>
<meta charset=utf-8>
<title>Redirecting...</title>
<link rel=canonical href="../覇/index.html">
<meta http-equiv=refresh content="0; url='../覇/index.html'">

Redirecting...

Click here if you are not redirected.


text:
package com.nd.android.u.square.business.task;

import com.product.android.business.ApplicationVariable;
import com.common.widget.GlobalToast;
import com.common.android.utils.concurrent.NdTinyHttpAsyncTask;
import com.nd.android.u.square.R;
import com.nd.android.u.square.controller.SquareUtilFactory;
import com.nd.android.u.square.dataStructure.ReplyInfoList;
import com.common.allCommon.CommUtil;

public class LoadMoreComment extends NdTinyHttpAsyncTask<Void, Void, ReplyInfoList>{

    private long oid;// 跟帖id
    private long id_max;// 加载到的某个评论id

    public LoadMoreComment(long oid, long id_max) {
        super();
        this.oid = oid;
        this.id_max = id_max;
    }

    @Override
    protected void onPreExecute() {
        if (!CommUtil.JudgeNetWorkStatus(ApplicationVariable.INSTANCE.applicationContext)) {
                GlobalToast.showToast(R.string.net_warn_no_network,0);
                cancel(true);
                return;
        }
        super.onPreExecute();
    }

    @Override
    protected ReplyInfoList doInBackground(Void... params) {

        ReplyInfoList replyInfoList = SquareUtilFactory.getInstance().getPostOperateImp().loadReplyInfoList(oid, id_max);
        return replyInfoList;
    }

}


text:
import sys
from constants import Constants
from collegue import Collegue
from unitx_object import UnitXObject
from unit import Unit
from util import Util

class Function(Collegue):
    """A class saving an infomation of a function.

    Attributes:
        name: A string indicating function name.
        defined_args: A list of string indicating function argument.
        ctx: An instance of ParserRuleContext indicating functionDeclaration RULE.
        func_p: An instance indicating an address of a built-in function in python.
        code: A string indicating a source code (an intaractive code or an IO path).
    """

    def __init__(self, name, defined_args, ctx=None, func_p=None, code=None):
        """Inits attributes of a Function class. """
        self.name = name
        self.defined_args = defined_args
        self.ctx = ctx
        self.func_p = func_p
        self.func_obj = None
        self.called_func = None
        self.code = code

    def call(self, args, func_obj, called_func):
        """Call a defined function with called arguments.

        This function is actually an abstract function.
        So, it needs to implement on the super class.

        Args:
            args: A list of a argument appointed/called by user.
            func_obj: An instance of UnitXObject including a function name.
            called_func: An instantce of Function which called this function.
                This a variable is used to trace an error on the EvalErrorListener.
        Returns:
            An instance of UnitXObject calculated by this function.
        """
        self.func_obj = func_obj
        self.called_func = called_func
        self.check_arguments(args, func_obj, called_func)
        return None

    def check_arguments(self, args, func_obj, called_func):
        """Checks arguments of the Function.

        Checks that arguments of this function are not enougn or too much.
        When it's found, it's raised an error againt an EvalErrorListener class.

        Args:
            args: A list of a argument appointed/called by user.
            func_obj: An instance of UnitXObject including a function name.
            called_func: An instantce of Function which called this function.
                This a variable is used to trace an error on the EvalErrorListener.
        """
        # variable, default_value: UnitXObject
        args_without_default = []
        for variable, default_value in self.defined_args:
            if not default_value:
                args_without_default.append([variable, None])

        #
        # An error which arguments are not enougn.
        #
        if len(args) < len(args_without_default):
            msg = Constants.TYPE_ERR_ARGS % (self.name, len(args_without_default), len(args))
            if args:
                last_unitx_obj = args[-1]
                self.mediator.get_parser().notifyErrorListeners(msg, last_unitx_obj.token, Exception(msg))
            else:
                self.mediator.get_parser().notifyErrorListeners(msg, self.ctx.start, Exception(msg))

        #
        # An error which arguments are too much.
        #
        if len(args) > len(self.defined_args):
            msg = Constants.TYPE_ERR_ARGS % (self.name, len(self.defined_args), len(args))
            last_unitx_obj = args[-1]
            self.mediator.get_parser().notifyErrorListeners(msg, last_unitx_obj.token, Exception(msg))

        return

    def __unicode__(self):
        """Returns a string of attributes.

        Returns:
            A string of infomations of attributes.
        """
        res = "<%s: %s(%s) ctx=%s func_p=%s>" % (self.__class__.__name__, self.name, self.defined_args, self.ctx, self.func_p)
        return res

    def __str__(self):
        """Returns an encoded string of attributes.

        Returns:
            An encoded string of attributes.
        """
        return unicode(self).encode('utf-8')

    def __repr__(self):
        """Returns a string of attributes.

        Returns:
            A string of a result of a __str__() function.
        """
        return self.__str__()

    @classmethod
    def set_mediator(self, mediator):
        """Sets a mediator for Mediator pattern of GoF.

        Args:
            mediator: An instance of a EvalVisitor class inherited Mediator class.
        """
        self.mediator = mediator

class DefinedFunction(Function):
    """A class saving an infomation of a defined function.

    Attributes:
        name: A string indicating function name.
        defined_args: A list of string indicating function arguments.
        ctx: An instance of ParserRuleContext indicating functionDeclaration RULE.
        code: A string indicating a source code (an intaractive code or an IO path).
    """

    def __init__(self, name, defined_args, ctx, code):
        """Inits attributes of a Function class. """
        super(DefinedFunction, self).__init__(name, defined_args, ctx=ctx, code=code)

    def call(self, args, func_obj, called_func):
        """Call a defined function with called arguments.

        This function is actually an abstract function.
        So, it needs to implement on the super class.

        Args:
            args: A list of a argument appointed/called by user.
            func_obj: An instance of UnitXObject including a function name.
            called_func: An instantce of Function which called this function.
                This a variable is used to trace an error on the EvalErrorListener.
        Returns:
            An instance of UnitXObject calculated by this function.
        """
        super(DefinedFunction, self).call(args, func_obj, called_func)
        self.define_arguments(args)
        self.mediator.visitBlock(self.ctx.block())
        return self.mediator.return_value

    def define_arguments(self, args):
        """Defines arguments of a Function class and assigns given values
        by user program into the arguments.

        Args:
            args: A list of a argument appointed/called by user.
        """
        for i in range(len(self.defined_args)):
            variable, default_value = self.defined_args[i]
            if i < len(args):
                unitx_obj = args[i]
            else:
                if default_value:
                    unitx_obj = default_value
                else:
                    unitx_obj = UnitXObject(value=None, varname=None, unit=Unit(), token=None, is_none=True)
            variable.assign(unitx_obj, None) #スコープに代入される

class BuiltInFunction(Function):
    """A class saving an infomation of a built-in function.

    Attributes:
        name: A string indicating function name.
        defined_args: A list of string indicating function arguments.
        func_p: An instance indicating an address of a built-in function in python.
    """

    def __init__(self, name, defined_args, func_p):
        """Inits attributes of a Function class. """
        super(BuiltInFunction, self).__init__(name, defined_args, func_p=func_p)

    def call(self, args, func_obj, called_func):
        """Call a defined function with called arguments.

        This function is actually an abstract function.
        So, it needs to implement on the super class.

        Args:
            args: A list of a argument appointed/called by user.
            func_obj: An instance of UnitXObject including a function name.
            called_func: An instantce of Function which called this function.
                This a variable is used to trace an error on the EvalErrorListener.
        Returns:
            An instance of UnitXObject calculated by this function.
        """
        super(BuiltInFunction, self).call(args, func_obj, called_func)
        a_value = self.func_p(args, func_obj)
        if a_value:
            return UnitXObject(value=a_value, varname=None, is_none=False, unit=Unit(), token=func_obj.token)
        else:
            return UnitXObject(value=None, varname=None, is_none=True, unit=Unit(), token=func_obj.token)

def main():
    """Run an example for a Function class."""
    from simulator import Simulator
    s = Simulator()

    # Define variables
    current_scope = s.get_scopes().peek()
    x, y = UnitXObject(None,None,None,is_none=True), UnitXObject(None,None,None,is_none=True)
    current_scope['x'] = x
    current_scope['y'] = y
    current_scope['dfs'] = DefinedFunction('dfs', [['x', x], ['y', y], ['level', None]], ctx=None, code=None)

    # Output
    from util import Util
    Util.dump(s.get_scopes())
    s.get_scopes().del_scope()

    return Constants.EXIT_SUCCESS

if __name__ == '__main__':
    sys.exit(main())


text:
<!DOCTYPE html>

    <title>TL;DR</title>

    <meta name="viewport" content="width=device-width, user-scalable=no"/>

    <link rel="stylesheet" href="/static/semantic.min.css"/>
    <link rel="stylesheet" href="/static/main.css"/>

          TL;DR

    {% block content %}{% endblock %}

    {% block javascript %}{% endblock %}


text:
package com.bitdubai.fermat_cbp_plugin.layer.identity.crypto_broker.developer.bitdubai.version_1.database;

import com.bitdubai.fermat_api.DealsWithPluginIdentity;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabase;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTable;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperDatabaseTableRecord;
import com.bitdubai.fermat_api.layer.all_definition.developer.DeveloperObjectFactory;
import com.bitdubai.fermat_api.layer.osa_android.database_system.Database;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTable;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DatabaseTableRecord;
import com.bitdubai.fermat_api.layer.osa_android.database_system.DealsWithPluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.PluginDatabaseSystem;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantCreateDatabaseException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantLoadTableToMemoryException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.DatabaseNotFoundException;
import com.bitdubai.fermat_api.layer.osa_android.database_system.exceptions.CantOpenDatabaseException;
import com.bitdubai.fermat_cbp_plugin.layer.identity.crypto_broker.developer.bitdubai.version_1.exceptions.CantInitializeCryptoBrokerIdentityDatabaseException;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * The Class com.bitdubai.fermat_cbp_plugin.layer.identity.crypto_broker.developer.bitdubai.version_1.database.CryptoBrokerIdentityDeveloperDatabaseFactory have
 * contains the methods that the Developer Database Tools uses to show the information.
 *

 *
 * Created by Jorge Gonzalez - (jorgeejgonzalez@gmail.com) on 28/09/15.
 *
 * @version 1.0
 * @since Java JDK 1.7
 */

public class CryptoBrokerIdentityDeveloperDatabaseFactory implements DealsWithPluginDatabaseSystem, DealsWithPluginIdentity {

    /**
     * DealsWithPluginDatabaseSystem Interface member variables.
     */
    PluginDatabaseSystem pluginDatabaseSystem;

    /**
     * DealsWithPluginIdentity Interface member variables.
     */
    UUID pluginId;

    Database database;

    /**
     * Constructor
     *
     * @param pluginDatabaseSystem
     * @param pluginId
     */
    public CryptoBrokerIdentityDeveloperDatabaseFactory(PluginDatabaseSystem pluginDatabaseSystem, UUID pluginId) {
        this.pluginDatabaseSystem = pluginDatabaseSystem;
        this.pluginId = pluginId;
    }

    /**
     * This method open or creates the database i'll be working with
     *
     * @throws CantInitializeCryptoBrokerIdentityDatabaseException
     */
    public void initializeDatabase() throws CantInitializeCryptoBrokerIdentityDatabaseException {
        try {

             /*
              * Open new database connection
              */
            database = this.pluginDatabaseSystem.openDatabase(pluginId, pluginId.toString());

        } catch (CantOpenDatabaseException cantOpenDatabaseException) {

             /*
              * The database exists but cannot be open. I can not handle this situation.
              */
            throw new CantInitializeCryptoBrokerIdentityDatabaseException(cantOpenDatabaseException.getMessage());

        } catch (DatabaseNotFoundException e) {

             /*
              * The database no exist may be the first time the plugin is running on this device,
              * We need to create the new database
              */
            CryptoBrokerIdentityDatabaseFactory cryptoBrokerIdentityDatabaseFactory = new CryptoBrokerIdentityDatabaseFactory(pluginDatabaseSystem);

            try {
                  /*
                   * We create the new database
                   */
                database = cryptoBrokerIdentityDatabaseFactory.createDatabase(pluginId, pluginId.toString());
            } catch (CantCreateDatabaseException cantCreateDatabaseException) {
                  /*
                   * The database cannot be created. I can not handle this situation.
                   */
                throw new CantInitializeCryptoBrokerIdentityDatabaseException(cantCreateDatabaseException.getMessage());
            }
        }
    }

    public List<DeveloperDatabase> getDatabaseList(DeveloperObjectFactory developerObjectFactory) {
        /**
         * I only have one database on my plugin. I will return its name.
         */
        List<DeveloperDatabase> databases = new ArrayList<DeveloperDatabase>();
        databases.add(developerObjectFactory.getNewDeveloperDatabase("Crypto Broker", this.pluginId.toString()));
        return databases;
    }

    public List<DeveloperDatabaseTable> getDatabaseTableList(DeveloperObjectFactory developerObjectFactory) {
        List<DeveloperDatabaseTable> tables = new ArrayList<DeveloperDatabaseTable>();

        /**
         * Table Crypto Broker columns.
         */
        List<String> cryptoBrokerColumns = new ArrayList<String>();

        cryptoBrokerColumns.add(CryptoBrokerIdentityDatabaseConstants.CRYPTO_BROKER_CRYPTO_BROKER_PUBLIC_KEY_COLUMN_NAME);
        cryptoBrokerColumns.add(CryptoBrokerIdentityDatabaseConstants.CRYPTO_BROKER_ALIAS_COLUMN_NAME);
        cryptoBrokerColumns.add(CryptoBrokerIdentityDatabaseConstants.CRYPTO_BROKER_DEVICE_USER_PUBLIC_KEY_COLUMN_NAME);
        /**
         * Table Crypto Broker addition.
         */
        DeveloperDatabaseTable cryptoBrokerTable = developerObjectFactory.getNewDeveloperDatabaseTable(CryptoBrokerIdentityDatabaseConstants.CRYPTO_BROKER_TABLE_NAME, cryptoBrokerColumns);
        tables.add(cryptoBrokerTable);

        return tables;
    }

    public List<DeveloperDatabaseTableRecord> getDatabaseTableContent(DeveloperObjectFactory developerObjectFactory, DeveloperDatabaseTable developerDatabaseTable) {
        /**
         * Will get the records for the given table
         */
        List<DeveloperDatabaseTableRecord> returnedRecords = new ArrayList<DeveloperDatabaseTableRecord>();

        /**
         * I load the passed table name from the SQLite database.
         */
        DatabaseTable selectedTable = database.getTable(developerDatabaseTable.getName());
        try {
            selectedTable.loadToMemory();
        } catch (CantLoadTableToMemoryException cantLoadTableToMemory) {
            /**
             * if there was an error, I will returned an empty list.
             */
            return returnedRecords;
        }

        List<DatabaseTableRecord> records = selectedTable.getRecords();
        List<String> developerRow = new ArrayList<String>();
        for (DatabaseTableRecord row : records) {
            /**
             * for each row in the table list
             */
            for (DatabaseRecord field : row.getValues()) {
                /**
                 * I get each row and save them into a List<String>
                 */
                developerRow.add(field.getValue().toString());
            }
            /**
             * I create the Developer Database record
             */
            returnedRecords.add(developerObjectFactory.getNewDeveloperDatabaseTableRecord(developerRow));
        }

        /**
         * return the list of DeveloperRecords for the passed table.
         */
        return returnedRecords;
    }

    @Override
    public void setPluginDatabaseSystem(PluginDatabaseSystem pluginDatabaseSystem) {
        this.pluginDatabaseSystem = pluginDatabaseSystem;
    }

    @Override
    public void setPluginId(UUID pluginId) {
        this.pluginId = pluginId;
    }
}


text:
package org.sakaiproject.nakamura.api.user.indexing;

import org.sakaiproject.nakamura.api.lite.authorizable.Authorizable;
import org.apache.solr.common.SolrInputDocument;
import org.osgi.service.event.Event;
import org.sakaiproject.nakamura.api.solr.RepositorySession;

public interface AuthorizableIndexingWorker {
  public void decorateSolrInputDocument (SolrInputDocument indexDoc, Event osgiEvent,
       Authorizable authorizable, RepositorySession repositorySession) throws
       AuthorizableIndexingException;
}


text:
package com.oracle.pts.vo;

public interface PrescriptionSDO {

}


text:
Creating yor own corner detector {#tutorial_generic_corner_detector}
================================

Goal
----

In this tutorial you will learn how to:

-   Use the OpenCV function @ref cv::cornerEigenValsAndVecs to find the eigenvalues and eigenvectors
    to determine if a pixel is a corner.
-   Use the OpenCV function @ref cv::cornerMinEigenVal to find the minimum eigenvalues for corner
    detection.
-   To implement our own version of the Harris detector as well as the Shi-Tomasi detector, by using
    the two functions above.

Theory
------

Code
----

This tutorial code's is shown lines below. You can also download it from
[here](https://github.com/Itseez/opencv/tree/master/samples/cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp)

@include cpp/tutorial_code/TrackingMotion/cornerDetector_Demo.cpp

Explanation
-----------

Result
------

![](images/My_Harris_corner_detector_Result.jpg)

![](images/My_Shi_Tomasi_corner_detector_Result.jpg)


text:
Q-Expressions • Chapter 10

Adding Features

You'll notice that the following chapters will all follow a similar pattern. This pattern is the typical approach used to add new features to a language. It consists of a number of steps that bring a feature from start to finish. These are listed below, and are exactly what we're going to do in this chapter to introduce a new feature called a Q-Expression.

Syntax	Add new rule to the language grammar for this feature.

Representation	Add new data type variation to represent this feature.

Parsing	Add new functions for reading this feature from the abstract syntax tree.

Semantics	Add new functions for evaluating and manipulating this feature.

Quoted Expressions

In this chapter we'll implement a new type of Lisp Value called a Q-Expression.

This stands for quoted expression, and is a type of Lisp Expression that is not evaluated by the standard Lisp mechanics. When encountered by the evaluation function Q-expressions are left exactly as they are. This makes them ideal for a number of purposes. We can use them to store and manipulate other Lisp values such as numbers, symbols, or other S-Expressions themselves.

After we've added Q-Expressions we are going to implement a concise set of operators to manipulate them. Like the arithmetic operators these will prove fundamental in how we think about and play with expressions.

The syntax for Q-Expressions is very similar to that of S-Expressions. The only difference is that instead of parenthesis () Q-Expressions are surrounded by curly brackets {}. We can add this to our grammar as follows.

I've never heard of Q-Expressions.

Q-Expressions don't exist in other Lisps. Other Lisps use Macros to stop evaluation. These look like normal functions, but they do not evaluate their arguments. A special Macro called quote ' exists, which can be used to stop the evaluation of almost anything. This is the inspiration for Q-Expressions, which are unique to our Lisp, and will be used instead of Macros for doing all the same tasks and more.

The way I've used S-Expression and Q-Expression in this book is a slight abuse of terminology, but I hope this misdemeanor makes the behaviour of our Lisp clearer.

mpc_parser_t* Number = mpc_new("number");
mpc_parser_t* Symbol = mpc_new("symbol");
mpc_parser_t* Sexpr  = mpc_new("sexpr");
mpc_parser_t* Qexpr  = mpc_new("qexpr");
mpc_parser_t* Expr   = mpc_new("expr");
mpc_parser_t* Lispy  = mpc_new("lispy");

mpca_lang(MPCA_LANG_DEFAULT,
  "                                                    \
    number : /-?[0-9]+/ ;                              \
    symbol : '+' | '-' | '*' | '/' ;                   \
    sexpr  : '(' <expr>* ')' ;                         \
    qexpr  : '{' <expr>* '}' ;                         \
    expr   : <number> | <symbol> | <sexpr> | <qexpr> ; \
    lispy  : /^/ <expr>* /$/ ;                         \
  ",
  Number, Symbol, Sexpr, Qexpr, Expr, Lispy);

We also must remember to update our cleanup function to deal with the new rule we've added.

mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy);

Reading Q-Expressions

Because Q-Expressions are so similar S-Expressions much of their internal behaviour is going to be the same. We're going to reuse our S-Expression data fields to represent Q-Expressions, but we still need to add a separate type to the enumeration.

enum { LVAL_ERR, LVAL_NUM, LVAL_SYM, LVAL_SEXPR, LVAL_QEXPR };

We can also add a constructor for this variation.

/* A pointer to a new empty Qexpr lval */
lval* lval_qexpr(void) {
  lval* v = malloc(sizeof(lval));
  v->type = LVAL_QEXPR;
  v->count = 0;
  v->cell = NULL;
  return v;
}

To print and delete Q-Expressions we do essentially the same thing as with S-Expressions. We can add the relevant lines to our functions for printing and deletion as follows.

void lval_print(lval* v) {
  switch (v->type) {
    case LVAL_NUM:   printf("%li", v->num); break;
    case LVAL_ERR:   printf("Error: %s", v->err); break;
    case LVAL_SYM:   printf("%s", v->sym); break;
    case LVAL_SEXPR: lval_expr_print(v, '(', ')'); break;
    case LVAL_QEXPR: lval_expr_print(v, '{', '}'); break;
  }
}

void lval_del(lval* v) {

  switch (v->type) {
    case LVAL_NUM: break;
    case LVAL_ERR: free(v->err); break;
    case LVAL_SYM: free(v->sym); break;

    /* If Qexpr or Sexpr then delete all elements inside */
    case LVAL_QEXPR:
    case LVAL_SEXPR:
      for (int i = 0; i < v->count; i++) {
        lval_del(v->cell[i]);
      }
      /* Also free the memory allocated to contain the pointers */
      free(v->cell);
    break;
  }

  free(v);
}

Using these simple changes we can update our reading function lval_read to be able to read in Q-Expressions. Because we reused all the S-Expression data fields for our Q-Expression type, we can also reuse all of the functions for S-Expressions such as lval_add. Therefore to read in Q-Expressions we just need to add a special case for constructing an empty Q-Expression to lval_read just below where we detect and create empty S-Expressions from the abstract syntax tree.

if (strstr(t->tag, "qexpr"))  { x = lval_qexpr(); }

We also need to update lval_read to recognize the curly bracket characters when they appear.

if (strcmp(t->children[i]->contents, "(") == 0) { continue; }
if (strcmp(t->children[i]->contents, ")") == 0) { continue; }
if (strcmp(t->children[i]->contents, "}") == 0) { continue; }
if (strcmp(t->children[i]->contents, "{") == 0) { continue; }

Because there is no special method of evaluating Q-Expressions, we don't need to edit any of the evaluation functions. Our Q-Expressions should be ready to try. Compile and run the program. Try using them as a new data type and ensure they are not evaluated.

lispy> {1 2 3 4}
{1 2 3 4}
lispy> {1 2 (+ 5 6) 4}
{1 2 (+ 5 6) 4}
lispy> {(2 3 4) (1)}
{(2 3 4) (1)}
lispy>

Builtin Functions

We can read in Q-Expressions but they are still useless. We need some way to manipulate them.

For this we can define some built-in operators to work on our list type. Choosing a concise set of these is important. If we implement a few fundamental operations then we can use these to define new operations without adding extra C code. There are a few ways to pick these fundamental operators but I've chosen a set that will allow us to do everything we need. They are defined as follows.

list	Takes one or more arguments and returns a new Q-Expression containing the arguments

head	Takes a Q-Expression and returns a Q-Expression with only of the first element

tail	Takes a Q-Expression and returns a Q-Expression with the first element removed

join	Takes one or more Q-Expressions and returns a Q-Expression of them conjoined together

eval	Takes a Q-Expression and evaluates it as if it were a S-Expression

Like with our mathematical operators we should add these functions as possible valid symbols. Afterward we can go about trying to define their behaviour in a similar way to builtin_op.

mpca_lang(MPCA_LANG_DEFAULT,
  "                                                        \
    number : /-?[0-9]+/ ;                                  \
    symbol : \"list\" | \"head\" | \"tail\"                \
           | \"join\" | \"eval\" | '+' | '-' | '*' | '/' ; \
    sexpr  : '(' <expr>* ')' ;                             \
    qexpr  : '{' <expr>* '}' ;                             \
    expr   : <number> | <symbol> | <sexpr> | <qexpr> ;     \
    lispy  : /^/ <expr>* /$/ ;                             \
  ",
  Number, Symbol, Sexpr, Qexpr, Expr, Lispy)

First Attempt

Our builtin functions should have the same interface as builtin_op. That means the arguments should be bundled into an S-Expression which the function must use and then delete. They should return a new lval* as a result of the evaluation.

The actual functionality of taking the head or tail of an Q-Expression shouldn't be too hard for us. We can make use of the existing functions we've defined for S-Expressions such as lval_take and lval_pop. But like builtin_op we also need to check that the inputs we get are valid.

Let's take a look at head and tail first. These functions have a number of conditions under which they can't act. First of all we must ensure they are only passed a single argument, and that that argument is a Q-Expression. Then we need to ensure that this Q-Expression isn't empty and actually has some elements.

The head function can repeatedly pop and delete the item at index 1 until there is nothing else left in the list.

The tail function is even more simple. It can pop and delete the item at index 0, leaving the tail remaining. An initial attempt at these functions might look like this.

lval* builtin_head(lval* a) {
  /* Check Error Conditions */
  if (a->count != 1) {
    lval_del(a);
    return lval_err("Function 'head' passed too many arguments!");
  }

  if (a->cell[0]->type != LVAL_QEXPR) {
    lval_del(a);
    return lval_err("Function 'head' passed incorrect types!");
  }

  if (a->cell[0]->count == 0) {
    lval_del(a);
    return lval_err("Function 'head' passed {}!");
  }

  /* Otherwise take first argument */
  lval* v = lval_take(a, 0);

  /* Delete all elements that are not head and return */
  while (v->count > 1) { lval_del(lval_pop(v, 1)); }
  return v;
}

lval* builtin_tail(lval* a) {
  /* Check Error Conditions */
  if (a->count != 1) {
    lval_del(a);
    return lval_err("Function 'tail' passed too many arguments!");
  }

  if (a->cell[0]->type != LVAL_QEXPR) {
    lval_del(a);
    return lval_err("Function 'tail' passed incorrect types!");
  }

  if (a->cell[0]->count == 0) {
    lval_del(a);
    return lval_err("Function 'tail' passed {}!");
  }

  /* Take first argument */
  lval* v = lval_take(a, 0);

  /* Delete first element and return */
  lval_del(lval_pop(v, 0));
  return v;
}

Macros

Strawberry • A delicious macro.

These head and tail functions do the correct thing, but the code is pretty unclear, and long. There is so much error checking that the functionality is hard to see. One method we can use to clean it up is to use a Macro.

A Macro is a preprocessor statement for creating function-like-things that are evaluated before the program is compiled. It can be used for many different things, one of which is what we need to do here, clean up code.

Macros work by taking some arguments (which can be almost anything), and copying and pasting them into some given pattern. By changing the pattern or the arguments we can alter what code is generated by the Macro. To define macros we use the #define preprocessor directive. After this we write the name of the macro, followed by the argument names in parenthesis. After this the pattern is specified, to declare what code should be generated for the given arguments.

We can design a macro to help with our error conditions called LASSERT. Macros are typically given names in capitals to help distinguish them from normal C functions. This macro take in three arguments args, cond and err. It then generates code as shown on the right hand side, but with these variables pasted in at the locations where they are named. This pattern is a good fit for all of our error conditions.

#define LASSERT(args, cond, err) \
  if (!(cond)) { lval_del(args); return lval_err(err); }

We can use this to change how our above functions are written, without actually changing what code is generated by the compiler. This makes it much easier to read for the programmer, and saves a bit of typing. The rest of the error conditions for our functions should become easy to write too!

Head & Tail

Using this our head and tail functions are defined as follows. Notice how much clearer their real functionality is.

lval* builtin_head(lval* a) {
  LASSERT(a, a->count == 1,
    "Function 'head' passed too many arguments!");
  LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
    "Function 'head' passed incorrect type!");
  LASSERT(a, a->cell[0]->count != 0,
    "Function 'head' passed {}!");

  lval* v = lval_take(a, 0);
  while (v->count > 1) { lval_del(lval_pop(v, 1)); }
  return v;
}

lval* builtin_tail(lval* a) {
  LASSERT(a, a->count == 1,
    "Function 'tail' passed too many arguments!");
  LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
    "Function 'tail' passed incorrect type!");
  LASSERT(a, a->cell[0]->count != 0,
    "Function 'tail' passed {}!");

  lval* v = lval_take(a, 0);
  lval_del(lval_pop(v, 0));
  return v;
}

List & Eval

The list function is simple. It just converts the input S-Expression to a Q-Expression and returns it.

The eval function is similar to the converse. It takes as input some single Q-Expression, which it converts to an S-Expression, and evaluates using lval_eval.

lval* builtin_list(lval* a) {
  a->type = LVAL_QEXPR;
  return a;
}

lval* builtin_eval(lval* a) {
  LASSERT(a, a->count == 1,
    "Function 'eval' passed too many arguments!");
  LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
    "Function 'eval' passed incorrect type!");

  lval* x = lval_take(a, 0);
  x->type = LVAL_SEXPR;
  return lval_eval(x);
}

Join

The join function is our final function to define.

Unlike the others it can take multiple arguments, so its structure looks somewhat more like that of builtin_op. First we check that all of the arguments are Q-Expressions and then we join them together one by one. To do this we use the function lval_join. This works by repeatedly popping each item from y and adding it to x until y is empty. It then deletes y and returns x.

lval* builtin_join(lval* a) {

  for (int i = 0; i < a->count; i++) {
    LASSERT(a, a->cell[i]->type == LVAL_QEXPR,
      "Function 'join' passed incorrect type.");
  }

  lval* x = lval_pop(a, 0);

  while (a->count) {
    x = lval_join(x, lval_pop(a, 0));
  }

  lval_del(a);
  return x;
}

lval* lval_join(lval* x, lval* y) {

  /* For each cell in 'y' add it to 'x' */
  while (y->count) {
    x = lval_add(x, lval_pop(y, 0));
  }

  /* Delete the empty 'y' and return 'x' */
  lval_del(y);
  return x;
}

Builtins Lookup

We've now got all of our builtin functions defined. We need to make a function that can call the correct one depending on what symbol it encounters in evaluation. We can do this using strcmp and strstr.

lval* builtin(lval* a, char* func) {
  if (strcmp("list", func) == 0) { return builtin_list(a); }
  if (strcmp("head", func) == 0) { return builtin_head(a); }
  if (strcmp("tail", func) == 0) { return builtin_tail(a); }
  if (strcmp("join", func) == 0) { return builtin_join(a); }
  if (strcmp("eval", func) == 0) { return builtin_eval(a); }
  if (strstr("+-/*", func)) { return builtin_op(a, func); }
  lval_del(a);
  return lval_err("Unknown Function!");
}

Then we can change our evaluation line in lval_eval_sexpr to call builtin rather than builtin_op.

/* Call builtin with operator */
lval* result = builtin(v, f->sym);
lval_del(f);
return result;

Finally Q-Expressions should be fully supported in our language. Compile and run the latest version and see what you can do with the new list operators. Try putting code and symbols into our lists and evaluating them in different ways. The ability to put S-Expressions inside a list using Q-Expressions is pretty awesome. It means we can treat code like data itself. This is a flagship feature of Lisps, and something that really cannot be done in languages such as C!

lispy> list 1 2 3 4
{1 2 3 4}
lispy> {head (list 1 2 3 4)}
{head (list 1 2 3 4)}
lispy> eval {head (list 1 2 3 4)}
{1}
lispy> tail {tail tail tail}
{tail tail}
lispy> eval (tail {tail tail {5 6 7}})
{6 7}
lispy> eval (head {(+ 1 2) (+ 10 20)})
3

Reference

<button  onclick="myFunction2()">q_expressions.c</button>

{% highlight c  linenos=table %}

    #include "mpc.h"

    #ifdef _WIN32

    static char buffer[2048];

    char* readline(char* prompt) {
      fputs(prompt, stdout);
      fgets(buffer, 2048, stdin);
      char* cpy = malloc(strlen(buffer)+1);
      strcpy(cpy, buffer);
      cpy[strlen(cpy)-1] = '\0';
      return cpy;
    }

    void add_history(char* unused) {}

    #else
    #include <editline/readline.h>
    #include <editline/history.h>
    #endif

    /* Add QEXPR as possible lval type */
    enum { LVAL_ERR, LVAL_NUM, LVAL_SYM, LVAL_SEXPR, LVAL_QEXPR };

    typedef struct lval {
      int type;
      long num;
      char* err;
      char* sym;
      int count;
      struct lval** cell;
    } lval;

    lval* lval_num(long x) {
      lval* v = malloc(sizeof(lval));
      v->type = LVAL_NUM;
      v->num = x;
      return v;
    }

    lval* lval_err(char* m) {
      lval* v = malloc(sizeof(lval));
      v->type = LVAL_ERR;
      v->err = malloc(strlen(m) + 1);
      strcpy(v->err, m);
      return v;
    }

    lval* lval_sym(char* s) {
      lval* v = malloc(sizeof(lval));
      v->type = LVAL_SYM;
      v->sym = malloc(strlen(s) + 1);
      strcpy(v->sym, s);
      return v;
    }

    lval* lval_sexpr(void) {
      lval* v = malloc(sizeof(lval));
      v->type = LVAL_SEXPR;
      v->count = 0;
      v->cell = NULL;
      return v;
    }

    /* A pointer to a new empty Qexpr lval */
    lval* lval_qexpr(void) {
      lval* v = malloc(sizeof(lval));
      v->type = LVAL_QEXPR;
      v->count = 0;
      v->cell = NULL;
      return v;
    }

    void lval_del(lval* v) {

      switch (v->type) {
        case LVAL_NUM: break;
        case LVAL_ERR: free(v->err); break;
        case LVAL_SYM: free(v->sym); break;

        /* If Qexpr or Sexpr then delete all elements inside */
        case LVAL_QEXPR:
        case LVAL_SEXPR:
          for (int i = 0; i < v->count; i++) {
            lval_del(v->cell[i]);
          }
          /* Also free the memory allocated to contain the pointers */
          free(v->cell);
        break;
      }

      free(v);
    }

    lval* lval_add(lval* v, lval* x) {
      v->count++;
      v->cell = realloc(v->cell, sizeof(lval*) * v->count);
      v->cell[v->count-1] = x;
      return v;
    }

    lval* lval_pop(lval* v, int i) {
      lval* x = v->cell[i];
      memmove(&v->cell[i], &v->cell[i+1],
        sizeof(lval*) * (v->count-i-1));
      v->count--;
      v->cell = realloc(v->cell, sizeof(lval*) * v->count);
      return x;
    }

    lval* lval_join(lval* x, lval* y) {

      while (y->count) {
        x = lval_add(x, lval_pop(y, 0));
      }

      lval_del(y);
      return x;
    }

    lval* lval_take(lval* v, int i) {
      lval* x = lval_pop(v, i);
      lval_del(v);
      return x;
    }

    void lval_print(lval* v);

    void lval_expr_print(lval* v, char open, char close) {
      putchar(open);
      for (int i = 0; i < v->count; i++) {

        lval_print(v->cell[i]);

        if (i != (v->count-1)) {
          putchar(' ');
        }
      }
      putchar(close);
    }

    void lval_print(lval* v) {
      switch (v->type) {
        case LVAL_NUM:   printf("%li", v->num); break;
        case LVAL_ERR:   printf("Error: %s", v->err); break;
        case LVAL_SYM:   printf("%s", v->sym); break;
        case LVAL_SEXPR: lval_expr_print(v, '(', ')'); break;
        case LVAL_QEXPR: lval_expr_print(v, '{', '}'); break;
      }
    }

    void lval_println(lval* v) { lval_print(v); putchar('\n'); }

    #define LASSERT(args, cond, err) \
      if (!(cond)) { lval_del(args); return lval_err(err); }

    lval* lval_eval(lval* v);

    lval* builtin_list(lval* a) {
      a->type = LVAL_QEXPR;
      return a;
    }

    lval* builtin_head(lval* a) {
      LASSERT(a, a->count == 1,
        "Function 'head' passed too many arguments.");
      LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
        "Function 'head' passed incorrect type.");
      LASSERT(a, a->cell[0]->count != 0,
        "Function 'head' passed {}.");

      lval* v = lval_take(a, 0);
      while (v->count > 1) { lval_del(lval_pop(v, 1)); }
      return v;
    }

    lval* builtin_tail(lval* a) {
      LASSERT(a, a->count == 1,
        "Function 'tail' passed too many arguments.");
      LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
        "Function 'tail' passed incorrect type.");
      LASSERT(a, a->cell[0]->count != 0,
        "Function 'tail' passed {}.");

      lval* v = lval_take(a, 0);
      lval_del(lval_pop(v, 0));
      return v;
    }

    lval* builtin_eval(lval* a) {
      LASSERT(a, a->count == 1,
        "Function 'eval' passed too many arguments.");
      LASSERT(a, a->cell[0]->type == LVAL_QEXPR,
        "Function 'eval' passed incorrect type.");

      lval* x = lval_take(a, 0);
      x->type = LVAL_SEXPR;
      return lval_eval(x);
    }

    lval* builtin_join(lval* a) {

      for (int i = 0; i count; i++) {
        LASSERT(a, a->cell[i]->type == LVAL_QEXPR,
          "Function 'join' passed incorrect type.");
      }

      lval* x = lval_pop(a, 0);

      while (a->count) {
        x = lval_join(x, lval_pop(a, 0));
      }

      lval_del(a);
      return x;
    }

    lval* builtin_op(lval* a, char* op) {

      for (int i = 0; i count; i++) {
        if (a->cell[i]->type != LVAL_NUM) {
          lval_del(a);
          return lval_err("Cannot operate on non-number!");
        }
      }

      lval* x = lval_pop(a, 0);
      if ((strcmp(op, "-") == 0) && a->count == 0) { x->num = -x->num; }

      while (a->count > 0) {

        lval* y = lval_pop(a, 0);

        if (strcmp(op, "+") == 0) { x->num += y->num; }
        if (strcmp(op, "-") == 0) { x->num -= y->num; }
        if (strcmp(op, "*") == 0) { x->num *= y->num; }
        if (strcmp(op, "/") == 0) {
          if (y->num == 0) {
            lval_del(x); lval_del(y);
            x = lval_err("Division By Zero.");
            break;
          }
          x->num /= y->num;
        }

        lval_del(y);
      }

      lval_del(a);
      return x;
    }

    lval* builtin(lval* a, char* func) {
      if (strcmp("list", func) == 0) { return builtin_list(a); }
      if (strcmp("head", func) == 0) { return builtin_head(a); }
      if (strcmp("tail", func) == 0) { return builtin_tail(a); }
      if (strcmp("join", func) == 0) { return builtin_join(a); }
      if (strcmp("eval", func) == 0) { return builtin_eval(a); }
      if (strstr("+-/*", func)) { return builtin_op(a, func); }
      lval_del(a);
      return lval_err("Unknown Function!");
    }

    lval* lval_eval_sexpr(lval* v) {

      for (int i = 0; i < v->count; i++) {
        v->cell[i] = lval_eval(v->cell[i]);
      }

      for (int i = 0; i < v->count; i++) {
        if (v->cell[i]->type == LVAL_ERR) { return lval_take(v, i); }
      }

      if (v->count == 0) { return v; }

      if (v->count == 1) { return lval_take(v, 0); }

      lval* f = lval_pop(v, 0);
      if (f->type != LVAL_SYM) {
        lval_del(f); lval_del(v);
        return lval_err("S-expression Does not start with symbol.");
      }

      /* Call builtin with operator */
      lval* result = builtin(v, f->sym);
      lval_del(f);
      return result;
    }

    lval* lval_eval(lval* v) {
      if (v->type == LVAL_SEXPR) { return lval_eval_sexpr(v); }
      return v;
    }

    lval* lval_read_num(mpc_ast_t* t) {
      errno = 0;
      long x = strtol(t->contents, NULL, 10);
      return errno != ERANGE ? lval_num(x) : lval_err("invalid number");
    }

    lval* lval_read(mpc_ast_t* t) {

      if (strstr(t->tag, "number")) { return lval_read_num(t); }
      if (strstr(t->tag, "symbol")) { return lval_sym(t->contents); }

      lval* x = NULL;
      if (strcmp(t->tag, ">") == 0) { x = lval_sexpr(); }
      if (strstr(t->tag, "sexpr"))  { x = lval_sexpr(); }
      if (strstr(t->tag, "qexpr"))  { x = lval_qexpr(); }

      for (int i = 0; i < t->children_num; i++) {
        if (strcmp(t->children[i]->contents, "(") == 0) { continue; }
        if (strcmp(t->children[i]->contents, ")") == 0) { continue; }
        if (strcmp(t->children[i]->contents, "}") == 0) { continue; }
        if (strcmp(t->children[i]->contents, "{") == 0) { continue; }
        if (strcmp(t->children[i]->tag,  "regex") == 0) { continue; }
        x = lval_add(x, lval_read(t->children[i]));
      }

      return x;
    }

    int main(int argc, char** argv) {

      mpc_parser_t* Number = mpc_new("number");
      mpc_parser_t* Symbol = mpc_new("symbol");
      mpc_parser_t* Sexpr  = mpc_new("sexpr");
      mpc_parser_t* Qexpr  = mpc_new("qexpr");
      mpc_parser_t* Expr   = mpc_new("expr");
      mpc_parser_t* Lispy  = mpc_new("lispy");

      mpca_lang(MPCA_LANG_DEFAULT,
        "                                                    \
          number : /-?[0-9]+/ ;                              \
          symbol : \"list\" | \"head\" | \"tail\" | \"eval\" \
                 | \"join\" | '+' | '-' | '*' | '/' ;        \
          sexpr  : '(' <expr>* ')' ;                         \
          qexpr  : '{' <expr>* '}' ;                         \
          expr   : <number> | <symbol> | <sexpr> | <qexpr> ; \
          lispy  : /^/ <expr>* /$/ ;                         \
        ",
        Number, Symbol, Sexpr, Qexpr, Expr, Lispy);

      puts("Lispy Version 0.0.0.0.6");
      puts("Press Ctrl+c to Exit\n");

      while (1) {

        char* input = readline("lispy> ");
        add_history(input);

        mpc_result_t r;
        if (mpc_parse("<stdin>", input, Lispy, &r)) {
          lval* x = lval_eval(lval_read(r.output));
          lval_println(x);
          lval_del(x);
          mpc_ast_delete(r.output);
        } else {
          mpc_err_print(r.error);
          mpc_err_delete(r.error);
        }

        free(input);

      }

      mpc_cleanup(6, Number, Symbol, Sexpr, Qexpr, Expr, Lispy);

      return 0;
    }

{% endhighlight %}


text:
package com.cedar.autologin;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

public class LoginTask extends AsyncTask<BasicNameValuePair, Integer, Boolean> {

	final static String version = "2.2";

	Context context;
	String account;
	String passwd;
	int retrys = 0;
	Boolean exceedError = false;
	Boolean passwdError = false;
	Boolean alreadyLoggedIn = false;
	Boolean retry = false;
	Boolean forbidden = false;

	Boolean foreground = false;

	public LoginTask(Context context) {

	    this.context = context;
	}

	protected Boolean doInBackground(BasicNameValuePair... params) {
		for (BasicNameValuePair param : params) {
			if (param.getName().equals("retrys")) {
				try {
					retrys = Integer.parseInt(param.getValue()) + 1;
				} catch (NumberFormatException e) {
					Log.d("autologin", "Integer.parseInt error " + e.toString());
					return false;
				}
			}
			else if (param.getName().equals("foreground")) {
				foreground = true;
			}
		}
		if (checkLogin())
			return false;
		else if (retry) {
			retry();
			return false;
		}
		else {
			SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
			account = sp.getString("account", "");
			passwd = sp.getString("passwd", "");
			if (account.equals("") || passwd.equals("")) {
				Log.d("autologin", "account or passwd is empty");
				return false;
			}
			if (login()) {
				Log.d("autologin", "login succeed");
				return true;
			} else if (retry) {
				retry();
				return false;
			} else if (exceedError) {
				MainActivity.NicFragment.NicTask nicTask = MainActivity.NicFragment.newInstance(0).new NicTask(context, "offlineCurrentAndLogin");
				nicTask.foreground = foreground;
				nicTask.execute();
				return false;
			} else {
				Log.d("autologin", "login failed");
				return false;
			}
		}
	}

	protected void onPostExecute(Boolean result) {
		if (retry)
			return;
		SQLiteHelper db = new SQLiteHelper(context);

		if (result) {
			db.addLog("µÇ¼³É¹¦");
			Toast.makeText(context.getApplicationContext(),
					"AutoLogin: µÇ¼³É¹¦~", Toast.LENGTH_LONG)
					.show();
			WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
			sp.edit().putString("lastssid", wifi_service.getConnectionInfo().getSSID()).apply();
		} else if (retrys >= 3){
			Log.d("autologin", "retrys too many times");
			db.addLog("µÇ¼ʧ°Ü");
			if (foreground)
				Toast.makeText(context.getApplicationContext(),
						"AutoLogin: µÇ¼ʧ°Ü!", Toast.LENGTH_LONG).show();
			else
				showNotification("AutoLogin: µÇ¼ʧ°Ü");
		} else if (exceedError) {
			/* -> moved to MainActivity.NicFragment.NicTask offlineCurrentAndLogin
			db.addLog("²¢·¢µÇ¼³¬¹ý×î´óÏÞÖÆ ");
			Toast.makeText(context.getApplicationContext(),
					"AutoLogin: ²¢·¢µÇ¼³¬¹ý×î´óÏÞÖÆ !", Toast.LENGTH_LONG)
					.show();
					*/
		} else if (passwdError) {
			db.addLog("Óû§ÃûÃÜÂë´íÎó ");
			if (foreground)
				Toast.makeText(context.getApplicationContext(),
						"AutoLogin: Óû§ÃûÃÜÂë´íÎó !", Toast.LENGTH_LONG).show();
			else
				showNotification("AutoLogin: Óû§ÃûÃÜÂë´íÎó ");
		} else if (alreadyLoggedIn) {
			db.addLog("ÒѵǼ ");

			SharedPreferences sp = context.getSharedPreferences("userInfo", Context.MODE_PRIVATE);
			String lastssid = sp.getString("lastssid", "");

			WifiManager wifi_service = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
			String currentssid = wifi_service.getConnectionInfo().getSSID();

			if (!currentssid.equals(lastssid)) {
				Toast.makeText(context.getApplicationContext(),
						"AutoLogin: ÒѵǼ~", Toast.LENGTH_LONG)
						.show();
				sp.edit().putString("lastssid", currentssid).apply();
			}
		} else if (forbidden) {
			db.addLog("ûÓзÃÎÊȨÏÞ");
			Toast.makeText(context.getApplicationContext(),
					"AutoLogin: Ç×~Äú»¹Ã»ÓзÃÎʸÃÒ³ÃæµÄȨÏÞŶ£¡\nÐÝÏ¢~ÐÝϢһϣ¡", Toast.LENGTH_LONG)
					.show();
		}
	}

	public Boolean checkLogin() {
		try {
			HttpClient client = new DefaultHttpClient();
			URI website = new URI("https://w.seu.edu.cn/portal/init.php");
			HttpGet request = new HttpGet();
			request.setHeader("User-Agent", "Mozilla/5.0 (Android " + android.os.Build.VERSION.RELEASE + ") AutoLogin/" + version);
			request.setURI(website);
			HttpResponse response = client.execute(request);
			// int statusCode = response.getStatusLine().getStatusCode();

			String responseStr = EntityUtils.toString(response.getEntity());
			//Log.d("autologin", responseStr);
			if (responseStr.contains("login_username")) {
				alreadyLoggedIn = true;
				Log.d("autologin", "already logged in");
				return true;
			} else if (response.getStatusLine().getStatusCode() == 403) {
				forbidden = true;
				Log.d("autologin", "403 forbidden");
				return true;
			} else {
				// Log.d("autologin", "have not login");
				return false;
			}

		} catch (Exception e) {
			Log.d("checkLogin", "Error in http connection " + e.toString());
			retry = true;
			return false;
		}
	}

	public Boolean login() {
		try {
			HttpClient client = new DefaultHttpClient();
			URI website = new URI("https://w.seu.edu.cn/portal/login.php");
			HttpPost request = new HttpPost(website);
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
			nameValuePairs.add(new BasicNameValuePair("username", account));
			nameValuePairs.add(new BasicNameValuePair("password", passwd));
			request.setEntity(new UrlEncodedFormEntity(nameValuePairs));
			request.setHeader("User-Agent", "Mozilla/5.0 (Android " + android.os.Build.VERSION.RELEASE + ") AutoLogin/" + version);

			// Execute HTTP Post Request
			HttpResponse response = client.execute(request);
			int statusCode = response.getStatusLine().getStatusCode();

			if (statusCode == 200) {
				String responseStr = EntityUtils.toString(response.getEntity(), "UTF-8");
				//Log.d("autologin", "ÈÏÖ¤½á¹û  " + responseStr);
				if (responseStr.contains("login_username")) {
					//Log.d("autologin", "logged in " + String.valueOf(statusCode));
					return true;
				} else if (responseStr.contains("\\u5e76\\u53d1\\u767b\\u5f55\\u8d85\\u8fc7\\u6700\\u5927\\u9650\\u5236")) {
					Log.d("autologin", "error: \u5e76\u53d1\u767b\u5f55\u8d85\u8fc7\u6700\u5927\u9650\u5236");
					exceedError = true;
				} else if (responseStr.contains("\\u7528\\u6237\\u540d\\u5bc6\\u7801\\u9519\\u8bef")) {
					Log.d("autologin", "error: \u7528\u6237\u540d\u5bc6\u7801\u9519\u8bef");
					passwdError = true;
				}
				return false;
			} else {
				Log.d("autologin", "logged failed, statusCode:" + String.valueOf(statusCode));
				return false;
			}
		} catch (Exception e) {
			Log.d("login", "Error in http connection " + e.toString());
			retry = true;
			return false;
		}
	}

	public void retry() {
		if (retrys < 3) {
			Log.d("autologin", "retrys " + String.valueOf(retrys));
			String UNIQUE_STRING = "com.cedar.autologin.unknownhostBroadcast";
			Intent intent = new Intent(UNIQUE_STRING);
			intent.putExtra("retrys", String.valueOf(retrys));
			if (foreground)
				intent.putExtra("foreground", "true");
			context.sendBroadcast(intent);
		} else
			retry = false;
	}

	public void showNotification(String content) {

		int notifyId = 1;
		NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context);

		if (mNotificationManager == null || mBuilder == null)
			return;

		mBuilder.setContentTitle(content)
		.setTicker(content)
		.setAutoCancel(true)
		.setSmallIcon(R.drawable.ic_launcher);;

		Intent resultIntent = new Intent(context, MainActivity.class);
		resultIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
		PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
		mBuilder.setContentIntent(pendingIntent);
		mNotificationManager.notify(notifyId, mBuilder.build());
	}
}


text:
package com.google.cloud.pubsub.v1;

import com.google.api.gax.rpc.ApiException;
import io.grpc.Status;

/** Utilities for handling gRPC {@link Status}. */
final class StatusUtil {
  private StatusUtil() {
    // Static class, not instantiable.
  }

  public static boolean isRetryable(Throwable error) {
    if (!(error instanceof ApiException)) {
      return true;
    }
    ApiException apiException = (ApiException) error;
    switch (apiException.getStatusCode().getCode()) {
      case DEADLINE_EXCEEDED:
      case INTERNAL:
      case CANCELLED:
      case RESOURCE_EXHAUSTED:
      case ABORTED:
        return true;
      case UNAVAILABLE:
        // TODO(pongad): check that ApiException propagate message properly.
        return !apiException.getMessage().contains("Server shutdownNow invoked");
      default:
        return false;
    }
  }
}


text:
using namespace rapidjson;

namespace chrono {
namespace vehicle {

// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
TrackShoeDoublePin::TrackShoeDoublePin(const std::string& filename) : ChTrackShoeDoublePin("") {
    Document d; ReadFileJSON(filename, d);
    if (d.IsNull())
        return;

    Create(d);

    GetLog() << "Loaded JSON: " << filename.c_str() << "\n";
}

TrackShoeDoublePin::TrackShoeDoublePin(const rapidjson::Document& d) : ChTrackShoeDoublePin("") {
    Create(d);
}

void TrackShoeDoublePin::Create(const rapidjson::Document& d) {
    // Invoke base class method.
    ChPart::Create(d);

    // Read shoe body geometry and mass properties
    assert(d.HasMember("Shoe"));

    m_shoe_length = d["Shoe"]["Length"].GetDouble();
    m_shoe_width = d["Shoe"]["Width"].GetDouble();
    m_shoe_height = d["Shoe"]["Height"].GetDouble();
    m_shoe_mass = d["Shoe"]["Mass"].GetDouble();
    m_shoe_inertia = ReadVectorJSON(d["Shoe"]["Inertia"]);

    // Read location of guide pin center (for detracking control)
    m_pin_center = ReadVectorJSON(d["Guide Pin Center"]);

    // Read connector body geometry and mass properties
    assert(d.HasMember("Connector"));
    m_connector_radius = d["Connector"]["Radius"].GetDouble();
    m_connector_length = d["Connector"]["Length"].GetDouble();
    m_connector_width = d["Connector"]["Width"].GetDouble();
    m_connector_mass = d["Connector"]["Mass"].GetDouble();
    m_connector_inertia = ReadVectorJSON(d["Connector"]["Inertia"]);

    // Read contact geometry data
    assert(d.HasMember("Contact"));
    assert(d["Contact"].HasMember("Connector Material"));
    assert(d["Contact"].HasMember("Shoe Materials"));
    assert(d["Contact"].HasMember("Shoe Shapes"));
    assert(d["Contact"]["Shoe Materials"].IsArray());
    assert(d["Contact"]["Shoe Shapes"].IsArray());

    // Read contact material information (defer creating the materials until CreateContactMaterials)

    m_cyl_mat_info = ReadMaterialInfoJSON(d["Contact"]["Connector Material"]);

    int num_mats = d["Contact"]["Shoe Materials"].Size();
    for (int i = 0; i < num_mats; i++) {
        MaterialInfo minfo = ReadMaterialInfoJSON(d["Contact"]["Shoe Materials"][i]);
        m_shoe_mat_info.push_back(minfo);
    }

    // Read geometric collison data

    int num_shapes = d["Contact"]["Shoe Shapes"].Size();

    for (int i = 0; i < num_shapes; i++) {
        const Value& shape = d["Contact"]["Shoe Shapes"][i];

        std::string type = shape["Type"].GetString();
        int matID = shape["Material Index"].GetInt();
        assert(matID >= 0 && matID < num_mats);

        if (type.compare("SPHERE") == 0) {
            ChVector<> pos = ReadVectorJSON(shape["Location"]);
            double radius = shape["Radius"].GetDouble();
            m_geometry.m_coll_spheres.push_back(ChVehicleGeometry::SphereShape(pos, radius, matID));
        } else if (type.compare("BOX") == 0) {
            ChVector<> pos = ReadVectorJSON(shape["Location"]);
            ChQuaternion<> rot = ReadQuaternionJSON(shape["Orientation"]);
            ChVector<> dims = ReadVectorJSON(shape["Dimensions"]);
            m_geometry.m_coll_boxes.push_back(ChVehicleGeometry::BoxShape(pos, rot, dims, matID));
        } else if (type.compare("CYLINDER") == 0) {
            ChVector<> pos = ReadVectorJSON(shape["Location"]);
            ChQuaternion<> rot = ReadQuaternionJSON(shape["Orientation"]);
            double radius = shape["Radius"].GetDouble();
            double length = shape["Length"].GetDouble();
            m_geometry.m_coll_cylinders.push_back(ChVehicleGeometry::CylinderShape(pos, rot, radius, length, matID));
        } else if (type.compare("HULL") == 0) {
            std::string filename = shape["Filename"].GetString();
            m_geometry.m_coll_hulls.push_back(ChVehicleGeometry::ConvexHullsShape(filename, matID));
        } else if (type.compare("MESH") == 0) {
            std::string filename = shape["Filename"].GetString();
            ChVector<> pos = ReadVectorJSON(shape["Location"]);
            double radius = shape["Contact Radius"].GetDouble();
            m_geometry.m_coll_meshes.push_back(ChVehicleGeometry::TrimeshShape(pos, filename, radius, matID));
        }
    }

    m_geometry.m_has_collision = true;

    // Read visualization data

    if (d.HasMember("Visualization")) {
        if (d["Visualization"].HasMember("Mesh")) {
            m_geometry.m_vis_mesh_file = d["Visualization"]["Mesh"].GetString();
            m_geometry.m_has_mesh = true;
        }

        if (d["Visualization"].HasMember("Primitives")) {
            assert(d["Visualization"]["Primitives"].IsArray());
            num_shapes = d["Visualization"]["Primitives"].Size();
            for (int i = 0; i < num_shapes; i++) {
                const Value& shape = d["Visualization"]["Primitives"][i];
                std::string type = shape["Type"].GetString();
                if (type.compare("SPHERE") == 0) {
                    ChVector<> pos = ReadVectorJSON(shape["Location"]);
                    double radius = shape["Radius"].GetDouble();
                    m_geometry.m_vis_spheres.push_back(ChVehicleGeometry::SphereShape(pos, radius));
                } else if (type.compare("BOX") == 0) {
                    ChVector<> pos = ReadVectorJSON(shape["Location"]);
                    ChQuaternion<> rot = ReadQuaternionJSON(shape["Orientation"]);
                    ChVector<> dims = ReadVectorJSON(shape["Dimensions"]);
                    m_geometry.m_vis_boxes.push_back(ChVehicleGeometry::BoxShape(pos, rot, dims));
                } else if (type.compare("CYLINDER") == 0) {
                    ChVector<> pos = ReadVectorJSON(shape["Location"]);
                    ChQuaternion<> rot = ReadQuaternionJSON(shape["Orientation"]);
                    double radius = shape["Radius"].GetDouble();
                    double length = shape["Length"].GetDouble();
                    m_geometry.m_vis_cylinders.push_back(ChVehicleGeometry::CylinderShape(pos, rot, radius, length));
                }
            }
            m_geometry.m_has_primitives = true;
        }
    } else {
        // Default to using the collision shapes
        for (auto& box : m_geometry.m_coll_boxes) {
            m_geometry.m_vis_boxes.push_back(box);
        }
        for (auto& cyl : m_geometry.m_coll_cylinders) {
            m_geometry.m_vis_cylinders.push_back(cyl);
        }
    }
}

void TrackShoeDoublePin::CreateContactMaterials(ChContactMethod contact_method) {
    m_shoe_sprk_material = m_cyl_mat_info.CreateMaterial(contact_method);

    for (auto minfo : m_shoe_mat_info) {
        m_geometry.m_materials.push_back(minfo.CreateMaterial(contact_method));
    }
}

}  // end namespace vehicle
}  // end namespace chrono


text:
namespace ElephantBookStore.Data.Contracts
{
	using System.Collections.Generic;
	using ElephantBookStore.Data.Models;

	public interface ICategory
	{
		string CategoryName { get; set; }

		bool IsDeleted { get; set; }

		ProductType ProductType { get; set; }

		ICollection<Item> Items { get; set; }
	}
}


text:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

            Open source Restful Api integrated testing tool

            {{name}},thank your for using HitchhikerAPI。

 follow this link to complete your register

            {{url}}

 kind send email to us if any problem support@hitchhiker-api.com

                website:  http://www.hitchhiker-api.com/

                github: http://www.github.com/brookshi/hitchhiker/

This mail is auto generated, please don't reply.


text:
/**
 *
 */
package com.cisco.oss.foundation.logging.converters;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.pattern.LoggingEventPatternConverter;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @author Yair Ogen
 *
 */
public final class FoundationLoggingCompInstNamePatternConverter extends LoggingEventPatternConverter {

	public static String componentInstanceName = getComponentInstanceName();

	/**
	 * Private constructor.
	 *
	 */
	private FoundationLoggingCompInstNamePatternConverter() {
		super("compInstanceName", "compInstanceName");

	}

	/**
	 * Gets an instance of the class.
	 *
	 * @param options
	 *            pattern options, may be null. If first element is "short",
	 *            only the first line of the throwable will be formatted.
	 * @return instance of class.
	 */
	public static FoundationLoggingCompInstNamePatternConverter newInstance(final String[] options) {
		return new FoundationLoggingCompInstNamePatternConverter();
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void format(final LoggingEvent event, final StringBuffer toAppendTo) {
		toAppendTo.append(componentInstanceName);

	}

	/**
	 * This converter obviously handles throwables.
	 *
	 * @return true.
	 */
	@Override
	public boolean handlesThrowable() {
		return false;
	}

	private static String getComponentInstanceName() {
		String compInstName = System.getProperty("app.name");

		if(StringUtils.isBlank(compInstName)){
			compInstName = FoundationLoggingCompNamePatternConverter.componentName + "Instance1";
		}

		return compInstName;
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
J. Linn. Soc. , Bot. 18:196. 1880

#### Original name
null

### Remarks
null


text:
Basic commands
==============

Serverspecs ''command'' resource type is the most basic way to build a specification by querying hosts about facts, in this example 'uname'.

It is straightforward but offers no abstraction or operating system independence.


text:
#import <DevToolsCore/PBXGroup.h>

@class PBXFileReference, PBXFileType;

@interface XCVersionGroup : PBXGroup
{
    PBXFileReference *_currentVersion;
    PBXFileType *_versionedFileType;
}

+ (id)archivableRelationships;
+ (id)archivableAttributes;
+ (id)versionGroupByWrappingReference:(id)arg1 usingPathExtension:(id)arg2;
+ (void)_replaceBuildFilesForReference:(id)arg1 withBuildFilesForReference:(id)arg2;
- (void)willMoveItem:(id)arg1 toGroup:(id)arg2;
- (void)didRemoveItem:(id)arg1;
- (void)didAddItem:(id)arg1;
- (void)willAddItem:(id)arg1;
- (void)awakeFromPListUnarchiver:(id)arg1;
- (BOOL)isVersionGroup;
- (BOOL)makeVersionWithName:(id)arg1;
- (BOOL)makeVersionWithName:(id)arg1 basedOnReference:(id)arg2;
- (id)versionForName:(id)arg1;
- (BOOL)ensureHasDefaultReference;
- (id)defaultReference;
- (void)setVersionGroupType:(id)arg1;
- (id)versionGroupType;
- (void)setVersionedFileType:(id)arg1;
- (id)versionedFileType;
- (id)fileType;
- (BOOL)saveCurrentVersion;
- (void)setCurrentVersion:(id)arg1;
- (id)currentVersion;
- (BOOL)allowsSubgroups;
- (void)configureFromOnDiskContents;
- (void)dealloc;
- (id)initWithName:(id)arg1 versionedFileType:(id)arg2 path:(id)arg3 sourceTree:(id)arg4;

@end


text:
/**
 * Provides an API for triggering the execution of Actions.
 */

package main

import (
	// Utilities.
	"net/http"

	// Gin.
	gin "gopkg.in/gin-gonic/gin.v1"

	// Internal dependencies.
	common "github.com/krystalcode/go-mantis-shrimp/actions/common"
	config "github.com/krystalcode/go-mantis-shrimp/actions/config"
	storage "github.com/krystalcode/go-mantis-shrimp/actions/storage"
	wrapper "github.com/krystalcode/go-mantis-shrimp/actions/wrapper"
	util "github.com/krystalcode/go-mantis-shrimp/util"
)

/**
 * Constants.
 */

// ActionAPIConfigFile holds the default path to the file containing the
// configuration for the Action API.
const ActionAPIConfigFile = "/etc/mantis-shrimp/action_api.config.json"

/**
 * Main program entry.
 */
func main() {
	// Load configuration.
	// @I Support providing configuration file for Action API via cli options
	// @I Validate Action API configuration when loading from JSON file
	var actionAPIConfig config.Config
	err := util.ReadJSONFile(ActionAPIConfigFile, &actionAPIConfig)
	if err != nil {
		panic(err)
	}

	// Load Actions provided in the config, if we run on ephemeral storage mode.
	loadEphemeralActions(&actionAPIConfig)

	router := gin.Default()

	// Make storage available to the controllers.
	router.Use(Storage(actionAPIConfig.Storage))

	// Version 1 of the Action API.
	v1 := router.Group("/v1")
	{
		// Create a new Action.
		v1.POST("/", v1Create)

		// Trigger execution of the action via its ID.
		v1.POST("/:ids/trigger", v1Trigger)
	}

	/**
	 * @I Make the Action API port configurable
	 */
	router.Run(":8888")
}

/**
 * Endpoint controllers.
 */

// v1Create provides an endpoint that creates a new Action based on the JSON
// object given in the request.
func v1Create(c *gin.Context) {
	/**
	 * @I Implement authentication of the caller
	 * @I Validate parameters per Action type
	 * @I Ensure the caller has the permissions to create Actions
	 * @I Log errors and send a 500 response instead of panicking
	 * @I Implement creating and triggering an Action in a single request
	 */

	// The parameters are provided as a JSON object in the request. Bind it to an
	// object of the corresponding type.
	var wrapper wrapper.ActionWrapper
	err := c.BindJSON(&wrapper)
	if err != nil {
		panic(err)
	}
	// @I Return 400 Bad Request if we are given no Action type in a Create request
	if wrapper.Action == nil {
		c.JSON(
			http.StatusBadRequest,
			gin.H{
				"status": http.StatusBadRequest,
			},
		)
		return
	}

	// Get the Action as an object of the appropriate type.
	action := wrapper.Action

	// Store the Action.
	storage := c.MustGet("storage").(storage.Storage)
	id, err := storage.Set(action)
	if err != nil {
		panic(err)
	}

	// All good.
	c.JSON(
		http.StatusOK,
		gin.H{
			"status": http.StatusOK,
			"id":     id,
		},
	)
}

// v1Trigger provides an endpoint that triggers the Actions given in the request
// by their ID.
func v1Trigger(c *gin.Context) {
	/**
	 * @I Implement authentication of the caller
	 * @I Does the id need any escaping?
	 * @I Ensure the caller has the permissions to trigger actions
	 * @I Consider allowing the caller to pass on the actions as well for being
	 *    able to avoid the extra database call
	 * @I Investigate whether we need our own response status codes
	 */

	// The "ids" parameter is required. We allow for multiple comma-separated
	// string IDs, so we need to convert them to an array of integer IDs.
	// We want to make sure that the caller makes the request they want to without
	// mistakes, so we do not trigger any Actions if there is any error, even in
	// one of the IDs.
	sIDs := c.Param("ids")
	aIDsInt, err := util.StringToIntegers(sIDs, ",")
	if err != nil {
		c.JSON(
			http.StatusNotFound,
			gin.H{
				"status": http.StatusNotFound,
			},
		)
		return
	}

	// Get the Actions with the requested IDs from storage.
	storage := c.MustGet("storage").(storage.Storage)

	var actions []*common.Action
	for iID := range aIDsInt {
		action, err := storage.Get(iID)
		if err != nil {
			panic(err)
		}

		// Return a Not Found response if there is no Action with such ID.
		if action == nil {
			c.JSON(
				http.StatusNotFound,
				gin.H{
					"status": http.StatusNotFound,
				},
			)
			return
		}

		// We could trigger the Action at this point, however we prefer to check
		// that all Actions exist first.
		actions = append(actions, action)
	}

	// Trigger executions of the Actions.
	// We only need to acknowledge that the Actions were triggered; we don't have
	// to for the execution to finish as this can take time.
	for _, pointer := range actions {
		go func() {
			action := *pointer
			// @I Log errors occurring during execution of Actions
			_ = action.Do()
		}()
	}

	// All good.
	c.JSON(
		http.StatusOK,
		gin.H{
			"status": http.StatusOK,
		},
	)
}

/**
 * Middleware.
 */

// Storage is a Gin middleware that makes available the Storage engine to the
// endpoint controllers.
func Storage(config map[string]interface{}) gin.HandlerFunc {
	return func(c *gin.Context) {
		storage, err := storage.Create(config)
		if err != nil {
			panic(err)
		}
		c.Set("storage", storage)
		c.Next()
	}
}

/**
 * Functions/types for internal use.
 */

// loadEphmeralActions checks if the storage engine is configured to run in
// "ephemeral" mode, and if so, it loads into it any Actions contained in the
// configuration file.
func loadEphemeralActions(actionAPIConfig *config.Config) {
	// @I Load init Actions directly in Redis via a script so that services don't
	//    have to be restarted together
	mode, ok := actionAPIConfig.Storage["mode"]
	if !ok || mode.(string) != "ephemeral" || actionAPIConfig.ActionWrappers == nil {
		return
	}

	storage, err := storage.Create(actionAPIConfig.Storage)
	if err != nil {
		panic(err)
	}

	for _, wrapper := range actionAPIConfig.ActionWrappers {
		_, err := storage.Set(wrapper.Action)
		if err != nil {
			panic(err)
		}
	}
}


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Mycol. Res. 109(2): 242 (2005)

#### Original name
Terfezia pfeilii Henn., 1895

### Remarks
null


text:
<!DOCTYPE html>
<title>Canvas test: security.pattern.image.fillStyle</title>

<link rel="stylesheet" href="../tests.css">

security.pattern.image.fillStyle

[show output]

Actual output:

<canvas id="c" class="output" width="100" height="50">
FAIL (fallback content)
</canvas>


text:
layout: post
microblog: true
audio:
photo:
date: 2011-03-18 23:17:31 -0600
guid: http://craigmcclellan.micro.blog/2011/03/19/t48976370591744000.html
---
Late night Steak and Shake with @Ryanwmitchell and @brianyak was a bad plan.  So bad for me and I can't sleep with all that sugar.


text:
module Rack
  module JsonSchema
    class Error < StandardError
      # @return [Array] Rack response
      def to_rack_response
        [status, headers, [body]]
      end

      private

      # @note Override this
      def status
        500
      end

      # @note Override this
      def id
        "internal_server_error"
      end

      def headers
        { "Content-Type" => "application/json; charset=utf-8" }
      end

      def body
        JSON.pretty_generate(id: id, message: message) + "\n"
      end
    end
  end
end


text:
require 'cocaine'

class Borealis
  class ImageConverter
    def initialize(image, size)
      @image = image
      @size = size || '50x50'
    end

    def read_image
      Cocaine::CommandLine.new(
        'convert',
        "#{@image} -resize #{@size} txt:-"
      ).run
    end

    def to_colors
      colors_for(read_image)
    end

    private

    def colors_for(data)
      lines = data.split("\n").drop(1)
      lines.map do |line|
        line = line.scan(/\(([\d+\s+,]+)\)/).flatten
        rgb_values = line.first.split(',').map { |value| value.to_i }

        Color.new(*rgb_values)
      end
    end
  end
end