text:
<?php

namespace PhpGitHooks\Tests\Application\Config;

use PhpGitHooks\Application\Config\ConfigFile;
use PhpGitHooks\Infrastructure\Config\InvalidConfigStructureException;
use PhpGitHooks\Infrastructure\Disk\Config\InMemoryConfigFileReader;

class ConfigFileTest extends \PHPUnit_Framework_TestCase
{
    /** @var  ConfigFile */
    private $configFile;
    /** @var  InMemoryConfigFileReader */
    private $configFileReader;

    protected function setUp()
    {
        $this->configFileReader = new InMemoryConfigFileReader();
        $this->configFile = new ConfigFile($this->configFileReader);
    }

    /**
     * @test
     */
    public function getPreCommitConfiguration()
    {
        $this->configFileReader->fileContents = ['pre-commit' => [
            'enabled' => true,
            'execute' => [],
        ]];

        $configData = $this->configFile->getPreCommitConfiguration();

        $this->assertSame([], $configData);
    }

    /**
     * @throws InvalidConfigStructureException
     *
     * @test
     */
    public function getPreCommitConfigurationThrowsException()
    {
        $this->setExpectedException(InvalidConfigStructureException::class);
        $this->configFileReader->fileContents = [];

        $this->configFile->getPreCommitConfiguration();
    }

    /**
     * @test
     */
    public function getCommitMsgConfiguration()
    {
        $this->configFileReader->fileContents = ['commit-msg' => [
            'enabled' => true,
            'regular-expression' => 'dkdklsls',
        ]];

        $configData = $this->configFile->getMessageCommitConfiguration();

        $this->assertArrayHasKey('enabled', $configData);
        $this->assertArrayHasKey('regular-expression', $configData);
    }

    /**
     * @throws InvalidConfigStructureException
     *
     * @test
     */
    public function getCommitMsgConfigurationThrowsException()
    {
        $this->setExpectedException(InvalidConfigStructureException::class);
        $this->configFileReader->fileContents = ['commit-msg' => []];

        $this->configFile->getMessageCommitConfiguration();
    }

    /**
     * @throws InvalidConfigStructureException
     *
     * @test
     */
    public function getCommitMsgConfigurationWithoutRegExpThrowsException()
    {
        $this->setExpectedException(InvalidConfigStructureException::class);
        $this->configFileReader->fileContents = ['commit-msg' => [
            'enabled' => true
        ]];

        $this->configFile->getMessageCommitConfiguration();
    }
}


text:
================================
 OpenStack-Ansible Release Notes
================================

.. toctree::
   :maxdepth: 1

   unreleased

redpajama_set_name: RedPajamaGithub


text:
module Authenticable
  # Overwrite devise current user
  # def current_author
  #   @current_author ||= Author.find_by(auth_token: request.headers['Authorization'])
  # end

  # def authenticate_with_token!
  #   render json: { errors: "Not authenticate" } unless author_logined_in?
  # end

  # def author_logined_in?
  #   current_author.present?
  # end

end


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;

namespace Xceed.Wpf.DataGrid
{
  public class GroupLevelDescriptionCollection : ReadOnlyObservableCollection<GroupLevelDescription>
  {
    public GroupLevelDescriptionCollection()
      : base( new ObservableCollection<GroupLevelDescription>() )
    {
    }

    internal void Add( GroupLevelDescription info )
    {
      this.Items.Add( info );
    }

    internal void Insert( int index, GroupLevelDescription info )
    {
      this.Items.Insert( index, info );
    }

    internal bool Remove( GroupLevelDescription info )
    {
      return this.Items.Remove( info );
    }

    internal void RemoveAt( int index )
    {
      this.Items.RemoveAt( index );
    }

    internal void Clear()
    {
      this.Items.Clear();
    }
  }
}


text:
A python tool to convert records from fixed-width and delimited files into dictionaries

## Summary
The **textrecords** package provides a simple API for converting delimited and fixed-width text records into
dictionaries and vice-versa. Features include:

* nested parse rules
* a parse rule builder
* support for multiple record types in the same stream
* support for json-schema validation

## JSON schema
This project does not attempt to reproduce the functionality of a schema validator. Instead, **textrecords**
requires the minimum information to convert a line of text into a json-like data structure. Schema validation
can be achieved by including a json schema in the text record parse rule, either directly or by reference.


text:
PyAutoGUI
=========

PyAutoGUI is a  cross-platform GUI automation Python module for human beings. Used to programmatically control the mouse & keyboard.

Full documentation available at https://pyautogui.readthedocs.org

Source code available at https://github.com/asweigart/pyautogui

Dependencies
============

If you are installing PyAutoGUI from PyPI using pip:

Windows has no dependencies. The Win32 extensions do not need to be installed.

OS X needs the pyobjc-core and pyobjc module installed (in that order).

Linux needs the python3-Xlib (or python-Xlib for Python 2) module installed.

Pillow needs to be installed, and on Linux you may need to install additional libraries to make sure Pillow's PNG/JPEG works correctly. See:

    https://stackoverflow.com/questions/7648200/pip-install-pil-e-tickets-1-no-jpeg-png-support

    http://ubuntuforums.org/showthread.php?t=1751455

If you want to do development and contribute to PyAutoGUI, you will need to install these modules from PyPI:

* pyscreeze
* pymsgbox
* pytweening

Example Usage
=============

Keyboard and Mouse Control
--------------------------

    >>> import pyautogui
    >>> screenWidth, screenHeight = pyautogui.size()
    >>> currentMouseX, currentMouseY = pyautogui.position()
    >>> pyautogui.moveTo(100, 150)
    >>> pyautogui.click()
    >>> pyautogui.moveRel(None, 10)  # move mouse 10 pixels down
    >>> pyautogui.doubleClick()
    >>> pyautogui.moveTo(500, 500, duration=2, tween=pyautogui.tweens.easeInOutQuad)  # use tweening/easing function to move mouse over 2 seconds.
    >>> pyautogui.typewrite('Hello world!', interval=0.25)  # type with quarter-second pause in between each key
    >>> pyautogui.press('esc')
    >>> pyautogui.keyDown('shift')
    >>> pyautogui.typewrite(['left', 'left', 'left', 'left', 'left', 'left'])
    >>> pyautogui.keyUp('shift')
    >>> pyautogui.hotkey('ctrl', 'c')

Display Message Boxes
---------------------

    >>> import pyautogui
    >>> pyautogui.alert('This is an alert box.')
    'OK'
    >>> pyautogui.confirm('Shall I proceed?')
    'Cancel'
    >>> pyautogui.confirm('Enter option.', buttons=['A', 'B', 'C'])
    'B'
    >>> pyautogui.prompt('What is your name?')
    'Al'
    >>> pyautogui.password('Enter password (text will be hidden)')
    'swordfish'

Screenshot Functions
--------------------

(PyAutoGUI uses Pillow for image-related features.)

    >>> import pyautogui
    >>> im1 = pyautogui.screenshot()
    >>> im1.save('my_screenshot.png')
    >>> im2 = pyautogui.screenshot('my_screenshot2.png')

You can also locate where an image is on the screen:

    >>> import pyautogui
    >>> button7location = pyautogui.locateOnScreen('button.png') # returns (left, top, width, height) of matching region
    >>> button7location
    (1416, 562, 50, 41)
    >>> buttonx, buttony = pyautogui.center(button7location)
    >>> buttonx, buttony
    (1441, 582)
    >>> pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found

The locateCenterOnScreen() function returns the center of this match region:

    >>> import pyautogui
    >>> buttonx, buttony = pyautogui.locateCenterOnScreen('button.png') # returns (x, y) of matching region
    >>> buttonx, buttony
    (1441, 582)
    >>> pyautogui.click(buttonx, buttony)  # clicks the center of where the button was found


text:
+++
title = "Bitcoin"
shortcode = "~mister-dister-dozzod-dozzod"
license = "MIT"
image = "https://urbit.ewr1.vultrobjects.com/hastuc-dibtux/2021.8.24..02.57.38-bitcoin.svg"
bgColor = "#EB9452"
developer = "~zod"
website = "https://tlon.io"
+++

Urbit's Bitcoin wallet enables your ship to connect to a `%btc-provider` for easier selection  of a trusted full node and then helps construct a bitcoin transaction to an urbit ship without needing to deal with remembering or directly exchanging public addresses.


text:
package org.apache.sling.resourceresolver.impl;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.sling.api.resource.LoginException;
import org.apache.sling.api.resource.NonExistingResource;
import org.apache.sling.api.resource.Resource;
import org.apache.sling.api.resource.ResourceDecorator;
import org.apache.sling.api.resource.ResourceMetadata;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceUtil;
import org.apache.sling.api.resource.ValueMap;
import org.apache.sling.resourceresolver.impl.helper.ResourceDecoratorTracker;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderHandler;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderStorage;
import org.apache.sling.resourceresolver.impl.providers.ResourceProviderStorageProvider;
import org.apache.sling.spi.resource.provider.QueryLanguageProvider;
import org.apache.sling.spi.resource.provider.ResolveContext;
import org.apache.sling.spi.resource.provider.ResourceContext;
import org.apache.sling.spi.resource.provider.ResourceProvider;
import org.junit.Before;
import org.mockito.Mockito;

/** Base class for tests that involve ResourceDecorators */
public abstract class ResourceDecoratorTestBase {

    protected ResourceResolver resolver;
    protected static final String QUERY_LANGUAGE = "some.funnny.language";

    protected abstract Resource wrapResourceForTest(Resource resource);

    @Before
    public void setup() throws LoginException {
        final ResourceDecorator d = new ResourceDecorator() {
            @Override
            public Resource decorate(Resource resource) {
                return ResourceDecoratorTestBase.this.wrapResourceForTest(resource);
            }

            @Override
            public Resource decorate(Resource resource, HttpServletRequest request) {
                throw new UnsupportedOperationException("Not supposed to be used in these tests");
            }

        };

        final ResourceDecoratorTracker t = new ResourceDecoratorTracker();
        t.bindResourceDecorator(d, null);

        final ResourceProvider<?> provider = new ResourceProvider<Object>() {

            @Override
            public QueryLanguageProvider<Object> getQueryLanguageProvider() {
                return new QueryLanguageProvider<Object>() {

                    @Override
                    public String[] getSupportedLanguages(ResolveContext<Object> ctx) {
                        return new String[] { QUERY_LANGUAGE };
                    }

                    @Override
                    public Iterator<Resource> findResources(ResolveContext<Object> ctx, String query, String language) {
                        final List<Resource> found = new ArrayList<Resource>();
                        found.add(mockResource("/tmp/C"));
                        found.add(mockResource("/tmp/D"));
                        found.add(mockResource("/var/one"));
                        found.add(mockResource("/var/two"));
                        return found.iterator();
                    }

                    @Override
                    public Iterator<ValueMap> queryResources(ResolveContext<Object> ctx, String query, String language) {
                        return null;
                    }
                };
            }

            @Override
            public Resource getResource(ResolveContext<Object> ctx, String path, final ResourceContext rCtx, Resource parent) {
                if(path.equals("/") || path.startsWith("/tmp") || path.startsWith("/var")) {
                    return mockResource(path);
                }
                return null;
            }

            @Override
            public Iterator<Resource> listChildren(ResolveContext<Object> ctx, Resource parent) {
                final List<Resource> children = new ArrayList<Resource>();
                if("/".equals(parent.getPath())) {
                    children.add(mockResource("/tmp"));
                    children.add(mockResource("/var"));
                } else if("/var".equals(parent.getPath())) {
                    children.add(mockResource("/var/one"));
                    children.add(mockResource("/var/two"));
                    children.add(mockResource("/var/three"));
                } else if("/tmp".equals(parent.getPath())) {
                    children.add(mockResource("/tmp/A"));
                    children.add(mockResource("/tmp/B"));
                    children.add(mockResource("/tmp/C"));
                    children.add(mockResource("/tmp/D"));
                }
                return children.iterator();
            }

        };

        ResourceResolverFactoryActivator activator = new ResourceResolverFactoryActivator();
        final CommonResourceResolverFactoryImpl crf = new CommonResourceResolverFactoryImpl(activator) {
            @Override
            public ResourceDecoratorTracker getResourceDecoratorTracker() {
                return t;
            }

            @Override
            public ResourceAccessSecurityTracker getResourceAccessSecurityTracker() {
                return new ResourceAccessSecurityTracker();
            }
        };

        final List<ResourceProviderHandler> list = Arrays.asList(MockedResourceResolverImplTest.createRPHandler(provider, "A-provider", 0L, "/"));
        resolver = new ResourceResolverImpl(crf, false, null, new ResourceProviderStorageProvider() {

            @Override
            public ResourceProviderStorage getResourceProviderStorage() {
                return new ResourceProviderStorage(list);
            }
        });
    }

