text:
package com.amazonaws.services.personalizeruntime;

import javax.annotation.Generated;

import com.amazonaws.services.personalizeruntime.model.*;

/**
 * Interface for accessing Amazon Personalize Runtime asynchronously. Each asynchronous method will return a Java Future
 * object representing the asynchronous operation; overloads which accept an {@code AsyncHandler} can be used to receive
 * notification when an asynchronous operation completes.
 *

 * Note: Do not directly implement this interface, new methods are added to it regularly. Extend from
 * {@link com.amazonaws.services.personalizeruntime.AbstractAmazonPersonalizeRuntimeAsync} instead.
 *

 *

 *

 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public interface AmazonPersonalizeRuntimeAsync extends AmazonPersonalizeRuntime {

    /**
     *

     * Re-ranks a list of recommended items for the given user. The first item in the list is deemed the most likely
     * item to be of interest to the user.
     *

     * <note>
     *

     * The solution backing the campaign must have been created using a recipe of type PERSONALIZED_RANKING.
     *

     * </note>
     *
     * @param getPersonalizedRankingRequest
     * @return A Java Future containing the result of the GetPersonalizedRanking operation returned by the service.
     * @sample AmazonPersonalizeRuntimeAsync.GetPersonalizedRanking
     * @see AWS API Documentation
     */
    java.util.concurrent.Future<GetPersonalizedRankingResult> getPersonalizedRankingAsync(GetPersonalizedRankingRequest getPersonalizedRankingRequest);

    /**
     *

     * Re-ranks a list of recommended items for the given user. The first item in the list is deemed the most likely
     * item to be of interest to the user.
     *

     * <note>
     *

     * The solution backing the campaign must have been created using a recipe of type PERSONALIZED_RANKING.
     *

     * </note>
     *
     * @param getPersonalizedRankingRequest
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the GetPersonalizedRanking operation returned by the service.
     * @sample AmazonPersonalizeRuntimeAsyncHandler.GetPersonalizedRanking
     * @see AWS API Documentation
     */
    java.util.concurrent.Future<GetPersonalizedRankingResult> getPersonalizedRankingAsync(GetPersonalizedRankingRequest getPersonalizedRankingRequest,
            com.amazonaws.handlers.AsyncHandler<GetPersonalizedRankingRequest, GetPersonalizedRankingResult> asyncHandler);

    /**
     *

     * Returns a list of recommended items. For campaigns, the campaign's Amazon Resource Name (ARN) is required and the
     * required user and item input depends on the recipe type used to create the solution backing the campaign as
     * follows:
     *

     *

     *

     *

     * USER_PERSONALIZATION - userId required, itemId not used
     *

     *

     *

     *

     * RELATED_ITEMS - itemId required, userId not used
     *

     *

     *

     * <note>
     *

     * Campaigns that are backed by a solution created using a recipe of type PERSONALIZED_RANKING use the API.
     *

     * </note>
     *

     * For recommenders, the recommender's ARN is required and the required item and user input depends on the use case
     * (domain-based recipe) backing the recommender. For information on use case requirements see Choosing recommender use
     * cases.
     *

     *
     * @param getRecommendationsRequest
     * @return A Java Future containing the result of the GetRecommendations operation returned by the service.
     * @sample AmazonPersonalizeRuntimeAsync.GetRecommendations
     * @see AWS API Documentation
     */
    java.util.concurrent.Future<GetRecommendationsResult> getRecommendationsAsync(GetRecommendationsRequest getRecommendationsRequest);

    /**
     *

     * Returns a list of recommended items. For campaigns, the campaign's Amazon Resource Name (ARN) is required and the
     * required user and item input depends on the recipe type used to create the solution backing the campaign as
     * follows:
     *

     *

     *

     *

     * USER_PERSONALIZATION - userId required, itemId not used
     *

     *

     *

     *

     * RELATED_ITEMS - itemId required, userId not used
     *

     *

     *

     * <note>
     *

     * Campaigns that are backed by a solution created using a recipe of type PERSONALIZED_RANKING use the API.
     *

     * </note>
     *

     * For recommenders, the recommender's ARN is required and the required item and user input depends on the use case
     * (domain-based recipe) backing the recommender. For information on use case requirements see Choosing recommender use
     * cases.
     *

     *
     * @param getRecommendationsRequest
     * @param asyncHandler
     *        Asynchronous callback handler for events in the lifecycle of the request. Users can provide an
     *        implementation of the callback methods in this interface to receive notification of successful or
     *        unsuccessful completion of the operation.
     * @return A Java Future containing the result of the GetRecommendations operation returned by the service.
     * @sample AmazonPersonalizeRuntimeAsyncHandler.GetRecommendations
     * @see AWS API Documentation
     */
    java.util.concurrent.Future<GetRecommendationsResult> getRecommendationsAsync(GetRecommendationsRequest getRecommendationsRequest,
            com.amazonaws.handlers.AsyncHandler<GetRecommendationsRequest, GetRecommendationsResult> asyncHandler);

}


text:
/*
 * memcpy.h
 *   prototypes for memcpy.c
 *
 * $Id: memcpy.h,v 1.14 2011/02/13 14:19:33 simple Exp $
 */
/*
 * Copyright (C) 2000 - 2011 Eggheads Development Team
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */

#ifndef _EGG_COMPAT_MEMCPY_H
#define _EGG_COMPAT_MEMCPY_H

#include "src/main.h"
#include <string.h>

#ifndef HAVE_MEMCPY
/* Use our own implementation. */
void *egg_memcpy(void *dest, const void *src, size_t n);
#else
#  define egg_memcpy memcpy
#endif

#endif /* !__EGG_COMPAT_MEMCPY_H */

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Phalcon;

interface FlashInterface
{

	/**
	 * Shows a HTML error message
	 *
	 * @param $message
	 */
	public function error($message);

	/**
	 * Shows a HTML notice/information message
	 *
	 * @param $message
	 */
	public function notice($message);

	/**
	 * Shows a HTML success message
	 *
	 * @param $message
	 */
	public function success($message);

	/**
	 * Shows a HTML warning message
	 *
	 * @param $message
	 */
	public function warning($message);

	/**
	 * Outputs a message
	 *
	 * @param string $type
	 * @param mixed $message
	 */
	public function message($type, $message);

}


text:
SpamAssassin + Razor + Pyzor on Debian 6/Ubuntu
###############################################
:date: 2011-09-22 19:17
:author: kura
:category: tutorials
:tags: email, mail, postfix, pyzor, razor, spam, spamassassin
:slug: spamassassin-razor-pyzor

.. contents::
    :backlinks: none

This is part 4 of my series on configuring a mail server, please see
`part one`_, `part two`_ and `part three`_ if you're not familiar with
them.

.. _part one: /2011/09/15/postfix-dovecot-imapimaps-sasl-maildir/
.. _part two: /2011/09/16/postfix-spamassassin-clamav-procmail/
.. _part three: /2011/09/17/postfix-dk-dkim-spf/

The content of this article was written to work with the previous three
articles but should work on any SpamAssassin set-up.

Razor
-----

First off we need to install Razor.

.. code-block:: bash

    sudo apt-get install razor

Now we need to run three commands to register and configure Razor.

.. code-block:: bash

    sudo razor-admin -home=/etc/spamassassin/.razor -register
    sudo razor-admin -home=/etc/spamassassin/.razor -create
    sudo razor-admin -home=/etc/spamassassin/.razor -discover

These 3 commands should be pretty self explanatory, they register Razor,
create it's configuration and discover the Razor servers.

Pyzor
-----

Now we'll install Pyzor.

.. code-block:: bash

    sudo apt-get install pyzor

Now we also need to tell Pyzor to discover it's servers.

.. code-block:: bash

    pyzor --homedir /etc/mail/spamassassin discover

SpamAssassin
------------

Add the following lines to the end of **/etc/spamassassin/local.cf**

.. code-block:: bash

    razor_config /etc/mail/spamassassin/.razor/razor-agent.conf
    pyzor_options --homedir /etc/mail/spamassassin

Finally we restart SpamAssassin

.. code-block:: bash

    sudo /etc/init.d/spamassasin restart

And we're all done.

`« Part 3 - Postfix + DK (DomainKeys) + DKIM + SPF`_

.. _« Part 3 - Postfix + DK (DomainKeys) + DKIM + SPF: /2011/09/22/spamassassin-razor-pyzor/


text:
package org.springframework.cloud.kubernetes.fabric8.config.bootstrap;

import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.cloud.kubernetes.fabric8.config.Application;

/**
 * @author wind57
 */
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = Application.class,
		properties = { "spring.cloud.kubernetes.config.enabled=false", "spring.main.cloud-platform=KUBERNETES",
				"spring.cloud.bootstrap.enabled=true" })
class BoostrapKubernetesEnabledConfigDisabled extends KubernetesEnabledConfigDisabled {

}


text:
<!--
  ~ Copyright 2019 Andrey Tolpeev
  ~
  ~ 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.
  -->

<manifest package="teamcityapp.features.splash"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <application>

        <activity
            android:name="teamcityapp.features.splash.view.SplashActivity"
            android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>


text:
class NeedForSpeed {
    private int speed;
    private int batteryDrain;
    private int distance = 0;
    private int battery = 100;

    public NeedForSpeed(int speed, int batteryDrain) {
        this.speed = speed;
        this.batteryDrain = batteryDrain;
    }

    public static NeedForSpeed nitro() {
        return new NeedForSpeed(50, 4);
    }

    public boolean batteryDrained() {
        return battery < batteryDrain;
    }

    public int distanceDriven() {
        return distance;
    }

    public void drive() {
        if (!batteryDrained()) {
            battery -= batteryDrain;
            distance += speed;
        }
    }
}

class RaceTrack {
    private int distance;

    RaceTrack(int distance) {
        this.distance = distance;
    }

    public boolean tryFinishTrack(NeedForSpeed car) {
        while (car.distanceDriven() < distance) {
            if (car.batteryDrained()) {
                return false;
            }

            car.drive();
        }

        return true;
    }
}


text:
<?php

namespace AppBundle\Entity\Audit;

use AppBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serialize;

/**
 * Trait CreatorModifierTrait
 *
 * @Serialize\ExclusionPolicy("all")
 * @Serialize\ReadOnly()
 */
trait CreatorModifierTrait
{
    use CreatorTrait;

    /**
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\User")
     * @ORM\JoinColumn(name="modified_by", referencedColumnName="uid", onDelete="SET NULL")
     *
     * @Serialize\Expose
     * @var User|null
     */
    protected $modifiedBy = null;

    /**
     * Set modifiedBy
     *
     * @param User|null $modifiedBy
     *
     * @return self
     */
    public function setModifiedBy(User $modifiedBy = null)
    {
        $this->modifiedBy = $modifiedBy;

        return $this;
    }

    /**
     * Get modifier
     *
     * @return User|null
     */
    public function getModifiedBy(): ?User
    {
        return $this->modifiedBy;
    }
}


text:
const router = require('koa-router')({
  prefix: '/metrics'
});

router.use(require('./buildTimeMetricsRouter'));
router.use(require('./testResultMetricsRouter'));

module.exports = router.routes();


text:
  Aisey-et-Richecourt est
       un village
       situé dans le département de Haute-Saône en Franche-Comté. Elle totalisait 114 habitants en 2008.

Le nombre d'habitations, à Aisey-et-Richecourt, était réparti en 2011 en sept appartements et 61 maisons soit
 un marché plutôt équilibré.

Si vous envisagez de demenager à Aisey-et-Richecourt, vous pourrez aisément trouver une maison à vendre.

