text:
import prefixer from 'inline-style-prefixer/static';
import { isArray, convertToKebabCase } from './utils';

const splitDeclarations = obj => {
  return Object.keys(obj).map(k => ({
    key: convertToKebabCase(k),
    value: obj[k],
  }));
};

const flattenArrays = arr => {
  return arr.reduce((a, b) => a.concat(isArray(b) ? flattenArrays(b) : b), []);
};

const handleArrays = arr => {
  return arr.map(obj => {
    if (!isArray(obj.value)) {
      return obj;
    }

    if (obj.value.every(i => typeof i === 'string')) {
      return obj.value.map(v => ({ key: obj.key, value: v }));
    } else {
      return obj.value.map(v => handleArrays(splitDeclarations(v)));
    }
  });
};

const handleRecursion = arr => {
  return arr.map(obj => {
    if (typeof obj.value !== 'object') {
      return obj;
    }

    return {
      key: obj.key,
      value: formatRule(obj.value),
    };
  });
};

const handleMediaQueries = arr => {
  const isMediaQuery = str => str.startsWith('@media');
  if (!arr.some(r => isMediaQuery(r.key))) {
    return arr;
  }

  return arr.map(r => {
    if (!isMediaQuery(r.key)) {
      return r;
    }

    const recurse = val => {
      return val.map(v => {
        return typeof v.value === 'object'
          ? {
              key: v.key,
              value: recurse(v.value),
              query: r.key,
            }
          : v;
      });
    };

    return {
      key: r.key,
      value: recurse(r.value),
    };
  });
};

export const formatRule = styles => {
  return [styles]
    .map(prefixer)
    .map(splitDeclarations)
    .map(handleArrays)
    .map(flattenArrays)
    .map(handleRecursion)
    .map(handleMediaQueries)[0];
};


text:
//    nVLC
//
//    Author:  Roman Ginzburg
//
//    nVLC is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    nVLC is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//    GNU General Public License for more details.
//
// ========================================================================

using Declarations;
using LibVlcWrapper;
using System;
using System.Runtime.InteropServices;
using System.Security;

namespace Implementation.Loggers
{
    internal unsafe sealed class LogSubscriber : DisposableBase
    {
        private IntPtr m_instance;
        private LogCallback m_callback;
        private ILogger m_logger;
        private const int BUFFER_SIZE = 10240;

        public LogSubscriber(ILogger logger, IntPtr pInstance)
        {
            m_instance = pInstance;
            m_logger = logger;
            m_callback = OnLogCallback;
            IntPtr hCallback = Marshal.GetFunctionPointerForDelegate(m_callback);
            LibVlcMethods.libvlc_log_set(m_instance, hCallback, IntPtr.Zero);
        }

        private void OnLogCallback(void* data, libvlc_log_level level, void* ctx, char* fmt, char* args)
        {
            try
            {
                char* buffer = stackalloc char[BUFFER_SIZE];
                int len = vsprintf(buffer, fmt, args);
                string msg = Marshal.PtrToStringAnsi(new IntPtr(buffer), len);

                switch (level)
                {
                    case libvlc_log_level.LIBVLC_DEBUG:
                        m_logger.Debug(msg);
                        break;
                    case libvlc_log_level.LIBVLC_NOTICE:
                        m_logger.Info(msg);
                        break;
                    case libvlc_log_level.LIBVLC_WARNING:
                        m_logger.Warning(msg);
                        break;
                    case libvlc_log_level.LIBVLC_ERROR:
                    default:
                        m_logger.Error(msg);
                        break;
                }
            }
            catch (Exception ex)
            {
                m_logger.Error("Failed to handle log callback, reason : " + ex.Message);
            }
        }

        protected override void Dispose(bool disposing)
        {
            try
            {
                LibVlcMethods.libvlc_log_unset(m_instance);
            }
            catch (Exception)
            { }

            if (disposing)
            {
                m_callback = null;
            }
        }

        [DllImport("msvcrt", SetLastError = true, CallingConvention = CallingConvention.Cdecl)]
        [SuppressUnmanagedCodeSecurity]
        private static extern int vsprintf(char* str, char* format, char* arg);
    }
}

redpajama_set_name: RedPajamaGithub


text:
require("/org/bpmscript/bpmscript.js");

function KillHook() {
}
KillHook.prototype = {
  process: function(message) {
    log.info("kill hook called " + message);
  }
}

function Test() {}
Test.prototype = {

  /** call test **/
  autoStart: function(total) {
    this.channel.addKillHook(new KillHook());
    this.channel.reply({content: "STARTED"});
    while(true) {
      log.info("Sleeping One");
      this.channel.sleep(time.seconds(10));
    }
  }

}


text:
title: API Reference
newversionredirect: tools/api/
menu:
  influxdb_013:
    weight: 80
    parent: concepts
---

The InfluxDB API provides a simple way interact with the database.
It uses HTTP response codes, HTTP authentication, and responses are returned in
JSON.

The following sections assume your InfluxDB instance is running on `localhost`
port `8086` and HTTPS is not enabled.
Those settings [are configurable](/influxdb/v0.13/administration/config/).

## Endpoints