    protected void assertExistent(Resource r, boolean existent) {
        assertNotNull("Expecting non-null Resource", r);
        assertEquals("Expecting " + (existent ? "existent" : "non-existent") + " resource",
                existent,
                !NonExistingResource.RESOURCE_TYPE_NON_EXISTING.equals(r.getResourceType()));
    }

    protected Resource mockResource(String path) {
        final Resource result = Mockito.mock(Resource.class);
        Mockito.when(result.getPath()).thenReturn(path);
        Mockito.when(result.getName()).thenReturn(ResourceUtil.getName(path));
        final ResourceMetadata m = new ResourceMetadata();
        Mockito.when(result.getResourceMetadata()).thenReturn(m);
        return result;
    }
}


text:
'use strict';

const fastclick = require('fastclick');

import {domReady} from '@alexistessier/dom';

domReady(()=>{
    fastclick.attach(document.body);
});


text:
<?xml version='1.0' encoding='utf-8'?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="f09f0840-172e-4754-87e5-ba6faa30528b">
    <SourceTemplate><![CDATA[<?xml version="1.0" encoding="utf-8"?>
<Jobs>
  <ApplicationJob xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Guid="0fb30714-8ed0-4611-8f1b-cb8fec9dae91">
    <WebsiteUrl />
    <UserAgent>Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19</UserAgent>
    <UserNotes />
    <LastFileSize>384846</LastFileSize>
    <LastFileDate>2012-05-23T02:09:37.7748325</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>StartEnd</VariableType>
            <Regex />
            <Url><placeholder name="Url with version information" value="https://camunda.org/download/modeler/" /></Url>
            <StartText>

    7-Zip </StartText>
            <EndText>
</EndText>
            <TextualContent />
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url64</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>""</TextualContent>
            <Name>url64</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation />
    <DeletePreviousFile>true</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2012-05-23T02:09:37.7748325</LastUpdated>
    <TargetPath>C:\Chocolatey\_work\</TargetPath>
    <FixedDownloadUrl><placeholder name="Download Url - Optional" value="" /></FixedDownloadUrl>
    <Name><placeholder name="Name" value="Camunda Modeler" /></Name>
  </ApplicationJob>
</Jobs>]]></SourceTemplate>
    <WebsiteUrl />
    <UserAgent>Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19</UserAgent>
    <UserNotes />
    <LastFileSize>47683663</LastFileSize>
    <LastFileDate>2016-07-18T09:17:18-04:00</LastFileDate>
    <IgnoreFileInformation>false</IgnoreFileInformation>
    <DownloadBeta>Default</DownloadBeta>
    <DownloadDate xsi:nil="true" />
    <CheckForUpdatesOnly>false</CheckForUpdatesOnly>
    <VariableChangeIndicator />
    <HashVariable />
    <HashType>None</HashType>
    <CanBeShared>true</CanBeShared>
    <ShareApplication>false</ShareApplication>
    <ExclusiveDownload>false</ExclusiveDownload>
    <HttpReferer />
    <SetupInstructions />
    <Variables>
      <item>
        <key>
          <string>version</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>StartEnd</VariableType>
            <Regex />
            <Url>https://camunda.org/download/modeler/</Url>
            <StartText>camunda-modeler-</StartText>
            <EndText>-win32-ia32.zip</EndText>
            <TextualContent />
            <Name>version</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>url64</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>Textual</VariableType>
            <Regex />
            <TextualContent>""</TextualContent>
            <Name>url64</Name>
          </UrlVariable>
        </value>
      </item>
      <item>
        <key>
          <string>DownloadURL</string>
        </key>
        <value>
          <UrlVariable>
            <RegexRightToLeft>false</RegexRightToLeft>
            <VariableType>StartEnd</VariableType>
            <Regex />
            <Url>https://camunda.org/download/modeler/</Url>
            <StartText><a class="download-modeler" href="</StartText>
            <EndText>">camunda-modeler</EndText>
            <Name>DownloadURL</Name>
          </UrlVariable>
        </value>
      </item>
    </Variables>
    <ExecuteCommand />
    <ExecutePreCommand />
    <ExecuteCommandType>Batch</ExecuteCommandType>
    <ExecutePreCommandType>Batch</ExecutePreCommandType>
    <Category />
    <SourceType>FixedUrl</SourceType>
    <PreviousLocation>C:\Chocolatey\_work\camunda-modeler-1.2.1-win32-ia32.zip</PreviousLocation>
    <DeletePreviousFile>true</DeletePreviousFile>
    <Enabled>true</Enabled>
    <FileHippoId />
    <LastUpdated>2016-07-25T16:20:52.7535676-04:00</LastUpdated>
    <TargetPath>C:\Chocolatey\_work\</TargetPath>
    <FixedDownloadUrl>{DownloadURL}</FixedDownloadUrl>
    <Name>camunda-modeler</Name>
  </ApplicationJob>
</Jobs>


text:
namespace QuickUnity.Events
{
    /// <summary>
    /// The Event class is used as the base class for the creation of Event objects, which are passed as parameters to event listeners when an event occurs.
    /// </summary>
    public class Event
    {
        /// <summary>
        /// The type of event.
        /// </summary>
        private string eventType;

        /// <summary>
        /// The type of event.
        /// </summary>
        /// <value>The type of event.</value>
        public string EventType
        {
            get { return eventType; }
        }

        /// <summary>
        /// Gets or sets the context object.
        /// </summary>
        /// <value>The context object.</value>
        public object Context
        {
            get;
            set;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Event"/> class.
        /// </summary>
        /// <param name="eventType">The type of event.</param>
        /// <param name="context">The context object.</param>
        public Event(string eventType, object context = null)
        {
            this.eventType = eventType;
            Context = context;
        }
    }
}


text:
#include "config.h"
#include "platform/graphics/PathTraversalState.h"

#include "core/svg/SVGPathTraversalStateBuilder.h"

namespace blink {

SVGPathTraversalStateBuilder::SVGPathTraversalStateBuilder()
    : m_traversalState(0)
{
}

void SVGPathTraversalStateBuilder::moveTo(const FloatPoint& targetPoint, bool, PathCoordinateMode)
{
    ASSERT(m_traversalState);
    m_traversalState->m_totalLength += m_traversalState->moveTo(targetPoint);
}

void SVGPathTraversalStateBuilder::lineTo(const FloatPoint& targetPoint, PathCoordinateMode)
{
    ASSERT(m_traversalState);
    m_traversalState->m_totalLength += m_traversalState->lineTo(targetPoint);
}

void SVGPathTraversalStateBuilder::curveToCubic(const FloatPoint& point1, const FloatPoint& point2, const FloatPoint& targetPoint, PathCoordinateMode)
{
    ASSERT(m_traversalState);
    m_traversalState->m_totalLength += m_traversalState->cubicBezierTo(point1, point2, targetPoint);
}

void SVGPathTraversalStateBuilder::closePath()
{
    ASSERT(m_traversalState);
    m_traversalState->m_totalLength += m_traversalState->closeSubpath();
}

void SVGPathTraversalStateBuilder::setDesiredLength(float desiredLength)
{
    ASSERT(m_traversalState);
    m_traversalState->m_desiredLength = desiredLength;
}

bool SVGPathTraversalStateBuilder::continueConsuming()
{
    ASSERT(m_traversalState);
    m_traversalState->processSegment();
    return !m_traversalState->m_success;
}

void SVGPathTraversalStateBuilder::incrementPathSegmentCount()
{
    ASSERT(m_traversalState);
    ++m_traversalState->m_segmentIndex;
}

unsigned SVGPathTraversalStateBuilder::pathSegmentIndex()
{
    ASSERT(m_traversalState);
    return m_traversalState->m_segmentIndex;
}

float SVGPathTraversalStateBuilder::totalLength()
{
    ASSERT(m_traversalState);
    return m_traversalState->m_totalLength;
}

FloatPoint SVGPathTraversalStateBuilder::currentPoint()
{
    ASSERT(m_traversalState);
    return m_traversalState->m_current;
}

}


text:
#ifndef QT3D_RENDER_TEXTUREDATAMANAGER_H
#define QT3D_RENDER_TEXTUREDATAMANAGER_H

#include <Qt3DCore/private/qresourcemanager_p.h>
#include <Qt3DRenderer/qtexture.h>
#include <Qt3DRenderer/texturedata.h>
#include <Qt3DRenderer/private/handle_types_p.h>

#include <QPair>
#include <Qt3DCore/qnodeid.h>

QT_BEGIN_NAMESPACE

namespace Qt3D {

namespace Render {

typedef QPair<QTextureDataFunctorPtr, QVector<HTextureImage> > FunctorImageHandlesPair;
typedef QPair<QTextureDataFunctorPtr, HTextureData> FunctorTextureDataPair;

class TextureDataManager : public QResourceManager<TexImageData,
                                                   QNodeId,
                                                   16,
                                                   Qt3D::ArrayAllocatingPolicy,
                                                   Qt3D::ObjectLevelLockingPolicy>
{
public:
    TextureDataManager();
    void addToPendingTextures(const QNodeId &textureId);

    QVector<QNodeId> texturesPending();

    HTextureData textureDataFromFunctor(const QTextureDataFunctorPtr &functor) const;
    void addTextureDataForFunctor(HTextureData textureDataHandle, const QTextureDataFunctorPtr &functor);
    void removeTextureDataFunctor(const QTextureDataFunctorPtr &functor);

    void assignFunctorToTextureImage(const QTextureDataFunctorPtr &functor, HTextureImage imageHandle);

    QMutex *mutex() const;
    void cleanup();

private:
    QVector<QNodeId> m_texturesPending;
    QVector<FunctorTextureDataPair > m_textureDataFunctors;
    QVector<FunctorImageHandlesPair > m_texturesImagesPerFunctor;
    mutable QMutex m_mutex;
    QVector<HTextureData> m_textureHandlesToRelease;
};

} // Render

Q_DECLARE_RESOURCE_INFO(TexImageData, Q_REQUIRES_CLEANUP);

} // Qt3D

QT_END_NAMESPACE

#endif // TEXTUREDATAMANAGER_H


text:
angular.module('hljs', [])

.controller('HljsCtrl', [function HljsCtrl () {
  var ctrl = this;

  var _elm = null,
      _lang = null,
      _code = null;

  ctrl.init = function (codeElm) {
    _elm = codeElm;
  };

  ctrl.setLanguage = function (lang) {
    _lang = lang;

    if (_code) {
      ctrl.highlight(_code);
    }
  };

  ctrl.highlight = function (code) {
    if (!_elm) {
      return;
    }

    var res;

    _code = code;

    if (_lang) {
      // language specified
      res = hljs.highlight(_lang, _code, true);
    }
    else {
      // language auto-detect
      res = hljs.highlightAuto(_code);
    }

    _elm.html(res.value);
  };

  ctrl.clear = function () {
    if (!_elm) {
      return;
    }
    _code = null;
    _elm.text('');
  };

  ctrl.release = function () {
    _elm = null;
  };
}])

.directive('hljs', [function () {
  return {
    restrict: 'EA',
    controller: 'HljsCtrl',
    compile: function(tElm, tAttrs, transclude) {
      // get static code
      // strip the starting "new line" character
      var staticCode = tElm[0].innerHTML.replace(/^\r\n|\r|\n/, '');

      // put template
      tElm.html('

');

      return function postLink(scope, iElm, iAttrs, ctrl) {
        ctrl.init(iElm.find('code'));

        if (staticCode) {
          ctrl.highlight(staticCode);
        }

        scope.$on('$destroy', function () {
          ctrl.release();
        });
      };
    }
  };
}])

.directive('language', [function () {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function (scope, iElm, iAttrs, ctrl) {

      iAttrs.$observe('language', function (lang) {
        if (angular.isDefined(lang)) {
          ctrl.setLanguage(lang);
        }
      });
    }
  };
}])

.directive('source', [function () {
  return {
    require: 'hljs',
    restrict: 'A',
    link: function(scope, iElm, iAttrs, ctrl) {

      scope.$watch(iAttrs.source, function (newCode, oldCode) {
        if (newCode) {
          ctrl.highlight(newCode);
        }
        else {
          ctrl.clear();
        }
      });
    }
  };
}])

.directive('include', [
         '$http', '$templateCache', '$q',
function ($http,   $templateCache,   $q) {
  return {
    require: 'hljs',
    restrict: 'A',
    compile: function(tElm, tAttrs, transclude) {
      var srcExpr = tAttrs.include;

      return function postLink(scope, iElm, iAttrs, ctrl) {
        var changeCounter = 0;

        scope.$watch(srcExpr, function (src) {
          var thisChangeId = ++changeCounter;

          if (src && angular.isString(src)) {
            var templateCachePromise, dfd;

            templateCachePromise = $templateCache.get(src);
            if (!templateCachePromise) {
              dfd = $q.defer();
              $http.get(src, {cache: $templateCache}).success(function (code) {
                if (thisChangeId !== changeCounter) {
                  return;
                }
                dfd.resolve(code);
              }).error(function() {
                if (thisChangeId === changeCounter) {
                  ctrl.clear();
                }
                dfd.resolve();
              });
              templateCachePromise = dfd.promise;
            }

            $q.when(templateCachePromise)
            .then(function (code) {
              if (!code) {
                return;
              }

              // $templateCache from $http
              if (angular.isArray(code)) {
                // 1.1.5
                code = code[1];
              }
              else if (angular.isObject(code)) {
                // 1.0.7
                code = code.data;
              }

              code = code.replace(/^\r\n|\r|\n/, '');
              ctrl.highlight(code);
            });
          }
          else {
            ctrl.clear();
          }
        });
      };
    }
  };
}]);


text:
//
//  CalendarView.m
//  HiHome
//
//  Created by 王建成 on 15/9/23.
//  Copyright © 2015年 zykj. All rights reserved.
//

#import "CalendarView.h"

@interface CalendarView()
{
    NSMutableDictionary *eventsByDate;
}
@end

@implementation CalendarView

- (void)viewInit
{
    self.calendar = [JTCalendar new];

    // All modifications on calendarAppearance have to be done before setMenuMonthsView and setContentView
    // Or you will have to call reloadAppearance
    {
        self.calendar.calendarAppearance.calendar.firstWeekday = 2; // Sunday == 1, Saturday == 7
        self.calendar.calendarAppearance.dayCircleRatio = 9. / 10.;
        self.calendar.calendarAppearance.ratioContentMenu = 2.;
        self.calendar.calendarAppearance.focusSelectedDayChangeMode = YES;

        // Customize the text for each month
        self.calendar.calendarAppearance.monthBlock = ^NSString *(NSDate *date, JTCalendar *jt_calendar){
            NSCalendar *calendar = jt_calendar.calendarAppearance.calendar;
            NSDateComponents *comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth fromDate:date];
            NSInteger currentMonthIndex = comps.month;

            static NSDateFormatter *dateFormatter;
            if(!dateFormatter){
                dateFormatter = [NSDateFormatter new];
                dateFormatter.timeZone = jt_calendar.calendarAppearance.calendar.timeZone;
            }

            while(currentMonthIndex <= 0){
                currentMonthIndex += 12;
            }

            NSString *monthText = [[dateFormatter standaloneMonthSymbols][currentMonthIndex - 1] capitalizedString];

            return [NSString stringWithFormat:@"%ld\n%@", comps.year, monthText];
        };
    }