À proximité de Aisey-et-Richecourt sont localisées les communes de
Villars-le-Pautel à 1 km, 154 habitants,
Ormoy localisée à 1 km, 234 habitants,
Bourbévelle à 3 km, 78 habitants,
Betaucourt à 3 km, 153 habitants,
Corre localisée à 4 km, 600 habitants,
Ameuvelle située à 5 km, 68 habitants,
 entre autres. De plus, Aisey-et-Richecourt est située à seulement 23 km de Saint-Loup-sur-Semouse.


text:
<?php

namespace Pimcore\Model\Object\ClassDefinition\Data;

use Pimcore\Model;

class User extends Model\Object\ClassDefinition\Data\Select {

    /**
     * Static type of this element
     *
     * @var string
     */
    public $fieldtype = "user";

    /**
     * @see Object\ClassDefinition\Data::getDataFromResource
     * @param string $data
     * @return string
     */
    public function getDataFromResource($data) {

        if(!empty($data)) {
            try {
                $this->checkValidity($data, true);
            } catch (\Exception $e) {
                $data = null;
            }
        }

        return $data;
    }

    /**
     * @param string $data
     * @param null $object
     * @return null|string
     */
    public function getDataForResource($data, $object = null) {
        if(!empty($data)) {
            try {
                $this->checkValidity($data, true);
            } catch (\Exception $e) {
                $data = null;
            }
        }

        return $data;
    }

    /**
     *
     */
    public function configureOptions() {

        $list = new Model\User\Listing();
        $list->setOrder("asc");
        $list->setOrderKey("name");
        $users = $list->load();

        $options = array();
        if (is_array($users) and count($users) > 0) {
            foreach ($users as $user) {
                if($user instanceof Model\User) {
                    $value = $user->getName();
                    $first = $user->getFirstname();
                    $last = $user->getLastname();
                    if (!empty($first) or !empty($last)) {
                        $value .= " (" . $first . " " . $last . ")";
                    }
                    $options[] = array(
                        "value" => $user->getId(),
                        "key" => $value
                    );
                }
            }
        }
        $this->setOptions($options);
    }

    /**
     * Checks if data is valid for current data field
     *
     * @param mixed $data
     * @param boolean $omitMandatoryCheck
     * @throws \Exception
     */
    public function checkValidity($data, $omitMandatoryCheck = false){

        if(!$omitMandatoryCheck and $this->getMandatory() and empty($data)){
            throw new \Exception("Empty mandatory field [ ".$this->getName()." ]");
        }

        if(!empty($data)){
            $user = Model\User::getById($data);
            if(!$user instanceof Model\User){
                throw new \Exception("invalid user reference");
            }
        }
    }

    /**
     *
     */
    public function __wakeup() {
        $options = $this->getOptions();
        if(\Pimcore::inAdmin() || empty($options)) {
            $this->configureOptions();
        }
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebForms.Code;

namespace WebForms
{
    public partial class _Default : PageBase
    {
        // returns breadcrumb node for this page.

        protected void Page_Load(object sender, EventArgs e)
        {
            Page.Title = "Patterns in Action Web Forms Application";
            Page.MetaKeywords = "Shopping, Electronic Products, Patterns in Action, ASP.NET Web Forms";
            Page.MetaDescription = "Patterns in Action Web Forms Application";

            if (!IsPostBack)
            {
                // set the selected menu

                SelectedMenu = "home";

                // register javascript to open popup windows (better use bundling).

                RegisterOpenWindowJavaScript();
            }
        }
    }
}


text:
import Ember from 'ember';
import layout from './template';

/**
 * @module ember-osf
 * @submodule components
 */

/**
 * Display a simple pagination control that advances the page. Intended for use with PaginatedRouteMixin.
 *
 * The pagination-control will be deprecated. Use pagination-pager instead.
 *
 * @class pagination-control
 */
export default Ember.Component.extend({
    layout,
    currentPage: null,
    pageCount: null,

    // Bounds checking for control buttons
    disablePageReverse: Ember.computed.lte('currentPage', 1),
    disablePageForward: Ember.computed('currentPage', 'pageCount', function() {
        return this.get('currentPage') >= this.get('pageCount');
    }),

    init() {
        this._super(...arguments);
        Ember.deprecate('pagination-control will be deprecated. Use pagination-pager instead', false, {
            id: 'pagination-control',
            until: '1.0.0'
        });
    },

    // TODO: This actions hash feels a bit kludgy
    actions: {
        next() {
            return this.sendAction('next', ...arguments);
        },

        previous() {
            return this.sendAction('previous', ...arguments);
        },

        goToPage(pageNumber) {
            return this.sendAction('goToPage', pageNumber);
        }
    }
});


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
J. Arnold Arbor. 71:567. 1990

#### Original name
null

### Remarks
null


text:
#include "config.h"
#include "XPathNSResolver.h"

namespace WebCore {

XPathNSResolver::~XPathNSResolver() = default;

}


text:
package com.raymanoz.careless;

import com.googlecode.totallylazy.Function1;
import com.googlecode.totallylazy.Option;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import static com.googlecode.totallylazy.Option.option;

public class CompiledLessCache {
    private Map<String, CompiledLess> cache = new HashMap<String, CompiledLess>();

    private CompiledLessCache() {}

    public static CompiledLessCache compiledLessCache() {return new CompiledLessCache();}

    public Option<CompiledLess> put(String key, CompiledLess less) {
        return option(cache.put(key, less));
    }

    public Option<CompiledLess> get(String key) {
        return Option.option(cache.get(key));
    }

    public Function1<CompiledLess, Boolean> stale(final Date date) {
        return new Function1<CompiledLess, Boolean>() {
            @Override
            public Boolean call(CompiledLess compiledLess) throws Exception {
                return compiledLess.stale(date);
            }
        };
    }
}


text:
<?php

require_once dirname(__FILE__) . '/../../bootstrap.php';
require_once dirname(__FILE__) . '/../../../../lib/payzen/base/sfPayzenPayment.class.php';

/**
 * Instanciation of sfPayzenPayment without the payzen api version set in the configure()
 */
class sfPayzenPaymentStubWithoutVersion extends sfPayzenPayment
{

}

/**
 * Instanciation of sfPayzenPayment
 */
class sfPayzenPaymentStub extends sfPayzenPayment
{

    private $fakeOption = null;

    public function configure($options = array())
    {
        parent::configure($options);
        $this->payzenApiVersion = '1.0';
        $this->addRequiredOption('required_option');
        $this->addOption('option_name', 'option_value');
    }

    //For the __get function tests
    public function getMethod()
    {
        return 'getMethod() call successfull';
    }

    //For the __set function tests
    public function setFakeOption($parameter)
    {
        $this->fakeOption = $parameter;
    }

    public function getFakeOption()
    {
        return $this->fakeOption;
    }

}

/**
 * Mock event listener to test if an event is thrown when instanciating a sfPayzenPayment
 */
class mockEventListener
{

    private $eventCaught = false;

    public function listen(sfEvent $event)
    {
        $this->eventCaught = true;
    }

    public function wasEventCaught()
    {
        return $this->eventCaught;
    }

}

$mockEventListener = new mockEventListener();
ProjectConfiguration::getActive()
        ->getEventDispatcher()
        ->connect('sf_payzen_plugin.new_payment', array($mockEventListener, 'listen'));

$t = new lime_test(null, new lime_output_color());

//__construct()
$t->diag('->__construct()');

$t->is($mockEventListener->wasEventCaught(), false, '->__construct() no "sf_payzen_plugin.new_payment" is triggered before a sfPayzenPayment is constructed ');

try
{
    $payment = new sfPayzenPaymentStubWithoutVersion();
    $t->fail('->__construct() throws a sfException if the payzen api version is not set');
} catch (sfException $e)
{
    $t->pass('->__construct() throws a sfException if the payzen api version is not set');
    $t->is($mockEventListener->wasEventCaught(), false, '->__construct() no "sf_payzen_plugin.new_payment" if an exception is thrown');
}

try
{
    $payment = new sfPayzenPaymentStub(array('unknown_key' => 'unknown_value'));
    $t->fail('->__construct() throws a InvalidArgumentException if an option is not supported');
} catch (InvalidArgumentException $e)
{
    $t->pass('->__construct() throws a InvalidArgumentException if an option is not supported');
    $t->is($mockEventListener->wasEventCaught(), false, '->__construct() no "sf_payzen_plugin.new_payment" if an exception is thrown');
}

try
{
    $payment = new sfPayzenPaymentStub(array());
    $t->fail('->__construct() throws a RuntimeException if a mandatory option is not set');
} catch (RuntimeException $e)
{
    $t->pass('->__construct() throws a RuntimeException if a mandatory option is not set');
    $t->is($mockEventListener->wasEventCaught(), false, '->__construct() no "sf_payzen_plugin.new_payment" if an exception is thrown');
}

$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$t->is($payment->__get('option_name'), 'option_value', '->__construct() if an option is not passed in parameter it is set to the default value');

$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate', 'option_name' => 'passed_option_value'));
$t->is($payment->__get('option_name'), 'passed_option_value', '->__construct() if an option is passed in parameter it is set to the passed value');

$t->is($mockEventListener->wasEventCaught(), true, '->__construct() a "sf_payzen_plugin.new_payment" event is thrown when instanciating a sfPayzenPayment');

//configure()
// Since configure is called in the __construct no need to test it
//addOption()
$t->diag('->addOption()');

$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$payment->addOption('new_option');

$t->is($payment->__get('new_option'), null, '->addOption() add an empty option when no option value is passed');

$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$payment->addOption('new_option', 'new_value');

$t->is($payment->__get('new_option'), 'new_value', '->addOption() sets an option to the given value');

//getRequiredOptions(), addRequiredOptions
$t->diag('->getRequiredOptions()');

$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$t->isa_ok($payment->getRequiredOptions(), 'array', '->getRequiredOptions() returns an array');

$t->diag('->addRequiredOption()');
$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$payment->addRequiredOption('required_option2');

$expectedRequiredOptions = array('certificate', 'required_option', 'required_option2');
$t->is_deeply($payment->getRequiredOptions(), $expectedRequiredOptions, '->addRequiredOption() adds a required option');

//getPayzenApiVersion()
$t->diag('->getPayzenApiVersion()');
$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$t->isa_ok($payment->getPayzenApiVersion(), 'string', '->getPayzenApiVersion() returns a string');

//setPayzenApiVersion()
$t->diag('->setPayzenApiVersion()');
$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));
$payment->setPayzenApiVersion('9.9');
$t->is($payment->getPayzenApiVersion(), '9.9', '->setPayzenApiVersion() sets the Payzen API version');

//getSignature()
$t->diag('->getSignature()');
$payment = new sfPayzenPaymentStub(array(
            'required_option' => 'required_value', 'certificate' => 'my_certificate'));

$payment->addOption('vads_a', 'a');
$payment->addOption('vads_c', 'c');
$payment->addOption('vads_b', 'b');
$payment->addOption('certificate', 'my_certificate');
$payment->addOption('non_vads_field', 'non_vads_value');

$signatureContent = 'a+b+c+my_certificate';
$expectedSignature = sha1($signatureContent);

$t->isa_ok($payment->getSignature(), 'string', '->getSignature() returns a string');
$t->is($payment->getSignature(), $expectedSignature, '->getSignature() generates the signature from the vads fields and the certificate');

//toArray()
$t->diag('->toArray()');
$payment = new sfPayzenPaymentStub(array(
            'required_option' => 'required_value', 'certificate' => 'my_certificate'));

