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

Install using pip

.. code:: bash

    $ pip install behave-django

Add ``behave_django`` to your ``INSTALLED_APPS``

.. code:: python

    INSTALLED_APPS += ('behave_django',)

Create the features directory in your project's root directory. (Next to
``manage.py``)

::

    features/
        steps/
            your_steps.py
        environment.py
        your-feature.feature

Run ``python manage.py behave``

::

    $ python manage.py behave
    Creating test database for alias 'default'...
    Feature: Running tests # features/running-tests.feature:1
      In order to prove that behave-django works
      As the Maintainer
      I want to test running behave against this features directory
      Scenario: The Test                       # features/running-tests.feature:6
        Given this step exists                 # features/steps/running_tests.py:4 0.000s
        When I run "python manage.py behave"   # features/steps/running_tests.py:9 0.000s
        Then I should see the behave tests run # features/steps/running_tests.py:14 0.000s

    1 features passed, 0 failed, 0 skipped
    1 scenarios passed, 0 failed, 0 skipped
    3 steps passed, 0 failed, 0 skipped, 0 undefined
    Took.010s
    Destroying test database for alias 'default'...

.. note::

   Starting with version ``0.2.0``, you no longer need to insert the ``environment.before_scenario()`` and ``environment.after_scenario()`` functions in your ``environment.py`` file. The hooks are now included via monkey patching.


text:
channel-update command (local channel.xml)
--SKIPIF--
<?php
if (!getenv('PHP_PEAR_RUNTESTS')) {
    echo 'skip';
}
?>
--FILE--
<?php

require_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'setup.php.inc';

$ch = new PEAR_ChannelFile;
$ch->setName('pear.php.net');
$ch->setSummary('fake');
$ch->setServer('pear.php.net');
$ch->setDefaultPEARProtocols();
$fp = fopen($temp_path . DIRECTORY_SEPARATOR . 'fakechannel.xml', 'wb');
fwrite($fp, $ch->toXml());
fclose($fp);
$e = $command->run('channel-update', array(), array($temp_path . DIRECTORY_SEPARATOR . 'fakechannel.xml'));
$phpunit->assertNoErrors('after');
$phpunit->assertEquals(array (
  0 =>
  array (
    'info' => 'Update of Channel "pear.php.net" succeeded',
    'cmd' => 'no command',
  ),
), $fakelog->getLog(), 'log');

$reg = new PEAR_Registry($temp_path . DIRECTORY_SEPARATOR . 'php');
$chan = $reg->getChannel('pear.php.net');
$phpunit->assertIsA('PEAR_ChannelFile', $chan, 'updated ok?');
$phpunit->assertEquals('pear.php.net', $chan->getName(), 'name ok?');
$phpunit->assertEquals('fake', $chan->getSummary(), 'summary ok?');
echo 'tests done';
?>
--CLEAN--
<?php
require_once dirname(dirname(__FILE__)) . '/teardown.php.inc';
?>
--EXPECT--
tests done

redpajama_set_name: RedPajamaGithub


text:
from __future__ import unicode_literals

import django.utils.version
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
import shared_schema_tenants.validators

try:
    import django.contrib.postgres.fields.jsonb
except ImportError:
    pass

sites_dep_migration = ('sites', '0002_alter_domain_unique',)
if django.utils.version.get_complete_version()[1] < 10:
    sites_dep_migration = ('sites', '0001_initial',)

tenant_fields = [
    ('created', model_utils.fields.AutoCreatedField(
        default=django.utils.timezone.now, editable=False, verbose_name='created')),
    ('modified', model_utils.fields.AutoLastModifiedField(
        default=django.utils.timezone.now, editable=False, verbose_name='modified')),
    ('name', models.CharField(max_length=255)),
    ('slug', models.CharField(max_length=255, primary_key=True, serialize=False)),
]

if 'postgresql' in settings.DATABASES['default']['ENGINE']:
    tenant_fields.extend([
        ('settings', django.contrib.postgres.fields.jsonb.JSONField(
            blank=True, default={}, null=True)),
        ('extra_data', django.contrib.postgres.fields.jsonb.JSONField(
            blank=True, default={}, null=True)),
    ])