    [self.calendar setMenuMonthsView:self.calendarMenuView];
    [self.calendar setContentView:self.calendarContentView];
    [self.calendar setDataSource:self];

    [self createRandomEvents];

    [self.calendar reloadData];
}

- (void)viewDidLayoutSubviews
{
    [self.calendar repositionViews];
}

#pragma mark - Buttons callback
//
//- (IBAction)didGoTodayTouch
//{
//    [self.calendar setCurrentDate:[NSDate date]];
//}
//
//- (IBAction)didChangeModeTouch
//{
//    self.calendar.calendarAppearance.isWeekMode = !self.calendar.calendarAppearance.isWeekMode;
//
//    [self transitionExample];
//}

#pragma mark - JTCalendarDataSource

- (BOOL)calendarHaveEvent:(JTCalendar *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];

    if(eventsByDate[key] && [eventsByDate[key] count] > 0){
        return YES;
    }

    return NO;
}

- (void)calendarDidDateSelected:(JTCalendar *)calendar date:(NSDate *)date
{
    NSString *key = [[self dateFormatter] stringFromDate:date];
    NSArray *events = eventsByDate[key];

    NSLog(@"Date: %@ - %ld events", date, [events count]);
}

- (void)calendarDidLoadPreviousPage
{
    NSLog(@"Previous page loaded");
}

- (void)calendarDidLoadNextPage
{
    NSLog(@"Next page loaded");
}

#pragma mark - Transition examples

- (void)transitionExample
{
    CGFloat newHeight = 300;
    if(self.calendar.calendarAppearance.isWeekMode){
        newHeight = 75.;
    }

    [UIView animateWithDuration:.5
                     animations:^{
                         self.calendarContentViewHeight.constant = newHeight;
                         [self layoutIfNeeded];
                     }];

    [UIView animateWithDuration:.25
                     animations:^{
                         self.calendarContentView.layer.opacity = 0;
                     }
                     completion:^(BOOL finished) {
                         [self.calendar reloadAppearance];

                         [UIView animateWithDuration:.25
                                          animations:^{
                                              self.calendarContentView.layer.opacity = 1;
                                          }];
                     }];
}

#pragma mark - Fake data

- (NSDateFormatter *)dateFormatter
{
    static NSDateFormatter *dateFormatter;
    if(!dateFormatter){
        dateFormatter = [NSDateFormatter new];
        dateFormatter.dateFormat = @"dd-MM-yyyy";
    }

    return dateFormatter;
}

- (void)createRandomEvents
{
    eventsByDate = [NSMutableDictionary new];

    for(int i = 0; i < 30; ++i){
        // Generate 30 random dates between now and 60 days later
        NSDate *randomDate = [NSDate dateWithTimeInterval:(rand() % (3600 * 24 * 60)) sinceDate:[NSDate date]];

        // Use the date as key for eventsByDate
        NSString *key = [[self dateFormatter] stringFromDate:randomDate];

        if(!eventsByDate[key]){
            eventsByDate[key] = [NSMutableArray new];
        }

        [eventsByDate[key] addObject:randomDate];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end


text:
from flask import Blueprint, render_template, request, Response
from flask import redirect, make_response

from grano.lib.serialisation import jsonify
from grano.lib.args import object_or_404
from grano.model import Project, Permission, Pipeline, LogEntry
from grano.lib.pager import Pager
from grano.core import app, db, url_for
from grano.views.cache import validate_cache
from grano import authz

blueprint = Blueprint('log_entries_api', __name__)

@blueprint.route('/api/1/pipelines/<pipeline_id>/log', methods=['GET'])
def index(pipeline_id):
    pipeline = object_or_404(Pipeline.by_id(pipeline_id))
    authz.require(authz.project_read(pipeline.project))

    query = LogEntry.all()
    query = query.filter(LogEntry.pipeline==pipeline)

    if request.args.get('level'):
        query = query.filter(LogEntry.level==request.args.get('level'))

    pager = Pager(query)
    validate_cache(keys=pager.cache_keys())
    return jsonify(pager, index=True)

@blueprint.route('/api/1/pipelines/<pipeline_id>/log/<id>', methods=['GET'])
def view(pipeline_id, id):
    pipeline = object_or_404(Pipeline.by_id(pipeline_id))
    authz.require(authz.project_read(pipeline.project))
    log_entry = object_or_404(LogEntry.by_id(id))
    return jsonify(log_entry)


text:
/* Generated by camel build tools - do NOT edit this file! */
package org.apache.camel.component.ganglia;

import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.spi.ExtendedPropertyConfigurerGetter;
import org.apache.camel.spi.PropertyConfigurerGetter;
import org.apache.camel.spi.ConfigurerStrategy;
import org.apache.camel.spi.GeneratedPropertyConfigurer;
import org.apache.camel.util.CaseInsensitiveMap;
import org.apache.camel.support.component.PropertyConfigurerSupport;

/**
 * Generated by camel build tools - do NOT edit this file!
 */
@SuppressWarnings("unchecked")
public class GangliaComponentConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter {

    private org.apache.camel.component.ganglia.GangliaConfiguration getOrCreateConfiguration(GangliaComponent target) {
        if (target.getConfiguration() == null) {
            target.setConfiguration(new org.apache.camel.component.ganglia.GangliaConfiguration());
        }
        return target.getConfiguration();
    }

    @Override
    public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
        GangliaComponent target = (GangliaComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": target.setAutowiredEnabled(property(camelContext, boolean.class, value)); return true;
        case "configuration": target.setConfiguration(property(camelContext, org.apache.camel.component.ganglia.GangliaConfiguration.class, value)); return true;
        case "dmax": getOrCreateConfiguration(target).setDmax(property(camelContext, int.class, value)); return true;
        case "groupname":
        case "groupName": getOrCreateConfiguration(target).setGroupName(property(camelContext, java.lang.String.class, value)); return true;
        case "lazystartproducer":
        case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
        case "metricname":
        case "metricName": getOrCreateConfiguration(target).setMetricName(property(camelContext, java.lang.String.class, value)); return true;
        case "mode": getOrCreateConfiguration(target).setMode(property(camelContext, info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode.class, value)); return true;
        case "prefix": getOrCreateConfiguration(target).setPrefix(property(camelContext, java.lang.String.class, value)); return true;
        case "slope": getOrCreateConfiguration(target).setSlope(property(camelContext, info.ganglia.gmetric4j.gmetric.GMetricSlope.class, value)); return true;
        case "spoofhostname":
        case "spoofHostname": getOrCreateConfiguration(target).setSpoofHostname(property(camelContext, java.lang.String.class, value)); return true;
        case "tmax": getOrCreateConfiguration(target).setTmax(property(camelContext, int.class, value)); return true;
        case "ttl": getOrCreateConfiguration(target).setTtl(property(camelContext, int.class, value)); return true;
        case "type": getOrCreateConfiguration(target).setType(property(camelContext, info.ganglia.gmetric4j.gmetric.GMetricType.class, value)); return true;
        case "units": getOrCreateConfiguration(target).setUnits(property(camelContext, java.lang.String.class, value)); return true;
        case "wireformat31x":
        case "wireFormat31x": getOrCreateConfiguration(target).setWireFormat31x(property(camelContext, boolean.class, value)); return true;
        default: return false;
        }
    }

    @Override
    public Class<?> getOptionType(String name, boolean ignoreCase) {
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return boolean.class;
        case "configuration": return org.apache.camel.component.ganglia.GangliaConfiguration.class;
        case "dmax": return int.class;
        case "groupname":
        case "groupName": return java.lang.String.class;
        case "lazystartproducer":
        case "lazyStartProducer": return boolean.class;
        case "metricname":
        case "metricName": return java.lang.String.class;
        case "mode": return info.ganglia.gmetric4j.gmetric.GMetric.UDPAddressingMode.class;
        case "prefix": return java.lang.String.class;
        case "slope": return info.ganglia.gmetric4j.gmetric.GMetricSlope.class;
        case "spoofhostname":
        case "spoofHostname": return java.lang.String.class;
        case "tmax": return int.class;
        case "ttl": return int.class;
        case "type": return info.ganglia.gmetric4j.gmetric.GMetricType.class;
        case "units": return java.lang.String.class;
        case "wireformat31x":
        case "wireFormat31x": return boolean.class;
        default: return null;
        }
    }

    @Override
    public Object getOptionValue(Object obj, String name, boolean ignoreCase) {
        GangliaComponent target = (GangliaComponent) obj;
        switch (ignoreCase ? name.toLowerCase() : name) {
        case "autowiredenabled":
        case "autowiredEnabled": return target.isAutowiredEnabled();
        case "configuration": return target.getConfiguration();
        case "dmax": return getOrCreateConfiguration(target).getDmax();
        case "groupname":
        case "groupName": return getOrCreateConfiguration(target).getGroupName();
        case "lazystartproducer":
        case "lazyStartProducer": return target.isLazyStartProducer();
        case "metricname":
        case "metricName": return getOrCreateConfiguration(target).getMetricName();
        case "mode": return getOrCreateConfiguration(target).getMode();
        case "prefix": return getOrCreateConfiguration(target).getPrefix();
        case "slope": return getOrCreateConfiguration(target).getSlope();
        case "spoofhostname":
        case "spoofHostname": return getOrCreateConfiguration(target).getSpoofHostname();
        case "tmax": return getOrCreateConfiguration(target).getTmax();
        case "ttl": return getOrCreateConfiguration(target).getTtl();
        case "type": return getOrCreateConfiguration(target).getType();
        case "units": return getOrCreateConfiguration(target).getUnits();
        case "wireformat31x":
        case "wireFormat31x": return getOrCreateConfiguration(target).isWireFormat31x();
        default: return null;
        }
    }
}


