text:
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System;
using System.Collections.Generic;
using System.Linq.Expressions;

#if DLAB_UNROOT_NAMESPACE || DLAB_XRM
namespace DLaB.Xrm
#else
namespace Source.DLaB.Xrm
#endif

{
    public static partial class Extensions
    {
        #region IOrganizationService

        #region GetEntityOrDefault

        /// <summary>
        /// Gets the entity by id. Null is returned if it isn't found.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="id">Id of the entity to search for.</param>
        /// <returns></returns>
        public static Entity GetEntityOrDefault(this IOrganizationService service, string logicalName, Guid id)
        {
            return service.GetFirstOrDefault(logicalName, EntityHelper.GetIdAttributeName(logicalName), id);
        }

        /// <summary>
        /// Gets the entity by id. Null is returned if it isn't found.
        /// </summary>
        /// <param name="service">The service.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="id">Id of the entity to search for.</param>
        /// <param name="columnSet">Columns to retrieve.</param>
        /// <returns></returns>
        public static Entity GetEntityOrDefault(this IOrganizationService service, string logicalName, Guid id, ColumnSet columnSet)
        {
            return service.GetFirstOrDefault(logicalName, EntityHelper.GetIdAttributeName(logicalName), id);
        }

        /// <summary>
        /// Gets the first entity that matches the query expression.  Null is returned if none are found.
        /// </summary>
        /// <typeparam name="T">The Entity Type.</typeparam>
        /// <param name="service">The service.</param>
        /// <param name="id">Id of the entity to search for.</param>
        /// <returns></returns>
        public static T GetEntityOrDefault<T>(this IOrganizationService service, Guid id) where T : Entity
        {
            return service.GetFirstOrDefault<T>(EntityHelper.GetIdAttributeName<T>(), id);
        }

        /// <summary>
        /// Gets the first entity that matches the query expression.  Null is returned if none are found.
        /// </summary>
        /// <typeparam name="T">The Entity Type.</typeparam>
        /// <param name="service">The service.</param>
        /// <param name="id">Id of the entity to search for.</param>
        /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
        /// type are the column names to add.</param>
        /// <returns></returns>
        public static T GetEntityOrDefault<T>(this IOrganizationService service, Guid id, Expression<Func<T, object>> anonymousTypeInitializer) where T : Entity
        {
            return service.GetFirstOrDefault(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), id);
        }

        #endregion GetEntityOrDefault

        #region GetEntitiesById

        /// <summary>
        /// Gets the first 5000 active entities with the given ids.
        /// </summary>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<Entity> GetEntitiesById(this IOrganizationService service,
                string logicalName, IEnumerable<Guid> ids)
        {
            return service.GetEntitiesIn(logicalName, EntityHelper.GetIdAttributeName(logicalName), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities with the given ids.
        /// </summary>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<Entity> GetEntitiesById(this IOrganizationService service,
                string logicalName, params Guid[] ids)
        {
            return service.GetEntitiesIn(logicalName, EntityHelper.GetIdAttributeName(logicalName), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
        /// </summary>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="columnSet">Columns to retrieve.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<Entity> GetEntitiesById(this IOrganizationService service, string logicalName,
                ColumnSet columnSet, IEnumerable<Guid> ids)
        {
            return service.GetEntitiesIn(logicalName, columnSet, EntityHelper.GetIdAttributeName(logicalName), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
        /// </summary>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="columnSet">Columns to retrieve.</param>
        /// <param name="logicalName">Logical name of the entity.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<Entity> GetEntitiesById(this IOrganizationService service, string logicalName,
                 ColumnSet columnSet, params Guid[] ids)
        {
            return service.GetEntitiesIn(logicalName, columnSet, EntityHelper.GetIdAttributeName(logicalName), ids);
        }

        #endregion GetEntitiesById

        #region GetEntitiesById<T>

        /// <summary>
        /// Gets the first 5000 active entities with the given ids.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, IEnumerable<Guid> ids) where T : Entity
        {
            return service.GetEntitiesIn<T>(EntityHelper.GetIdAttributeName<T>(), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities with the given ids.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return.</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, params Guid[] ids) where T : Entity
        {
            return service.GetEntitiesIn<T>(EntityHelper.GetIdAttributeName<T>(), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return.</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
        /// type are the column names to add.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer,
                IEnumerable<Guid> ids) where T : Entity
        {
            return service.GetEntitiesIn(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return.</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="anonymousTypeInitializer">An Anonymous Type Initializer where the properties of the anonymous
        /// type are the column names to add.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, Expression<Func<T, object>> anonymousTypeInitializer,
                params Guid[] ids) where T : Entity
        {
            return service.GetEntitiesIn(anonymousTypeInitializer, EntityHelper.GetIdAttributeName<T>(), ids);
        }

        /// <summary>
        /// Gets the first 5000 active entities (with the given subset of columns only) with the given ids.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return.</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="columnSet">Columns to retrieve</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, ColumnSet columnSet, IEnumerable<Guid> ids) where T : Entity
        {
            return service.GetEntitiesIn<T>(columnSet, EntityHelper.GetIdAttributeName<T>(), ids);
        }

        /// <summary>
        /// Gets first 5000 Active Entities (with the given subset of columns only)
        /// where the columnNameAndValue Pairs match.
        /// </summary>
        /// <typeparam name="T">Type of Entity List to return.</typeparam>
        /// <param name="service">The IOrganizationService.</param>
        /// <param name="columnSet">Columns to retrieve.</param>
        /// <param name="ids">Ids of the entity to search for.</param>
        /// <returns></returns>
        public static List<T> GetEntitiesById<T>(this IOrganizationService service, ColumnSet columnSet, params Guid[] ids) where T : Entity
        {
            return service.GetEntitiesIn<T>(columnSet, EntityHelper.GetIdAttributeName<T>(), ids);
        }

        #endregion GetEntitiesById<T>

        #endregion IOrganizationServic
    }
}


text:
import {prepareDataCoordInfo, getStackedOnPoint} from './helper';

// var arrayDiff = require('zrender/src/core/arrayDiff');
// 'zrender/src/core/arrayDiff' has been used before, but it did
// not do well in performance when roam with fixed dataZoom window.

// function convertToIntId(newIdList, oldIdList) {
//     // Generate int id instead of string id.
//     // Compare string maybe slow in score function of arrDiff

//     // Assume id in idList are all unique
//     var idIndicesMap = {};
//     var idx = 0;
//     for (var i = 0; i < newIdList.length; i++) {
//         idIndicesMap[newIdList[i]] = idx;
//         newIdList[i] = idx++;
//     }
//     for (var i = 0; i < oldIdList.length; i++) {
//         var oldId = oldIdList[i];
//         // Same with newIdList
//         if (idIndicesMap[oldId]) {
//             oldIdList[i] = idIndicesMap[oldId];
//         }
//         else {
//             oldIdList[i] = idx++;
//         }
//     }
// }

function diffData(oldData, newData) {
    var diffResult = [];

    newData.diff(oldData)
        .add(function (idx) {
            diffResult.push({cmd: '+', idx: idx});
        })
        .update(function (newIdx, oldIdx) {
            diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
        })
        .remove(function (idx) {
            diffResult.push({cmd: '-', idx: idx});
        })
        .execute();

    return diffResult;
}

export default function (
    oldData, newData,
    oldStackedOnPoints, newStackedOnPoints,
    oldCoordSys, newCoordSys,
    oldValueOrigin, newValueOrigin
) {
    var diff = diffData(oldData, newData);

    // var newIdList = newData.mapArray(newData.getId);
    // var oldIdList = oldData.mapArray(oldData.getId);

    // convertToIntId(newIdList, oldIdList);

    // // FIXME One data ?
    // diff = arrayDiff(oldIdList, newIdList);

    var currPoints = [];
    var nextPoints = [];
    // Points for stacking base line
    var currStackedPoints = [];
    var nextStackedPoints = [];

    var status = [];
    var sortedIndices = [];
    var rawIndices = [];

    var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
    var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);

    for (var i = 0; i < diff.length; i++) {
        var diffItem = diff[i];
        var pointAdded = true;

        // FIXME, animation is not so perfect when dataZoom window moves fast
        // Which is in case remvoing or add more than one data in the tail or head
        switch (diffItem.cmd) {
            case '=':
                var currentPt = oldData.getItemLayout(diffItem.idx);
                var nextPt = newData.getItemLayout(diffItem.idx1);
                // If previous data is NaN, use next point directly
                if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
                    currentPt = nextPt.slice();
                }
                currPoints.push(currentPt);
                nextPoints.push(nextPt);

                currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
                nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);

                rawIndices.push(newData.getRawIndex(diffItem.idx1));
                break;
            case '+':
                var idx = diffItem.idx;
                currPoints.push(
                    oldCoordSys.dataToPoint([
                        newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
                        newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
                    ])
                );

                nextPoints.push(newData.getItemLayout(idx).slice());

                currStackedPoints.push(
                    getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
                );
                nextStackedPoints.push(newStackedOnPoints[idx]);

                rawIndices.push(newData.getRawIndex(idx));
                break;
            case '-':
                var idx = diffItem.idx;
                var rawIndex = oldData.getRawIndex(idx);
                // Data is replaced. In the case of dynamic data queue
                // FIXME FIXME FIXME
                if (rawIndex !== idx) {
                    currPoints.push(oldData.getItemLayout(idx));
                    nextPoints.push(newCoordSys.dataToPoint([
                        oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
                        oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
                    ]));

                    currStackedPoints.push(oldStackedOnPoints[idx]);
                    nextStackedPoints.push(
                        getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
                    );

                    rawIndices.push(rawIndex);
                }
                else {
                    pointAdded = false;
                }
        }

        // Original indices
        if (pointAdded) {
            status.push(diffItem);
            sortedIndices.push(sortedIndices.length);
        }
    }

    // Diff result may be crossed if all items are changed
    // Sort by data index
    sortedIndices.sort(function (a, b) {
        return rawIndices[a] - rawIndices[b];
    });

    var sortedCurrPoints = [];
    var sortedNextPoints = [];

    var sortedCurrStackedPoints = [];
    var sortedNextStackedPoints = [];

    var sortedStatus = [];
    for (var i = 0; i < sortedIndices.length; i++) {
        var idx = sortedIndices[i];
        sortedCurrPoints[i] = currPoints[idx];
        sortedNextPoints[i] = nextPoints[idx];

        sortedCurrStackedPoints[i] = currStackedPoints[idx];
        sortedNextStackedPoints[i] = nextStackedPoints[idx];

        sortedStatus[i] = status[idx];
    }

    return {
        current: sortedCurrPoints,
        next: sortedNextPoints,

        stackedOnCurrent: sortedCurrStackedPoints,
        stackedOnNext: sortedNextStackedPoints,

        status: sortedStatus
    };
}

redpajama_set_name: RedPajamaGithub


text:
module WulinMaster
  class InclusionExclusionPanel < Panel
    fill_window false
  end
end


text:
import ctypes
import os
from clang.cindex import Cursor
from clang.cindex import TranslationUnit
import unittest
from ctypeslib.codegen import clangparser, codegenerator
from StringIO import StringIO

import tempfile

def mktemp(suffix):
    handle, fnm = tempfile.mkstemp(suffix)
    os.close(handle)
    return fnm

def get_tu(source, lang='c', all_warnings=False, flags=[]):
    """Obtain a translation unit from source and language.

    By default, the translation unit is created from source file "t.<ext>"
    where <ext> is the default file extension for the specified language. By
    default it is C, so "t.c" is the default file name.

    Supported languages are {c, cpp, objc}.

    all_warnings is a convenience argument to enable all compiler warnings.
    """
    assert isinstance(flags, list)
    args = list(flags)
    name = 't.c'
    if lang == 'cpp':
        name = 't.cpp'
        args.append('-std=c++11')
    elif lang == 'objc':
        name = 't.m'
    elif lang != 'c':
        raise Exception('Unknown language: %s' % lang)

    if all_warnings:
        args += ['-Wall', '-Wextra']

    return TranslationUnit.from_source(name, args, unsaved_files=[(name,
                                                                   source)])

def get_cursor(source, spelling):
    """Obtain a cursor from a source object.

    This provides a convenient search mechanism to find a cursor with specific
    spelling within a source. The first argument can be either a
    TranslationUnit or Cursor instance.

    If the cursor is not found, None is returned.
    """
    children = []
    if isinstance(source, Cursor):
        children = source.get_children()
    else:
        # Assume TU
        children = source.cursor.get_children()

    for cursor in children:
        if cursor.spelling == spelling:
            return cursor

        # Recurse into children.
        result = get_cursor(cursor, spelling)
        if result is not None:
            return result

    return None

def get_cursors(source, spelling):
    """Obtain all cursors from a source object with a specific spelling.

    This provides a convenient search mechanism to find all cursors with specific
    spelling within a source. The first argument can be either a
    TranslationUnit or Cursor instance.

    If no cursors are found, an empty list is returned.
    """
    cursors = []
    children = []
    if isinstance(source, Cursor):
        children = source.get_children()
    else:
        # Assume TU
        children = source.cursor.get_children()

    for cursor in children:
        if cursor.spelling == spelling:
            cursors.append(cursor)

        # Recurse into children.
        cursors.extend(get_cursors(cursor, spelling))

    return cursors

class ADict(dict):

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

class ClangTest(unittest.TestCase):
    namespace = None
    full_parsing_options = False

    def _gen(self, ofi, fname, flags=[]):
        """Take a file input and generate the code.
        """
        # leave the new parser accessible for tests
        self.parser = clangparser.Clang_Parser(flags)
        if self.full_parsing_options:
            self.parser.activate_macros_parsing()
            self.parser.activate_comment_parsing()
        with open(fname):
            pass
        self.parser.parse(fname)
        items = self.parser.get_result()
        # gen code
        gen = codegenerator.Generator(ofi)
        gen.generate_headers(self.parser)
        gen.generate_code(items)
        return gen

    def gen(self, fname, flags=[]):
        """Take a file input and generate the code.
        """
        ofi = StringIO()
        gen = self._gen(ofi, fname, flags)
        # load code
        namespace = {}
        # DEBUG
        # print ofi.getvalue()
        # DEBUG
        ofi.seek(0)
        ignore_coding = ofi.readline()
        #exec ofi.getvalue() in namespace
        output = ''.join(ofi.readlines())
        exec output in namespace
        self.namespace = ADict(namespace)
        return

    def convert(self, src_code, flags=[]):
        """Take a string input, write it into a temp file and the code.
        """
        hfile = mktemp(".h")
        open(hfile, "w").write(src_code)
        try:
            self.gen(hfile, flags)
        finally:
            os.unlink(hfile)
        return

    def _get_target_with_struct_hack(self, name):
        """ because we rename "struct x" to struct_x, we have to reverse that
        """
        target = get_cursor(self.parser.tu, name)
        if target is None:
            target = get_cursor(self.parser.tu, name.replace('struct_', ''))
        if target is None:
            target = get_cursor(self.parser.tu, name.replace('union_', ''))
        return target

    def assertSizes(self, name):
        """ Compare size of records using clang sizeof versus python sizeof."""
        target = self._get_target_with_struct_hack(name)
        self.assertTrue(
            target is not None,
            '%s was not found in source' %
            name)
        _clang = target.type.get_size()
        _python = ctypes.sizeof(getattr(self.namespace, name))
        self.assertEquals(_clang, _python,
                          'Sizes for target: %s Clang:%d Python:%d flags:%s' % (name, _clang,
                                                                                _python, self.parser.flags))
        return

    def assertOffsets(self, name):
        """ Compare offset of records' fields using clang offsets versus
        python offsets.
        name: the name of the structure.
        The findings and offset comparaison of members fields is automatic.
        """
        target = self._get_target_with_struct_hack(name)
        target = target.type.get_declaration()
        self.assertTrue(
            target is not None,
            '%s was not found in source' %
            name)
        members = [c.displayname for c in target.type.get_fields()]
        _clang_type = target.type
        _python_type = getattr(self.namespace, name)
        # let'shandle bitfield - precalculate offsets
        fields_offsets = dict()
        for field_desc in _python_type._fields_:
            _n = field_desc[0]
            _f = getattr(_python_type, _n)
            bfield_bits = _f.size >> 16
            if bfield_bits:
                ofs = 8 * _f.offset + _f.size & 0xFFFF
            else:
                ofs = 8 * _f.offset
            # base offset
            fields_offsets[_n] = ofs
        # now use that
        for member in members:
            _c_offset = _clang_type.get_offset(member)
            #_p_offset = 8*getattr(_python_type, member).offset
            _p_offset = fields_offsets[member]
            self.assertEquals(_c_offset, _p_offset,
                              'Offsets for target: %s.%s Clang:%d Python:%d flags:%s' % (
                                  name, member, _c_offset, _p_offset, self.parser.flags))
        return

__all__ = [
    'get_cursor',
    'get_cursors',
    'get_tu',
    'ArchTest',
]


text:
namespace google {
namespace cloud {
namespace dialogflow_cx_internal {
GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN

WebhooksConnectionImpl::WebhooksConnectionImpl(
    std::unique_ptr<google::cloud::BackgroundThreads> background,
    std::shared_ptr<dialogflow_cx_internal::WebhooksStub> stub, Options options)
    : background_(std::move(background)),
      stub_(std::move(stub)),
      options_(internal::MergeOptions(std::move(options),
                                      WebhooksConnection::options())) {}

StreamRange<google::cloud::dialogflow::cx::v3::Webhook>
WebhooksConnectionImpl::ListWebhooks(
    google::cloud::dialogflow::cx::v3::ListWebhooksRequest request) {
  request.clear_page_token();
  auto& stub = stub_;
  auto retry =
      std::shared_ptr<dialogflow_cx::WebhooksRetryPolicy const>(retry_policy());
  auto backoff = std::shared_ptr<BackoffPolicy const>(backoff_policy());
  auto idempotency = idempotency_policy()->ListWebhooks(request);
  char const* function_name = __func__;
  return google::cloud::internal::MakePaginationRange<
      StreamRange<google::cloud::dialogflow::cx::v3::Webhook>>(
      std::move(request),
      [stub, retry, backoff, idempotency, function_name](
          google::cloud::dialogflow::cx::v3::ListWebhooksRequest const& r) {
        return google::cloud::internal::RetryLoop(
            retry->clone(), backoff->clone(), idempotency,
            [stub](grpc::ClientContext& context,
                   google::cloud::dialogflow::cx::v3::ListWebhooksRequest const&
                       request) {
              return stub->ListWebhooks(context, request);
            },
            r, function_name);
      },
      [](google::cloud::dialogflow::cx::v3::ListWebhooksResponse r) {
        std::vector<google::cloud::dialogflow::cx::v3::Webhook> result(
            r.webhooks().size());
        auto& messages = *r.mutable_webhooks();
        std::move(messages.begin(), messages.end(), result.begin());
        return result;
      });
}

StatusOr<google::cloud::dialogflow::cx::v3::Webhook>
WebhooksConnectionImpl::GetWebhook(
    google::cloud::dialogflow::cx::v3::GetWebhookRequest const& request) {
  return google::cloud::internal::RetryLoop(
      retry_policy(), backoff_policy(),
      idempotency_policy()->GetWebhook(request),
      [this](
          grpc::ClientContext& context,
          google::cloud::dialogflow::cx::v3::GetWebhookRequest const& request) {
        return stub_->GetWebhook(context, request);
      },
      request, __func__);
}

StatusOr<google::cloud::dialogflow::cx::v3::Webhook>
WebhooksConnectionImpl::CreateWebhook(
    google::cloud::dialogflow::cx::v3::CreateWebhookRequest const& request) {
  return google::cloud::internal::RetryLoop(
      retry_policy(), backoff_policy(),
      idempotency_policy()->CreateWebhook(request),
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::cx::v3::CreateWebhookRequest const&
                 request) { return stub_->CreateWebhook(context, request); },
      request, __func__);
}

StatusOr<google::cloud::dialogflow::cx::v3::Webhook>
WebhooksConnectionImpl::UpdateWebhook(
    google::cloud::dialogflow::cx::v3::UpdateWebhookRequest const& request) {
  return google::cloud::internal::RetryLoop(
      retry_policy(), backoff_policy(),
      idempotency_policy()->UpdateWebhook(request),
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::cx::v3::UpdateWebhookRequest const&
                 request) { return stub_->UpdateWebhook(context, request); },
      request, __func__);
}

Status WebhooksConnectionImpl::DeleteWebhook(
    google::cloud::dialogflow::cx::v3::DeleteWebhookRequest const& request) {
  return google::cloud::internal::RetryLoop(
      retry_policy(), backoff_policy(),
      idempotency_policy()->DeleteWebhook(request),
      [this](grpc::ClientContext& context,
             google::cloud::dialogflow::cx::v3::DeleteWebhookRequest const&
                 request) { return stub_->DeleteWebhook(context, request); },
      request, __func__);
}

GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END
}  // namespace dialogflow_cx_internal
}  // namespace cloud
}  // namespace google