else:
    tenant_fields.extend([
        ('_settings', models.TextField(blank=True, default="", null=True,
                                       validators=[shared_schema_tenants.validators.validate_json])),
        ('_extra_data', models.TextField(blank=True, default={}, null=True,
                                         validators=[shared_schema_tenants.validators.validate_json])),
    ])

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        sites_dep_migration,
    ]

    operations = [
        migrations.CreateModel(
            name='Tenant',
            fields=tenant_fields,
            options={
                'abstract': False,
            },
        ),
        migrations.CreateModel(
            name='TenantRelationship',
            fields=[
                ('id', models.AutoField(auto_created=True,
                                        primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(
                    default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(
                    default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('groups', models.ManyToManyField(blank=True,
                                                  related_name='user_tenant_groups', to='auth.Group')),
                ('permissions', models.ManyToManyField(blank=True,
                                                       related_name='user_tenant_permissions', to='auth.Permission')),
                ('tenant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                             related_name='relationships', to='shared_schema_tenants.Tenant')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                           related_name='relationships', to=settings.AUTH_USER_MODEL)),
            ],
        ),
        migrations.CreateModel(
            name='TenantSite',
            fields=[
                ('id', models.AutoField(auto_created=True,
                                        primary_key=True, serialize=False, verbose_name='ID')),
                ('created', model_utils.fields.AutoCreatedField(
                    default=django.utils.timezone.now, editable=False, verbose_name='created')),
                ('modified', model_utils.fields.AutoLastModifiedField(
                    default=django.utils.timezone.now, editable=False, verbose_name='modified')),
                ('site', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE,
                                              related_name='tenant_site', to='sites.Site')),
                ('tenant', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE,
                                             related_name='tenant_sites', to='shared_schema_tenants.Tenant')),
            ],
            options={
                'abstract': False,
            },
        ),
        migrations.AlterUniqueTogether(
            name='tenantrelationship',
            unique_together=set([('user', 'tenant')]),
        ),
    ]


text:
class Metadata < HasMetadata::Model
end


text:
module RsBenchmark
  class ApplicationController < ActionController::Base
    protected
      def calculate_percentile(array, percentile)
        array.sort[(percentile * array.length).floor]
      end
  end
end


text:
import React, { PropTypes, Component } from 'react';
import { Tooltip, Layer } from 'recharts';

class DemoSankeyLink extends Component {
  static propTypes = {
    sourceX: PropTypes.number,
    targetX: PropTypes.number,
    sourceY: PropTypes.number,
    targetY: PropTypes.number,
    sourceControlX: PropTypes.number,
    targetControlX: PropTypes.number,
    sourceRelativeY: PropTypes.number,
    targetRelativeY: PropTypes.number,
    linkWidth: PropTypes.number,
    index: PropTypes.number,
  }

  state = {
    fill: 'url(#linkGradient)',
  }

  render() {
    const { sourceX, targetX,
      sourceY, targetY,
      sourceControlX, targetControlX,
      sourceRelativeY, targetRelativeY,
      linkWidth,
      index,
    } = this.props;
    const { fill } = this.state;

    return (
      <Layer key={`CustomLink${index}`}>
        <path
          d={`
            M${sourceX},${sourceY + linkWidth / 2}
            C${sourceControlX},${sourceY + linkWidth / 2}
              ${targetControlX},${targetY + linkWidth / 2}
              ${targetX},${targetY + linkWidth / 2}
            L${targetX},${targetY - linkWidth / 2}
            C${targetControlX},${targetY - linkWidth / 2}
              ${sourceControlX},${sourceY - linkWidth / 2}
              ${sourceX},${sourceY - linkWidth / 2}
            Z
          `}
          fill={fill}
          strokeWidth="0"
          onMouseEnter={() => { this.setState({ fill: 'rgba(0, 136, 254, 0.5)' }); }}
          onMouseLeave={() => { this.setState({ fill: 'url(#linkGradient)' }); }}
        />
      </Layer>
    );
  }
}

export default DemoSankeyLink;


text:
<!DOCTYPE html>

    <title>ENYRL Scorekeeping</title>
    <link rel="stylesheet" type="text/css" href="ScoreSheet.css">

ENYRL Scorekeeping app

    Score Sheet


text:
var title = "Winter Walk";
var desc = "";
var offer = "Feel that cool breeze? It's reminiscent of something … <split butt_txt=\"What?\" \/> A cold, snow-covered place — crisp air and the quiet peace of each year's night. <split butt_txt=\"Tell me more!\" \/> I believe there's something special about the icicles … but perhaps you would like to see it for yourself?";
var completion = "Brrr! Did you really have to bring the chill back with you? Oh, I think you dropped this on your way back.";

var auto_complete = 0;
var familiar_turnin = 0;
var is_tracked = 0;
var show_alert = 0;
var silent_complete = 0;
var hide_questlog = 1;
var progress = [
];
var giver_progress = [
];
var no_progress = "null";
var prereq_quests = ["blue_and_white_part1"];
var prerequisites = [{
		"not"		:0,
		"condition":	"over_level",
		"value":	7
}];
var end_npcs = ["street_spirit","street_spirit_firebog","street_spirit_zutto","street_spirit_groddle","street_spirit_ix"];
var locations = {
	"level_quest_winter_walk"	: {
		"dev_tsid"	: "",
		"prod_tsid"	: "LIFH2AKJ5I735SV"
	},
	"level_quest_winter_haven"	: {
		"dev_tsid"	: "",
		"prod_tsid"	: "LIFNNTRK1073PQ6"
	}
};

var requirements = {
	"r512"	: {
		"type"		: "flag",
		"name"		: "leave",
		"desc"		: "Toggle flag leave"
	}
};

function onComplete(pc){ // generated from rewards
	var xp=0;
	var currants=0;
	var mood=0;
	var energy=0;
	var favor=0;
	var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0;
	multiplier += pc.imagination_get_quest_modifier();
	apiLogAction('QUEST_REWARDS', 'pc='+pc.tsid, 'quest='+this.class_tsid, 'xp='+intval(xp), 'mood='+intval(mood), 'energy='+intval(energy), 'currants='+intval(currants), 'favor='+intval(favor));
	pc.createItemFromFamiliar("ice", 23);
}
var rewards = {
	"items"	: {
		"0"	: {
			"class_tsid"	: "ice",
			"label"		: "Ice",
			"count"		: 23
		}
	}
};

function callback_winter_walk_part1_finish(details){
	var pc = details.pc;
	if (!pc) pc = this.owner;

	if (!pc) return;

	this.set_flag(pc, 'leave');

	pc.instances_exit(pc.location.instance_id);
}

function canOffer(pc){
	// We don't want to offer this immediately after part 1 finishes
	var part1 = pc.getQuestInstance('blue_and_white_part1');
	if (!part1) return false;
	if (!part1.ts_done) return false;
	if (time() - part1.ts_done < 60*60) return false;

	return true;
}

function onEnterLocation(location){
	if (location == 'level_quest_winter_haven'){
		var pc = this.owner;
		if (!pc) return;

		//pc.instances_exit('level_quest_winter_walk');
		return;
	}
}

function onExitLocation(previous_location){
	var pc = this.owner;
	if (!pc) return;

	if (pc.location.instance_id == 'level_quest_winter_walk' || pc.location.instance_id == 'level_quest_winter_haven') return;

	if (!this.is_complete){
		pc.quests_fail_and_remove(this.class_tsid);

		pc.instances_exit(previous_location);
	}
}

function onStarted(pc){
	this.questInstanceLocation(pc, 'level_quest_winter_walk', -2875, -81, 5*60);

	return {ok: 1};
}

// generated ok (NO DATE)


text:
import { EventEmitter } from "eventemitter3";
import { Document, Result, Query, Sort, Update, Collection, documents } from "./definitions";
import { getField, testDocAgainstQuery } from "./query";
import Cursor = require('./Cursor');
import clone = require('./clone');

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////// Main Collection Class
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

/** Collection - Mongo like evented data Cache */
class Stash extends EventEmitter implements Collection {
  readonly documents: documents = {};

  /** Generate a unique ID */
  genID(length: number = 18): string {
    let ID = "";
    while (ID.length < length) {
      const randNum = Math.floor((Math.random() * 100000000));
      ID += randNum.toString(36);
    }

    return ID.substring(0, length);
  }

  insert(doc: Object): Promise<Result> {
    const doInsert = () => {
      const _id = this.genID();
      doc = clone(doc) // Clone the doc
      doc["_id"] = _id;
      this.documents[_id] = doc as Document;
      this.emit("insert", doc);
      return { success: true, document: doc as Document };
    }

    return new Promise((resolve, reject) => {
      const hResolve = () => resolve(doInsert());
      const hasHooks = this.emit("beforeInsert", doc, hResolve, reject);
      if (!hasHooks) hResolve();
    });
  }

  update(query: Query, update: Object): Promise<Result> {
    const docs = this.findDocs(query);
    const oldDocs = docs.map((doc) => clone(doc));

    const act = () => {
      for (const key in update) {
        if (updateOperators.hasOwnProperty(key)) {
          updateOperators[key](docs, update[key]);
        }
      }

      this.emit("update", docs, oldDocs);
      return { success: true, documents: docs };
    }

    return new Promise((resolve, reject) => {
      const hResolve = () => { resolve(act()) };
      const hasHooks = this.emit("beforeUpdate", oldDocs, hResolve, reject);
      if (!hasHooks) hResolve();
    });
  }

  /** Remove a document from the cache. Promise resolves with the removed document(s). */
  remove(query: Query): Promise<Document[]> {
    const docsToRemove = this.findDocs(query);

    return new Promise((resolve, reject) => {
      const hResolve = () => {
        const removedDocs: Document[] = [];
        for (const doc of docsToRemove) {
          removedDocs.push(doc);
          delete this.documents[doc._id];
        }
        this.emit("remove", removedDocs);

        return resolve(removedDocs);
      }

      const hasHooks = this.emit("beforeRemove", docsToRemove, hResolve, reject);
      if (!hasHooks) hResolve();
    });
  }

  findOne(query: Query): Document | undefined {
    const doc = this.findDocs(query)[0];
    return doc ? clone(doc) : undefined;
  }

  find(query: Query): Cursor {
    return new Cursor(this.findDocs(query), query, this);
  }

  private findDocs(query: Query): Document[] {
    const matchingDocs: Document[] = [];

    let docs = this.documents;

    // If query has an _id find the doc it correponds too (if it exists)
    if (query.hasOwnProperty("_id")) {
      if (!docs.hasOwnProperty(query._id)) return [];

      docs = {};
      docs[query._id] = this.documents[query._id];
    }

    for (const docID in docs) {
      const document = docs[docID];
      if (testDocAgainstQuery(query, document)) matchingDocs.push(document);
    }

    return matchingDocs;
  }
}

export = Stash;

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////// Operators
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

type operator = (object: Object, field: string, value) => void;

function genericUpdate(docsToUpdate: Document[], fields: Object, operation: operator) {
  for (const doc of docsToUpdate) {
    for (const field in fields) {
      if (!fields.hasOwnProperty(field)) continue;

      const docField = getField(field, doc);
      if (docField.success) {
        operation(docField.reference, docField.field, fields[field])
      }
    }
  }
}

const updateOperators = {
  $set: function(docsToUpdate: Document[], fields: Object) {
    const set = (obj, field, value) => { obj[field] = value };
    genericUpdate(docsToUpdate, fields, set);
  },
  $unset: function(docsToUpdate: Document[], fields: Object) {
    const unset = (obj, field, value) => { delete obj[field] };
    genericUpdate(docsToUpdate, fields, unset);
  },
  $inc: function(docsToUpdate: Document[], fields: Object) {
    const inc = (obj, field, value) => { obj[field] += value };
    genericUpdate(docsToUpdate, fields, inc);
  },
  $mul: function(docsToUpdate: Document[], fields: Object) {
    const mul = (obj, field, value) => { obj[field] *= value };
    genericUpdate(docsToUpdate, fields, mul);
  }
};


text:
/***************************************************************************//**
 * @file pti.h
 * @brief This header file contains information for working with the packet
 * trace APIs.
 * @copyright Copyright 2015 Silicon Laboratories, Inc. www.silabs.com
 ******************************************************************************/

#ifndef __RADIO_PTI_H
#define __RADIO_PTI_H

#ifdef __cplusplus
extern "C" {
#endif

#include <stdint.h>

#include "em_gpio.h"

#include "rail_chip_specific.h"

// Once this is a RAIL API this code can be removed as rail-types.h does this
#ifndef RAIL_ENUM
#ifdef DOXYGEN_SHOULD_SKIP_THIS
/// The RAIL library does not use actual enums because the ARM EABI leaves their
/// size ambiguous. This ambiguity causes problems if the application is built
/// with different flags than the library. To work around this we use uint8_t
/// typedefs in compiled code for all enums. For documentation purposes this is
/// converted to an actual enum since it's much easier to read in Doxygen.
#define RAIL_ENUM(name) enum name
#else
/// Define used for the actual RAIL library which sets each enum to a uint8_t
/// typedef and creates a named enum structure for the enumeration values.
#define RAIL_ENUM(name) typedef uint8_t name; enum name##_enum
// For debugging use the following define to turn this back into a proper enum
// #define RAIL_ENUM(name) typedef enum name##_enum name; enum name##_enum
#endif
#endif

/***************************************************************************//**
 * @addtogroup Chip_Specific
 * @{
 ******************************************************************************/

/***************************************************************************//**
 * @addtogroup EFR32xG1x_PTI
 * @{
 * @brief EFR32 Packet Trace Interface (PTI) setup and configuration
 ******************************************************************************/

/*************************  FUNCTION PROTOTYPES   *****************************/

/**
 * Initialize the PTI interface
 *
 * @param ptiInit The structure that defines what pins and modes to use for
 * packet trace.
 *
 * This API will initialize the packet trace interface. It allows you to
 * configure what mode and pins to use for packet trace output. You must call
 * this API either before RAIL initialization or before an explicit call to
 * \ref PTI_Enable() to properly initialize PTI.
 */
RAIL_Status_t PTI_Config(const RAIL_PtiConfig_t *config);

/**
 * Enable or disable the PTI interface
 *
 * This API will turn on or off the packet trace interface (PTI). By default
 * this is turned on already during init time. Note that you must call \ref
 * RADIO_PTI_Init() with a valid initialization structure before calling this
 * API or PTI will not actually turn on.
 */
RAIL_Status_t PTI_Enable(bool enable);

/**
 * Get the current state of the PTI
 *
 * This function will return a pointer to a copy of the PTI state. If you
 * actually want to change the settings, the referenced structure must be
 * updated and then passed back to \ref RADIO_PTI_Config
 */
RAIL_Status_t PTI_GetConfig(RAIL_PtiConfig_t *ptiConfig);

/** @} (end addtogroup EFR32xG1x_PTI) */
/** @} (end addtogroup Chip_Specific) */

#ifdef __cplusplus
}
#endif

#endif //__RADIO_PTI_H


text:
#include "kmsrtpsynchronizer.h"

#define GST_DEFAULT_NAME "rtpsynchronizer"
GST_DEBUG_CATEGORY_STATIC (kms_rtp_synchronizer_debug_category);
#define GST_CAT_DEFAULT kms_rtp_synchronizer_debug_category

#define parent_class kms_rtp_synchronizer_parent_class
G_DEFINE_TYPE (KmsRtpSynchronizer, kms_rtp_synchronizer, G_TYPE_OBJECT);

#define KMS_RTP_SYNCHRONIZER_LOCK(rtpsynchronizer) \
  (g_rec_mutex_lock (&KMS_RTP_SYNCHRONIZER_CAST ((rtpsynchronizer))->priv->mutex))
#define KMS_RTP_SYNCHRONIZER_UNLOCK(rtpsynchronizer) \
  (g_rec_mutex_unlock (&KMS_RTP_SYNCHRONIZER_CAST ((rtpsynchronizer))->priv->mutex))

#define KMS_RTP_SYNCHRONIZER_GET_PRIVATE(obj) ( \
  G_TYPE_INSTANCE_GET_PRIVATE (                 \
    (obj),                                      \
    KMS_TYPE_RTP_SYNCHRONIZER,                  \
    KmsRtpSynchronizerPrivate                   \
  )                                             \
)

struct _KmsRtpSynchronizerPrivate
{
  GRecMutex mutex;

  KmsRtpSyncContext *context;
  gboolean feeded_sorted;

  guint32 ssrc;
  gint32 pt;
  gint32 clock_rate;

  gboolean base_initiated;
  GstClockTime base_ntp_ns_time;
  GstClockTime base_sync_time;

  guint64 ext_ts;
  guint64 last_sr_ext_ts;
  guint64 last_sr_ntp_ns_time;

  /* Interpolate PTSs */
  gboolean base_interpolate_initiated;
  GstClockTime base_interpolate_ext_ts;
  GstClockTime base_interpolate_time;

  /* Feeded sorted case */
  guint64 fs_last_ext_ts;
  GstClockTime fs_last_pts;
};

static void
kms_rtp_synchronizer_finalize (GObject * object)
{
  KmsRtpSynchronizer *self = KMS_RTP_SYNCHRONIZER (object);

  GST_DEBUG_OBJECT (self, "finalize");

  g_object_unref (self->priv->context);
  g_rec_mutex_clear (&self->priv->mutex);

  G_OBJECT_CLASS (parent_class)->finalize (object);
}

static void
kms_rtp_synchronizer_class_init (KmsRtpSynchronizerClass * klass)
{
  GObjectClass *gobject_class;

  gobject_class = G_OBJECT_CLASS (klass);
  gobject_class->finalize = kms_rtp_synchronizer_finalize;

  GST_DEBUG_CATEGORY_INIT (GST_CAT_DEFAULT, GST_DEFAULT_NAME, 0,
      GST_DEFAULT_NAME);

  g_type_class_add_private (klass, sizeof (KmsRtpSynchronizerPrivate));
}

static void
kms_rtp_synchronizer_init (KmsRtpSynchronizer * self)
{
  self->priv = KMS_RTP_SYNCHRONIZER_GET_PRIVATE (self);
  g_rec_mutex_init (&self->priv->mutex);

  self->priv->ext_ts = -1;
  self->priv->fs_last_ext_ts = -1;
}

KmsRtpSynchronizer *
kms_rtp_synchronizer_new (KmsRtpSyncContext * context, gboolean feeded_sorted)
{
  KmsRtpSynchronizer *self;

  self = KMS_RTP_SYNCHRONIZER (g_object_new (KMS_TYPE_RTP_SYNCHRONIZER, NULL));

  if (context != NULL) {
    self->priv->context = g_object_ref (context);
  } else {
    GST_WARNING_OBJECT (self,
        "No context provided, creating new one. This syncrhonizer cannot be synced with others.");
    self->priv->context = kms_rtp_sync_context_new (NULL);
  }

  self->priv->feeded_sorted = feeded_sorted;

  return self;
}

gboolean
kms_rtp_synchronizer_add_clock_rate_for_pt (KmsRtpSynchronizer * self,
    gint32 pt, gint32 clock_rate, GError ** error)
{
  gboolean ret = FALSE;

  if (clock_rate <= 0) {
    const gchar *msg = "clock-rate <= 0 no allowed.";

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR, KMS_RTP_SYNC_INVALID_DATA,
        msg);

    return FALSE;
  }

  KMS_RTP_SYNCHRONIZER_LOCK (self);

  /* TODO: allow more than one PT */
  if (self->priv->clock_rate != 0) {
    const gchar *msg = "Only one PT allowed.";

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR, KMS_RTP_SYNC_INVALID_DATA,
        msg);

    goto end;
  }

  self->priv->pt = pt;
  self->priv->clock_rate = clock_rate;

  ret = TRUE;

end:
  KMS_RTP_SYNCHRONIZER_UNLOCK (self);

  return ret;
}

static void
kms_rtp_synchronizer_process_rtcp_packet (KmsRtpSynchronizer * self,
    GstRTCPPacket * packet, GstClockTime current_time)
{
  GstRTCPType type;
  guint32 ssrc, rtp_time;
  guint64 ntp_time, ntp_ns_time;

  type = gst_rtcp_packet_get_type (packet);
  GST_DEBUG_OBJECT (self, "Received RTCP buffer of type: %d", type);

  if (type != GST_RTCP_TYPE_SR) {
    return;
  }

  gst_rtcp_packet_sr_get_sender_info (packet, &ssrc, &ntp_time, &rtp_time,
      NULL, NULL);

  /* convert ntp_time to nanoseconds */
  ntp_ns_time =
      gst_util_uint64_scale (ntp_time, GST_SECOND,
      (G_GINT64_CONSTANT (1) << 32));

  KMS_RTP_SYNCHRONIZER_LOCK (self);

  GST_DEBUG_OBJECT (self,
      "Received RTCP SR packet SSRC: %u, rtp_time: %u, ntp_time: %"
      G_GUINT64_FORMAT ", ntp_ns_time: %" GST_TIME_FORMAT, ssrc, rtp_time,
      ntp_time, GST_TIME_ARGS (ntp_ns_time));

  if (!self->priv->base_initiated) {
    kms_rtp_sync_context_get_time_matching (self->priv->context, ntp_ns_time,
        current_time, &self->priv->base_ntp_ns_time,
        &self->priv->base_sync_time);
    self->priv->base_initiated = TRUE;
  }

  self->priv->last_sr_ext_ts =
      gst_rtp_buffer_ext_timestamp (&self->priv->ext_ts, rtp_time);
  self->priv->last_sr_ntp_ns_time = ntp_ns_time;

  KMS_RTP_SYNCHRONIZER_UNLOCK (self);
}