text:
CWD="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
SCRIPT_DIR=$(dirname "$0")
HOME_DIR=$SCRIPT_DIR/..

cd $HOME_DIR
rm -rf dist/*
python3 setup.py sdist
python3 setup.py bdist_wheel --universal
twine upload dist/*
cd $CWD


text:
<ModuleInfoEntry>
    <Module Name="gucefMULTIPLAY" Type="SharedLibrary" Platform="All" Tags="platform">
        <Dependencies>
            <Dependency Name="gucefHeaders" />
            <Dependency Name="gucefMT" />
            <Dependency Name="gucefCORE" />
            <Dependency Name="gucefCOMCORE" />
            <Dependency Name="gucefCOM" />
        </Dependencies>
        <Linker>
            <Dependency Name="gucefMT" />
            <Dependency Name="gucefCORE" />
            <Dependency Name="gucefCOMCORE" />
            <Dependency Name="gucefCOM" />
        </Linker>
        <Preprocessor>
            <Define String="GUCEFMULTIPLAY_BUILD_MODULE" />
        </Preprocessor>
    </Module>
</ModuleInfoEntry>


text:
Code for [AI Explorables](http://pair.withgoogle.com/explorables/)

Make changes in `source` and view locally with:

```
yarn && yarn start
open http://localhost:2344/
```

**This is not an officially supported Google product**


text:
#include "Parts.h"

class CShoes :public CParts
{
public:
	CShoes(std::shared_ptr<CTask> task, Float2 pos, int page, Float2 parts_pos = Float2(0, 0));

private:
	void PartsDraw();
};


text:
package kafka

import (
  "log"
  "net"
  "os"
  "fmt"
  "encoding/binary"
  "io"
  "bufio"
)

const (
  NETWORK = "tcp"
)

type Broker struct {
  topic     string
  partition int
  hostname  string
}

func newBroker(hostname string, topic string, partition int) *Broker {
  return &Broker{topic: topic,
    partition: partition,
    hostname:  hostname}
}

func (b *Broker) connect() (conn *net.TCPConn, error os.Error) {
  raddr, err := net.ResolveTCPAddr(NETWORK, b.hostname)
  if err != nil {
    log.Println("Fatal Error: ", err)
    return nil, err
  }
  conn, err = net.DialTCP(NETWORK, nil, raddr)
  if err != nil {
    log.Println("Fatal Error: ", err)
    return nil, err
  }
  return conn, error
}

// returns length of response & payload & err
func (b *Broker) readResponse(conn *net.TCPConn) (uint32, []byte, os.Error) {
  reader := bufio.NewReader(conn)
  length := make([]byte, 4)
  lenRead, err := io.ReadFull(reader, length)
  if err != nil {
    return 0, []byte{}, err
  }
  if lenRead != 4 || lenRead < 0 {
    return 0, []byte{}, os.NewError("invalid length of the packet length field")
  }

  expectedLength := binary.BigEndian.Uint32(length)
  messages := make([]byte, expectedLength)
  lenRead, err = io.ReadFull(reader, messages)
  if err != nil {
    return 0, []byte{}, err
  }

  if uint32(lenRead) != expectedLength {
    return 0, []byte{}, os.NewError(fmt.Sprintf("Fatal Error: Unexpected Length: %d  expected:  %d", lenRead, expectedLength))
  }

  errorCode := binary.BigEndian.Uint16(messages[0:2])
  if errorCode != 0 {
    log.Println("errorCode: ", errorCode)
    return 0, []byte{}, os.NewError(
      fmt.Sprintf("Broker Response Error: %d", errorCode))
  }
  return expectedLength, messages[2:], nil
}


text:
package edu.gemini.util.skycalc.calc

import edu.gemini.spModel.core.Site
import edu.gemini.skycalc.{TimeUtils, ImprovedSkyCalc}
import edu.gemini.util.skycalc.SkycalcTarget
import java.util.Date
import edu.gemini.util.skycalc.calc.TargetCalculator.Fields

/**
 * Target calculator that allows to calculate different attributes of a target for a given interval at a given sampling
 * rate. The purpose of this trait is twofold:
 *

 *
It is a Scala facade to the Java skycalc code in {@see edu.gemini.skycalc.ImprovedSkyCalc}.

 *
It caches the values for a target for a given interval and sampling rate; this is relevant for places
 *       where these values are needed repetitively because the calculation is pretty complex and slow.

 *

 * If in doubt use {@link isDefinedAt} to make sure that values for a given time are actually calculated before
 * accessing them, otherwise an out of bounds exception will be thrown.
 */
trait TargetCalculator extends Calculator {
  require(site == Site.GN || site == Site.GS)

  val site: Site
  val target: SkycalcTarget

  val values: Vector[Vector[Double]] = calculate()

  import Fields._

  // ==  Gets the first of all calculated values for a given field, use this if only one value was calculated. ==
  lazy val elevation: Double = valueAt(Elevation.id, start)
  lazy val azimuth: Double = valueAt(Azimuth.id, start)
  lazy val airmass: Double = valueAt(Airmass.id, start)
  lazy val lunarDistance: Double = valueAt(LunarDistance.id, start)
  lazy val parallacticAngle: Double = valueAt(ParallacticAngle.id, start)
  lazy val hourAngle: Double = valueAt(HourAngle.id, start)
  lazy val skyBrightness: Double = valueAt(SkyBrightness.id, start)

  // == Accessor for a value by its field enumerator and a time.
  def valueAt(field: Field, t: Long): Double = valueAt(field.id, t)

  // ==  Accessors for any calculated values for a given field, use this if an interval of values was sampled. ==
  def elevationAt(t: Long): Double = valueAt(Elevation.id, t)
  lazy val minElevation: Double = min(Elevation.id)
  lazy val maxElevation: Double = max(Elevation.id)
  lazy val meanElevation: Double = mean(Elevation.id)

  def azimuthAt(t: Long): Double = valueAt(Azimuth.id, t)
  lazy val minAzimuth: Double = min(Azimuth.id)
  lazy val maxAzimuth: Double = max(Azimuth.id)
  lazy val meanAzimuth: Double = mean(Azimuth.id)

  def airmassAt(t: Long): Double = valueAt(Airmass.id, t)
  lazy val minAirmass: Double = min(Airmass.id)
  lazy val maxAirmass: Double = max(Airmass.id)
  lazy val meanAirmass: Double = mean(Airmass.id)

  def lunarDistanceAt(t: Long): Double = valueAt(LunarDistance.id, t)
  lazy val minLunarDistance: Double = min(LunarDistance.id)
  lazy val maxLunarDistance: Double = max(LunarDistance.id)
  lazy val meanLunarDistance: Double = mean(LunarDistance.id)

  def parallacticAngleAt(t: Long): Double = valueAt(ParallacticAngle.id, t)
  lazy val minParallacticAngle: Double = min(ParallacticAngle.id)
  lazy val maxParallacticAngle: Double = max(ParallacticAngle.id)
  lazy val meanParallacticAngle: Double = mean(ParallacticAngle.id)

  // If the target is visible during the scheduled time, return the weighted mean parallactic angle as Some(angle in degrees).
  // Otherwise, the target is not visible, so return None.
  lazy val weightedMeanParallacticAngle: Option[Double] = {
    val (weightedAngles, weights) = values(ParallacticAngle.id).zip(times).zip(values(Airmass.id)).map {
      case ((angle, t), airmass) =>
        // Wrap negative angles as per Andy's comment in OCSADV-16.
        val normalizedAngle = {
          if (angle < 0) {
            val normalizingFactor = {
              val dec = target.positionAt(t).getDecDeg
              if (dec - site.latitude < -10) 0
              else if (dec - site.latitude < 10) 180
              else 360
            }
            angle + normalizingFactor
          }
          else angle
        }

        //val weight = if (airmass <= 1.0) 0.0 else 1.6 * math.pow(airmass - 1.0, 0.6)
        val weight = if (airmass <= 1.0) 0.0 else math.pow(airmass - 1.0, 1.3)
        (normalizedAngle * weight, weight)
    }.unzip

    val weightedSum = weights.sum
    if (weightedSum == 0) None
    else Some(weightedAngles.sum / weightedSum)
  }

  def hourAngleAt(t: Long): Double = valueAt(HourAngle.id, t)
  lazy val minHourAngle: Double = min(HourAngle.id)
  lazy val maxHoursAngle: Double = max(HourAngle.id)
  lazy val meanHoursAngle: Double = mean(HourAngle.id)

  def skyBrightnessAt(t: Long): Double = valueAt(SkyBrightness.id, t)
  lazy val minSkyBrightness: Double = min(SkyBrightness.id)
  lazy val maxSkyBrightness: Double = max(SkyBrightness.id)
  lazy val meanSkyBrightness: Double = mean(SkyBrightness.id)