text:
class Album < ActiveRecord::Base
  belongs_to :user
  has_many :photo_albums
  has_many :photos, through: :photo_albums
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ScalaCompilerConfiguration">
    <profile name="SBT 1" modules="fpinscala-git">
      <option name="deprecationWarnings" value="true" />
    </profile>
  </component>
</project>


text:
namespace ash {

// A ToggleImageButton with fixed size, paddings and hover effects. These
// buttons are used in the header.
class ASH_EXPORT TrayPopupHeaderButton : public views::ToggleImageButton {
 public:
  static const char kViewClassName[];

  TrayPopupHeaderButton(views::ButtonListener* listener,
                        const gfx::ImageSkia& icon,
                        int accessible_name_id);
  TrayPopupHeaderButton(views::ButtonListener* listener,
                        int enabled_resource_id,
                        int disabled_resource_id,
                        int enabled_resource_id_hover,
                        int disabled_resource_id_hover,
                        int accessible_name_id);
  ~TrayPopupHeaderButton() override;

 private:
  // Overridden from views::View:
  const char* GetClassName() const override;
  gfx::Size GetPreferredSize() const override;

  // Overridden from views::CustomButton:
  void StateChanged() override;

  void Initialize(const gfx::ImageSkia& icon, int accessible_name_id);