gboolean
kms_rtp_synchronizer_process_rtcp_buffer (KmsRtpSynchronizer * self,
    GstBuffer * buffer, GstClockTime current_time, GError ** error)
{
  GstRTCPBuffer rtcp_buffer = GST_RTCP_BUFFER_INIT;
  GstRTCPPacket packet;

  if (!gst_rtcp_buffer_map (buffer, GST_MAP_READ, &rtcp_buffer)) {
    const gchar *msg = "Buffer cannot be mapped as RTCP";

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR,
        KMS_RTP_SYNC_UNEXPECTED_ERROR, msg);

    return FALSE;
  }

  if (!gst_rtcp_buffer_get_first_packet (&rtcp_buffer, &packet)) {
    GST_WARNING_OBJECT (self, "Empty RTCP buffer");
    goto unmap;
  }

  kms_rtp_synchronizer_process_rtcp_packet (self, &packet, current_time);

unmap:
  gst_rtcp_buffer_unmap (&rtcp_buffer);

  return TRUE;
}

static void
kms_rtp_synchronizer_rtp_diff_full (KmsRtpSynchronizer * self,
    GstRTPBuffer * rtp_buffer, gint32 clock_rate, guint64 base_ext_ts,
    gboolean wrapped_down, gboolean wrapped_up)
{
  GstBuffer *buffer = rtp_buffer->buffer;
  guint64 diff_rtptime, diff_rtp_ns_time;

  if (self->priv->ext_ts > base_ext_ts) {
    diff_rtptime = self->priv->ext_ts - base_ext_ts;
    diff_rtp_ns_time =
        gst_util_uint64_scale_int (diff_rtptime, GST_SECOND, clock_rate);

    if (wrapped_up) {
      GST_WARNING_OBJECT (self, "PTS wrapped up, setting MAXUINT64");
      GST_BUFFER_PTS (buffer) = G_MAXUINT64;
    } else if (wrapped_down
        && (diff_rtp_ns_time < (G_MAXUINT64 - GST_BUFFER_PTS (buffer)))) {
      GST_WARNING_OBJECT (self, "PTS wrapped down, setting to 0");
      GST_BUFFER_PTS (buffer) = 0;
    } else if (!wrapped_down
        && (diff_rtp_ns_time > (G_MAXUINT64 - GST_BUFFER_PTS (buffer)))) {
      GST_WARNING_OBJECT (self,
          "Diff RTP ns time greater than (MAXUINT64 - base PTS), setting MAXUINT64");
      GST_BUFFER_PTS (buffer) = G_MAXUINT64;
    } else {
      GST_BUFFER_PTS (buffer) += diff_rtp_ns_time;
    }
  } else if (self->priv->ext_ts < base_ext_ts) {
    diff_rtptime = base_ext_ts - self->priv->ext_ts;
    diff_rtp_ns_time =
        gst_util_uint64_scale_int (diff_rtptime, GST_SECOND, clock_rate);

    if (wrapped_down) {
      GST_WARNING_OBJECT (self, "PTS wrapped down, setting to 0");
      GST_BUFFER_PTS (buffer) = 0;
    } else if (wrapped_up && (diff_rtp_ns_time < GST_BUFFER_PTS (buffer))) {
      GST_WARNING_OBJECT (self, "PTS wrapped up, setting to MAXUINT64");
      GST_BUFFER_PTS (buffer) = G_MAXUINT64;
    } else if (!wrapped_up && (diff_rtp_ns_time > GST_BUFFER_PTS (buffer))) {
      GST_WARNING_OBJECT (self,
          "Diff RTP ns time greater than base PTS, setting to 0");
      GST_BUFFER_PTS (buffer) = 0;
    } else {
      GST_BUFFER_PTS (buffer) -= diff_rtp_ns_time;
    }
  } else {                      /* if equals */
    if (wrapped_down) {
      GST_WARNING_OBJECT (self, "PTS wrapped down, setting to 0");
      GST_BUFFER_PTS (buffer) = 0;
    } else if (wrapped_up) {
      GST_WARNING_OBJECT (self, "PTS wrapped up, setting MAXUINT64");
      GST_BUFFER_PTS (buffer) = G_MAXUINT64;
    }
  }
}

static void
kms_rtp_synchronizer_rtp_diff (KmsRtpSynchronizer * self,
    GstRTPBuffer * rtp_buffer, gint32 clock_rate, guint64 base_ext_ts)
{
  kms_rtp_synchronizer_rtp_diff_full (self, rtp_buffer, clock_rate, base_ext_ts,
      FALSE, FALSE);
}

gboolean
kms_rtp_synchronizer_process_rtp_buffer_mapped (KmsRtpSynchronizer * self,
    GstRTPBuffer * rtp_buffer, GError ** error)
{
  GstBuffer *buffer = rtp_buffer->buffer;
  guint64 pts_orig, ext_ts, last_sr_ext_ts, last_sr_ntp_ns_time;
  guint64 diff_ntp_ns_time;
  guint8 pt;
  guint32 ssrc, ts;
  gint32 clock_rate;
  gboolean ret = TRUE;

  ssrc = gst_rtp_buffer_get_ssrc (rtp_buffer);

  KMS_RTP_SYNCHRONIZER_LOCK (self);

  if (self->priv->ssrc == 0) {
    self->priv->ssrc = ssrc;
  } else if (ssrc != self->priv->ssrc) {
    gchar *msg = g_strdup_printf ("Invalid SSRC (%u), not matching with %u",
        ssrc, self->priv->ssrc);

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR, KMS_RTP_SYNC_INVALID_DATA,
        msg);
    g_free (msg);

    KMS_RTP_SYNCHRONIZER_UNLOCK (self);

    return FALSE;
  }

  pt = gst_rtp_buffer_get_payload_type (rtp_buffer);
  if (pt != self->priv->pt || self->priv->clock_rate <= 0) {
    gchar *msg =
        g_strdup_printf ("Invalid clock-rate %d for PT %u, not changing PTS",
        self->priv->clock_rate, pt);

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR, KMS_RTP_SYNC_INVALID_DATA,
        msg);
    g_free (msg);

    KMS_RTP_SYNCHRONIZER_UNLOCK (self);

    return FALSE;
  }

  pts_orig = GST_BUFFER_PTS (buffer);
  ts = gst_rtp_buffer_get_timestamp (rtp_buffer);
  gst_rtp_buffer_ext_timestamp (&self->priv->ext_ts, ts);

  if (self->priv->feeded_sorted) {
    if (self->priv->fs_last_ext_ts != -1
        && self->priv->ext_ts < self->priv->fs_last_ext_ts) {
      guint16 seq = gst_rtp_buffer_get_seq (rtp_buffer);
      gchar *msg =
          g_strdup_printf
          ("Received an unsorted RTP buffer when expecting sorted (ssrc: %"
          G_GUINT32_FORMAT ", seq: %" G_GUINT16_FORMAT ", ts: %"
          G_GUINT32_FORMAT ", ext_ts: %" G_GUINT64_FORMAT
          "). Moving to unsorted mode",
          ssrc, seq, ts, self->priv->ext_ts);

      GST_ERROR_OBJECT (self, "%s", msg);
      g_set_error_literal (error, KMS_RTP_SYNC_ERROR, KMS_RTP_SYNC_INVALID_DATA,
          msg);
      g_free (msg);

      self->priv->feeded_sorted = FALSE;
      ret = FALSE;
    } else if (self->priv->ext_ts == self->priv->fs_last_ext_ts) {
      GST_BUFFER_PTS (buffer) = self->priv->fs_last_pts;
      goto end;
    }
  }

  if (!self->priv->base_initiated) {
    GST_DEBUG_OBJECT (self,
        "Do not sync data for SSRC %u and PT %u, interpolating PTS", ssrc, pt);

    if (!self->priv->base_interpolate_initiated) {
      self->priv->base_interpolate_ext_ts = self->priv->ext_ts;
      self->priv->base_interpolate_time = GST_BUFFER_PTS (buffer);
      self->priv->base_interpolate_initiated = TRUE;
    } else {
      buffer = gst_buffer_make_writable (buffer);
      GST_BUFFER_PTS (buffer) = self->priv->base_interpolate_time;
      kms_rtp_synchronizer_rtp_diff (self, rtp_buffer, self->priv->clock_rate,
          self->priv->base_interpolate_ext_ts);
    }
  } else {
    gboolean wrapped_down, wrapped_up;

    wrapped_down = wrapped_up = FALSE;

    buffer = gst_buffer_make_writable (buffer);
    GST_BUFFER_PTS (buffer) = self->priv->base_sync_time;

    if (self->priv->last_sr_ntp_ns_time > self->priv->base_ntp_ns_time) {
      diff_ntp_ns_time =
          self->priv->last_sr_ntp_ns_time - self->priv->base_ntp_ns_time;
      wrapped_up = diff_ntp_ns_time > (G_MAXUINT64 - GST_BUFFER_PTS (buffer));
      GST_BUFFER_PTS (buffer) += diff_ntp_ns_time;
    } else if (self->priv->last_sr_ntp_ns_time < self->priv->base_ntp_ns_time) {
      diff_ntp_ns_time =
          self->priv->base_ntp_ns_time - self->priv->last_sr_ntp_ns_time;
      wrapped_down = GST_BUFFER_PTS (buffer) < diff_ntp_ns_time;
      GST_BUFFER_PTS (buffer) -= diff_ntp_ns_time;
    }
    /* if equals do nothing */

    kms_rtp_synchronizer_rtp_diff_full (self, rtp_buffer,
        self->priv->clock_rate, self->priv->last_sr_ext_ts, wrapped_down,
        wrapped_up);
  }

  if (self->priv->feeded_sorted) {
    if (GST_BUFFER_PTS (buffer) < self->priv->fs_last_pts) {
      guint16 seq = gst_rtp_buffer_get_seq (rtp_buffer);

      GST_WARNING_OBJECT (self,
          "Non monotonic PTS assignment in sorted mode (ssrc: %"
          G_GUINT32_FORMAT ", seq: %" G_GUINT16_FORMAT ", ts: %"
          G_GUINT32_FORMAT ", ext_ts: %" G_GUINT64_FORMAT
          "). Forcing monotonic", ssrc, seq, ts, self->priv->ext_ts);

      GST_BUFFER_PTS (buffer) = self->priv->fs_last_pts;
    }

    self->priv->fs_last_ext_ts = self->priv->ext_ts;
    self->priv->fs_last_pts = GST_BUFFER_PTS (buffer);
  }

end:
  clock_rate = self->priv->clock_rate;
  ext_ts = self->priv->ext_ts;
  last_sr_ext_ts = self->priv->last_sr_ext_ts;
  last_sr_ntp_ns_time = self->priv->last_sr_ntp_ns_time;

  KMS_RTP_SYNCHRONIZER_UNLOCK (self);

  kms_rtp_sync_context_write_stats (self->priv->context, ssrc, clock_rate,
      pts_orig, GST_BUFFER_PTS (buffer), GST_BUFFER_DTS (buffer), ext_ts,
      last_sr_ntp_ns_time, last_sr_ext_ts);

  return ret;
}

gboolean
kms_rtp_synchronizer_process_rtp_buffer (KmsRtpSynchronizer * self,
    GstBuffer * buffer, GError ** error)
{
  GstRTPBuffer rtp_buffer = GST_RTP_BUFFER_INIT;
  gboolean ret;

  if (!gst_rtp_buffer_map (buffer, GST_MAP_READ, &rtp_buffer)) {
    const gchar *msg = "Buffer cannot be mapped as RTP";

    GST_ERROR_OBJECT (self, "%s", msg);
    g_set_error_literal (error, KMS_RTP_SYNC_ERROR,
        KMS_RTP_SYNC_UNEXPECTED_ERROR, msg);
    return FALSE;
  }

  ret =
      kms_rtp_synchronizer_process_rtp_buffer_mapped (self, &rtp_buffer, error);

  gst_rtp_buffer_unmap (&rtp_buffer);

  return ret;
}