  /**
   * Calculates all values for the given times.
   * @return
   */
  protected def calculate() = {
    val skycalc = new ImprovedSkyCalc(site)

    // prepare temporary data structure
    val values = Array (
      new Array[Double](samples),
      new Array[Double](samples),
      new Array[Double](samples),
      new Array[Double](samples),
      new Array[Double](samples),
      new Array[Double](samples),
      new Array[Double](samples)
    )
    // fill temporary data structure with calculated values
    for (ix <- 0 to samples-1) {
      val t = times(ix)
      skycalc.calculate(target.positionAt(t), new Date(t), true)
      values(Elevation.id)(ix) = skycalc.getAltitude
      values(Azimuth.id)(ix) = skycalc.getAzimuth
      values(Airmass.id)(ix) = skycalc.getAirmass
      values(LunarDistance.id)(ix) = skycalc.getLunarDistance
      values(ParallacticAngle.id)(ix) = skycalc.getParallacticAngle
      values(HourAngle.id)(ix) = skycalc.getHourAngle
      values(SkyBrightness.id)(ix) = skycalc.getTotalSkyBrightness.doubleValue
    }

    // turn into immutable data structure
    Vector(
      // IMPORTANT: Make sure the order reflects the id values of the field enums!
      Vector(values(Elevation.id):_*),
      Vector(values(Azimuth.id):_*),
      Vector(values(Airmass.id):_*),
      Vector(values(LunarDistance.id):_*),
      Vector(values(ParallacticAngle.id):_*),
      Vector(values(HourAngle.id):_*),
      Vector(values(SkyBrightness.id):_*)
    )

  }
}

case class IntervalTargetCalculator(site: Site, target: SkycalcTarget, defined: Interval, rate: Long) extends FixedRateCalculator with LinearInterpolatingCalculator with TargetCalculator

case class SampleTargetCalculator(site: Site, target: SkycalcTarget, times: Vector[Long]) extends IrregularIntervalCalculator with LinearInterpolatingCalculator with TargetCalculator

case class SingleValueTargetCalculator(site: Site, target: SkycalcTarget, time: Long) extends SingleValueCalculator with TargetCalculator

object TargetCalculator {

  /** Enumeration that defines the different fields for this calculator for indexed access in sequence. */
  object Fields extends Enumeration {
    type Field = Value
    val Elevation, Azimuth, Airmass, LunarDistance, ParallacticAngle, HourAngle, SkyBrightness = Value
  }

  def apply(site: Site, target: SkycalcTarget, defined: Interval, rate: Long = TimeUtils.seconds(30)) = {
    new IntervalTargetCalculator(site, target, defined, rate)
  }
  def apply(site: Site, target: SkycalcTarget, time: Long): TargetCalculator = {
    new SingleValueTargetCalculator(site, target, time)
  }
  def apply(site: Site, target: SkycalcTarget, times: Vector[Long]): TargetCalculator = {
    new SampleTargetCalculator(site, target, times)
  }
}


text:
import os
from twisted.python.usage import Options as UsageOptions

class Options(UsageOptions, object):
    ""

def makeService(options):
    from twisted.application.internet import StreamServerEndpointService
    from twisted.internet.endpoints import serverFromString
    from twisted.internet import reactor
    from twisted.web.server import Site
    from twisted.logger import Logger

    log = Logger()

    from txlists.app import ListsManagementSite

    from twisted.application.service import MultiService, Service

    multiService = MultiService()

    class DeferredStartupService(Service, object):
        def startService(self):
            super(DeferredStartupService, self).startService()
            log.info("requesting service startup")
            (ListsManagementSite.makeManagementSite(reactor)
             .addCallback(dbReady))
    DeferredStartupService().setServiceParent(multiService)

    def dbReady(listsManagementSite):
        log.info("list management site ready {lms}", lms=listsManagementSite)
        resource = listsManagementSite.app.resource()
        StreamServerEndpointService(
            serverFromString(reactor, "{}:/certificates:tcp:8443".format(
                "txsni" if os.environ.get("NO_RENEW") else "le"
            )),
            Site(resource)
        ).setServiceParent(multiService)

    return multiService


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
  "http://www.w3.org/TR/html4/strict.dtd">

  <meta http-equiv="Content-type" content="text/html; charset=utf-8">
  <title>geometry.js example</title>


text:
<?xml version="1.0"?>
<ModuleDefinition xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
    <Fields>
        <FieldDefinition>
            <FieldName>ejectionForcePercentage</FieldName>
        </FieldDefinition>
    </Fields>
    <!--We do not put the methods board/leave seat as they are handled in their own system -->
</ModuleDefinition>


text:
package com.couchbase.mock.memcached.protocol;

import com.couchbase.mock.subdoc.Operation;

import java.net.ProtocolException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public abstract class BinarySubdocMultiCommand extends BinaryCommand {
    private int expiryTime;
    private boolean hasExpiry;
    private byte docFlags;
    protected final List<MultiSpec> specs = new ArrayList<MultiSpec>();

    public BinarySubdocMultiCommand(ByteBuffer header) throws ProtocolException {
        super(header);
    }

    @Override
    public void process() throws ProtocolException {
        bodyBuffer.rewind();
        switch (extraLength) {
            case 0:
                expiryTime = 0;
                docFlags = 0;
                hasExpiry = false;
                break;

            case 1:
                expiryTime = 0;
                hasExpiry = false;
                docFlags = bodyBuffer.get(0);
                break;

            case 4:
                expiryTime = bodyBuffer.getInt(0);
                hasExpiry = true;
                docFlags = 0;
                break;

            case 5:
                expiryTime = bodyBuffer.getInt(0);
                hasExpiry = true;
                docFlags = bodyBuffer.get(4);
                break;

            default:
                throw new ProtocolException("Extras must be 0, 1, 4, or 5!");

        }

        try {
            bodyBuffer.position(extraLength + keyLength);
            extractSpecs();
        } finally {
            bodyBuffer.rewind();
        }

        if (specs.isEmpty()) {
            throw new ProtocolException("Found no specs!");
        }
    }

    protected abstract void extractSpecs() throws ProtocolException;

    public List<MultiSpec> getLookupSpecs() {
        return specs;
    }

    public int getNewExpiry(int oldExpiry) {
        if (hasExpiry) {
            return expiryTime;
        } else {
            return oldExpiry;
        }
    }

    public byte getSubdocDocFlags() {
        return docFlags;
    }

    public static class MultiSpec {
        final private Operation op;
        final private String path;
        final private String value;
        final private byte flags;

        protected MultiSpec(Operation op, String path, String value, byte flags) {
            this.op = op;
            this.path = path;
            this.flags = flags;
            this.value = value;
        }

        protected MultiSpec(Operation op, String path, byte flags) {
            this(op, path, null, flags);
        }

        public Operation getOp() {
            return op;
        }
        public String getPath() {
            return path;
        }
        public String getValue() {
            return value;
        }
        public byte getFlags() {
            return flags;
        }
    }
}


text:
JSObjectRef PKTokenizerState_new(JSContextRef ctx, void *data);
JSClassRef PKTokenizerState_class(JSContextRef ctx);


text:
#ifndef ALIMUONDDLTRACKER_H
#define ALIMUONDDLTRACKER_H

/*$Id$*/

/// \ingroup raw
/// \class AliMUONDDLTracker
/// \brief MUON DDL tracker
///
//  Author Christian Finck

#include <TObject.h>
#include <TClonesArray.h>

class AliMUONBusStruct;
class AliMUONDspHeader;
class AliMUONBlockHeader;

class AliMUONDDLTracker : public TObject {

public:
   AliMUONDDLTracker();
   AliMUONDDLTracker(TRootIOCtor* dummy);
   virtual ~AliMUONDDLTracker();

   void    AddBusPatch(const AliMUONBusStruct& busPatch, Int_t iBlock, Int_t iDsp);
   void    AddDspHeader(const AliMUONDspHeader& dspHeader, Int_t iBlock);
   void    AddBlkHeader(const AliMUONBlockHeader& blkHeader);

   /// get TClonesArray
   TClonesArray*  GetBlkHeaderArray() const {return fBlkHeaderArray;}

   /// get entries
   Int_t GetBlkHeaderEntries() const {return fBlkHeaderArray->GetEntriesFast();}

   /// get entry
   AliMUONBlockHeader* GetBlkHeaderEntry(Int_t i) const {
     return (AliMUONBlockHeader*)fBlkHeaderArray->At(i);}

   // clear
   void Clear(Option_t* opt);

 private:
   /// Not implemented
   AliMUONDDLTracker(const AliMUONDDLTracker& event);
   /// Not implemented
   AliMUONDDLTracker& operator=(const AliMUONDDLTracker& event);

   TClonesArray* fBlkHeaderArray;  ///< array of block header

   ClassDef(AliMUONDDLTracker,1)  // MUON DDL Tracker
};
#endif


text:
<?php

declare(strict_types = 1);

namespace Unicity\MappingService\Data {

	/**
	 * This interface provides a contract that defines a model.
	 *
	 * @access public
	 * @interface
	 * @package MappingService
	 */
	interface IModel { }

}


text:
NS_ASSUME_NONNULL_BEGIN

#define ESTRequestBaseErrorDomain @"ESTRequestBaseErrorDomain"

typedef NS_ENUM(NSInteger, ESTRequestBaseError)
{
    ESTRequestBaseErrorConnectionFail
};

typedef void(^ESTRequestBlock)(id _Nullable result, NSError * _Nullable error);

@class ESTRequestBase;

@protocol ESTRequestBaseDelegate <NSObject>

- (void)request:(ESTRequestBase *)request didFinishLoadingWithResposne:(id)response;

- (void)request:(ESTRequestBase *)request didFailLoadingWithError:(NSError *)error;

@end

@interface ESTRequestBase : NSObject <NSURLConnectionDelegate, NSURLConnectionDataDelegate>

@property (nonatomic, weak) id<ESTRequestBaseDelegate> _Nullable delegate;

@property (nonatomic, assign) NSInteger code;
@property (nonatomic, strong) NSURLConnection * _Nullable connection;
@property (nonatomic, strong) NSMutableData * _Nullable receivedData;

- (NSMutableURLRequest *)createRequestWithUrl:(NSString *)url;

- (void)fireRequest:(NSMutableURLRequest *)request;
- (void)parseRespondedData:(id)data;
- (void)parseError:(NSError *)error;

- (void)sendRequest;
- (void)sendRequestWithCompletion:(ESTRequestBlock)completion;
- (void)cancelRequest;

#pragma mark - Helper methods

- (id _Nullable)objectForKey:(NSString *)aKey inDictionary:(NSDictionary * _Nullable)dict;

#pragma mark - Equality

- (BOOL)isEqualToRequest:(ESTRequestBase *)request;

@end

NS_ASSUME_NONNULL_END


text:
import React from 'react';
import { connect, MapStateToPropsFactory } from 'react-redux';
import './style/index.less';
import { Icon, Badge, notification, Dropdown, Menu, Modal, Upload, TreeSelect, message } from 'antd';
import { State } from '../../state/index';
import { RequestState } from '../../state/request';
import { actionCreator, ResetSyncMsgType } from '../../action/index';
import { LogoutType, ChangePasswordType } from '../../action/user';
import ChangePasswordDialog from './change_password_dialog';
import { Password } from '../../common/interfaces/password';
import { getProjectsIdNameStateSelector } from '../../components/collection_tree/selector';
import { ImportDataType } from '../../action/collection';
import Msg from '../../locales';
import LocalesString from '../../locales/string';

const Dragger = Upload.Dragger;

interface HeaderPanelStateProps {

    syncCount: number;

    message?: string;

    userName: string;

    userId: string;

    changePasswordState: RequestState;

    projects: { id: string, name: string }[];
}

