text:
require 'amiga/cpu'
require 'amiga/memory'
require 'amiga/main'

redpajama_set_name: RedPajamaGithub


text:
package org.apache.hadoop.hdfs;

import java.io.Closeable;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.hdfs.protocol.DatanodeID;
import org.apache.hadoop.hdfs.protocol.ExtendedBlock;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.util.Time;

import com.google.common.collect.LinkedListMultimap;
import com.google.common.util.concurrent.ThreadFactoryBuilder;

/**
 * FileInputStream cache is used to cache FileInputStream objects that we
 * have received from the DataNode.
 */
class FileInputStreamCache {
  private final static Log LOG = LogFactory.getLog(FileInputStreamCache.class);

  /**
   * The executor service that runs the cacheCleaner.  There is only one of
   * these per VM.
   */
  private final static ScheduledThreadPoolExecutor executor
      = new ScheduledThreadPoolExecutor(1, new ThreadFactoryBuilder().
          setDaemon(true).setNameFormat("FileInputStreamCache Cleaner").
          build());

  /**
   * The CacheCleaner for this FileInputStreamCache.  We don't create this
   * and schedule it until it becomes necessary.
   */
  private CacheCleaner cacheCleaner;

  /**
   * Maximum number of entries to allow in the cache.
   */
  private final int maxCacheSize;

  /**
   * The minimum time in milliseconds to preserve an element in the cache.
   */
  private final long expiryTimeMs;

  /**
   * True if the FileInputStreamCache is closed.
   */
  private boolean closed = false;

  /**
   * Cache entries.
   */
  private final LinkedListMultimap<Key, Value> map = LinkedListMultimap.create();

  /**
   * Expiry thread which makes sure that the file descriptors get closed
   * after a while.
   */
  private static class CacheCleaner implements Runnable, Closeable {
    private WeakReference<FileInputStreamCache> cacheRef;
    private ScheduledFuture<?> future;

    CacheCleaner(FileInputStreamCache cache) {
      this.cacheRef = new WeakReference<FileInputStreamCache>(cache);
    }

    @Override
    public void run() {
      FileInputStreamCache cache = cacheRef.get();
      if (cache == null) return;
      synchronized(cache) {
        if (cache.closed) return;
        long curTime = Time.monotonicNow();
        for (Iterator<Entry<Key, Value>> iter =
                  cache.map.entries().iterator(); iter.hasNext();
              iter = cache.map.entries().iterator()) {
          Entry<Key, Value> entry = iter.next();
          if (entry.getValue().getTime() + cache.expiryTimeMs >= curTime) {
            break;
          }
          entry.getValue().close();
          iter.remove();
        }
      }
    }

    @Override
    public void close() throws IOException {
      if (future != null) {
        future.cancel(false);
      }
    }

    public void setFuture(ScheduledFuture<?> future) {
      this.future = future;
    }
  }

  /**
   * The key identifying a FileInputStream array.
   */
  static class Key {
    private final DatanodeID datanodeID;
    private final ExtendedBlock block;

    public Key(DatanodeID datanodeID, ExtendedBlock block) {
      this.datanodeID = datanodeID;
      this.block = block;
    }

    @Override
    public boolean equals(Object other) {
      if (!(other instanceof FileInputStreamCache.Key)) {
        return false;
      }
      FileInputStreamCache.Key otherKey = (FileInputStreamCache.Key)other;
      return (block.equals(otherKey.block) &&
          (block.getGenerationStamp() == otherKey.block.getGenerationStamp()) &&
          datanodeID.equals(otherKey.datanodeID));
    }

    @Override
    public int hashCode() {
      return block.hashCode();
    }
  }

  /**
   * The value containing a FileInputStream array and the time it was added to
   * the cache.
   */
  static class Value {
    private final FileInputStream fis[];
    private final long time;

    public Value (FileInputStream fis[]) {
      this.fis = fis;
      this.time = Time.monotonicNow();
    }

    public FileInputStream[] getFileInputStreams() {
      return fis;
    }

    public long getTime() {
      return time;
    }

    public void close() {
      IOUtils.cleanup(LOG, fis);
    }
  }

  /**
   * Create a new FileInputStream
   *
   * @param maxCacheSize         The maximum number of elements to allow in
   *                             the cache.
   * @param expiryTimeMs         The minimum time in milliseconds to preserve
   *                             elements in the cache.
   */
  public FileInputStreamCache(int maxCacheSize, long expiryTimeMs) {
    this.maxCacheSize = maxCacheSize;
    this.expiryTimeMs = expiryTimeMs;
  }

  /**
   * Put an array of FileInputStream objects into the cache.
   *
   * @param datanodeID          The DatanodeID to store the streams under.
   * @param block               The Block to store the streams under.
   * @param fis                 The streams.
   */
  public void put(DatanodeID datanodeID, ExtendedBlock block,
      FileInputStream fis[]) {
    boolean inserted = false;
    try {
      synchronized(this) {
        if (closed) return;
        if (map.size() + 1 > maxCacheSize) {
          Iterator<Entry<Key, Value>> iter = map.entries().iterator();
          if (!iter.hasNext()) return;
          Entry<Key, Value> entry = iter.next();
          entry.getValue().close();
          iter.remove();
        }
        if (cacheCleaner == null) {
          cacheCleaner = new CacheCleaner(this);
          ScheduledFuture<?> future =
              executor.scheduleAtFixedRate(cacheCleaner, expiryTimeMs, expiryTimeMs,
                  TimeUnit.MILLISECONDS);
          cacheCleaner.setFuture(future);
        }
        map.put(new Key(datanodeID, block), new Value(fis));
        inserted = true;
      }
    } finally {
      if (!inserted) {
        IOUtils.cleanup(LOG, fis);
      }
    }
  }

  /**
   * Find and remove an array of FileInputStream objects from the cache.
   *
   * @param datanodeID          The DatanodeID to search for.
   * @param block               The Block to search for.
   *
   * @return                    null if no streams can be found; the
   *                            array otherwise.  If this is non-null, the
   *                            array will have been removed from the cache.
   */
  public synchronized FileInputStream[] get(DatanodeID datanodeID,
      ExtendedBlock block) {
    Key key = new Key(datanodeID, block);
    List<Value> ret = map.get(key);
    if (ret.isEmpty()) return null;
    Value val = ret.get(0);
    map.remove(key, val);
    return val.getFileInputStreams();
  }

  /**
   * Close the cache and free all associated resources.
   */
  public synchronized void close() {
    if (closed) return;
    closed = true;
    IOUtils.cleanup(LOG, cacheCleaner);
    for (Iterator<Entry<Key, Value>> iter = map.entries().iterator();
          iter.hasNext();) {
      Entry<Key, Value> entry = iter.next();
      entry.getValue().close();
      iter.remove();
    }
  }

  public synchronized String toString() {
    StringBuilder bld = new StringBuilder();
    bld.append("FileInputStreamCache(");
    String prefix = "";
    for (Entry<Key, Value> entry : map.entries()) {
      bld.append(prefix);
      bld.append(entry.getKey());
      prefix = ", ";
    }
    bld.append(")");
    return bld.toString();
  }

  public long getExpiryTimeMs() {
    return expiryTimeMs;
  }

  public int getMaxCacheSize() {
    return maxCacheSize;
  }
}


text:
namespace content {

namespace {

using webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl;

static ImageTransportFactoryAndroid* g_factory = NULL;

class DirectGLImageTransportFactory : public ImageTransportFactoryAndroid {
 public:
  DirectGLImageTransportFactory();
  virtual ~DirectGLImageTransportFactory();

  virtual uint32_t InsertSyncPoint() OVERRIDE { return 0; }
  virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE {}
  virtual uint32_t CreateTexture() OVERRIDE {
    return context_->createTexture();
  }
  virtual void DeleteTexture(uint32_t id) OVERRIDE {
    context_->deleteTexture(id);
  }
  virtual void AcquireTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
  virtual void ReleaseTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE {}
  virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
    return context_.get();
  }
  virtual GLHelper* GetGLHelper() OVERRIDE { return NULL; }

 private:
  scoped_ptr<WebGraphicsContext3DInProcessCommandBufferImpl> context_;

  DISALLOW_COPY_AND_ASSIGN(DirectGLImageTransportFactory);
};

DirectGLImageTransportFactory::DirectGLImageTransportFactory() {
  WebKit::WebGraphicsContext3D::Attributes attrs;
  attrs.shareResources = true;
  attrs.noAutomaticFlushes = true;
  context_.reset(webkit::gpu::WebGraphicsContext3DInProcessCommandBufferImpl::
                     CreateViewContext(attrs, NULL));
  if (context_->makeContextCurrent())
    context_->pushGroupMarkerEXT(
        base::StringPrintf("DirectGLImageTransportFactory-%p", this).c_str());
}

DirectGLImageTransportFactory::~DirectGLImageTransportFactory() {
}

class CmdBufferImageTransportFactory : public ImageTransportFactoryAndroid {
 public:
  CmdBufferImageTransportFactory();
  virtual ~CmdBufferImageTransportFactory();

  virtual uint32_t InsertSyncPoint() OVERRIDE;
  virtual void WaitSyncPoint(uint32_t sync_point) OVERRIDE;
  virtual uint32_t CreateTexture() OVERRIDE;
  virtual void DeleteTexture(uint32_t id) OVERRIDE;
  virtual void AcquireTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
  virtual void ReleaseTexture(
      uint32 texture_id, const signed char* mailbox_name) OVERRIDE;
  virtual WebKit::WebGraphicsContext3D* GetContext3D() OVERRIDE {
    return context_.get();
  }
  virtual GLHelper* GetGLHelper() OVERRIDE;

 private:
  scoped_ptr<WebGraphicsContext3DCommandBufferImpl> context_;
  scoped_ptr<GLHelper> gl_helper_;

  DISALLOW_COPY_AND_ASSIGN(CmdBufferImageTransportFactory);
};

CmdBufferImageTransportFactory::CmdBufferImageTransportFactory() {
  WebKit::WebGraphicsContext3D::Attributes attrs;
  attrs.shareResources = true;
  GpuChannelHostFactory* factory = BrowserGpuChannelHostFactory::instance();
  GURL url("chrome://gpu/ImageTransportFactoryAndroid");
  base::WeakPtr<WebGraphicsContext3DSwapBuffersClient> swap_client;
  context_.reset(new WebGraphicsContext3DCommandBufferImpl(0, // offscreen
                                                           url,
                                                           factory,
                                                           swap_client));
  context_->InitializeWithDefaultBufferSizes(
      attrs,
      false,
      CAUSE_FOR_GPU_LAUNCH_WEBGRAPHICSCONTEXT3DCOMMANDBUFFERIMPL_INITIALIZE);

  if (context_->makeContextCurrent())
    context_->pushGroupMarkerEXT(
        base::StringPrintf("CmdBufferImageTransportFactory-%p", this).c_str());
}

CmdBufferImageTransportFactory::~CmdBufferImageTransportFactory() {
}

uint32_t CmdBufferImageTransportFactory::InsertSyncPoint() {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return 0;
  }
  return context_->insertSyncPoint();
}

void CmdBufferImageTransportFactory::WaitSyncPoint(uint32_t sync_point) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->waitSyncPoint(sync_point);
}