  DISALLOW_COPY_AND_ASSIGN(TrayPopupHeaderButton);
};

}  // namespace ash

#endif  // ASH_COMMON_SYSTEM_TRAY_TRAY_POPUP_HEADER_BUTTON_H_


text:
import sys

def find_a_in_a_string(searched_string):

	counter = 0
	for character in searched_string:
		if character == 'a':
			counter = counter + 1
		else:
			continue
	print("There are %s letters 'a' in a string." % counter)

find_a_in_a_string(sys.argv[1])


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: sample.proto

package org.springframework.protobuf;

public interface SecondMsgOrBuilder
    extends com.google.protobuf.MessageOrBuilder {

  // optional int32 blah = 1;
  /**
   * optional int32 blah = 1;
   */
  boolean hasBlah();
  /**
   * optional int32 blah = 1;
   */
  int getBlah();
}


text:
<?php

namespace yellowarmy\MainBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class MainController extends Controller
{
    public function homeAction()
    {

    }

}


text:
package com.app.infrastructure.security;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import com.app.domain.model.types.Persona;

@Service
@Transactional
/**
 *
 * @author David Romero Alcaide
 *
 */
public class UserAccountService {

	// Managed repository -----------------------------------------------------

	@Autowired
	/**
	 *
	 */
	private UserAccountRepository userAccountRepository;