interface HeaderPanelDispatchProps {

    onChangePassword(password: Password);

    logout(userId: string, needClearCache: boolean);

    importPostman(projectId: string, data: any);

    resetSyncMsg();
}

type HeaderPanelProps = HeaderPanelStateProps & HeaderPanelDispatchProps;

interface HeaderPanelState {

    isChangePwdDlgOpen: boolean;

    isImportDlgOpen: boolean;

    selectedProjectInDlg: string;
}

class HeaderPanel extends React.Component<HeaderPanelProps, HeaderPanelState> {

    constructor(props: HeaderPanelProps) {
        super(props);
        this.state = {
            isChangePwdDlgOpen: false,
            isImportDlgOpen: false,
            selectedProjectInDlg: ''
        };
    }

    public componentDidUpdate(_prevProps: HeaderPanelProps, _prevState: HeaderPanelState) {
        const { message } = this.props;
        if (!!message && notification.warning) {
            notification.warning({
                message: LocalesString.get('Common.WarningMsg'),
                description: message,
            });
            this.props.resetSyncMsg();
        }
    }

    private onUserMenuClick = (e) => {
        switch (e.key) {
            case 'logout': {
                this.props.logout(this.props.userId, false);
                break;
            }
            case 'logoutAndClear': {
                this.props.logout(this.props.userId, true);
                break;
            }
            case 'changePwd': {
                this.setState({ ...this.state, isChangePwdDlgOpen: true });
                break;
            }
            default:
                break;
        }
    }

    private onCancelChangePwd = () => {
        this.setState({ ...this.state, isChangePwdDlgOpen: false });
    }

    private onChangePwd = (data: Password) => {
        this.props.onChangePassword(data);
    }

    private importPostman = (file: File) => {
        if (!this.state.selectedProjectInDlg) {
            message.warning(LocalesString.get('Header.SelectProjectFirst'), 3);
            return;
        }
        const fr = new FileReader();
        const projectId = this.state.selectedProjectInDlg;
        fr.onload = (e) => {
            var data = JSON.parse((e.target as any).result);
            this.props.importPostman(projectId, data);
        };
        fr.readAsText(file);
        this.setState({ ...this.state, isImportDlgOpen: false, selectedProjectInDlg: '' });
    }

    private userMenu = (
        <Menu onClick={this.onUserMenuClick} style={{ width: 200 }}>
            <Menu.Item key="changePwd">
                <Icon type="key" /> {Msg('Header.ChangePassword')}
            </Menu.Item>
            <Menu.Item key="logout">
                <Icon type="logout" /> {Msg('Header.Logout')}
            </Menu.Item>
            <Menu.Item key="logoutAndClear">
                <Icon type="close-circle-o" /> {Msg('Header.Logout&Clear')}
            </Menu.Item>
        </Menu>
    );

    public render() {
        const { syncCount, userName, changePasswordState } = this.props;

        return (

                    <Badge style={{ fontFamily: 'SourceCodePro', boxShadow: '0 0 0 0 #fff' }} count={syncCount}>
                        <Icon className={`${syncCount > 0 ? 'header-sync-anim' : ''} header-sync`} type="sync" />
                    </Badge>

                        {syncCount > 0 ? Msg('Header.Syncing') : Msg('Header.Insync')}

                         this.setState({ ...this.state, isImportDlgOpen: true })}>
                            <Icon type="upload" /> {Msg('Header.Import')}

                        <Dropdown overlay={this.userMenu}>

                                {userName} <Icon type="down" />

                        </Dropdown>

                <ChangePasswordDialog
                    isDlgOpen={this.state.isChangePwdDlgOpen}
                    changePasswordState={changePasswordState}
                    onCancel={this.onCancelChangePwd}
                    onOk={this.onChangePwd}
                />
                <Modal
                    visible={this.state.isImportDlgOpen}
                    title={Msg('Header.ImportJson')}
                    width={500}
                    closable={true}
                    onCancel={() => this.setState({ ...this.state, isImportDlgOpen: false })}
                    footer={[]}
                >

{Msg('Header.SelectProject')}

                    <TreeSelect
                        allowClear={true}
                        style={{ marginTop: 8, width: '100%' }}
                        dropdownStyle={{ maxHeight: 500, overflow: 'auto' }}
                        placeholder={LocalesString.get('Collection.SelectProject')}
                        treeDefaultExpandAll={true}
                        value={this.state.selectedProjectInDlg}
                        onChange={(e) => this.setState({ ...this.state, selectedProjectInDlg: e })}
                        treeData={this.props.projects.map(t => ({ key: t.id, value: t.id, label: t.name }))}
                    />

                        <Dragger
                            showUploadList={false}
                            accept=".json"
                            customRequest={obj => { this.importPostman(obj.file); }}
                            action=""
                        >

                                <Icon type="inbox" />

{Msg('Header.DragFile')}

                        </Dragger>

                </Modal>

        );
    }
}

const makeMapStateToProps: MapStateToPropsFactory<any, any, any> = () => {
    const getProjects = getProjectsIdNameStateSelector();

    const mapStateToProps: (state: State) => HeaderPanelStateProps = state => {
        const { syncCount, message } = state.uiState.syncState;
        const { name } = state.userState.userInfo;
        return {
            syncCount,
            message,
            userName: name,
            changePasswordState: state.userState.changePasswordState,
            userId: state.userState.userInfo.id,
            projects: getProjects(state),
        };
    };
    return mapStateToProps;
};

const mapDispatchToProps = (dispatch: any): HeaderPanelDispatchProps => {
    return {
        logout: (userId, needClearCache) => dispatch(actionCreator(LogoutType, { userId, needClearCache })),
        onChangePassword: (password) => dispatch(actionCreator(ChangePasswordType, password)),
        importPostman: (projectId, data) => dispatch(actionCreator(ImportDataType, { projectId, data })),
        resetSyncMsg: () => dispatch(actionCreator(ResetSyncMsgType))
    };
};

export default connect(
    makeMapStateToProps,
    mapDispatchToProps,
)(HeaderPanel);


text:
class Animal:
    __nome = ""
    __idade = 0
    _estaVivo = True

    def __init__(self, nome, idade = 0):
        self.__nome = nome
        self.__idade = idade
        self.__estaVivo = True

    def __del__(self):
        print("O animal ", self.nome, " será eliminado da memória.")

    @property
    def nome(self):
        return self.__nome

    @nome.setter
    def nome(self, nome):
        if len(nome) < 3:
            self.__nome = "Totó"
        else:
            self.__nome = nome

    @property
    def idade(self):
        return self.__idade

    @idade.setter
    def idade(self, idade):
        if idade < 0:
            self.__idade = 0
        else:
            self.__idade = idade

    @property
    def estaVivo(self):
        return self._estaVivo

    def andar(self):
        print("O animal ", self.__nome, " está andando!")
        self.__metodo_privado()

    def morrer(self):
        self._estaVivo = False
        print("O animal ", self.__nome, " morreu :(")

    def __metodo_privado(self):
        print("Esse é um método privado.")

class Cachorro(Animal):
    __possuiRabo = True

    def __init__(self, nome, idade=1, possuiRabo=True):
        self.__possuiRabo = possuiRabo
        super().__init__(nome, idade)

    @property
    def possuiRabo(self):
        return self.__possuiRabo

    @possuiRabo.setter
    def possuiRabo(self, possuiRabo):
        self.__possuiRabo = possuiRabo

    def andar(self):
        print("Agora o cachorro ", self.nome, "é quem está andando.")

    def cavar(self):
        if self.estaVivo:
            print("O cachorro", self.nome, " está cavando.")
            self._estaVivo = False
        else:
            print("O cachorro", self.nome, " já morreu :(")

#animal1 = Animal(nome="Totó", idade=1)
animal1 = Cachorro(nome="Totó", idade=10)
#animal1.nome = "To"
#animal1.idade = -3
print(animal1.nome)
print(animal1.idade)
animal1.andar()
#animal1.possuiRabo = False
print(animal1.possuiRabo)
animal1.cavar()
print(animal1.estaVivo)
animal1.morrer()
print(animal1.estaVivo)
animal1.cavar()
del(animal1)


text:
package com.litepaltest.test.crud.query;

import org.litepal.crud.DataSupport;
import org.litepal.exceptions.DataSupportException;
import org.litepal.util.DBUtility;

import android.database.Cursor;
import android.test.AndroidTestCase;

import com.litepaltest.model.Book;

public class QueryBySQLTest extends AndroidTestCase {

	private Book book;

    private String bookTable;

	@Override
	protected void setUp() throws Exception {
		super.setUp();
        bookTable = DBUtility.getTableNameByClassName(Book.class.getName());
		book = new Book();
		book.setBookName("数据库");
		book.setPages(300);
		book.save();
	}

	public void testQueryBySQL() {
		Cursor cursor = DataSupport.findBySQL("select * from " + bookTable);
		assertTrue(cursor.getCount() > 0);
		cursor.close();
	}

	public void testQueryBySQLWithPlaceHolder() {
		Cursor cursor = DataSupport.findBySQL(
				"select * from " + bookTable + " where id=? and bookname=? and pages=?",
				String.valueOf(book.getId()), "数据库", "300");
		assertTrue(cursor.getCount() == 1);
		cursor.moveToFirst();
		String bookName = cursor.getString(cursor.getColumnIndexOrThrow("bookname"));
		int pages = cursor.getInt(cursor.getColumnIndexOrThrow("pages"));
		assertEquals(bookName, "数据库");
		assertEquals(pages, 300);
		cursor.close();
	}

	public void testQueryBySQLWithWrongParams() {
		try {
			DataSupport.findBySQL("select * from " + bookTable + " where id=? and bookname=? and pages=?",
					String.valueOf(book.getId()), "数据库");
			fail();
		} catch (DataSupportException e) {
			assertEquals("The parameters in conditions are incorrect.", e.getMessage());
		}
		Cursor cursor = DataSupport.findBySQL(new String[] {});
		assertNull(cursor);
		cursor = DataSupport.findBySQL();
		assertNull(cursor);
	}

}


text:
package com.google.javascript.jscomp.transpile;

import static com.google.common.truth.Truth.assertThat;

import com.google.common.testing.EqualsTester;
import java.net.URI;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link TranspileResult}. */
@RunWith(JUnit4.class)
public final class TranspileResultTest {

  @Test
  public void testEquals() throws Exception {
    new EqualsTester()
        .addEqualityGroup(
            new TranspileResult(new URI("a"), "b", "c", "d"),
            new TranspileResult(new URI("a"), "b", "c", "d"))
        .addEqualityGroup(new TranspileResult(new URI("A"), "b", "c", "d"))
        .addEqualityGroup(new TranspileResult(new URI("a"), "B", "c", "d"))
        .addEqualityGroup(new TranspileResult(new URI("a"), "b", "C", "d"))
        .addEqualityGroup(new TranspileResult(new URI("a"), "b", "c", "D"))
        .testEquals();
  }

  @Test
  public void testEmbedSourceMap_noSourceMap() throws Exception {
    TranspileResult result = new TranspileResult(new URI("a"), "b", "c", "");
    assertThat(result.embedSourcemap()).isSameInstanceAs(result);
    assertThat(result.embedSourcemapUrl("foo")).isSameInstanceAs(result);
  }

  @Test
  public void testEmbedSourceMap() throws Exception {
    TranspileResult result = new TranspileResult(new URI("a"), "b", "c", "{\"version\": 3}");
    assertThat(result.embedSourcemap())
        .isEqualTo(
            new TranspileResult(
                new URI("a"),
                "b",
                "c\n//# sourceMappingURL=data:,%7B%22version%22%3A%203%7D\n",
                ""));
    assertThat(result.embedSourcemapUrl("foo.js.map"))
        .isEqualTo(
            new TranspileResult(
                new URI("a"), "b", "c\n//# sourceMappingURL=foo.js.map\n", "{\"version\": 3}"));
  }
}


