text:
import re
import string
from functools import partial
from inspect import signature
from typing import Any, Dict, List, Optional

from django.http import HttpRequest, HttpResponse

from zerver.decorator import log_exception_to_webhook_logger, webhook_view
from zerver.lib.exceptions import UnsupportedWebhookEventType
from zerver.lib.request import REQ, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import (
    check_send_webhook_message,
    validate_extract_webhook_http_header,
)
from zerver.lib.webhooks.git import (
    TOPIC_WITH_BRANCH_TEMPLATE,
    TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE,
    get_commits_comment_action_message,
    get_force_push_commits_event_message,
    get_issue_event_message,
    get_pull_request_event_message,
    get_push_commits_event_message,
    get_push_tag_event_message,
    get_remove_branch_event_message,
)
from zerver.models import UserProfile

BITBUCKET_TOPIC_TEMPLATE = '{repository_name}'

BITBUCKET_FORK_BODY = "{actor} forked the repository into [{fork_name}]({fork_url})."
BITBUCKET_COMMIT_STATUS_CHANGED_BODY = ('[System {key}]({system_url}) changed status of'
                                        ' {commit_info} to {status}.')
BITBUCKET_REPO_UPDATED_CHANGED = ('{actor} changed the {change} of the **{repo_name}**'
                                  ' repo from **{old}** to **{new}**')
BITBUCKET_REPO_UPDATED_ADDED = '{actor} changed the {change} of the **{repo_name}** repo to **{new}**'

PULL_REQUEST_SUPPORTED_ACTIONS = [
    'approved',
    'unapproved',
    'created',
    'updated',
    'rejected',
    'fulfilled',
    'comment_created',
    'comment_updated',
    'comment_deleted',
]

@webhook_view('Bitbucket2')
@has_request_variables
def api_bitbucket2_webhook(request: HttpRequest, user_profile: UserProfile,
                           payload: Dict[str, Any]=REQ(argument_type='body'),
                           branches: Optional[str]=REQ(default=None),
                           user_specified_topic: Optional[str]=REQ("topic", default=None)) -> HttpResponse:
    type = get_type(request, payload)
    if type == 'push':
        # ignore push events with no changes
        if not payload['push']['changes']:
            return json_success()
        branch = get_branch_name_for_push_event(payload)
        if branch and branches:
            if branches.find(branch) == -1:
                return json_success()

    subject = get_subject_based_on_type(payload, type)
    body_function = get_body_based_on_type(type)
    if 'include_title' in signature(body_function).parameters:
        body = body_function(
            payload,
            include_title=user_specified_topic is not None,
        )
    else:
        body = body_function(payload)

    if type != 'push':
        check_send_webhook_message(request, user_profile, subject,
                                   body, unquote_url_parameters=True)
    else:
        for b, s in zip(body, subject):
            check_send_webhook_message(request, user_profile, s, b,
                                       unquote_url_parameters=True)

    return json_success()

def get_subject_for_branch_specified_events(payload: Dict[str, Any],
                                            branch_name: Optional[str]=None) -> str:
    return TOPIC_WITH_BRANCH_TEMPLATE.format(
        repo=get_repository_name(payload['repository']),
        branch=get_branch_name_for_push_event(payload) if branch_name is None else branch_name,
    )

def get_push_subjects(payload: Dict[str, Any]) -> List[str]:
    subjects_list = []
    for change in payload['push']['changes']:
        potential_tag = (change['new'] or change['old'] or {}).get('type')
        if potential_tag == 'tag':
            subjects_list.append(str(get_subject(payload)))
        else:
            if change.get('new'):
                branch_name = change['new']['name']
            else:
                branch_name = change['old']['name']
            subjects_list.append(str(get_subject_for_branch_specified_events(payload, branch_name)))
    return subjects_list

def get_subject(payload: Dict[str, Any]) -> str:
    assert(payload['repository'] is not None)
    return BITBUCKET_TOPIC_TEMPLATE.format(repository_name=get_repository_name(payload['repository']))

def get_subject_based_on_type(payload: Dict[str, Any], type: str) -> Any:
    if type.startswith('pull_request'):
        return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=get_repository_name(payload['repository']),
            type='PR',
            id=payload['pullrequest']['id'],
            title=payload['pullrequest']['title'],
        )
    if type.startswith('issue'):
        return TOPIC_WITH_PR_OR_ISSUE_INFO_TEMPLATE.format(
            repo=get_repository_name(payload['repository']),
            type='Issue',
            id=payload['issue']['id'],
            title=payload['issue']['title'],
        )
    if type == 'push':
        return get_push_subjects(payload)
    return get_subject(payload)

def get_type(request: HttpRequest, payload: Dict[str, Any]) -> str:
    if payload.get('push'):
        return 'push'
    elif payload.get('fork'):
        return 'fork'
    elif payload.get('comment') and payload.get('commit'):
        return 'commit_comment'
    elif payload.get('commit_status'):
        return 'change_commit_status'
    elif payload.get('issue'):
        if payload.get('changes'):
            return "issue_updated"
        if payload.get('comment'):
            return 'issue_commented'
        return "issue_created"
    elif payload.get('pullrequest'):
        pull_request_template = 'pull_request_{}'
        # Note that we only need the HTTP header to determine pullrequest events.
        # We rely on the payload itself to determine the other ones.
        event_key = validate_extract_webhook_http_header(request, "X_EVENT_KEY", "BitBucket")
        assert event_key is not None
        action = re.match('pullrequest:(?P<action>.*)$', event_key)
        if action:
            action_group = action.group('action')
            if action_group in PULL_REQUEST_SUPPORTED_ACTIONS:
                return pull_request_template.format(action_group)
    else:
        event_key = validate_extract_webhook_http_header(request, "X_EVENT_KEY", "BitBucket")
        if event_key == 'repo:updated':
            return event_key

    raise UnsupportedWebhookEventType(event_key)

def get_body_based_on_type(type: str) -> Any:
    fn = GET_SINGLE_MESSAGE_BODY_DEPENDING_ON_TYPE_MAPPER.get(type)
    return fn

def get_push_bodies(payload: Dict[str, Any]) -> List[str]:
    messages_list = []
    for change in payload['push']['changes']:
        potential_tag = (change['new'] or change['old'] or {}).get('type')
        if potential_tag == 'tag':
            messages_list.append(get_push_tag_body(payload, change))
        # if change['new'] is None, that means a branch was deleted
        elif change.get('new') is None:
            messages_list.append(get_remove_branch_push_body(payload, change))
        elif change.get('forced'):
            messages_list.append(get_force_push_body(payload, change))
        else:
            messages_list.append(get_normal_push_body(payload, change))
    return messages_list

def get_remove_branch_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:
    return get_remove_branch_event_message(
        get_actor_info(payload),
        change['old']['name'],
    )

def get_force_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:
    return get_force_push_commits_event_message(
        get_actor_info(payload),
        change['links']['html']['href'],
        change['new']['name'],
        change['new']['target']['hash'],
    )

def get_commit_author_name(commit: Dict[str, Any]) -> str:
    if commit['author'].get('user'):
        return get_user_info(commit['author']['user'])
    return commit['author']['raw'].split()[0]

def get_normal_push_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:
    commits_data = [{
        'name': get_commit_author_name(commit),
        'sha': commit.get('hash'),
        'url': commit.get('links').get('html').get('href'),
        'message': commit.get('message'),
    } for commit in change['commits']]

    return get_push_commits_event_message(
        get_actor_info(payload),
        change['links']['html']['href'],
        change['new']['name'],
        commits_data,
        is_truncated=change['truncated'],
    )

def get_fork_body(payload: Dict[str, Any]) -> str:
    return BITBUCKET_FORK_BODY.format(
        actor=get_user_info(payload["actor"]),
        fork_name=get_repository_full_name(payload['fork']),
        fork_url=get_repository_url(payload['fork']),
    )

def get_commit_comment_body(payload: Dict[str, Any]) -> str:
    comment = payload['comment']
    action = '[commented]({})'.format(comment['links']['html']['href'])
    return get_commits_comment_action_message(
        get_actor_info(payload),
        action,
        comment['commit']['links']['html']['href'],
        comment['commit']['hash'],
        comment['content']['raw'],
    )

def get_commit_status_changed_body(payload: Dict[str, Any]) -> str:
    commit_api_url = payload['commit_status']['links']['commit']['href']
    commit_id = commit_api_url.split('/')[-1]

    commit_info = "[{short_commit_id}]({repo_url}/commits/{commit_id})".format(
        repo_url=get_repository_url(payload['repository']),
        short_commit_id=commit_id[:7],
        commit_id=commit_id,
    )

    return BITBUCKET_COMMIT_STATUS_CHANGED_BODY.format(
        key=payload['commit_status']['key'],
        system_url=payload['commit_status']['url'],
        commit_info=commit_info,
        status=payload['commit_status']['state'],
    )

def get_issue_commented_body(payload: Dict[str, Any],
                             include_title: bool=False) -> str:
    action = '[commented]({}) on'.format(payload['comment']['links']['html']['href'])
    return get_issue_action_body(payload, action, include_title)

def get_issue_action_body(payload: Dict[str, Any], action: str,
                          include_title: bool=False) -> str:
    issue = payload['issue']
    assignee = None
    message = None
    if action == 'created':
        if issue['assignee']:
            assignee = get_user_info(issue['assignee'])
        message = issue['content']['raw']

    return get_issue_event_message(
        get_actor_info(payload),
        action,
        issue['links']['html']['href'],
        issue['id'],
        message,
        assignee,
        title=issue['title'] if include_title else None,
    )

def get_pull_request_action_body(payload: Dict[str, Any], action: str,
                                 include_title: bool=False) -> str:
    pull_request = payload['pullrequest']
    return get_pull_request_event_message(
        get_actor_info(payload),
        action,
        get_pull_request_url(pull_request),
        pull_request.get('id'),
        title=pull_request['title'] if include_title else None,
    )

def get_pull_request_created_or_updated_body(payload: Dict[str, Any], action: str,
                                             include_title: bool=False) -> str:
    pull_request = payload['pullrequest']
    assignee = None
    if pull_request.get('reviewers'):
        assignee = get_user_info(pull_request.get('reviewers')[0])

    return get_pull_request_event_message(
        get_actor_info(payload),
        action,
        get_pull_request_url(pull_request),
        pull_request.get('id'),
        target_branch=pull_request['source']['branch']['name'],
        base_branch=pull_request['destination']['branch']['name'],
        message=pull_request['description'],
        assignee=assignee,
        title=pull_request['title'] if include_title else None,
    )

def get_pull_request_comment_created_action_body(
        payload: Dict[str, Any],
        include_title: bool=False,
) -> str:
    action = '[commented]({})'.format(payload['comment']['links']['html']['href'])
    return get_pull_request_comment_action_body(payload, action, include_title)

def get_pull_request_deleted_or_updated_comment_action_body(
        payload: Dict[str, Any], action: str,
        include_title: bool=False,
) -> str:
    action = "{} a [comment]({})".format(action, payload['comment']['links']['html']['href'])
    return get_pull_request_comment_action_body(payload, action, include_title)

def get_pull_request_comment_action_body(
        payload: Dict[str, Any], action: str,
        include_title: bool=False,
) -> str:
    action += ' on'
    return get_pull_request_event_message(
        get_actor_info(payload),
        action,
        payload['pullrequest']['links']['html']['href'],
        payload['pullrequest']['id'],
        message=payload['comment']['content']['raw'],
        title=payload['pullrequest']['title'] if include_title else None,
    )