uint32_t CmdBufferImageTransportFactory::CreateTexture() {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return false;
  }
  return context_->createTexture();
}

void CmdBufferImageTransportFactory::DeleteTexture(uint32_t id) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->deleteTexture(id);
}

void CmdBufferImageTransportFactory::AcquireTexture(
    uint32 texture_id, const signed char* mailbox_name) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->bindTexture(GL_TEXTURE_2D, texture_id);
  context_->consumeTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
  context_->flush();
}

void CmdBufferImageTransportFactory::ReleaseTexture(
    uint32 texture_id, const signed char* mailbox_name) {
  if (!context_->makeContextCurrent()) {
    LOG(ERROR) << "Failed to make helper context current.";
    return;
  }
  context_->bindTexture(GL_TEXTURE_2D, texture_id);
  context_->produceTextureCHROMIUM(GL_TEXTURE_2D, mailbox_name);
}

GLHelper* CmdBufferImageTransportFactory::GetGLHelper() {
  if (!gl_helper_)
    gl_helper_.reset(new GLHelper(context_.get()));

  return gl_helper_.get();
}

}  // anonymous namespace

// static
ImageTransportFactoryAndroid* ImageTransportFactoryAndroid::GetInstance() {
  if (!g_factory) {
    if (CompositorImpl::UsesDirectGL())
      g_factory = new DirectGLImageTransportFactory();
    else
      g_factory = new CmdBufferImageTransportFactory();
  }

  return g_factory;
}

ImageTransportFactoryAndroid::ImageTransportFactoryAndroid() {
}

ImageTransportFactoryAndroid::~ImageTransportFactoryAndroid() {
}

} // namespace content


text:
from spectacles.functionaltest import FunctionalTestCase
from spectacles.yamldriver import YAMLDriver
from splinter import Browser
import unittest

class GoogleTestCase(FunctionalTestCase):

    def setUp(self):

        self.b = Browser()
        self.yaml_driver = YAMLDriver(self, self.b)

    def test_run_all_yaml_tests(self):
    	self.yaml_driver.run_many("./e2etests/yaml/spec_search*.yml")
    	#self.yaml_driver.run_many("./e2etests/yaml/spec_example_with_include.yml")
        pass

    @unittest.skip("..")
    def test_sales_tookkit(self):
    	self.yaml_driver.run_many("./e2etests/yaml/stk_*.yml")
    	#self.yaml_driver.run_many("./e2etests/yaml/include_add_vpn_from_dashboard.yml")
    	pass

    def tearDown(self):
        self.b.quit()


text:
	#define CHUNKCONTROLLER_H__

	#include <craft/platformSpecification.hpp>
	#include <craft/segment.hpp>
	#include <craft/chunk.hpp>
	#include <craft/shaderVoxel.hpp>
	#include <craft/character.hpp>
	#include <craft/octreeNode.hpp>

	#include <vector>

	class chunkController
	{
		std::vector< std::vector<chunk*> > chunk_list;
		float data_buffer[16][16][16];
		int flag;

		octreeNode* traverseTree (int, int, int, int);
		void dataConstructor (int, int, std::vector< std::vector<chunk*> >);
		void sourceTree (octreeNode*, int, int, int, int, int*, segment*);
		void bufferConstructor (int, int, std::vector< std::vector<chunk*> >);

		public:
			chunkController ();
			chunkController (character*);
			~chunkController ();
			void updateSegFlag (character*);
			void updateData (character*);
			void updateBuffer ();
			void render (character*, shaderVoxel*);
			void setFlag (int);
			int getFlag ();
	};

#endif


text:
<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android"
    android:color="#005f91">
    <item>
        <shape android:shape="oval">
            <solid android:color="#00a6ff"/>
        </shape>
    </item>
</ripple>


text:
<!DOCTYPE html>

    <title>Researching the voluntary sector » Timescapes: An ESRC Qualitative Longitudinal Initiative</title>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link rel="Shortcut Icon" type="image/ico" href="http://www.leeds.ac.uk/site/favicon.ico" />

    <link rel="stylesheet" type="text/css" href="../../assets/css/uol.min.css" media="screen" />
    <link rel="stylesheet" type="text/css" href="../../assets/css/timescapes.css" media="screen" />

School of Sociology and Social Policy

Timescapes: An ESRC Qualitative Longitudinal Initiative

Home

About

Research

Events  and Dissemination

Timescapes Archive

Secondary Analysis

Knowledge Bank for QL Research

You are here:

Events  and Dissemination »

Seminars »

Researching the voluntary sector

Training Events

Seminars

Timescapes Lunchtime Seminar Series

Young lives and imagined futures

Researching the voluntary sector

Choice and Change: A Qualitative Longitudinal Study

'Rescue and Repair':  Grandparents with Parental Care of Their Grandchildren

Conferences and Workshops

Timescapes Memoryshare

Exhibitions

Resources

Speaker abstracts and biographies [PDF: 140KB]

Full programme  [PDF:100KB]

Twitter transcript: a full transcription of the seminar  [PDF: 96KB]

              Telling stories about favourite charities: an academic conference prompted one blogger to consider how we experience charities, by Roxanne
              Persaud. The Guardian: 16 March 2011

Timescapes Methods Guide no. 15: Macmillan, R. et al (2012): 'What Happens Next?' Researching the Third Sector Using Qualitative Longitudinal Methods [PDF
              1,058 KB]

Researching the voluntary sector

There is a growing interest in the use of qualitative longitudinal and life history methods in third sector research. Engaging qualitatively with time enables a more finely grained understanding of the dynamics of third sector organisations: their
          histories, their strategies for the future, and their journeys through a complex and rapidly changing policy landscape.

This seminar on 9 March 2011 brought together a number of funded projects using such methods to produce distinctive forms of knowledge on the third sector.

Speakers included Victoria Bell (Teeside), Sue Bond (Edinburgh Napier), Irene Hardill (Northumberland), David Lewis (LSE), and Rob Macmillan (Birmingham) and Zoe Munby (Home Start).

The event was hosted by the Timescapes Qualitative Longitudinal Initiative, in collaboration with the Third Sector Research Centre, with funding from the Economic and Social Research Council.

Partners

Economic & Social Research Council (ESRC)

London South Bank University

Cardiff University

The University of Edinburgh

The Open University

UK Data Archive

Copyright

Accessibility

Privacy

Freedom of Information

© Copyright Leeds 2011


text:
package eu.hlavki.identity.services.config;

import java.util.Optional;

public interface AppConfiguration {

    Optional<String> getExternalAccountsGroup();

    void setExternalAccountsGroup(String groupName);
}


text: AnyPay Xamarin Android App


text:
namespace ThingM.Blink1.ColorProcessor
{
    using System;
    using System.Globalization;
    using System.Text.RegularExpressions;

    /// <summary>
    ///     HTML Color in a hexadecimal (#FFFFFF) format.
    /// </summary>
    public class HtmlHexadecimal : IColorProcessor
    {
        #region Fields

        /// <summary>
        ///     The HTML color in a hexadecimal (#FFFFFF) format.
        /// </summary>
        private string htmlColor;

        #endregion

        #region Constructors and Destructors

        /// <summary>
        /// Initializes a new instance of the <see cref="HtmlHexadecimal"/> class.
        /// </summary>
        /// <param name="htmlColor">
        /// The HTML color in a hexadecimal (#FFFFFF) format.
        /// </param>
        public HtmlHexadecimal(string htmlColor)
        {
            this.HtmlColor = htmlColor;
        }

        #endregion

        #region Public Properties

        /// <summary>
        ///     Gets or sets the HTML color in a hexadecimal (#FFFFFF) format.
        /// </summary>
        public string HtmlColor
        {
            get
            {
                return this.htmlColor;
            }

            set
            {
                if (this.IsFormatValid(value) == false)
                {
                    throw new ArgumentException("Color format is invalid. Valid format is #FFFFFF.");
                }

                this.htmlColor = value;
            }
        }

        #endregion

        #region Public Methods and Operators