	// Supporting services ----------------------------------------------------

	// Constructors -----------------------------------------------------------

	/**
	 *
	 * Constructor
	 */
	public UserAccountService() {
		super();
	}

	// Simple CRUD methods ----------------------------------------------------
	/**
	 *
	 * @author David Romero Alcaide
	 * @param persona
	 * @return
	 */
	public UserAccount findByPersona(Persona persona) {
		Assert.notNull(persona);

		UserAccount result;

		result = userAccountRepository.findByPersonaId(persona.getId());

		return result;
	}

	/**
	 * @author David Romero Alcaide
	 * @param userAccount
	 */
	public void save(UserAccount userAccount) {
		Assert.notNull(userAccount);
		UserAccount result = userAccountRepository.save(userAccount);
		Assert.notNull(result);
		Assert.isTrue(result.getId() > 0);
	}

	// Other business methods -------------------------------------------------

}


text:
package com.cloud.api.command.user.nat;

import com.cloud.api.APICommand;
import com.cloud.api.ApiConstants;
import com.cloud.api.ApiErrorCode;
import com.cloud.api.BaseCmd;
import com.cloud.api.Parameter;
import com.cloud.api.ServerApiException;
import com.cloud.api.response.IPAddressResponse;
import com.cloud.api.response.NetworkResponse;
import com.cloud.api.response.SuccessResponse;
import com.cloud.api.response.UserVmResponse;
import com.cloud.exception.NetworkRuleConflictException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.IpAddress;
import com.cloud.user.Account;
import com.cloud.uservm.UserVm;
import com.cloud.utils.exception.InvalidParameterValueException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@APICommand(name = "enableStaticNat", description = "Enables static NAT for given IP address", responseObject = SuccessResponse.class,
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class EnableStaticNatCmd extends BaseCmd {
    public static final Logger s_logger = LoggerFactory.getLogger(CreateIpForwardingRuleCmd.class.getName());

    private static final String s_name = "enablestaticnatresponse";

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.IP_ADDRESS_ID, type = CommandType.UUID, entityType = IPAddressResponse.class, required = true, description = "the public IP "
            + "address ID for which static NAT feature is being enabled")
    private Long ipAddressId;

    @Parameter(name = ApiConstants.VIRTUAL_MACHINE_ID, type = CommandType.UUID, entityType = UserVmResponse.class, required = true, description = "the ID of "
            + "the virtual machine for enabling static NAT feature")
    private Long virtualMachineId;

    @Parameter(name = ApiConstants.NETWORK_ID,
            type = CommandType.UUID,
            entityType = NetworkResponse.class,
            description = "The network of the VM the static NAT will be enabled for."
                    + " Required when public IP address is not associated with any guest network yet (VPC case)")
    private Long networkId;
    @Parameter(name = ApiConstants.VM_GUEST_IP,
            type = CommandType.STRING,
            required = false,
            description = "VM guest NIC secondary IP address for the port forwarding rule")
    private String vmSecondaryIp;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    @Override
    public void execute() throws ResourceUnavailableException {
        try {
            final boolean result = _rulesService.enableStaticNat(ipAddressId, virtualMachineId, getNetworkId(), getVmSecondaryIp());
            if (result) {
                final SuccessResponse response = new SuccessResponse(getCommandName());
                this.setResponseObject(response);
            } else {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to enable static NAT");
            }
        } catch (final NetworkRuleConflictException ex) {
            s_logger.info("Network rule conflict: " + ex.getMessage());
            s_logger.trace("Network Rule Conflict: ", ex);
            throw new ServerApiException(ApiErrorCode.NETWORK_RULE_CONFLICT_ERROR, ex.getMessage());
        }
    }

    public long getNetworkId() {
        final IpAddress ip = _entityMgr.findById(IpAddress.class, getIpAddressId());
        Long ntwkId = null;

        if (ip.getAssociatedWithNetworkId() != null) {
            ntwkId = ip.getAssociatedWithNetworkId();
        } else {
            ntwkId = networkId;
        }

        // in case of portable public IP, network ID passed takes precedence
        if (ip.isPortable() && networkId != null) {
            ntwkId = networkId;
        }

        if (ntwkId == null) {
            throw new InvalidParameterValueException("Unable to enable static NAT for the ipAddress id=" + ipAddressId +
                    " as IP is not associated with any network and no networkId is passed in");
        }
        return ntwkId;
    }

    public String getVmSecondaryIp() {
        if (vmSecondaryIp == null) {
            return null;
        }
        return vmSecondaryIp;
    }

    public Long getIpAddressId() {
        return ipAddressId;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        final UserVm userVm = _entityMgr.findById(UserVm.class, getVirtualMachineId());
        if (userVm != null) {
            return userVm.getAccountId();
        }

        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
    }

    public Long getVirtualMachineId() {
        return virtualMachineId;
    }
}