def get_push_tag_body(payload: Dict[str, Any], change: Dict[str, Any]) -> str:
    if change.get('new'):
        tag = change['new']
        action = 'pushed'
    elif change.get('old'):
        tag = change['old']
        action = 'removed'

    return get_push_tag_event_message(
        get_actor_info(payload),
        tag.get('name'),
        tag_url=tag['links']['html'].get('href'),
        action=action,
    )

def append_punctuation(title: str, message: str) -> str:
    if title[-1] not in string.punctuation:
        message = f"{message}."

    return message

def get_repo_updated_body(payload: Dict[str, Any]) -> str:
    changes = ['website', 'name', 'links', 'language', 'full_name', 'description']
    body = ""
    repo_name = payload['repository']['name']
    actor = get_actor_info(payload)

    for change in changes:
        new = payload['changes'][change]['new']
        old = payload['changes'][change]['old']
        if change == 'full_name':
            change = 'full name'
        if new and old:
            message = BITBUCKET_REPO_UPDATED_CHANGED.format(
                actor=actor, change=change, repo_name=repo_name,
                old=old, new=new,
            )
            message = append_punctuation(new, message) + '\n'
            body += message
        elif new and not old:
            message = BITBUCKET_REPO_UPDATED_ADDED.format(
                actor=actor, change=change, repo_name=repo_name, new=new,
            )
            message = append_punctuation(new, message) + '\n'
            body += message

    return body

def get_pull_request_url(pullrequest_payload: Dict[str, Any]) -> str:
    return pullrequest_payload['links']['html']['href']

def get_repository_url(repository_payload: Dict[str, Any]) -> str:
    return repository_payload['links']['html']['href']

def get_repository_name(repository_payload: Dict[str, Any]) -> str:
    return repository_payload['name']

def get_repository_full_name(repository_payload: Dict[str, Any]) -> str:
    return repository_payload['full_name']

def get_user_info(dct: Dict[str, Any]) -> str:
    # See https://developer.atlassian.com/cloud/bitbucket/bitbucket-api-changes-gdpr/
    # Since GDPR, we don't get username; instead, we either get display_name
    # or nickname.
    if "display_name" in dct:
        return dct["display_name"]

    if "nickname" in dct:
        return dct["nickname"]

    log_exception_to_webhook_logger(
        summary="Could not find display_name/nickname field",
        # We call this an unsupported_event, even though we
        # are technically still sending a message.
        unsupported_event=True,
    )

    if "username" in dct:
        # We don't expect this to happen after April 2019; this is
        # just defensive code, plus it allows us to avoid changing
        # a bunch of test fixtures.  We will want to delete this code
        # as soon as we have confidence that we don't get errors
        # related to display_name/nickname being missing. (see above
        # code)
        return dct["username"]

    return "Unknown user"

def get_actor_info(payload: Dict[str, Any]) -> str:
    actor = payload['actor']
    return get_user_info(actor)

def get_branch_name_for_push_event(payload: Dict[str, Any]) -> Optional[str]:
    change = payload['push']['changes'][-1]
    potential_tag = (change['new'] or change['old'] or {}).get('type')
    if potential_tag == 'tag':
        return None
    else:
        return (change['new'] or change['old']).get('name')

GET_SINGLE_MESSAGE_BODY_DEPENDING_ON_TYPE_MAPPER = {
    'fork': get_fork_body,
    'commit_comment': get_commit_comment_body,
    'change_commit_status': get_commit_status_changed_body,
    'issue_updated': partial(get_issue_action_body, action='updated'),
    'issue_created': partial(get_issue_action_body, action='created'),
    'issue_commented': get_issue_commented_body,
    'pull_request_created': partial(get_pull_request_created_or_updated_body, action='created'),
    'pull_request_updated': partial(get_pull_request_created_or_updated_body, action='updated'),
    'pull_request_approved': partial(get_pull_request_action_body, action='approved'),
    'pull_request_unapproved': partial(get_pull_request_action_body, action='unapproved'),
    'pull_request_fulfilled': partial(get_pull_request_action_body, action='merged'),
    'pull_request_rejected': partial(get_pull_request_action_body, action='rejected'),
    'pull_request_comment_created': get_pull_request_comment_created_action_body,
    'pull_request_comment_updated': partial(get_pull_request_deleted_or_updated_comment_action_body,
                                            action='updated'),
    'pull_request_comment_deleted': partial(get_pull_request_deleted_or_updated_comment_action_body,
                                            action='deleted'),
    'push': get_push_bodies,
    'repo:updated': get_repo_updated_body,
}


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Search extends CI_Controller {

	/**
	 * Index Page for this controller.
	 *
	 * Maps to the following URL
	 * 		http://example.com/index.php/welcome
	 *	- or -
	 * 		http://example.com/index.php/welcome/index
	 *	- or -
	 * Since this controller is set as the default controller in
	 * config/routes.php, it's displayed at http://example.com/
	 *
	 * So any other public methods not prefixed with an underscore will
	 * map to /index.php/welcome/<method_name>
	 * @see https://codeigniter.com/user_guide/general/urls.html
	 */
	public function __construct()
    {
        parent::__construct();
        $this->load->helper(array('form','url'));
        $this->load->library(array('session', 'form_validation', 'email','pagination'));
        $this->load->database();
        $this->load->model('Init_models');
    }

	public function index()
	{
		$banners = $this->Init_models->getadvertisebanners();
             $view_params = array(
                'm_title' => 'Search',
                'title'   => 'Search',
                'banners' => $banners

            );
		$this->load->view('course/search',$view_params);
	}
}

redpajama_set_name: RedPajamaGithub


text:
class TextToSpeechPrivate {
	public:
		ISpVoice * pVoice;
		TextToSpeechPrivate();
		~TextToSpeechPrivate();
		void say(const QString &text);
		void setVolume(int v);
};

TextToSpeechPrivate::TextToSpeechPrivate() {
	pVoice = NULL;

	HRESULT hr = CoCreateInstance(CLSID_SpVoice, NULL, CLSCTX_ALL, IID_ISpVoice, (void **)&pVoice);
	if (FAILED(hr))
		qWarning("TextToSpeechPrivate: Failed to allocate TTS Voice");
}

TextToSpeechPrivate::~TextToSpeechPrivate() {
	if (pVoice)
		pVoice->Release();
}

void TextToSpeechPrivate::say(const QString &text) {
	if (pVoice) {
		pVoice->Speak((const wchar_t *) text.utf16(), SPF_ASYNC, NULL);
	}
}

void TextToSpeechPrivate::setVolume(int volume) {
	if (pVoice)
		pVoice->SetVolume(volume);
}

TextToSpeech::TextToSpeech(QObject *p) : QObject(p) {
	enabled = true;
	d = new TextToSpeechPrivate();
}

TextToSpeech::~TextToSpeech() {
	delete d;
}

void TextToSpeech::say(const QString &text) {
	if (enabled)
		d->say(text);
}

void TextToSpeech::setEnabled(bool e) {
	enabled = e;
}

void TextToSpeech::setVolume(int volume) {
	d->setVolume(volume);
}

bool TextToSpeech::isEnabled() const {
	return enabled;
}


text:
package com.betfair.tornjak.kpi.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Required;
import org.springframework.core.Ordered;

import com.betfair.tornjak.kpi.KPIMonitor;
import com.betfair.tornjak.kpi.KPITimer;

/**
 * AOP advice which is responsible for measuring and counting methods by means of annotations.
 */
@Aspect
public class KPIMeasuringAspect implements Ordered {

    private KPIMonitor kpiMonitor;
    private int order = 10;

    @AfterThrowing("@annotation(kpiEvent)")
    public void countAdvice(final JoinPoint jp, KPIEvent kpiEvent) {
        addEvent(jp, kpiEvent.value(), kpiEvent.operation(), false, kpiEvent.catchFailures());
    }

    private void addEvent(JoinPoint jp, String eventValue, String eventOperation, boolean succeeded, boolean catchFailures) {
        final String name = eventValue.isEmpty() ? jp.getTarget().getClass().getSimpleName() : eventValue;
        final String operation = eventOperation.isEmpty() ? jp.getSignature().getName() : eventOperation;

        if (catchFailures) {
            kpiMonitor.addEvent(name, operation, succeeded);
        } else {
            kpiMonitor.addEvent(name, operation);
        }
    }

    @AfterReturning("@annotation(kpiEvent)")
    public void doEventAdvice(final JoinPoint jp, KPIEvent kpiEvent) {
        addEvent(jp, kpiEvent.value(), kpiEvent.operation(), true, kpiEvent.catchFailures());
    }

    @Around("@annotation(kpiTimedEvent)")
    public Object measureDuration(final ProceedingJoinPoint pjp, KPITimedEvent kpiTimedEvent) throws Throwable {

        KPITimer timer = new KPITimer();
        boolean succeeded = true;
        try {
            timer.start();
            return pjp.proceed();

        } catch(Throwable t) {
            succeeded = false;
            throw t;

        } finally {
            // this looks like a reasonable and clean place to stop the clock, even if we've wasted a few nanos before
            //  we actually get here
            double duration = timer.stop();
            final String eventValue = kpiTimedEvent.value();
            final String name = eventValue.isEmpty() ? pjp.getTarget().getClass().getSimpleName() : eventValue;
            final String operation = kpiTimedEvent.operation().isEmpty() ? pjp.getSignature().getName() : kpiTimedEvent.operation();

            if (kpiTimedEvent.catchFailures()) {
                kpiMonitor.addEvent(name, operation, duration, succeeded);
            } else {
                kpiMonitor.addEvent(name, operation, duration);
            }
        }
    }

    /**
     * DI
     */
    @Required
    public void setMonitor(KPIMonitor kpiMonitor) {
        this.kpiMonitor = kpiMonitor;
    }

    public int getOrder() {
    	return this.order;
    }

    public void setOrder(int order) {
        this.order = order;
    }

}