text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/ads/googleads/v10/services/keyword_theme_constant_service.proto

namespace Google\Ads\GoogleAds\V10\Services;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * Response message for
 * [KeywordThemeConstantService.SuggestKeywordThemeConstants][google.ads.googleads.v10.services.KeywordThemeConstantService.SuggestKeywordThemeConstants].
 *
 * Generated from protobuf message google.ads.googleads.v10.services.SuggestKeywordThemeConstantsResponse
 */
class SuggestKeywordThemeConstantsResponse extends \Google\Protobuf\Internal\Message
{
    /**
     * Smart Campaign keyword theme suggestions.
     *
     * Generated from protobuf field repeated .google.ads.googleads.v10.resources.KeywordThemeConstant keyword_theme_constants = 1;
     */
    private $keyword_theme_constants;

    /**
     * Constructor.
     *
     * @param array $data {
     *     Optional. Data for populating the Message object.
     *
     *     @type \Google\Ads\GoogleAds\V10\Resources\KeywordThemeConstant[]|\Google\Protobuf\Internal\RepeatedField $keyword_theme_constants
     *           Smart Campaign keyword theme suggestions.
     * }
     */
    public function __construct($data = NULL) {
        \GPBMetadata\Google\Ads\GoogleAds\V10\Services\KeywordThemeConstantService::initOnce();
        parent::__construct($data);
    }

    /**
     * Smart Campaign keyword theme suggestions.
     *
     * Generated from protobuf field repeated .google.ads.googleads.v10.resources.KeywordThemeConstant keyword_theme_constants = 1;
     * @return \Google\Protobuf\Internal\RepeatedField
     */
    public function getKeywordThemeConstants()
    {
        return $this->keyword_theme_constants;
    }