text:
package com.bootcamp.globant;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;

public class MainActivity extends Activity {

	public static final String NEW_CALL_EXAMPLE = "com.bootcamp.globant.NEW_CALL_EXAMPLE";
	private Calendar now= null;
	private TimePicker mTimePicker = null;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Set TimePicker to now.
		now = Calendar.getInstance();
		int hour = now.get(Calendar.HOUR_OF_DAY);
		int minutes = now.get(Calendar.MINUTE);
		mTimePicker = (TimePicker) findViewById(R.id.timePicker);
		mTimePicker.setIs24HourView(true);
		mTimePicker.setCurrentHour(hour);
		mTimePicker.setCurrentMinute(minutes);

		// Set Button
		Button setButton = (Button) findViewById(R.id.buttonSet);
		setButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// Get TimePicker
				mTimePicker = (TimePicker) findViewById(R.id.timePicker);

				now = Calendar.getInstance();
				int toHour = 0;
				int toMinutes = 0;
				if (mTimePicker.getCurrentHour() > now.get(Calendar.HOUR_OF_DAY)) {
					toHour =    mTimePicker.getCurrentHour() - now.get(Calendar.HOUR_OF_DAY);
					toMinutes = mTimePicker.getCurrentMinute() - now.get(Calendar.MINUTE);
				} else {
					toHour =    now.get(Calendar.HOUR_OF_DAY) - mTimePicker.getCurrentHour();
					toMinutes = now.get(Calendar.MINUTE) - mTimePicker.getCurrentMinute();
				}

				Log.e("INFO", "Time Picker: "+mTimePicker.getCurrentHour()+":"+mTimePicker.getCurrentMinute());
				Log.e("INFO", "Now: "+now.get(Calendar.HOUR_OF_DAY)+":"+now.get(Calendar.MINUTE));
				Log.e("INFO", "Diferencia: "+toHour+":"+toMinutes);

				PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, AlarmActivity.class), 0);
				Date date = new Date();
				long setTime = System.currentTimeMillis() + toHour * 60 * 60 * 1000 + toMinutes * 60 * 1000;
				Log.e("INFO", "Current Time: "+System.currentTimeMillis());
				Log.e("INFO", "Set Time    : "+setTime);
				date.setTime(setTime);
				// Creamos una Alarma predefinida.
				AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
				alarms.set(AlarmManager.RTC_WAKEUP, date.getTime(), pi);
			}
		});

		// Cancelamos la alarma, debemos proveer el PendingIntent relacionado.
		//alarms.cancel(pi);
	}

}


text:
  * Bumped version to 0.3.16
  * Expose simplesmtp version number [c2382203]
  * typo in SMTP (chrisdew) [6c39a8d7]
  * Fix typo in README.md (Meekohi) [597a25cb]

## v0.3.15 2013-11-15

  * Bumped version to 0.3.15
  * Fixed bugs in connection timeout implementation (finian) [1a25d5af]

## v0.3.14 2013-11-08

  * Bumped version to 0.3.14
  * fixed: typo causing connection.remoteAddress to be undefined (johnnyleung) 795fe81f
  * improvements to handling stage (mysz) 5a79e6a1
  * fixes TypeError: Cannot use 'in' operator to search for 'dsn' in undefined (mysz) 388d9b82
  * lost saving stage in "DATA" (mysz) de694f67
  * more info on smtp error (mysz) 42a4f964

## v0.3.13 2013-10-29

  * Bumped version to 0.3.13
  * Handling errors which close connection on or before EHLO (mysz) 03345d4d

## v0.3.12 2013-10-29

  * Bumped version to 0.3.12
  * Allow setting maxMessages to pool 5d185708

## v0.3.11 2013-10-22

  * Bumped version to 0.3.11
  * style update 2095d3a9
  * fix tests 17a3632f
  * DSN Support implemented. (irvinzz) d1e8ba29

## v0.3.10 2013-09-09

  * Bumped version to 0.3.10
  * added greetingTimeout, connectionTimeout and rejectUnathorized options to connection pool 8fa55cd3

## v0.3.9 2013-09-09

  * Bumped version to 0.3.9
  * added "use strict" definitions, added new options for client: greetingTimeout, connectionTimeout, rejectUnathorized 51047ae0
  * Do not include localAddress in the options if it is unset 7eb0e8fc

## v0.3.8 2013-08-21

  * Bumped version to 0.3.8
  * short fix for #42, Client parser hangs on certain input (dannycoates) 089f5cd4

## v0.3.7 2013-08-16

  * Bumped version to 0.3.7
  * minor adjustments for better portability with browserify (whiteout-io) 15715498
  * Added raw message to error object (andremetzen) 15715498
  * Passing to error handler the message sent from SMTP server when an error occurred (andremetzen) 15d4cbb4

## v0.3.6 2013-08-06

  * Bumped version to 0.3.6
  * Added changelog
  * Timeout if greeting is not received after connection is established


text:
package tests.data_structures;

import java.util.LinkedHashSet;
import java.util.Set;

import com.alejandrorm.util.data_structures.graph.Edge;
import com.alejandrorm.util.data_structures.graph.DirectedGraph;
import com.alejandrorm.util.data_structures.graph.Vertex;
import com.alejandrorm.util.data_structures.graph.algorithms.CycleDetector;
import com.alejandrorm.util.data_structures.graph.algorithms.Dijkstra;

public class DirectedGraphs {

	public static void main(String[] args) {
		Set<Vertex<String>> verticies = new LinkedHashSet<>();
		Vertex<String> a = new Vertex<>("A");
		Vertex<String> b = new Vertex<>("B");
		Vertex<String> c = new Vertex<>("C");
		Vertex<String> d = new Vertex<>("D");
		Vertex<String> e = new Vertex<>("E");
		Vertex<String> f = new Vertex<>("F");
		Vertex<String> g = new Vertex<>("G");
		{
			verticies.add(a);
			verticies.add(b);
			verticies.add(c);
			verticies.add(d);
			verticies.add(e);
			verticies.add(f);
			verticies.add(g);
		}

		Set<Edge<String>> edges = new LinkedHashSet<>();
		Edge<String> ea_b = new Edge<>(7, a, b);
		Edge<String> ea_d = new Edge<>(5, a, d);

		Edge<String> eb_c = new Edge<>(8, b, c);
		Edge<String> eb_d = new Edge<>(9, b, d);
		Edge<String> eb_e = new Edge<>(7, b, e);

		Edge<String> ec_e = new Edge<>(5, c, e);

		Edge<String> ed_e = new Edge<>(15, d, e);
		Edge<String> ed_f = new Edge<>(6, d, f);

		Edge<String> ee_f = new Edge<>(8, e, f);
		Edge<String> ee_g = new Edge<>(9, e, g);

		Edge<String> ef_g = new Edge<>(11, f, g);
		{
			edges.add(ea_b);
			edges.add(ea_d);
			edges.add(eb_c);
			edges.add(eb_d);
			edges.add(eb_e);
			edges.add(ec_e);
			edges.add(ed_e);
			edges.add(ed_f);
			edges.add(ee_g);
			edges.add(ee_f);
			edges.add(ef_g);
		}

		DirectedGraph<String> graph = new DirectedGraph<>(verticies, edges);

		System.out.println(graph);

		System.out.println("Dijkstra: "+ Dijkstra.getShortestPath(graph, a, g));

		System.out.println("Contains a cycle: " + CycleDetector.isCyclic(graph));
	}

}


text:
"""Counts class module."""
from itertools import product

import numpy
import pytest

from make_test_ref import SEED
from ndd import fnsb
from ndd.counts import CountsDistribution, unique

numpy.random.seed(SEED)

P = 100
X = numpy.random.randint(2, size=P)

@pytest.fixture(params=product([10, 100, 1000], [10, 100, 1000]))
def data(request):
    return CountsDistribution().random(*request.param)

def test_fcounter(data):
    fcounter = fnsb.counter
    fcounter.fit(ar=data.counts)
    assert CountsDistribution(nk=fcounter.nk, zk=fcounter.zk) == data

def test_unique(data):
    nk, zk = unique(nk=data.counts, sort=True)
    assert CountsDistribution(nk=nk, zk=zk) == data

def test_mapping():
    y = dict(zip(range(P), X))
    assert CountsDistribution().fit(X) == CountsDistribution().fit(y)

def test_generator():
    y = (n for n in X)
    assert CountsDistribution().fit(X) == CountsDistribution().fit(y)

def test_series():
    try:
        from pandas import Series
    except ImportError:
        assert 1
    else:
        y = Series(X)
        assert CountsDistribution().fit(X) == CountsDistribution().fit(y)


text:
/*******************************************************************************
 * 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.
 *******************************************************************************/
package io.onedecision.engine.decisions.api;

/**
 * Base class for all exceptions thrown by the engine.
 *
 * @author Tim Stephenson
 */
public class DecisionException extends RuntimeException {

	private static final long serialVersionUID = 434480901378400857L;

    public DecisionException() {
        super();
    }

    public DecisionException(String message) {
        super(message);
    }

    public DecisionException(String msg, Exception cause) {
        super(msg, cause);
    }

}


text:
from utils import header_utils

import pretty_markdown

class FixHeaderBalancingCommand(pretty_markdown.PrettyMarkdownCommand):
    def modify(self, text):
        """Balances headers."""

        balancing = pretty_markdown.settings().get('header_balancing')
        return header_utils.fix_header_balancing(text, balancing)

class ConvertHeadersCommand(pretty_markdown.PrettyMarkdownCommand):
    def modify(self, text):
        """Depending on settings, converts atx to Setext header or vice versa."""

        return text


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

MAALOX ADVANCED MAXIMUM STRENGTH CHERRY- aluminum hydroxide, magnesium hydroxide and dimethicone liquid
Novartis Consumer Health, Inc

Disclaimer: Most OTC drugs are not reviewed and approved by FDA, however they may be marketed if they comply with applicable regulations and policies. FDA has not evaluated whether this product complies.

Drug Facts

Active ingredient (in each 5mL = 1 teaspoonful)

Aluminum Hydroxide (equiv. to dried gel, USP) 400 mg
Magnesium Hydroxide 400 mg
Simethicone 40 mg

Purpose

Antacid
Antacid
Anti-Gas

Uses

for the relief of

acid indigestion

heartburn

sour stomach

upset stomach associated with these symptoms

pressure and bloating commonly referred to as gas

Warnings

Do not take

more than 8 teaspoonsful in a 24-hour period or use the maximum dosage for more than 2 weeks except under the advice and supervision of a physician

Ask a doctor before use if you have

kidney disease

 a magnesium-restricted diet

Ask a doctor or pharmacist before use if you are

presently taking a prescription drug.  Antacids may interact with certain prescription drugs.

Stop use and ask a doctor if

symptoms last more than 2 weeks

Keep Out of Reach of Children

Directions

shake well before using.

adults and children 12 years and older: take 2 to 4 teaspoonfuls two times a day or as directed by a physician.

do not take more than 8 teaspoonsful in 24 hours or use the maximum dosage for more than 2 weeks

children under 12 years: consult a physician.

Other information

each teaspoonful contains: magnesium 145 mg,  potassium 5 mg

store at controlled room temperature 20-25°C(68-77°F)

protect from freezing

Inactive ingredients

butylparaben, carboxymethylcellulose sodium, flavor, glycerin, hypromellose, microcrystalline cellulose, potassium citrate, propylene glycol, propylparaben, purified water, saccharin sodium, sorbitol

Questions or comments?