text:
package com.google.android.exoplayer2.upstream;

import com.google.android.exoplayer2.upstream.Loader.Loadable;

import java.io.IOException;

/**
 * Conditionally throws errors affecting a {@link Loader}.
 */
public interface LoaderErrorThrower {

  /**
   * Throws a fatal error, or a non-fatal error if loading is currently backed off and the current
   * {@link Loadable} has incurred a number of errors greater than the {@link Loader}s default
   * minimum number of retries. Else does nothing.
   *
   * @throws IOException The error.
   */
  void maybeThrowError() throws IOException;

  /**
   * Throws a fatal error, or a non-fatal error if loading is currently backed off and the current
   * {@link Loadable} has incurred a number of errors greater than the specified minimum number
   * of retries. Else does nothing.
   *
   * @param minRetryCount A minimum retry count that must be exceeded for a non-fatal error to be
   *     thrown. Should be non-negative.
   * @throws IOException The error.
   */
  void maybeThrowError(int minRetryCount) throws IOException;

  /**
   * A {@link LoaderErrorThrower} that never throws.
   */
  final class Dummy implements LoaderErrorThrower {

    @Override
    public void maybeThrowError() throws IOException {
      // Do nothing.
    }

    @Override
    public void maybeThrowError(int minRetryCount) throws IOException {
      // Do nothing.
    }

  }

}


text:
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using FileClip;
using FileClip.Repositories;
using System.IO;
namespace Tests
{
    [TestClass]
    public class Test_create_repositories
    {
        [TestMethod]
        public void Create_default_repo()
        {
            var filePath=Helper.GetCurrentFolder()+"\\filedb.s3db";
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            string newDir=Path.Combine(Helper.GetCurrentFolder(),"TestDir01");
            if(!Directory.Exists(newDir))
            {
                Directory.CreateDirectory(newDir);
            }

            var repo1 = FileClipManager.GetRepository(new SqliteFileRepository(), newDir);

            var exfilePath=Helper.GetCurrentFolder() +"\\TestFiles\\testDoc1.pdf";
            repo1.StoreFile(exfilePath);
            var fileInfo = repo1.StoreFile(exfilePath);
            var fileInfo2 = repo1.GetFile(fileInfo.Id);
        }

    }
}


text:
from __future__ import absolute_import

from sentry.api.bases.avatar import AvatarMixin
from sentry.api.bases.organization import OrganizationEndpoint
from sentry.models import OrganizationAvatar

class OrganizationAvatarEndpoint(AvatarMixin, OrganizationEndpoint):
    object_type = "organization"
    model = OrganizationAvatar

    def get_avatar_filename(self, obj):
        # for consistency with organization details endpoint
        return u"{}.png".format(obj.slug)