    /**
     * Smart Campaign keyword theme suggestions.
     *
     * Generated from protobuf field repeated .google.ads.googleads.v10.resources.KeywordThemeConstant keyword_theme_constants = 1;
     * @param \Google\Ads\GoogleAds\V10\Resources\KeywordThemeConstant[]|\Google\Protobuf\Internal\RepeatedField $var
     * @return $this
     */
    public function setKeywordThemeConstants($var)
    {
        $arr = GPBUtil::checkRepeatedField($var, \Google\Protobuf\Internal\GPBType::MESSAGE, \Google\Ads\GoogleAds\V10\Resources\KeywordThemeConstant::class);
        $this->keyword_theme_constants = $arr;

        return $this;
    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Bull. trimest. Soc. mycol. Fr. 97(2): 93 (1981)

#### Original name
Cercospora wisteriicola J.M. Yen

### Remarks
null


text:
Stephen Rosen

sirosen@globus.org

Work Experience

Globus

Software Engineer

University of Chicago

July 2013 -- Present

Maintain 24x7 production SaaS services on AWS

Develop software for several products, including the open source Globus SDK and CLI

Manticore Project

Contributor

John Reppy, University of Chicago

June 2011 -- June 2013

Adapted thread scheduling to prioritize non-IO bound computations

Worked on full or partial flattening on arbitrarily nested arrays and tuples

Computer Science Instructional Laboratories

System Administrator

University of Chicago

May 2010 -- June 2013

Administered Mac OS X servers, Ubuntu servers, VMWare ESXi servers, and Mac OS X workstations

Implemented a configuration managment service using Fabric

Computer Science Department

TA, Grader

University of Chicago

January 2012 -- June 2013

Networks and Distributed Systems (Winter 2012, Spring 2013), Computer Science with Applications I (Autumn 2012), Honors Introduction to Computer Science II (Winter 2013)

Skills & Experience

Selected Open Source Work

Globus SDK

globus-sdk-python.readthedocs.io

Globus CLI

github.com/globus/globus-cli

nose2

nose2.io

click

click.palletsprojects.com

webargs

webargs.readthedocs.io

Programming & Scripting Languages

Python, Bash, make, awk, SQL, Rust, Javascript, CSS, Ruby, C, SML, Java, and a smattering of others

Education

University of Chicago

BS in Computer Science and BS in Mathematics

June 2013, GPA 3.5

Notable Courses: Topics in Operating Systems, Advanced Distributed Systems, Formal Languages, Algebraic Number Theory

Publications

Data-Only Flattening for Nested Data Parallelism

Manticore Project, University of Chicago

Published In: PPoPP 2013

Authors: L. Bergstrom, J. Reppy, S. Rosen, A. Shaw, M. Rainey, M. Fluet

Status Report: The Manticore Project (2012)

Manticore Project, University of Chicago

Authors: C. Berger, L. Bergstrom, J. Reppy, S. Rosen, N. Sandler, A. Shaw, M. Rainey, M. Fluet


text:
package org.fcrepo.camel.serialization;

import static org.apache.camel.Exchange.FILE_NAME;
import static org.apache.camel.util.ObjectHelper.loadResourceAsStream;
import static org.fcrepo.camel.serialization.SerializationRouter.SERIALIZATION_PATH;

import org.junit.Test;
import java.util.Properties;

import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.commons.io.IOUtils;

/**
 * Test the route workflow with the 'includeBinaries' config property set to true.
 *
 * @author Bethany Seeger
 * @since 2015-11-24
 */

public class BinaryEnabledRouteTest extends AbstractRouteTest {

    @Override
    protected Properties useOverridePropertiesWithPropertiesComponent() {
        final Properties props = new Properties();

        props.put("serialization.stream", "seda:foo");
        props.put("input.stream", "seda:bar");
        props.put("serialization.format", "RDF_XML");
        props.put("serialization.descriptions", "metadata_file");
        props.put("serialization.binaries", "binary_file");
        props.put("serialization.includeBinaries", "true");
        props.put("filter.containers", baseURL + auditContainer);

        return props;
    }

    @Test
    public void testMetadataUpdaterBinary() throws Exception {
        context.getRouteDefinition("FcrepoSerializationBinaryUpdater").adviceWith(context,
          new AdviceWithRouteBuilder() {
              @Override
              public void configure() throws Exception {
                  replaceFromWith("direct:start");
                        mockEndpointsAndSkip("fcrepo:*");
                        mockEndpointsAndSkip("file:*");
              }
        });
        context.start();

        getMockEndpoint("mock:file:binary_file").expectedMessageCount(1);
        getMockEndpoint("mock:file:binary_file").expectedHeaderReceived(FILE_NAME, "/foo");

        // send a file!
        final String body = IOUtils.toString(loadResourceAsStream("binary.rdf"), "UTF-8");

        template.sendBodyAndHeader(body, SERIALIZATION_PATH, "/foo");

        assertMockEndpointsSatisfied();
    }
}


text:
jQuery( document ).ready( function( $ ) {

	var integrationRef = null,
		rendering = false, // state during braintree setup
		container = paypalBraintreeData.checkoutWithPayPalContainer; // shortcut

	function onPaymentMethodReceived( paymentData ) {
		$( 'body' ).block( {
			message: null,
			overlayCSS: {
				background: '#fff',
				opacity: 0.6
			}
		} );

		$.ajax( {
			type: 'POST',
			url: paypalBraintreeData.checkoutWithPayPal.detailsPostbackURL,
			data: paymentData,
			dataType: "json"
		} ).done( function( responseData ) {
			if ( 'undefined' !== typeof responseData.success && responseData.success ) {
				if ( 'undefined' !== typeof responseData.redirectTo ) {
					window.location = responseData.redirectTo;
				}
			}
		} );
	}

	function onReady( integration ) {
		integrationRef = integration;
		rendering = false;
	};

	function init() {
		if ( 'undefined' === typeof braintree ) {
			return;
		}

		if ( 'undefined' === typeof paypalBraintreeData || 'undefined' === typeof paypalBraintreeData.token || 'undefined' === typeof paypalBraintreeData.checkoutWithPayPal ) {
			return;
		}

		if ( ! paypalBraintreeData.checkoutWithPayPal ) {
			return;
		}

		if ( 0 === $( '#' + container ).length ) {
			return;
		}

		renderButton();

		// Currently there's no one global event that triggered when cart is
		// udpated, so need to register callback to two events and avoid possible
		// conflict with flag `rendering`.
		$( document.body ).on( 'updated_wc_div', onCartUpdated );
		$( document.body ).on( 'updated_cart_totals', onCartUpdated );
	}

	function renderButton() {
		var setupArgs = {
			paypal : {
				container: container,
				singleUse: true, // cart checkout must always be single use
				amount: paypalBraintreeData.checkoutWithPayPal.amount,
				currency: paypalBraintreeData.checkoutWithPayPal.currency
			},
			onReady: onReady,
			onPaymentMethodReceived: onPaymentMethodReceived
		};

		rendering = true;
		braintree.setup( paypalBraintreeData.token, "custom", setupArgs );
	}

	function onCartUpdated() {
		// A call to setup already made.
		if ( rendering ) {
			return;
		}

		if ( ! integrationRef ) {
			return;
		}

		// Teardown old reference.
		if ( integrationRef && 'function' === typeof integrationRef.teardown ) {
			integrationRef.teardown( function() {
				integrationRef = null;
			} );
		}

		// Update amount and currency from updated data after cart is udpated.
		paypalBraintreeData.checkoutWithPayPal.amount = $( '#' + container ).data( 'amount' );
		paypalBraintreeData.checkoutWithPayPal.currency = $( '#' + container ).data( 'currency' );

		// Rerender the button.
		renderButton();
	}

	init();

} );


text:
const PAGINATION_UI_BUTTON_LIMIT = 4;
const UI_LIMIT = 6;
const SPREAD = '...';
const PREV = 'Prev';
const NEXT = 'Next';
const FIRST = '« First';
const LAST = 'Last »';

export default {
  props: {
    /**
      This function will take the information given by the pagination component

      Here is an example `change` method:

      change(pagenum) {
        gl.utils.visitUrl(`?page=${pagenum}`);
      },
    */
    change: {
      type: Function,
      required: true,
    },

    /**
      pageInfo will come from the headers of the API call
      in the `.then` clause of the VueResource API call
      there should be a function that contructs the pageInfo for this component

      This is an example:

      const pageInfo = headers => ({
        perPage: +headers['X-Per-Page'],
        page: +headers['X-Page'],
        total: +headers['X-Total'],
        totalPages: +headers['X-Total-Pages'],
        nextPage: +headers['X-Next-Page'],
        previousPage: +headers['X-Prev-Page'],
      });
    */
    pageInfo: {
      type: Object,
      required: true,
    },
  },
  methods: {
    changePage(e) {
      const text = e.target.innerText;
      const { totalPages, nextPage, previousPage } = this.pageInfo;

      switch (text) {
        case SPREAD:
          break;
        case LAST:
          this.change(totalPages);
          break;
        case NEXT:
          this.change(nextPage);
          break;
        case PREV:
          this.change(previousPage);
          break;
        case FIRST:
          this.change(1);
          break;
        default:
          this.change(+text);
          break;
      }
    },
  },
  computed: {
    prev() {
      return this.pageInfo.previousPage;
    },
    next() {
      return this.pageInfo.nextPage;
    },
    getItems() {
      const total = this.pageInfo.totalPages;
      const page = this.pageInfo.page;
      const items = [];

      if (page > 1) items.push({ title: FIRST });

      if (page > 1) {
        items.push({ title: PREV, prev: true });
      } else {
        items.push({ title: PREV, disabled: true, prev: true });
      }

      if (page > UI_LIMIT) items.push({ title: SPREAD, separator: true });

      const start = Math.max(page - PAGINATION_UI_BUTTON_LIMIT, 1);
      const end = Math.min(page + PAGINATION_UI_BUTTON_LIMIT, total);

      for (let i = start; i <= end; i += 1) {
        const isActive = i === page;
        items.push({ title: i, active: isActive, page: true });
      }

      if (total - page > PAGINATION_UI_BUTTON_LIMIT) {
        items.push({ title: SPREAD, separator: true, page: true });
      }

      if (page === total) {
        items.push({ title: NEXT, disabled: true, next: true });
      } else if (total - page >= 1) {
        items.push({ title: NEXT, next: true });
      }

      if (total - page >= 1) items.push({ title: LAST, last: true });

      return items;
    },
  },
  template: `

          {{item.title}}

  `,
};


text:
import DOMUtil from './DOMUtil'
import invariant from 'invariant'

// Block tag flow is different because LIs do not have
// a deterministic style ;_;
const INLINE_TAGS = {
  b: 'bold',
  code: 'code',
  del: 'strikethrough',
  em: 'italic',
  i: 'italic',
  s: 'strikethrough',
  strike: 'strikethrough',
  strong: 'bold',
  u: 'underline'
}

function isValidAnchorNode (link) {
  invariant(
    link instanceof HTMLAnchorElement,
    'Link must be an HTMLAnchorElement.'
  )

  const protocol = link.protocol
  return protocol === 'http:' || protocol === 'https:'
}

function retrieveNodeAttribute (node) {
  const tagName = DOMUtil.tagName(node)
  switch (tagName) {
    case 'b':
    case 'code':
    case 'del':
    case 'em':
    case 'i':
    case 's':
    case 'strike':
    case 'strong':
      return {
        [INLINE_TAGS[tagName]]: true
      }
    case 'a':
      if (isValidAnchorNode(node)) {
        return { link: node.href }
      }
    default:
      if (node instanceof HTMLElement) {
        if (node.style.fontWeight === 'bold') {
          return { bold: true }
        }

        if (node.style.fontStyle === 'italic') {
          return { italic: true }
        }

        if (node.style.textDecoration === 'underline') {
          return { underline: true }
        }

        if (node.style.textDecoration === 'line-through') {
          return { strikethrough: true }
        }
      }

      return {}
  }
}

function parse (node, outerScope) {
  let ops = []

  if (!outerScope) {
    outerScope = retrieveNodeAttribute(node)
  }

  for (const child of node.childNodes) {
    if (child.nodeType === Node.TEXT_NODE) {
      ops.push({insert: child.data, attributes: outerScope})
      continue
    }

    if (child.nodeType === Node.ELEMENT_NODE) {
      const tagName = DOMUtil.tagName(child)

      switch (tagName) {
        case 'br':
          ops.push({insert: '\n'})
          break
        case 'img':
          ops.push({
            insert: 1,
            attributes: {
              image: child.getAttribute('src'),
              alt: child.getAttribute('alt')
            }
          })
          break
        default:
          if (child.hasChildNodes()) {
            const attrs = {...outerScope, ...retrieveNodeAttribute(child)}
            ops = ops.concat(parse(child, attrs))
            if (
              DOMUtil.isBlockNode(child) &&
              child.nextSibling instanceof HTMLElement
            ) {
              ops.push({insert: '\n'})
            }
          }
          break
      }

      continue
    }
  }
  return ops
}

export default (html) => parse(DOMUtil.makeFragment(html))


text:
import { NotificationOffFilled32 } from "../../";

export = NotificationOffFilled32;


text:
[!!] Finish translating... (todo: description of benefits of static properties for configuration)

## Core Configuration - הגדרות בסיסיות

ההגדרה הראשונה אותה יש לבצע בכל התקנה של קוהנה היא שינוי ההגדרות של [Kohana::init] ב `application/bootstrap.php`.
ההגדרות הן:

שגיאות:
האם להשתמש בטיפול שגיאות ויוצאי דופן פנימי של הקוהנה
ערך ברירת מחדל - True, יש לשנות ל FLASE במידה ולא מעוניינים

פרופיל:
האם להשתמש בדף הפרופיל הסטטיסטי
ערך ברירת מחדל - True
יש לשנות ל FALSE במידה ולא מעוניינים - מומלץ שלא להשתמש באפשרות זו בגרסה הסופית על מנת להסתיר מידע רגיש וטעינה מהירה יותר של הדפים

caching - זכרון מטמון
האם לשמור בזכרון מטמון את המיקום של הקבצים בין בקשות?
ערך ברירת מחדל - True, יש לשנות ל FALSE במידה ולא מעוניינים
פעולה זו מגבירה באופן דרמטי את מהירות הטעינת דפים [Kohana::find_file] ולכן יכולה להיות בעלת השפעה גדולה על רמת הביצועים הכללית של האפליקציה.
חשוב להשתמש באופצייה זו רק בגרסה הסופית או בשביל נסיונות.

`string` charset
:   Character set used for all input and output. (Default `"utf-8"`) Should be a character set that is supported by both [htmlspecialchars](http://php.net/htmlspecialchars) and [iconv](http://php.net/iconv).

`string` base_url
:   Base URL for the application. (Default `"/"`) Can be a complete or partial URL. For example "http://example.com/kohana/" or just "/kohana/" would both work.

`string` index_file
:   The PHP file that starts the application. (Default `"index.php"`) Set to `FALSE` when you remove the index file from the URL with URL rewriting.

`string` cache_dir
:   Cache file directory. (Default `"application/cache"`) Must point to a **writable** directory.

## Cookie Settings

There are several static properties in the [Cookie] class that should be set, particularly on production websites.

`string` salt
:   Unique salt string that is used to enable [signed cookies](security.cookies)

`integer` expiration
:   Default expiration lifetime in seconds

`string` path
:   URL path to restrict cookies to be accessed

`string` domain
:   URL domain to restrict cookies to be accessed

`boolean` secure
:   Only allow cookies to be accessed over HTTPS

`boolean` httponly
:   Only allow cookies to be accessed over HTTP (also disables Javascript access)

# Configuration Files

Configuration is done in plain PHP files, which look similar to:

~~~
<?php defined('SYSPATH') or die('No direct script access.');

return array(
    'setting' => 'value',
    'options' => array(
        'foo' => 'bar',
    ),
);
~~~

If the above configuration file was called `myconf.php`, you could acess it using:

~~~
$config = Kohana::config('myconf');
$options = $config['options'];
~~~

[Kohana::config] also provides a shortcut for accessing individual keys from configuration arrays using "dot paths".

Get the "options" array:

~~~
$options = Kohana::config('myconf.options');
~~~

Get the "foo" key from the "options" array:

~~~
$foo = Kohana::config('myconf.options.foo');
~~~

Configuration arrays can also be accessed as objects, if you prefer that method:

~~~
$options = Kohana::config('myconf')->options;
~~~


text:
/**
 * Markdown 编辑器
 */
var simplemde = new SimpleMDE({
    element: document.getElementById("editor")
});


text:
class gatherer : public caf::random_gatherer {
public:
  using super = caf::random_gatherer;

  template <class Scatterer>
  gatherer(caf::local_actor* self, Scatterer& out)
      : super(self, out),
        parent_(static_cast<simulant*>(self)->parent()) {
    // nop
  }

  ~gatherer() override;

  void assign_credit(long downstream_capacity) override;

  long initial_credit(long downstream_capacity, path_ptr x) override;

  void batch_completed(caf::inbound_path* from, size_t xs_size, int64_t id);

private:
  entity* parent_;

  double proportional_ = 1;
  double integral_ = .2;
  double derivative_ = 0;
  double min_rate_ = 100;

  /// State for computing the rate using a PID controller.
  struct rate_state {
    tick_duration last_time_;
    tick_duration batch_interval_;
    double last_rate_;
    double last_err_;
  };

  std::unordered_map<caf::inbound_path*, rate_state> rate_states_;

  void update_rate(caf::inbound_path* from, tick_duration time,
                   size_t num_elements, tick_duration processing_delay,
                   tick_duration scheduling_delay);
};

#endif // GATHERER_HPP


text:
package org.apache.camel.component.vertx.common;

import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.TrustManagerFactory;

import io.vertx.core.net.TCPSSLOptions;
import org.apache.camel.CamelContext;
import org.apache.camel.support.jsse.KeyManagersParameters;
import org.apache.camel.support.jsse.SSLContextParameters;
import org.apache.camel.support.jsse.TrustManagersParameters;

public final class VertxHelper {

    private VertxHelper() {
        // Utility class
    }

    /**
     * Configures key store and trust store options for the given TCPSSLOptions from the configuration specified on
     * SSLContextParameters
     *
     * @param camelContext         the CamelContext
     * @param sslContextParameters the SSL configuration to use for the KeyManagerFactory & TrustManagerFactory
     * @param tcpsslOptions        the TCPSSLOptions instance to configure
     */
    public static void setupSSLOptions(
            CamelContext camelContext, SSLContextParameters sslContextParameters, TCPSSLOptions tcpsslOptions)
            throws Exception {

        if (camelContext == null) {
            throw new IllegalArgumentException("camelContext cannot be null");
        }

        if (sslContextParameters == null) {
            throw new IllegalArgumentException("sslContextParameters cannot be null");
        }

        if (tcpsslOptions == null) {
            throw new IllegalArgumentException("tcpsslOptions cannot be null");
        }

        tcpsslOptions.setSsl(true);

        KeyManagerFactory keyManagerFactory = createKeyManagerFactory(camelContext, sslContextParameters);
        tcpsslOptions.setKeyCertOptions(new KeyManagerFactoryOptions(keyManagerFactory));

        TrustManagerFactory trustManagerFactory = createTrustManagerFactory(camelContext, sslContextParameters);
        tcpsslOptions.setTrustOptions(new TrustManagerFactoryOptions(trustManagerFactory));
    }

    private static KeyManagerFactory createKeyManagerFactory(
            CamelContext camelContext, SSLContextParameters sslContextParameters)
            throws Exception {
        final KeyManagersParameters keyManagers = sslContextParameters.getKeyManagers();
        if (keyManagers == null) {
            return null;
        }
        keyManagers.setCamelContext(camelContext);
        if (keyManagers.getKeyStore() != null) {
            keyManagers.getKeyStore().setCamelContext(camelContext);
        }

        String kmfAlgorithm = camelContext.resolvePropertyPlaceholders(keyManagers.getAlgorithm());
        if (kmfAlgorithm == null) {
            kmfAlgorithm = KeyManagerFactory.getDefaultAlgorithm();
        }

        KeyManagerFactory kmf;
        if (keyManagers.getProvider() == null) {
            kmf = KeyManagerFactory.getInstance(kmfAlgorithm);
        } else {
            kmf = KeyManagerFactory.getInstance(kmfAlgorithm,
                    camelContext.resolvePropertyPlaceholders(keyManagers.getProvider()));
        }

        char[] kmfPassword = null;
        if (keyManagers.getKeyPassword() != null) {
            kmfPassword = camelContext.resolvePropertyPlaceholders(keyManagers.getKeyPassword()).toCharArray();
        }

        KeyStore ks = keyManagers.getKeyStore() == null ? null : keyManagers.getKeyStore().createKeyStore();

        kmf.init(ks, kmfPassword);
        return kmf;
    }

    private static TrustManagerFactory createTrustManagerFactory(
            CamelContext camelContext, SSLContextParameters sslContextParameters)
            throws Exception {
        final TrustManagersParameters trustManagers = sslContextParameters.getTrustManagers();
        if (trustManagers == null) {
            return null;
        }
        trustManagers.setCamelContext(camelContext);
        if (trustManagers.getKeyStore() != null) {
            trustManagers.getKeyStore().setCamelContext(camelContext);
        }

        TrustManagerFactory tmf = null;

        if (trustManagers.getKeyStore() != null) {
            String tmfAlgorithm = camelContext.resolvePropertyPlaceholders(trustManagers.getAlgorithm());
            if (tmfAlgorithm == null) {
                tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
            }

            if (trustManagers.getProvider() == null) {
                tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
            } else {
                tmf = TrustManagerFactory.getInstance(tmfAlgorithm,
                        camelContext.resolvePropertyPlaceholders(trustManagers.getProvider()));
            }

            KeyStore ks = trustManagers.getKeyStore() == null ? null : trustManagers.getKeyStore().createKeyStore();
            tmf.init(ks);
        }
        return tmf;
    }
}


text:
create schema bookstore;

-- ##################################################
-- CREATE TABLES
-- ##################################################
create table registered_user
(
  id int not null generated always as identity constraint pk_registered_user primary key,
  email_address varchar(255),
  password varchar(255),
  salt varchar(4),
  first_name varchar(255),
  last_name varchar(255),
  street varchar(255),
  house_number varchar(5),
  zip_code varchar(5),
  city varchar(255)
);
create table user_group
(
  id int not null generated always as identity constraint pk_user_group primary key,
  group_name varchar(255)
);
create table registered_user_group_mapping
(
  id int not null generated always as identity constraint pk_registered_user_group_mapping primary key,
  fk_registered_user_id int constraint fk_registered_user_group_mapping_to_registered_user references registered_user on delete cascade on update restrict,
  fk_user_group_id int constraint fk_registered_user_group_mapping_to_user_group references user_group on delete cascade on update restrict
);
create table payment_transfer
(
  id int not null generated always as identity constraint pk_payment_transfer primary key,
  fk_registered_user_id int constraint fk_payment_transfer_to_registered_user references registered_user on delete cascade on update restrict,
  iban varchar(22),
  bic varchar(11),
  account_holder varchar(255)
);
create table payment_credit_card
(
  id int not null generated always as identity constraint pk_payment_credit_card primary key,
  fk_registered_user_id int constraint fk_payment_credit_card_to_registered_user references registered_user on delete cascade on update restrict,
  credit_card_number varchar(16),
  card_validation_code varchar(4),
  card_holder varchar(255),
  expiration_month int,
  expiration_year int
);
create table publisher
(
  id int not null generated always as identity constraint pk_publisher primary key,
  publisher_name varchar(255)
);
create table author
(
  id int not null generated always as identity constraint pk_author primary key,
  first_name varchar(255),
  last_name varchar(255)
);
create table book
(
  id int not null generated always as identity constraint pk_book primary key,
  isbn_13 varchar(13),
  fk_publisher_id int constraint fk_book_to_publisher references publisher on delete cascade on update restrict,
  fk_author_id int constraint fk_book_to_author references author on delete cascade on update restrict,
  title varchar(255),
  edition int,
  year_of_release int,
  language varchar(255),
  number_of_pages int,
  price double,
  quantity int
);
create table comment
(
  id int not null generated always as identity constraint pk__comment primary key,
  fk_book_id int constraint fk_comment_to_book references book on delete cascade on update restrict,
  fk_registered_user_id int constraint fk_comment_to_registered_user references registered_user on delete cascade on update restrict,
  comment_text varchar(250)
);
create table booking_order
(
  id int not null generated always as identity constraint pk_order primary key,
  fk_registered_user_id int constraint fk_booking_order_to_registered_user references registered_user on delete cascade on update restrict,
  fk_payment_credit_card int constraint fk_booking_order_to_payment_credit_card references payment_credit_card on delete cascade on update restrict,
  fk_payment_transfer int constraint fk_booking_order_to_payment_transfer references payment_transfer on delete cascade on update restrict
);
create table booking_order_detail
(
  id int not null generated always as identity constraint pk_book_order_detail primary key,
  fk_booking_order_id int constraint fk_booking_order_detail_to_booking_order references booking_order on delete cascade on update restrict,
  fk_book_id int constraint fk_booking_order_detail_to_book references book on delete cascade on update restrict,
  quantity int
);

-- ##################################################
-- CREATE VIEWS
-- ##################################################
create view view_user_authentification as
select ru.email_address, ru.password, ug.group_name
from registered_user_group_mapping rugm
left join registered_user ru on rugm.fk_registered_user_id = ru.id
left join user_group ug on rugm.fk_user_group_id = ug.id;

-- ##################################################
-- INSERT (DUMMY) DATA INTO TABLES
-- ##################################################
insert into registered_user (email_address, password, salt, first_name, last_name, street, house_number, zip_code, city) values
('max.mustermann@beispiel.de', 'b6ec4a0c92fc390b8bb30be6efd16b94dd75fe4fd76bd89c8c44daf85295db98', 'Fy73', 'Max', 'Mustermann', 'Abc Str.', '1', '12345', 'Berlin'),
('jan.gabler@beispiel.de', 'c7490aebff95f18e81a97aa84072f8ce714efa893c6f30dee3eac4f560dbe681', 'Bx8N', 'Jan', 'Gabler', 'Def Str.', '2', '12345', 'Berlin'),
('malte.schwering@beispiel.de', 'f178366558ec65e83430a2bdaf5ef0ecad51493d10427234ece1f404e632d223', '9Lr2', 'Malte', 'Schwering', 'Ghi Str.', '3', '12345', 'Berlin'),
('christopher.schulze@beispiel.de', '6e94b4ca24b455bab76f036e11485a67d842ffbf7da4a436a836f09dbc7f33b6', 'kBSL', 'Christopher', 'Schulze', 'Jkl Str.', '4', '12345', 'Zossen');
insert into user_group (group_name) values
('admin'),
('user');
insert into registered_user_group_mapping (fk_registered_user_id, fk_user_group_id) values
(1, 2),
(2, 1),
(3, 1);
insert into payment_transfer (fk_registered_user_id, iban, bic, account_holder) values
(1, 'DE11111111111111111111', '11111111111', 'Max Mustermann'),
(2, 'DE22222222222222222222', '22222222222', 'Jan Gabler'),
(3, 'DE33333333333333333333', '33333333333', 'Malte Schwering');
insert into payment_credit_card (fk_registered_user_id, credit_card_number, card_validation_code, card_holder, expiration_month, expiration_year) values
(1, '1111111111111111', '111', 'Max Mustermann', 1, 2021),
(2, '2222222222222222', '222', 'Jan Gabler', 2, 2022),
(3, '3333333333333333', '333', 'Malte Schwering', 3, 2023);
insert into publisher (publisher_name) values
('Klett-Cotta'),
('Heyne'),
('Knaur'),
('Eichborn'),
('Carlsen'),
('Deutscher Taschenbuch Verlag'),
('A&C Black'),
('Dorling Kindersley Verlag'),
('FISCHER Taschenbuch');
insert into author (first_name, last_name) values
('J.R.R.', 'Tolkien'),
('Stephen', 'King'),
('Sebastian', 'Fitzek'),
('Timur', 'Vermes'),
('J. K.', 'Rowling'),
('Johann Wolfgang', 'von Goethe'),
('William', 'Shakespeare'),
('Jamie', 'Oliver'),
('Nelson', 'Mandela');
insert into book (isbn_13, fk_publisher_id, fk_author_id, title, edition, year_of_release, language, number_of_pages, price, quantity) values
('9783608938289', 1, 1, 'Der Herr der Ringe', 3, 2009, 'Deutsch', 1292, 49.95, 576),
('9783453435773', 2, 2, 'Es', 3, 2011, 'Deutsch', 1533, 12.99, 398),
('9783426637937', 3, 3, 'Das Kind', 1, 2009, 'Deutsch', 392, 9.99, 712),
('9783847905172', 4, 4, 'Er ist wieder da', 1, 2012, 'Deutsch', 396, 19.33, 857),
('9783551551672', 5, 5, 'Harry Potter und der Stein der Weisen', 1, 1998, 'Deutsch', 335, 15.90, 101),
('9783423124003', 6, 6, 'Faust - Eine Tragödie: Erster und zweiter Teil', 8, 1997, 'Deutsch', 416, 6.90, 666),
('9781903436912', 7, 7, 'Romeo and Juliet: Third Series', 7, 2012, 'Englisch', 451, 11.05, 539),
('9783831022632', 8, 8, 'Jamies 15-Minuten-Küche', 1, 2012, 'Deutsch', 288, 24.95, 928),
('9783596138043', 9, 9, 'Der lange Weg zur Freiheit: Autobiographie', 30, 1997, 'Deutsch', 864, 13.95, 237);
insert into comment (fk_book_id, fk_registered_user_id, comment_text) values
(1, 1, 'Kommentar A'),
(2, 2, 'Kommentar B'),
(3, 3, 'Kommentar C');
insert into booking_order (fk_registered_user_id, fk_payment_credit_card, fk_payment_transfer) values
(1, 1, null),
(2, 2, null),
(3, 3, null);
insert into booking_order_detail (fk_booking_order_id, fk_book_id, quantity) values
(1, 1, 1),
(2, 2, 2),
(3, 3, 3);

-- ##################################################
-- DROP VIEWS & TABLES
-- ##################################################
drop view view_user_authentification;
drop table booking_order_detail;
drop table booking_order;
drop table comment;
drop table book;
drop table author;
drop table publisher;
drop table payment_credit_card;
drop table payment_transfer;
drop table registered_user_group_mapping;
drop table user_group;
drop table registered_user;


text:
cls
$tenantName = "[YOUR TENANT]"
$tenantAdminAccountName = "[YOUR USER ACCOUNT]"
$tenantDomain = $tenantName + ".onMicrosoft.com"
$tenantAdminSPN = $tenantAdminAccountName + "@" + $tenantDomain

$resourceGroupName = "lab02"
$webAppName = "MyWebApp714"
$sourceSlotName = "staging"
$destinationSlotName = "production"

# establish login
$credential = Get-Credential -UserName $tenantAdminSPN -Message "Enter password"
Login-AzureRmAccount -Credential $credential | Out-Null

Write-Host "Swapping deployment slots..."
Swap-AzureRmWebAppSlot `
       -ResourceGroupName $resourceGroupName `
       -Name $webAppName `
       -SourceSlotName $sourceSlotName `
       -DestinationSlotName $destinationSlotName


text:
"use strict";

jest.mock("../../../src/lib/analytics");
jest.mock("../../../src/lib/basic-component-verification");
jest.mock("../../../src/lib/create-assets-url");
jest.mock("../../../src/lib/create-deferred-client");

const analytics = require("../../../src/lib/analytics");
const basicComponentVerification = require("../../../src/lib/basic-component-verification");
const createDeferredClient = require("../../../src/lib/create-deferred-client");
const { create } = require("../../../src/apple-pay");
const ApplePay = require("../../../src/apple-pay/apple-pay");
const {
  wait,
  fake: { client: fakeClient, clientToken, configuration },
} = require("../../helpers");

describe("applePay.create", () => {
  let testContext;

  beforeEach(() => {
    testContext = {};
    testContext.configuration = configuration();
    testContext.configuration.gatewayConfiguration.applePayWeb = {};

    testContext.client = fakeClient({
      configuration: testContext.configuration,
    });

    jest
      .spyOn(createDeferredClient, "create")
      .mockResolvedValue(testContext.client);
    jest.spyOn(basicComponentVerification, "verify").mockResolvedValue(null);
  });

  it("verifies with basicComponentVerification", () => {
    const client = testContext.client;

    return create({
      client,
    }).then(() => {
      expect(basicComponentVerification.verify).toBeCalledTimes(1);
      expect(basicComponentVerification.verify).toHaveBeenCalledWith(
        expect.objectContaining({
          name: "Apple Pay",
          client,
        })
      );
    });
  });

  it("can create with an authorization instead of a client", () => {
    let clientIsReady = false;

    createDeferredClient.create.mockImplementation(() => {
      return wait(10).then(() => {
        clientIsReady = true;

        return testContext.client;
      });
    });

    jest.useFakeTimers();

    return create({
      authorization: clientToken,
      useDeferredClient: true,
      debug: true,
    })
      .then((applePayInstance) => {
        expect(clientIsReady).toBe(false);
        expect(createDeferredClient.create).toBeCalledTimes(1);
        expect(createDeferredClient.create).toHaveBeenCalledWith(
          expect.objectContaining({
            authorization: clientToken,
            debug: true,
            assetsUrl: "https://example.com/assets",
            name: "Apple Pay",
          })
        );

        expect(applePayInstance).toBeInstanceOf(ApplePay);

        jest.advanceTimersByTime(11);
      })
      .then(() => {
        expect(clientIsReady).toBe(true);
      });
  });

  it("rejects with an error when apple pay is not enabled in configuration", () => {
    delete testContext.configuration.gatewayConfiguration.applePayWeb;

    return expect(create({ client: testContext.client })).rejects.toMatchObject(
      {
        code: "APPLE_PAY_NOT_ENABLED",
        type: "MERCHANT",
        message: "Apple Pay is not enabled for this merchant.",
      }
    );
  });

  it("sends an analytics event", () => {
    const client = testContext.client;

    return create({
      client,
      displayName: "Awesome Merchant",
    }).then(() => {
      expect(analytics.sendEvent).toHaveBeenCalledWith(
        client,
        "applepay.initialized"
      );
    });
  });
});


text:
package com.yammer.telemetry.agent;

public class SinkConfiguration {
    private LogConfiguration log = new LogConfiguration();

    public LogConfiguration getLog() { return log; }

    public boolean isEnabled() {
        return log.isEnabled();
    }
}


text:
/*
 * Copyright (C) 2018 ScyllaDB Ltd.
 */

#include <seastar/core/reactor.hh>
#include <seastar/core/thread_cputime_clock.hh>
#include <seastar/core/loop.hh>
#include <seastar/util/later.hh>
#include <seastar/testing/test_case.hh>
#include <seastar/testing/thread_test_case.hh>
#include <../../src/core/stall_detector.hh>
#include <atomic>
#include <chrono>

using namespace seastar;
using namespace std::chrono_literals;

class temporary_stall_detector_settings {
    std::chrono::milliseconds _old_threshold;
    std::function<void ()> _old_report;
public:
    temporary_stall_detector_settings(std::chrono::duration<double> threshold, std::function<void ()> report)
            : _old_threshold(engine().get_blocked_reactor_notify_ms())
            , _old_report(engine().get_stall_detector_report_function()) {
        engine().update_blocked_reactor_notify_ms(std::chrono::duration_cast<std::chrono::milliseconds>(threshold));
        engine().set_stall_detector_report_function(std::move(report));
    }
    ~temporary_stall_detector_settings() {
        engine().update_blocked_reactor_notify_ms(_old_threshold);
        engine().set_stall_detector_report_function(std::move(_old_report));
    }
};

void spin(std::chrono::duration<double> how_much) {
    auto end = internal::cpu_stall_detector::clock_type::now() + how_much;
    while (internal::cpu_stall_detector::clock_type::now() < end) {
        // spin!
    }
}

void spin_some_cooperatively(std::chrono::duration<double> how_much) {
    auto end = std::chrono::steady_clock::now() + how_much;
    while (std::chrono::steady_clock::now() < end) {
        spin(200us);
        if (need_preempt()) {
            thread::yield();
        }
    }
}

SEASTAR_THREAD_TEST_CASE(normal_case) {
    std::atomic<unsigned> reports{};
    temporary_stall_detector_settings tsds(10ms, [&] { ++reports; });
    spin_some_cooperatively(1s);
    BOOST_REQUIRE_EQUAL(reports, 0);
}

SEASTAR_THREAD_TEST_CASE(simple_stalls) {
    std::atomic<unsigned> reports{};
    temporary_stall_detector_settings tsds(10ms, [&] { ++reports; });
    unsigned nr = 10;
    for (unsigned i = 0; i < nr; ++i) {
        spin_some_cooperatively(100ms);
        spin(20ms);
    }
    spin_some_cooperatively(100ms);

    // blocked-reactor-reports-per-minute defaults to 5, so we don't
    // get all 10 reports.
    BOOST_REQUIRE_EQUAL(reports, 5);
}

SEASTAR_THREAD_TEST_CASE(no_poll_no_stall) {
    std::atomic<unsigned> reports{};
    temporary_stall_detector_settings tsds(10ms, [&] { ++reports; });
    spin_some_cooperatively(1ms); // need to yield so that stall detector change from above take effect
    static constexpr unsigned tasks = 2000;
    promise<> p;
    auto f = p.get_future();
    parallel_for_each(boost::irange(0u, tasks), [&p] (unsigned int i) {
        (void)later().then([i, &p] {
            spin(500us);
            if (i == tasks - 1) {
                p.set_value();
            }
        });
        return make_ready_future<>();
    }).get();
    f.get();
    BOOST_REQUIRE_EQUAL(reports, 0);
}


text:
using Duality;
using static MFEP.Duality.Plugins.Animation.Utils;

namespace MFEP.Duality.Plugins.Animation.AnimPieces
{
	/// <summary>
	///     Moves the animated GameObject along a preinitialized path. The path consists of the segments between the
	///     PathVertices.
	/// </summary>
	public class PathFollowMovement : IAnimPiece
	{
		private Vector2 lastPos;

		private RawList<Vector2> pathVertices;
		private Segment[] segments;

		/// <summary>
		///     MUST BE DECLARED. The local coordinates of the path the animation will follow.
		///     Default is null
		/// </summary>
		public Vector2[] PathVertices { get; set; }

		/// <summary>
		///     If set to false, running every segment takes the same time, the segments' length does not count. Otherwise, the
		///     speeed will be constant.
		///     Default is true
		/// </summary>
		public bool ConstantVelocity { get; set; } = true;

		/// <summary>
		///     Wheter the movement is combineable with other movement. Even if false, the movement takes place in local space.
		///     Default is true
		/// </summary>
		public bool Relative { get; set; } = true;

		/// <summary>
		///     If set to true, the algorithm automaticallt generates one more segment between the first and last vertex.
		///     Default is false
		/// </summary>
		public bool Closed { get; set; } = false;

		/// <summary>
		///     TODO
		/// </summary>
		public SignalGen OverSpeedGen { get; set; } = Unity;

		/// <summary>
		///     TODO
		/// </summary>
		public SignalGen SegmentSpeedGen { get; set; } = Unity;

		public void Tick (float pc, GameObject gameObject)
		{
			pc = OverSpeedGen (pc);
			foreach (var currSegment in segments) {
				if (!(pc < currSegment.EndPercent)) continue;
				var currPercent = (pc - currSegment.StartPercent) / (currSegment.EndPercent - currSegment.StartPercent);
				currPercent = SegmentSpeedGen (currPercent);
				var pos = Vector2.Lerp (currSegment.StartPos, currSegment.EndPos, currPercent);
				if (Relative) {
					gameObject.Transform.MoveBy (pos - lastPos);
					lastPos = pos;
				} else {
					gameObject.Transform.MoveTo (pos);
				}
				break;
			}
		}

		public void Initialize ()
		{
			if (PathVertices == null) {
				Log.Core.WriteError ("PathVertices should not be null!");
				return;
			}
			pathVertices = new RawList<Vector2> (PathVertices);
			if (Closed) Close ();
			CalculateSegments ();
		}

		private void CalculateSegments ()
		{
			segments = new Segment[pathVertices.Count - 1];
			var totalLength = CalculateTotalLength (pathVertices);
			var accSegmentLength = 0.0f;

			for (var index = 0; index < segments.Length; index++) {
				var beginPos = pathVertices[index];
				var endPos = pathVertices[index + 1];

				var currentSegmentLength = ConstantVelocity
					? (beginPos - endPos).Length / totalLength
					: 1.0f / segments.Length;

				segments[index] = new Segment
				{
					StartPercent = accSegmentLength,
					EndPercent = accSegmentLength + currentSegmentLength,
					StartPos = beginPos,
					EndPos = endPos
				};

				accSegmentLength += currentSegmentLength;
			}
		}

		private void Close ()
		{
			if (pathVertices[0] != pathVertices[pathVertices.Count - 1]) pathVertices.Add (pathVertices[0]);
		}

		private static float CalculateTotalLength (RawList<Vector2> vertices)
		{
			var length = 0.0f;
			for (var index = 0; index < vertices.Count - 1; ++index) length += (vertices[index] - vertices[index + 1]).Length;
			return length;
		}

		private struct Segment
		{
			public float StartPercent { get; set; }
			public Vector2 StartPos { get; set; }
			public float EndPercent { get; set; }
			public Vector2 EndPos { get; set; }
		}
	}
}


text:
using Orchard.DependencyInjection;
using Orchard.DisplayManagement.Handlers;
using Orchard.DisplayManagement.Views;
using System.Threading.Tasks;

namespace Orchard.ContentManagement.Display.ContentDisplay
{
    public interface IContentFieldDisplayDriver : IDependency
    {
        Task<IDisplayResult> BuildDisplayAsync(string fieldName, ContentPart contentPart, BuildDisplayContext context);
        Task<IDisplayResult> BuildEditorAsync(string fieldName, ContentPart contentPart, BuildEditorContext context);
        Task<IDisplayResult> UpdateEditorAsync(string fieldName, ContentPart contentPart, UpdateEditorContext context);
    }
}


text:
package org.elasticsearch.xpack.sql.session;

import org.elasticsearch.action.ActionListener;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.io.stream.NamedWriteable;
import org.elasticsearch.common.io.stream.NamedWriteableRegistry;

/**
 * Information required to access the next page of response.
 */
public interface Cursor extends NamedWriteable {

    class Page {
        private final RowSet rowSet;
        private final Cursor next;

        public Page(RowSet rowSet, Cursor next) {
            this.rowSet = rowSet;
            this.next = next;
        }

        public RowSet rowSet() {
            return rowSet;
        }

        public Cursor next() {
            return next;
        }

        public static Page last(RowSet rowSet) {
            return new Page(rowSet, EMPTY);
        }
    }

    Cursor EMPTY = EmptyCursor.INSTANCE;

    /**
     * Request the next page of data.
     */
    void nextPage(Configuration cfg, Client client, NamedWriteableRegistry registry, ActionListener<Page> listener);

    /**
     *  Cleans the resources associated with the cursor
     */
    void clear(Configuration cfg, Client client, ActionListener<Boolean> listener);
}


text:
<?php

/**
 * @category   Zend
 * @package    Zend_Application
 * @subpackage Resource
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Application_Resource_UserAgent extends Zend_Application_Resource_ResourceAbstract
{
    /**
     * @var Zend_Http_UserAgent
     */
	protected $_userAgent;

    /**
     * Intialize resource
     *
     * @return Zend_Http_UserAgent
     */
    public function init()
    {
		$userAgent = $this->getUserAgent();

        // Optionally seed the UserAgent view helper
        $bootstrap = $this->getBootstrap();
        if ($bootstrap->hasResource('view') || $bootstrap->hasPluginResource('view')) {
            $bootstrap->bootstrap('view');
            $view = $bootstrap->getResource('view');
            if (null !== $view) {
                $view->userAgent($userAgent);
            }
        }

        return $userAgent;
	}

    /**
     * Get UserAgent instance
     *
     * @return Zend_Http_UserAgent
     */
    public function getUserAgent()
    {
		if (null === $this->_userAgent) {
			$options = $this->getOptions();
			$this->_userAgent = new Zend_Http_UserAgent($options);
		}

		return $this->_userAgent;
	}
}


text:
protos=${GOPATH-$HOME/go}/src/github.com/dgraph-io/dgraph/protos
pushd $protos > /dev/null
protoc --gofast_out=plugins=grpc:. -I=. *.proto


text:
// Copyright (c) 2007-2017 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Game.Modes.Objects.Drawables;
using osu.Game.Modes.Osu.Objects.Drawables;

namespace osu.Game.Modes.Osu
{
    class OsuScoreProcessor : ScoreProcessor
    {
        public OsuScoreProcessor(int hitObjectCount)
            : base(hitObjectCount)
        {
            Health.Value = 1;
            Accuracy.Value = 1;
        }

        protected override void UpdateCalculations(JudgementInfo judgement)
        {
            if (judgement != null)
            {
                switch (judgement.Result)
                {
                    case HitResult.Hit:
                        Combo.Value++;
                        Health.Value += 0.1f;
                        break;
                    case HitResult.Miss:
                        Combo.Value = 0;
                        Health.Value -= 0.2f;
                        break;
                }
            }

            int score = 0;
            int maxScore = 0;

            foreach (OsuJudgementInfo j in Judgements)
            {
                score += j.ScoreValue;
                maxScore += j.MaxScoreValue;
            }

            TotalScore.Value = score;
            Accuracy.Value = (double)score / maxScore;
        }
    }
}


text:
require 'rails_helper'

RSpec.describe Spree::Promotion::Rules::Taxon, type: :model do
  let(:taxon)   { create :taxon, name: 'first' }
  let(:taxon2)  { create :taxon, name: 'second' }
  let(:order)   { create :order_with_line_items }
  let(:product) { order.products.first }

  let(:rule) do
    Spree::Promotion::Rules::Taxon.create!(promotion: create(:promotion))
  end

  context '#eligible?(order)' do
    context 'with any match policy' do
      before do
        rule.update!(preferred_match_policy: 'any')
      end

      it 'is eligible if order does have any prefered taxon' do
        product.taxons << taxon
        rule.taxons << taxon
        expect(rule).to be_eligible(order)
      end

      context 'when order contains items from different taxons' do
        before do
          product.taxons << taxon
          rule.taxons << taxon
        end

        it 'should act on a product within the eligible taxon' do
          expect(rule).to be_actionable(order.line_items.last)
        end

        it 'should not act on a product in another taxon' do
          order.line_items << create(:line_item, product: create(:product, taxons: [taxon2]))
          expect(rule).not_to be_actionable(order.line_items.last)
        end
      end

      context "when order does not have any prefered taxon" do
        before { rule.taxons << taxon2 }
        it { expect(rule).not_to be_eligible(order) }
        it "sets an error message" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.full_messages.first).
            to eq "You need to add a product from an applicable category before applying this coupon code."
        end
        it "sets an error code" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.details[:base].first[:error_code]).
            to eq :no_matching_taxons
        end
      end

      context 'when a product has a taxon child of a taxon rule' do
        before do
          taxon.children << taxon2
          product.taxons << taxon2
          rule.taxons << taxon
        end

        it{ expect(rule).to be_eligible(order) }
      end
    end

    context 'with all match policy' do
      before do
        rule.update!(preferred_match_policy: 'all')
      end

      it 'is eligible order has all prefered taxons' do
        product.taxons << taxon2
        order.products.last.taxons << taxon

        rule.taxons = [taxon, taxon2]

        expect(rule).to be_eligible(order)
      end

      context "when order does not have all prefered taxons" do
        before { rule.taxons << taxon }
        it { expect(rule).not_to be_eligible(order) }
        it "sets an error message" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.full_messages.first).
            to eq "You need to add a product from all applicable categories before applying this coupon code."
        end
        it "sets an error code" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.details[:base].first[:error_code]).
            to eq :missing_taxon
        end
      end

      context 'when a product has a taxon child of a taxon rule' do
        let(:taxon3) { create :taxon }

        before do
          taxon.children << taxon2
          taxon.save!
          taxon.reload

          product.taxons = [taxon2, taxon3]
          rule.taxons = [taxon, taxon3]
        end

        it { expect(rule).to be_eligible(order) }
      end
    end

    context 'with none match policy' do
      before do
        rule.preferred_match_policy = 'none'
      end

      context "none of the order's products are in listed taxon" do
        before { rule.taxons << taxon2 }
        it { expect(rule).to be_eligible(order) }
      end

      context "one of the order's products is in a listed taxon" do
        before do
          order.products.first.taxons << taxon
          rule.taxons << taxon
        end
        it "should not be eligible" do
          expect(rule).not_to be_eligible(order)
        end
        it "sets an error message" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.full_messages.first).
            to eq "Your cart contains a product from an excluded category that prevents this coupon code from being applied."
        end
        it "sets an error code" do
          rule.eligible?(order)
          expect(rule.eligibility_errors.details[:base].first[:error_code]).
            to eq :has_excluded_taxon
        end
      end
    end

    context 'with an invalid match policy' do
      before do
        order.products.first.taxons << taxon
        rule.taxons << taxon
        rule.preferred_match_policy = 'invalid'
        rule.save!(validate: false)
      end

      it 'logs a warning and uses "any" policy' do
        expect(Spree::Deprecation).to(
          receive(:warn).
          with(/has unexpected match policy "invalid"/)
        )

        expect(
          rule.eligible?(order)
        ).to be_truthy
      end
    end
  end

  describe '#actionable?' do
    let(:line_item) { order.line_items.first! }
    let(:order) { create :order_with_line_items }
    let(:taxon) { create :taxon, name: 'first' }

    context 'with an invalid match policy' do
      before do
        rule.preferred_match_policy = 'invalid'
        rule.save!(validate: false)
        line_item.product.taxons << taxon
        rule.taxons << taxon
      end

      it 'logs a warning and uses "any" policy' do
        expect(Spree::Deprecation).to(
          receive(:warn).
          with(/has unexpected match policy "invalid"/)
        )

        expect(
          rule.actionable?(line_item)
        ).to be_truthy
      end
    end

    context 'when a product has a taxon of a taxon rule' do
      before do
        product.taxons << taxon
        rule.taxons << taxon
        rule.save!
      end

      it 'is actionable' do
        expect(rule).to be_actionable(line_item)
      end
    end

    context 'when a product has a taxon child of a taxon rule' do
      before do
        taxon.children << taxon2
        product.taxons << taxon2
        rule.taxons << taxon
        rule.save!
      end

      it 'is actionable' do
        expect(rule).to be_actionable(line_item)
      end
    end

    context 'when a product does not have taxon or child taxon of a taxon rule' do
      before do
        product.taxons << taxon2
        rule.taxons << taxon
        rule.save!
      end

      it 'is not actionable' do
        expect(rule).not_to be_actionable(line_item)
      end
    end
  end