        /// <summary>
        ///     Convert the color to the RGB format.
        /// </summary>
        /// <returns>
        ///     The color in a RGB format.
        /// </returns>
        public Rgb ToRgb()
        {
            ushort red = ushort.Parse(this.htmlColor.Substring(1, 2), NumberStyles.AllowHexSpecifier);
            ushort green = ushort.Parse(this.htmlColor.Substring(3, 2), NumberStyles.AllowHexSpecifier);
            ushort blue = ushort.Parse(this.htmlColor.Substring(5, 2), NumberStyles.AllowHexSpecifier);

            Rgb rgb = new Rgb(red, green, blue);

            return rgb;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Validate if the string format match the HTML hexadecimal #FFFFFF format.
        /// </summary>
        /// <param name="color">
        /// The HTML color.
        /// </param>
        /// <returns>
        /// True if the format is valid, false otherwise.
        /// </returns>
        private bool IsFormatValid(string color)
        {
            if (string.IsNullOrEmpty(color))
            {
                return false;
            }

            Regex htmlHexColorRegex = new Regex(@"^\#([a-fA-F0-9]{6})$");

            return htmlHexColorRegex.IsMatch(color);
        }

        #endregion
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Spinner
        android:id="@+id/classes_spinner"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="20dp" />

    <Spinner
        android:id="@+id/category_spinner"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_margin="20dp" />
</LinearLayout>


text:
package com.jfixby.scarabei.api.names;

import com.jfixby.scarabei.api.collections.List;

public interface ID {

	public static final String SEPARATOR = ".";

	ID child (String string);

	ID parent ();

	String getLastStep ();

	boolean includes (ID other);

	ID child (ID subpackage);

	List<String> steps ();

	public String toString (String customSeparator);

}


text:
PEGASUS_USING_PEGASUS;
PEGASUS_USING_STD;

#include "UNIX_ElementInConnectorProvider.h"

extern "C"
PEGASUS_EXPORT CIMProvider* PegasusCreateProvider(const String& providerName)
{
	if (String::equalNoCase(providerName, CIMHelper::EmptyString)) return NULL;
	else if (String::equalNoCase(providerName, "UNIX_ElementInConnectorProvider")) return new UNIX_ElementInConnectorProvider();
	return NULL;
}


text:
import * as React from "react";
import { Direction, MenuOffsetData, TooltipAlignment, ReactDivAttr, ForwardRefReturn } from "../../../typings/shared";

// NOTE: The index does not export * on this file because non-default export of Tooltip clashs with Tooltip at the top-level index.
//       You'll need to export types manually in this directory's index file.

type ExcludedAttributes = "onBlur" | "onChange" | "onContextMenu" | "onFocus" | "onMouseOut" | "onMouseOver" | "role";
export type TooltipOnChangeEvent<T extends Element> = React.FocusEvent<T> | React.KeyboardEvent<T> | React.MouseEvent<T>;

export interface TooltipProps extends Omit<ReactDivAttr, ExcludedAttributes> {
    align?: TooltipAlignment | undefined;
    defaultOpen?: boolean | undefined;
    direction?: Direction | undefined;
    focusTrap?: boolean | undefined;
    iconDescription?: string | undefined;
    iconName?: string | undefined;
    menuOffset?:
        MenuOffsetData
        | ((menuBody: HTMLElement, menuDirection: TooltipProps['direction']) => Required<MenuOffsetData> | undefined) | undefined;
    onChange?(event: TooltipOnChangeEvent<HTMLDivElement>, data: { open: boolean }): void; // optional/required depending on static carbon lib config
    open?: boolean | undefined;
    renderIcon?: ForwardRefReturn<unknown, unknown> | undefined;
    selectorPrimaryFocus?: string | undefined;
    showIcon?: boolean | undefined;
    tooltipBodyId?: string | undefined;
    tooltipId?: string | undefined;
    triggerClassName?: string | undefined;
    triggerId?: string | undefined;
    triggerText?: React.ReactNode | undefined;
}

declare class TooltipComponent extends React.Component<TooltipProps> { }
export { TooltipComponent as Tooltip };

declare const Tooltip: ForwardRefReturn<unknown, TooltipProps>;
export default Tooltip;


text:
// This is a part of the Active Template Library.
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Active Template Library Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Active Template Library product.

#ifndef __ATLSMTPUTIL_H__
#define __ATLSMTPUTIL_H__

#pragma once

#if (defined(_WINSOCKAPI_) && !defined(_WINSOCK2API_))
#error <atlsmtputil.h> requires <winsock2.h> -- include <winsock2.h> before you include <windows.h> or <winsock.h>
#endif
#include <winsock2.h>
#include <windows.h>
#include <string.h>
#include <stdlib.h>
#include <tchar.h>
#include <atlstr.h>
#include <winnls.h>
#include <atlspriv.h>

//=======================================================================
//defines for SMTPMail module
//=======================================================================

//If overlapped I/O is desired, need 2.0 or greater
#define ATLSMTP_WSA_VERSION  ATL_WINSOCK_VER

//The maximum number of characters on a SMTP line
#define ATLSMTP_MAX_LINE_LENGTH 1000

#define ATLSMTP_MAX_SERVER_NAME_LENGTH 256

//Encoding schemes
#define ATLSMTP_BASE64_ENCODE 0
#define ATLSMTP_UUENCODE      1
#define ATLSMTP_QP_ENCODE     2

//I/O Defines
#define ATLSMTP_READBUFFER_SIZE        4096
#define ATLSMTP_GET_LINES              100

//Miscellaneous defines
#define ATLSMTP_SEND_FILE   1
#define ATLSMTP_FORMAT_SMTP 8

#define ATLSMTP_RETCODE_LEN 3

#pragma pack(push,_ATL_PACKING)
namespace ATL
{

//=======================================================================
// Miscellaneous Utility Functions
//=======================================================================
//A list of recipients in a string must by separated by one
//of the following characters
inline BOOL AtlSmtpIsRecipientDelimiter(char ch) throw()
{
	return (ch == ',' || ch == ';' || ch == ' ' || ch == '\0');
}

//Send data to hFile and wait for it to finish sending
inline BOOL AtlSmtpSendAndWait(HANDLE hFile, LPCSTR lpData, int nDataLength, LPOVERLAPPED pOverlapped) throw()
{
	ATLASSERT(lpData != NULL);
	ATLENSURE(pOverlapped != NULL);

	DWORD dwWritten = 0, dwErr = 0;
	int nRet = 0, nBufPos = 0;

	//write all the data
	do
	{
		//Write a chunk of data, offsetting the buffer and amount to write by what's already
		//been written
		nRet = WriteFile(hFile, (void*)(lpData+nBufPos), nDataLength-nBufPos, &dwWritten, pOverlapped);
		if (!nRet && (dwErr = GetLastError()) != ERROR_IO_INCOMPLETE && dwErr != ERROR_IO_PENDING)
			return FALSE;

		//Get the result of the write operation (wait for it)
		nRet = GetOverlappedResult(hFile, pOverlapped, &dwWritten, TRUE);
		if (!nRet)
			return FALSE;

		//Need to update offsets when writing to a file
		pOverlapped->Offset += dwWritten;
		nBufPos += dwWritten;

	} while (nBufPos < nDataLength);
	return TRUE;
}

//Read up to nDestLen bytes from hFile, keep reading while there's more data and there's
//room in the buffer
inline BOOL AtlSmtpReadData(__in HANDLE hFile, __out_ecount_part_z(*pnDestLen, *pnDestLen) LPSTR lpData, __inout int* pnDestLen, __in LPOVERLAPPED pOverlapped)
{
	ATLASSERT(lpData != NULL);
	ATLASSERT(pnDestLen != NULL);
	ATLENSURE(pOverlapped != NULL);

	DWORD dwRead = 0, dwErr = 0;
	int nBufPos = 0;
	do
	{
		//REad a chunk of data, offsetting the buffer and amount to read by what's already been read
		int nRet = ReadFile(hFile, (void*)(lpData+nBufPos), (*pnDestLen)-nBufPos, &dwRead, pOverlapped);
		if (!nRet && (dwErr = GetLastError()) != ERROR_MORE_DATA && dwErr != ERROR_IO_PENDING && dwErr != ERROR_IO_INCOMPLETE)
			return FALSE;

		//Get the result of the read operation (wait for it)
		nRet = GetOverlappedResult(hFile, pOverlapped, &dwRead, TRUE);
		if (!nRet)
			return FALSE;

		//Handle offsets when reading from a file
		pOverlapped->Offset += dwRead;
		nBufPos += dwRead;
	} while (nBufPos < *pnDestLen && dwErr == ERROR_MORE_DATA);
	*pnDestLen = nBufPos;
	return TRUE;
}

//Used in sending encoded data
//lpData is the data to be sent now
//lpPrev is a pointer to the buffer that the previous call was made on
//This allows the new buffer (lpData) to be filled while lpPrev is being sent
//If all the data in lpPrev had not finished sending, we complete the send and wait
inline BOOL AtlSmtpSendOverlapped(HANDLE hFile, LPCSTR lpData, int nDataLength, LPCSTR lpPrev, DWORD dwPrevLength, LPOVERLAPPED pOverlapped)
{
	ATLASSERT(lpData != NULL);
	ATLENSURE(pOverlapped != NULL);

	DWORD dwWritten = 0, dwErr = 0, dwBufPos = 0;
	int nRet = 0;

	//Get the results of the previous call (if any)
	if (lpPrev && (!GetOverlappedResult(hFile, pOverlapped, &dwWritten, FALSE) || dwWritten < dwPrevLength))
	{
		//If any error but IO_INCOMPLETE, return failure
		if ((dwErr = GetLastError()) != ERROR_SUCCESS  && dwErr != ERROR_IO_INCOMPLETE && dwErr != ERROR_IO_PENDING)
		{
			return FALSE;
		}
		//Finish writing lpPrev if we need to
		while (dwBufPos < dwPrevLength)
		{
			//Get the result of the previous write (wait for it)
			nRet = GetOverlappedResult(hFile, pOverlapped, &dwWritten, TRUE);
			if (!nRet || (dwBufPos += dwWritten) == dwPrevLength)
			{
				if ((dwErr = GetLastError()) != ERROR_IO_INCOMPLETE && dwErr != ERROR_IO_PENDING)
					break;
			}

			//If we are writing to a file, we need to update the offsets
			pOverlapped->Offset += dwWritten;
			if(dwBufPos>dwPrevLength)
			{
				/* shouldn't happen */
				ATLASSERT(false);
				break;
			}
			nRet = WriteFile(hFile, (void*)(lpPrev+dwBufPos), dwPrevLength-dwBufPos, &dwWritten, pOverlapped);

			//If any error but IO_PENDING and IO_INCOMPLETE, break
			if (!nRet && (dwErr = GetLastError()) != ERROR_IO_PENDING && dwErr != ERROR_IO_INCOMPLETE)
				break;
		}
		if (dwBufPos < dwPrevLength)
			return FALSE;
	}

	//Now that all the previous data has been sent, start sending the current data
	nRet = WriteFile(hFile, (void*)lpData, nDataLength, &dwWritten, pOverlapped);
	GetOverlappedResult(hFile, pOverlapped, &dwWritten, FALSE);

	pOverlapped->Offset += dwWritten;

	//If any error but IO_PENDING
	if (!nRet && (dwErr = GetLastError()) != ERROR_IO_PENDING && dwErr != ERROR_IO_INCOMPLETE)
		return FALSE;
	return TRUE;
}

//Send a SMTP command and read the response
//return TRUE if it matches szResponse, FALSE otherwise
inline BOOL AtlSmtpSendAndCheck(__in HANDLE hFile, __in LPCSTR lpData, __in int nDataLength, __out_ecount_part(nMaxResponseLength, *pnResponseLength) LPSTR lpResponse, __out int* pnResponseLength, __in int nMaxResponseLength,
							 __in_z LPCSTR szResponse, __in LPOVERLAPPED pOverlapped) throw()
{
	ATLASSERT(lpData != NULL);
	ATLASSERT(lpResponse != NULL);
	ATLASSERT(pnResponseLength != NULL);

	BOOL bRet = AtlSmtpSendAndWait(hFile, lpData, nDataLength, pOverlapped);
	if (bRet)
	{
		*pnResponseLength = nMaxResponseLength;
		bRet = AtlSmtpReadData(hFile, lpResponse, pnResponseLength, pOverlapped);
	}
	if (!bRet || strncmp((char*)lpResponse, szResponse, ATLSMTP_RETCODE_LEN))
		return FALSE;
	return TRUE;
}

} // namespace ATL
#pragma pack(pop)

#endif // __ATLSMTPUTIL_H__


text:
import { Contact, ContactType } from "../../server/schema/Contact";

const sponsor: Contact = {
  name: "Solita",
  about: "Solita is a digital business company",
  image: {
    url: "sponsors/solita.svg",
  },
  social: {
    homepage: "https://www.solita.fi/en/",
    facebook: "Solita",
    github: "solita",
    linkedin: "company/solita-oy",
    instagram: "solitaoy",
    twitter: "SolitaOy",
    youtube: "SolitaOy",
  },
  location: {
    country: {
      name: "Finland",
      code: "FI",
    },
    city: "Helsinki",
  },
  type: [ContactType.SPONSOR],
};

export default sponsor;


text:
<?xml version="1.0"?>
<package>
  <name>md49_messages</name>
  <version>0.1.0</version>
  <description>The md49_messages package</description>

  <author email="scheik.todeswache@googlemail.com">Fabian Prinzing</author>

  <maintainer email="scheik.todeswache@googlemail.com">Fabian Prinzing</maintainer>

  <license>BSD</license>

  <url type="website">http://www.the-starbearer.de</url>
  <url type="bugtracker">https://github.com/scheik/ROS-Workspace/issues</url>
  <url type="repository">https://github.com/scheik/ROS-Workspace</url>

  <buildtool_depend>catkin</buildtool_depend>
  <build_depend>message_generation</build_depend>
  <build_depend>std_msgs</build_depend>
  <run_depend>message_runtime</run_depend>
  <run_depend>std_msgs</run_depend>

</package>


text:
import os
from simplecrypt import encrypt, decrypt

class EncryptedFile(object):
    def __init__(self, path, password):
        self.__path = path
        self.__password = password

    def write(self, content, mode="w"):
        encrypted = encrypt(self.__password, content)
        with open(self.__path, mode) as fd:
            fd.write(encrypted)

    def read(self):
        self.ensure_exists()
        self.__ensure_data_header_exists()
        with open(self.__path, "r") as fd:
            content = fd.read()
            return decrypt(self.__password, content)

    def is_empty(self):
        return os.path.getsize(self.__path) == 0

    def ensure_exists(self):
        if not os.path.exists(self.__path):
            raise IOError("File doesn't exist.")

    def __ensure_data_header_exists(self):
        if self.is_empty():
            self.write("")


text:
<?xml version="1.0" encoding="UTF-8"?>

<!--

 Copyright 2003 - 2009 The eFaps Team

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

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

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.

 Author:          The eFaps Team
 Revision:        $Rev$
 Last Changed:    $Date$
 Last Changed By: $Author$

-->

<datamodel-statusgroup  xmlns="http://www.efaps.org/xsd"
                 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                 xsi:schemaLocation="http://www.efaps.org/xsd http://www.efaps.org/xsd/eFaps_1.0.xsd">
  <uuid>a311a6be-fc3c-48c7-a4b9-4b389c996f0a</uuid>
  <file-application>eFapsApp-Sales</file-application>
  <file-revision>$Rev$</file-revision>

  <definition>
    <version-expression>(version==latest)</version-expression>
    <name>Sales_DocumentStatus</name>
    <parent>Admin_DataModel_StatusAbstract</parent>
  </definition>

</datamodel-statusgroup>


text: <title>Conway's Game of Life</title>


text:
import unittest

class PersistentList(object):
    def __repr__(self):
        return ''

    def prepend(self, item):
        return ListNode(item, self)

    def head(self):
        pass

    def tail(self):
        return self

    def __eq__(self, other):
        return isinstance(other, self.__class__) \
               and self.head() is None

    def __add__(self, other):
        return other

    def map(self, mapper):
        return self

    def filter(self, predicate):
        return self

    def __iter__(self):
        return ListIter(self)

class ListIter(object):
    def __init__(self, list):
        self._list = list

    def __next__(self):
        item = self._list.head()
        self._list = self._list.tail()
        if item is None:
            raise StopIteration
        else:
            return item

class ListNode(PersistentList):
    def __init__(self, head, tail):
        self._head = head
        self._tail = tail

    def __repr__(self):
        tail_repr = repr(self._tail)
        if tail_repr == '':
            return repr(self._head)
        else:
            return repr(self._head) + ', ' + tail_repr

    def head(self):
        return self._head

    def tail(self):
        return self._tail

    def __eq__(self, other):
        return isinstance(other, self.__class__) \
               and self.head() == other.head() \
               and self.tail() == other.tail()

    def __add__(self, other):
        return (self.tail() + other).prepend(self.head())

    def map(self, mapper):
        return self.tail().map(mapper).prepend(mapper(self.head()))

    def filter(self, predicate):
        if predicate(self.head()):
            return self.tail().filter(predicate).prepend(self.head())
        else:
            return self.tail().filter(predicate)

class PersistentListTest(unittest.TestCase):
    def setUp(self):
        self.empty = PersistentList()

    def testCreateList(self):
        self.assertEqual('', repr(self.empty))

    def testPrependToList(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual('3, 2, 1', repr(nonempty))

    def testHeadOfEmptyList(self):
        self.assertEqual(None, self.empty.head())

    def testHeadOfNonemptyList(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual(3, nonempty.head())

    def testTailOfEmptyList(self):
        self.assertEqual(PersistentList(), self.empty.tail())

    def testTailOfNonemptyList(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)
        self.assertEqual(self.empty.prepend(1).prepend(2), nonempty.tail())

    def testConcatenationOfTwoEmptyLists(self):
        self.assertEqual(self.empty, self.empty + self.empty)

    def testConcatenationOfEmptyAndNonemptyLists(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual(nonempty, self.empty + nonempty)
        self.assertEqual(nonempty, nonempty + self.empty)

    def testConcatenationOfTwoNonemptyLists(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)
        the_other = self.empty.prepend(4).prepend(5).prepend(6)

        self.assertEqual('6, 5, 4, 3, 2, 1', repr(the_other + nonempty))

    def testMapEmptyList(self):
        self.assertEqual(self.empty, self.empty.map(lambda e: e ** 2))

    def testMapNonemptyList(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual(self.empty.prepend(1).prepend(4).prepend(9), nonempty.map(lambda e: e ** 2))

    def testFilterEmptyList(self):
        self.assertEqual(self.empty, self.empty.filter(lambda e: e != 2))

    def testFilterNonemptyList(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual(self.empty.prepend(1).prepend(3), nonempty.filter(lambda e: e != 2))

    def testListIterable(self):
        nonempty = self.empty.prepend(1).prepend(2).prepend(3)

        self.assertEqual([], list(self.empty))
        self.assertEqual([3, 2, 1], list(nonempty))


text:
/*global Promise */
/*eslint-env node */
/*jslint node: true */
"use strict";

module.exports = function (grunt) {

    var _       = require("lodash"),
        build   = require("./build")(grunt),
        common  = require("./lib/common")(grunt),
        exec    = require("child_process").exec,
        fs      = require("fs-extra"),
        glob    = require("glob"),
        https   = require("https"),
        path    = require("path"),
        tar     = require("tar"),
        temp    = require("temp"),
        zlib    = require("zlib");

    temp.track();

    function runNpmInstall(where, callback) {
        grunt.log.writeln("running npm install --production in " + where);
        exec('npm install --production', { cwd: './' + where }, function (err, stdout, stderr) {
            if (err) {
                grunt.log.error(stderr);
            } else {
                grunt.log.writeln(stdout || "finished npm install in " + where);
            }
            return err ? callback(stderr) : callback(null, stdout);
        });
    }

    grunt.registerTask("npm-install", "Install node_modules to the dist folder so it gets bundled with release", function () {
        var npmShrinkwrapJSON = grunt.file.readJSON("npm-shrinkwrap.json");
        common.writeJSON(grunt, "dist/npm-shrinkwrap.json", npmShrinkwrapJSON);

        var packageJSON = grunt.file.readJSON("package.json");
        delete packageJSON.devDependencies;
        delete packageJSON.scripts; // we don't want to run post-install scripts in dist folder
        common.writeJSON(grunt, "dist/package.json", packageJSON);

        var done = this.async();
        runNpmInstall("dist", function (err) {
            return err ? done(false) : done();
        });
    });

    grunt.registerTask("npm-install-src", "Install node_modules to the src folder", function () {
        var done = this.async();
        runNpmInstall("src", function (err) {
            return err ? done(false) : done();
        });
    });

    grunt.registerTask("npm-install-extensions", "Install node_modules for default extensions which have package.json defined", function () {
        var _done = this.async();
        glob("src/extensions/**/package.json", function (err, files) {
            if (err) {
                grunt.log.error(err);
                return _done(false);
            }
            files = files.filter(function (path) {
                return path.indexOf("node_modules") === -1;
            });
            var done = _.after(files.length, _done);
            files.forEach(function (file) {
                runNpmInstall(path.dirname(file), function (err) {
                    return err ? _done(false) : done();
                });
            });
        });
    });

    grunt.registerTask(
        "npm-install-source",
        "Install node_modules for src folder and default extensions which have package.json defined",
        ["npm-install-src", "copy:thirdparty", "npm-install-extensions"]
    );

    function getNodeModulePackageUrl(extensionName) {
        return new Promise(function (resolve, reject) {
            exec("npm view " + extensionName + " dist.tarball", {}, function (err, stdout, stderr) {
                if (err) {
                    grunt.log.error(stderr);
                }
                return err ? reject(stderr) : resolve(stdout.toString("utf8").trim());
            });
        });
    }

    function getTempDirectory(tempName) {
        return new Promise(function (resolve, reject) {
            temp.mkdir(tempName, function(err, dirPath) {
                return err ? reject(err) : resolve(dirPath);
            });
        });
    }

    function downloadUrlToFolder(url, dirPath) {
        return new Promise(function (resolve, reject) {
            grunt.log.writeln(url + " downloading...");
            https.get(url, function (res) {

                if (res.statusCode !== 200) {
                    return reject(new Error("Request failed: " + res.statusCode));
                }

                var unzipStream = zlib.createGunzip();
                res.pipe(unzipStream);

                var extractStream = tar.Extract({ path: dirPath, strip: 0 });
                unzipStream.pipe(extractStream);

                extractStream.on('finish', function() {
                    grunt.log.writeln(url + " successfully downloaded");
                    resolve(path.resolve(dirPath, "package"));
                });

            }).on('error', function(err) {
                reject(err);
            });
        });
    }

    function move(from, to) {
        return new Promise(function (resolve, reject) {
            fs.remove(to, function (err) {
                if (err) {
                    return reject(err);
                }
                fs.move(from, to, function (err) {
                    if (err) {
                        return reject(err);
                    }
                    return resolve();
                });
            });
        });
    }

    function downloadAndInstallExtensionFromNpm(obj) {
        var extensionName = obj.name;
        var extensionVersion = obj.version ? "@" + obj.version : "";
        var data = {};
        return getNodeModulePackageUrl(extensionName + extensionVersion)
            .then(function (urlToDownload) {
                data.urlToDownload = urlToDownload;
                return getTempDirectory(extensionName);
            })
            .then(function (tempDirPath) {
                data.tempDirPath = tempDirPath;
                return downloadUrlToFolder(data.urlToDownload, data.tempDirPath);
            })
            .then(function (extensionPath) {
                var target = path.resolve(__dirname, '..', 'src', 'extensions', 'default', extensionName);
                return move(extensionPath, target);
            });
    }

    grunt.registerTask("npm-download-default-extensions",
                       "Downloads extensions from npm and puts them to the src/extensions/default folder",
                       function () {

        var packageJSON = grunt.file.readJSON("package.json");
        var extensionsToDownload = Object.keys(packageJSON.defaultExtensions).map(function (name) {
            return {
                name: name,
                version: packageJSON.defaultExtensions[name]
            };
        });

        var done = this.async();
        Promise.all(extensionsToDownload.map(function (extension) {
            return downloadAndInstallExtensionFromNpm(extension);
        })).then(function () {
            return done();
        }).catch(function (err) {
            grunt.log.error(err);
            return done(false);
        });

    });

};


text:
import { WebGLRenderTarget, WebGLRenderer } from "./three-core";
import { ShaderPass } from "./three-shaderpass";

export class EffectComposer {
    constructor(renderer: WebGLRenderer, renderTarget?: WebGLRenderTarget);

    renderTarget1: WebGLRenderTarget;
    renderTarget2: WebGLRenderTarget;
    writeBuffer: WebGLRenderTarget;
    readBuffer: WebGLRenderTarget;
    passes: any[];
    copyPass: ShaderPass;

    swapBuffers(): void;

    addPass(pass: any): void;

    insertPass(pass: any, index: number): void;

    render(delta?: number): void;

    reset(renderTarget?: WebGLRenderTarget): void;

    setSize(width: number, height: number): void;
}

export class Pass{
    // if set to true, the pass is processed by the composer
	enabled: boolean;

	// if set to true, the pass indicates to swap read and write buffer after rendering
	needsSwap: boolean;

	// if set to true, the pass clears its buffer before rendering
	clear: boolean;

	// if set to true, the result of the pass is rendered to screen
    renderToScreen: boolean;

    setSize(width: number, height:number ): void;

    render(renderer: WebGLRenderer, writeBuffer: WebGLRenderTarget, readBuffer: WebGLRenderTarget, delta: number, maskActive?: boolean): void;

}


text:
Ankita Sastry

Hi, I'm Ankita Sastry, a computer science engineer from PESIT, Bangalore!


text:
class WXDLLIMPEXP_FWD_CORE wxDataObject;
struct wxDataIdToDataObject;

#include "wx/list.h"

WX_DECLARE_LIST(wxDataObject, wxDataObjectList);
WX_DECLARE_LIST(wxDataIdToDataObject, wxDataIdToDataObjectList);

WXDLLIMPEXP_CORE bool wxOpenClipboard();
WXDLLIMPEXP_CORE bool wxClipboardOpen();
WXDLLIMPEXP_CORE bool wxCloseClipboard();
WXDLLIMPEXP_CORE bool wxEmptyClipboard();
WXDLLIMPEXP_CORE bool wxIsClipboardFormatAvailable(wxDataFormat dataFormat);
WXDLLIMPEXP_CORE bool wxSetClipboardData(wxDataFormat dataFormat, wxObject *obj, int width = 0, int height = 0);
WXDLLIMPEXP_CORE wxObject* wxGetClipboardData(wxDataFormat dataFormat, long *len = NULL);
WXDLLIMPEXP_CORE wxDataFormat wxEnumClipboardFormats(wxDataFormat dataFormat);
WXDLLIMPEXP_CORE wxDataFormat wxRegisterClipboardFormat(char *formatName);
WXDLLIMPEXP_CORE bool wxGetClipboardFormatName(wxDataFormat dataFormat, char *formatName, int maxCount);

//-----------------------------------------------------------------------------
// wxClipboard
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxClipboard : public wxClipboardBase
{
public:
    wxClipboard();
    virtual ~wxClipboard();

    // open the clipboard before SetData() and GetData()
    virtual bool Open();

    // close the clipboard after SetData() and GetData()
    virtual void Close();

    // opened?
    virtual bool IsOpened() const { return m_open; }

    // replaces the data on the clipboard with data
    virtual bool SetData( wxDataObject *data );

    // adds data to the clipboard
    virtual bool AddData( wxDataObject *data );

    // format available on the clipboard ?
    virtual bool IsSupported( const wxDataFormat& format );

    // fill data with data on the clipboard (if available)
    virtual bool GetData( wxDataObject& data );

    // clears wxTheClipboard and the system's clipboard if possible
    virtual void Clear();

    // implementation from now on
    bool              m_open;
    wxDataObjectList  m_data;
    wxDataIdToDataObjectList m_idToObject;

private:
    DECLARE_DYNAMIC_CLASS(wxClipboard)
};

#endif // wxUSE_CLIPBOARD

#endif // _WX_CLIPBRD_H_


text:
class Shoes
  module Mock
    class Link
      include Shoes::Mock::CommonMethods

      def initialize(dsl, app, opts = {})
      end
    end
  end
end


text:
const createLogHandler = handlers => message => {
    if (handlers.hasOwnProperty(message.type)) {
        return handlers[message.type](message);
    }

    return handlers['unknown'](message);
};

export const screenLogger = createLogHandler({
    noop: message => createLogHandler({
        'noop-api': ({ api }) => console.log(`api ${api.name.bold} ${'is up to date'.bold.green}`),
        'noop-plugin': ({ plugin }) => console.log(`- plugin ${plugin.name.bold} ${'is up to date'.bold.green}`),
        'noop-global-plugin': ({ plugin }) => console.log(`global plugin ${plugin.name.bold} ${'is up to date'.bold.green}`),
        'noop-consumer': ({ consumer }) => console.log(`consumer ${consumer.username.bold} ${'is up to date'.bold.green}`),
        'noop-credential': ({ credential, credentialIdName }) => console.log(`- credential ${credential.name.bold} with ${credentialIdName.bold}: ${credential.attributes[credentialIdName].bold} ${'is up to date'.bold.green}`),

        unknown: action => console.log('unknown action', action),
    })(message.params),
    request: ({ uri, params: { method, body } }) => console.log(
        `\n${method.bold.blue}`, uri.blue, "\n", body ? body : ''
    ),
    response: ({ ok, status, statusText, content }) => console.log(
        ok ? `${status} ${statusText.bold}`.green : `${status} ${statusText.bold}`.red,
        content
    ),
    debug: () => {},
    'experimental-features': ({ message }) => console.log(message),
    'kong-info': ({ version }) => console.log(`Kong version: ${version}`),
    unknown: message => console.log('unknown', message),
});


text:
#include <zephyr/device.h>
#include <soc.h>
#include <stm32_ll_lptim.h>
#include <stm32_ll_bus.h>
#include <stm32_ll_rcc.h>
#include <stm32_ll_pwr.h>
#include <stm32_ll_system.h>
#include <zephyr/drivers/clock_control.h>
#include <zephyr/drivers/clock_control/stm32_clock_control.h>
#include <zephyr/drivers/timer/system_timer.h>
#include <zephyr/sys_clock.h>
#include <zephyr/irq.h>

#include <zephyr/spinlock.h>

#define DT_DRV_COMPAT st_stm32_lptim

#if DT_NUM_INST_STATUS_OKAY(DT_DRV_COMPAT) > 1
#error Only one LPTIM instance should be enabled
#endif

#define LPTIM (LPTIM_TypeDef *) DT_INST_REG_ADDR(0)

#if DT_INST_NUM_CLOCKS(0) == 1
#warning Kconfig for LPTIM source clock (LSI/LSE) is deprecated, use device tree.
static const struct stm32_pclken lptim_clk[] = {
	STM32_CLOCK_INFO(0, DT_DRV_INST(0)),
	/* Use Kconfig to configure source clocks fields */
	/* Fortunately, values are consistent across enabled series */
#ifdef CONFIG_STM32_LPTIM_CLOCK_LSI
	{.bus = STM32_SRC_LSI, .enr = LPTIM1_SEL(1)}
#else
	{.bus = STM32_SRC_LSE, .enr = LPTIM1_SEL(3)}
#endif
};
#else
static const struct stm32_pclken lptim_clk[] = STM32_DT_INST_CLOCKS(0);
#endif

static const struct device *const clk_ctrl = DEVICE_DT_GET(STM32_CLOCK_CONTROL_NODE);

/*
 * Assumptions and limitations:
 *
 * - system clock based on an LPTIM instance, clocked by LSI or LSE
 * - prescaler is set to 1 (LL_LPTIM_PRESCALER_DIV1 in the related register)
 * - using LPTIM AutoReload capability to trig the IRQ (timeout irq)
 * - when timeout irq occurs the counter is already reset
 * - the maximum timeout duration is reached with the lptim_time_base value
 * - with prescaler of 1, the max timeout (lptim_time_base) is 2seconds
 */

static uint32_t lptim_clock_freq = 32000;
static int32_t lptim_time_base;

/* minimum nb of clock cycles to have to set autoreload register correctly */
#define LPTIM_GUARD_VALUE 2

/* A 32bit value cannot exceed 0xFFFFFFFF/LPTIM_TIMEBASE counting cycles.
 * This is for example about of 65000 x 2000ms when clocked by LSI
 */
static uint32_t accumulated_lptim_cnt;
/* Next autoreload value to set */
static uint32_t autoreload_next;
/* Indicate if the autoreload register is ready for a write */
static bool autoreload_ready = true;

static struct k_spinlock lock;

/* For tick accuracy, a specific tick to freq ratio is expected */
/* This check assumes LSI@32KHz or LSE@32768Hz */
#if !defined(CONFIG_STM32_LPTIM_TICK_FREQ_RATIO_OVERRIDE)
#if (((DT_CLOCKS_CELL_BY_IDX(DT_DRV_INST(0), 1, bus) == STM32_SRC_LSI) &&	\
		(CONFIG_SYS_CLOCK_TICKS_PER_SEC != 4000)) ||			\
	((DT_CLOCKS_CELL_BY_IDX(DT_DRV_INST(0), 1, bus) == STM32_SRC_LSE) &&	\
		(CONFIG_SYS_CLOCK_TICKS_PER_SEC != 4096)))
#warning Advised tick freq is 4096 for LSE / 4000 for LSI
#endif
#endif /* !CONFIG_STM32_LPTIM_TICK_FREQ_RATIO_OVERRIDE */

static void lptim_irq_handler(const struct device *unused)
{

	ARG_UNUSED(unused);

	uint32_t autoreload = LL_LPTIM_GetAutoReload(LPTIM);

	if ((LL_LPTIM_IsActiveFlag_ARROK(LPTIM) != 0)
		&& LL_LPTIM_IsEnabledIT_ARROK(LPTIM) != 0) {
		LL_LPTIM_ClearFlag_ARROK(LPTIM);
		if ((autoreload_next > 0) && (autoreload_next != autoreload)) {
			/* the new autoreload value change, we set it */
			autoreload_ready = false;
			LL_LPTIM_SetAutoReload(LPTIM, autoreload_next);
		} else {
			autoreload_ready = true;
		}
	}

	if ((LL_LPTIM_IsActiveFlag_ARRM(LPTIM) != 0)
		&& LL_LPTIM_IsEnabledIT_ARRM(LPTIM) != 0) {

		k_spinlock_key_t key = k_spin_lock(&lock);

		/* do not change ARR yet, sys_clock_announce will do */
		LL_LPTIM_ClearFLAG_ARRM(LPTIM);

		/* increase the total nb of autoreload count
		 * used in the sys_clock_cycle_get_32() function.
		 */
		autoreload++;

		accumulated_lptim_cnt += autoreload;

		k_spin_unlock(&lock, key);

		/* announce the elapsed time in ms (count register is 16bit) */
		uint32_t dticks = (autoreload
				* CONFIG_SYS_CLOCK_TICKS_PER_SEC)
				/ lptim_clock_freq;

		sys_clock_announce(IS_ENABLED(CONFIG_TICKLESS_KERNEL)
				? dticks : (dticks > 0));
	}
}

static void lptim_set_autoreload(uint32_t arr)
{
	/* Update autoreload register */
	autoreload_next = arr;

	if (!autoreload_ready)
		return;

	/* The ARR register ready, we could set it directly */
	if ((arr > 0) && (arr != LL_LPTIM_GetAutoReload(LPTIM))) {
		/* The new autoreload value change, we set it */
		autoreload_ready = false;
		LL_LPTIM_ClearFlag_ARROK(LPTIM);
		LL_LPTIM_SetAutoReload(LPTIM, arr);
	}
}

static inline uint32_t z_clock_lptim_getcounter(void)
{
	uint32_t lp_time;
	uint32_t lp_time_prev_read;

	/* It should be noted that to read reliably the content
	 * of the LPTIM_CNT register, two successive read accesses
	 * must be performed and compared
	 */
	lp_time = LL_LPTIM_GetCounter(LPTIM);
	do {
		lp_time_prev_read = lp_time;
		lp_time = LL_LPTIM_GetCounter(LPTIM);
	} while (lp_time != lp_time_prev_read);
	return lp_time;
}

void sys_clock_set_timeout(int32_t ticks, bool idle)
{
	/* new LPTIM AutoReload value to set (aligned on Kernel ticks) */
	uint32_t next_arr = 0;

	ARG_UNUSED(idle);

	if (!IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
		return;
	}

	if (ticks == K_TICKS_FOREVER) {
		clock_control_off(clk_ctrl, (clock_control_subsys_t *) &lptim_clk[0]);
		return;
	}

	/* if LPTIM clock was previously stopped, it must now be restored */
	clock_control_on(clk_ctrl, (clock_control_subsys_t *) &lptim_clk[0]);

	/* passing ticks==1 means "announce the next tick",
	 * ticks value of zero (or even negative) is legal and
	 * treated identically: it simply indicates the kernel would like the
	 * next tick announcement as soon as possible.
	 */
	ticks = CLAMP(ticks - 1, 1, lptim_time_base);

	k_spinlock_key_t key = k_spin_lock(&lock);

	/* read current counter value (cannot exceed 16bit) */

	uint32_t lp_time = z_clock_lptim_getcounter();

	uint32_t autoreload = LL_LPTIM_GetAutoReload(LPTIM);

	if (LL_LPTIM_IsActiveFlag_ARRM(LPTIM)
	    || ((autoreload - lp_time) < LPTIM_GUARD_VALUE)) {
		/* interrupt happens or happens soon.
		 * It's impossible to set autoreload value.
		 */
		k_spin_unlock(&lock, key);
		return;
	}

	/* calculate the next arr value (cannot exceed 16bit)
	 * adjust the next ARR match value to align on Ticks
	 * from the current counter value to first next Tick
	 */
	next_arr = (((lp_time * CONFIG_SYS_CLOCK_TICKS_PER_SEC)
			/ lptim_clock_freq) + 1) * lptim_clock_freq
			/ (CONFIG_SYS_CLOCK_TICKS_PER_SEC);
	/* add count unit from the expected nb of Ticks */
	next_arr = next_arr + ((uint32_t)(ticks) * lptim_clock_freq)
			/ CONFIG_SYS_CLOCK_TICKS_PER_SEC - 1;

	/* maximise to TIMEBASE */
	if (next_arr > lptim_time_base) {
		next_arr = lptim_time_base;
	}
	/* The new autoreload value must be LPTIM_GUARD_VALUE clock cycles
	 * after current lptim to make sure we don't miss
	 * an autoreload interrupt
	 */
	else if (next_arr < (lp_time + LPTIM_GUARD_VALUE)) {
		next_arr = lp_time + LPTIM_GUARD_VALUE;
	}

	/* Update autoreload register */
	lptim_set_autoreload(next_arr);

	k_spin_unlock(&lock, key);
}

uint32_t sys_clock_elapsed(void)
{
	if (!IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
		return 0;
	}

	k_spinlock_key_t key = k_spin_lock(&lock);

	uint32_t lp_time = z_clock_lptim_getcounter();

	/* In case of counter roll-over, add this value,
	 * even if the irq has not yet been handled
	 */
	if ((LL_LPTIM_IsActiveFlag_ARRM(LPTIM) != 0)
	  && LL_LPTIM_IsEnabledIT_ARRM(LPTIM) != 0) {
		lp_time += LL_LPTIM_GetAutoReload(LPTIM) + 1;
	}

	k_spin_unlock(&lock, key);

	/* gives the value of LPTIM counter (ms)
	 * since the previous 'announce'
	 */
	uint64_t ret = ((uint64_t)lp_time * CONFIG_SYS_CLOCK_TICKS_PER_SEC) / lptim_clock_freq;

	return (uint32_t)(ret);
}

uint32_t sys_clock_cycle_get_32(void)
{
	/* just gives the accumulated count in a number of hw cycles */

	k_spinlock_key_t key = k_spin_lock(&lock);

	uint32_t lp_time = z_clock_lptim_getcounter();

	/* In case of counter roll-over, add this value,
	 * even if the irq has not yet been handled
	 */
	if ((LL_LPTIM_IsActiveFlag_ARRM(LPTIM) != 0)
	  && LL_LPTIM_IsEnabledIT_ARRM(LPTIM) != 0) {
		lp_time += LL_LPTIM_GetAutoReload(LPTIM) + 1;
	}

	lp_time += accumulated_lptim_cnt;

	/* convert lptim count in a nb of hw cycles with precision */
	uint64_t ret = ((uint64_t)lp_time * sys_clock_hw_cycles_per_sec()) / lptim_clock_freq;

	k_spin_unlock(&lock, key);

	/* convert in hw cycles (keeping 32bit value) */
	return (uint32_t)(ret);
}

static int sys_clock_driver_init(const struct device *dev)
{
	int err;

	ARG_UNUSED(dev);

	if (!device_is_ready(clk_ctrl)) {
		return -ENODEV;
	}

	/* Enable LPTIM bus clock */
	err = clock_control_on(clk_ctrl, (clock_control_subsys_t *) &lptim_clk[0]);
	if (err < 0) {
		return -EIO;
	}

#if defined(LL_APB1_GRP1_PERIPH_LPTIM1)
	LL_APB1_GRP1_ReleaseReset(LL_APB1_GRP1_PERIPH_LPTIM1);
#elif defined(LL_APB3_GRP1_PERIPH_LPTIM1)
	LL_SRDAMR_GRP1_EnableAutonomousClock(LL_SRDAMR_GRP1_PERIPH_LPTIM1AMEN);
#endif

	/* Enable LPTIM clock source */
	err = clock_control_configure(clk_ctrl,
				      (clock_control_subsys_t *) &lptim_clk[1],
				      NULL);
	if (err < 0) {
		return -EIO;
	}

	/* Get LPTIM clock freq */
	err = clock_control_get_rate(clk_ctrl, (clock_control_subsys_t *) &lptim_clk[1],
			       &lptim_clock_freq);

	if (err < 0) {
		return -EIO;
	}
#if defined(CONFIG_SOC_SERIES_STM32L0X)
	/* Driver only supports freqs up to 32768Hz. On L0, LSI freq is 37KHz,
	 * which will overflow the LPTIM counter.
	 * Previous LPTIM configuration using device tree was doing forcing this
	 * with a Kconfig default. Impact is that time is 1.13 faster than reality.
	 * Following lines reproduce this behavior in order not to change behavior.
	 * This issue will be fixed by implementation LPTIM prescaler support.
	 */
	if (lptim_clk[1].bus == STM32_SRC_LSI) {
		lptim_clock_freq = KHZ(32);
	}
#endif

	/* Set LPTIM time base based on clck source freq
	 * Time base = (2s * freq) - 1
	 */
	if (lptim_clock_freq == KHZ(32)) {
		lptim_time_base = 0xF9FF;
	} else if (lptim_clock_freq == 32768) {
		lptim_time_base = 0xFFFF;
	} else {
		return -EIO;
	}

	/* Clear the event flag and possible pending interrupt */
	IRQ_CONNECT(DT_INST_IRQN(0),
		    DT_INST_IRQ(0, priority),
		    lptim_irq_handler, 0, 0);
	irq_enable(DT_INST_IRQN(0));

#ifdef CONFIG_SOC_SERIES_STM32WLX
	/* Enable the LPTIM wakeup EXTI line */
	LL_EXTI_EnableIT_0_31(LL_EXTI_LINE_29);
#endif

	/* configure the LPTIM counter */
	LL_LPTIM_SetClockSource(LPTIM, LL_LPTIM_CLK_SOURCE_INTERNAL);
	/* configure the LPTIM prescaler with 1 */
	LL_LPTIM_SetPrescaler(LPTIM, LL_LPTIM_PRESCALER_DIV1);
#ifdef CONFIG_SOC_SERIES_STM32U5X
	LL_LPTIM_OC_SetPolarity(LPTIM, LL_LPTIM_CHANNEL_CH1,
				LL_LPTIM_OUTPUT_POLARITY_REGULAR);
#else
	LL_LPTIM_SetPolarity(LPTIM, LL_LPTIM_OUTPUT_POLARITY_REGULAR);
#endif
	LL_LPTIM_SetUpdateMode(LPTIM, LL_LPTIM_UPDATE_MODE_IMMEDIATE);
	LL_LPTIM_SetCounterMode(LPTIM, LL_LPTIM_COUNTER_MODE_INTERNAL);
	LL_LPTIM_DisableTimeout(LPTIM);
	/* counting start is initiated by software */
	LL_LPTIM_TrigSw(LPTIM);

#ifdef CONFIG_SOC_SERIES_STM32U5X
	/* Enable the LPTIM before proceeding with configuration */
	LL_LPTIM_Enable(LPTIM);

	LL_LPTIM_DisableIT_CC1(LPTIM);
	while (LL_LPTIM_IsActiveFlag_DIEROK(LPTIM) == 0) {
	}
	LL_LPTIM_ClearFlag_DIEROK(LPTIM);
	LL_LPTIM_ClearFLAG_CC1(LPTIM);
#else
	/* LPTIM interrupt set-up before enabling */
	/* no Compare match Interrupt */
	LL_LPTIM_DisableIT_CMPM(LPTIM);
	LL_LPTIM_ClearFLAG_CMPM(LPTIM);
#endif

	/* Autoreload match Interrupt */
	LL_LPTIM_EnableIT_ARRM(LPTIM);
#ifdef CONFIG_SOC_SERIES_STM32U5X
	while (LL_LPTIM_IsActiveFlag_DIEROK(LPTIM) == 0) {
	}
	LL_LPTIM_ClearFlag_DIEROK(LPTIM);
#endif
	LL_LPTIM_ClearFLAG_ARRM(LPTIM);
	/* ARROK bit validates the write operation to ARR register */
	LL_LPTIM_EnableIT_ARROK(LPTIM);
	LL_LPTIM_ClearFlag_ARROK(LPTIM);

	accumulated_lptim_cnt = 0;

#ifndef CONFIG_SOC_SERIES_STM32U5X
	/* Enable the LPTIM counter */
	LL_LPTIM_Enable(LPTIM);
#endif

	/* Set the Autoreload value once the timer is enabled */
	if (IS_ENABLED(CONFIG_TICKLESS_KERNEL)) {
		/* LPTIM is triggered on a LPTIM_TIMEBASE period */
		lptim_set_autoreload(lptim_time_base);
	} else {
		/* LPTIM is triggered on a Tick period */
		lptim_set_autoreload((lptim_clock_freq / CONFIG_SYS_CLOCK_TICKS_PER_SEC) - 1);
	}

	/* Start the LPTIM counter in continuous mode */
	LL_LPTIM_StartCounter(LPTIM, LL_LPTIM_OPERATING_MODE_CONTINUOUS);

#ifdef CONFIG_DEBUG
	/* stop LPTIM during DEBUG */
#if defined(LL_DBGMCU_APB1_GRP1_LPTIM1_STOP)
	LL_DBGMCU_APB1_GRP1_FreezePeriph(LL_DBGMCU_APB1_GRP1_LPTIM1_STOP);
#elif defined(LL_DBGMCU_APB3_GRP1_LPTIM1_STOP)
	LL_DBGMCU_APB3_GRP1_FreezePeriph(LL_DBGMCU_APB3_GRP1_LPTIM1_STOP);
#endif

#endif
	return 0;
}

SYS_INIT(sys_clock_driver_init, PRE_KERNEL_2,
	 CONFIG_SYSTEM_CLOCK_INIT_PRIORITY);


text:
namespace EPiBootstrapArea
{
    public static class ContentAreaTags
    {
        public const string FullWidth = "displaymode-full";
        public const string HalfWidth = "displaymode-half";
        public const string NoRenderer = "displaymode-norenderer";
        public const string None = "displaymode-none";
        public const string OneQuarterWidth = "displaymode-one-quarter";
        public const string OneThirdWidth = "displaymode-one-third";
        public const string ThreeQuartersWidth = "displaymode-three-quarters";
        public const string TwoThirdsWidth = "displaymode-two-thirds";
    }
}


text:
<?php

namespace app\modules\user\models;

use Yii;

/**
 * This is the model class for table "user".
 *
 * @property integer $id
 * @property string $identity
 * @property string $password
 * @property integer $parent_id
 * @property integer $level
 * @property string $auth_key
 * @property string $access_token
 * @property string $started
 * @property string $lastvisit
 * @property integer $status
 *
 * @property Activity[] $activities
 * @property Comment[] $comments
 * @property Event[] $events
 * @property Journal[] $journals
 * @property Mood[] $moods
 * @property Payment[] $payments
 * @property Photos[] $photos
 * @property Profile[] $profiles
 * @property Rating[] $ratings
 * @property Wishlist[] $wishlists
 */
class User extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'user';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['identity', 'password', 'parent_id', 'level', 'auth_key', 'access_token', 'started', 'status'], 'required'],
            [['parent_id', 'level', 'status'], 'integer'],
            [['started', 'lastvisit'], 'safe'],
            [['identity', 'access_token'], 'string', 'max' => 128],
            [['password'], 'string', 'max' => 64],
            [['auth_key'], 'string', 'max' => 32]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'identity' => 'Identity',
            'password' => 'Password',
            'parent_id' => 'Parent ID',
            'level' => 'Level',
            'auth_key' => 'Auth Key',
            'access_token' => 'Access Token',
            'started' => 'Started',
            'lastvisit' => 'Lastvisit',
            'status' => 'Status',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getActivities()
    {
        return $this->hasMany(Activity::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getComments()
    {
        return $this->hasMany(Comment::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getEvents()
    {
        return $this->hasMany(Event::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getJournals()
    {
        return $this->hasMany(Journal::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getMoods()
    {
        return $this->hasMany(Mood::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPayments()
    {
        return $this->hasMany(Payment::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getPhotos()
    {
        return $this->hasMany(Photos::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProfiles()
    {
        return $this->hasMany(Profile::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getRatings()
    {
        return $this->hasMany(Rating::className(), ['user_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getWishlists()
    {
        return $this->hasMany(Wishlist::className(), ['user_id' => 'id']);
    }
}


text:
[Unit testing your Redux actions and reducers](unit-testing.md) is nice, but you can do even more to make sure nothing breaks your application. The most integral part of a React app are your components, so why not test them too!

<!-- TOC depthFrom:2 depthTo:6 withLinks:1 updateOnSave:1 orderedList:0 -->

- [Shallow rendering](#shallow-rendering)
- [enzyme](#enzyme)

<!-- /TOC -->

## Shallow rendering

React provides us with a nice add-on called the Shallow Renderer. This renderer will render a React component **one level deep**. Lets take a look at what that means with a simple `<Button>` component!

This component renders a `<button>` element containing a checkmark icon and some text:

```JS
// Button.react.js

import CheckmarkIcon from './CheckmarkIcon.react';

function Button(props) {
  return (
    <button className="btn" onClick={props.onClick}>
      <CheckmarkIcon />
      { props.children }
    </button>
  );
}

export default Button;
```

> Note: This is a [stateless ("dumb") component](../js/react/README.md#components-and-containers)!

It might be used in another component like this:

```JS
// HomePage.react.js

import Button from './Button.react';

class HomePage extends React.Component {
  render() {
    return(
      <Button onClick={this.doSomething}>Click me!</Button>
    );
  }
}
```

> Note: This is a [stateful ("smart") component](../js/react/README.md#components-and-containers)!

When rendered normally with the standard `ReactDOM.render` function, this will be the HTML output (*comments added by hand for easier understanding*):

```HTML
<!-- <Button> -->
<button>
  <i class="fa fa-checkmark"></i>  <!-- <CheckmarkIcon /> -->
  Click Me!                        <!-- { props.children } -->
</button>
<!-- </Button> -->
```

In comparison, when rendered with the shallow renderer, we'll get a String containing this "HTML":

```HTML
<!-- <Button> -->
<button>
  <CheckmarkIcon />
  Click Me!          <!-- { props.children } -->
</button>
<!-- </Button> -->
```

If we tested our `Button` with the normal renderer, and there was a problem with the `CheckmarkIcon`, the test for the `Button` would fail as well and it would be hard to find the culprit of the failures. Using the shallow renderer, we can asses and identify the problems since we don't render any other components other than the one we're testing!

The problem with the shallow renderer is that all assertions have to be done manually, and you cannot do anything that needs the DOM.

Thankfully, [AirBnB](https://twitter.com/AirBnBNerds) has open sourced their wrapper around the React shallow renderer and jsdom, called `enzyme`. `enzyme` is a testing utility that gives us a nice assertion/traversment/manipulation API.

## enzyme

Lets test our `<Button>` component! We're going to assess three things: First, that it renders a HTML `<button>` tag, second that it renders its children we pass it and third that handles clicks!

This is our Mocha setup:

```JS
describe('<Button />', () => {
  it('renders a <button>', () => {});

  it('renders its children', () => {});

  it('handles clicks', () => {});
});
```

Lets start with testing that it renders a `<button>`. To do that we first `shallow` render it, and then `expect` that a `<button>` node exists.

```JS
it('renders a <button>', () => {
  const renderedComponent = shallow(
    <Button></Button>
  );
  expect(
    renderedComponent.find("button").node
  ).toExist();
});
```

Nice, if somebody breaks our button component by having it render an `<a>` tag or something else we'll immediately know! Lets do something a bit more advanced now, and asses that our `<Button>` renders its children.

We render our button component with some text, and then asses that our text exists:

```JS
it('renders its children', () => {
  const text = "Click me!";
  const renderedComponent = shallow(
    <Button>{ text }</Button>
  );
  expect(
    renderedComponent.contains(text)
  ).toEqual(true);
});
```

Great! Onwards to our last and most advanced test, which assesses that our `<Button>` handles clicks correctly. We'll use a Spy for that, a Spy is a function that knows if and how often it has been called. `expect` thankfully provides them for us, so all we have to do is use them. We create the Spy, pass it as the `onClick` function to our component, simulate a click on the `<button>` tag and lastly assess that our spy was called!

```JS
it('handles clicks', () => {
  const onClickSpy = expect.createSpy();
  const renderedComponent = shallow(<Button onClick={onClickSpy} />);
  renderedComponent.find('button').simulate('click');
  expect(onClickSpy).toHaveBeenCalled();
});
```

That's how you unit test your components and make sure they work correctly!


text:
$(function(){
    // Classes
    function WSRouter(kittyManager, id){
        this.id = '';
        this.kittyManager = kittyManager;
    };

    WSRouter.prototype.onMessage = function(msg){
        var data    = JSON.parse(msg.data);
        var status  = data.type;
        switch(status){
            case 'start_done':
                console.log('START', data);
                var kittens = data.kittens;
                this.kittyManager.set(kittens);
                break;
            case 'added':
                var kitty = data.kitty;
                this.kittyManager.add(kitty);
                console.log('Kitty added', kitty);
                break;
            case 'mew':
                console.log('Kitty say mew', data.id);

                var $kitty = $('#' + data.id + ' .mew');

                $kitty.addClass('now');
                setTimeout(function(){
                    $kitty.addClass('anim');
                },1);

                kittyManager.mew(data.id);

                setTimeout(function(){
                    $kitty.removeClass('now');
                    setTimeout(function(){
                        $kitty.removeClass('anim');
                    },10);
                },1000);

                break;
        }
    };

    function Kitty(options){
        _.extend(this, options);
        this.config = JSON.parse(options.config);
        this.options = options;
        this.mewWav = new Audio("/audio/cat11.wav");

    }
    Kitty.prototype.render = function(){
        this.$name = $('

');
        this.$mew  = $('
Mew
');

        this.$el = $('

');

        this.$name.html(this.name);

        this.$el.append(this.$mew);
        this.$el.append(this.$name);
        this.$el.css({
            'border-color' : this.config.hsl
        });
        this.$name.css({
            'background-color' : this.config.hsl
        });
        this.$mew.css({
            'background-color' : this.config.hsl
        });

        return this;
    };

    function KittyManager(){
        this.kittens = [];
        this.$kittens = [];
        this.$room = $('

');
        $body.append(this.$room);
    };
    KittyManager.prototype.mew = function(kid){
        this.kittens.filter(function(kitty){
            return kitty._id+'' === kid+'';
        })[0].mewWav.play();
    };
    KittyManager.prototype.set = function(kittens){
        var self = this;
        this.kittens = [];
        kittens.forEach(function(kitty){
            var kitty = new Kitty(kitty);
            self.kittens.push(kitty);
        });
        this.render();
    };
    KittyManager.prototype.add = function(kitty){
        this.kittens.push(new Kitty(kitty));
        this.render();
    };
    KittyManager.prototype.render = function(){
        var self = this;
        this.$room.empty();
        this.$kittens = [];
        this.kittens.forEach(function(kitty, i){
            var $kitty = kitty.render().$el;
            var config = kitty.config;
            var left = config.left + '%';
            var top = config.top + '%';

            $kitty.css({
                left: left,
                top : top
            });

            self.$kittens.push($kitty);
            self.$room.append($kitty);

            console.log(kitty);
        });
    };

    function AppController(id, socket, kittyManager, wsRouter){
        this.id      = id;
        this.socket  = socket;
        this.manager = kittyManager;
        this.router  = wsRouter;

        this.render();
        this.applyEvents();
    };
    AppController.prototype.addKitty = function(){
        var message = {
            id   : this.id,
            type : 'add_kitty'
        };

        this.socket.send(JSON.stringify(message));
    };
    AppController.prototype.render = function(){
        if(!this.$addButton || this.$addButton.length === 0){
            this.$addButton = $('<button id="add">+</button>');
            $body.append(this.$addButton);
        }
    };
    AppController.prototype.applyEvents = function(){
        var self = this;
        if(this.$addButton && this.$addButton.length !== 0){
            console.log('Add clicked');
            this.$addButton.click(function(){
                self.addKitty();
            });
        }
    };

    var $body = $('body').eq(0);

    var location = window.location.href;
    var levels = location.split('/');
    var id = levels[levels.length - 1];
    var socket = new WebSocket("ws://localhost:8081");
    var kittyManager = new KittyManager();
    var wsRouter = new WSRouter(kittyManager, id);
    var controller = new AppController(id, socket, kittyManager, wsRouter);

    _.bindAll(wsRouter, 'onMessage');
    _.bindAll(controller, 'addKitty');

    socket.onopen = function(){
        initWS();
        console.log("Socket has been opened");
    };

    function initWS(){
        socket.onmessage = wsRouter.onMessage;
        var initData = {
            id: id,
            type: 'start'
        };
        socket.send(JSON.stringify(initData));
    };

});


text:
export function sortListQuery(queryListFrequency) {
  // Function that sorts a list of tuple based on the second item of the tuple.
  // It returns a list of sorted interlocutors and/or activities
  queryListFrequency.sort((first, second) => second[1] - first[1]);
  let requestResult = [];
  queryListFrequency.forEach((result) => {
    requestResult = requestResult.concat(result[0]);
  });
  return requestResult;
}

function replaceAccent(tag) {
  const strAccents = tag.split('');
  let strAccentsOut = [];
  const strAccentsLen = strAccents.length;
  const accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
  const accentsOut = 'AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz';
  for (let y = 0; y < strAccentsLen; y++) {
    if (accents.indexOf(strAccents[y]) !== -1) {
      strAccentsOut[y] = accentsOut.substr(accents.indexOf(strAccents[y]), 1);
    } else { strAccentsOut[y] = strAccents[y]; }
  }
  strAccentsOut = strAccentsOut.join('');
  return strAccentsOut;
}

export function cleanTag(tag) {
  return replaceAccent(tag.toLowerCase()).replace(/[^a-zA-Z0-9]/g, '');
}


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

              <input class="mdl-mega-footer--heading-checkbox" type="checkbox" checked>

Features

About

Terms

Partners

Updates

              <input class="mdl-mega-footer--heading-checkbox" type="checkbox" checked>

Details

Spec

Tools

Resources

              <input class="mdl-mega-footer--heading-checkbox" type="checkbox" checked>

Technology

How it works

Patterns

Usage

Products

Contracts

              <input class="mdl-mega-footer--heading-checkbox" type="checkbox" checked>

FAQ

Questions

Answers

Contact us

              More Information

Web Starter Kit

Help

Privacy and Terms


text:
<Alloy>

	<Collection src="BusStop"/>

	<Window class="container">

		Hello, World

		<TableView dataCollection="BusStop">
			<TableViewRow>
				row
			</TableViewRow>
		</TableView>

	</Window>

</Alloy>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Гостевая книга</title>

    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

    <!-- Optional theme -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap-theme.min.css">

    <!-- Stylesheet -->
    <link rel="stylesheet" href="<? echo asset_url()?>css/style.css">

</head>


text:
define(['require',
    'backbone',
    'hbs!tmpl/tag/TagAttributeDetailLayoutView_tmpl',
    'utils/Utils',
    'views/tag/AddTagAttributeView',
    'collection/VCommonList',
    'models/VTag',
    'utils/Messages'
], function(require, Backbone, TagAttributeDetailLayoutViewTmpl, Utils, AddTagAttributeView, VCommonList, VTag, Messages) {
    'use strict';

    var TagAttributeDetailLayoutView = Backbone.Marionette.LayoutView.extend(
        /** @lends TagAttributeDetailLayoutView */
        {
            template: TagAttributeDetailLayoutViewTmpl,
            /** Layout sub regions */
            regions: {},
            /** ui selector cache */
            ui: {
                title: '[data-id="title"]',
                editButton: '[data-id="editButton"]',
                editBox: '[data-id="editBox"]',
                addAttrBtn: '[data-id="addAttrBtn"]',
                saveButton: "[data-id='saveButton']",
                showAttribute: "[data-id='showAttribute']",
                cancelButton: "[data-id='cancelButton']",
                addTagListBtn: '[data-id="addTagListBtn"]',
                addTagtext: '[data-id="addTagtext"]',
                addTagPlus: '[data-id="addTagPlus"]',
                description: '[data-id="description"]',
                descriptionTextArea: '[data-id="descriptionTextArea"]',
                publishButton: '[data-id="publishButton"]',
            },
            /** ui events hash */
            events: function() {
                var events = {};
                events["click " + this.ui.cancelButton] = 'onCancelButtonClick';
                events["click " + this.ui.addAttrBtn] = 'onClickAddAttribute';
                events["click " + this.ui.addTagListBtn] = 'onClickAddTagBtn';
                events["click " + this.ui.editButton] = 'onEditButton';
                return events;
            },
            /**
             * intialize a new TagAttributeDetailLayoutView Layout
             * @constructs
             */
            initialize: function(options) {
                _.extend(this, _.pick(options, 'globalVent', 'tag', 'vent'));
                this.tagCollection = new VCommonList();
                this.tagCollection.url = "/api/atlas/types/" + this.tag;
                this.tagCollection.modelAttrName = "definition";
                this.tagCollection.fetch({ reset: true });
                this.bindEvents();
            },
            bindEvents: function() {
                this.listenTo(this.tagCollection, 'reset', function() {
                    var that = this,
                        attributeData = "";
                    _.each(this.tagCollection.models, function(attr) {
                        var traitTypes = attr.get("traitTypes");
                        if (traitTypes[0].typeDescription != null) {
                            var descriptionValue = traitTypes[0].typeDescription;
                            that.ui.description.html(descriptionValue);
                        }
                        _.each(traitTypes[0].attributeDefinitions, function(value, key) {
                            attributeData += '' + value.name + '';
                        });
                    });
                    if (attributeData.length) {
                        that.ui.addTagtext.hide();
                        that.ui.addTagPlus.show();
                    }
                    that.ui.showAttribute.html(attributeData);
                }, this);
                this.listenTo(this.tagCollection, 'error', function(error, response) {
                    if (response.responseJSON && response.responseJSON.error) {
                        Utils.notifyError({
                            content: response.responseJSON.error
                        });
                    }

                }, this);
            },
            onRender: function() {
                this.ui.title.html('' + this.tag + '');
                this.ui.saveButton.attr("disabled", "true");
                this.ui.publishButton.prop('disabled', true);
            },
            onSaveButton: function(saveObject, message) {
                var that = this,
                    tagModel = new VTag();
                tagModel.set(saveObject).save(null, {
                    type: "PUT",
                    success: function(model, response) {
                        that.tagCollection.fetch({ reset: true });
                        Utils.notifySuccess({
                            content: message
                        });
                    },
                    error: function(model, response) {
                        if (response.responseJSON && response.responseJSON.error) {
                            that.tagCollection.fetch({ reset: true });
                            Utils.notifyError({
                                content: response.responseJSON.error
                            });
                        }
                    }
                });
            },
            onClickAddTagBtn: function(e) {
                var that = this;
                require(['views/tag/AddTagAttributeView',
                        'modules/Modal'
                    ],
                    function(AddTagAttributeView, Modal) {
                        var view = new AddTagAttributeView(),
                            modal = new Modal({
                                title: 'Add Attribute',
                                content: view,
                                cancelText: "Cancel",
                                okText: 'Add',
                                allowCancel: true,
                            }).open();
                        modal.on('ok', function() {
                            var attributeName = $(view.el).find("input").val();
                            that.tagCollection.first().get('traitTypes')[0].attributeDefinitions.push({
                                "name": attributeName,
                                "dataTypeName": "string",
                                "multiplicity": "optional",
                                "isComposite": false,
                                "isUniquvar e": false,
                                "isIndexable": true,
                                "reverseAttributeName": null
                            });
                            that.onSaveButton(that.tagCollection.first().toJSON(), Messages.addAttributeSuccessMessage);
                        });
                        modal.on('closeModal', function() {
                            modal.trigger('cancel');
                        });
                    });
            },
            onCancelButtonClick: function() {
                this.ui.description.show();
                this.ui.editButton.show();
                this.ui.editBox.hide();
            },
            textAreaChangeEvent: function(view, modal) {
                if (view.tagCollection.first().get('traitTypes')[0].typeDescription == view.ui.description.val()) {
                    modal.$el.find('button.ok').prop('disabled', true);
                } else {
                    modal.$el.find('button.ok').prop('disabled', false);
                }
            },
            onPublishClick: function(view) {
                view.tagCollection.first().get('traitTypes')[0].typeDescription = view.ui.description.val();
                this.onSaveButton(this.tagCollection.first().toJSON(), Messages.updateTagDescriptionMessage);
                this.ui.description.show();
            },
            onEditButton: function(e) {
                var that = this;
                $(e.currentTarget).blur();
                require([
                    'views/tag/CreateTagLayoutView',
                    'modules/Modal'
                ], function(CreateTagLayoutView, Modal) {
                    var view = new CreateTagLayoutView({ 'tagCollection': that.tagCollection, 'tag': that.tag });
                    var modal = new Modal({
                        title: 'Edit Tag',
                        content: view,
                        cancelText: "Cancel",
                        okText: 'Save',
                        allowCancel: true,
                    }).open();
                    view.ui.description.on('keyup', function(e) {
                        that.textAreaChangeEvent(view, modal);
                    });
                    modal.$el.find('button.ok').prop('disabled', true);
                    modal.on('ok', function() {
                        that.onPublishClick(view);
                    });
                    modal.on('closeModal', function() {
                        modal.trigger('cancel');
                    });
                });
            }
        });
    return TagAttributeDetailLayoutView;
});


text: Shared parameters; content of this file does not matter for testing.


text:
'use strict';

/**
 * @module document
 */

const uuid = require('./uuid');

/**
 * Initialize an object as document
 * @param {Object} doc
 * @return {Document}
 * @module util/document
 */
exports.init = (doc) => {
    if(typeof doc._id === 'undefined' || doc._id === null) {
        doc._id = uuid();
    }

    if(!doc._rev) {
        doc._rev = `1-${uuid()}`;
    }

    return doc;
};

/**
 * Validate a document before save
 * @param {Document} doc
 * @return {Boolean}
 * @module util/document
 */
exports.preValidate = (doc) => {
    return (typeof doc === 'object' && !Array.isArray(doc));
};

/**
 * Validate a document after save
 * @param {Document} doc
 * @return {Boolean}
 * @module util/document
 */
exports.postValidate = (doc) => {
    if(typeof doc === 'object' && doc._id && doc._rev) {
        return true;
    }

    return false;
};

/**
 * Check if the document has an _id attribute
 * @param {Document} doc
 * @return {Boolean}
 * @module util/document
 */
exports.hasId = (doc) => {
    if(typeof doc._id !== 'undefined' && doc._id !== null) {
        return true;
    }

    return false;
};

/**
 * Update the revision of a document to
 * a certain version or just increment (null param)
 * @param {Document} doc
 * @param {Number} [version]
 * @return {Document}
 * @module util/document
 */
exports.update = (doc, version) => {
    if(doc._rev) {
        let revs = doc._rev.split('-');
        doc._rev = (version || (parseInt(revs[0], 10) + 1)) + '-' + revs[1];
        revs = null;
    }

    return doc;
};

/**
 * Parse the revision of a document
 * and return object with version and hash
 * @param {Document} doc
 * @return {Object}
 * @module util/document
 */
exports.revision = (doc) => {
    if(typeof doc._rev === 'string') {
        let revs = doc._rev.split('-');

        return {
            version: parseInt(revs[0], 10),
            hash: revs[1],
        };
    } else {
        return doc._rev;
    }
};