| Endpoint    | Description |
| :---------- | :---------- |
| [/ping](#ping) | Use `/ping` to check the status of your InfluxDB instance and your version of InfluxDB. |
| [/query](#query) | Use `/query` to query data and manage databases, retention policies, and users. |
| [/write](#write) | Use `/write` to write data to a pre-existing database. |

### /ping

The ping endpoint accepts both `GET` and `HEAD` HTTP requests.
Use this endpoint to check the status of your InfluxDB instance and your version
of InfluxDB.

#### Definition
```
GET http://localhost:8086/ping
```
```
HEAD http://localhost:8086/ping
```

#### Example

Extract the version of your InfluxDB instance in the `X-Influxdb-Version` field
of the header:
```bash
$ curl -sl -I localhost:8086/ping

HTTP/1.1 204 No Content
Request-Id: 7d641f0b-e23b-11e5-8005-000000000000
X-Influxdb-Version: 0.13.x
Date: Fri, 04 Mar 2016 19:01:23 GMT
```

#### Status Codes and Responses

The response body is empty.

| HTTP Status Code   | Description    |
| :----------------- | :------------- |
| 204      | Success! Your InfluxDB instance is up and running.      |

### /query

The `/query` endpoint accepts `GET` and `POST` HTTP requests.
Use this endpoint to query data and manage databases, retention policies,
and users.

#### Definition

```
GET http://localhost:8086/query
```
```
POST http://localhost:8086/query
```

#### Verb usage

| Verb  | Query Type |
| :---- | :--------- |
| GET   | Use for all queries that start with:

 [`SELECT`](/influxdb/v0.13/query_language/spec/#select)*

 [`SHOW`](/influxdb/v0.13/query_language/spec/#show-continuous-queries)   |
| POST  | Use for all queries that start with:

 [`ALTER`](/influxdb/v0.13/query_language/spec/#alter-retention-policy)

 [`CREATE`](/influxdb/v0.13/query_language/spec/#create-continuous-query)

 [`DELETE`](/influxdb/v0.13/query_language/spec/#delete)

 [`DROP`](/influxdb/v0.13/query_language/spec/#drop-continuous-query)

 [`GRANT`](/influxdb/v0.13/query_language/spec/#grant)

 [`KILL`](/influxdb/v0.13/query_language/spec/#kill-query)

 [`REVOKE`](/influxdb/v0.13/query_language/spec/#revoke) |

\* The only exceptions are `SELECT` queries that include an [`INTO` clause](/influxdb/v0.13/query_language/data_exploration/#the-into-clause).
Those `SELECT` queries require a `POST` request.

#### Query String Parameters

| Query String Parameter | Optional/Required | Definition |
| :--------------------- | :---------------- |:---------- |
| chunk_size=\<number_of_points> | Optional | Set the number of points returned per batch. By default, InfluxDB returns points in batches of 10,000 points. |
| db=\<database_name> | Required for database-dependent queries (most [`SELECT`](/influxdb/v0.13/query_language/spec/#select) queries and [`SHOW`](/influxdb/v0.13/query_language/spec/#show-continuous-queries) queries require this parameter). | Sets the target [database](/influxdb/v0.13/concepts/glossary/#database) for the query. |
| epoch=[h,m,s,ms,u,ns] | Optional | Returns epoch timestamps with the specified precision. By default, InfluxDB returns timestamps in RFC3339 format with nanosecond precision. |
| p=\<password> | Optional if you haven't [enabled authentication](/influxdb/v0.13/administration/authentication_and_authorization/#set-up-authentication). Required if you've enabled authentication. | Sets the password for authentication if you've enabled authentication. Use with the query string parameter `u`. |
| pretty=true | Optional | Enables pretty-printed JSON output. While this is useful for debugging it is not recommended for production use as it consumes unnecessary network bandwidth. |
| rp=\<retention_policy_name> | Optional | Sets the target [retention policy](/influxdb/v0.13/concepts/glossary/#retention-policy-rp) for the query. InfluxDB queries the `DEFAULT` retention policy if you do not specify a retention policy.  |
| u=\<username> | Optional if you haven't [enabled authentication](/influxdb/v0.13/administration/authentication_and_authorization/#set-up-authentication). Required if you've enabled authentication. | Sets the username for authentication if you've enabled authentication. The user must have read access to the database. Use with the query string parameter `p`. |

#### Request Body

```
--data-urlencode "q=<InfluxQL query>"
```

All queries must be URL encoded and follow
[InfluxQL](/influxdb/v0.13/query_language/) syntax.
Our example shows the `--data-urlencode` parameter from `curl`, which we will
use in all examples on this page.

Delimit multiple queries with a semicolon.

#### Examples

Query data with a `SELECT` statement:
```
$ curl -GET 'http://localhost:8086/query?db=mydb' --data-urlencode 'q=SELECT * FROM "mymeas"'

{"results":[{"series":[{"name":"mymeas","columns":["time","myfield","mytag1","mytag2"],"values":[["2016-05-20T21:30:00Z",12,"1",null],["2016-05-20T21:30:20Z",11,"2",null],["2016-05-20T21:30:40Z",18,null,"1"],["2016-05-20T21:31:00Z",19,null,"3"]]}]}]}
```

Query data with a `SELECT` statement and an `INTO` clause:
```
$ curl -POST 'http://localhost:8086/query?db=mydb' --data-urlencode 'q=SELECT * INTO "newmeas" FROM "mymeas"'

{"results":[{"series":[{"name":"result","columns":["time","written"],"values":[["1970-01-01T00:00:00Z",4]]}]}]}
```

Query data with a `SELECT` statement and return pretty-printed JSON:
```
$ curl -GET 'http://localhost:8086/query?db=mydb&pretty=true' --data-urlencode 'q=SELECT * FROM "mymeas"'

{
    "results": [
        {
            "series": [
                {
                    "name": "mymeas",
                    "columns": [
                        "time",
                        "myfield",
                        "mytag1",
                        "mytag2"
                    ],
                    "values": [
                        [
                            "2016-05-20T21:30:00Z",
                            12,
                            "1",
                            null
                        ],
                        [
                            "2016-05-20T21:30:20Z",
                            11,
                            "2",
                            null
                        ],
                        [
                            "2016-05-20T21:30:40Z",
                            18,
                            null,
                            "1"
                        ],
                        [
                            "2016-05-20T21:31:00Z",
                            19,
                            null,
                            "3"
                        ]
                    ]
                }
            ]
        }
    ]
}
```

Query data with a `SELECT` statement and return second precision epoch
timestamps:
```
$ curl -GET 'http://localhost:8086/query?db=mydb&epoch=s' --data-urlencode 'q=SELECT * FROM "mymeas"'

{"results":[{"series":[{"name":"mymeas","columns":["time","myfield","mytag1","mytag2"],"values":[[1463779800,12,"1",null],[1463779820,11,"2",null],[1463779840,18,null,"1"],[1463779860,19,null,"3"]]}]}]}
```

Create a database:
```
$ curl -POST 'http://localhost:8086/query' --data-urlencode 'q=CREATE DATABASE mydb'

{"results":[{}]}
```

Create a database using HTTP authentication:
```
$ curl -POST 'http://localhost:8086/query?u=myusername&p=mypassword' --data-urlencode 'q=CREATE DATABASE mydb'

{"results":[{}]}
```

Send multiple queries:
```
$ curl -GET 'http://localhost:8086/query?db=mydb&epoch=s' --data-urlencode 'q=SELECT * FROM "mymeas";SELECT mean("myfield") FROM "mymeas"'

{"results":[{"series":[{"name":"mymeas","columns":["time","myfield","mytag1","mytag2"],"values":[[1463779800,12,"1",null],[1463779820,11,"2",null],[1463779840,18,null,"1"],[1463779860,19,null,"3"]]}]},{"series":[{"name":"mymeas","columns":["time","mean"],"values":[[0,15]]}]}]}
```

#### Status codes and responses

Responses are returned in JSON.
Enable pretty-print JSON by including the query string parameter `pretty=true`.

##### Summary Table

| HTTP status code | Description |
| :--------------- | :---------- |
| 200 OK | Success! The returned JSON offers further information. |
| 400 Bad Request | Unacceptable request. Can occur with a syntactically incorrect query. The returned JSON offers further information. |

##### Examples

A successful request that returns data:
```
$ curl -i -GET 'http://localhost:8086/query?db=mydb' --data-urlencode 'q=SELECT * FROM "mymeas"'

HTTP/1.1 200 OK
[...]
{"results":[{"series":[{"name":"mymeas","columns":["time","myfield","mytag1","mytag2"],"values":[["2016-05-20T21:30:00Z",12,"1",null],["2016-05-20T21:30:20Z",11,"2",null],["2016-05-20T21:30:40Z",18,null,"1"],["2016-05-20T21:31:00Z",19,null,"3"]]}]}]}
```

A successful request that returns an error:
```
$ curl -i -GET 'http://localhost:8086/query?db=mydb1' --data-urlencode 'q=SELECT * FROM "mymeas"'

HTTP/1.1 200 OK
[...]
{"results":[{"error":"database not found: mydb1"}]}
```

An incorrectly formatted query:
```
$ curl -i -GET 'http://localhost:8086/query?db=mydb' --data-urlencode 'q=SELECT *'

HTTP/1.1 400 Bad Request
[...]
{"error":"error parsing query: found EOF, expected FROM at line 1, char 9"}
```

### /write

The `/write` endpoint accepts `POST` HTTP requests.
Use this endpoint to write data to a pre-existing database.

#### Definition

```
POST http://localhost:8086/write
```

#### Query String Parameters

| Query String Parameter | Optional/Required | Description |
| :--------------------- | :---------------- | :---------- |
| db=\<database> | Required | Sets the target [database](/influxdb/v0.13/concepts/glossary/#database) for the write. |
| p=\<password> | Optional if you haven't [enabled authentication](/influxdb/v0.13/administration/authentication_and_authorization/#set-up-authentication). Required if you've enabled authentication. | Sets the password for authentication if you've enabled authentication. Use with the query string parameter `u`. |
| precision=[n,u,ms,s,m,h] | Optional | Sets the precision for the supplied Unix time values. InfluxDB assumes that timestamps are in nanoseconds if you do not specify `precision`. |
| rp=\<retention_policy_name> | Optional | Sets the target [retention policy](/influxdb/v0.13/concepts/glossary/#retention-policy-rp) for the write. InfluxDB writes to the `DEFAULT` retention policy if you do not specify a retention policy. |
| u=\<username> | Optional if you haven't [enabled authentication](/influxdb/v0.13/administration/authentication_and_authorization/#set-up-authentication). Required if you've enabled authentication. | Sets the username for authentication if you've enabled authentication. The user must have write access to the database. Use with the query string parameter `p`. |

#### Request Body

```
--data-binary '<Data in Line Protocol format>'
```

All data must be binary encoded and in the
[Line Protocol](/influxdb/v0.13/concepts/glossary/#line-protocol) format.
Our example shows the `--data-binary` parameter from curl, which we will use in
all examples on this page.
Using any encoding method other than `--data-binary` will likely lead to issues;
`-d`, `--data-urlencode`, and `--data-ascii` may strip out newlines or
introduce new, unintended formatting.

Options:

* Write several points to the database with one request by separating each point
by a new line.
* Write points from a file with the `@` flag.
The file should contain a batch of points in the Line Protocol format.
Individual points must be on their own line and separated by newline characters
(`\n`).
Files containing carriage returns will cause parser errors.

    We recommend writing points in batches of 5,000 to 10,000 points.
Smaller batches, and more HTTP requests, will result in sub-optimal performance.

#### Examples

Write a point to the database `mydb` with a nanosecond timestamp:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb" --data-binary 'mymeas,mytag=1 myfield=90 1463683075000000000'
```

Write a point to the database `mydb` with the local server's nanosecond timestamp:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb" --data-binary 'mymeas,mytag=1 myfield=90'
```

Write a point to the database `mydb` with a timestamp in seconds:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb&precision=s" --data-binary 'mymeas,mytag=1 myfield=90 1463683075'
```

Write a point to the database `mydb` and the retention policy `myrp`:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb&rp=myrp" --data-binary 'mymeas,mytag=1 myfield=90'
```

Write a point to the database `mydb` using HTTP authentication:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb&u=myusername&p=mypassword" --data-binary 'mymeas,mytag=1 myfield=91'
```

Write several points to the database `mydb` by separating points with a new line:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb" --data-binary 'mymeas,mytag=3 myfield=89
mymeas,mytag=2 myfield=34 1463689152000000000'
```

Write several points to the database `mydb` from the file `data.txt`:
```
$ curl -i -POST "http://localhost:8086/write?db=mydb" --data-binary @data.txt
```

A sample of the data in `data.txt`:
```
mymeas,mytag1=1 value=21 1463689680000000000
mymeas,mytag1=1 value=34 1463689690000000000
mymeas,mytag2=8 value=78 1463689700000000000
mymeas,mytag3=9 value=89 1463689710000000000
```

#### Status codes and responses

In general, status codes of the form `2xx` indicate success, `4xx` indicate
that InfluxDB could not understand the request, and `5xx` indicate that the
system is overloaded or significantly impaired.
Errors are returned in JSON.

##### Summary Table

| HTTP status code | Description    |
| :--------------- | :------------- |
| 204 No Content   | Success!      |
| 400 Bad Request  | Unacceptable request. Can occur with a Line Protocol syntax error or if a user attempts to write values to a field that previously accepted a different value type. The returned JSON offers further information. |
| 404 Not Found    | Unacceptable request. Can occur if a user attempts to write to a database that does not exist. The returned JSON offers further information. |
| 500 Internal Server Error  | The system is overloaded or significantly impaired. Can occur if a user attempts to write to a retention policy that does not exist. The returned JSON offers further information. |

##### Examples

A successful write:
```
HTTP/1.1 204 No Content
```

Write a point with an incorrect timestamp:
```
HTTP/1.1 400 Bad Request
[...]
{"error":"unable to parse 'mymeas,mytag=1 myfield=91 abc123': bad timestamp"}
```

Write an integer to a field that previously accepted a float:
```
HTTP/1.1 400 Bad Request
[...]
{"error":"field type conflict: input field \"myfield\" on measurement \"mymeas\" is type int64, already exists as type float"}
```

Write a point to a database that doesn't exist:
```
HTTP/1.1 404 Not Found
[...]
{"error":"database not found: \"mydb1\""}
```

Write a point to a retention policy that doesn't exist:
```
HTTP/1.1 500 Internal Server Error
[...]
{"error":"retention policy not found: myrp"}
```


text:
package org.apache.geode.internal.cache.client.protocol;

import java.util.LinkedList;
import java.util.List;
import java.util.ServiceLoader;

import org.apache.geode.internal.cache.client.protocol.exception.ServiceLoadingFailureException;
import org.apache.geode.internal.cache.client.protocol.exception.ServiceVersionNotFoundException;

public class ClientProtocolServiceLoader {
  private final List<ClientProtocolService> clientProtocolServices;

  public ClientProtocolServiceLoader() {
    clientProtocolServices = initializeProtocolServices();
  }

  private static List<ClientProtocolService> initializeProtocolServices() {
    List<ClientProtocolService> resultList = new LinkedList<>();
    for (ClientProtocolService clientProtocolService : ServiceLoader
        .load(ClientProtocolService.class)) {
      resultList.add(clientProtocolService);
    }

    return resultList;
  }

  public ClientProtocolService lookupService() {
    if (clientProtocolServices.isEmpty()) {
      throw new ServiceLoadingFailureException(
          "There is no ClientProtocolService implementation found in JVM");
    }

    if (clientProtocolServices.size() > 1) {
      throw new ServiceLoadingFailureException(
          "There is more than one ClientProtocolService implementation found in JVM; aborting");
    }
    ClientProtocolService clientProtocolService = clientProtocolServices.get(0);
    return clientProtocolService;
  }
}


text:
import six
import inflection
from schematics import types
from schematics import models

class BetfairModelMeta(models.ModelMeta):
    """Set default `serialized_name` and `deserialize_from` of Schematics types
    to camel-cased attribute names.
    """
    def __new__(meta, name, bases, attrs):
        for name, attr in six.iteritems(attrs):
            if isinstance(attr, types.BaseType):
                camelized = inflection.camelize(name, uppercase_first_letter=False)
                attr.serialized_name = attr.serialized_name or camelized
                attr.deserialize_from = attr.deserialize_from or camelized
        return super(BetfairModelMeta, meta).__new__(meta, name, bases, attrs)

class BetfairModel(six.with_metaclass(BetfairModelMeta, models.Model)):

    def __init__(self, **data):
        super(BetfairModel, self).__init__()
        self.import_data(data)

    def import_data(self, data, **kwargs):
        kwargs['strict'] = False
        return super(BetfairModel, self).import_data(data, **kwargs)


text:
/* eslint-disable no-unused-vars */
import { h } from 'hyperapp'

export const LeafletMap = ({ actions }) =>
  <div id='map' oncreate={actions.renderMap}>
    {' '}
  </div>


text:
package org.cluj.bus.pojo;

public class TripInfo
{
    private String busId;

    private String tripId;

    public String getBusId()
    {
        return busId;
    }

    public void setBusId(String busId)
    {
        this.busId = busId;
    }

    public String getTripId()
    {
        return tripId;
    }

    public void setTripId(String tripId)
    {
        this.tripId = tripId;
    }
}


text:
current_dir() {
    local sdir="$1"
    local udir=""
    # Resolve ${sdir} until the file is no longer a symlink
    while [ -h "${sdir}" ]; do
        udir="$(cd -P "$(dirname "${sdir}")" && pwd)"
        sdir="$(readlink "${sdir}")"
        # If ${sdir} was a relative symlink, we need to resolve it
        # relative to the path where the symlink file was located
        [[ "${sdir}" != /* ]] && sdir="${udir}/${sdir}"
    done
    udir="$(cd -P "$(dirname "${sdir}")" && pwd)"
    echo "${udir}"
}

### Unofficial strict mode
set -euo pipefail
IFS=$'\n\t'

### Processing
cwd=${PWD}
print_banner=0
finish() {
    if [ "${print_banner}" == 0 ]; then
        echo "Cleaning up..."
        print_banner=1
    fi
    cd "${cwd}" || exit 1
    exit "${1:-1}"
}
sdir=$(current_dir "${BASH_SOURCE[0]}")
# Configure Git user name and email
email=0
personal_repo=0
cfg_fname="${sdir}/repo-cfg.sh"
if [ -f "${cfg_fname}" ]; then
    # shellcheck disable=SC1090,SC1091
    source "${sdir}/repo-cfg.sh"
else
    echo "Using default repo config"
fi
if [ "${email}" == 1 ]; then
    if [ "${personal_repo}" == 1 ]; then
        if [ "${PERSONAL_NAME}" != "" ] && [ "${PERSONAL_EMAIL}" != "" ]; then
            echo "Configuring personal Git author information"
            git config user.name "${PERSONAL_NAME}"
            git config user.email "${PERSONAL_EMAIL}"
        fi
    else
        if [ "${WORK_NAME}" != "" ] && [ "${WORK_EMAIL}" != "" ]; then
            echo "Configuring work Git author information"
            git config user.name "${WORK_NAME}"
            git config user.email "${WORK_EMAIL}"
        fi
    fi
fi
repo_dir=$(dirname "${sdir}")
# Use pre-commit framework if possible
hooks=('pre-commit')
if [ -f "${repo_dir}/.pre-commit-config.yaml" ]; then
    if which pre-commit &> /dev/null; then
        cd "${repo_dir}" || exit 1
        echo "Setting up pre-commit framework"
        pre-commit install
    fi
    hooks=()
fi
gname="$(basename "$(git rev-parse --show-toplevel)")"
if [ "${gname}" == "pypkg" ]; then
    hooks+=('post-merge')
fi
if [ "${#hooks[@]}" != 0 ]; then
    echo "Setting up shell hooks"
    git_hooks_dir="$(git rev-parse --git-dir)"/hooks
    cd "${git_hooks_dir}" || exit 1
    for hook in ${hooks[*]}; do
        echo "Setting ${hook} hook"
        ln -s -f "${sdir}/${hook}" "${hook}"
    done
fi


text:
<?php
namespace Karen;

use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;

interface ApplicationInterface
{
    public function __construct(Request $request = null, Response $response = null);
    public function addQueue(string $name, callable $callable);
    public function getQueues(): array;
    public function run();
    public function sendResponse();
}


text:
import plugin

class Plugin(plugin.Plugin):
    def register_commands(self):
        self.regexes = [
            ('\x01VERSION\x01', self.ctcp),
        ]

    def ctcp(self, message, args):
        """ Get version information. """
        self.irc.ctcp(message.source, 'VERSION', 'pyfoot; see %s' % self.conf[
            'web_url'], notice=True)


text:
//***************************************************
// 文件名(File Name):      CheckAdviceView.cs(审方UI层)
//
// 数据表(Tables):         nothing
// 视图(Views)               nothing
//
// 作者(Author):           郭婷
//
// 日期(Create Date):     2013.1.21
//***************************************************
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Base;
using CJia.PIVAS.Views;
using CJia;

namespace CJia.PIVAS.App.UI
{
    /// <summary>
    /// 医嘱状态枚举类
    /// </summary>
    public enum AdviceStatus
    {
        待审 = 1000101,
        已审 = 1000102,
        不予配药 = 1000103,
        拒绝 = 1000104
    }
    /// <summary>
    /// 审方
    /// </summary>
    public partial class CheckAdviceView : Tools.View, Views.ICheckAdviceView
    {
        /// <summary>
        /// 审方构造函数
        /// </summary>
        public CheckAdviceView()
        {
            InitializeComponent();
            Init();
            //btnRefresh_Click(null, null);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        private void Init()
        {
            OnInitLoad(null, null);
            CheckOffice();
            deBeginDate.EditValue = CJia.PIVAS.Models.PIVASModel.QuerySysdate().Date;
            deEndDate.EditValue = CJia.PIVAS.Models.PIVASModel.QuerySysdate();
            //rgAdviceState.EditValue = "未审";
        }

        //重载CreatePresenter函数
        protected override object CreatePresenter()
        {
            return new Presenters.CheckAdvicePresenter(this);
        }

        // 定义审方参数
        Views.CheckAdviceArgs checkAdviceArgs = new Views.CheckAdviceArgs();

        #region ICheckAdviceView成员
        /// <summary>
        /// 初始化事件
        /// </summary>
        public event EventHandler OnInitLoad;

        /// <summary>
        /// 刷新医嘱事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnRefresh;

        /// <summary>
        /// 单个通过事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnInsertCheck;

        /// <summary>
        /// 取消审核事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnCancelCheck;

        /// <summary>
        /// 拒绝医嘱事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnRefuseCheck;

        /// <summary>
        /// 查询病人信息事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnPatient;

        /// <summary>
        /// 查询病史资料事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnPatientHistory;

        /// <summary>
        /// 审方完成事件
        /// </summary>
        public event EventHandler<Views.CheckAdviceArgs> OnComplete;

        /// <summary>
        /// 绑定可进配置中心的所有病区
        /// </summary>
        /// <param name="data"></param>
        public void ExeBindOffice(DataTable data)
        {
            cbOffice.DataSource = data;
            if (data == null) return;
            DataRow dr = data.NewRow();
            dr["office_id"] = "0";
            dr["office_name"] = "<--全部-->";
            data.Rows.InsertAt(dr, 0);
            cbOffice.DisplayMember = "office_name";
            cbOffice.ValueMember = "office_id";
        }

        /// <summary>
        /// 绑定所有未审医嘱
        /// </summary>
        /// <param name="data"></param>
        public void ExeGetAllNoCheckAdvice(DataTable data)
        {
            gcAdvice.DataSource = data;
            gvAdvice.ExpandAllGroups();
        }

        /// <summary>
        /// 绑定医嘱
        /// </summary>
        /// <param name="data"></param>
        public void ExeGetAdvice(DataTable dtAdvice)
        {
            gcAdvice.DataSource = dtAdvice;
            if (dtAdvice == null)
            {
                btnSingleOk.Enabled = btnCancelCheck.Enabled = btnRefuseAdvice.Enabled = btnUpdateBatch.Enabled = btnRefuseDosage.Enabled = btnPatient.Enabled = btnPatientHistory.Enabled = btnComplete.Enabled = false;
                mbtnSingleOk.Enabled = mbtnCancelCheck.Enabled = mbtnRefuseAdvice.Enabled = mbtnUpdateBatch.Enabled = mbtnRefuseDosage.Enabled = mbtnPatient.Enabled = mbtnPatientHistory.Enabled = mbtnComplete.Enabled = false;
            }
            else
            {
                btnPatient.Enabled = btnPatientHistory.Enabled = true;
                mbtnPatient.Enabled = mbtnPatientHistory.Enabled = true;
            }
            gvAdvice.ExpandAllGroups();
        }

        ///// <summary>
        ///// 绑定需要插入的待审医嘱
        ///// </summary>
        ///// <param name="dtBatchData"></param>
        //public void ExeGetBatchData(DataTable dtBatchData)
        //{
        //    gcAdvice.DataSource = dtBatchData;
        //    if (dtBatchData == null)
        //    {
        //        btnComplete.Enabled = false;
        //        mbtnComplete.Enabled = false;
        //    }
        //    else
        //    {
        //        btnComplete.Enabled = true;
        //        mbtnComplete.Enabled = true;
        //    }
        //    gvAdvice.ExpandAllGroups();
        //}

        /// <summary>
        /// 绑定病人信息
        /// </summary>
        /// <param name="data"></param>
        public void ExeBindPatient(DataTable data)
        {
            PatientView patientView = new PatientView(data);
            this.ShowAsWindow("病人信息", patientView);
        }

        /// <summary>
        /// 绑定病史资料
        /// </summary>
        /// <param name="data"></param>
        public void ExeBindPatientHistory(DataTable data)
        {
            //重复利用,可用临时变量代替
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            string patientName = drFocus["PATIENT_NAME"].ToString();
            string inhosId = drFocus["INHOS_ID"].ToString();
            string illfieldName = drFocus["PATIENT_ILLFILED_NAME"].ToString();
            string officeName = drFocus["PATIENT_OFFICE_NAME"].ToString();
            string bedName = drFocus["BED_NAME"].ToString();
            PatientHistoryView patientHistory = new PatientHistoryView(patientName, inhosId, illfieldName, officeName, bedName, data);
            this.ShowAsWindow("病史资料", patientHistory);
        }

        #endregion

        #region 自定义函数
        /// <summary>
        /// 判断病区是否有数据
        /// </summary>
        private void CheckOffice()
        {
            if (cbOffice.SelectedIndex < 0) return;
            else
            {
                cbOffice.SelectedIndex = 0;
            }
        }

        /// <summary>
        /// 固定参数赋值
        /// </summary>
        private void AssignFixParam()
        {
            DateTime beginDate = DateTime.Parse(deBeginDate.EditValue.ToString());
            checkAdviceArgs.BeginListDate = beginDate;  //开始时间
            DateTime endDate = DateTime.Parse(deEndDate.EditValue.ToString());
            checkAdviceArgs.EndListDate = endDate;  //结束时间
            if (cbOffice.SelectedValue == null)
            {
                return;
            }
            checkAdviceArgs.OfficeID = cbOffice.SelectedValue.ToString();    //病区ID
        }

        /// <summary>
        /// 变化参数赋值
        /// </summary>
        private void AssignChangeParam()
        {
            //成组药品类别按钮是否选中 false标识未选,true标识选中
            if (ceHLY.Checked)
            {
                checkAdviceArgs.IsTypeHLY = true;
            }
            else
            {
                checkAdviceArgs.IsTypeHLY = false;
            }
            if (ceKSS.Checked)
            {
                checkAdviceArgs.IsTypeKSS = true;
            }
            else
            {
                checkAdviceArgs.IsTypeKSS = false;
            }
            if (ceSSD.Checked)
            {
                checkAdviceArgs.IsTypeSSD = true;
            }
            else
            {
                checkAdviceArgs.IsTypeSSD = false;
            }
            if (cePTY.Checked)
            {
                checkAdviceArgs.IsTypePTY = true;
            }
            else
            {
                checkAdviceArgs.IsTypePTY = false;
            }
        }

        /// <summary>
        /// 鼠标停留参数赋值
        /// </summary>
        private void MouseFocusParam()
        {
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            checkAdviceArgs.GroupIndex = drFocus["GROUP_INDEX"].ToString();
            checkAdviceArgs.OriginalPivasBatchNo = drFocus["ORIGINAL_PIVAS_BATCH_NO"].ToString();
            checkAdviceArgs.CheckPivasBatchNo = drFocus["CHECK_PIVAS_BATCH_NO"].ToString();
            checkAdviceArgs.CancelReason = drFocus["CANCEL_REASON"].ToString();
        }

        /// <summary>
        /// 获得原始医嘱状态
        /// </summary>
        /// <returns>返回原始医嘱状态</returns>
        private int GetOriginalCheckStatus()
        {
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            int originalCheckPivasStatus = 0;   //原始审核状态
            originalCheckPivasStatus = int.Parse(drFocus["CHECK_PIVAS_STATUS"].ToString());
            return originalCheckPivasStatus;
        }

        /// <summary>
        /// 判断审核状态
        /// </summary>
        private bool CheckAdviceStatus()
        {
            bool flag = true;
            int originalCheckPivasStatus = GetOriginalCheckStatus();
            if (originalCheckPivasStatus == 0)
            {
                MessageBox.Show("请先选择一行数据");
                flag = false;
            }
            if (originalCheckPivasStatus == (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "已审", true))
            {
                MessageBox.Show("已审核");
                flag = false;
            }
            if (originalCheckPivasStatus == (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "不予配药", true))
            {
                MessageBox.Show("已拒绝配药");
                flag = false;
            }
            if (originalCheckPivasStatus == (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "拒绝", true))
            {
                MessageBox.Show("已拒绝医嘱");
                flag = false;
            }
            return flag;
        }
        /// <summary>
        /// 判断是否可以撤销审核
        /// </summary>
        private bool IsCanCancelCheck()
        {
            bool flag = true;
            int originalCheckPivasStatus = GetOriginalCheckStatus();
            if (originalCheckPivasStatus == 0)
            {
                MessageBox.Show("请先选择一行数据!");
                flag = false;
            }
            if (originalCheckPivasStatus == (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "待审", true))
            {
                MessageBox.Show("未审核,请先审核");
                flag = false;
            }
            return flag;
        }

        /// <summary>
        /// 根据选择所有、未审、已审按钮控制按钮是否可以点击
        /// </summary>
        private void CheckrgAdviceState()
        {
            if (rgAdviceState.EditValue.ToString() == "所有")
            {
                checkAdviceArgs.IsValidCheck = checkAdviceArgs.IsNoCheck = checkAdviceArgs.IsYesCheck = false;
                checkAdviceArgs.IsAllCheck = btnSingleOk.Enabled = btnCancelCheck.Enabled = btnRefuseAdvice.Enabled = btnRefuseDosage.Enabled = btnUpdateBatch.Enabled = btnComplete.Enabled = true;
                mbtnSingleOk.Enabled = mbtnRefuseAdvice.Enabled = mbtnRefuseDosage.Enabled = mbtnUpdateBatch.Enabled = mbtnComplete.Enabled = mbtnCancelCheck.Enabled = true;
            }
            else if (rgAdviceState.EditValue.ToString() == "未审")
            {
                checkAdviceArgs.IsValidCheck = checkAdviceArgs.IsAllCheck = checkAdviceArgs.IsYesCheck = btnCancelCheck.Enabled = btnUpdateBatch.Enabled = false;
                mbtnCancelCheck.Enabled = mbtnUpdateBatch.Enabled = false;
                checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "待审", true);
                checkAdviceArgs.IsNoCheck = btnSingleOk.Enabled = btnRefuseAdvice.Enabled = btnRefuseDosage.Enabled = btnComplete.Enabled = true;
                mbtnSingleOk.Enabled = mbtnRefuseAdvice.Enabled = mbtnRefuseDosage.Enabled = mbtnComplete.Enabled = true;
            }
            else if (rgAdviceState.EditValue.ToString() == "已审")
            {
                checkAdviceArgs.IsValidCheck = checkAdviceArgs.IsAllCheck = checkAdviceArgs.IsNoCheck = btnSingleOk.Enabled = btnRefuseAdvice.Enabled = btnRefuseDosage.Enabled = btnComplete.Enabled = false;
                mbtnSingleOk.Enabled = mbtnRefuseAdvice.Enabled = mbtnRefuseDosage.Enabled = mbtnComplete.Enabled = false;
                checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "已审", true);
                checkAdviceArgs.IsYesCheck = btnCancelCheck.Enabled = btnUpdateBatch.Enabled = true;
                mbtnCancelCheck.Enabled = mbtnUpdateBatch.Enabled = true;
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        public void NewRefresh()
        {
            if (ceInvalidAdvice.Checked)//无效
            {
                //参数
                checkAdviceArgs.IsValidCheck = true;
                checkAdviceArgs.IsAllCheck = checkAdviceArgs.IsYesCheck = checkAdviceArgs.IsNoCheck = false;
                //控制按钮显示隐藏
                rgAdviceState.Enabled = ceHLY.Enabled = ceKSS.Enabled = ceSSD.Enabled = cePTY.Enabled = btnSingleOk.Enabled = btnRefuseAdvice.Enabled = btnRefuseDosage.Enabled = btnUpdateBatch.Enabled = btnComplete.Enabled = false;
                mbtnSingleOk.Enabled = mbtnRefuseAdvice.Enabled = mbtnRefuseDosage.Enabled = mbtnUpdateBatch.Enabled = mbtnComplete.Enabled = false;
                btnCancelCheck.Enabled = true;
                mbtnCancelCheck.Enabled = true;
                //执行方法
                AssignFixParam();
                AssignChangeParam();
                if (OnRefresh != null)
                {
                    OnRefresh(null, checkAdviceArgs);
                }
            }
            else
            {
                rgAdviceState.Enabled = ceHLY.Enabled = ceKSS.Enabled = ceSSD.Enabled = cePTY.Enabled = true;
                RGAdviceStateChange();
            }
        }

        /// <summary>
        /// //所有、已审、未审按钮改变事件
        /// </summary>
        public void RGAdviceStateChange()
        {
            CheckrgAdviceState();
            AssignFixParam();
            AssignChangeParam();
            if (OnRefresh != null)
            {
                OnRefresh(null, checkAdviceArgs);
            }
        }

        /// <summary>
        /// 单个通过
        /// </summary>
        public void SingleOk()
        {
            if (CheckAdviceStatus())
            {
                MouseFocusParam();
                checkAdviceArgs.OriginalPivasStatus = GetOriginalCheckStatus();
                checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "已审", true);
                if (OnInsertCheck != null)
                {
                    OnInsertCheck(null, checkAdviceArgs);
                }
                NewRefresh();
            }
        }

        /// <summary>
        /// 撤销审核
        /// </summary>
        public void CancelCheck()
        {
            if (IsCanCancelCheck())
            {
                MouseFocusParam();
                if (CJia.PIVAS.Tools.Message.ShowQuery("是否确认撤销审核", CJia.PIVAS.Tools.Message.Button.YesNo) == CJia.PIVAS.Tools.Message.Result.Yes)
                {
                    checkAdviceArgs.OriginalPivasStatus = GetOriginalCheckStatus();
                    checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "待审", true);
                    if (OnCancelCheck != null)
                    {
                        OnCancelCheck(null, checkAdviceArgs);
                    }
                    NewRefresh();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 拒绝医嘱
        /// </summary>
        public void RefuseAdvice()
        {
            if (CheckAdviceStatus())
            {
                if (CJia.PIVAS.Tools.Message.ShowQuery("是否确认拒绝医嘱", CJia.PIVAS.Tools.Message.Button.YesNo) == CJia.PIVAS.Tools.Message.Result.Yes)
                {
                    MouseFocusParam();
                    checkAdviceArgs.OriginalPivasStatus = GetOriginalCheckStatus();
                    checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "拒绝", true);
                    if (OnRefuseCheck != null)
                    {
                        OnRefuseCheck(null, checkAdviceArgs);
                    }
                    NewRefresh();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 拒绝配药
        /// </summary>
        public void RefuseDosage()
        {
            if (CheckAdviceStatus())
            {
                if (CJia.PIVAS.Tools.Message.ShowQuery("是否确认拒绝配药", CJia.PIVAS.Tools.Message.Button.YesNo) == CJia.PIVAS.Tools.Message.Result.Yes)
                {
                    MouseFocusParam();
                    checkAdviceArgs.OriginalPivasStatus = GetOriginalCheckStatus();
                    checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "不予配药", true);
                    if (OnRefuseCheck != null)
                    {
                        OnRefuseCheck(null, checkAdviceArgs);
                    }
                    NewRefresh();
                }
                else
                {
                    return;
                }
            }
        }

        /// <summary>
        /// 修改批次
        /// </summary>
        public void UpdateBatch()
        {
            bool flag = true;
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            if (int.Parse(drFocus["CHECK_PIVAS_STATUS"].ToString()) != (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "已审", true))
            {
                MessageBox.Show("审核状态不符合要求!");
                flag = false;
            }
            string groupIndex = "0";
            string frequencyName = "";
            List<int> batchs = null;
            if (drFocus["GROUP_INDEX"].ToString() != null)
            {
                groupIndex = drFocus["GROUP_INDEX"].ToString();
            }
            else
            {
                MessageBox.Show("请先选择一行数据!");
                flag = false;
            }
            if (drFocus["FREQUENCY_NAME"].ToString() != null)
            {
                frequencyName = drFocus["FREQUENCY_NAME"].ToString();
            }
            else
            {
                MessageBox.Show("频率为空!");
                flag = false;
            }
            if (drFocus["CHECK_PIVAS_BATCH_NO"].ToString() != null)
            {
                batchs = CJia.PIVAS.Common.BatchHandle(drFocus["CHECK_PIVAS_BATCH_NO"].ToString());
            }
            else
            {
                MessageBox.Show("批次号为空!");
                flag = false;
            }
            if (flag)
            {
                CJia.PIVAS.App.UI.DataManage.EditFrequencyToBatchView editFrequencyBatch = new DataManage.EditFrequencyToBatchView(2, groupIndex, frequencyName, batchs);
                this.ShowAsWindow("病人信息", editFrequencyBatch);
                NewRefresh();
            }
        }

        /// <summary>
        /// 查询病史资料
        /// </summary>
        public void SelectPatientHistory()
        {
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            if (drFocus == null)
            {
                MessageBox.Show("请先选择一行数据!");
                return;
            }
            checkAdviceArgs.InhosId = drFocus["INHOS_ID"].ToString();
            if (OnPatientHistory != null)
            {
                OnPatientHistory(null, checkAdviceArgs);
            }
        }

        /// <summary>
        /// 查询病人信息
        /// </summary>
        public void SelectPatientInfo()
        {
            DataRow drFocus = gvAdvice.GetFocusedDataRow();
            if (drFocus == null)
            {
                MessageBox.Show("请先选择一行数据!");
                return;
            }
            checkAdviceArgs.InhosId = drFocus["INHOS_ID"].ToString();
            if (OnPatient != null)
            {
                OnPatient(null, checkAdviceArgs);
            }
        }

        /// <summary>
        /// 全部通过
        /// </summary>
        public void CompleteCheck()
        {
            AssignFixParam();
            checkAdviceArgs.CheckPivasStatus = (int)(AdviceStatus)Enum.Parse(typeof(AdviceStatus), "已审", true);
            if (OnComplete != null)
            {
                OnComplete(null, checkAdviceArgs);
            }
            NewRefresh();
        }

        ///// <summary>
        ///// 判断是否可以修改批次
        ///// </summary>
        //private bool IsCanUpdateBatch()
        //{
        //    bool flag = true;
        //    DataRow drFocus = gvAdvice.GetFocusedDataRow();
        //    if (int.Parse(drFocus["CHECK_PIVAS_STATUS"].ToString()) != int.Parse(AdviceStatus.已审.ToString()))
        //    {
        //        MessageBox.Show("审核状态不符合要求!");
        //        flag = false;
        //    }
        //    int groupIndex = 0;
        //    string frequencyName = "";
        //    List<int> batchs = null;
        //    if (drFocus["GROUP_INDEX"].ToString() != null)
        //    {
        //        groupIndex = int.Parse(drFocus["GROUP_INDEX"].ToString());
        //    }
        //    else
        //    {
        //        MessageBox.Show("请先选择一行数据!");
        //        flag = false;
        //    }
        //    if (drFocus["FREQUENCY_NAME"].ToString() != null)
        //    {
        //        frequencyName = drFocus["FREQUENCY_NAME"].ToString();
        //    }
        //    else
        //    {
        //        MessageBox.Show("频率为空!");
        //        flag = false;
        //    }
        //    if (drFocus["CHECK_PIVAS_BATCH_NO"].ToString() != null)
        //    {
        //        batchs = CJia.PIVAS.Common.BatchHandle(drFocus["CHECK_PIVAS_BATCH_NO"].ToString());
        //    }
        //    else
        //    {
        //        MessageBox.Show("批次号为空!");
        //        flag = false;
        //    }
        //    return flag;
        //}
        #endregion

        #region 按钮事件
        //刷新按钮
        private void btnRefresh_Click(object sender, EventArgs e)
        {
            NewRefresh();
        }

        //所有、已审、未审按钮
        private void rgAdviceState_EditValueChanged(object sender, EventArgs e)
        {
            RGAdviceStateChange();
        }

        //单个通过按钮
        private void btnSingleOk_Click(object sender, EventArgs e)
        {
            SingleOk();
        }

        //撤销审核按钮
        private void btnCancelCheck_Click(object sender, EventArgs e)
        {
            CancelCheck();
        }

        //拒绝医嘱按钮
        private void btnRefuseAdvice_Click(object sender, EventArgs e)
        {
            RefuseAdvice();
        }

        //拒绝配药按钮
        private void btnRefuseDosage_Click(object sender, EventArgs e)
        {
            RefuseDosage();
        }

        //修改批次按钮
        private void btnUpdateBatch_Click(object sender, EventArgs e)
        {
            UpdateBatch();
        }

        //病史资料按钮
        private void btnPatientHistory_Click(object sender, EventArgs e)
        {
            SelectPatientHistory();
        }

        //病人信息按钮
        private void btnPatient_Click(object sender, EventArgs e)
        {
            SelectPatientInfo();
        }

        //审方完成按钮
        private void btnComplete_Click(object sender, EventArgs e)
        {
            CompleteCheck();
        }
        #endregion

        #region 快捷键
        protected override bool ProcessCmdKey(ref System.Windows.Forms.Message msg, Keys keyData)
        {
            switch (keyData)
            {
                case Keys.F5:
                    btnRefresh.Focus();
                    btnRefresh_Click(null, null);
                    return true;
                default:
                    break;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }
        #endregion

        #region 显示有异常的医嘱
        private void gvAdvice_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            if (gvAdvice.RowCount > 0)
            {
                for (int i = 0; i < gvAdvice.RowCount; i++)
                {
                    string isInPivas = "1";
                    isInPivas = this.gvAdvice.GetRowCellDisplayText(e.RowHandle, this.colIsInPivas);
                    if (isInPivas == "0")
                    {
                        e.Appearance.BackColor = System.Drawing.Color.White;
                        e.Appearance.ForeColor = System.Drawing.Color.Red;
                    }
                }
            }
        }
        #endregion

        //#region 右键选择点击事件
        //private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        //{

        //}
        //#endregion
    }
}


text:
namespace Apache.Ignite.Core.Events
{
    using System;
    using Apache.Ignite.Core.Cluster;
    using Apache.Ignite.Core.Common;

    /// <summary>
    /// Represents a Ignite event.
    /// </summary>
    public interface IEvent
    {
        /// <summary>
        /// Gets globally unique ID of this event.
        /// </summary>
        IgniteGuid Id { get; }

        /// <summary>
        /// Gets locally unique ID that is atomically incremented for each event. Unlike global <see cref="Id" />
        /// this local ID can be used for ordering events on this node.
        /// <para/>
        /// Note that for performance considerations Ignite doesn't order events globally.
        /// </summary>
        long LocalOrder { get; }

        /// <summary>
        /// Node where event occurred and was recorded.
        /// </summary>
        IClusterNode Node { get; }

        /// <summary>
        /// Gets optional message for this event.
        /// </summary>
        string Message { get; }

        /// <summary>
        /// Gets type of this event. All system event types are defined in <see cref="EventType"/>
        /// </summary>
        int Type { get; }

        /// <summary>
        /// Gets name of this event.
        /// </summary>
        string Name { get; }

        /// <summary>
        /// Gets event timestamp. Timestamp is local to the node on which this event was produced.
        /// Note that more than one event can be generated with the same timestamp.
        /// For ordering purposes use <see cref="LocalOrder"/> instead.
        /// </summary>
        DateTime Timestamp { get; }

        /// <summary>
        /// Gets shortened version of ToString result.
        /// </summary>
        string ToShortString();
    }
}


text:
<?php

namespace Splash\Local\Objects\Invoice;

use Mage;
use Mage_Sales_Model_Order_Invoice;

/**
 * Magento 1 Orders Invoices Objects Lists Access
 */
trait ObjectListTrait
{
    /**
     * Return List Of Order's Invoices with required filters
     *
     * @param string $filter Filters for Object Listing.
     * @param array  $params Search parameters for result List.
     *
     * @return array $data                 List of all customers main data
     */
    public function objectsList($filter = null, $params = null)
    {
        //====================================================================//
        // Setup filters
        $filters = array();
        if (!empty($filter) && is_string($filter)) {
            $filters = array(
                array('attribute' => 'increment_id',     'like' => "%".$filter."%"),
            );
        }
        //====================================================================//
        // Execute Core Object List Function
        return $this->coreObjectsList($filters, (array) $params);
    }

    /**
     * Convert Object for Lists
     *
     * @param Mage_Sales_Model_Order_Invoice $listObject
     *
     * @return array
     */
    protected function objectListToArray(Mage_Sales_Model_Order_Invoice $listObject): array
    {
        $currencySymbol = " ".Mage::app()->getLocale()->currency($listObject->getOrderCurrencyCode())->getSymbol();

        return array(
            "id" => $listObject->getEntityId(),
            "increment_id" => $listObject->getIncrementId(),
            "reference" => $listObject->getOrderIncrementId(),
            "customer_name" => $listObject->getOrder()->getCustomerName(),
            "created_at" => $listObject->getCreatedAt(),
            "grand_total" => round($listObject->getGrandTotal(), 2).$currencySymbol,
        );
    }
}


text:
def whyrun_supported?
  true
end

def parse_app_dir_name url
  file_name = url.split('/')[-1]
  # funky logic to parse oracle's non-standard naming convention
  # for jdk1.6
  if file_name =~ /^(jre|jdk).*$/
    major_num = file_name.scan(/\d/)[0]
    update_num = file_name.scan(/\d+/)[1]
    # pad a single digit number with a zero
    if update_num.length < 2
      update_num = "0" + update_num
    end
    package_name = file_name.scan(/[a-z]+/)[0]
    app_dir_name = "#{package_name}1.#{major_num}.0_#{update_num}"
  else
    app_dir_name = file_name.split(/(.tar.gz|.zip)/)[0]
    app_dir_name = app_dir_name.split("-bin")[0]
  end
  [app_dir_name, file_name]
end

def oracle_downloaded?(download_path, new_resource)
  if ::File.exists? download_path
    require 'digest'
    downloaded_sha =  Digest::SHA256.file(download_path).hexdigest
    downloaded_sha == new_resource.checksum
  else
    return false
  end
end

def download_direct_from_oracle(tarball_name, new_resource)
  download_path = "#{Chef::Config[:file_cache_path]}/#{tarball_name}"
  jdk_id = new_resource.url.scan(/\/([6789]u[0-9][0-9]?-b[0-9][0-9])\//)[0][0]
  cookie = "oraclelicensejdk-#{jdk_id}-oth-JPR=accept-securebackup-cookie;gpw_e24=http://edelivery.oracle.com"
  if node['java']['oracle']['accept_oracle_download_terms']
    # install the curl package
    p = package "curl" do
      action :nothing
    end
    # no converge_by block since the package provider will take care of this run_action
    p.run_action(:install)
    description = "download oracle tarball straight from the server"
    converge_by(description) do
       Chef::Log.debug "downloading oracle tarball straight from the source"
       cmd = Chef::ShellOut.new(
                                  %Q[ curl -L --cookie "#{cookie}" #{new_resource.url} -o #{download_path} ]
                               )
       cmd.run_command
       cmd.error!
    end
  else
    Chef::Application.fatal!("You must set the attribute node['java']['oracle']['accept_oracle_download_terms'] to true if you want to download directly from the oracle site!")
  end
end

action :install do
  app_dir_name, tarball_name = parse_app_dir_name(new_resource.url)
  app_root = new_resource.app_home.split('/')[0..-2].join('/')
  app_dir = app_root + '/' + app_dir_name

  unless new_resource.default
    Chef::Log.debug("processing alternate jdk")
    app_dir = app_dir  + "_alt"
    app_home = new_resource.app_home + "_alt"
  else
    app_home = new_resource.app_home
  end

  unless ::File.exists?(app_dir)
    Chef::Log.info "Adding #{new_resource.name} to #{app_dir}"
    require 'fileutils'

    unless ::File.exists?(app_root)
      description = "create dir #{app_root} and change owner to #{new_resource.owner}"
      converge_by(description) do
          FileUtils.mkdir app_root, :mode => new_resource.app_home_mode
          FileUtils.chown new_resource.owner, new_resource.owner, app_root
      end
    end

    if new_resource.url =~ /^http:\/\/download.oracle.com.*$/
      download_path = "#{Chef::Config[:file_cache_path]}/#{tarball_name}"
      if  oracle_downloaded?(download_path, new_resource)
        Chef::Log.debug("oracle tarball already downloaded, not downloading again")
      else
        download_direct_from_oracle tarball_name, new_resource
      end
    else
      Chef::Log.debug("downloading tarball from an unofficial repository")
      r = remote_file "#{Chef::Config[:file_cache_path]}/#{tarball_name}" do
        source new_resource.url
        checksum new_resource.checksum
        mode 0755
        action :nothing
      end
      #no converge by on run_action remote_file takes care of it.
      r.run_action(:create_if_missing)
    end

    require 'tmpdir'

    description = "create tmpdir, extract compressed data into tmpdir,
                    move extracted data to #{app_dir} and delete tmpdir"
    converge_by(description) do
       tmpdir = Dir.mktmpdir
       case tarball_name
       when /^.*\.bin/
         cmd = Chef::ShellOut.new(
                                  %Q[ cd "#{tmpdir}";
                                      cp "#{Chef::Config[:file_cache_path]}/#{tarball_name}" . ;
                                      bash ./#{tarball_name} -noregister
                                    ] ).run_command
         unless cmd.exitstatus == 0
           Chef::Application.fatal!("Failed to extract file #{tarball_name}!")
         end
       when /^.*\.zip/
         cmd = Chef::ShellOut.new(
                            %Q[ unzip "#{Chef::Config[:file_cache_path]}/#{tarball_name}" -d "#{tmpdir}" ]
                                  ).run_command
         unless cmd.exitstatus == 0
           Chef::Application.fatal!("Failed to extract file #{tarball_name}!")
         end
       when /^.*\.tar.gz/
         cmd = Chef::ShellOut.new(
                            %Q[ tar xvzf "#{Chef::Config[:file_cache_path]}/#{tarball_name}" -C "#{tmpdir}" ]
                                  ).run_command
         unless cmd.exitstatus == 0
           Chef::Application.fatal!("Failed to extract file #{tarball_name}!")
         end
       end

       cmd = Chef::ShellOut.new(
                          %Q[ mv "#{tmpdir}/#{app_dir_name}" "#{app_dir}" ]
                                ).run_command
       unless cmd.exitstatus == 0
           Chef::Application.fatal!(%Q[ Command \' mv "#{tmpdir}/#{app_dir_name}" "#{app_dir}" \' failed ])
         end
       FileUtils.rm_r tmpdir
     end
     new_resource.updated_by_last_action(true)
  end

  #set up .jinfo file for update-java-alternatives
  java_name =  app_home.split('/')[-1]
  jinfo_file = "#{app_root}/.#{java_name}.jinfo"
  if platform_family?("debian") && !::File.exists?(jinfo_file)
    description = "Add #{jinfo_file} for debian"
    converge_by(description) do
      Chef::Log.debug "Adding #{jinfo_file} for debian"
      template jinfo_file do
        source "oracle.jinfo.erb"
        variables(
          :priority => new_resource.alternatives_priority,
          :bin_cmds => new_resource.bin_cmds,
          :name => java_name,
          :app_dir => app_home
        )
        action :create
      end
    end
    new_resource.updated_by_last_action(true)
  end

  #link app_home to app_dir
  Chef::Log.debug "app_home is #{app_home} and app_dir is #{app_dir}"
  current_link = ::File.symlink?(app_home) ? ::File.readlink(app_home) : nil
  if current_link != app_dir
    description = "Symlink #{app_dir} to #{app_home}"
    converge_by(description) do
       Chef::Log.debug "Symlinking #{app_dir} to #{app_home}"
       FileUtils.rm_f app_home
       FileUtils.ln_sf app_dir, app_home
    end
  end

  #update-alternatives
  if new_resource.bin_cmds
    new_resource.bin_cmds.each do |cmd|

      bin_path = "/usr/bin/#{cmd}"
      alt_path = "#{app_home}/bin/#{cmd}"
      priority = new_resource.alternatives_priority

      # install the alternative if needed
      alternative_exists = Chef::ShellOut.new("update-alternatives --display #{cmd} | grep #{alt_path}").run_command.exitstatus == 0
      unless alternative_exists
        description = "Add alternative for #{cmd}"
        converge_by(description) do
          Chef::Log.debug "Adding alternative for #{cmd}"
          install_cmd = Chef::ShellOut.new("update-alternatives --install #{bin_path} #{cmd} #{alt_path} #{priority}").run_command
          unless install_cmd.exitstatus == 0
            Chef::Application.fatal!(%Q[ set alternative failed ])
          end
        end
        new_resource.updated_by_last_action(true)
      end

      # set the alternative if default
      if new_resource.default
        alternative_is_set = Chef::ShellOut.new("update-alternatives --display #{cmd} | grep \"link currently points to #{alt_path}\"").run_command.exitstatus == 0
        unless alternative_is_set
          description = "Set alternative for #{cmd}"
          converge_by(description) do
            Chef::Log.debug "Setting alternative for #{cmd}"
            set_cmd = Chef::ShellOut.new("update-alternatives --set #{cmd} #{alt_path}").run_command
            unless set_cmd.exitstatus == 0
              Chef::Application.fatal!(%Q[ set alternative failed ])
            end
          end
          new_resource.updated_by_last_action(true)
        end
      end

    end
  end
end

action :remove do
  app_dir_name, tarball_name = parse_app_dir_name(new_resource.url)
  app_root = new_resource.app_home.split('/')[0..-2].join('/')
  app_dir = app_root + '/' + app_dir_name

  if ::File.exists?(app_dir)
    new_resource.bin_cmds.each do |cmd|
      cmd = execute "update_alternatives" do
        command "update-alternatives --remove #{cmd} #{app_dir} "
        returns [0,2]
        action :nothing
      end
      # the execute resource will take care of of the run_action(:run)
      cmd.run_action(:run)
    end
    description = "remove #{new_resource.name} at #{app_dir}"
    converge_by(description) do
       Chef::Log.info "Removing #{new_resource.name} at #{app_dir}"
       FileUtils.rm_rf app_dir
    end
    new_resource.updated_by_last_action(true)
  end
end


text:
//Generated by the Argon Build System

#ifndef BT_SOFT_BODY_SOLVER_VERTEX_BUFFER_OPENGL_H
#define BT_SOFT_BODY_SOLVER_VERTEX_BUFFER_OPENGL_H

#include "BulletSoftBody/btSoftBodySolverVertexBuffer.h"
#ifdef USE_MINICL
	#include "MiniCL/cl.h"
#else //USE_MINICL
	#ifdef __APPLE__
		#include <OpenCL/OpenCL.h>
	#else
		#include <CL/cl.h>
		#include <CL/cl_gl.h>
	#endif //__APPLE__
#endif//USE_MINICL

#ifdef _WIN32//for glut.h
#include <windows.h>
#endif

//think different
#if defined(__APPLE__) && !defined (VMDMESA)
#include <OpenGL/OpenGL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#else

#ifdef _WINDOWS
#include <windows.h>
#include <GL/gl.h>
#include <GL/glu.h>
#else
#include <GL/glut.h>
#endif //_WINDOWS
#endif //APPLE

class btOpenGLInteropVertexBufferDescriptor : public btVertexBufferDescriptor
{
protected:
	/** OpenCL context */
	cl_context			m_context;

	/** OpenCL command queue */
	cl_command_queue	m_commandQueue;

	/** OpenCL interop buffer */
	cl_mem m_buffer;

	/** VBO in GL that is the basis of the interop buffer */
	GLuint m_openGLVBO;

public:
	/**
	 * context is the OpenCL context this interop buffer will work in.
	 * queue is the command queue that kernels and data movement will be enqueued into.
	 * openGLVBO is the OpenGL vertex buffer data will be copied into.
	 * vertexOffset is the offset in floats to the first vertex.
	 * vertexStride is the stride in floats between vertices.
	 */
	btOpenGLInteropVertexBufferDescriptor( cl_command_queue cqCommandQue, cl_context context, GLuint openGLVBO, int vertexOffset, int vertexStride )
	{
#ifndef USE_MINICL
		cl_int ciErrNum = CL_SUCCESS;
		m_context = context;
		m_commandQueue = cqCommandQue;

		m_vertexOffset = vertexOffset;
		m_vertexStride = vertexStride;

		m_openGLVBO = openGLVBO;

		m_buffer = clCreateFromGLBuffer(m_context, CL_MEM_WRITE_ONLY, openGLVBO, &ciErrNum);
		if( ciErrNum != CL_SUCCESS )
		{
			btAssert( 0 &&  "clEnqueueAcquireGLObjects(copySoftBodyToVertexBuffer)");
		}

		m_hasVertexPositions = true;
#else
		btAssert(0);//MiniCL shouldn't get here
#endif
	}

	/**
	 * context is the OpenCL context this interop buffer will work in.
	 * queue is the command queue that kernels and data movement will be enqueued into.
	 * openGLVBO is the OpenGL vertex buffer data will be copied into.
	 * vertexOffset is the offset in floats to the first vertex.
	 * vertexStride is the stride in floats between vertices.
	 * normalOffset is the offset in floats to the first normal.
	 * normalStride is the stride in floats between normals.
	 */
	btOpenGLInteropVertexBufferDescriptor( cl_command_queue cqCommandQue, cl_context context, GLuint openGLVBO, int vertexOffset, int vertexStride, int normalOffset, int normalStride )
	{
#ifndef USE_MINICL
		cl_int ciErrNum = CL_SUCCESS;
		m_context = context;
		m_commandQueue = cqCommandQue;

		m_openGLVBO = openGLVBO;

		m_buffer = clCreateFromGLBuffer(m_context, CL_MEM_WRITE_ONLY, openGLVBO, &ciErrNum);
		if( ciErrNum != CL_SUCCESS )
		{
			btAssert( 0 &&  "clEnqueueAcquireGLObjects(copySoftBodyToVertexBuffer)");
		}

		m_vertexOffset = vertexOffset;
		m_vertexStride = vertexStride;
		m_hasVertexPositions = true;

		m_normalOffset = normalOffset;
		m_normalStride = normalStride;
		m_hasNormals = true;
#else
		btAssert(0);
#endif //USE_MINICL

	}

	virtual ~btOpenGLInteropVertexBufferDescriptor()
	{
		clReleaseMemObject( m_buffer );
	}

	/**
	 * Return the type of the vertex buffer descriptor.
	 */
	virtual BufferTypes getBufferType() const
	{
		return OPENGL_BUFFER;
	}

	virtual cl_context getContext() const
	{
		return m_context;
	}

	virtual cl_mem getBuffer() const
	{
		return m_buffer;
	}
};

#endif // #ifndef BT_SOFT_BODY_SOLVER_VERTEX_BUFFER_OPENGL_H


text:
package org.apache.arrow.memory;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.apache.arrow.memory.util.MemoryUtil;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

public class TestForeignAllocation {
  BufferAllocator allocator;

  @Before
  public void before() {
    allocator = new RootAllocator();
  }

  @After
  public void after() {
    allocator.close();
  }

  @Test
  public void wrapForeignAllocation() {
    final long bufferSize = 16;
    UnsafeForeignAllocation allocation = new UnsafeForeignAllocation(bufferSize);
    try {
      assertEquals(0, allocator.getAllocatedMemory());
      ArrowBuf buf = allocator.wrapForeignAllocation(allocation);
      assertEquals(bufferSize, buf.capacity());
      buf.close();
      assertTrue(allocation.released);
    } finally {
      allocation.release0();
    }
    assertEquals(0, allocator.getAllocatedMemory());
  }

  private static class UnsafeForeignAllocation extends ForeignAllocation {
    boolean released = false;

    public UnsafeForeignAllocation(long bufferSize) {
      super(bufferSize, MemoryUtil.UNSAFE.allocateMemory(bufferSize));
    }

    @Override
    protected void release0() {
      if (!released) {
        MemoryUtil.UNSAFE.freeMemory(memoryAddress());
        released = true;
      }
    }
  }
}


text:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <gtthread.h>

struct philosopher_data
{
	const char *name;
	gtthread_mutex_t *first_chopstick;
	gtthread_mutex_t *second_chopstick;
};

void * philosophize(void *arg)
{
	struct philosopher_data *data = (struct philosopher_data *)arg;
	int random_time;
	printf("%s enters the room\n",data->name);
	while(1)
	{
		/*think for awhile*/

		printf("%s is thinking...\n",data->name);
		for(random_time = (rand()%1000000); random_time > 0;--random_time)
		{
			gtthread_yield();
		}
		/*acquire first chopstick*/
		gtthread_mutex_lock(data->first_chopstick);
		/*acquire second chopstick*/
		gtthread_mutex_lock(data->second_chopstick);
		/*eat for awhile*/
		printf("%s is eating...\n",data->name);
		for(random_time = (rand()%1000000); random_time > 0;--random_time)
		{
			gtthread_yield();
		}
		/*release first chopstick*/
		gtthread_mutex_unlock(data->first_chopstick);
		/*release second chopstick*/
		gtthread_mutex_unlock(data->second_chopstick);
	}
}

int main(int argc, char **argv)
{
	int i;
	struct philosopher_data philosophers[5];
	gtthread_mutex_t chopsticks[5];
	gtthread_t threads[5];
	srand((unsigned int)time(NULL));
	gtthread_init(50000L);
	for(i = 0; i < 5; ++i)
	{
		gtthread_mutex_init(&(chopsticks[i]));
	}

	/*To avoid deadlock, the first four philosophers will be right-handed,
          and will therefore pick up the chopstick on their right first,
          and will also put down the chopstick on their right first.

          This means that the deadlock configuration may never occur.
          If all five are seated and all try to grab their first chopstick,
          all but one will acquire their right-hand chopstick.  The left-handed thinker
          will want the chopstick on the left first and will thus wait for it to be free.

          This allows the thinker to his right to acquire two chopsticks, eat and then release.
          Once he is done, the philosopher to his right can acquire his old right-hand stick, etc..
         */

	philosophers[0].name = "Aristotle";
	philosophers[0].first_chopstick = &(chopsticks[0]);
	philosophers[0].second_chopstick = &(chopsticks[1]);

	philosophers[1].name = "Plato";
	philosophers[1].first_chopstick = &(chopsticks[1]);
	philosophers[1].second_chopstick = &(chopsticks[2]);

	philosophers[2].name = "Descartes";
	philosophers[2].first_chopstick = &(chopsticks[2]);
	philosophers[2].second_chopstick = &(chopsticks[3]);

	philosophers[3].name = "Confucius";
	philosophers[3].first_chopstick = &(chopsticks[3]);
	philosophers[3].second_chopstick = &(chopsticks[4]);

	/*Of course, Marx is left handed.  He wasn't really, but its a philosopher thing.*/
	                                                /*We mortals wouldn't understand.*/

	philosophers[4].name = "Marx";
	philosophers[4].first_chopstick = &(chopsticks[0]);
	philosophers[4].second_chopstick = &(chopsticks[4]);

	for(i = 0; i < 5; ++i)
	{
		gtthread_create(&(threads[i]),philosophize,&(philosophers[i]));
	}

	gtthread_exit(NULL);
	return 0;
}


text:
'use strict';

var path = require('path');

module.exports = function(app) {
  if (!app.get('isDevEnv')) return;

  var serveDir = app.loopback.static;

  app.use(serveDir(projectPath('.tmp')));
  app.use('/bower_components', serveDir(projectPath('bower_components')));
  app.use('/lbclient', serveDir(projectPath('client/lbclient')));
};

function projectPath(relative) {
  return path.resolve(__dirname, '../..', relative);
}


text:
<?php

class content_ctl_wap_article extends wap_frontpage
{
    public function index()
    {
        $nav_url = $_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$this->gen_url(array('app'=>'wap', 'ctl'=>'default','act'=>'index'));
        $this->begin($nav_url);
        $article_id = $this->_request->get_param(0);
        if($article_id > 0){
            $detail = kernel::single('content_article_detail')->get_detail($article_id, true);
            if($detail['indexs']['ifpub']=='true' && $detail['indexs']['pubtime'] <= time()){
                $oCAN = kernel::single('content_article_node');
                $node_info = $oCAN->get_node($detail['indexs']['node_id'], true);
                if($node_info['ifpub'] == 'true'){
                    $aPath = $oCAN->get_node_path($detail['indexs']['node_id'], true);
                    $aPath[] = array(
                        'link'  => $this->app->router()->gen_url(array('app'=>'content', 'ctl'=>'wap_article', 'act'=>'index', 'arg0'=>$article_id)),
                        'title' => $detail['indexs']['title'],
                    );
                    $GLOBALS['runtime']['path'] = $aPath;
                    //title keywords description
                    $this->get_seo_info($detail['bodys'], $aPath);
                    unset($aPath);
                    if($this->weixin_share_page == null)
                        $this->weixin_share_page = array();
                    if(in_array('article-index', $this->weixin_share_page)){
                        $this->pagedata['from_weixin'] = $this->from_weixin;
                        $this->pagedata['weixin']['appid'] = $this->weixin_a_appid;
                        $this->pagedata['weixin']['imgUrl'] = base_storager::image_path(app::get('weixin')->getConf('weixin_basic_setting.weixin_logo'));
                        $this->pagedata['weixin']['linelink'] = app::get('wap')->router()->gen_url(array('app'=>'content','ctl'=>'wap_article','act'=>'index','arg0'=>$article_id, 'full'=>1));
                        $this->pagedata['weixin']['shareTitle'] = $this->pagedata['title'];
                        $this->pagedata['weixin']['descContent'] = $this->pagedata['description'];
                    }
                    switch($detail['indexs']['type'])
                    {
                        case 1:
                            $this->_index1($detail);
                        break;
                        case 2:
                            $this->_index2($detail);
                        break;
                        case 3:
                            $this->_index3($detail);
                        break;
                        default:
                    }//End Switch
                } else {
                    $this->end(false, app::get('content')->_('文章节点未发布!'));
                }
            } else {
                $this->end(false, app::get('content')->_('文章未发布!'));
            }
        } else {
            $this->end(false, app::get('content')->_('访问出错!'));
        }
    }//End Function

    private function _index1($detail)
    {
        $this->pagedata['detail'] = $detail;
        $this->pagedata['content'] = kernel::single('content_article_detail')->parse_hot_link($detail['bodys']);
        $this->set_tmpl('article');
        $this->set_tmpl_file($detail['bodys']['tmpl_path']);
        $this->page('wap/article/index.html');
    }//End Function

    private function _index2($detail)
    {
        $this->set_tmpl_file($detail['bodys']['tmpl_path']);
        $this->page('content:' . $detail['indexs']['article_id']);
    }//End Function

    private function _index3($detail)
    {
        if(preg_match('/^\[header\]/', trim($detail['bodys']['content']))){
            $this->set_tmpl_file('block/header.html');
            $this->page('wap/article/empty.html');
        }//头
        $this->page('content:' . $detail['indexs']['article_id'], true);
        if(preg_match('/\[footer\]$/', trim($detail['bodys']['content']))){
            $this->set_tmpl_file('block/footer.html');
            $this->page('wap/article/empty.html');
        }//尾
    }//End Function

    public function l/*lists*/() {
        $nav_url = $_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$this->gen_url(array('app'=>'wap', 'ctl'=>'default','act'=>'index'));
        $this->begin($nav_url);
        $art_list_id = $this->_request->get_param(0);
        if(empty($art_list_id)){
            $this->end(false, app::get('content')->_('访问出错'));
        }
        $oCAN = kernel::single('content_article_node');

        $aPath = $oCAN->get_node_path($art_list_id, true);
        $info = $oCAN->get_node($art_list_id, true);
        if($info['ifpub']!='true') {
            $this->end(false, app::get('content')->_('未发布!错误访问!'));
        }
        $GLOBALS['runtime']['path'] = $aPath;

        //title keywords description
        $this->get_seo_info($info, $aPath);

        $filter = array('node_id'=>$art_list_id);

        //每页条数
        $pageLimit = $this->app->getConf('gallery.display.listnum');
        $pageLimit = ($pageLimit ? $pageLimit : 10);

        //当前页
        $page = (int)$this->_request->get_param(1);
        $page or $page=1;
        $filter['ifpub'] = 'true';
        $filter['platform'] = 'wap';
        $filter['pubtime|sthan'] = time();

        $indexsObj = $this->app->model('article_indexs');
        $bodysObj = $this->app->model('article_bodys');

        //总数
        $count = $indexsObj->count($filter);
        $arr_articles = $indexsObj->getList('*', $filter, $pageLimit*($page-1),$pageLimit, 'pubtime DESC');
        $article_ids = array();
        foreach((array)$arr_articles as $key=>$art){
            $article_ids[] = $art['article_id'];
            $tmp_arr_articles[$art['article_id']] = $art;
        }

        if($article_ids)
        {
            $sql = "SELECT a.* , b.storage, b.s_url FROM `sdb_content_article_bodys` a LEFT JOIN `sdb_image_image` b ON a.image_id = b.image_id WHERE a.article_id IN (" .join(',' , $article_ids).") order by a.article_id desc";
            $arr_article_bodys = kernel::database()->select($sql);
        }

        //print_r($arr_article_bodys);
        $arr_articles = $arr_image_ids = array();
        foreach((array)$arr_article_bodys as $key=>$art){
            $art['s_url'] = '/'.$art['s_url'];
            $arr_articles[] = array_merge($tmp_arr_articles[$art['article_id']],$art);
            $arr_image_ids[] = $art['image_id'];
        }

        //标识用于生成url
        $token = md5("page{$page}");
        $this->pagedata['pager'] = array(
            'current'=>$page,
            'total'=>ceil($count/$pageLimit),
            'link'=>$this->gen_url(array('app'=>'content', 'ctl'=>'wap_article', 'act'=>'l', 'arg0'=>$art_list_id, 'arg2'=>$token)),
            'token'=>$token
        );

        $filter = array();
        $filter['ifpub'] = 'true';
        $filter['pubtime|than'] = time();
        $arr = $indexsObj->getList( 'pubtime',$filter,0,1,' pubtime ASC' );
        if( $arr ) { //设置缓存过期时间
            reset( $arr );
            $arr = current($arr);
            cachemgr::set_expiration($arr['pubtime']);
        }

        $this->pagedata['cat'] = $aNode[0];
        $this->pagedata['hasimage'] = $info['hasimage'];
        $this->pagedata['articles'] = $arr_articles;
        $this->set_tmpl('articlelist');
        $this->set_tmpl_file($info['list_tmpl_path']);
        if($info['hasimage']=='true'){
            $view = 'wap/article/list_image.html';
        }else{
           $view = 'wap/article/list.html';
        }
        if(is_null($this->weixin_share_page)) $this->weixin_share_page = array();
        if(in_array('article-list', $this->weixin_share_page)){
            $this->pagedata['from_weixin'] = $this->from_weixin;
            $this->pagedata['weixin']['appid'] = $this->weixin_a_appid;
            $this->pagedata['weixin']['imgUrl'] = base_storager::image_path(app::get('weixin')->getConf('weixin_basic_setting.weixin_logo'));
            $this->pagedata['weixin']['linelink'] = app::get('wap')->router()->gen_url(array('app'=>'content','ctl'=>'wap_article','act'=>'l','arg0'=>$art_list_id, 'full'=>1));
            $this->pagedata['weixin']['shareTitle'] = $this->pagedata['title'];
            $this->pagedata['weixin']['descContent'] = $this->pagedata['description'];
        }
        $this->page($view);
    }

    public function i/*nodeindex*/() {
         $nav_url = $_SERVER['HTTP_REFERER']?$_SERVER['HTTP_REFERER']:$this->gen_url(array('app'=>'wap', 'ctl'=>'default','act'=>'index'));
        $this->begin($nav_url);
        $id = $this->_request->get_param(0);
        if($id > 0) {
            $oCAN = kernel::single('content_article_node');
            $aPath = $oCAN->get_node_path($id, true);
            $GLOBALS['runtime']['path'] = $aPath;

            $info = $oCAN->get_node($id, true);
            if($info['ifpub']=='true') {
                $this->get_seo_info($info, $aPath);
                $this->set_tmpl_file($info['tmpl_path']);
                $this->page('content_node:' . $info['node_id']);
            } else {
                $this->end(false, app::get('content')->_('未发布!错误访问!'));
            }
        } else {
            $this->end(false, app::get('content')->_('错误访问!'));
        }
    }

    private function get_seo_info($aInfo, $aPath) {
        is_array($info) or $info = array();
        is_array($aPath) or $aPath = array();
        //title keywords description
        $title = array();
        $title[] = $aInfo['seo_title'] ? $aInfo['seo_title'] : $aPath[count($aPath)-1]['title'];
        if(!$aInfo['seo_title']) {
            $title[] = $this->site_name ? $this->site_name : app::get('site')->getConf('site.name');
        }
        $title = array_filter($title);

        $this->pagedata['title'] = implode('-', $title);
        $this->pagedata['description']  = $aInfo['seo_description'] ? $aInfo['seo_description'] : $this->pagedata['title'];
        if($aInfo['seo_keywords']) {
            $this->pagedata['keywords'] = $aInfo['seo_keywords'];
        } else {
            $keyword = array();
            foreach($aPath as $row) {
                $keyword[] = $row['title'];
            }
            $this->pagedata['keywords'] = implode('-', $keyword);
        }
    }

    function ajax_widgets(){
        $indexs = $this->app->model('article_indexs')->getList('article_id,title',array('node_id'=>intval($_POST['node_id'])) );
        echo json_encode($indexs);
    }

}//End Class


text:
#pragma once

#include <chrono>

#include <thrift/lib/cpp/async/TAsyncSocket.h>

#include "mcrouter/lib/mc/protocol.h"

namespace apache { namespace thrift { namespace transport {
class SSLContext;
}}} // apache::thrift::transport

namespace facebook { namespace memcache {

/**
 * A struct for storing all connection related options.
 */
struct ConnectionOptions {
  typedef apache::thrift::async::TAsyncSocket::OptionMap SocketOptions;

  ConnectionOptions(folly::StringPiece host_,
                    uint16_t port_,
                    mc_protocol_t protocol_) :
      host(host_.begin(), host_.end()),
      port(port_),
      protocol(protocol_) {
  }

  /**
   * Hostname of the peer to connect to.
   */
  std::string host;

  /**
   * Port of the peer to connect to.
   */
  uint16_t port{0};

  /**
   * Type of protocol that should be used.
   */
  mc_protocol_t protocol{mc_unknown_protocol};

  /**
   * Number of TCP KeepAlive probes to send before considering connection dead.
   *
   * Note: Option will be enabled iff it is supported by the OS and this
   *       value > 0.
   */
  int tcpKeepAliveCount{0};

  /**
   * Interval between last data packet sent and the first TCP KeepAlive probe.
   */
  int tcpKeepAliveIdle{0};

  /**
   * Interval between two consequent TCP KeepAlive probes.
   */
  int tcpKeepAliveInterval{0};

  /**
   * Send/connect timeout in ms.
   */
  std::chrono::milliseconds timeout{0};

  /**
   * SSLContext provider callback. If null, then unsecured connections will be
   * established, else it will be called for each attempt to establish
   * connection.
   */
  std::function<std::shared_ptr<apache::thrift::transport::SSLContext>()>
    sslContextProvider;
};

}} // facebook::memcache


text:
package watcher

import (
	"encoder-backend/pkg/watcher/events"
	log "github.com/sirupsen/logrus"
)

// Subscribe
// add a new subscriber
func (c *Client) Subscribe(name string, channel chan<- events.Event) {

	c.btx.Lock()
	_, ok := c.subscribers[name]
	c.btx.Unlock()

	if ok {
		log.Warnf("watcher.client.subscribe: subscriber [%s] already subscribed", name)
		return
	}

	c.streams = append(c.streams, channel)

	c.btx.Lock()
	c.subscribers[name] = len(c.streams) - 1
	c.btx.Unlock()
}


text:
/* Date: 2016-08-16 */

/*==================[inclusions]=============================================*/

#include "tasks.h"        /* <= own header */

#include "sapi.h"         /* <= sAPI header */

/*==================[macros and definitions]=================================*/

/*==================[internal data declaration]==============================*/

/*==================[internal functions declaration]=========================*/

/*==================[internal data definition]===============================*/

/*==================[external data definition]===============================*/

/*==================[internal functions definition]==========================*/

/*==================[external functions definition]==========================*/

/* ------------ INICIALIZACION DE TAREAS ------------ */

/* FUNCION que inicializa las tareas. */
void tasksInit(void){

   /* Inicializar la placa */
   boardConfig();

   /* Inicializar GPIOs */
   gpioConfig( 0, GPIO_ENABLE );

   /* Configuración de pines de entrada para Teclas de la CIAA-NXP */
   gpioConfig( TEC1, GPIO_INPUT );
   gpioConfig( TEC2, GPIO_INPUT );
   gpioConfig( TEC3, GPIO_INPUT );
   gpioConfig( TEC4, GPIO_INPUT );

   /* Configuración de pines de salida para Leds de la CIAA-NXP */
   gpioConfig( LEDR, GPIO_OUTPUT );
   gpioConfig( LEDG, GPIO_OUTPUT );
   gpioConfig( LEDB, GPIO_OUTPUT );
   gpioConfig( LED1, GPIO_OUTPUT );
   gpioConfig( LED2, GPIO_OUTPUT );
   gpioConfig( LED3, GPIO_OUTPUT );

}

/* --------------------- TAREAS --------------------- */

/* FUNCION que realiza la tarea 1.
   Esta tarea lee una tecla cada 40ms y escribe su valor
   en LEDB */
void task1(void){

   gpioWrite( LEDB, !gpioRead(TEC1) );

}

/* FUNCION que realiza la tarea 2.
   Esta tarea hace destellar el LED2 (blink) cada
   250ms. */
void task2(void){

   static bool_t led2Status = OFF;

   led2Status = !led2Status;
   gpioWrite( LED2, led2Status );

}

/* FUNCION que realiza la tarea 3.
   Esta tarea hace destellar el LED3 (blink) cada
   500ms. */
void task3(void){

   static bool_t led3Status = OFF;

   led3Status = !led3Status;
   gpioWrite( LED3, led3Status );

}

/*==================[end of file]============================================*/


text:
=======
DocBlock
========

DocBlock for Atom.


text:
(function() {
  'use strict';

  describe('Directive: manageParticipants', function() {
    var $scope,
        $compile,
        element,
        showAddParticipantsSpy;

    beforeEach(function() {
      showAddParticipantsSpy = jasmine.createSpy('ManageParticipantsCtrlSpy');
      module('PDRClient', function($controllerProvider) {
        $controllerProvider.register('ManageParticipantsCtrl', function() {
          this.showAddParticipants = showAddParticipantsSpy;
        });

      });
      inject(function(_$compile_, _$rootScope_) {
        $compile = _$compile_;
        $scope = _$rootScope_.$new(true);
      });
    });

    describe('when autoShow is true', function() {
      beforeEach(function() {
        element = angular.element('<manage-participants auto-show="true"></manage-participants>');
        $compile(element)($scope);
        $scope.$digest();
      });

      it('calls #showAddParticipants on the ManageParticipantsCtrl', function() {
        expect(showAddParticipantsSpy).toHaveBeenCalled();
      });
    });

    describe('when autoShow is false', function() {
      beforeEach(function() {
        element = angular.element('<manage-participants auto-show="false"></manage-participants>');
        $compile(element)($scope);
        $scope.$digest();
      });

      it('calls #showAddParticipants on the ManageParticipantsCtrl', function() {
        expect(showAddParticipantsSpy).not.toHaveBeenCalled();
      });
    });

    describe('when autoShow is undefined', function() {
      beforeEach(function() {
        element = angular.element('<manage-participants></manage-participants>');
        $compile(element)($scope);
        $scope.$digest();
      });

      it('calls #showAddParticipants on the ManageParticipantsCtrl', function() {
        expect(showAddParticipantsSpy).not.toHaveBeenCalled();
      });
    });
  });
})();


text:
from django import forms
from feedback.tasks import send_feedback_email_task

class FeedbackForm(forms.Form):
    email = forms.EmailField(label="Email Address")
    message = forms.CharField(label="Message", widget=forms.Textarea(attrs={'rows': 5}))
    honeypot = forms.CharField(widget=forms.HiddenInput(), required=False)

    def send_email(self):
        # try to trick spammers by checking whether the honeypot field is filled in
        # not super complicated/effective but if works
        if self.cleaned_data['honeypot']:
            return False
        send_feedback_email_task.delay(self.cleaned_data['email'], self.cleaned_data['message'])


text:
package com.buildmlearnstore.activities;

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

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.buildmlearnstore.model.Question;
import com.buildmlearnstore.model.QuizModel;

public class QuestionActivity extends SherlockActivity {

	private TextView iQuestion_no_Label;
	private TextView iQuestionLabel;
	private RadioButton iRad1, iRad2, iRad3, iRad0;
	private Button iSubmitButton, iNextButton;
	private List<RadioButton> iRadButtonList = new ArrayList<RadioButton>();
	private int iQuestionIndex = 0;
	private int iCurrentCorrectAnswer;
	private RadioGroup iRadioGroup;
	private ArrayList<Question> mQuestionAnsList;
	private QuizModel mQuizModel;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.questions_view);
		mQuizModel=QuizModel.getInstance();
		mQuestionAnsList=mQuizModel.getQueAnsList();

		iQuestion_no_Label = (TextView) findViewById(R.id.question_no);
		iQuestionLabel = (TextView) findViewById(R.id.question_label);

		iRad0 = (RadioButton) findViewById(R.id.radio0);
		iRad1 = (RadioButton) findViewById(R.id.radio1);
		iRad2 = (RadioButton) findViewById(R.id.radio2);
		iRad3 = (RadioButton) findViewById(R.id.radio3);

		iRadioGroup = (RadioGroup) findViewById(R.id.radioGroup1);

		iRadButtonList.add(iRad0);
		iRadButtonList.add(iRad1);
		iRadButtonList.add(iRad2);
		iRadButtonList.add(iRad3);

		iSubmitButton = (Button) findViewById(R.id.submit_button);
		iSubmitButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				int selectedAnswer = getSelectedAnswer();
				if (selectedAnswer == -1) {
					Toast.makeText(QuestionActivity.this,
							"Please select an answer!", 1000).show();
				} else if (selectedAnswer != -1
						&& selectedAnswer == iCurrentCorrectAnswer) {
					iRadButtonList.get(iCurrentCorrectAnswer)
							.setBackgroundColor(Color.GREEN);
					Toast.makeText(QuestionActivity.this,
							"That's the correct answer!", 1000).show();
					mQuizModel.setTotalCorrect(mQuizModel.getTotalCorrect()+1);
					//gd.correct++;

					iSubmitButton.setEnabled(false);
					/*
					 * iSubmitButton.setVisibility(View.GONE);
					 * iNextButton.setVisibility(View.VISIBLE);
					 */
				} else {
					iRadButtonList.get(selectedAnswer).setBackgroundColor(
							Color.RED);
					iRadButtonList.get(iCurrentCorrectAnswer)
							.setBackgroundColor(Color.GREEN);
					Toast.makeText(QuestionActivity.this,
							"Sorry, wrong answer!", 1000).show();
					mQuizModel.setTotalWrong(mQuizModel.getTotalWrong()+1);
					iSubmitButton.setEnabled(false);
					//gd.wrong++;
					// iSubmitButton.setVisibility(View.GONE);
					// iNextButton.setVisibility(View.VISIBLE);

				}
			}
		});

		iNextButton = (Button) findViewById(R.id.next_button);
		iNextButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {

				// set all radios to white
				for (int i = 0; i < iRadButtonList.size(); i++) {
					iRadButtonList.get(i).setBackgroundColor(Color.TRANSPARENT);
				}

				// Increase the index to next ques
				iQuestionIndex = iQuestionIndex + 1;

				if (iQuestionIndex <mQuestionAnsList.size()) {
					populateQuestion(iQuestionIndex);

					iSubmitButton.setEnabled(true);
					// iNextButton.setVisibility(View.GONE);
				} else {
					// if the quiz is over
					reInitialize();
					Intent myIntent = new Intent(arg0.getContext(),
							ScoreActivity.class);
					startActivity(myIntent);
					finish();
				}
			}
		});
		// iNextButton.setVisibility(View.GONE);

		populateQuestion(iQuestionIndex);

	}

	public void radioClick(View v) {

	}

	public void populateQuestion(int index) {
		for (int i = 0; i < iRadButtonList.size(); i++) {
			iRadButtonList.get(i).setBackgroundColor(Color.TRANSPARENT);
			iRadButtonList.get(i).setChecked(false);
			iRadButtonList.get(i).setVisibility(View.INVISIBLE);
		}

		iQuestion_no_Label.setText("Question #" + String.valueOf(index + 1)
				+ " of " + mQuestionAnsList.size());

		//String[] ques_content = mQuestionAnsList.get(index).split("==");

		//String question = ques_content[0];
		iQuestionLabel.setText(mQuestionAnsList.get(index).getQuestion());

		for (int i = 0; i < mQuestionAnsList.get(index).getAnswerOption().size() ; i++) {
			iRadButtonList.get(i).setText(mQuestionAnsList.get(index).getAnswerOption().get(i));
			iRadButtonList.get(i).setVisibility(View.VISIBLE);
		}

		iCurrentCorrectAnswer = mQuestionAnsList.get(index).getOptionNumber();
	}

	public int getSelectedAnswer() {
		int selected = -1;
		for (int i = 0; i < iRadButtonList.size(); i++) {
			if (iRadButtonList.get(i).isChecked()) {
				return i;
			}
		}
		return selected;
	}

	public void reInitialize() {

		iQuestionIndex = 0;
	//	gd.iQuizList.clear();
	}

}


text:
//
//  DCDetailPicCell.h
//  CDDStoreDemo
//
//  Created by 陈甸甸 on 2018/2/24.
//  Copyright © 2018年 RocketsChen. All rights reserved.
//

#import "DCItemImageCell.h"

@interface DCDetailPicCell : UICollectionViewCell

/* imageView */
@property (strong , nonatomic)UIImageView *itemImageView;

/** 保存到相册 */
@property (nonatomic, copy) dispatch_block_t savePhotoBlock;

@end


text:
package com.google.idea.blaze.base.sync.workspace;

import com.google.common.collect.ImmutableList;
import com.google.idea.blaze.base.model.primitives.WorkspacePath;
import java.io.Serializable;

/** Computes the working set of files of directories from source control. */
public class WorkingSet implements Serializable {
  private static final long serialVersionUID = 2L;

  public final ImmutableList<WorkspacePath> addedFiles;
  public final ImmutableList<WorkspacePath> modifiedFiles;
  public final ImmutableList<WorkspacePath> deletedFiles;

  public WorkingSet(
      ImmutableList<WorkspacePath> addedFiles,
      ImmutableList<WorkspacePath> modifiedFiles,
      ImmutableList<WorkspacePath> deletedFiles) {
    this.addedFiles = addedFiles;
    this.modifiedFiles = modifiedFiles;
    this.deletedFiles = deletedFiles;
  }

  public boolean isEmpty() {
    return addedFiles.isEmpty() && modifiedFiles.isEmpty() && deletedFiles.isEmpty();
  }
}