end


text:
FactoryGirl.define do
  factory :group do
    name   "string"
  end
end


text:
package jpl.ch01.ex10;

public class Term {
	public int num;
	public Boolean even;
}


text:
package postgresweb.components.items

import japgolly.scalajs.react._
import japgolly.scalajs.react.vdom.prefix_<^._
import japgolly.scalajs.react.{ReactComponentB, _}
import postgresweb.css.CommonStyles
import postgresweb.models.{JSONQueryFilter, Table, JSONSchema, JSONQuery}
import postgresweb.services.{GlobalState, ModelClient}

import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import scala.util.{Failure, Success}

import scalacss.Defaults._
import scalacss.ScalaCssReact._

object Tables{
  object Style extends StyleSheet.Inline {

    import dsl._
    val table = style(addClassNames("mdl-data-table","mdl-js-data-table","mdl-shadow--2dp"))
    val td = style(addClassNames("mdl-data-table__cell--non-numeric"))

    val select = style(addClassName("select-wrap"))
    val input  = style(
      addClassName("mdl-textfield__input"),
      width(100.px),
      fontSize(11.px),
      display.inherit,
      lineHeight(15.px)
    )

    val selected = styleF.bool( selected => styleS(
      mixinIf(selected)(
        backgroundColor(c"#C5CAE9")
      )
    )
    )
  }
}