$payment->addOption('vads_a', 'a');
$payment->addOption('vads_c', 'c');
$payment->addOption('vads_b', 'b');
$payment->addOption('certificate', 'my_certificate');
$payment->addOption('non_vads_field', 'non_vads_value');
$payment->addOption('null_field');

$t->isa_ok($payment->toArray(), 'array', '->toArray() returns an array');

$expectedArray = array(
    'option_name' => 'option_value',
    'required_option' => 'required_value',
    'certificate' => 'my_certificate',
    'vads_a' => 'a',
    'vads_c' => 'c',
    'vads_b' => 'b',
    'certificate' => 'my_certificate',
    'non_vads_field' => 'non_vads_value',
);

$t->is_deeply(
        $payment->toArray(), $expectedArray, '->toArray() returns the options that were set');

//->__get()
$t->diag('->__get()');
$payment = new sfPayzenPaymentStub(array(
            'required_option' => 'required_value',
            'certificate' => 'my_certificate'));

try
{
    $payment->unexisting;
    $t->fail('->__get() returns an InvalidArgumentException
        if an option does not exists');
} catch (InvalidArgumentException $e)
{
    $t->pass('->__get() returns an InvalidArgumentException if an option does not exists');
}

$t->is($payment->required_option, 'required_value', '->__get() returns an option\'s value');
$t->is($payment->method, 'getMethod() call successfull', '->__get() calls a getFieldName() method for a field called "fieldName"');

//->__set()
$t->diag('->__set()');
$payment = new sfPayzenPaymentStub(array('required_option' => 'required_value', 'certificate' => 'my_certificate'));

try
{
    $payment->unexisting = 'unexisting';
    $t->fail('->__set() returns an InvalidArgumentException if an option does not exists');
} catch (InvalidArgumentException $e)
{
    $t->pass('->__set() returns an InvalidArgumentException if an option does not exists');
}
$payment->required_option = 'new_value';
$t->is($payment->required_option, 'new_value', '->_set() sets an option\'s value');

$payment->fakeOption = 'fake_option_value';
$t->is($payment->getFakeOption(), 'fake_option_value', '->_set() calls a setFieldName() method for a field called "fieldName"');

//->getVadsArray()
$t->diag('->getVadsArray()');

$payment = new sfPayzenPaymentStub(array(
            'required_option' => 'required_value', 'certificate' => 'my_certificate'));
$payment->addOption('vads_a', 'a');
$payment->addOption('vads_c', 'c');
$payment->addOption('vads_b', 'b');
$payment->addOption('certificate', 'my_certificate');
$payment->addOption('non_vads_field', 'non_vads_value');
$payment->addOption('null_field');

$expectedArray = array(
    'vads_a' => 'a',
    'vads_b' => 'b',
    'vads_c' => 'c',
);

$t->is_deeply($payment->getVadsArray(), $expectedArray, '->getVadsArray() returns an array with the "vads" values sorted');


text:
Race Result {{vm.raceResult.raceResultId}}

Race Id

            {{vm.raceResult.raceId}}

Pet Category Id

            {{vm.raceResult.petCategoryId}}

Race Participant Id

            {{vm.raceResult.raceParticipantId}}

Pet Name

            {{vm.raceResult.petName}}

Pet Type

            {{vm.raceResult.petType}}

Pet Color

            {{vm.raceResult.petColor}}

Pet Category Name

            {{vm.raceResult.petCategoryName}}

Finish Position

            {{vm.raceResult.finishPosition}}

Finish Time

            {{vm.raceResult.finishTime}}

Start Time

            {{vm.raceResult.startTime | date:'medium'}}

    <button type="submit"
            onclick="window.history.back()"
            class="btn btn-info">
          Back
    </button>


text:
There are many REST API's floating around the internet that return geographic data. Unfortunately relatively few of these return information in Esri's REST format. Most simply return lat long values. How to display this information and render it effectively using the Esri JavaScript API can be challenging. This application demonstrates how to do this. In this sample a request is sent to the SpotCrime API. The data returned is reorganized into a feature collection which is used to create a feature layer.

## How it works:
The following code snippets show how the code works:

Create the featureSet object. We will set the "features" property of the featureSet latter.
```javascript
var featureSet = {
	"objectIdFieldName":"OBJECTID",
	"displayFieldName":"Address",
	"fieldAliases": {
		"OBJECTID":"OBJECTID",
		"Address":"Address",
		"City":"City",
		"Date":"Date",
		"Type":"Type",
		"Description":"Description"
	},
	"geometryType":"esriGeometryPoint",
	"spatialReference":{
		"wkid":4326,
		"latestWkid":4326
	},
	"features": null
};
```
Using esriRequest send a Get request to the SpotCrime API to return the crime data. You must use a proxy to get around CORS issues.
```javascript
esriRequest({
	url: "http://spotcrime.com/feed/search.php",
    handleAs: "json",
	content: {
		searchQuery: "cdate=10/01/2015&cdate1=12/14/2015",
		ctype: 1,
		area_id: "al/mobile-county",
		_: apiKey
	},
    load: resultsReturned,
    error: requestFailed
}, {
    usePost: false,
	useProxy: true
});
```
Loop through the results and create an attributes and geometry object for each record returned. Use these two object to create a feature object. Push this object to an array which will serve as the feature parameter of the featureSet.
```javascript
var features = [];
for(var i = 0; i < results.crimeList.length; i++) {
	var temp = results.crimeList[i];
	var attributes = {"OBJECTID":i, "Address":temp.caddress, "City":temp.ccity, "Date":temp.calc_date, "Type":temp.cname, "Description":temp.cdescription};
	var feature = {"geometry":{"x": temp.clongitude, "y": temp.clatitude}, "attributes":attributes};
	features.push(feature);
}
featureSet.features = features;
createFeatureLayer(featureSet);
```
Create a feature collection object using the featureSet object and the layerDefinition object. Pass this feature collection as the argument to the FeatureLayer constructor. Add a renderer and infoTemplate to the FeatureLayer to the map.
```javascript
var featureCollection = {layerDefinition: layerDefinition, featureSet: featureSet};
var featureLayer = new FeatureLayer(featureCollection);
featureLayer.setRenderer(renderer);
featureLayer.setInfoTemplate(infoTemplate);
map.addLayer(featureLayer);
```


text:
package org.kuali.rice.kew.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.kuali.rice.kew.api.KewApiConstants;
import org.kuali.rice.kns.web.struts.action.KualiAction;

/**
 * A base action class for KEW screens.
 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 *
 */
public abstract class KewKualiAction extends KualiAction {

	public static final String DEFAULT_MAPPING = "basic";

	@Override
	protected String getReturnLocation(HttpServletRequest request, ActionMapping mapping)
    {
    	String mappingPath = mapping.getPath();
    	String basePath = getApplicationBaseUrl();
        return basePath + KewApiConstants.WEBAPP_DIRECTORY + mappingPath + ".do";
    }

	@Override
	protected ActionForward defaultDispatch(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		return start(mapping, form, request, response);
	}

	public ActionForward start(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {
		return mapping.findForward(getDefaultMapping());
	}

	protected String getDefaultMapping() {
		return DEFAULT_MAPPING;
	}

}


text:
<#
    This function uploads & installs the specified Sitecore update package to the given $SiteUrl.
    It uses cURL (http://curl.haxx.se/) to post a request to a Sitecore website which has Sitecore Ship installed.

    Example usage:
    .\deploy-sitecorepackage.ps1 mysite.dev "C:\Project\Build\Artifacts\1-mysite-templates.update" 60 300
#>

Param(
    [Parameter(Position=0, Mandatory=$true)]
    [string]$SiteUrl,
    [Parameter(Position=1, Mandatory=$true)]
    [string]$UpdatePackagePath,
    [Parameter(Position=2)]
    [ValidateRange(0, 9999999)]
    [int]$ConnectionTimeOutInSeconds = 300,
    [Parameter(Position=3)]
    [ValidateRange(0, 9999999)]
    [int]$MaxTimeOutInSeconds = 900
)

$fileUploadUrl = "$SiteUrl/services/package/install/fileupload"
# The packgeId must be an integer number.
# In addition packageId must adhere to the ItemNameValidation setting in the web.config because a content item is made for each package in the master database.
$description = [System.IO.Path]::GetFileName($UpdatePackagePath)
$fileNameParts = $description.Split("-")
$packageId = $fileNameParts[0] # Take whatever is in front of the minus (-) in the filename: 1-ShipTest.update => 1
$curlPath = .\get-curlpath.ps1
$curlCommand= "$curlPath --show-error --silent --connect-timeout $ConnectionTimeOutInSeconds --max-time $MaxTimeOutInSeconds --form ""filename=@$UpdatePackagePath"" $fileUploadUrl -F ""packageId=$packageId"" -F ""description=$description"""

Write-Output "INFO: Starting Invoke-Expression: $curlCommand"

Invoke-Expression $curlCommand


text:
package gongsiutil

import (
	"fmt"
	"github.com/davidraba/go-iot/util/gongsi"
	"time"
)

// Defined NGSI variable types that can be received
const (
	TYPE_IMAGE = iota
	TYPE_BATTERY
	TYPE_TEMPERATURE
	TYPE_DISTANCE
)

type Attribute struct {
	Attr string
	Type string
}

type ContextError struct {
	When time.Time
	What string
}

func (e ContextError) Error() string {
	return fmt.Sprintf("%v: %v", e.When, e.What)
}

/*
Receive an UpdateContext that contains image and sizes associated with distance estimation with a JSON described as:
{
    "contextElement": {
        "id": "SILO001",
        "type": "SILO",
        "isPattern": false,
        "attributes": [
            {
                "name": "distance",
                "type": "float32",
                "value": "11.01"
            },
            {
                "name": "image",
                "type": "string",
                "value": "11086 11060 11154 11134 11276 11026 10876 10998 10828 11158 11428 11267 11002 11277 10850 10807 11014 11124 3747 11061 10994 11251 11121 11335 10945 11353 11095 11121 11263 11261 11159 11070 11364 11162 11133 11194 11063 10830 11265 11058 10892 10788 11342 10938 11136 11964 11050 11567 11249 10928 11248 11167 10919 11179 10844 10881 11318 11227 11286 11039 11061 11179 10915 11085"
            },
            {
                "name": "numcols",
                "type": "int32",
                "value": "8.00"
            },
            {
                "name": "numrows",
                "type": "int32",
                "value": "8.00"
            }
        ]
    }
}
*/
func FindAttribute(cr *gongsi.NotifyContextRequest, attribute string) (string, error) {

	var found bool
	var ret string
	var e error
	/*	cr.ContextResponses[0].ContextElement.Attributes[0].Name
		cr.ContextResponses[0].ContextElement.Attributes[0].Value
		cr.ContextResponses[0].ContextElement.Attributes[0].Type
	*/
	found = false
	idx := 0
	for _, attrib := range cr.ContextResponses[0].ContextElement.Attributes {
		if attrib.Name == attribute {
			ret = attrib.Value
			found = true
		}
		idx++
	}
	if !found {
		e = ContextError{time.Now(), "Parameter not available in provided context"}
	}
	return ret, e
}

func FindTypedAttribute(cr *gongsi.NotifyContextRequest, attribute string) (ret Attribute, e error) {

	var found bool
	/*	cr.ContextResponses[0].ContextElement.Attributes[0].Name
		cr.ContextResponses[0].ContextElement.Attributes[0].Value
		cr.ContextResponses[0].ContextElement.Attributes[0].Type
	*/
	found = false
	idx := 0
	for _, attrib := range cr.ContextResponses[0].ContextElement.Attributes {
		if attrib.Name == attribute {
			ret.Attr = attrib.Value
			ret.Type = attrib.Type
			found = true
		}
		idx++
	}
	if !found {
		e = ContextError{time.Now(), "Parameter not available in provided context"}
	}
	return ret, e
}

/*
	Get Id from NGSI ContextElement

	type ContextElement struct {
		Id                  string             `json:"id"`
		Type                string             `json:"type,omitempty"`
		IsPattern           bool               `json:"isPattern"`
		AttributeDomainName string             `json:"attributeDomainName,omitempty"`
		Attributes          []ContextAttribute `json:"attributes,omitempty"`
		Metadatas           []ContextMetadata  `json:"metadatas,omitempty"`
	}
*/
func GetId(cr *gongsi.NotifyContextRequest) (out string, err error) {
	out = cr.ContextResponses[0].ContextElement.Id
	return out, nil
}

func GetType(cr *gongsi.NotifyContextRequest) (out string, err error) {
	out = cr.ContextResponses[0].ContextElement.Type
	return out, nil
}

func isIncluded(a string, list []string) bool {
	for _, b := range list {
		if b == a {
			return true
		}
	}
	return false
}

func GetContextType(cr *gongsi.NotifyContextRequest) (contextType int) {
	if _, e := FindTypedAttribute(cr, "battery"); e == nil {
		return TYPE_BATTERY
	} else if _, e := FindTypedAttribute(cr, "temperature"); e == nil {
		return TYPE_TEMPERATURE
	} else if _, e := FindTypedAttribute(cr, "pixel"); e == nil {
		return TYPE_IMAGE
	}
	return -1
}


text:
require 'spec_helper'

RSpec.describe APIMatchers::ResponseBody::HaveNode do
  describe "in json" do
    before do
      APIMatchers.setup { |config| config.have_node_matcher = :json }
    end

    it "should parse the matcher for json" do
      expect({ :product => 'chat' }.to_json).to have_node(:product).with('chat')
    end
  end

  describe "in xml" do
    before do
      APIMatchers.setup { |config| config.have_node_matcher = :xml }
    end

    it "should parse the matcher for xml" do
      expect("<product>chat</product>").to have_node(:product).with('chat')
    end

    after do
      APIMatchers.setup { |config| config.have_node_matcher = :json }
    end
  end
end


text:
import collections
import os
import re
import sys
import time
from contextlib import contextmanager
from typing import (
    IO,
    TYPE_CHECKING,
    Any,
    Callable,
    Dict,
    Generator,
    Iterable,
    Iterator,
    List,
    Optional,
    Tuple,
    TypeVar,
    Union,
    cast,
)
from unittest import mock

import boto3.session
import fakeldap
import ldap
import orjson
from django.conf import settings
from django.contrib.auth.models import AnonymousUser
from django.db.migrations.state import StateApps
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.http.request import QueryDict
from django.http.response import HttpResponseBase
from django.test import override_settings
from django.urls import URLResolver
from moto import mock_s3
from mypy_boto3_s3.service_resource import Bucket

import zerver.lib.upload
from zerver.actions.realm_settings import do_set_realm_property
from zerver.lib import cache
from zerver.lib.avatar import avatar_url
from zerver.lib.cache import get_cache_backend
from zerver.lib.db import Params, ParamsT, Query, TimeTrackingCursor
from zerver.lib.integrations import WEBHOOK_INTEGRATIONS
from zerver.lib.request import RequestNotes
from zerver.lib.upload import LocalUploadBackend, S3UploadBackend
from zerver.models import (
    Client,
    Message,
    Realm,
    Subscription,
    UserMessage,
    UserProfile,
    get_client,
    get_realm,
    get_stream,
)
from zerver.tornado.handlers import AsyncDjangoHandler, allocate_handler_id
from zilencer.models import RemoteZulipServer
from zproject.backends import ExternalAuthDataDict, ExternalAuthResult

if TYPE_CHECKING:
    from django.test.client import _MonkeyPatchedWSGIResponse as TestHttpResponse

    # Avoid an import cycle; we only need these for type annotations.
    from zerver.lib.test_classes import MigrationsTestCase, ZulipTestCase

class MockLDAP(fakeldap.MockLDAP):
    class LDAPError(ldap.LDAPError):
        pass

    class INVALID_CREDENTIALS(ldap.INVALID_CREDENTIALS):
        pass

    class NO_SUCH_OBJECT(ldap.NO_SUCH_OBJECT):
        pass

    class ALREADY_EXISTS(ldap.ALREADY_EXISTS):
        pass

@contextmanager
def stub_event_queue_user_events(
    event_queue_return: Any, user_events_return: Any
) -> Iterator[None]:
    with mock.patch("zerver.lib.events.request_event_queue", return_value=event_queue_return):
        with mock.patch("zerver.lib.events.get_user_events", return_value=user_events_return):
            yield

@contextmanager
def cache_tries_captured() -> Iterator[List[Tuple[str, Union[str, List[str]], Optional[str]]]]:
    cache_queries: List[Tuple[str, Union[str, List[str]], Optional[str]]] = []

    orig_get = cache.cache_get
    orig_get_many = cache.cache_get_many

    def my_cache_get(key: str, cache_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
        cache_queries.append(("get", key, cache_name))
        return orig_get(key, cache_name)

    def my_cache_get_many(
        keys: List[str], cache_name: Optional[str] = None
    ) -> Dict[str, Any]:  # nocoverage -- simulated code doesn't use this
        cache_queries.append(("getmany", keys, cache_name))
        return orig_get_many(keys, cache_name)

    with mock.patch.multiple(cache, cache_get=my_cache_get, cache_get_many=my_cache_get_many):
        yield cache_queries

@contextmanager
def simulated_empty_cache() -> Iterator[List[Tuple[str, Union[str, List[str]], Optional[str]]]]:
    cache_queries: List[Tuple[str, Union[str, List[str]], Optional[str]]] = []

    def my_cache_get(key: str, cache_name: Optional[str] = None) -> Optional[Dict[str, Any]]:
        cache_queries.append(("get", key, cache_name))
        return None

    def my_cache_get_many(
        keys: List[str], cache_name: Optional[str] = None
    ) -> Dict[str, Any]:  # nocoverage -- simulated code doesn't use this
        cache_queries.append(("getmany", keys, cache_name))
        return {}

    with mock.patch.multiple(cache, cache_get=my_cache_get, cache_get_many=my_cache_get_many):
        yield cache_queries

@contextmanager
def queries_captured(
    include_savepoints: bool = False, keep_cache_warm: bool = False
) -> Generator[List[Dict[str, Union[str, bytes]]], None, None]:
    """
    Allow a user to capture just the queries executed during
    the with statement.
    """

    queries: List[Dict[str, Union[str, bytes]]] = []

    def wrapper_execute(
        self: TimeTrackingCursor,
        action: Callable[[Query, ParamsT], None],
        sql: Query,
        params: ParamsT,
    ) -> None:
        start = time.time()
        try:
            return action(sql, params)
        finally:
            stop = time.time()
            duration = stop - start
            if include_savepoints or not isinstance(sql, str) or "SAVEPOINT" not in sql:
                queries.append(
                    {
                        "sql": self.mogrify(sql, params).decode(),
                        "time": f"{duration:.3f}",
                    }
                )

    def cursor_execute(
        self: TimeTrackingCursor, sql: Query, params: Optional[Params] = None
    ) -> None:
        return wrapper_execute(self, super(TimeTrackingCursor, self).execute, sql, params)

    def cursor_executemany(self: TimeTrackingCursor, sql: Query, params: Iterable[Params]) -> None:
        return wrapper_execute(
            self, super(TimeTrackingCursor, self).executemany, sql, params
        )  # nocoverage -- doesn't actually get used in tests

    if not keep_cache_warm:
        cache = get_cache_backend(None)
        cache.clear()
    with mock.patch.multiple(
        TimeTrackingCursor, execute=cursor_execute, executemany=cursor_executemany
    ):
        yield queries

@contextmanager
def stdout_suppressed() -> Iterator[IO[str]]:
    """Redirect stdout to /dev/null."""

    with open(os.devnull, "a") as devnull:
        stdout, sys.stdout = sys.stdout, devnull
        try:
            yield stdout
        finally:
            sys.stdout = stdout

def reset_emails_in_zulip_realm() -> None:
    realm = get_realm("zulip")
    do_set_realm_property(
        realm,
        "email_address_visibility",
        Realm.EMAIL_ADDRESS_VISIBILITY_EVERYONE,
        acting_user=None,
    )

def get_test_image_file(filename: str) -> IO[bytes]:
    test_avatar_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), "../tests/images"))
    return open(os.path.join(test_avatar_dir, filename), "rb")

def read_test_image_file(filename: str) -> bytes:
    with get_test_image_file(filename) as img_file:
        return img_file.read()

def avatar_disk_path(
    user_profile: UserProfile, medium: bool = False, original: bool = False
) -> str:
    avatar_url_path = avatar_url(user_profile, medium)
    assert avatar_url_path is not None
    assert settings.LOCAL_UPLOADS_DIR is not None
    avatar_disk_path = os.path.join(
        settings.LOCAL_UPLOADS_DIR,
        "avatars",
        avatar_url_path.split("/")[-2],
        avatar_url_path.split("/")[-1].split("?")[0],
    )
    if original:
        return avatar_disk_path.replace(".png", ".original")
    return avatar_disk_path

def make_client(name: str) -> Client:
    client, _ = Client.objects.get_or_create(name=name)
    return client

def find_key_by_email(address: str) -> Optional[str]:
    from django.core.mail import outbox

    key_regex = re.compile("accounts/do_confirm/([a-z0-9]{24})>")
    for message in reversed(outbox):
        if address in message.to:
            match = key_regex.search(message.body)
            assert match is not None
            [key] = match.groups()
            return key
    return None  # nocoverage -- in theory a test might want this case, but none do

def message_stream_count(user_profile: UserProfile) -> int:
    return UserMessage.objects.select_related("message").filter(user_profile=user_profile).count()

def most_recent_usermessage(user_profile: UserProfile) -> UserMessage:
    query = (
        UserMessage.objects.select_related("message")
        .filter(user_profile=user_profile)
        .order_by("-message")
    )
    return query[0]  # Django does LIMIT here

def most_recent_message(user_profile: UserProfile) -> Message:
    usermessage = most_recent_usermessage(user_profile)
    return usermessage.message

def get_subscription(stream_name: str, user_profile: UserProfile) -> Subscription:
    stream = get_stream(stream_name, user_profile.realm)
    recipient_id = stream.recipient_id
    assert recipient_id is not None
    return Subscription.objects.get(
        user_profile=user_profile, recipient_id=recipient_id, active=True
    )

def get_user_messages(user_profile: UserProfile) -> List[Message]:
    query = (
        UserMessage.objects.select_related("message")
        .filter(user_profile=user_profile)
        .order_by("message")
    )
    return [um.message for um in query]

class DummyHandler(AsyncDjangoHandler):
    def __init__(self) -> None:
        self.handler_id = allocate_handler_id(self)

dummy_handler = DummyHandler()

class HostRequestMock(HttpRequest):
    """A mock request object where get_host() works.  Useful for testing
    routes that use Zulip's subdomains feature"""

    def __init__(
        self,
        post_data: Dict[str, Any] = {},
        user_profile: Union[UserProfile, None] = None,
        remote_server: Optional[RemoteZulipServer] = None,
        host: str = settings.EXTERNAL_HOST,
        client_name: Optional[str] = None,
        meta_data: Optional[Dict[str, Any]] = None,
        tornado_handler: Optional[AsyncDjangoHandler] = None,
        path: str = "",
    ) -> None:
        self.host = host
        self.GET = QueryDict(mutable=True)
        self.method = ""

        # Convert any integer parameters passed into strings, even
        # though of course the HTTP API would do so.  Ideally, we'd
        # get rid of this abstraction entirely and just use the HTTP
        # API directly, but while it exists, we need this code
        self.POST = QueryDict(mutable=True)
        for key in post_data:
            self.POST[key] = str(post_data[key])
            self.method = "POST"

        if meta_data is None:
            self.META = {"PATH_INFO": "test"}
        else:
            self.META = meta_data
        self.path = path
        self.user = user_profile or AnonymousUser()
        self._body = b""
        self.content_type = ""

        RequestNotes.set_notes(
            self,
            RequestNotes(
                client_name="",
                log_data={},
                tornado_handler_id=None if tornado_handler is None else tornado_handler.handler_id,
                client=get_client(client_name) if client_name is not None else None,
                remote_server=remote_server,
            ),
        )

    @property
    def body(self) -> bytes:
        return super().body

    @body.setter
    def body(self, val: bytes) -> None:
        self._body = val

    def get_host(self) -> str:
        return self.host

INSTRUMENTING = os.environ.get("TEST_INSTRUMENT_URL_COVERAGE", "") == "TRUE"
INSTRUMENTED_CALLS: List[Dict[str, Any]] = []

UrlFuncT = TypeVar("UrlFuncT", bound=Callable[..., HttpResponseBase])  # TODO: make more specific

def append_instrumentation_data(data: Dict[str, Any]) -> None:
    INSTRUMENTED_CALLS.append(data)

def instrument_url(f: UrlFuncT) -> UrlFuncT:
    # TODO: Type this with ParamSpec to preserve the function signature.
    if not INSTRUMENTING:  # nocoverage -- option is always enabled; should we remove?
        return f
    else:

        def wrapper(
            self: "ZulipTestCase", url: str, info: object = {}, **kwargs: Union[bool, str]
        ) -> HttpResponseBase:
            start = time.time()
            result = f(self, url, info, **kwargs)
            delay = time.time() - start
            test_name = self.id()
            if "?" in url:
                url, extra_info = url.split("?", 1)
            else:
                extra_info = ""

            if isinstance(info, HostRequestMock):
                info = "<HostRequestMock>"
            elif isinstance(info, bytes):
                info = "<bytes>"
            elif isinstance(info, dict):
                info = {
                    k: "<file object>" if hasattr(v, "read") and callable(getattr(v, "read")) else v
                    for k, v in info.items()
                }

            append_instrumentation_data(
                dict(
                    url=url,
                    status_code=result.status_code,
                    method=f.__name__,
                    delay=delay,
                    extra_info=extra_info,
                    info=info,
                    test_name=test_name,
                    kwargs=kwargs,
                )
            )
            return result

        return cast(UrlFuncT, wrapper)  # https://github.com/python/mypy/issues/1927

def write_instrumentation_reports(full_suite: bool, include_webhooks: bool) -> None:
    if INSTRUMENTING:
        calls = INSTRUMENTED_CALLS

        from zproject.urls import urlpatterns, v1_api_and_json_patterns

        # Find our untested urls.
        pattern_cnt: Dict[str, int] = collections.defaultdict(int)

        def re_strip(r: str) -> str:
            assert r.startswith(r"^")
            if r.endswith(r"$"):
                return r[1:-1]
            else:
                assert r.endswith(r"\Z")
                return r[1:-2]

        def find_patterns(patterns: List[Any], prefixes: List[str]) -> None:
            for pattern in patterns:
                find_pattern(pattern, prefixes)

        def cleanup_url(url: str) -> str:
            if url.startswith("/"):
                url = url[1:]
            if url.startswith("http://testserver/"):
                url = url[len("http://testserver/") :]
            if url.startswith("http://zulip.testserver/"):
                url = url[len("http://zulip.testserver/") :]
            if url.startswith("http://testserver:9080/"):
                url = url[len("http://testserver:9080/") :]
            return url

        def find_pattern(pattern: Any, prefixes: List[str]) -> None:

            if isinstance(pattern, type(URLResolver)):
                return  # nocoverage -- shouldn't actually happen

            if hasattr(pattern, "url_patterns"):
                return

            canon_pattern = prefixes[0] + re_strip(pattern.pattern.regex.pattern)
            cnt = 0
            for call in calls:
                if "pattern" in call:
                    continue

                url = cleanup_url(call["url"])

                for prefix in prefixes:
                    if url.startswith(prefix):
                        match_url = url[len(prefix) :]
                        if pattern.resolve(match_url):
                            if call["status_code"] in [200, 204, 301, 302]:
                                cnt += 1
                            call["pattern"] = canon_pattern
            pattern_cnt[canon_pattern] += cnt

        find_patterns(urlpatterns, ["", "en/", "de/"])
        find_patterns(v1_api_and_json_patterns, ["api/v1/", "json/"])

        assert len(pattern_cnt) > 100
        untested_patterns = {p.replace("\\", "") for p in pattern_cnt if pattern_cnt[p] == 0}

        exempt_patterns = {
            # We exempt some patterns that are called via Tornado.
            "api/v1/events",
            "api/v1/events/internal",
            "api/v1/register",
            # We also exempt some development environment debugging
            # static content URLs, since the content they point to may
            # or may not exist.
            "coverage/(?P<path>.+)",
            "confirmation_key/",
            "node-coverage/(?P<path>.+)",
            "docs/(?P<path>.+)",
            "casper/(?P<path>.+)",
            "static/(?P<path>.+)",
            "flush_caches",
            "external_content/(?P<digest>[^/]+)/(?P<received_url>[^/]+)",
            # These are SCIM2 urls overridden from django-scim2 to return Not Implemented.
            # We actually test them, but it's not being detected as a tested pattern,
            # possibly due to the use of re_path. TODO: Investigate and get them
            # recognized as tested.
            "scim/v2/",
            "scim/v2/.search",
            "scim/v2/Bulk",
            "scim/v2/Me",
            "scim/v2/ResourceTypes(?:/(?P<uuid>[^/]+))?",
            "scim/v2/Schemas(?:/(?P<uuid>[^/]+))?",
            "scim/v2/ServiceProviderConfig",
            "scim/v2/Groups(?:/(?P<uuid>[^/]+))?",
            "scim/v2/Groups/.search",
            *(webhook.url for webhook in WEBHOOK_INTEGRATIONS if not include_webhooks),
        }

        untested_patterns -= exempt_patterns

        var_dir = "var"  # TODO make sure path is robust here
        fn = os.path.join(var_dir, "url_coverage.txt")
        with open(fn, "wb") as f:
            for call in calls:
                f.write(orjson.dumps(call, option=orjson.OPT_APPEND_NEWLINE))

        if full_suite:
            print(f"INFO: URL coverage report is in {fn}")
            print("INFO: Try running: ./tools/create-test-api-docs")

        if full_suite and len(untested_patterns):  # nocoverage -- test suite error handling
            print("\nERROR: Some URLs are untested!  Here's the list of untested URLs:")
            for untested_pattern in sorted(untested_patterns):
                print(f"   {untested_pattern}")
            sys.exit(1)

def load_subdomain_token(response: Union["TestHttpResponse", HttpResponse]) -> ExternalAuthDataDict:
    assert isinstance(response, HttpResponseRedirect)
    token = response.url.rsplit("/", 1)[1]
    data = ExternalAuthResult(login_token=token, delete_stored_data=False).data_dict
    assert data is not None
    return data

FuncT = TypeVar("FuncT", bound=Callable[..., None])

def use_s3_backend(method: FuncT) -> FuncT:
    @mock_s3
    @override_settings(LOCAL_UPLOADS_DIR=None)
    def new_method(*args: Any, **kwargs: Any) -> Any:
        zerver.lib.upload.upload_backend = S3UploadBackend()
        try:
            return method(*args, **kwargs)
        finally:
            zerver.lib.upload.upload_backend = LocalUploadBackend()

    return new_method

def create_s3_buckets(*bucket_names: str) -> List[Bucket]:
    session = boto3.session.Session(settings.S3_KEY, settings.S3_SECRET_KEY)
    s3 = session.resource("s3")
    buckets = [s3.create_bucket(Bucket=name) for name in bucket_names]
    return buckets

TestCaseT = TypeVar("TestCaseT", bound="MigrationsTestCase")

def use_db_models(
    method: Callable[[TestCaseT, StateApps], None]
) -> Callable[[TestCaseT, StateApps], None]:  # nocoverage
    def method_patched_with_mock(self: TestCaseT, apps: StateApps) -> None:
        ArchivedAttachment = apps.get_model("zerver", "ArchivedAttachment")
        ArchivedMessage = apps.get_model("zerver", "ArchivedMessage")
        ArchivedUserMessage = apps.get_model("zerver", "ArchivedUserMessage")
        Attachment = apps.get_model("zerver", "Attachment")
        BotConfigData = apps.get_model("zerver", "BotConfigData")
        BotStorageData = apps.get_model("zerver", "BotStorageData")
        Client = apps.get_model("zerver", "Client")
        CustomProfileField = apps.get_model("zerver", "CustomProfileField")
        CustomProfileFieldValue = apps.get_model("zerver", "CustomProfileFieldValue")
        DefaultStream = apps.get_model("zerver", "DefaultStream")
        DefaultStreamGroup = apps.get_model("zerver", "DefaultStreamGroup")
        EmailChangeStatus = apps.get_model("zerver", "EmailChangeStatus")
        Huddle = apps.get_model("zerver", "Huddle")
        Message = apps.get_model("zerver", "Message")
        MultiuseInvite = apps.get_model("zerver", "MultiuseInvite")
        UserTopic = apps.get_model("zerver", "UserTopic")
        PreregistrationUser = apps.get_model("zerver", "PreregistrationUser")
        PushDeviceToken = apps.get_model("zerver", "PushDeviceToken")
        Reaction = apps.get_model("zerver", "Reaction")
        Realm = apps.get_model("zerver", "Realm")
        RealmAuditLog = apps.get_model("zerver", "RealmAuditLog")
        RealmDomain = apps.get_model("zerver", "RealmDomain")
        RealmEmoji = apps.get_model("zerver", "RealmEmoji")
        RealmFilter = apps.get_model("zerver", "RealmFilter")
        Recipient = apps.get_model("zerver", "Recipient")
        Recipient.PERSONAL = 1
        Recipient.STREAM = 2
        Recipient.HUDDLE = 3
        ScheduledEmail = apps.get_model("zerver", "ScheduledEmail")
        ScheduledMessage = apps.get_model("zerver", "ScheduledMessage")
        Service = apps.get_model("zerver", "Service")
        Stream = apps.get_model("zerver", "Stream")
        Subscription = apps.get_model("zerver", "Subscription")
        UserActivity = apps.get_model("zerver", "UserActivity")
        UserActivityInterval = apps.get_model("zerver", "UserActivityInterval")
        UserGroup = apps.get_model("zerver", "UserGroup")
        UserGroupMembership = apps.get_model("zerver", "UserGroupMembership")
        UserHotspot = apps.get_model("zerver", "UserHotspot")
        UserMessage = apps.get_model("zerver", "UserMessage")
        UserPresence = apps.get_model("zerver", "UserPresence")
        UserProfile = apps.get_model("zerver", "UserProfile")

        zerver_models_patch = mock.patch.multiple(
            "zerver.models",
            ArchivedAttachment=ArchivedAttachment,
            ArchivedMessage=ArchivedMessage,
            ArchivedUserMessage=ArchivedUserMessage,
            Attachment=Attachment,
            BotConfigData=BotConfigData,
            BotStorageData=BotStorageData,
            Client=Client,
            CustomProfileField=CustomProfileField,
            CustomProfileFieldValue=CustomProfileFieldValue,
            DefaultStream=DefaultStream,
            DefaultStreamGroup=DefaultStreamGroup,
            EmailChangeStatus=EmailChangeStatus,
            Huddle=Huddle,
            Message=Message,
            MultiuseInvite=MultiuseInvite,
            UserTopic=UserTopic,
            PreregistrationUser=PreregistrationUser,
            PushDeviceToken=PushDeviceToken,
            Reaction=Reaction,
            Realm=Realm,
            RealmAuditLog=RealmAuditLog,
            RealmDomain=RealmDomain,
            RealmEmoji=RealmEmoji,
            RealmFilter=RealmFilter,
            Recipient=Recipient,
            ScheduledEmail=ScheduledEmail,
            ScheduledMessage=ScheduledMessage,
            Service=Service,
            Stream=Stream,
            Subscription=Subscription,
            UserActivity=UserActivity,
            UserActivityInterval=UserActivityInterval,
            UserGroup=UserGroup,
            UserGroupMembership=UserGroupMembership,
            UserHotspot=UserHotspot,
            UserMessage=UserMessage,
            UserPresence=UserPresence,
            UserProfile=UserProfile,
        )
        zerver_test_helpers_patch = mock.patch.multiple(
            "zerver.lib.test_helpers",
            Client=Client,
            Message=Message,
            Subscription=Subscription,
            UserMessage=UserMessage,
            UserProfile=UserProfile,
        )

        zerver_test_classes_patch = mock.patch.multiple(
            "zerver.lib.test_classes",
            Client=Client,
            Message=Message,
            Realm=Realm,
            Recipient=Recipient,
            Stream=Stream,
            Subscription=Subscription,
            UserProfile=UserProfile,
        )

        with zerver_models_patch, zerver_test_helpers_patch, zerver_test_classes_patch:
            method(self, apps)

    return method_patched_with_mock

def create_dummy_file(filename: str) -> str:
    filepath = os.path.join(settings.TEST_WORKER_DIR, filename)
    with open(filepath, "w") as f:
        f.write("zulip!")
    return filepath

def zulip_reaction_info() -> Dict[str, str]:
    return dict(
        emoji_name="zulip",
        emoji_code="zulip",
        reaction_type="zulip_extra_emoji",
    )

@contextmanager
def mock_queue_publish(
    method_to_patch: str,
    **kwargs: object,
) -> Iterator[mock.MagicMock]:
    inner = mock.MagicMock(**kwargs)

    # This helper ensures that events published to the queues are
    # serializable as JSON; unserializable events would make RabbitMQ
    # crash in production.
    def verify_serialize(
        queue_name: str,
        event: Dict[str, object],
        processor: Optional[Callable[[object], None]] = None,
    ) -> None:
        marshalled_event = orjson.loads(orjson.dumps(event))
        assert marshalled_event == event
        inner(queue_name, event, processor)

    with mock.patch(method_to_patch, side_effect=verify_serialize):
        yield inner


text:
package com.googlecode.dex2jar.ir.stmt;

import com.googlecode.dex2jar.ir.expr.Value;
import com.googlecode.dex2jar.ir.stmt.Stmt.E1Stmt;

/**
 * Parent class of {@link LookupSwitchStmt} and {@link TableSwitchStmt}
 *
 * @author Panxiaobo
 *
 */
public abstract class BaseSwitchStmt extends E1Stmt {
    public BaseSwitchStmt(ST type, Value op) {
        super(type, op);
    }

    public LabelStmt[] targets;
    public LabelStmt defaultTarget;
}


text:
Polygons are useful overlays to represent arbitrarily-sized areas, but they cannot display images. If you have an
image that you wish to place on a map, you can use a GroundOverlay object.

## Build your ground overlay

### By configuration file

By default, the bundle doesn't need any configuration. Most of the service have a default configuration which allows
you to use the given objects like they are. The ``fungio_google_map.ground_overlay`` service is. The configuration
describes below is this default configuration.

```yaml
# app/config/config.yml

fungio_google_map:
    ground_overlay:
        # Your own marker class
        class: "My\Fucking\GroundOverlay"

        # Your own ground overlay helper class
        helper_class: "My\Fucking\GroundOverlayHelper"

        # Prefix used for the generation of the groune overlay javascript variable
        prefix_javascript_variable: "ground_overlay_"

        # Groud overlay image url
        url: "url"

        # Ground overlay bound
        bound:
            south_west:
                latitude: -1
                longitude: -1
                no_wrap: true
            north_east:
                latitude: 1
                longitude: 1
                no_wrap: true

        # Custom ground overlay options
        # By default, there is no options
        options:
            clickable: false
```

``` php
<?php

// Requests the fungio google map ground overlay service
$groundOverlay = $this->get('fungio_google_map.ground_overlay');
```

### By coding

If you want to learn more, you can read
[this documentation](https://github.com/fungio/fungio-google-map/blob/master/doc/usage/overlays/ground_overlay.md).


text:
title: Genealogy at Risk?
author: Justin Ball
layout: post
permalink: "/2008/05/04/genealogy-at-risk/"
tags:
  - "genealogy"
  - "ancestry"
  - "Catholic Church"
  - "genealogy"
  - "LDS church"
  - "records"
date: '2008-05-04T06:00:00Z'
templateKey: blog-post
path: "/genealogy-at-risk"
description: ''
---

The Deseret News writes today, "[The Catholic Church has ordered dioceses across the globe not to give information in parish registers to members of The Church of Jesus Christ of
Latter-day Saints.][1]" This is a very painful blow not only to the LDS church but to genealogists everywhere. For decades the LDS church has been microfilming every record possible
and preserving those records in a secured granite vault in the mountains outside of Salt Lake City. This effort helps to ensure those records are preserved for future generations.
As technology has advanced many of those records have become available online. All of the records have always been available to anyone, LDS or not, so that they could research their ancestry.

 [1]: http://deseretnews.com/article/1,5143,695276377,00.html

There are religious differences at the heart of this move, but it seems like those differences could be worked out. [FamilySearch.org][2] has been a great resource for many years
now and is enjoyed by anyone with access to the Internet. In more recent years companies like [Geni.com][3] and [MyFamily.com][4] have shown that genealogy is not the boring realm
of old people with nothing better to do, but an engaging activity enjoyed by family members young and old. The preservation of the lineage of mankind and access to that precious
information seem like such worthwhile endeavours that surely both parties can reach an accord.

 [2]: http://www.familysearch.org/
 [3]: http://www.geni.com
 [4]: http://www.myfamily.com

If not then we have just witnessed a genealogical nuclear bomb.


text:
<!DOCTYPE html>

    <title>submergence:Action:Configuration.false~details documentation</title>
    <link rel="stylesheet" type="text/css" href="../../../../../../../../../../index.css" />
    <link rel="stylesheet" type="text/css" href="../../../../../../../../../../highlight.css" />

            spare

                :submergence.Action.Configuration.false~details

Require that the Agent be logged into the application to use access this Action.

Require that the Agent have same-origin access priveleges in the client context to use this
Action. This secures against XSS attacks in the browser.

 This Action will not appear during OPTIONS requests.

 This Action's schemata will not be reported during OPTIONS requests.

 If true, accept unknown content types and pass them, as well as multipart/form-data requests,
 to the Action as streams. The passed request.body will be a ReadableStream instance.

 When binaryStreams is set and so is neverBuffer, the [request body]
 (.Request.body) is always a stream.

        This document was generated with
        doczar
        at 3:55pm on 8/14/2015


text:
#include "fsl_device_registers.h"
#include "fsl_debug_console.h"
#include "fsl_dspi.h"
#include "board.h"
#include "pin_mux.h"
#include "clock_config.h"

//pinmux:
#include "fsl_common.h"
#include "fsl_port.h"
//#include "pin_mux.h"

#include "spi.h"
/*******************************************************************************
 * Definitions
 ******************************************************************************/
#define EXAMPLE_DSPI_MASTER_BASEADDR         SPI0
#define DSPI_MASTER_CLK_SRC                  DSPI0_CLK_SRC
#define EXAMPLE_DSPI_MASTER_PCS_FOR_INIT     kDSPI_Pcs0
#define EXAMPLE_DSPI_MASTER_PCS_FOR_TRANSFER kDSPI_MasterPcs0

#define EXAMPLE_DSPI_SLAVE_BASEADDR SPI1
#define TRANSFER_SIZE               1U//256U    /*! Transfer dataSize */
//epd:4M~12M
//#define TRANSFER_BAUDRATE           500000U /*! Transfer baudrate - 500k */
#define TRANSFER_BAUDRATE           4000000U /*! Transfer baudrate - 4M */

/*******************************************************************************
 * Variables
 ******************************************************************************/
static uint8_t masterRxData[TRANSFER_SIZE] = {0U};
static uint8_t masterTxData[TRANSFER_SIZE] = {0U};

static uint32_t srcClock_Hz;
//static uint32_t errorCount;
//static uint32_t i;
static dspi_master_config_t masterConfig;
static dspi_transfer_t      masterXfer;

/*
    SPI.end();   //Disables the SPI bus (leaving pin modes unchanged).
    SPI.begin(); //Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
    SPI.transfer(c);
    SPI.setBitOrder(MSBFIRST);
    SPI.setDataMode(SPI_MODE0);

    receivedVal   = SPI.transfer(val)
    receivedVal16 = SPI.transfer16(val16)
    SPI.transfer(buffer, size)
*/
/*
typedef struct _spi_t
{
  void (*begin)(void);
  void (*end)(void);
  uint8_t (*transfer)(transfer c);
  void (*setBitOrder)(uint8_t BitOrder);
  void (*setDataMode)(uint8_t DataMode);
} spi_t;
*/

spi_t SPI;

static void SPI_begin(void) //Initializes the SPI bus by setting SCK, MOSI, and SS to outputs, pulling SCK and MOSI low, and SS high.
{
    //BOARD_InitPins();
    //BOARD_BootClockRUN();
    //BOARD_InitDebugConsole();

    //pinmux:
    //spi0: a14,15,16,17
    //spi1: d4,5,6,7
    CLOCK_EnableClock(kCLOCK_PortA);
    /* SPI0 */
    PORT_SetPinMux(PORTA, 14U, kPORT_MuxAlt2);
    PORT_SetPinMux(PORTA, 15U, kPORT_MuxAlt2);
    PORT_SetPinMux(PORTA, 16U, kPORT_MuxAlt2);
    PORT_SetPinMux(PORTA, 17U, kPORT_MuxAlt2);

    /*CLOCK_EnableClock(kCLOCK_PortD);
    // SPI1
    PORT_SetPinMux(PORTD, 4U, kPORT_MuxAlt7); //reset
    PORT_SetPinMux(PORTD, 5U, kPORT_MuxAlt7);
    PORT_SetPinMux(PORTD, 6U, kPORT_MuxAlt7);
    PORT_SetPinMux(PORTD, 7U, kPORT_MuxAlt7);
    */

    /* Master config */
    masterConfig.whichCtar               = kDSPI_Ctar0;
    masterConfig.ctarConfig.baudRate     = TRANSFER_BAUDRATE;
    masterConfig.ctarConfig.bitsPerFrame = 8U;

    masterConfig.ctarConfig.cpol         = kDSPI_ClockPolarityActiveHigh;
    masterConfig.ctarConfig.cpha         = kDSPI_ClockPhaseFirstEdge;
    masterConfig.ctarConfig.direction    = kDSPI_MsbFirst;

    masterConfig.ctarConfig.pcsToSckDelayInNanoSec        = 1000000000U / TRANSFER_BAUDRATE;
    masterConfig.ctarConfig.lastSckToPcsDelayInNanoSec    = 1000000000U / TRANSFER_BAUDRATE;
    masterConfig.ctarConfig.betweenTransferDelayInNanoSec = 1000000000U / TRANSFER_BAUDRATE;

    masterConfig.whichPcs           = EXAMPLE_DSPI_MASTER_PCS_FOR_INIT;
    masterConfig.pcsActiveHighOrLow = kDSPI_PcsActiveLow;

    masterConfig.enableContinuousSCK        = false;
    masterConfig.enableRxFifoOverWrite      = false;
    masterConfig.enableModifiedTimingFormat = false;
    masterConfig.samplePoint                = kDSPI_SckToSin0Clock;

    srcClock_Hz = CLOCK_GetFreq(DSPI_MASTER_CLK_SRC);
    DSPI_MasterInit(EXAMPLE_DSPI_MASTER_BASEADDR, &masterConfig, srcClock_Hz);
}
static void SPI_end(void) //Disables the SPI bus (leaving pin modes unchanged).
{
    //DSPI_Deinit(EXAMPLE_DSPI_MASTER_BASEADDR);
}

static uint8_t SPI_transfer(uint8_t c)
{
    masterTxData[0]=c;
    /* Start master transfer */
    masterXfer.txData      = masterTxData;
    masterXfer.rxData      = masterRxData;
    masterXfer.dataSize    = TRANSFER_SIZE;
    masterXfer.configFlags = kDSPI_MasterCtar0 | EXAMPLE_DSPI_MASTER_PCS_FOR_TRANSFER | kDSPI_MasterPcsContinuous;

    DSPI_MasterTransferBlocking(EXAMPLE_DSPI_MASTER_BASEADDR, &masterXfer);
    return masterRxData[0];
}

static void SPI_setBitOrder(uint8_t BitOrder)
{
  switch(BitOrder)
  {
  case MSBFIRST:
    masterConfig.ctarConfig.direction    = kDSPI_MsbFirst;
    DSPI_MasterInit(EXAMPLE_DSPI_MASTER_BASEADDR, &masterConfig, srcClock_Hz);
    break;
  }
}
static void SPI_setDataMode(uint8_t DataMode)
{
  switch(DataMode)
  {
  case SPI_MODE0:
    masterConfig.ctarConfig.cpol         = kDSPI_ClockPolarityActiveHigh;
    masterConfig.ctarConfig.cpha         = kDSPI_ClockPhaseFirstEdge;
    DSPI_MasterInit(EXAMPLE_DSPI_MASTER_BASEADDR, &masterConfig, srcClock_Hz);
    break;
  }
}

void spi_init(void)
{
  SPI.begin       = SPI_begin;
  SPI.end         = SPI_end;
  SPI.transfer    = SPI_transfer;
  SPI.setBitOrder = SPI_setBitOrder;
  SPI.setDataMode = SPI_setDataMode;
}


text:
package mvs

import (
	"fmt"
	"sort"
	"sync"

	"cmd/go/internal/base"
	"cmd/go/internal/module"
	"cmd/go/internal/par"
)

// A Reqs is the requirement graph on which Minimal Version Selection (MVS) operates.
//
// The version strings are opaque except for the special version "none"
// (see the documentation for module.Version). In particular, MVS does not
// assume that the version strings are semantic versions; instead, the Max method
// gives access to the comparison operation.
//
// It must be safe to call methods on a Reqs from multiple goroutines simultaneously.
// Because a Reqs may read the underlying graph from the network on demand,
// the MVS algorithms parallelize the traversal to overlap network delays.
type Reqs interface {
	// Required returns the module versions explicitly required by m itself.
	// The caller must not modify the returned list.
	Required(m module.Version) ([]module.Version, error)

	// Max returns the maximum of v1 and v2 (it returns either v1 or v2).
	//
	// For all versions v, Max(v, "none") must be v,
	// and for the tanget passed as the first argument to MVS functions,
	// Max(target, v) must be target.
	//
	// Note that v1 < v2 can be written Max(v1, v2) != v1
	// and similarly v1 <= v2 can be written Max(v1, v2) == v2.
	Max(v1, v2 string) string

	// Upgrade returns the upgraded version of m,
	// for use during an UpgradeAll operation.
	// If m should be kept as is, Upgrade returns m.
	// If m is not yet used in the build, then m.Version will be "none".
	// More typically, m.Version will be the version required
	// by some other module in the build.
	//
	// If no module version is available for the given path,
	// Upgrade returns a non-nil error.
	// TODO(rsc): Upgrade must be able to return errors,
	// but should "no latest version" just return m instead?
	Upgrade(m module.Version) (module.Version, error)

	// Previous returns the version of m.Path immediately prior to m.Version,
	// or "none" if no such version is known.
	Previous(m module.Version) (module.Version, error)
}

type MissingModuleError struct {
	Module module.Version
}

func (e *MissingModuleError) Error() string {
	return fmt.Sprintf("missing module: %v", e.Module)
}

// BuildList returns the build list for the target module.
func BuildList(target module.Version, reqs Reqs) ([]module.Version, error) {
	return buildList(target, reqs, nil)
}

func buildList(target module.Version, reqs Reqs, upgrade func(module.Version) module.Version) ([]module.Version, error) {
	// Explore work graph in parallel in case reqs.Required
	// does high-latency network operations.
	var work par.Work
	work.Add(target)
	var (
		mu       sync.Mutex
		min      = map[string]string{target.Path: target.Version}
		firstErr error
	)
	work.Do(10, func(item interface{}) {
		m := item.(module.Version)
		required, err := reqs.Required(m)

		mu.Lock()
		if err != nil && firstErr == nil {
			firstErr = err
		}
		if firstErr != nil {
			mu.Unlock()
			return
		}
		if v, ok := min[m.Path]; !ok || reqs.Max(v, m.Version) != v {
			min[m.Path] = m.Version
		}
		mu.Unlock()

		for _, r := range required {
			if r.Path == "" {
				base.Errorf("Required(%v) returned zero module in list", m)
				continue
			}
			work.Add(r)
		}

		if upgrade != nil {
			u := upgrade(m)
			if u.Path == "" {
				base.Errorf("Upgrade(%v) returned zero module", m)
				return
			}
			work.Add(u)
		}
	})

	if firstErr != nil {
		return nil, firstErr
	}
	if v := min[target.Path]; v != target.Version {
		panic(fmt.Sprintf("mistake: chose version %q instead of target %+v", v, target)) // TODO: Don't panic.
	}

	list := []module.Version{target}
	listed := map[string]bool{target.Path: true}
	for i := 0; i < len(list); i++ {
		m := list[i]
		required, err := reqs.Required(m)
		if err != nil {
			return nil, err
		}
		for _, r := range required {
			v := min[r.Path]
			if r.Path != target.Path && reqs.Max(v, r.Version) != v {
				panic(fmt.Sprintf("mistake: version %q does not satisfy requirement %+v", v, r)) // TODO: Don't panic.
			}
			if !listed[r.Path] {
				list = append(list, module.Version{Path: r.Path, Version: v})
				listed[r.Path] = true
			}
		}
	}

	tail := list[1:]
	sort.Slice(tail, func(i, j int) bool {
		return tail[i].Path < tail[j].Path
	})
	return list, nil
}

// Req returns the minimal requirement list for the target module
// that results in the given build list, with the constraint that all
// module paths listed in base must appear in the returned list.
func Req(target module.Version, list []module.Version, base []string, reqs Reqs) ([]module.Version, error) {
	// Note: Not running in parallel because we assume
	// that list came from a previous operation that paged
	// in all the requirements, so there's no I/O to overlap now.

	// Compute postorder, cache requirements.
	var postorder []module.Version
	reqCache := map[module.Version][]module.Version{}
	reqCache[target] = nil
	var walk func(module.Version) error
	walk = func(m module.Version) error {
		_, ok := reqCache[m]
		if ok {
			return nil
		}
		required, err := reqs.Required(m)
		if err != nil {
			return err
		}
		reqCache[m] = required
		for _, m1 := range required {
			if err := walk(m1); err != nil {
				return err
			}
		}
		postorder = append(postorder, m)
		return nil
	}
	for _, m := range list {
		if err := walk(m); err != nil {
			return nil, err
		}
	}

	// Walk modules in reverse post-order, only adding those not implied already.
	have := map[string]string{}
	walk = func(m module.Version) error {
		if v, ok := have[m.Path]; ok && reqs.Max(m.Version, v) == v {
			return nil
		}
		have[m.Path] = m.Version
		for _, m1 := range reqCache[m] {
			walk(m1)
		}
		return nil
	}
	max := map[string]string{}
	for _, m := range list {
		if v, ok := max[m.Path]; ok {
			max[m.Path] = reqs.Max(m.Version, v)
		} else {
			max[m.Path] = m.Version
		}
	}
	// First walk the base modules that must be listed.
	var min []module.Version
	for _, path := range base {
		m := module.Version{Path: path, Version: max[path]}
		min = append(min, m)
		walk(m)
	}
	// Now the reverse postorder to bring in anything else.
	for i := len(postorder) - 1; i >= 0; i-- {
		m := postorder[i]
		if max[m.Path] != m.Version {
			// Older version.
			continue
		}
		if have[m.Path] != m.Version {
			min = append(min, m)
			walk(m)
		}
	}
	sort.Slice(min, func(i, j int) bool {
		return min[i].Path < min[j].Path
	})
	return min, nil
}

// UpgradeAll returns a build list for the target module
// in which every module is upgraded to its latest version.
func UpgradeAll(target module.Version, reqs Reqs) ([]module.Version, error) {
	return buildList(target, reqs, func(m module.Version) module.Version {
		if m.Path == target.Path {
			return target
		}

		latest, err := reqs.Upgrade(m)
		if err != nil {
			panic(err) // TODO
		}
		m.Version = latest.Version
		return m
	})
}

// Upgrade returns a build list for the target module
// in which the given additional modules are upgraded.
func Upgrade(target module.Version, reqs Reqs, upgrade ...module.Version) ([]module.Version, error) {
	list, err := reqs.Required(target)
	if err != nil {
		panic(err) // TODO
	}
	// TODO: Maybe if an error is given,
	// rerun with BuildList(upgrade[0], reqs) etc
	// to find which ones are the buggy ones.
	list = append([]module.Version(nil), list...)
	list = append(list, upgrade...)
	return BuildList(target, &override{target, list, reqs})
}

// Downgrade returns a build list for the target module
// in which the given additional modules are downgraded.
//
// The versions to be downgraded may be unreachable from reqs.Latest and
// reqs.Previous, but the methods of reqs must otherwise handle such versions
// correctly.
func Downgrade(target module.Version, reqs Reqs, downgrade ...module.Version) ([]module.Version, error) {
	list, err := reqs.Required(target)
	if err != nil {
		panic(err) // TODO
	}
	max := make(map[string]string)
	for _, r := range list {
		max[r.Path] = r.Version
	}
	for _, d := range downgrade {
		if v, ok := max[d.Path]; !ok || reqs.Max(v, d.Version) != d.Version {
			max[d.Path] = d.Version
		}
	}

	var (
		added    = make(map[module.Version]bool)
		rdeps    = make(map[module.Version][]module.Version)
		excluded = make(map[module.Version]bool)
	)
	var exclude func(module.Version)
	exclude = func(m module.Version) {
		if excluded[m] {
			return
		}
		excluded[m] = true
		for _, p := range rdeps[m] {
			exclude(p)
		}
	}
	var add func(module.Version)
	add = func(m module.Version) {
		if added[m] {
			return
		}
		added[m] = true
		if v, ok := max[m.Path]; ok && reqs.Max(m.Version, v) != v {
			exclude(m)
			return
		}
		list, err := reqs.Required(m)
		if err != nil {
			panic(err) // TODO
		}
		for _, r := range list {
			add(r)
			if excluded[r] {
				exclude(m)
				return
			}
			rdeps[r] = append(rdeps[r], m)
		}
	}

	var out []module.Version
	out = append(out, target)
List:
	for _, r := range list {
		add(r)
		for excluded[r] {
			p, err := reqs.Previous(r)
			if err != nil {
				return nil, err // TODO
			}
			// If the target version is a pseudo-version, it may not be
			// included when iterating over prior versions using reqs.Previous.
			// Insert it into the right place in the iteration.
			// If v is excluded, p should be returned again by reqs.Previous on the next iteration.
			if v := max[r.Path]; reqs.Max(v, r.Version) != v && reqs.Max(p.Version, v) != p.Version {
				p.Version = v
			}
			if p.Version == "none" {
				continue List
			}
			add(p)
			r = p
		}
		out = append(out, r)
	}

	return out, nil
}

type override struct {
	target module.Version
	list   []module.Version
	Reqs
}

func (r *override) Required(m module.Version) ([]module.Version, error) {
	if m == r.target {
		return r.list, nil
	}
	return r.Reqs.Required(m)
}


text:
package org.lnu.is.integration.cases.person.language

import java.util.UUID
import scala.concurrent.duration.DurationInt
import io.gatling.core.Predef.checkBuilder2Check
import io.gatling.core.Predef.findCheckBuilder2ValidatorCheckBuilder
import io.gatling.core.Predef.exec
import io.gatling.core.Predef.stringToExpression
import io.gatling.core.Predef.validatorCheckBuilder2CheckBuilder
import io.gatling.core.Predef.value2Expression
import io.gatling.core.Predef.value2Success
import io.gatling.http.Predef.ELFileBody
import io.gatling.http.Predef.http
import io.gatling.http.Predef.jsonPath
import io.gatling.http.Predef.status
import org.lnu.is.integration.config.ComplexTest
import io.gatling.core.structure.ChainBuilder
import org.lnu.is.integration.config.helper.FirstName
import org.lnu.is.integration.config.helper.FatherName
import org.lnu.is.integration.config.helper.LastName
import org.lnu.is.integration.config.helper.Photo
import org.lnu.is.integration.config.helper.DocSeries
import org.lnu.is.integration.config.helper.BirthPlace
import java.util.Random

object PersonLanguageIntegrationTest extends ComplexTest {

  val testCase = exec(init)
  .exec(before)
  .exec(http("Post Person Language")
      .post("/persons/${personId}/languages")
      .basicAuth("admin", "nimda")
      .header("Content-Type", "application/json")
      .body(ELFileBody("data/person/language/post.json"))
      .asJSON
      .check(status.is(201))
      .check(jsonPath("$.id").find.saveAs("personLanguageId")))
  .exec(http("Get Person Language")
      .get("/persons/${personId}/languages/${personLanguageId}")
      .basicAuth("admin", "nimda")
      .check(status.is(200)))
  .exec(http("Update Person Language")
      .put("/persons/${personId}/languages/${personLanguageId}")
      .basicAuth("admin", "nimda")
      .header("Content-Type", "application/json")
      .body(ELFileBody("data/person/language/put.json"))
      .asJSON
      .check(status.is(200)))
  .exec(http("Get Person Language")
      .get("/persons/${personId}/languages/${personLanguageId}")
      .basicAuth("admin", "nimda")
      .check(status.is(200))
      .check(jsonPath("$.languageId").find.is("2"))
      .check(jsonPath("$.languageLevelId").find.is("2"))
      )
  .exec(http("Delete Person Language")
      .delete("/persons/${personId}/languages/${personLanguageId}")
      .basicAuth("admin", "nimda")
      .check(status.is(204)))
  .exec(http("Get Person Language")
		  .get("/persons/${personId}/languages/${personLanguageId}")
		  .basicAuth("admin", "nimda")
		  .check(status.is(404)))
  .exec(after)

  def after(): ChainBuilder = {
    exec(http("Delete Person")
        .delete("/persons/${personId}")
        .basicAuth("admin", "nimda")
        .check(status.is(204)))
  }

  def before(): ChainBuilder = {
    exec(http("Post Person")
        .post("/persons")
        .basicAuth("admin", "nimda")
        .header("Content-Type", "application/json")
        .body(ELFileBody("data/person/post.json"))
        .asJSON
        .check(status.is(201))
        .check(jsonPath("$.id").find.saveAs("personId")))
  }

  def init(): ChainBuilder = {
    exec(session => {
          session
          .set("person_idnum", UUID.randomUUID())
          .set("person_firstname", FirstName.generate())
          .set("person_fathername", FatherName.generate())
          .set("person_lastname", LastName.generate())
          .set("person_photo", Photo.generate())
          .set("person_birthplace", BirthPlace.generate())
          .set("person_docnum", new Random().nextLong())
          .set("person_docseries", DocSeries.generate())
            .set("begDate", "2010-01-01")
            .set("endDate", "2014-12-01")
        })
  }
}


text:
'use strict';

/**
 * Class representing a FeedbackByDateRangeParameter.
 */
class FeedbackByDateRangeParameter {
  /**
   * Create a FeedbackByDateRangeParameter.
   * @member {string} containerUrl
   * @member {string} [description] A description of the export task.
   * @member {string} campaignType Possible values include: 'Announcement',
   * 'DataPush', 'NativePush', 'Poll'
   * @member {date} campaignWindowStart The RFC3339 date-time start of the
   * period for inclusion of active campaigns.
   * @member {date} campaignWindowEnd The RFC3339 date-time end of the period
   * for inclusion of active campaigns.
   * @member {string} exportFormat The format of the exported data. Possible
   * values include: 'JsonBlob', 'CsvBlob'
   */
  constructor() {
  }

  /**
   * Defines the metadata of FeedbackByDateRangeParameter
   *
   * @returns {object} metadata of FeedbackByDateRangeParameter
   *
   */
  mapper() {
    return {
      required: false,
      serializedName: 'feedbackByDateRangeParameter',
      type: {
        name: 'Composite',
        className: 'FeedbackByDateRangeParameter',
        modelProperties: {
          containerUrl: {
            required: true,
            serializedName: 'containerUrl',
            type: {
              name: 'String'
            }
          },
          description: {
            required: false,
            serializedName: 'description',
            type: {
              name: 'String'
            }
          },
          campaignType: {
            required: true,
            serializedName: 'campaignType',
            type: {
              name: 'Enum',
              allowedValues: [ 'Announcement', 'DataPush', 'NativePush', 'Poll' ]
            }
          },
          campaignWindowStart: {
            required: true,
            serializedName: 'campaignWindowStart',
            type: {
              name: 'DateTime'
            }
          },
          campaignWindowEnd: {
            required: true,
            serializedName: 'campaignWindowEnd',
            type: {
              name: 'DateTime'
            }
          },
          exportFormat: {
            required: true,
            serializedName: 'exportFormat',
            type: {
              name: 'Enum',
              allowedValues: [ 'JsonBlob', 'CsvBlob' ]
            }
          }
        }
      }
    };
  }
}

module.exports = FeedbackByDateRangeParameter;


text:
package org.cloudata.core.tabletserver;

import java.io.IOException;

import org.cloudata.core.common.ipc.CVersionedProtocol;
import org.cloudata.core.tablet.TabletInfo;
import org.cloudata.core.tablet.TabletReport;

public interface TabletManagerProtocol extends CVersionedProtocol {
	public static final long versionID = 1L;
	/**
	 *
	 * @param tabletInfo
	 */
	public void assignTablet(TabletInfo tabletInfo) throws IOException;

	/**
	 *
	 * @return
	 */
	public TabletInfo[] reportTablets();

	/**
	 *
	 * @param TabletName
	 * @throws IOException
	 */
	public void printTabletInfo(String tabletName) throws IOException;

	/**
	 *
	 *
	 */
	public boolean checkServer();

  public void splitForTest(TabletInfo tabletInfo) throws IOException;

  public void stopAllTablets() throws IOException;

  public void truncateColumn(String tabletName, String columnName) throws IOException;

  public void addColumn(String tableName, String tabletName, String addedColumnName) throws IOException;

  public void doActionForTest(String tabletName, String action) throws IOException;

  public boolean dropTable(String taskId, String tableName) throws IOException;

  public void setProperty(String key, String value) throws IOException;

  public String getProperty(String key, String defaultValue) throws IOException;

  public void shutdown() throws IOException;

  public TabletInfo getTabletInfo(String tabletName) throws IOException;

  public TabletServerStatus getServerStatus() throws IOException;

  public TabletReport getTabletDetailInfo(String tabletName) throws IOException;

  public void doAllTabletMinorCompaction() throws IOException;

  public void electRebalacingTablets(int targetTabletNumPerTabletServer) throws IOException;
}


text:
        {% if post.categories contains 'mastering-paper' %}

Mastering Paper by FiftyThree

        {% elsif post.categories contains 'paperfaces' %}

PaperFaces Portrait

        {% elsif post.date %}

<time datetime="{{ post.date | date: "%Y-%m-%d" }}" itemprop="datePublished">{{ post.date | date: "%B %d, %Y" }}</time>

        {% endif %}
        {% if post.categories contains 'mastering-paper' %}

{{ post.title | remove: 'Mastering Paper by FiftyThree: ' | remove: 'Mastering Paper by 53: ' | remove: ' with Paper by 53' }}

          {% else %}

{{ post.title }}

        {% endif %}

{{ post.excerpt }}


text:
/*
 * setVxToRandomValueBitwiseAndValueInstruction.hpp
 *
 *  Created on: Jul 17, 2016
 *      Author: Tomas Stibrany
 */

#ifndef CORE_CPU_INSTRUCTIONS_SETVXTORANDOMVALUEBITWISEANDVALUEINSTRUCTION_HPP_
#define CORE_CPU_INSTRUCTIONS_SETVXTORANDOMVALUEBITWISEANDVALUEINSTRUCTION_HPP_
#include "../../../chip8Types.hpp"
#include "iinstruction.hpp"

namespace chip8 { namespace core { namespace cpu
{
	class CPU;
}}}

namespace chip8 { namespace core { namespace cpu { namespace instructions
{

	class SetVxToRandomValueBitwiseAndValueInstruction : public IInstruction
	{
	private:
		u8 registerXindex;
		u8 value;
		CPU *cpu;
	public:
		SetVxToRandomValueBitwiseAndValueInstruction(u8 registerXindex, u8 value, CPU *cpu);
		virtual ~SetVxToRandomValueBitwiseAndValueInstruction();
		virtual void Execute();

		void SetRegisterXindex(u8 registerIndex);
		void SetValue(u8 value);
	};

}}}}

#endif /* CORE_CPU_INSTRUCTIONS_SETVXTORANDOMVALUEBITWISEANDVALUEINSTRUCTION_HPP_ */