text:
module ActiveMerchant #:nodoc:
  module Billing #:nodoc:
    class PriorityGateway < Gateway
      # Sandbox and Production
      self.test_url = 'https://sandbox.api.mxmerchant.com/checkout/v3/payment'
      self.live_url = 'https://api.mxmerchant.com/checkout/v3/payment'

      class_attribute :test_url_verify, :live_url_verify, :test_auth, :live_auth, :test_env_verify, :live_env_verify, :test_url_batch, :live_url_batch, :test_url_jwt, :live_url_jwt, :merchant

      # Sandbox and Production - verify card
      self.test_url_verify = 'https://sandbox-api2.mxmerchant.com/merchant/v1/bin'
      self.live_url_verify = 'https://api2.mxmerchant.com/merchant/v1/bin'

      # Sandbox and Production - check batch status
      self.test_url_batch = 'https://sandbox.api.mxmerchant.com/checkout/v3/batch'
      self.live_url_batch = 'https://api.mxmerchant.com/checkout/v3/batch'

      # Sandbox and Production - generate jwt for verify card url
      self.test_url_jwt = 'https://sandbox-api2.mxmerchant.com/security/v1/application/merchantId'
      self.live_url_jwt = 'https://api2.mxmerchant.com/security/v1/application/merchantId'

      self.supported_countries = ['US']
      self.default_currency = 'USD'
      self.supported_cardtypes = %i[visa master american_express discover]

      self.homepage_url = 'https://mxmerchant.com/'
      self.display_name = 'Priority'

      def initialize(options = {})
        requires!(options, :merchant_id, :api_key, :secret)
        super
      end

      def basic_auth
        Base64.strict_encode64("#{@options[:api_key]}:#{@options[:secret]}")
      end

      def request_headers
        {
          'Content-Type' => 'application/json',
          'Authorization' => "Basic #{basic_auth}"
        }
      end

      def request_verify_headers(jwt)
        {
          'Authorization' => "Bearer #{jwt}"
        }
      end

      def purchase(amount, credit_card, options = {})
        params = {}
        params['authOnly'] = false
        params['isSettleFunds'] = true

        add_merchant_id(params)
        add_amount(params, amount, options)
        add_auth_purchase_params(params, credit_card, options)

        commit('purchase', params: params)
      end

      def authorize(amount, credit_card, options = {})
        params = {}
        params['authOnly'] = true
        params['isSettleFunds'] = false

        add_merchant_id(params)
        add_amount(params, amount, options)
        add_auth_purchase_params(params, credit_card, options)

        commit('purchase', params: params)
      end

      def credit(amount, credit_card, options = {})
        params = {}
        params['authOnly'] = false
        params['isSettleFunds'] = true
        amount = -amount

        add_merchant_id(params)
        add_amount(params, amount, options)
        add_credit_params(params, credit_card, options)
        commit('credit', params: params)
      end

      def refund(amount, authorization, options = {})
        params = {}
        add_merchant_id(params)
        params['paymentToken'] = payment_token(authorization) || options[:payment_token]

        # refund amounts must be negative
        params['amount'] = ('-' + localized_amount(amount.to_f, options[:currency])).to_f

        commit('refund', params: params)
      end

      def capture(amount, authorization, options = {})
        params = {}
        add_merchant_id(params)
        add_amount(params, amount, options)
        params['paymentToken'] = payment_token(authorization) || options[:payment_token]
        params['tenderType'] = options[:tender_type].present? ? options[:tender_type] : 'Card'

        commit('capture', params: params)
      end

      def void(authorization, options = {})
        params = {}

        commit('void', params: params, iid: payment_id(authorization))
      end

      def verify(credit_card, _options = {})
        jwt = create_jwt.params['jwtToken']

        commit('verify', card_number: credit_card.number, jwt: jwt)
      end

      def get_payment_status(batch_id)
        commit('get_payment_status', params: batch_id)
      end

      def close_batch(batch_id)
        commit('close_batch', params: batch_id)
      end

      def create_jwt
        commit('create_jwt', params: @options[:merchant_id])
      end

      def supports_scrubbing?
        true
      end

      def scrub(transcript)
        transcript.
          gsub(%r((Authorization: Basic )\w+), '\1[FILTERED]').
          gsub(%r((number\\?"\s*:\s*\\?")[^"]*)i, '\1[FILTERED]').
          gsub(%r((cvv\\?"\s*:\s*\\?")[^"]*)i, '\1[FILTERED]')
      end

      private

      def add_amount(params, amount, options)
        params['amount'] = localized_amount(amount.to_f, options[:currency])
      end

      def add_merchant_id(params)
        params['merchantId'] = @options[:merchant_id]
      end

      def add_auth_purchase_params(params, credit_card, options)
        add_replay_id(params, options)
        add_credit_card(params, credit_card, 'purchase', options)
        add_purchases_data(params, options)
        add_shipping_data(params, options)
        add_pos_data(params, options)
        add_additional_data(params, options)
      end

      def add_credit_params(params, credit_card, options)
        add_replay_id(params, options)
        add_credit_card(params, credit_card, 'purchase', options)
        add_additional_data(params, options)
      end

      def add_replay_id(params, options)
        params['replayId'] = options[:replay_id] if options[:replay_id]
      end

      def add_credit_card(params, credit_card, action, options)
        return unless credit_card&.is_a?(CreditCard)

        card_details = {}
        card_details['expiryMonth'] = format(credit_card.month, :two_digits).to_s
        card_details['expiryYear'] = format(credit_card.year, :two_digits).to_s
        card_details['cardType'] = credit_card.brand
        card_details['last4'] = credit_card.last_digits
        card_details['cvv'] = credit_card.verification_value unless credit_card.verification_value.nil?
        card_details['number'] = credit_card.number
        card_details['avsStreet'] = options[:billing_address][:address1] if options[:billing_address]
        card_details['avsZip'] =  options[:billing_address][:zip] if !options[:billing_address].nil? && !options[:billing_address][:zip].nil?

        params['cardAccount'] = card_details
      end

      def exp_date(credit_card)
        "#{format(credit_card.month, :two_digits)}/#{format(credit_card.year, :two_digits)}"
      end

      def add_additional_data(params, options)
        params['isAuth'] = options[:is_auth].present? ? options[:is_auth] : 'true'
        params['paymentType'] = options[:payment_type].present? ? options[:payment_type] : 'Sale'
        params['tenderType'] = options[:tender_type].present? ? options[:tender_type] : 'Card'
        params['taxExempt'] = options[:tax_exempt].present? ? options[:tax_exempt] : 'false'
        params['taxAmount'] = options[:tax_amount] if options[:tax_amount]
        params['shouldGetCreditCardLevel'] = options[:should_get_credit_card_level] if options[:should_get_credit_card_level]
        params['source'] = options[:source] if options[:source]
        params['invoice'] = options[:invoice] if options[:invoice]
        params['isTicket'] = options[:is_ticket] if options[:is_ticket]
        params['shouldVaultCard'] = options[:should_vault_card] if options[:should_vault_card]
        params['sourceZip'] = options[:source_zip] if options[:source_zip]
        params['authCode'] = options[:auth_code] if options[:auth_code]
        params['achIndicator'] = options[:ach_indicator] if options[:ach_indicator]
        params['bankAccount'] = options[:bank_account] if options[:bank_account]
        params['meta'] = options[:meta] if options[:meta]
      end

      def add_pos_data(params, options)
        pos_data = {}
        pos_data['cardholderPresence'] = options.dig(:pos_data, :cardholder_presence) || 'Ecom'
        pos_data['deviceAttendance'] = options.dig(:pos_data, :device_attendance) || 'HomePc'
        pos_data['deviceInputCapability'] = options.dig(:pos_data, :device_input_capability) || 'Unknown'
        pos_data['deviceLocation'] = options.dig(:pos_data, :device_location) || 'HomePc'
        pos_data['panCaptureMethod'] = options.dig(:pos_data, :pan_capture_method) || 'Manual'
        pos_data['partialApprovalSupport'] = options.dig(:pos_data, :partial_approval_support) || 'NotSupported'
        pos_data['pinCaptureCapability'] = options.dig(:pos_data, :pin_capture_capability) || 'Incapable'

        params['posData'] = pos_data
      end

      def add_purchases_data(params, options)
        return unless options[:purchases]

        params['purchases'] = []

        options[:purchases].each do |purchase|
          purchase_object = {}

          purchase_object['name'] = purchase[:name] if purchase[:name]
          purchase_object['description'] = purchase[:description] if purchase[:description]
          purchase_object['code'] = purchase[:code] if purchase[:code]
          purchase_object['unitOfMeasure'] = purchase[:unit_of_measure] if purchase[:unit_of_measure]
          purchase_object['unitPrice'] = purchase[:unit_price] if purchase[:unit_price]
          purchase_object['quantity'] = purchase[:quantity] if purchase[:quantity]
          purchase_object['taxRate'] = purchase[:tax_rate] if purchase[:tax_rate]
          purchase_object['taxAmount'] = purchase[:tax_amount] if purchase[:tax_amount]
          purchase_object['discountRate'] = purchase[:discount_rate] if purchase[:discount_rate]
          purchase_object['discountAmount'] = purchase[:discount_amount] if purchase[:discount_amount]
          purchase_object['extendedAmount'] = purchase[:extended_amount] if purchase[:extended_amount]
          purchase_object['lineItemId'] = purchase[:line_item_id] if purchase[:line_item_id]

          params['purchases'].append(purchase_object)
        end
      end

      def add_shipping_data(params, options)
        params['shipAmount'] = options[:ship_amount] if options[:ship_amount]

        shipping_country = shipping_country_from(options)
        params['shipToCountry'] = shipping_country if shipping_country

        shipping_zip = shipping_zip_from(options)
        params['shipToZip'] = shipping_zip if shipping_zip
      end

      def shipping_country_from(options)
        options[:ship_to_country] || options.dig(:shipping_address, :country) || options.dig(:billing_address, :country)
      end

      def shipping_zip_from(options)
        options[:ship_to_zip] || options.dig(:shipping_addres, :zip) || options.dig(:billing_address, :zip)
      end

      def payment_token(authorization)
        return unless authorization
        return authorization unless authorization.include?('|')

        authorization.split('|').last
      end

      def payment_id(authorization)
        return unless authorization
        return authorization unless authorization.include?('|')

        authorization.split('|').first
      end

      def commit(action, params: '', iid: '', card_number: nil, jwt: '')
        response =
          begin
            case action
            when 'void'
              parse(ssl_request(:delete, url(action, params, ref_number: iid), nil, request_headers))
            when 'verify'
              parse(ssl_get(url(action, params, credit_card_number: card_number), request_verify_headers(jwt)))
            when 'get_payment_status', 'create_jwt'
              parse(ssl_get(url(action, params, ref_number: iid), request_headers))
            when 'close_batch'
              parse(ssl_request(:put, url(action, params, ref_number: iid), nil, request_headers))
            else
              parse(ssl_post(url(action, params), post_data(params), request_headers))
            end
          rescue ResponseError => e
            # currently Priority returns a 404 with no body on certain calls. In those cases we will substitute the response status from response.message
            gateway_response = e.response.body.presence || e.response.message
            parse(gateway_response)
          end

        success = success_from(response, action)
        Response.new(
          success,
          message_from(response),
          response,
          authorization: success ? authorization_from(response) : nil,
          error_code: success || response == '' ? nil : error_from(response),
          test: test?
        )
      end

      def url(action, params, ref_number: '', credit_card_number: nil)
        case action
        when 'void'
          base_url + "/#{ref_number}?force=true"
        when 'verify'
          (verify_url + '?search=') + credit_card_number.to_s[0..6]
        when 'get_payment_status', 'close_batch'
          batch_url + "/#{params}"
        when 'create_jwt'
          jwt_url + "/#{params}/token"
        else
          base_url + '?includeCustomerMatches=false&echo=true'
        end
      end

      def base_url
        test? ? test_url : live_url
      end

      def verify_url
        test? ? self.test_url_verify : self.live_url_verify
      end

      def jwt_url
        test? ? self.test_url_jwt : self.live_url_jwt
      end

      def batch_url
        test? ? self.test_url_batch : self.live_url_batch
      end

      def handle_response(response)
        case response.code.to_i
        when 204
          { status: 'Success' }.to_json
        when 200...300
          response.body
        else
          raise ResponseError.new(response)
        end
      end

      def parse(body)
        return {} if body.blank?

        parsed_response = JSON.parse(body)
        parsed_response.is_a?(String) ? { 'message' => parsed_response } : parsed_response
      rescue JSON::ParserError
        message = 'Invalid JSON response received from Priority Gateway. Please contact Priority Gateway if you continue to receive this message.'
        message += " (The raw response returned by the API was #{body.inspect})"
        {
          'message' => message
        }
      end

      def success_from(response, action)
        return !response['bank'].empty? if action == 'verify' && response['bank']

        %w[Approved Open Success Settled Voided].include?(response['status'])
      end

      def message_from(response)
        return response['details'][0] if response['details'] && response['details'][0]

        response['authMessage'] || response['message'] || response['status']
      end

      def authorization_from(response)
        [response['id'], response['paymentToken']].join('|')
      end

      def error_from(response)
        response['errorCode'] || response['status']
      end

      def post_data(params)
        params.to_json
      end
    end
  end
end


text:
package com.sequenceiq.it.cloudbreak.testcase.mock;

import javax.inject.Inject;

import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

import com.sequenceiq.it.cloudbreak.assertion.CommonAssert;
import com.sequenceiq.it.cloudbreak.assertion.util.VersionCheckTestAssertion;
import com.sequenceiq.it.cloudbreak.client.UtilTestClient;
import com.sequenceiq.it.cloudbreak.context.Description;
import com.sequenceiq.it.cloudbreak.context.MockedTestContext;
import com.sequenceiq.it.cloudbreak.context.TestCaseDescription;
import com.sequenceiq.it.cloudbreak.dto.util.VersionCheckTestDto;

public class VersionCheckTest extends AbstractMockTest {

    @Inject
    private UtilTestClient utilTestClient;

    @BeforeMethod
    public void beforeMethod(Object[] data) {
        createDefaultUser((MockedTestContext) data[0]);
    }

    @Test(dataProvider = "contextWithTestContextAndInvalidVersionValue")
    public void testGetVersionByInvalidVersionNumber(MockedTestContext testContext, String invalidVersionValue,
            @Description TestCaseDescription testCaseDescription) {
        testContext
                .given(VersionCheckTestDto.class)
                .withVersion(invalidVersionValue)
                .when(utilTestClient.versionChecker())
                .then(CommonAssert::responseExists)
                .then(VersionCheckTestAssertion.versionIsNotOk())
                .validate();
    }

    @DataProvider(name = "contextWithTestContextAndInvalidVersionValue")
    public Object[][] provideInvalidAttributes() {
        return new Object[][]{
                {
                        getBean(MockedTestContext.class),
                        "",
                        description("a version check", "version is empty", "version is not ok")
                },
                {
                        getBean(MockedTestContext.class),
                        "someOtherInvalidValue",
                        description("a version check", "version is invalid", "version is not ok")
                }
        };
    }

    private TestCaseDescription description(String given, String when, String then) {
        return new TestCaseDescription.TestCaseDescriptionBuilder()
                .given(given)
                .when(when)
                .then(then);
    }

}


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

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>冲突解决3</title>

Test-prototype(将被隐藏)

Test-jQuery(将被绑定单击事件)


text:
package whistleblowerclient.services;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Stack;

/**
 * Created by tethik on 05/01/16.
 */
public class DownloadedSubmissions {

    public List<String> submissions = new Stack<>();

    private DownloadedSubmissions() {
        try {
            load();
        } catch(IOException ex) {
        }
    }

    private static DownloadedSubmissions instance = new DownloadedSubmissions();

    public static DownloadedSubmissions getInstance() {
        return instance;
    }

    public void add(String id) throws IOException {
        submissions.add(id);
        save();
    }

    public void save() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(new File("saved.json"), this);
    }

    public void load() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        submissions = mapper.readValue(new File("saved.json"), this.getClass()).submissions;
    }

}


text:
<?xml version="1.0"?>
<!--
  Licensed to the Apache Software Foundation (ASF) under one or more
  contributor license agreements.  See the NOTICE file distributed with
  this work for additional information regarding copyright ownership.
  The ASF licenses this file to You under the Apache License, Version 2.0
  (the "License"); you may not use this file except in compliance with
  the License.  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
-->
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>

<configuration>

<!-- Base Hive configurations -->

<!-- Hive Execution Parameters -->
  <property>
    <name>javax.jdo.option.ConnectionURL</name>
    <value>jdbc:mysql://localhost/metastore</value>
    <description>the URL of the MySQL database</description>
  </property>

  <property>
    <name>javax.jdo.option.ConnectionDriverName</name>
    <value>com.mysql.jdbc.Driver</value>
  </property>

  <property>
    <name>javax.jdo.option.ConnectionUserName</name>
    <value>hive</value>
  </property>

  <property>
    <name>javax.jdo.option.ConnectionPassword</name>
    <value>hive</value>
  </property>

  <property>
    <name>datanucleus.autoCreateSchema</name>
    <value>false</value>
  </property>

  <property>
    <name>datanucleus.fixedDatastore</name>
    <value>true</value>
  </property>

  <property>
    <name>datanucleus.autoStartMechanism</name>
    <value>SchemaTable</value>
  </property>

  <property>
    <name>hive.metastore.schema.verification</name>
    <value>true</value>
  </property>

  <property>
    <name>hive.metastore.uris</name>
    <value>thrift://$master:9083</value>
    <description>IP address (or fully-qualified domain name) and port of the metastore host</description>
  </property>

  <!-- The following properties are to be uncommented when using Hive on spark (Hive with Spark as execution engine)
  <property>
    <name>hive.execution.engine</name>
    <value>spark</value>
  </property>

  <property>
    <name>hive.enable.spark.execution.engine</name>
    <value>true</value>
  </property>

  <property>
    <name>spark.eventLog.enabled</name>
    <value>true</value>
  </property>

  <property>
    <name>spark.eventLog.dir</name>
    <value>hdfs:///user/spark/applicationHistory</value>
  </property>

  <property>
    <name>spark.serializer</name>
    <value>org.apache.spark.serializer.KryoSerializer</value>
  </property>

  <property>
    <name>spark.master</name>
    <value>yarn</value>
  </property>

  -->

</configuration>


text:
Phase	Team 1	 	 	Team 2

# for match in matches

	{{ match.name|safe }}

	{{ match.teams[0].name }}

	{{ match.teams[0].goals }}
	{{ match.teams[1].goals }}

	{{ match.teams[1].name }}

# endfor
# if not matches

There have not been any matches yet.

# endif


text:
Installation
============

GeoPandas depends for its spatial functionality on a large geospatial, open
source stack of libraries (`GEOS`_, `GDAL`_, `PROJ`_). See the
:ref:`dependencies` section below for more details. Those base C
libraries can sometimes be a challenge to install. Therefore, we advise you
to closely follow the recommendations below to avoid installation problems.

.. _install-conda:

Installing with Anaconda / conda
--------------------------------

To install GeoPandas and all its dependencies, we recommend to use the `conda`_
package manager. This can be obtained by installing the
`Anaconda Distribution`_ (a free Python distribution for data science), or
through `miniconda`_ (minimal distribution only containing Python and the
`conda`_ package manager). See also the `installation docs
<https://conda.io/docs/user-guide/install/download.html>`__ for more information
on how to install Anaconda or miniconda locally.

The advantage of using the `conda`_ package manager is that it provides
pre-built binaries for all the required and optional dependencies of GeoPandas
for all platforms (Windows, Mac, Linux).

To install the latest version of GeoPandas, you can then do::

    conda install geopandas

Using the conda-forge channel
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

`conda-forge`_ is a community effort that provides conda packages for a wide
range of software. It provides the *conda-forge* package channel for conda from
which packages can be installed, in addition to the "*defaults*" channel
provided by Anaconda.
Depending on what other packages you are working with, the *defaults* channel
or *conda-forge* channel may be better for your needs (e.g. some packages are
available on *conda-forge* and not on *defaults*).

GeoPandas and all its dependencies are available on the *conda-forge*
channel, and can be installed as::

    conda install --channel conda-forge geopandas

.. note::

    We strongly recommend to either install everything from the *defaults*
    channel, or everything from the *conda-forge* channel. Ending up with a
    mixture of packages from both channels for the dependencies of GeoPandas
    can lead to import problems.
    See the `conda-forge section on using multiple channels
    <http://conda-forge.org/docs/user/tipsandtricks.html#using-multiple-channels>`__
    for more details.

Creating a new environment
^^^^^^^^^^^^^^^^^^^^^^^^^^

Creating a new environment is not strictly necessary, but given that installing
other geospatial packages from different channels may cause dependency conflicts
(as mentioned in the note above), it can be good practice to install the geospatial
stack in a clean environment starting fresh.

The following commands create a new environment with the name ``geo_env``,
configures it to install packages always from conda-forge, and installs
GeoPandas in it::

    conda create -n geo_env
    conda activate geo_env
    conda config --env --add channels conda-forge
    conda config --env --set channel_priority strict
    conda install python=3 geopandas

.. _install-pip:

Installing with pip
-------------------

GeoPandas can also be installed with pip, if all dependencies can be installed
as well::

    pip install geopandas

.. _install-deps:

.. warning::

    When using pip to install GeoPandas, you need to make sure that all dependencies are
    installed correctly.

    - `fiona`_ provides binary wheels with the dependencies included for Mac and Linux,
      but not for Windows.
    - `pyproj`_, `rtree`_, and `shapely`_ provide binary wheels with dependencies included
      for Mac, Linux, and Windows.
    - Windows wheels for `shapely`, `fiona`, `pyproj` and `rtree`
      can be found at `Christopher Gohlke's website
      <https://www.lfd.uci.edu/~gohlke/pythonlibs/>`_.

    Depending on your platform, you might need to compile and install their
    C dependencies manually. We refer to the individual packages for more
    details on installing those.
    Using conda (see above) avoids the need to compile the dependencies yourself.

Installing from source
----------------------

You may install the latest development version by cloning the
`GitHub` repository and using pip to install from the local directory::

    git clone https://github.com/geopandas/geopandas.git
    cd geopandas
    pip install .

It is also possible to install the latest development version
directly from the GitHub repository with::

    pip install git+git://github.com/geopandas/geopandas.git

For installing GeoPandas from source, the same :ref:`note <install-deps>` on
the need to have all dependencies correctly installed applies. But, those
dependencies can also be installed independently with conda before installing
GeoPandas from source::

    conda install pandas fiona shapely pyproj rtree

See the :ref:`section on conda <install-conda>` above for more details on
getting running with Anaconda.

.. _dependencies:

Dependencies
------------

Required dependencies:

- `numpy`_
- `pandas`_ (version 1.0 or later)
- `shapely`_ (interface to `GEOS`_; version 1.7 or later)
- `fiona`_ (interface to `GDAL`_; version 1.8 or later)
- `pyproj`_ (interface to `PROJ`_; version 2.6.1 or later)
- `packaging`_

Further, optional dependencies are:

- `rtree`_ (optional; spatial index to improve performance and required for
  overlay operations; interface to `libspatialindex`_)
- `psycopg2`_ (optional; for PostGIS connection)
- `GeoAlchemy2`_ (optional; for writing to PostGIS)
- `geopy`_ (optional; for geocoding)

For plotting, these additional packages may be used:

- `matplotlib`_ (>= 3.2.0)
- `mapclassify`_ (>= 2.4.0)

Using the optional PyGEOS dependency
------------------------------------

Work is ongoing to improve the performance of GeoPandas. Currently, the
fast implementations of basic spatial operations live in the `PyGEOS`_
package (but work is under way to contribute those improvements to Shapely).
Starting with GeoPandas 0.8, it is possible to optionally use those
experimental speedups by installing PyGEOS. This can be done with conda
(using the conda-forge channel) or pip::

    # conda
    conda install pygeos --channel conda-forge
    # pip
    pip install pygeos

More specifically, whether the speedups are used or not is determined by:

- If PyGEOS >= 0.8 is installed, it will be used by default (but installing
  GeoPandas will not yet automatically install PyGEOS as dependency, you need
  to do this manually).

- You can still toggle the use of PyGEOS when it is available, by:

  - Setting an environment variable (``USE_PYGEOS=0/1``). Note this variable
    is only checked at first import of GeoPandas.
  - Setting an option: ``geopandas.options.use_pygeos = True/False``. Note,
    although this variable can be set during an interactive session, it will
    only work if the GeoDataFrames you use are created (e.g. reading a file
    with ``read_file``) after changing this value.

.. warning::

    The use of PyGEOS is experimental! Although it is passing all tests,
    there might still be issues and not all functions of GeoPandas will
    already benefit from speedups (one known issue: the `to_crs` coordinate
    transformations lose the z coordinate). But trying this out is very welcome!
    Any issues you encounter (but also reports of successful usage are
    interesting!) can be reported at https://gitter.im/geopandas/geopandas
    or https://github.com/geopandas/geopandas/issues

.. _PyPI: https://pypi.python.org/pypi/geopandas

.. _GitHub: https://github.com/geopandas/geopandas

.. _numpy: http://www.numpy.org

.. _pandas: http://pandas.pydata.org

.. _shapely: https://shapely.readthedocs.io

.. _fiona: https://fiona.readthedocs.io

.. _matplotlib: http://matplotlib.org

.. _geopy: https://github.com/geopy/geopy

.. _psycopg2: https://pypi.python.org/pypi/psycopg2

.. _GeoAlchemy2: https://geoalchemy-2.readthedocs.io/

.. _mapclassify: http://pysal.org/mapclassify

.. _pyproj: https://github.com/pyproj4/pyproj

.. _rtree: https://github.com/Toblerity/rtree

.. _libspatialindex: https://github.com/libspatialindex/libspatialindex

.. _conda: https://conda.io/en/latest/

.. _Anaconda distribution: https://www.anaconda.com/distribution/

.. _miniconda: https://docs.conda.io/en/latest/miniconda.html

.. _conda-forge: https://conda-forge.org/

.. _GDAL: https://www.gdal.org/

.. _GEOS: https://geos.osgeo.org

.. _PROJ: https://proj.org/

.. _PyGEOS: https://github.com/pygeos/pygeos/

.. _packaging: https://packaging.pypa.io/en/latest/


text:
using YesSql.Indexes;
using YesSql.Tests.Models;

namespace YesSql.Tests.Indexes
{
    public class CarIndex : MapIndex
    {
        public string Name { get; set; }
        public Categories Category { get; set; }
    }

    public class CarIndexProvider : IndexProvider<Car>
    {
        public override void Describe(DescribeContext<Car> context)
        {
            context
                .For<CarIndex>()
                .Map(c => new CarIndex
                {
                    Name = c.Name,
                    Category = c.Category,
                });
        }
    }
}


text:
.. index:: alternative Python implementations

*********************************************
Running on alternative Python implementations
*********************************************

Pyro is a pure Python library so you should be able to use it with
any compatible Python implementation. There are a few gotchas however.
If possible please use the most recent version available of your Python implementation.

.. note::
    You may have to install the `serpent <https://pypi.python.org/pypi/serpent>`_ serialization library manually (this is a dependency).
    Check that you can ``import serpent`` to make sure it is installed.

.. index:: IronPython

IronPython
----------
`IronPython <http://ironpython.net>`_ is a Python implementation running on the .NET virtual machine.

- Pyro runs with IronPython 2.7.5. Older versions may or may not work, and can lack required modules such as zlib.

- IronPython cannot properly serialize exception objects, which could lead to problems when dealing with
  Pyro's enhanced tracebacks. For now, Pyro contains a workaround for this `bug <https://github.com/IronLanguages/main/issues/943>`_.

- You may have to use the ``-X:Frames`` command line option when starting Ironpython.
  (one of the libraries Pyro4 depends on when running in Ironpython, requires this)

.. index:: Pypy

Pypy
----
`Pypy <http://pypy.org>`_ is a Python implementation written in Python itself, and it usually
is quite a lot faster than the default implementation because it has a :abbr:`JIT (Just in time)`-compiler.

Pyro runs happily on recent versions of Pypy.


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p10/procedures/hwp/spi/p10_spi_init_pib.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2020                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file p10_spi_init_pib.C
/// @brief Set the root control register for the given proc to use PIB mux path
///
/// *HWP HW Maintainer: Thi Tran <thi@us.ibm.com>
/// *HWP FW Maintainer: Matt Raybuck <matthew.raybuck@ibm.com>
/// *HWP Consumed by: Hostboot

#include "p10_spi_init_pib.H"
#include <p10_scom_perv.H>

fapi2::ReturnCode p10_spi_init_pib(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    // Give these constants more managable names.
    // Use this atomic clear register to set 0 bits in ROOT_CTRL_8 register
    const uint64_t ROOT_CTRL_8_CLEAR =
        static_cast<uint64_t>(scomt::perv::FSXCOMP_FSXLOG_ROOT_CTRL8_CLEAR_WO_CLEAR);

    // Select SPIM_0 for BOOT0 SEEPROM
    const uint64_t SPIM0_PORT_MUX_SELECT =
        scomt::perv::FSXCOMP_FSXLOG_ROOT_CTRL8_CLEAR_TPFSI_SPIMST0_PORT_MUX_SEL_DC;

    // Select SPIM_1 for BOOT1 SEEPROM
    const uint64_t SPIM1_PORT_MUX_SELECT =
        scomt::perv::FSXCOMP_FSXLOG_ROOT_CTRL8_CLEAR_TPFSI_SPIMST1_PORT_MUX_SEL_DC;

    // Select SPIM_2 for MVPD/KEYSTORE SEEPROM
    const uint64_t SPIM2_PORT_MUX_SELECT =
        scomt::perv::FSXCOMP_FSXLOG_ROOT_CTRL8_CLEAR_TPFSI_SPIMST2_PORT_MUX_SEL_DC;

    // Select SPIM_3 for MEASUREMENT ROM
    const uint64_t SPIM3_PORT_MUX_SELECT =
        scomt::perv::FSXCOMP_FSXLOG_ROOT_CTRL8_CLEAR_TPFSI_SPIMST3_PORT_MUX_SEL_DC;

    fapi2::buffer<uint64_t> root_ctrl_clear_buffer;

    // Force root control reg 8 to use PIB for SPI Master for all 4 SPI engines
    // CLEAR function: for clearing individual bits
    // (set logical '0' value = PIB mode), take corresponding CLEAR address
    // of the given register and write a '1' into that bit positions that
    // needs to be cleared.
    root_ctrl_clear_buffer.setBit<SPIM0_PORT_MUX_SELECT>();
    root_ctrl_clear_buffer.setBit<SPIM1_PORT_MUX_SELECT>();
    root_ctrl_clear_buffer.setBit<SPIM2_PORT_MUX_SELECT>();
    root_ctrl_clear_buffer.setBit<SPIM3_PORT_MUX_SELECT>();

    // Update ROOT_CTRL_8 register via its atomic clear register
    FAPI_TRY(fapi2::putScom(
                 i_target,
                 ROOT_CTRL_8_CLEAR,
                 root_ctrl_clear_buffer));

fapi_try_exit:
    FAPI_INF("p10_spi_init_pib: Exit");
    return fapi2::current_err;

}


text:
import * as firestore from '@firebase/firestore-types';
/**
 * A helper object that can accumulate an arbitrary amount of events and resolve
 * a promise when expected number has been emitted.
 */
export declare class EventsAccumulator<T extends firestore.DocumentSnapshot | firestore.QuerySnapshot> {
    private events;
    private waitingFor;
    private deferred;
    private rejectAdditionalEvents;
    storeEvent: (evt: T) => void;
    awaitEvents(length: number): Promise<T[]>;
    awaitEvent(): Promise<T>;
    /** Waits for a latency compensated local snapshot. */
    awaitLocalEvent(): Promise<T>;
    /** Waits for multiple latency compensated local snapshot. */
    awaitLocalEvents(count: number): Promise<T[]>;
    /** Waits for a snapshot that has no pending writes */
    awaitRemoteEvent(): Promise<T>;
    assertNoAdditionalEvents(): Promise<void>;
    allowAdditionalEvents(): void;
    private checkFulfilled;
}


text:
require 'tempfile'

require_relative 'gen-rb/article_manager_types'

require_relative 'utils/async_worker'
require_relative 'archive_file'
require_relative 'article_manager_base_client'

require_relative 'vendors/wsj'

module ColdBlossom
  module Darius
    module ArticleManager
      class BuildArchiveWorker
        extend ArticleManager::Utils::WorkerClient
        include ArticleManager::Utils::WorkerServer

        BUNDLER_VERSION = '2013-10-18'

        def initialize
          @vendors = {
              'wsj' => {:time_zone => Darius::ArticleManager::Vendors::WSJ::TIME_ZONE}
          }
        end

        def create(params)
          params[:archive_source] ||= ArchiveSource::NONE
          job = {
              :vendor => params[:vendor],
              :flavor => params[:flavor],
              :date => params[:date],
              :archive_source => params[:archive_source]
          }

          handle_validate_request job
          handle_check_archive job
          handle_build job
        end

        private
        def handle_validate_request(job)
          case job[:archive_source]
            when ArchiveSource::NONE # only check existing
              job[:check_archive] = true
            when ArchiveSource::CACHE
              job[:check_archive] = false
            when ArchiveSource::SOURCE
              job[:check_archive] = false
            when ArchiveSource::EXTERNAL
              job[:check_archive] = false
            else
              raise "Unrecognized Archive Source Option: #{params[:archive_source]}"
          end
        end

        def handle_check_archive(job)
          return unless job[:check_archive]
        end

        def handle_build (job)
          bundle_date = Time.parse(job[:date]).in_time_zone @vendors[job[:vendor]][:time_zone]
          bundle = {
              :index_files => [],
              :article_files => []
          }
          temp_files = []
          begin
            result = @article_manager_client.getDocument(GetDocumentRequest.new do |r|
              r.vendor = job[:vendor]
              r.datetime = job[:date]
              r.documentType = DocumentType::DAILY_ARCHIVE_INDEX
              r.flavor = DocumentFlavor::PROCESSED_JSON
              r.outputType = OutputType::TEXT
            end)
            index = JSON.parse result.document, :symbolize_names => true

            # download index file
            result = @article_manager_client.getDocument(GetDocumentRequest.new do |r|
              r.vendor = job[:vendor]
              r.documentType = DocumentType::DAILY_ARCHIVE_INDEX
              r.flavor = job[:flavor]
              r.datetime = job[:date]
              r.outputType = OutputType::S3_ARN
            end)

            index_file = {:handle => Tempfile.new("archive_index_#{bundle_date.strftime '%Y%m%d'}-")}
            temp_files << index_file[:handle]
            begin
              @cache_manager.download_cached_file :arn, result.document, index_file[:handle] do |key, metadata|
                index_file[:metadata] = metadata.to_h
                index_file[:key] = key
              end
            ensure
              index_file[:handle].close
            end
            bundle[:index_files] << index_file

            article_seq = 0
            index[:articles].each do |article|
              article_seq += 1
              #break if article_seq > 2 # for testing
              request = GetDocumentRequest.new do |r|
                r.vendor = job[:vendor]
                r.datetime = job[:date]
                r.documentType = DocumentType::ARTICLE
                r.flavor = job[:flavor]
                r.documentUrl = article[:url]
                r.outputType = OutputType::S3_ARN
              end
              r = @article_manager_client.getDocument request

              article_file = {:handle => Tempfile.new("archive_article_#{job[:vendor]}_#{bundle_date.strftime '%Y%m%d'}-#{article_seq}-")}
              temp_files << article_file[:handle]
              begin
                @cache_manager.download_cached_file :arn, r.document, article_file[:handle] do |key, metadata|
                  article_file[:metadata] = metadata.to_h
                  article_file[:key] = key
                end
                puts "Caching Temporary File #{article_file[:handle].path}"
              ensure
                article_file[:handle].close
              end
              bundle[:article_files] << article_file
            end

            bundle_file = Tempfile.new 'archive_bundle'
            temp_files << bundle_file
            Archive::ArchiveFile.write_bundle bundle, bundle_file
            bundle_file.close

            doc_flavor = nil
            case job[:flavor]
              when DocumentFlavor::RAW
                doc_flavor = 'raw'
              when DocumentFlavor::PROCESSED_JSON
                doc_flavor = 'json'
            end
            @cache_manager.upload_bundle("#{job[:vendor]}:archive:#{doc_flavor}", bundle_date, bundle_file.path, {:bundler_version => BUNDLER_VERSION})

          rescue Exception => e
            p e
            p e.backtrace
            raise e
          ensure
            temp_files.each do |file|
              file.unlink
            end
          end
        end

      end
    end
  end
end


text:
package me.myiume.myiulib;

import me.myiume.myiulib.api.Locale;
import me.myiume.myiulib.api.LogLevel;
import me.myiume.myiulib.api.Minigame;
import me.myiume.myiulib.api.Round;
import me.myiume.myiulib.event.MyiuLibEvent;
import me.myiume.myiulib.util.NmsUtil;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.UUID;
import java.util.logging.Logger;

/**
 * MyiuLib's primary (central) class.
 *
 * @version 0.4.0
 * @since 0.1.0
 */
public class MyiuLib extends JavaPlugin {

	/**
	 * MyiuLib's logger.
	 *
	 *
This is for use within the library; please do not use this in
	 * your plugin or you'll confuse the server owner.

	 *
	 * @since 0.1.0
	 */
	public static Logger log;

	/**
	 * Whether block changes should be logged immediately.
	 */
	public static boolean IMMEDIATE_LOGGING;

	/**
	 * The minimum level at which messages should be logged.
	 */
	public static LogLevel LOGGING_LEVEL;

	/**
	 * Whether vanilla spectating is globally disabled.
	 */
	private static boolean VANILLA_SPECTATING_DISABLED;

	/**
	 * The locale for MyiuLib itself.
	 */
	public static Locale locale;

	private static boolean disabling = false;

	/**
	 * Standard {@link JavaPlugin#onEnable()} override.
	 *
	 * @since 0.1.0
	 */
	@Override
	@SuppressWarnings("unchecked")
	public void onEnable() {

		MGUtil.plugin = this;
		log = getLogger();
		Bukkit.getPluginManager().registerEvents(new MGListener(), this);
		saveDefaultConfig();
		IMMEDIATE_LOGGING = getConfig().getBoolean("immediate-logging");
		LOGGING_LEVEL = LogLevel.valueOf(getConfig().getString("logging-level").toUpperCase());
		if (LOGGING_LEVEL == null) {
			LOGGING_LEVEL = LogLevel.WARNING;
			MyiuLib.log("The configured logging level is invalid!", LogLevel.WARNING);
		}
		VANILLA_SPECTATING_DISABLED = getConfig().getBoolean("disable-vanilla-spectating");

		locale = new Locale("MyiuLib");
		locale.initialize();

		if (this.getDescription().getVersion().contains("dev")) {
			log.warning(locale.getMessage("plugin.alert.dev-build"));
		}

		// store UUIDs of online players
		List<String> names = new ArrayList<String>();
		for (Player pl : NmsUtil.getOnlinePlayers()) {
			names.add(pl.getName());
		}
		try {
			new UUIDFetcher(names).call();
		}
		catch (Exception ex) {
			ex.printStackTrace();
			MyiuLib.log.severe(locale.getMessage("plugin.alert.uuid-fail"));
		}

		log.info(locale.getMessage("plugin.event.enable", this.toString()));
	}

	/**
	 * Standard {@link JavaPlugin#onDisable()} override.
	 *
	 * @since 0.1.0
	 */
	@Override
	public void onDisable() {
		disabling = true;
		Bukkit.broadcastMessage(ChatColor.DARK_PURPLE + "[MyiuLib] " + locale.getMessage("plugin.event.restart"));
		for (Minigame mg : Minigame.getMinigameInstances()) {
			for (Round r : mg.getRoundList()) {
				r.end(false);
			}
		}
		Minigame.uninitialize();
		MyiuLibEvent.uninitialize();
		NmsUtil.uninitialize();
		UUIDFetcher.uninitialize();
		log.info(locale.getMessage("plugin.event.disable", this.toString()));
		MyiuLib.uninitialize();
	}

	/**
	 *
This method should not be called from your plugin. So don't use it.
	 * Please.

	 *
	 * @param plugin the name of the plugin to register worlds for
	 */
	public static void registerWorlds(String plugin) {
		MGListener.addWorlds(plugin);
	}

	private static void uninitialize() {
		log = null;
		MGUtil.plugin = null;
	}

	/**
	 * Internal convenience method for logging. Please do not call this
	 * from your plugin.
	 *
	 * @param message the message to log.
	 * @param level   the {@link LogLevel level} at which to log the message
	 * @since 0.3.0
	 */
	public static void log(String message, LogLevel level) {
		MGUtil.log(message, "MyiuLib", level);
	}

	@Override
	public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
		if (label.equalsIgnoreCase("mglib")) {
			sender.sendMessage(ChatColor.LIGHT_PURPLE +
					locale.getMessage("plugin.event.info", getDescription().getVersion(), "Myiume"));
			return true;
		}
		return false;
	}

	/**
	 * Retrieves worlds registered with MyiuLib's event listener for the given
	 * plugin.
	 *
	 * @param plugin the plugin to retrieve worlds for
	 * @return worlds registered with MyiuLib's event listener for the given
	 * plugin
	 * @since 0.4.0
	 */
	public static List<String> getWorlds(String plugin) {
		return MGListener.getWorlds();
	}

	/**
	 * Retrieves a hashmap mapping the names of online players to their
	 * respective UUIDs.
	 *
	 * @return a hashmap mapping the names of online players to their
	 * respective UUIDs
	 * @since 0.3.0
	 */
	public static HashMap<String, UUID> getOnlineUUIDs() {
		return UUIDFetcher.uuids;
	}

	/**
	 * Retrieves whether vanilla spectating has been globally disabled by
	 * MyiuLib's config.yml file.
	 *
	 * @return whether vanilla spectating has been globally disabled by MyiuLib's
	 * config.yml file
	 * @since 0.3.0
	 */
	public static boolean isVanillaSpectatingDisabled() {
		return VANILLA_SPECTATING_DISABLED;
	}

	/**
	 * Determines whether MyiuLib is in the process of disabling.
	 * This is to provide security when unsetting static objects.
	 *
	 * @return whether MyiuLib is in the process of disabling.
	 * @since 0.4.0
	 */
	public static boolean isDisabling() {
		return disabling;
	}

}


text:
<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Your free landing page</title>
    <meta name="description" content="A pure client-side landing page template that you can freely fork, customize, host and link to your own domain name (e.g. using Github Pages). Relies on Mailchimp (for user email subscriptions) and Google Analytics (for stats)." property="description">
    <meta name="keywords" content="landing page, free, product page, startup, github, template, boilerplate" property="keywords">
    <meta name="viewport" content="width=device-width, initial-scale=1" property="viewport">
    <meta name="og:title" content="Fork to get your free landing page" property="og:title">
    <meta name="og:description" content="A pure client-side landing page template that you can freely fork, customize, host and link to your own domain name (e.g. using Github Pages). Relies on Mailchimp (for user email subscriptions) and Google Analytics (for stats)." property="og:description">
    <meta name="og:image" content="" property="og:image">
    <link rel="icon" href="favicon.ico">
    <link type="text/css" rel="stylesheet" href="./res/bootstrap.min.css">
    <link type="text/css" rel="stylesheet" href="./res/styles.css">
    <link href="https://fonts.googleapis.com/css?family=Lobster" rel="stylesheet">

SuitGrid

Coming Soon

                      Join our mailing list for more updates

                  <form class="form form-horizontal user-signup__form" name="form" novalidate="" action="//suitgrid.us14.list-manage.com/subscribe/post?u=9ed6f766edd5f9806fcfb8a9e&id=2ccdab5f29" method="POST">

                          <input type="email" name="EMAIL" class="form-control form-control__input user-signup__email" pattern="/^[a-zA-Z0-9+-_]+(\.[_a-zA-Z0-9+]+)*@[a-zA-Z0-9+-_]+(\.[a-zA-Z0-9+-_]+)*(\.[a-zA-Z]+)$/" placeholder="Email" aria-required="true" required="required">

                          <button type="submit" class="btn btn-default submit user-signup__submit">SUBMIT</button>

                  </form>


text:
Ajax.Responders.register({
  onCreate: function(request) {
    var throbber = $('throbber');
      throbber.style.display = 'block';
  },
  onComplete: function(request){
    var throbber = $('throbber');
      throbber.style.display = 'none';
  },
  onFailure: function(request){
    alert('Error contacting server.');
    // add exception notification here
  }
}
)

Content ={
  // TODO: This is where the toggling of display options should be implemented.
  cache: [],
  display_as: function(str){
    switch(str){
      case 'thumbnails' :
        $('details').hide();
        $('thumbnails').show();
      break;
      case 'details' :
        $('details').show();
        $('thumbnails').hide();
      break;
    }
    new Ajax.Request('/account/display_as/'+str);
  },
  in_cache: function(element){
    if(Content.cache.include(element)){
      return true;
    }else{
      return false;
    }
  },
  add_to_cache: function(e){
    Content.cache.push(e);
  }
}

// Collection of helper methods for common view functionality
View = {
  HasManySortHelper : null,

  // Assumes either id_1 or id_2 is set visible and the other is hidden
  flip_flop : function(id_1,id_2){
    $(id_1).toggle();
    $(id_2).toggle();
    return false;
  },
  show_hide : function(show_id,hide_id){
    $(show_id).show();
    $(hide_id).hide();
    return false;
  }
}

View.Onload = {
  loaded: false,
  addEvent: function(fn) {
    if (this.loaded) fn();
    else {
      var oldonload = (window.onload) ? window.onload : function () {};
      window.onload = function () { oldonload(); fn(); };
    }
  },
  init: function() {
    this.loaded = true;
  }
};

// Fade any flash messages after a certain amount of time.
View.FadeFlash = function(){
  new Element.scrollTo('page_flash');
  window.setTimeout('Effect.Fade(\'page_flash\', {duration:.5})',3000);
}

View.SelectRow = function(checkbox, parent_row,unselected_class,selected_class){
  if(checkbox.checked){
    $(parent_row).className= selected_class;
    $(parent_row).onmouseout='';
  }else{
    $(parent_row).className= unselected_class;
  }
}
View.CheckAll = function(list,name,toggle){

  toggle_val = toggle.checked
  for(var i = 0; i < list.length;i++){
    list[i].checked = toggle_val
  }

}
View.HasManySortHelper ={
  sort_items : true,
  hidden_selected_items_to_submit : null,
  selelected_items_to_display : null,

  move_all : function(fbox,tbox){
    while(fbox.options.length > 0){
      this.swap_option(tbox , fbox.options[0])
    }
  this.clone_select(
            this.selelected_items_to_display ,
            this.hidden_selected_items_to_submit
          )
    },

  move : function(fbox,tbox)
    {
    // If no items were selected then implicity they probably want to move the top one
    if (fbox.selectedIndex == -1 && fbox.options.length > 0){
      this.swap_option(tbox , fbox.options[0])
    }

      for(var i=0; i<fbox.options.length; i++){
          if(fbox.options[i].selected){
        this.swap_option(tbox , fbox.options[i])
      }
      }
    this.clone_select(
              this.selelected_items_to_display ,
              this.hidden_selected_items_to_submit
            )
    },

  clone_select : function(fbox, tbox ){
    while(tbox.options.length > 0){
      this.remove_option(tbox,tbox.options[0])
    }
    for(var i =0; i < fbox.options.length; i++){
      tbox.appendChild(new Option(fbox.options[i].text,fbox.options[i].value));
      tbox.options[tbox.options.length-1].selected = true;
    }

  },

  swap_option : function(tbox , opt){
    tbox.appendChild(opt)
    opt.selected = false;
  },

  remove_option : function(sel, opt){
    sel.removeChild(opt);
  },

  remove_all_options : function(sel){
    while(sel.options.length > 0){
      this.remove_option(sel,sel.options[0])
    }
  },

  update_collection : function(fbox, tbox) {
    this.remove_all_options(this.hidden_selected_items_to_submit)

    for(var i=0; i<tbox.options.length; i++){
      var no = new Option();
      no.value = tbox.options[i].value;
      no.text = tbox.options[i].text;
      this.hidden_selected_items_to_submit.options[i] = no;
      this.hidden_selected_items_to_submit.options[i].selected = true;
    }
  }
}


text:
#ifndef CO_SDO_CLIENT_H
#define CO_SDO_CLIENT_H

#include "301/CO_driver.h"
#include "301/CO_ODinterface.h"
#include "301/CO_SDOserver.h"
#include "301/CO_fifo.h"

/* default configuration, see CO_config.h */
#ifndef CO_CONFIG_SDO_CLI
#define CO_CONFIG_SDO_CLI (0)
#endif
#ifndef CO_CONFIG_SDO_CLI_BUFFER_SIZE
 #if (CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_BLOCK
  #define CO_CONFIG_SDO_CLI_BUFFER_SIZE 1000
 #else
  #define CO_CONFIG_SDO_CLI_BUFFER_SIZE 32
 #endif
#endif

#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_ENABLE) || defined CO_DOXYGEN

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @defgroup CO_SDOclient SDO client
 * CANopen Service Data Object - client protocol.
 *
 * @ingroup CO_CANopen_301
 * @{
 * SDO client is able to access Object Dictionary variables from remote nodes.
 * Usually there is one SDO client on CANopen network, which is able to
 * configure other CANopen nodes. It is also possible to establish individual
 * SDO client-server communication channels between devices.
 *
 * SDO client is used in CANopenNode from CO_gateway_ascii.c with default SDO
 * CAN identifiers. There is quite advanced usage in non-blocking function.
 *
 * If enabled, SDO client is initialized in CANopen.c file with
 * @ref CO_SDOclient_init() function.
 *
 * Basic usage:
 * @code{.c}
CO_SDO_abortCode_t read_SDO(CO_SDOclient_t *SDO_C, uint8_t nodeId,
                            uint16_t index, uint8_t subIndex,
                            uint8_t *buf, size_t bufSize, size_t *readSize)
{
    CO_SDO_return_t SDO_ret;

    // setup client (this can be skipped, if remote device don't change)
    SDO_ret = CO_SDOclient_setup(SDO_C,
                                 CO_CAN_ID_SDO_CLI + nodeId,
                                 CO_CAN_ID_SDO_SRV + nodeId,
                                 nodeId);
    if (SDO_ret != CO_SDO_RT_ok_communicationEnd) {
        return CO_SDO_AB_GENERAL;
    }

    // initiate upload
    SDO_ret = CO_SDOclientUploadInitiate(SDO_C, index, subIndex, 1000, false);
    if (SDO_ret != CO_SDO_RT_ok_communicationEnd) {
        return CO_SDO_AB_GENERAL;
    }

    // upload data
    do {
        uint32_t timeDifference_us = 10000;
        CO_SDO_abortCode_t abortCode = CO_SDO_AB_NONE;

        SDO_ret = CO_SDOclientUpload(SDO_C,
                                     timeDifference_us,
                                     false,
                                     &abortCode,
                                     NULL, NULL, NULL);
        if (SDO_ret < 0) {
            return abortCode;
        }

        sleep_us(timeDifference_us);
    } while(SDO_ret > 0);

    // copy data to the user buffer (for long data function must be called
    // several times inside the loop)
    *readSize = CO_SDOclientUploadBufRead(SDO_C, buf, bufSize);

    return CO_SDO_AB_NONE;
}

CO_SDO_abortCode_t write_SDO(CO_SDOclient_t *SDO_C, uint8_t nodeId,
                             uint16_t index, uint8_t subIndex,
                             uint8_t *data, size_t dataSize)
{
    CO_SDO_return_t SDO_ret;
    bool_t bufferPartial = false;

    // setup client (this can be skipped, if remote device is the same)
    SDO_ret = CO_SDOclient_setup(SDO_C,
                                 CO_CAN_ID_SDO_CLI + nodeId,
                                 CO_CAN_ID_SDO_SRV + nodeId,
                                 nodeId);
    if (SDO_ret != CO_SDO_RT_ok_communicationEnd) {
        return -1
    }

    // initiate download
    SDO_ret = CO_SDOclientDownloadInitiate(SDO_C, index, subIndex,
                                           dataSize, 1000, false);
    if (SDO_ret != CO_SDO_RT_ok_communicationEnd) {
        return -1
    }

    // fill data
    size_t nWritten = CO_SDOclientDownloadBufWrite(SDO_C, data, dataSize);
    if (nWritten < dataSize) {
        bufferPartial = true;
        // If SDO Fifo buffer is too small, data can be refilled in the loop.
    }

    //download data
    do {
        uint32_t timeDifference_us = 10000;
        CO_SDO_abortCode_t abortCode = CO_SDO_AB_NONE;

        SDO_ret = CO_SDOclientDownload(SDO_C,
                                       timeDifference_us,
                                       false,
                                       bufferPartial,
                                       &abortCode,
                                       NULL, NULL);
        if (SDO_ret < 0) {
            return abortCode;
        }

        sleep_us(timeDifference_us);
    } while(SDO_ret > 0);

    return CO_SDO_AB_NONE;
}
 * @endcode
 *
 * @see @ref CO_SDOserver
 */

/**
 * SDO client object
 */
typedef struct {
#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_LOCAL) || defined CO_DOXYGEN
    /** From CO_SDOclient_init() */
    OD_t *OD;
    /** From CO_SDOclient_init() */
    uint8_t nodeId;
    /** Object dictionary interface for locally transferred object */
    OD_IO_t OD_IO;
#endif
    /** From CO_SDOclient_init() */
    CO_CANmodule_t *CANdevRx;
    /** From CO_SDOclient_init() */
    uint16_t CANdevRxIdx;
    /** From CO_SDOclient_init() */
    CO_CANmodule_t *CANdevTx;
    /** From CO_SDOclient_init() */
    uint16_t CANdevTxIdx;
    /** CAN transmit buffer inside CANdevTx for CAN tx message */
    CO_CANtx_t *CANtxBuff;
#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_FLAG_OD_DYNAMIC) || defined CO_DOXYGEN
    /** Copy of CANopen COB_ID Client -> Server, meaning of the specific bits:
        - Bit 0...10: 11-bit CAN identifier.
        - Bit 11..30: reserved, must be 0.
        - Bit 31: if 1, SDO client object is not used. */
    uint32_t COB_IDClientToServer;
    /** Copy of CANopen COB_ID Server -> Client, similar as above */
    uint32_t COB_IDServerToClient;
    /** Extension for OD object */
    OD_extension_t OD_1280_extension;
#endif
    /** Node-ID of the SDO server */
    uint8_t nodeIDOfTheSDOServer;
    /* If true, SDO channel is valid */
    bool_t valid;
    /** Index of current object in Object Dictionary */
    uint16_t index;
    /** Subindex of current object in Object Dictionary */
    uint8_t subIndex;
    /* If true, then data transfer is finished */
    bool_t finished;
    /** Size of data, which will be transferred. It is optionally indicated by
     * client in case of download or by server in case of upload. */
    size_t sizeInd;
    /** Size of data which is actually transferred. */
    size_t sizeTran;
    /** Internal state of the SDO client */
    volatile CO_SDO_state_t state;
    /** Maximum timeout time between request and response in microseconds */
    uint32_t SDOtimeoutTime_us;
    /** Timeout timer for SDO communication */
    uint32_t timeoutTimer;
    /** CO_fifo_t object for data buffer (not pointer) */
    CO_fifo_t bufFifo;
    /** Data buffer of usable size @ref CO_CONFIG_SDO_CLI_BUFFER_SIZE, used
     * inside bufFifo. Must be one byte larger for fifo usage. */
    uint8_t buf[CO_CONFIG_SDO_CLI_BUFFER_SIZE + 1];
    /** Indicates, if new SDO message received from CAN bus. It is not cleared,
     * until received message is completely processed. */
    volatile void *CANrxNew;
    /** 8 data bytes of the received message */
    uint8_t CANrxData[8];
#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_FLAG_CALLBACK_PRE) || defined CO_DOXYGEN
    /** From CO_SDOclient_initCallbackPre() or NULL */
    void (*pFunctSignal)(void *object);
    /** From CO_SDOclient_initCallbackPre() or NULL */
    void *functSignalObject;
#endif
#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_SEGMENTED) || defined CO_DOXYGEN
    /** Toggle bit toggled in each segment in segmented transfer */
    uint8_t toggle;
#endif
#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_BLOCK) || defined CO_DOXYGEN
    /** Timeout time for SDO sub-block upload, half of #SDOtimeoutTime_us */
    uint32_t block_SDOtimeoutTime_us;
    /** Timeout timer for SDO sub-block upload */
    uint32_t block_timeoutTimer;
    /** Sequence number of segment in block, 1..127 */
    uint8_t block_seqno;
    /** Number of segments per block, 1..127 */
    uint8_t block_blksize;
    /** Number of bytes in last segment that do not contain data */
    uint8_t block_noData;
    /** Server CRC support in block transfer */
    bool_t block_crcEnabled;
    /** Last 7 bytes of data at block upload */
    uint8_t block_dataUploadLast[7];
    /** Calculated CRC checksum */
    uint16_t block_crc;
#endif
} CO_SDOclient_t;

/**
 * Initialize SDO client object.
 *
 * Function must be called in the communication reset section.
 *
 * @param SDO_C This object will be initialized.
 * @param OD Object Dictionary. It is used in case, if client is accessing
 * object dictionary from its own device. If NULL, it will be ignored.
 * @param OD_1280_SDOcliPar OD entry for SDO client parameter (0x1280+). It
 * may have IO extension enabled to allow dynamic configuration (see also
 * @ref CO_CONFIG_FLAG_OD_DYNAMIC). Entry is required.
 * @param nodeId CANopen Node ID of this device. It is used in case, if client
 * is accessing object dictionary from its own device. If 0, it will be ignored.
 * @param CANdevRx CAN device for SDO client reception.
 * @param CANdevRxIdx Index of receive buffer in the above CAN device.
 * @param CANdevTx CAN device for SDO client transmission.
 * @param CANdevTxIdx Index of transmit buffer in the above CAN device.
 * @param [out] errInfo Additional information in case of error, may be NULL.
 *
 * @return #CO_ReturnError_t: CO_ERROR_NO or CO_ERROR_ILLEGAL_ARGUMENT.
 */
CO_ReturnError_t CO_SDOclient_init(CO_SDOclient_t *SDO_C,
                                   OD_t *OD,
                                   OD_entry_t *OD_1280_SDOcliPar,
                                   uint8_t nodeId,
                                   CO_CANmodule_t *CANdevRx,
                                   uint16_t CANdevRxIdx,
                                   CO_CANmodule_t *CANdevTx,
                                   uint16_t CANdevTxIdx,
                                   uint32_t *errInfo);

#if ((CO_CONFIG_SDO_CLI) & CO_CONFIG_FLAG_CALLBACK_PRE) || defined CO_DOXYGEN
/**
 * Initialize SDOclient callback function.
 *
 * Function initializes optional callback function, which should immediately
 * start processing of CO_SDOclientDownload() or CO_SDOclientUpload() function.
 * Callback is called after SDOclient message is received from the CAN bus or
 * when new call without delay is necessary (exchange data with own SDO server
 * or SDO block transfer is in progress).
 *
 * @param SDOclient This object.
 * @param object Pointer to object, which will be passed to pFunctSignal(). Can
 * be NULL.
 * @param pFunctSignal Pointer to the callback function. Not called if NULL.
 */
void CO_SDOclient_initCallbackPre(CO_SDOclient_t *SDOclient,
                                  void *object,
                                  void (*pFunctSignal)(void *object));
#endif

/**
 * Setup SDO client object.
 *
 * Function is called in from CO_SDOclient_init() and each time when
 * "SDO client parameter" is written. Application can call this function before
 * new SDO communication. If parameters to this function are the same as before,
 * then CAN is not reconfigured.
 *
 * @param SDO_C This object.
 * @param COB_IDClientToServer See @ref CO_SDOclient_t.
 * @param COB_IDServerToClient See @ref CO_SDOclient_t.
 * @param nodeIDOfTheSDOServer Node-ID of the SDO server. If it is the same as
 * node-ID of this node, then data will be exchanged with this node
 * (without CAN communication).
 *
 * @return #CO_SDO_return_t, CO_SDO_RT_ok_communicationEnd or
 * CO_SDO_RT_wrongArguments
 */
CO_SDO_return_t CO_SDOclient_setup(CO_SDOclient_t *SDO_C,
                                   uint32_t COB_IDClientToServer,
                                   uint32_t COB_IDServerToClient,
                                   uint8_t nodeIDOfTheSDOServer);

/**
 * Initiate SDO download communication.
 *
 * Function initiates SDO download communication with server specified in
 * CO_SDOclient_init() function. Data will be written to remote node.
 * Function is non-blocking.
 *
 * @param SDO_C This object.
 * @param index Index of object in object dictionary in remote node.
 * @param subIndex Subindex of object in object dictionary in remote node.
 * @param sizeIndicated Optionally indicate size of data to be downloaded.
 * Actual data are written with one or multiple CO_SDOclientDownloadBufWrite()
 * calls.
 * - If sizeIndicated is different than 0, then total number of data
 * written by CO_SDOclientDownloadBufWrite() will be compared against
 * sizeIndicated. Also sizeIndicated info will be passed to the server, which
 * will compare actual data size downloaded. In case of mismatch, SDO abort
 * message will be generated.
 * - If sizeIndicated is 0, then actual data size will not be verified.
 * @param SDOtimeoutTime_ms Timeout time for SDO communication in milliseconds.
 * @param blockEnable Try to initiate block transfer.
 *
 * @return #CO_SDO_return_t
 */
CO_SDO_return_t CO_SDOclientDownloadInitiate(CO_SDOclient_t *SDO_C,
                                             uint16_t index,
                                             uint8_t subIndex,
                                             size_t sizeIndicated,
                                             uint16_t SDOtimeoutTime_ms,
                                             bool_t blockEnable);

/**
 * Initiate SDO download communication - update size.
 *
 * This is optional function, which updates sizeIndicated, if it was not known
 * in the CO_SDOclientDownloadInitiate() function call. This function can be
 * used after CO_SDOclientDownloadBufWrite(), but must be used before
 * CO_SDOclientDownload().
 *
 * @param SDO_C This object.
 * @param sizeIndicated Same as in CO_SDOclientDownloadInitiate().
 */
void CO_SDOclientDownloadInitiateSize(CO_SDOclient_t *SDO_C,
                                      size_t sizeIndicated);

/**
 * Write data into SDO client buffer
 *
 * This function copies data from buf into internal SDO client fifo buffer.
 * Function returns number of bytes successfully copied. If there is not enough
 * space in destination, not all bytes will be copied. Additional data can be
 * copied in next cycles. If there is enough space in destination and
 * sizeIndicated is different than zero, then all data must be written at once.
 *
 * This function is basically a wrapper for CO_fifo_write() function. As
 * alternative, other functions from CO_fifo can be used directly, for example
 * CO_fifo_cpyTok2U8() or similar.
 *
 * @param SDO_C This object.
 * @param buf Buffer which will be copied
 * @param count Number of bytes in buf
 *
 * @return number of bytes actually written.
 */
size_t CO_SDOclientDownloadBufWrite(CO_SDOclient_t *SDO_C,
                                    const uint8_t *buf,
                                    size_t count);

/**
 * Process SDO download communication.
 *
 * Function must be called cyclically until it returns <=0. It Proceeds SDO
 * download communication initiated with CO_SDOclientDownloadInitiate().
 * Function is non-blocking.
 *
 * If function returns #CO_SDO_RT_blockDownldInProgress and OS has buffer for
 * CAN tx messages, then this function may be called multiple times within own
 * loop. This can speed-up SDO block transfer.
 *
 * @param SDO_C This object.
 * @param timeDifference_us Time difference from previous function call in
 * [microseconds].
 * @param abort If true, SDO client will send abort message from SDOabortCode
 * and transmission will be aborted.
 * @param bufferPartial True indicates, not all data were copied to internal
 * buffer yet. Buffer will be refilled later with #CO_SDOclientDownloadBufWrite.
 * @param [out] SDOabortCode In case of error in communication, SDO abort code
 * contains reason of error. Ignored if NULL.
 * @param [out] sizeTransferred Actual size of data transferred. Ignored if NULL
 * @param [out] timerNext_us info to OS - see CO_process(). Ignored if NULL.
 *
 * @return #CO_SDO_return_t. If less than 0, then error occurred,
 * SDOabortCode contains reason and state becomes idle. If 0, communication
 * ends successfully and state becomes idle. If greater than 0, then
 * communication is in progress.
 */
CO_SDO_return_t CO_SDOclientDownload(CO_SDOclient_t *SDO_C,
                                     uint32_t timeDifference_us,
                                     bool_t abort,
                                     bool_t bufferPartial,
                                     CO_SDO_abortCode_t *SDOabortCode,
                                     size_t *sizeTransferred,
                                     uint32_t *timerNext_us);

/**
 * Initiate SDO upload communication.
 *
 * Function initiates SDO upload communication with server specified in
 * CO_SDOclient_init() function. Data will be read from remote node.
 * Function is non-blocking.
 *
 * @param SDO_C This object.
 * @param index Index of object in object dictionary in remote node.
 * @param subIndex Subindex of object in object dictionary in remote node.
 * @param SDOtimeoutTime_ms Timeout time for SDO communication in milliseconds.
 * @param blockEnable Try to initiate block transfer.
 *
 * @return #CO_SDO_return_t
 */
CO_SDO_return_t CO_SDOclientUploadInitiate(CO_SDOclient_t *SDO_C,
                                           uint16_t index,
                                           uint8_t subIndex,
                                           uint16_t SDOtimeoutTime_ms,
                                           bool_t blockEnable);

/**
 * Process SDO upload communication.
 *
 * Function must be called cyclically until it returns <=0. It Proceeds SDO
 * upload communication initiated with CO_SDOclientUploadInitiate().
 * Function is non-blocking.
 *
 * If this function returns #CO_SDO_RT_uploadDataBufferFull, then data must be
 * read from fifo buffer to make it empty. This function can then be called
 * once again immediately to speed-up block transfer. Note also, that remaining
 * data must be read after function returns #CO_SDO_RT_ok_communicationEnd.
 * Data must not be read, if function returns #CO_SDO_RT_blockUploadInProgress.
 *
 * @param SDO_C This object.
 * @param timeDifference_us Time difference from previous function call in
 * [microseconds].
 * @param abort If true, SDO client will send abort message from SDOabortCode
 * and reception will be aborted.
 * @param [out] SDOabortCode In case of error in communication, SDO abort code
 * contains reason of error. Ignored if NULL.
 * @param [out] sizeIndicated If larger than 0, then SDO server has indicated
 * size of data transfer. Ignored if NULL.
 * @param [out] sizeTransferred Actual size of data transferred. Ignored if NULL
 * @param [out] timerNext_us info to OS - see CO_process(). Ignored if NULL.
 *
 * @return #CO_SDO_return_t. If less than 0, then error occurred,
 * SDOabortCode contains reason and state becomes idle. If 0, communication
 * ends successfully and state becomes idle. If greater than 0, then
 * communication is in progress.
 */
CO_SDO_return_t CO_SDOclientUpload(CO_SDOclient_t *SDO_C,
                                   uint32_t timeDifference_us,
                                   bool_t abort,
                                   CO_SDO_abortCode_t *SDOabortCode,
                                   size_t *sizeIndicated,
                                   size_t *sizeTransferred,
                                   uint32_t *timerNext_us);

/**
 * Read data from SDO client buffer.
 *
 * This function copies data from internal fifo buffer of SDO client into buf.
 * Function returns number of bytes successfully copied. It can be called in
 * multiple cycles, if data length is large.
 *
 * This function is basically a wrapper for CO_fifo_read() function. As
 * alternative, other functions from CO_fifo can be used directly, for example
 * CO_fifo_readU82a() or similar.
 *
 * @warning This function (or similar) must NOT be called when
 * CO_SDOclientUpload() returns #CO_SDO_RT_blockUploadInProgress!
 *
 * @param SDO_C This object.
 * @param buf Buffer into which data will be copied
 * @param count Copy up to count bytes into buffer
 *
 * @return number of bytes actually read.
 */
size_t CO_SDOclientUploadBufRead(CO_SDOclient_t *SDO_C,
                                 uint8_t *buf,
                                 size_t count);

/**
 * Close SDO communication temporary.
 *
 * Function must be called after finish of each SDO client communication cycle.
 * It disables reception of SDO client CAN messages. It is necessary, because
 * CO_SDOclient_receive function may otherwise write into undefined SDO buffer.
 *
 * @param SDO_C This object.
 */
void CO_SDOclientClose(CO_SDOclient_t *SDO_C);

/** @} */ /* CO_SDOclient */

#ifdef __cplusplus
}
#endif /*__cplusplus*/

#endif /* (CO_CONFIG_SDO_CLI) & CO_CONFIG_SDO_CLI_ENABLE */

#endif /* CO_SDO_CLIENT_H */