case class Tables(model:String) {

  case class State(table:Table,page:Int,selectedRow:Vector[(String,String)],query:JSONQuery)

  class Backend(scope:BackendScope[Unit,State]) {

    val client = ModelClient(model)

    def load(jq: JSONQuery):Future[Table] = {
      println("load")
      client.Helpers.filter2table(jq).map { table =>
          println("laoded")
          scope.modState(_.copy(table = table)).runNow()
          table
      }
    }

    load(JSONQuery.baseFilter)

    /**
      * When a row is selected set the global state with the id of the selected row
      * and set the component state
      *
      * @param headers table headers
      * @param row selected row
      * @return A callback that do the action
      */
    def selectRow(headers: Vector[String], row: Vector[String]):Callback = {
      GlobalState.selectedId = row.headOption
      for{
        _ <- Callback.log("Selected row: " + row)
        result <- scope.modState(_.copy(selectedRow = headers.zip(row)))
      } yield result
    }

    /**
      * Helpler method to generate the options for the filter field according to the type of the field
      *
      * @param `type` type of the field (you can use JSONSchema::typeOfTitle to retrive it
      * @return A list of options according to the type
      */
    def filterOption(`type`:String):Seq[TagMod] = `type` match {
      case "string" => Seq(
        <.option(^.value := "=", ^.selected := true,"="),
        <.option(^.value := "like","Like")
      )
      case "number" => Seq(
        <.option(^.value := "=", ^.selected := true,"="),
        <.option(^.value := "<","<"),
        <.option(^.value := ">",">"),
        <.option(^.value := "not","not")
      )
      case _ => {
        println("Type not found: " + `type`)
        Seq(
          <.option(^.value := "=", "=")
        )
      }
    }

    def refresh() = for{
      state <- scope.state
      table <- {
        println("refresh:" + state.query)
        Callback(load(state.query))
      }
    } yield table

    def modOperator(s:State, field:String)(e: ReactEventI):Callback = {
      val operator = e.target.value
      println(operator)
      val value = s.query.filter.lift(field).map(_.value).getOrElse("")
      val newFilter = s.query.filter + (field -> JSONQueryFilter(value,Some(operator)))
      val newQuery = s.query.copy(filter = newFilter)
      scope.modState(_.copy(query = newQuery)) >>
        Callback.log("State operator for " + field + "changed") >>
        Callback(load(newQuery))
    }

    def modFilter(s:State, field:String)(e: ReactEventI):Callback = {
      val value = e.target.value
      val operator:Option[String] = s.query.filter.lift(field).flatMap(_.operator)
      val newFilter = if(value.size > 0) {
        s.query.filter + (field -> JSONQueryFilter(value,operator))
      } else {
        println("Remove filter to field" + field)
        s.query.filter - field
      }
      val newQuery = s.query.copy(filter = newFilter)

      println(newQuery)
      scope.modState(_.copy(query = newQuery)) >>
        Callback.log("State filter for " + field + "changed") >>
        Callback(load(newQuery))
    }

    def render(S:State) = {
      import Tables._
      <.div(CommonStyles.row,
        <.div(CommonStyles.fullWidth,
          <.div(CommonStyles.scroll,
            <.table(Style.table,
              <.thead(
                <.tr(
                  S.table.headers.map(title => <.th(Style.td,title))
                )
              ),
              <.tbody(
                <.tr(
                  S.table.headers.map(title => <.td(Style.td,
                    <.input(Style.input,^.onChange ==> modFilter(S,title)), //TODO should not be the title here but the key
                    <.span(Style.select,
                      <.select(
                        ^.onChange ==> modOperator(S,title), //TODO should not be the title here but the key
                        filterOption(S.table.schema.typeOfTitle(title))
                      )
                    )
                  ))
                ),
                S.table.rows.map{row =>
                  <.tr( Style.selected(row == S.selectedRow.map(_._2)),
                    ^.onClick --> selectRow(S.table.headers,row),
                    row.map{ cell =>
                      <.td(Style.td,cell.toString)
                    }
                  )
                }
              )
            )
          )
        )
      )
    }
  }

  val component = ReactComponentB[Unit]("ItemsInfo")
    .initialState(State(Table.empty,1,Vector(),JSONQuery.baseFilter))
    .renderBackend[Backend]
    .buildU

  def apply() = component()
}