text:
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public static class SceneSearching
{

    // move this to other script
    internal static void Idle(SimpleUnit getSource,
       bool instaResetMov = false, bool instaResetRot = true,
       bool resetMovement = true, bool resetRotation = true)
    {
        getSource.Idle(instaResetMov, instaResetRot, resetMovement, resetRotation);
    }

    public static IEnumerator AttackWithRefuel
        (Transform transform,
        Transform possibleTarget,
        float closestDistance,
        LerpedSideEngine sideEngine,
        float mobility,
        RefuelControl enginesMonitor,
        GunControl gunControl,
        Action onLeft,
        Action onRight)
    {
        // edit: active target isnt private to class but to function
        Transform activeTarget = possibleTarget;
        while (activeTarget != null)
        {
            if (enginesMonitor.needToRefuel)
            {
                break;
            }

            //enginesMonitor.monitoredEngine.Run(true);
            gunControl.FireForwardGuns();

            gunControl.FireRotatingGuns(activeTarget);

            if (Vector3.Distance(activeTarget.position, transform.position) > closestDistance)
            {
                MovementCommands.SmoothRotateTowards(transform, activeTarget.position, mobility, sideEngine);//  function() {Steering(targetPosition)}

            } else
            {
                gunControl.CancelFireForwardGuns();
                yield return Avoid(transform, activeTarget, onLeft, onRight);
            }
            yield return null;
        }
        gunControl.CancelFireForwardGuns();

        //enginesMonitor.monitoredEngine.Run(false);
    }

    public static Collider2D[] ScanArea(Vector3 position, float radius)
    {
        return Physics2D.OverlapCircleAll(position, radius);
    }

    internal static Queue<Vector3> CreateCircularPathAround(this Transform transform, Transform target, int samples, float radiusOfPath,
        bool constructCounterClockwise = false)
    {
        if (samples == 0)
        {
            return null;
        }

        int minDisti = -1;
        float minDistToTransform = float.MaxValue;

        // clockwise path
        Vector3[] temp = new Vector3[samples];
        for (int i = 0; i < samples; i++)
        {
            var a = (2 * Mathf.PI / samples) * i;
            var x = target.position.x + radiusOfPath * Mathf.Cos(a);
            var y = target.position.y + radiusOfPath * Mathf.Sin(a);
            var vec = new Vector2(x, y);

            temp[i] = vec;

            // get min
            var dist = Vector3.Distance(vec, transform.position);
            if (dist < minDistToTransform)
            {
                minDisti = i;
                minDistToTransform = dist;
            }
        }

        // turn around into counterclockwise if necessary
        if (constructCounterClockwise)
        {
            // len/2 goes up to middle, inclusive
            for (int i = 0; i < temp.Length/2; i++)
            {
                var val1 = temp[temp.Length-i-1];
                temp[temp.Length - i - 1] = temp[i];
                temp[i] = val1;
            }
        }

        // construct path to start at secondpoint in circle, this insures it wont go in reverse because first point is too close
        // you can fix that by checking if point is in front of transform
        Queue<Vector3> result = new Queue<Vector3>();
        for (int i = minDisti+1; i != minDisti; i=(i+1)% temp.Length)
        {
            Debug.DrawLine(temp[i], temp[(i+temp.Length-1)%temp.Length], Color.red, 10);
            result.Enqueue(temp[i]);
        }

        return result;
    }

    /// <summary>
    /// Avoid the target to certain distance by going left or right
    /// Doesn't check if there is no movement.
    /// You can do same version witout coroutine
    ///
    /// This is tehnicaly beahviour
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="activeTarget"></param>
    /// <param name="avoidToDistance"></param>
    /// <returns></returns>
    public static IEnumerator Avoid(Transform transform,
        Transform target, Action OnLeft, Action OnRight, float avoidToDistance = 1
        )
    {
        string state = "";
        //rotate away for a while. its still going forward
        while (true)
        {
            if (Avoid(transform, target.position, avoidToDistance, ref state))
            {
                if (state == "left")
                {
                    // TODO: state = left
                    //Left();
                    OnLeft();
                }
                if (state == "right")
                {
                    //Right();
                    OnRight();
                }
            } else
            {
                break;
            }
            yield return null;
        }
    }

    /// <summary>
    /// sets state to left or right while if target is too close
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="target"></param>
    /// <param name="avoidToDistance"></param>
    /// <param name="state"></param>
    /// <returns></returns>
    public static bool Avoid(Transform transform,
        Vector3 target, float avoidToDistance
        , ref string state)
    {
        // avoid direction is chosen randomly based on time.
        // todo: you should chose it on min angle avoid target
        int choice = ((int)Time.time) % 2;
        state = "";

        float dist = Vector3.Distance(target, transform.position);
        if (dist > avoidToDistance)
        {
            return false;
        }

        if (choice == 0)
        {
            // TODO: state = left
            state = "left";
        } else
        {
            state = "right";
        }
        return true;
    }

    /// <summary>
    /// Returns first enemy scanned based on alliances
    /// -Previous version was based on spaceships-
    /// </summary>
    /// <param name="scanRange"></param>
    /// <param name="alliance"></param>
    /// <param name="drawRays"></param>
    /// <returns></returns>
    public static Collider2D Collision2DScan(this Transform transform, float scanRange, string alliance, bool drawRays = false)
    {
        Collider2D[] scanned = Physics2D.OverlapCircleAll(transform.position, scanRange, 1 << LayerMask.NameToLayer("Scan"));
        Collider2D enemy = null;
        for (int i = 0; i < scanned.Length; i++)
        {
            Alliance sp = scanned[i].transform.root.GetComponent<Alliance>();
            if (sp && sp.alliance != alliance)
            {
                enemy = scanned[i];
                break;
            }
        }
        if (drawRays)
        {
            Debug.DrawRay(transform.position - (Vector3.up + Vector3.right) * scanRange, (Vector3.up + Vector3.right) * 2 * scanRange);
            Debug.DrawRay(transform.position - (Vector3.up + Vector3.left) * scanRange, (Vector3.up + Vector3.left) * 2 * scanRange);
        }
        return enemy;
    }

    internal static void MoveTo(Transform transform, SimpleUnit getSource, Vector3 target, float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
        float nearbyRange = 1, float nearbyToTargetSpeedMod = 1)
    {
        howNear = Mathf.Clamp(howNear, 0, float.MaxValue);
        nearbyRange = Mathf.Clamp(nearbyRange, howNear, float.MaxValue);

        getSource.ModifySpeed(farSpeedMod);
        // use custom or default distance calculation
        float dist = DefaultDistance(transform, target);
        if (dist < nearbyRange)
        {
            getSource.ModifySpeed(nearbyToTargetSpeedMod);
        }
        if (dist > howNear)
        {
            GoTo(transform, getSource, target + Vector3.up);
        } else
        {
            //Idle();
            Idle(getSource);
            getSource.steering = getSource.nonModifiedSteering;
            //getSource.Idle();
        }
    }

    internal static IEnumerator MoveToPos(Transform transform, SimpleUnit getSource, Vector3 target, bool idleAtEnd, float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
        float nearbyRange = 1, float nearbyToTargetSpeedMod = 1)
    {
        nearbyRange = Mathf.Clamp(nearbyRange, howNear, nearbyRange);
        while (true)
        {
            howNear = Mathf.Clamp(howNear, 0, float.MaxValue);
            nearbyRange = Mathf.Clamp(nearbyRange, howNear, float.MaxValue);

            getSource.ModifySpeed(farSpeedMod);
            // use custom or default distance calculation
            GoTo(transform, getSource, target + Vector3.up);
            float dist = DefaultDistance(transform, target);
            if (dist < nearbyRange)
            {
                getSource.ModifySpeed(nearbyToTargetSpeedMod);
                if (dist > howNear)
                {
                    getSource.ModifySpeed(nearSpeedMod);
                } else
                {
                    if (idleAtEnd)
                    {
                        getSource.steering = getSource.nonModifiedSteering;
                        Idle(getSource);
                    }
                    break;
                }
            }
            yield return null;
        }
    }

    internal static IEnumerator FollowTarget_v2(Transform transform, SimpleUnit unit, Transform target, OverrideTravel travelInfo,
        bool stopWitoutTarget
        , float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
        float nearbyRange = 1, float nearbyToTargetSpeedMod = 1) {
        while (true) {
            if (travelInfo != null) {
                if (travelInfo.applySecondaryTravel) {
                    // Debug.DrawLine(transform.position, travelInfo.secondaryTravel, Color.green);
                    GoTo(transform, unit, travelInfo.secondaryTravel, howNear, nearSpeedMod, farSpeedMod, nearbyRange, nearbyToTargetSpeedMod);
                } else {
                    // Debug.DrawLine(transform.position, travelInfo.target.position, Color.red);
                    if (!Follow(transform, unit, travelInfo.target, stopWitoutTarget, howNear, nearSpeedMod, farSpeedMod, nearbyRange, nearbyToTargetSpeedMod))
                        break;
                }
            }else {
                Debug.Log("Apply travel info", transform);
            }
            yield return null;
        }
        // go idle, dont reset movement if it has to go forward
        unit.steering = unit.nonModifiedSteering;
        unit.Idle(resetMovement: stopWitoutTarget);
    }

    /// <summary>
    /// This version is ok for specific use
    /// </summary>
    /// <param name="getSource"></param>
    /// <param name="target"></param>
    /// <param name="stopWitoutTarget"></param>
    /// <param name="howNear"></param>
    /// <param name="distanceCalculation"></param>
    /// <returns></returns>
    public static IEnumerator FollowTarget(Transform transform, SimpleUnit getSource, Transform target, bool stopWitoutTarget
        , float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
        float nearbyRange = 1, float nearbyToTargetSpeedMod = 1, Func<Transform, float> distanceCalculation = null)
    {
        while (target)
        {
            if (!Follow(transform, getSource, target, stopWitoutTarget, howNear, nearSpeedMod, farSpeedMod, nearbyRange, nearbyToTargetSpeedMod, distanceCalculation))
                break;
            yield return null;
        }
        // go idle, dont reset movement if it has to go forward
        getSource.steering = getSource.nonModifiedSteering;
        getSource.Idle(resetMovement: stopWitoutTarget);
    }

    public static bool Follow(Transform transform, SimpleUnit getSource, Transform target, bool stopWitoutTarget, float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
    float nearbyRange = 1, float nearbyToTargetSpeedMod = 1, Func<Transform, float> distanceCalculation = null)
    {
        GoTo(transform, getSource, target, howNear, nearSpeedMod, farSpeedMod, nearbyRange, nearbyToTargetSpeedMod);
        // use custom or default distance calculation
        if (!((distanceCalculation != null && distanceCalculation(target) > howNear)
            || (distanceCalculation == null && DefaultDistance(transform, target.position) > howNear)))
            return false;
        return true;
    }

    internal static float DefaultDistance(Transform transform, Vector3 target)
    {
        return Vector3.Distance(transform.position, target);
    }

    /// <summary>
    /// Choses first unit in array that isn't itself
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="scene"></param>
    /// <returns></returns>
    public static Transform ChoseFirstTarget(Transform transform)//, UnitsInScene scene)
    {
        Transform target = null;
        Alliance[] units = UnitsInScene.GetAllUnits().ToArray();
        for (int i = 0; i < units.Length; i++)//scene.
        {
            if (units[i] == transform)
            {
                continue;
            }
            target = units[i].transform;
            break;
        }
        return target;
    }

    public static Transform ChoseClosestTarget(Transform transform, string flag)
    {
        Alliance[] units = UnitsInScene.GetEnemyShips(flag).ToArray();
        float minDist = float.MaxValue;
        int imin = -1;
        for (int i = 0; i < units.Length; i++)
        {
            if (units[i] == null)
            {
                continue;
            }
            if (units[i].alliance != flag)
            {
                if (minDist > Vector3.Distance(units[i].transform.position, transform.position))
                {
                    imin = i;
                }
            }
        }
        return imin == -1 ? null : units[imin].transform;
    }

    public static void GoTo(Transform transform, SimpleUnit getSource, Transform target, float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
    float nearbyRange = 1, float nearbyToTargetSpeedMod = 1)
    {
        if (!target)
        {
            return;
        }
        GoTo(transform, getSource, target.position, howNear, nearSpeedMod, farSpeedMod, nearbyRange, nearbyToTargetSpeedMod);
    }

    public static void TurnTowards(this Transform transform, AiInfo ai, Vector3 target) {

        float angle = Vector3.Angle(transform.up, target - transform.position);
        Vector3 axis = Vector3.Cross(transform.up, target - transform.position);

        ai.Get();
        float rotationAccuracyAngle = ai.rotationAccuracy;
        float rotationInnerAccuracyAngle = ai.innerAccuracy;
        float slowSteeringSpeed = ai.slowDownEffect;
        float regularSteeringSpeed = ai.nonModifiedSteering;
        SimpleUnit source = ai.source;

        if (angle > rotationAccuracyAngle) {
            source.steering = regularSteeringSpeed;
            MovementCommands.ExecuteRotationTo(source, axis.z);
        } else {
            source.steering = slowSteeringSpeed;
            if (angle > rotationInnerAccuracyAngle) {
                MovementCommands.ExecuteRotationTo(source, axis.z);
            } else {
                source.steering = regularSteeringSpeed;
                source.Idle(resetMovement: false); // reset rotation
            }
        }
    }

    /// <summary>
    /// travels to point update, goes into idle when if it arrived.
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="getSource"></param>
    /// <param name="target"></param>
    /// <param name="howNear"></param>
    /// <param name="nearSpeedMod"></param>
    /// <param name="farSpeedMod"></param>
    /// <param name="nearbyRange"></param>
    /// <param name="nearbyToTargetSpeedMod"></param>
    public static void GoTo(Transform transform, SimpleUnit getSource,
        Vector3 target
     , float howNear = 0.1f, float nearSpeedMod = 1, float farSpeedMod = 1,
    float nearbyRange = 1, float nearbyToTargetSpeedMod = 1)
    {
        if (DefaultDistance(transform, target) > howNear) {
            TurnTowards(transform, getSource, target, 1f, getSource.steering, 0.01f, getSource.steering / 5);

            getSource.ExecuteMove(SimpleUnit.Moves.forward);
        }else
        getSource.Idle();
    }

    /// <summary>
    /// Rotates towards target 2 ways to rotate to target + smooth accurate rotation:
    /// when inside rotation rotate with normal speed
    /// when inside smooth rotation use slow speed
    ///
    /// Example move params: 1f, getSource.steering, 0.01f, getSource.steering / 5
    /// </summary>
    /// <param name="transform"></param>
    /// <param name="getSource"></param>
    /// <param name="target"></param>
    /// <param name="targetUp"></param>
    /// <param name="normalRotationAccuracy"></param>
    /// <param name="slowSpeed"></param>
    /// <param name="smoothRotationAccuracy"></param>
    /// <param name="drawLine"></param>
    public static void TurnTowards(Transform transform, SimpleUnit getSource, Vector3 target
        , float normalRotationAccuracy, float normalSpeed, float slowSpeed, float smoothRotationAccuracy)
    {
        float angle = Vector3.Angle(transform.up, target - transform.position);
        Vector3 axis = Vector3.Cross(transform.up, target - transform.position);

        if (angle > normalRotationAccuracy)
        {
            getSource.steering = normalSpeed;// getSource.nonModifiedRotation
            MovementCommands.ExecuteRotationTo(getSource, axis.z);
        } else
        {
            getSource.steering = slowSpeed;
            if (angle > smoothRotationAccuracy)
            {
                MovementCommands.ExecuteRotationTo(getSource, axis.z);
            } else
            {
                getSource.steering = getSource.nonModifiedSteering;
                getSource.Idle(resetMovement: false); // reset rotation
            }
        }
    }

    /// <summary>
    /// finds direction of target relative to the ship - left or right
    /// </summary>
    /// <returns></returns>
    public static int GetSideToTarget(Transform transform, Vector3 targetPosition)
    {
        var relativePoint = transform.InverseTransformPoint(targetPosition);
        if (relativePoint.x <= 0.0) // change into < later. and change 0.0s into something else to have better forward
            return 1;
        //print ("Object is to the left");
        else if (relativePoint.x > 0.0)
        {
            return -1;
            //print ("Object is to the right");
        } else
        {
            return 0;
            //print ("Object is directly ahead");
        }
    }

    /// <summary>
    /// Travel along the whole path
    /// </summary>
    /// <returns></returns>
    public static IEnumerator TravelPath(Transform transform, QuePath travel, Vector3 targetPos)
    {
        while (travel.NodeCount() > 0)
        {
            Debug.DrawLine(transform.position, targetPos, Color.red, 5);
            while (Vector3.Distance(targetPos, transform.position) > 1f)
            {
                yield return null;
            }
            targetPos = travel.NextNode().transform.position;// when arrive to it, go to next
        }
    }

    /// <summary>
    /// Chose path and go near first node
    /// </summary>
    /// <returns></returns>
    public static IEnumerator EnterPath(Transform transform, Vector3 targetPos,
        CircularPath targetsNodes, QuePath travel)
    {
        travel = targetsNodes.GetPath(targetsNodes.Closest(transform.position), 2);
        QuePath bakFullPath = travel;// unused

        targetPos = travel.NextNode().transform.position;//get first node
        Debug.DrawLine(transform.position, targetPos, Color.blue, 5);

        while (Vector3.Distance(targetPos, transform.position) > 1f)
        {
            yield return null;
        }
    }

    /// <summary>
    /// Calls updates while going between waypoins.
    /// Doesnt actualy move, just a behaviour interface.
    /// </summary>
    /// <param name="targetPos"></param>
    /// <param name="howClose"></param>
    /// <param name="onUpdate"></param>
    /// <param name="onClose"></param>
    /// <param name="onArrive"></param>
    /// <returns></returns>
    public static IEnumerator TravelInPath(Transform transform, Vector3[] targetPos,
        float howClose = 1f, Action<Vector3, float> onUpdate = null,
        Action<Vector3> onClose = null, Action onArrive = null)
    {
        int i = 0;
        float dist = 1;
        while (i < targetPos.Length)
        {
            dist = Vector3.Distance(targetPos[i], transform.position);
            if (onUpdate != null)
            onUpdate(targetPos[i], dist);
            if (dist <= howClose)
            {
                i++;
                if (onClose != null)
                onClose(targetPos[i]);// send new target pos
            }
            yield return null;
        }
        onArrive();
    }

    [System.Obsolete("remove this function")]
    public static bool DistanceTooBig(Vector3 targetPos, Vector3 transformPos)
    {
        if (Vector3.Distance(targetPos, transformPos) < 1f)
        {
            return false;
        }
        return true;
    }

    /// <summary>
    /// It goes like this: scan 1 ship, assign all ships in range to it and remove them from next scans
    /// Repeat for all and return array with all ranges
    /// </summary>
    /// <param name="blastRadius">Put your explosion radius here</param>
    public static Transform GetApproximationOfGroupCount(MonoBehaviour requestedBy, int shipCount, ref float approxAverageNumOfShipsPerScan, Transform[] allShips, float blastRadius = 100)
    {
        Transform[] shipsNotScanned = new Transform[shipCount];

        bool[] ignore = new bool[shipCount];

        // use statistics to quick chose targets
        int maxCount = 0;
        Transform maxCountShip = null;
        int sum = 0;
        int count = 0;
        for (int i = 0; i < shipCount; i++)
        {
            if (ignore[i])
            {
                continue;
            }
            Transform unit = shipsNotScanned[i];
            if (unit == null)
            {
                continue;
            }
            //print(unit);
            //Debug.DrawRay(unit.position, Vector2.up * blastRadius, Color.cyan, 5);
            Collider2D[] results = Physics2D.OverlapCircleAll(unit.position, blastRadius, 1 << LayerMask.NameToLayer("Detection"));
            int unitCount = results.Length;
            //print(allShips.Count + " "+requestedBy + " " + results.Length + " " + unitCount);

            count++;
            sum += unitCount;

            for (int j = 0; j < results.Length; j++)
            {
                int index = IndexOf(results[j].transform.root, allShips);
                if (index > -1 && !ignore[index])
                {
                    //print(requestedBy + " " + results[j] + " " + results[j].transform.root);
                    ignore[index] = true;
                }
            }

            if (unitCount > maxCount)
            {
                maxCount = unitCount;
                maxCountShip = unit;
            }

            // early exit if optimal group is found. this will lead to towers shooting to the group 1 or 2 times before avg will increase and search will broaden
            if (approxAverageNumOfShipsPerScan > 0 && unitCount / 2 > approxAverageNumOfShipsPerScan)
            {
                break;
            }
        }

        if (maxCountShip == null)
        {
            return null;
        }

        approxAverageNumOfShipsPerScan = sum / count;
        return maxCountShip;
    }

    public static int IndexOf(Transform root, Transform[] allShips)
    {
        for (int i = 0; i < allShips.Length; i++)
        {
            if (root == allShips[i].transform)
            {
                return i;
            }
        }
        return -1;
    }

    internal static void GetDistanceSorted(Vector3 calcFrom, List<Alliance> allShips, ref TargetsDistanceSortedList<Component> sortList) {
        for (int i = 0; i < allShips.Count; i++) {
            if (allShips[i] == null) { UnitsInScene.RequestNullUpdate(); continue; }
            Transform ship = allShips[i].transform;

            float dist = Mathf.Pow(ship.position.x - calcFrom.x, 2) + Mathf.Pow(ship.position.x - calcFrom.y, 2);
            sortList.Set(ship, dist);
        }
    }

    internal static bool ContainsTransform(Transform[] sortList, Transform ship) {
        return false;
    }

    internal static List<T> GetDistanceSorted<T>(Vector3 calcFrom, ref List<T> allShips) where T : MonoBehaviour {
        List<TargetDist<T>> sorted = GetDistanceSorted<T>(calcFrom, allShips);
        List<T> sortedDist = new List<T>();
        for (int i = 0; i < sorted.Count; i++) {
            sortedDist.Add(sorted[i].target);
        }
        return sortedDist;
    }

    internal static List<TargetDist<T>> GetDistanceSorted<T>(Vector3 calcFrom, List<T> allShips) where T: MonoBehaviour {
        List<TargetDist<T>> sortedDist = new List<TargetDist<T>>();

        for (int i = 0; i < allShips.Count; i ++) {
            Transform ship = allShips[i].transform;
            if (ship == null) { UnitsInScene.RequestNullUpdate(); continue; }

            float dist = Mathf.Pow(ship.position.x - calcFrom.x, 2) + Mathf.Pow(ship.position.x- calcFrom.y, 2);

            // insertion sort
            int j = i;
            while (j > 0 && sortedDist[j-1].dist > dist) {
                j--;// you can put like /2 or smth here to speed it up into binary log n. but it will be innacurate
            }
            sortedDist.Insert(j, new TargetDist<T>(allShips[i], dist));
        }
        return sortedDist;
    }

    internal static Transform GetClosestShip(MonoBehaviour requestBy, int optimizationSteps, Transform[] allShips)
    {
        Transform min = null;
        float mind = float.MaxValue;
        for (int i = 0; i < allShips.Length; i += optimizationSteps) {
            Transform ship = allShips[i];
            if (ship == null) {
                continue;
            }
            float dist = Mathf.Pow(ship.position.x - requestBy.transform.position.x, 2) + Mathf.Pow(ship.position.x - requestBy.transform.position.y, 2);
            if (dist < mind) {
                min = allShips[i];
                mind = dist;
            }
        }
        return min;
    }

}

class TargetsDistanceSortedList<Component> : List<TargetDist<Component>> where Component: UnityEngine.Component{
    public bool Contains(Transform obj) {
        for (int i = 0; i < Count; i++) {
            if (this[i].target.transform == obj) {
                return true;
            }
        }
        return false;
    }

    internal void Add(Transform ship, float dist) {
        base.Add(new TargetDist<Component>(ship as Component, dist));
    }

    internal void Set(Transform key, float value) {
        for (int i = 0; i < Count; i++) {
            if (this[i].target == key) {
                this[i].dist = value;
                return;
            }
        }
        // not found
        Add(key, value);
    }
}

class TargetDist<T> where T:Component {
    public T target;
    public float dist;

    public TargetDist(T target, float dist) {
        this.target = target;
        this.dist = dist;
    }
}