call 1-800-452-0051 24 hours a day, 7 days a week.

Principal Display Panel

0067-6280-12

See New Dosing Directions

Maalox
Advanced
Maximum Strength
Antacid & Antigas

FAST RELIEF
HEARTBURN & ACID INDIGESTION
PRESSURE & BLOATING

Cherry
Flavored Liquid

355 mL (12 FL OZ)

MAALOX
					ADVANCED MAXIMUM STRENGTH CHERRY
aluminum hydroxide, magnesium hydroxide,simethicone liquid

Product Information

Product Type
HUMAN OTC DRUG LABEL
Item Code (Source)
NDC:0067-6280

Route of Administration
ORAL
DEA Schedule

Active Ingredient/Active Moiety

Ingredient Name
Basis of Strength
Strength

ALUMINUM HYDROXIDE (ALUMINUM HYDROXIDE)
ALUMINUM HYDROXIDE
400 mg  in 5 mL

MAGNESIUM HYDROXIDE (MAGNESIUM CATION)
MAGNESIUM HYDROXIDE
400 mg  in 5 mL

DIMETHICONE (DIMETHICONE)
DIMETHICONE
40 mg  in 5 mL

Inactive Ingredients

Ingredient Name
Strength

BUTYLPARABEN

CARBOXYMETHYLCELLULOSE SODIUM

GLYCERIN

HYPROMELLOSES

CELLULOSE, MICROCRYSTALLINE

POTASSIUM CITRATE

PROPYLENE GLYCOL

PROPYLPARABEN

WATER

SACCHARIN SODIUM

SORBITOL

Product Characteristics

Color
WHITE
Score

Shape

Size

Flavor
CHERRY
Imprint Code

Contains

Packaging

#
Item Code
Package Description
Marketing Start Date
Marketing End Date

1
NDC:0067-6280-12
355 mL in 1 BOTTLE

2
NDC:0067-6280-26
770 mL in 1 BOTTLE

Marketing Information

Marketing Category
Application Number or Monograph Citation
Marketing Start Date
Marketing End Date

OTC monograph final
part332
03/06/2008

Labeler - Novartis Consumer Health, Inc
							(879821635)

Revised: 9/2013

Document Id: 1ee52d89-b40e-4d8d-aed9-6b1aced5d75a

Set id: 1ee52d89-b40e-4d8d-aed9-6b1aced5d75a

Version: 1

Effective Time: 20130901

Novartis Consumer Health, Inc


text:
class AdminVariantDetailsEditPage < SitePrism::Page
  set_url '/admin/splits/{split_id}/variant_details/{variant}/edit'

  section :form, 'form' do
    element :display_name, 'input[name="variant_detail[display_name]"]'
    element :description, 'textarea[name="variant_detail[description]"]'
    element :screenshot, 'input[name="variant_detail[screenshot]"]'
    element :current_screenshot, '.variant_detail_screenshot .hint'
    element :retire_button, '.retire-variant-link'
    element :submit_button, 'input[type=submit]'
  end

  def retire_variant
    form.retire_button.click
  end
end


text:
/**
 * @file reference_76a.h
 * @brief the class of 76a (for mobileye)
 */

#ifndef MODULES_DRIVERS_MOBILEYE_PROTOCOL_REFERENCE_76A_H
#define MODULES_DRIVERS_MOBILEYE_PROTOCOL_REFERENCE_76A_H

#include "modules/drivers/proto/mobileye.pb.h"
#include "modules/drivers/canbus/can_comm/protocol_data.h"

/**
 * @namespace apollo::drivers::mobileye
 * @brief apollo::drivers::mobileye
 */

namespace apollo {
namespace drivers {
namespace mobileye {

using ::apollo::drivers::Mobileye;

class Reference76a : public ::apollo::drivers::canbus::ProtocolData<Mobileye> {
 public:
  static const int ID;

  void Parse(const uint8_t* bytes, int32_t length,
             Mobileye* mobileye) const override;

  // config detail: {'name': 'ref_point_1_position', 'offset': -127.99609375,
  // 'precision': 0.00390625, 'len': 16, 'f_type': 'value', 'is_signed_var':
  // False, 'physical_range': '[-127.99609375|128]', 'bit': 0, 'type': 'double',
  // 'order': 'intel', 'physical_unit': '"meters"'}
  double ref_point_1_position(const uint8_t* bytes, int32_t length) const;

  // config detail: {'name': 'ref_point_1_distance', 'offset': 0.0, 'precision':
  // 0.00390625, 'len': 15, 'f_type': 'value', 'is_signed_var': False,
  // 'physical_range': '[0|127.99609375]', 'bit': 16, 'type': 'double', 'order':
  // 'intel', 'physical_unit': '"meters"'}
  double ref_point_1_distance(const uint8_t* bytes, int32_t length) const;

  bool is_ref_point_1_validity(const uint8_t* bytes, int32_t length) const;

  // config detail: {'name': 'ref_point_2_position', 'offset': -127.99609375,
  // 'precision': 0.00390625, 'len': 16, 'f_type': 'value', 'is_signed_var':
  // False, 'physical_range': '[-127.99609375|128]', 'bit': 32, 'type':
  // 'double', 'order': 'intel', 'physical_unit': '"meters"'}
  double ref_point_2_position(const uint8_t* bytes, int32_t length) const;

  // config detail: {'name': 'ref_point_2_distance', 'offset': 0.0, 'precision':
  // 0.00390625, 'len': 15, 'f_type': 'value', 'is_signed_var': False,
  // 'physical_range': '[0|127.99609375]', 'bit': 48, 'type': 'double', 'order':
  // 'intel', 'physical_unit': '"meters"'}
  double ref_point_2_distance(const uint8_t* bytes, int32_t length) const;

  bool is_ref_point_2_validity(const uint8_t* bytes, int32_t length) const;
};

}  // namespace mobileye
}  // namespace drivers
}  // namespace apollo

#endif  // MODULES_DRIVERS_MOBILEYE_PROTOCOL_REFERENCE_76A_H


text:
using System;
using Bundler.Infrastructure;
using Bundler.Infrastructure.Server;

namespace Bundler.Helper {
    public static class ConfigurationValidator {
        public static void Validate(IBundleContext bundleContext) {
            if (bundleContext == null) throw new ArgumentNullException(nameof(bundleContext));
            if (bundleContext.Watcher == null) throw new NullReferenceException($"{nameof(IBundleContext)}.{nameof(IBundleContext.Watcher)}");
            if (bundleContext.UrlHelper == null) throw new NullReferenceException($"{nameof(IBundleContext)}.{nameof(IBundleContext.UrlHelper)}");
            if (bundleContext.VirtualPathProvider == null) throw new NullReferenceException($"{nameof(IBundleContext)}.{nameof(IBundleContext.VirtualPathProvider)}");
            if (bundleContext.Configuration == null) throw new NullReferenceException($"{nameof(IBundleContext)}.{nameof(IBundleContext.Configuration)}");
        }
    }
}


text:
var main = require('./lib/main');

module.exports = main;


text:
import {Services} from '#service';
import {getChildJsonConfig} from '../../../src/json';
import {isProtocolValid} from '../../../src/url';
import {once} from '#core/types/function';
import {registerServiceBuilder} from '../../../src/service-helpers';
import {user, userAssert} from '../../../src/log';

/** @private @const {string} */
export const CONFIG_SRC_ATTRIBUTE_NAME = 'src';

/** @private const {string} */
export const CREDENTIALS_ATTRIBUTE_NAME = 'data-credentials';

/** @private @const {string} */
const TAG = 'amp-story-request-service';

/**
 * Service to send XHRs.
 */
export class AmpStoryRequestService {
  /**
   * @param {!Window} win
   * @param {!Element} storyElement
   */
  constructor(win, storyElement) {
    /** @private @const {!Element} */
    this.storyElement_ = storyElement;

    /** @private @const {!../../../src/service/xhr-impl.Xhr} */
    this.xhr_ = Services.xhrFor(win);

    /** @const @type {function():(!Promise<!JsonObject>|!Promise<null>)} */
    this.loadShareConfig = once(() => this.loadShareConfigImpl_());
  }

  /**
   * @param {string} rawUrl
   * @param {Object=} opts
   * @return {(!Promise<!JsonObject>|!Promise<null>)}
   */
  executeRequest(rawUrl, opts = {}) {
    if (!isProtocolValid(rawUrl)) {
      user().error(TAG, 'Invalid config url.');
      return Promise.resolve(null);
    }

    return Services.urlReplacementsForDoc(this.storyElement_)
      .expandUrlAsync(user().assertString(rawUrl))
      .then((url) => this.xhr_.fetchJson(url, opts))
      .then((response) => {
        userAssert(response.ok, 'Invalid HTTP response');
        return response.json();
      });
  }

  /**
   * Retrieves the publisher share providers.
   * Has to be called through `loadShareConfig`.
   * @return {(!Promise<!JsonObject>|!Promise<null>)}
   */
  loadShareConfigImpl_() {
    const shareConfigEl = this.storyElement_.querySelector(
      'amp-story-social-share, amp-story-bookend'
    );
    if (!shareConfigEl) {
      return Promise.resolve();
    }

    if (shareConfigEl.hasAttribute(CONFIG_SRC_ATTRIBUTE_NAME)) {
      const rawUrl = shareConfigEl.getAttribute(CONFIG_SRC_ATTRIBUTE_NAME);
      const credentials = shareConfigEl.getAttribute(
        CREDENTIALS_ATTRIBUTE_NAME
      );
      return this.executeRequest(rawUrl, credentials ? {credentials} : {});
    }

    // Fallback. Check for an inline json config.
    let config = null;
    try {
      config = getChildJsonConfig(shareConfigEl);
    } catch (err) {}

    return Promise.resolve(config);
  }
}

/**
 * Util function to retrieve the request service. Ensures we can retrieve the
 * service synchronously from the amp-story codebase without running into race
 * conditions.
 * @param  {!Window} win
 * @param  {!Element} storyEl
 * @return {!AmpStoryRequestService}
 */
export const getRequestService = (win, storyEl) => {
  let service = Services.storyRequestService(win);

  if (!service) {
    service = new AmpStoryRequestService(win, storyEl);
    registerServiceBuilder(win, 'story-request', function () {
      return service;
    });
  }

  return service;
};


text:
package org.datalorax.populace.core.populate.instance;

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

/**
 * Instance factory for primitive types
 *
 * @author Andrew Coates - 03/03/2015.
 */
@SuppressWarnings("unchecked")
public class PrimitiveInstanceFactory implements InstanceFactory {
    public static final PrimitiveInstanceFactory INSTANCE = new PrimitiveInstanceFactory();

    private static final Map<Class<?>, Object> DEFAULT_INSTANCE_MAP = new HashMap<Class<?>, Object>() {{
       put(boolean.class, false);
       put(Boolean.class, true);
       put(byte.class, (byte) 42);
       put(Byte.class, (byte) 42);
       put(char.class, 'c');
       put(Character.class, 'c');
       put(short.class, (short)42);
       put(Short.class, (short)42);
       put(int.class, 42);
       put(Integer.class, 42);
       put(long.class, 42L);
       put(Long.class, 42L);
       put(float.class, 4.2f);
       put(Float.class, 4.2f);
       put(double.class, 4.2);
       put(Double.class, 4.2);
    }};

    @Override
    public <T> T createInstance(final Class<? extends T> type, final Object parent, final InstanceFactories instanceFactories) {
        return (T) DEFAULT_INSTANCE_MAP.get(type);
    }

    @Override
    public boolean equals(final Object that) {
        return this == that || (that != null && getClass() == that.getClass());
    }

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

    @Override
    public String toString() {
        return getClass().getSimpleName();
    }
}