text:
import sys

class A(object):
    def simple_print(self):
        print("Function simple_print!")

class AMock(object):
    def mocked_print(self):
        print("Printing Mocked")

class B(object):
    def __init__(self, aobj):
        self.a = aobj

    def print_b(self):
        current_frame = sys._getframe(0)
        import pdb; pdb.set_trace()
        self.a.simple_print()

def main():
    aobj = A()
    aobj.simple_print()

    bobj = B(aobj)
    bobj.print_b()

    mock_obj = AMock()
    aobj.simple_print = mock_obj.mocked_print

    print("Simple print:", aobj.simple_print)

    newobj = B(aobj)
    newobj.print_b()

if __name__ == "__main__":
    main()


text:
require 'spec_helper'

describe 'ChargeBee::InvalidRequestError' do
  let(:invalid_request_json) do
    {
        message:  'id: The value chargebee_account is already present.',
        type: 'invalid_request',
        api_error_code: 'duplicate_entry',
        param: 'id',
        error_code: 'param_not_unique',
        error_msg: 'The value chargebee_account is already present.',
        error_param: 'id',
        http_status_code: 400
    }
  end

  it "provide message from error api response" do
    error = ChargeBee::InvalidRequestError.new(400, invalid_request_json)
    expect(error.message).to eq 'id: The value chargebee_account is already present.'
  end

end


text:
// PacketRouter: proc to handle actions for different known Packet tags
package main

import (
	"github.com/trustmaster/goflow"

//	"log"
)

type PacketRouter struct {
	flow.Component
	In  <-chan *ClientPacket
	Log chan<- *ClientPacket

	world *GameServer
}

func NewPacketRouter(w *GameServer) *PacketRouter {
	pr := new(PacketRouter)

	pr.world = w

	return pr
}

func (pr *PacketRouter) OnIn(p *ClientPacket) {

	defer func() {
		//if err := recover(); err != nil {
		//	log.Println("PacketRouter: OnIn: panic:", err)
		//}
	}()

	// log all packets
	pr.Log <- p

	pr.world.HandlePacket(p)

	/*
		switch p.Tag {
		case "move":
			v := p.Data.(game.Direction)
			log.Printf("PacketRouter: OnIn: %s %s %s", p.Client.Con.RemoteAddr(), p.Tag, v)
		default:
			log.Printf("PacketRouter: OnIn: unknown packet type %s", p.Tag)
		}
	*/
}


text:
package com.intellij.ide.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.application.ex.ApplicationInfoEx;
import com.intellij.openapi.project.DumbAwareAction;
import org.jetbrains.annotations.NotNull;

public class ReportProblemAction extends DumbAwareAction {
  @Override
  public void update(@NotNull AnActionEvent e) {
    ApplicationInfoEx info = ApplicationInfoEx.getInstanceEx();
    e.getPresentation().setEnabledAndVisible(info != null && info.getYoutrackUrl() != null);
  }

  @Override
  public void actionPerformed(@NotNull AnActionEvent e) {
    ApplicationInfoEx appInfo = ApplicationInfoEx.getInstanceEx();
    SendFeedbackAction.doPerformActionImpl(e.getProject(), appInfo.getYoutrackUrl(), SendFeedbackAction.getDescription());
  }
}


text:
import { TypeNode, NamedTypeNode, ListTypeNode, NonNullTypeNode } from "../language/ast";
import { GraphQLType, GraphQLNullableType, GraphQLNamedType, GraphQLList, GraphQLNonNull } from "../type/definition";
import { GraphQLSchema } from "../type/schema";

/**
 * Given a Schema and an AST node describing a type, return a GraphQLType
 * definition which applies to that type. For example, if provided the parsed
 * AST node for `[User]`, a GraphQLList instance will be returned, containing
 * the type called "User" found in the schema. If a type called "User" is not
 * found in the schema, then undefined will be returned.
 */
export function typeFromAST(schema: GraphQLSchema, typeNode: NamedTypeNode): GraphQLNamedType | undefined;

export function typeFromAST(schema: GraphQLSchema, typeNode: ListTypeNode): GraphQLList<any> | undefined;

export function typeFromAST(schema: GraphQLSchema, typeNode: NonNullTypeNode): GraphQLNonNull<any> | undefined;