text:
#ifndef __SIP_SOCKET_API_H__
#define __SIP_SOCKET_API_H__

#include "cpr.h"
#include "cpr_socket.h"

/**
 * sipSocketSend
 *
 * @brief The sipSocketSend() function is a wrapper used by the sipstack to send
 * data over a socket. This function decides to use the secure versus unsecure
 * connection based on the "secure" flag.
 *
 * @note - The implementation of both secure/non-secure is the same in RT/TNP
 * products. It is different for the other vendors and hence we need this
 * flexibility.
 *
 * @param[in] soc  Specifies the socket created with cprSocket() to send
 * @param[in] buf  A pointer to the buffer of the message to send.
 * @param[in] len  Specifies the length in bytes of the message pointed to by the buffer argument.
 * @param[in] flags  - The options used for the send.
 *
 *
 */
ssize_t
sipSocketSend (cpr_socket_t soc,
         CONST void *buf,
         size_t len,
         int32_t flags,
         boolean secure);

/**
 * sipSocketRecv
 *
 * @brief The sipSocketRecv() function is a wrapper used by the sipstack to send
 * data over a socket. This function decides to use the secure versus unsecure
 * connection based on the "secure" flag.
 *
 * @note - The implementation of both secure/non-secure is the same in RT/TNP
 * products. It is different for the other vendors and hence we need this
 * flexibility.
 *
 * @param[in] soc  Specifies the socket created with cprSocket() to send
 * @param[in] buf  A pointer to the buffer of the message to send.
 * @param[in] len  Specifies the length in bytes of the message pointed to by the buffer argument.
 * @param[in] flags  - The options used for the recv.
 */
ssize_t
sipSocketRecv (cpr_socket_t soc,
         void * RESTRICT buf,
         size_t len,
         int32_t flags,
         boolean secure);

/**
 * sipSocketClose
 *
 * @brief The sipSocketClose() function is a wrapper used by the sipstack to
 * close a socket. This function decides to use the secure versus unsecure
 * connection based on the "secure" flag.
 *
 * @note - The implementation of both secure/non-secure is the same in RT/TNP
 * products. It is different for the other vendors and hence we need this
 * flexibility.
 *
 * @param[in] soc  - The socket that needs to be destroyed
 *
 * @return CPR_SUCCESS on success otherwise, CPR_FAILURE. cpr_errno needs to be set in this case.
 *
 * @note The possible error values this function should return are
 *         @li [CPR_EBADF]      socket is not a valid socket descriptor.
 */
cpr_status_e
sipSocketClose (cpr_socket_t soc,
                boolean secure);
#endif


text:
<!DOCTYPE html>

	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<title>myNewApp</title>

	<link rel="stylesheet" type="text/css" href="style/lib/bootstrap/bootstrap.min.css" />
	<link rel="stylesheet" type="text/css" href="style/lib/bootstrap/bootstrap-theme.min.css" />

	<link rel="stylesheet" type="text/css" href="style/generated_css/reset.css"/>
	<link rel="stylesheet" type="text/css" href="style/generated_css/main.css"/>

				{{ navTitle }}

		<ng-view></ng-view>

redpajama_set_name: RedPajamaGithub


text:
python_version=$1

echo "Installing ${python_version}..."

CFLAGS="-I$(xcrun --show-sdk-path)/usr/include" pyenv install $1


text:
package com.blazebit.persistence.view.testsuite.update.correlated.creatable;

import com.blazebit.persistence.testsuite.base.jpa.assertion.AssertStatementBuilder;
import com.blazebit.persistence.testsuite.base.jpa.category.NoDatanucleus;
import com.blazebit.persistence.testsuite.base.jpa.category.NoEclipselink;
import com.blazebit.persistence.testsuite.entity.Document;
import com.blazebit.persistence.testsuite.entity.Person;
import com.blazebit.persistence.view.FlushMode;
import com.blazebit.persistence.view.FlushStrategy;
import com.blazebit.persistence.view.spi.EntityViewConfiguration;
import com.blazebit.persistence.view.testsuite.update.AbstractEntityViewUpdateDocumentTest;
import com.blazebit.persistence.view.testsuite.update.correlated.creatable.model.DocumentIdView;
import com.blazebit.persistence.view.testsuite.update.correlated.creatable.model.PersonCreateView;
import com.blazebit.persistence.view.testsuite.update.correlated.creatable.model.UpdatablePersonView;
import com.blazebit.persistence.view.testsuite.update.correlated.creatable.model.UpdatableDocumentWithCollectionsView;
import org.junit.Assert;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

import java.util.Collection;
import java.util.Iterator;

import static org.junit.Assert.*;

/**
 *
 * @author Christian Beikov
 * @since 1.3.0
 */
@RunWith(Parameterized.class)
// NOTE: No Datanucleus support yet
@Category({ NoDatanucleus.class, NoEclipselink.class})
public class EntityViewUpdateCorrelatedCreatableSubviewCollectionsTest extends AbstractEntityViewUpdateDocumentTest<UpdatableDocumentWithCollectionsView> {

    public EntityViewUpdateCorrelatedCreatableSubviewCollectionsTest(FlushMode mode, FlushStrategy strategy, boolean version) {
        super(mode, strategy, version, UpdatableDocumentWithCollectionsView.class);
    }

    @Parameterized.Parameters(name = "{0} - {1} - VERSIONED={2}")
    public static Object[][] combinations() {
        return MODE_STRATEGY_VERSION_COMBINATIONS;
    }

    @Override
    protected void registerViewTypes(EntityViewConfiguration cfg) {
        cfg.addEntityView(UpdatablePersonView.class);
        cfg.addEntityView(PersonCreateView.class);
        cfg.addEntityView(DocumentIdView.class);
    }

    @Override
    protected String[] getFetchedCollections() {
        return new String[] { "partners" };
    }

    @Test
    public void testUpdateWithPersonCreateView() {
        final UpdatableDocumentWithCollectionsView docView = getDoc1View();
        clearQueries();

        // When
        PersonCreateView personCreateView = evm.create(PersonCreateView.class);
        personCreateView.setName("newPers");
        docView.addPerson(personCreateView);
        update(docView);

        // Then
        AssertStatementBuilder builder = assertUnorderedQuerySequence();

        if (!isQueryStrategy() && (isFullMode() || version)) {
            fullFetch(builder);
        }

        builder.insert(Person.class);

        if (isFullMode() && isQueryStrategy() || version) {
            builder.update(Document.class);
        }
        builder.validate();

        assertNoUpdateAndReload(docView, true);
        Iterator<Person> iterator = doc1.getPartners().iterator();
        Person p = iterator.next();
        if (!p.getId().equals(personCreateView.getId())) {
            p = iterator.next();
        }
        assertEquals(p.getId(), personCreateView.getId());
        assertEquals("newPers", p.getName());
        assertSubviewEquals(doc1.getPartners(), docView.getPartners());
    }

    public static void assertSubviewEquals(Collection<Person> persons, Collection<UpdatablePersonView> personSubviews) {
        if (persons == null) {
            assertNull(personSubviews);
            return;
        }

        assertNotNull(personSubviews);
        assertEquals(persons.size(), personSubviews.size());
        for (Person p : persons) {
            boolean found = false;
            for (UpdatablePersonView pSub : personSubviews) {
                if (p.getName().equals(pSub.getName())) {
                    found = true;
                    break;
                }
            }

            if (!found) {
                Assert.fail("Could not find a person subview instance with the name: " + p.getName());
            }
        }
    }

    @Override
    protected AssertStatementBuilder fullFetch(AssertStatementBuilder builder) {
        return builder.select(Document.class);
    }

    @Override
    protected AssertStatementBuilder fullUpdate(AssertStatementBuilder builder) {
        return builder.update(Document.class);
    }

    @Override
    protected AssertStatementBuilder versionUpdate(AssertStatementBuilder builder) {
        return builder.update(Document.class);
    }
}


text:
import makeStyleMapper from './makeStyleMapper';
import Model from '../Model';
import { LineStyleOption } from '../../util/types';
import { PathStyleProps } from 'zrender/src/graphic/Path';

export const LINE_STYLE_KEY_MAP = [
    ['lineWidth', 'width'],
    ['stroke', 'color'],
    ['opacity'],
    ['shadowBlur'],
    ['shadowOffsetX'],
    ['shadowOffsetY'],
    ['shadowColor'],
    ['lineDash', 'type'],
    ['lineDashOffset', 'dashOffset'],
    ['lineCap', 'cap'],
    ['lineJoin', 'join'],
    ['miterLimit']
    // Option decal is in `DecalObject` but style.decal is in `PatternObject`.
    // So do not transfer decal directly.
];

const getLineStyle = makeStyleMapper(LINE_STYLE_KEY_MAP);

type LineStyleKeys = 'lineWidth'
    | 'stroke'
    | 'opacity'
    | 'shadowBlur'
    | 'shadowOffsetX'
    | 'shadowOffsetY'
    | 'shadowColor'
    | 'lineDash'
    | 'lineDashOffset'
    | 'lineCap'
    | 'lineJoin'
    | 'miterLimit';

export type LineStyleProps = Pick<PathStyleProps, LineStyleKeys>;

class LineStyleMixin {

    getLineStyle(
        this: Model,
        excludes?: readonly (keyof LineStyleOption)[]
    ): LineStyleProps {
        return getLineStyle(this, excludes);
    }

};

export {LineStyleMixin};


text:
$( document ).ready(function() {
	$("a").click(function(){

		var href = $(this).attr("href");
		var title = $(this).text();
		//alert(title);

		window.history.pushState("", title, href);
		$("#live-page").load(href + ".html #test");
		//$("#live-page").html(title + '  ' + href);
		return false;

	});

});


text:
layout: project
colors:
    default: f16d1d
    dark: ef6411
    light: f5b38c

title: BPCLEtool
skills: [UI, Visual Design, JS/Jquery, CSS/SCSS]
summary: BPCLEtool is a web application that helps health organisations improve and maintain clinical education best practices.  Originally developed for the Victorian Department of Health, BPCLEtool is used by hundreds of health organisations across Australia.
feature_image:
    small: /assets/img/bpcle-small.png
    medium: /assets/img/bpcle-medium.png
    large: /assets/img/bpcle-large.png

links:
-   url: https://bpcletool.net.au
    text: View Application

priority: 4

sections:
-   |
    ## The Problem
    The BPCLE Framework was developed by [Darcy Associates](http://darcyassociates.com.au/) for the Victorian Department of Health, in order to define best practices in clinical learning environments.
    As part of this process, Darcy Associates also developed a prototype excel application that allowed health organisations to rate themselves against the framework and discover how they could improve their educational environments.

    Our task was to extend this concept; by designing and developing a modern, accessible, intuitive web application.

    As the design lead, my challenges included:

    * Leading users through a complex multi-step process
    * Ensuring help was readily available when needed
    * Developing intuitive information architecture
    * Maintaining visual consistency as new features were added to the application

-   |
    ## The Solution

    My first port of call was to develop a series of wireframes to:

    * Divide the application's functionality into intuitive groupings
    * Show or hide content to the appropriate user classes
    * Establish how a standard user would move sequentially through the application's functionality
    * Set out visual cues to highlight an individual's progress

    Following this, the application's aesthetic design was built out in an iterative process, with intermittent user acceptance testing validating or challenging design decisions.

    Particular highlights of the design include:

    * Well labeled and easy to use input forms
    * Fast and informative JavaScript form validation
    * Simple, consistent data presentation
    * Intuitive use of colour for descriptive purposes (e.g. red to highlight a bad result, green to highlight a good result)
    * Non-invasive help functionality, with tooltips and dropdowns revealing information at the point of need

---


text:
package br.unicamp.ic.lsd.mercurius.addressmgr.impl;

import br.unicamp.ic.lsd.mercurius.addressmgr.spec.prov.AddressManager;
import br.unicamp.ic.lsd.mercurius.datatype.Address;

class AddressMgtImpl {

	private AddressManager manager;

	AddressMgtImpl(AddressManager manager) {
		super();
		this.manager = manager;
	}

	Address saveAddress(Address address) {
		return manager.getAddressDAO().merge(address);
	}

	void deleteAddress(Address address) {
		manager.getAddressDAO().removeById(address.getId());
	}

}


text:
<#
.Synopsis
    Verify basic VHDx Hard Disk resizing.
.Description
    This is a PowerShell test case script that implements Dynamic
    Resizing of VHDX test case 2.3.1 and 2.3.2.
    Ensures that the VM sees the newly attached VHDx Hard Disk
    Creates partitions, filesytem, mounts partitions, sees if it can perform
    Read/Write operations on the newly created partitions and deletes partitions
    A typical test case definition for this test script would look
    similar to the following:
        <test>
            <testName>VHDXResizeBasic</testName>
            <testScript>SetupScripts\VHDxResizeToBigger.ps1</testScript>
            <setupScript>SetupScripts\Add-VHDXHardDisk.ps1</setupScript>
            <cleanupScript>SetupScripts\Remove-VHDXHardDisk.ps1</cleanupScript>
            <timeout>600</timeout>
            <onError>Continue</onError>
            <testparams>
                <param>SCSI=0,0,Dynamic,512</param>
                <param>NewSize=4GB</param>
                <param>ControllerType=SCSI</param>
                <param>Type=Dynamic</param>
                <param>TC_COVERED=STOR-VHDx-01</param>
            </testparams>
        </test>
.Parameter vmName
    Name of the VM to attached and resize the VHDx Hard Disk.
.Parameter hvServer
    Name of the Hyper-V server hosting the VM.
.Parameter testParams
    Test data for this test case
.Example
    setupScripts\STOR_VHDXResize_Basic.ps1 -vmName "VM-Name" -hvServer "HYPERV_SERVER" -TestParams "ipv4=255.255.255.255;sshKey=YOUR_KEY.ppk;TC_COVERED=STOR-VHDx-01"
#>

param( [String] $vmName,
       [String] $hvServer,
       [String] $testParams
)

$sshKey     = $null
$ipv4       = $null
$newSize    = $null
$rootDir    = $null
$TC_COVERED = $null
$TestLogDir = $null
$TestName   = $null
$vhdxDrive  = $null

#######################################################################
#
# Main script body
#
#######################################################################

#
# Make sure the required arguments were passed
#
if (-not $vmName)
{
    "Error: no VMName was specified"
    return $False
}

if (-not $hvServer)
{
    "Error: No hvServer was specified"
    return $False
}

if (-not $testParams)
{
    "Error: No test parameters specified"
    return $False
}

#
# Debug - display the test parameters so they are captured in the log file
#
Write-Output "TestParams : '${testParams}'"

$summaryLog  = "${vmName}_summary.log"
Del $summaryLog -ErrorAction SilentlyContinue

#
# Parse the test parameters
#
$params = $testParams.TrimEnd(";").Split(";")
foreach ($p in $params)
{
    $fields = $p.Split("=")
    $value = $fields[1].Trim()

    switch ($fields[0].Trim())
    {
    "SSHKey"    { $sshKey  = $fields[1].Trim() }
    "ipv4"      { $ipv4    = $fields[1].Trim() }
    "newSize"   { $newSize = $fields[1].Trim() }
    "rootDIR"   { $rootDir = $fields[1].Trim() }
    "TC_COVERED" { $TC_COVERED = $fields[1].Trim() }
    "TestLogDir" { $TestLogDir = $fields[1].Trim() }
    "TestName"   { $TestName = $fields[1].Trim() }
    "SCSI"  { $controllerType = "SCSI" }
    "IDE"  { $controllerType = "IDE" }
    default     {}  # unknown param - just ignore it
    }
}

if (-not $rootDir)
{
    "Warn: no rootdir was specified"
}
else
{
    cd $rootDir }

# Source TCUtils.ps1
if (Test-Path ".\setupScripts\TCUtils.ps1")
{
    . .\setupScripts\TCUtils.ps1
}
else
{
    "Error: Could not find setupScripts\TCUtils.ps1" | Tee-Object -Append -file $summaryLog
    return $false
}

# if host build number lower than 9600, skip test
$BuildNumber = GetHostBuildNumber $hvServer

if ($BuildNumber -eq 0)
{
    return $false
}
elseif ($BuildNumber -lt 9600)
{
    return $Skipped
}

if ( $controllerType -eq "IDE" )
{
    $vmGeneration = GetVMGeneration $vmName $hvServer
    if ($vmGeneration -eq 2 )
    {
         Write-Output "Generation 2 VM does not support IDE disk, skip test" | Tee-Object -Append -file $summaryLog
         return $Skipped
    }
}

# Source STOR_VHDXResize_Utils.ps1
if (Test-Path ".\setupScripts\STOR_VHDXResize_Utils.ps1")
{
    . .\setupScripts\STOR_VHDXResize_Utils.ps1
}
else
{
    "Error: Could not find setupScripts\STOR_VHDXResize_Utils.ps1" | Tee-Object -Append -file $summaryLog
    return $false
}

Write-Output "Covers: ${TC_COVERED}" | Tee-Object -Append -file $summaryLog

#
# Convert the new size
#
$newVhdxSize = ConvertStringToUInt64 $newSize
$sizeFlag = ConvertStringToUInt64 "20GB"
#
# Make sure the VM has a SCSI 0 controller, and that
# Lun 0 on the controller has a .vhdx file attached.
#

"Info : Check if VM ${vmName} has a $controllerType drive"
$vhdxName = $vmName + "-" + $controllerType
$vhdxDisks = Get-VMHardDiskDrive -VMName $vmName -ComputerName $hvServer

foreach ($vhdx in $vhdxDisks)
{
    $vhdxPath = $vhdx.Path
    if ($vhdxPath.Contains($vhdxName))
    {
        $vhdxDrive = Get-VMHardDiskDrive -VMName $vmName -Controllertype $controllertype -ControllerNumber $vhdx.ControllerNumber -ControllerLocation $vhdx.ControllerLocation -ComputerName $hvServer -ErrorAction SilentlyContinue
    }
}
if (-not $vhdxDrive)
{
    "Error: VM ${vmName} does not have a $controllertype $vhdxDrive.ControllerNumber lun $vhdxDrive.ControllerLocation drive on ${hvServer}" | Tee-Object -Append -file $summaryLog
    $error[0].Exception.Message
    return $False
}

"Info: Check if the virtual disk file exists"
$vhdPath = $vhdxDrive.Path
$vhdxInfo = GetRemoteFileInfo $vhdPath $hvServer
if (-not $vhdxInfo)
{
    "Error: The vhdx file (${vhdPath} does not exist on server ${hvServer}" | Tee-Object -Append -file $summaryLog
    return $False
}

"Info: Verify the file is a .vhdx"
if (-not $vhdPath.EndsWith(".vhdx") -and -not $vhdPath.EndsWith(".avhdx"))
{
    "Error: $controllertype $vhdxDrive.ControllerNumber lun $vhdxDrive.ControllerLocation virtual disk is not a .vhdx file." | Tee-Object -Append -file $summaryLog
    "       Path = ${vhdPath}"
    return $False
}

#
# Make sure there is sufficient disk space to grow the VHDX to the specified size
#
$deviceID = $vhdxInfo.Drive
$diskInfo = Get-WmiObject -Query "SELECT * FROM Win32_LogicalDisk Where DeviceID = '${deviceID}'" -ComputerName $hvServer
if (-not $diskInfo)
{
    "Error: Unable to collect information on drive ${deviceID}" | Tee-Object -Append -file $summaryLog
    return $False
}

# if disk is very large, e.g. 2T with dynamic, require less disk free space
if ($diskInfo.FreeSpace -le $sizeFlag + 10MB)
{
    "Error: Insufficent disk free space" | Tee-Object -Append -file $summaryLog
    "       This test case requires ${newSize} free"
    "       Current free space is $($diskInfo.FreeSpace)"
    return $False
}

#
# Make sure if we can perform Read/Write operations on the guest VM
#

$guest_script = "STOR_VHDXResize_PartitionDisk"

$sts = RunRemoteScriptCheckResult $guest_script
if (-not $($sts[-1]))
{
  "Error: Running '${guest_script}'script failed on VM. check VM logs , exiting test case execution " | Tee-Object -Append -file $summaryLog
  return $False
}

# for IDE need to stop VM before resize

write-output "Controller type is $controllerType"
if ( $controllerType -eq "IDE" )
{
  "Info: Resize IDE disck needs to turn off VM"
  Stop-VM -VMName $vmName -ComputerName $hvServer -force
}

Resize-VHD -Path $vhdPath -SizeBytes ($newVhdxSize) -ComputerName $hvServer -ErrorAction SilentlyContinue

if (-not $?)
{
   "Error: Unable to grow VHDX file '${vhdPath}" | Tee-Object -Append -file $summaryLog
   return $False
}

# Now start the VM if IDE disk attached
if ( $controllerType -eq "IDE" )
{
  $timeout = 300
  $sts = Start-VM -Name $vmName -ComputerName $hvServer
  if (-not (WaitForVMToStartKVP $vmName $hvServer $timeout ))
  {
      Write-Output "ERROR: ${vmName} failed to start" | Tee-Object -Append -file $summaryLog
      return $False
  }
  else
  {
      Write-Output "INFO: Started VM ${vmName}"
  }

}

# check file size after resize
$vhdxInfoResize = Get-VHD -Path $vhdPath -ComputerName $hvServer -ErrorAction SilentlyContinue

if ( $newSize.contains("GB") -and $vhdxInfoResize.Size/1gb -ne $newSize.Trim("GB") )
{
  "Error: Failed to Resize Disk to new Size" | Tee-Object -Append -file $summaryLog
  return $False
}

#
# Let system have some time for the volume change to be indicated
#
Start-Sleep -s 60

#
# Check if the guest sees the added space

#
"Info: Check if the guest sees the new space"
# Older kernels might require a few requests to refresh the disks info
.\bin\plink.exe -i ssh\${sshKey} root@${ipv4} "fdisk -l > /dev/null"

.\bin\plink.exe -i ssh\${sshKey} root@${ipv4} "echo 1 > /sys/block/sdb/device/rescan"
if (-not $?)
{
    "Error: Failed to force $controllerType device rescan" | Tee-Object -Append -file $summaryLog
    return $False
}

$diskSize = .\bin\plink.exe -i ssh\${sshKey} root@${ipv4} "fdisk -l /dev/sdb  2> /dev/null | grep Disk | grep sdb | cut -f 5 -d ' '"
if (-not $?)
{
    "Error: Unable to determine disk size from within the guest after growing the VHDX" | Tee-Object -Append -file $summaryLog
    return $False
}

if ($diskSize -ne $newVhdxSize)
{
    "Error: VM ${vmName} sees a disk size of ${diskSize}, not the expected size of ${newVhdxSize}" | Tee-Object -Append -file $summaryLog
    return $False
}

#
# Make sure if we can perform Read/Write operations on the guest VM
#

if ([int]($newVhdxGrowSize/1gb) -gt 2048)
{
    $guest_script = "STOR_VHDXResize_PartitionDiskOver2TB"
}
else
{
    $guest_script = "STOR_VHDXResize_PartitionDisk"
    $addParam = .\bin\plink.exe -i ssh\${sshKey} root@${ipv4} "echo 'rerun=yes' >> constants.sh"
    if ($? -ne "True")
    {
        "Error: Unable to alter constants.sh for second run. " | Tee-Object -Append -file $summaryLog
        return $False
    }
}

$sts = RunRemoteScriptCheckResult $guest_script
if (-not $($sts[-1]))
{
    "Error: Running '${guest_script}'script failed on VM. check VM logs , exiting test case execution " | Tee-Object -Append -file $summaryLog
    return $False
}
"Info : The guest sees the new size after resizing ($diskSize)" | Tee-Object -Append -file $summaryLog
"Info : VHDx Resize - ${TC_COVERED} is Done"

return $True


text:
.class public interface abstract Lcom/upsight/android/googlepushservices/internal/GooglePushServicesComponent;
.super Ljava/lang/Object;
.source "GooglePushServicesComponent.java"

# interfaces
.implements Lcom/upsight/android/googlepushservices/UpsightGooglePushServicesComponent;

# annotations
.annotation runtime Ldagger/Component;
    modules = {
        Lcom/upsight/android/googlepushservices/internal/GooglePushServicesModule;
    }
.end annotation

.annotation runtime Ljavax/inject/Singleton;
.end annotation


text:
package org.xbmc.kore.jsonrpc;

import androidx.annotation.NonNull;

import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * A Java future implementation, with explicit methods to complete the Future
 * <p>
 * Don't forget that a call to {@link ApiFuture#get()} blocks the current
 * thread until it's unblocked by {@link ApiFuture#cancel(boolean)},
 * {@link ApiFuture#complete(Object)}  or {@link ApiFuture#completeExceptionally(Throwable)}
 *
 * @param <T> The type of the result returned by {@link ApiFuture#get()}
 */
public class ApiFuture<T> implements Future<T> {
    private enum Status { WAITING, OK, ERROR, CANCELLED }
    private final Object lock = new Object();
    private Status status = Status.WAITING;
    private T ok;
    private Throwable error;

    public ApiFuture() {}

    @Override
    public T get() throws InterruptedException, ExecutionException {
        try {
            return get(0, TimeUnit.MILLISECONDS);
        } catch (TimeoutException e) {
            throw new IllegalStateException("Request timed out. This should not happen when time out is disabled!");
        }
    }

    @Override
    public T get(long timeout, @NonNull TimeUnit unit)
            throws InterruptedException, ExecutionException, TimeoutException
    {
        boolean timed = timeout > 0;
        long remaining = unit.toNanos(timeout);
        while (true) synchronized (lock) {
            switch (status) {
                case OK: return ok;
                case ERROR: throw new ExecutionException(error);
                case CANCELLED: throw new CancellationException();
                case WAITING:
                    if (timed && remaining <= 0) {
                        throw new TimeoutException();
                    }
                    if (!timed) {
                        lock.wait();
                    } else {
                        long start = System.nanoTime();
                        TimeUnit.NANOSECONDS.timedWait(lock, remaining);
                        remaining -= System.nanoTime() - start;
                    }
            }
        }
    }

    private boolean setResultAndNotify(Status status, T ok, Throwable error) {
        synchronized (lock) {
            if (this.status != Status.WAITING) {
                return false;
            }

            this.status = status;
            if (status == Status.OK) this.ok = ok;
            if (status == Status.ERROR) this.error = error;

            this.lock.notifyAll();
            return true;
        }
    }

    @Override
    public boolean cancel(boolean b) {
        return setResultAndNotify(Status.CANCELLED, null, null);
    }

    @Override
    public boolean isCancelled() {
        return status == Status.CANCELLED;
    }

    @Override
    public boolean isDone() {
        return status != Status.WAITING;
    }

    /**
     * If not already completed, sets the value returned by get() to the given value.
     * @param value - the result value
     * @return true if this invocation caused this CompletableFuture to transition to a completed state, else false
     */
    public boolean complete(T value) {
        return setResultAndNotify(Status.OK, value, null);
    }

    /**
     * If not already completed, causes invocations of get() to throw the given exception.
     * @param ex = the exception
     * @return true if this invocation caused this CompletableFuture to transition to a completed state, else false
     */
    public boolean completeExceptionally(Throwable ex) {
        return setResultAndNotify(Status.ERROR, null, ex);
    }
}


text:
package monotime

import (
	_ "unsafe" // required to use //go:linkname
)

//go:noescape
//go:linkname nanotime runtime.nanotime
func nanotime() int64

// Now returns the current time in nanoseconds from a monotonic clock.
// The time returned is based on some arbitrary platform-specific point in the
// past.  The time returned is guaranteed to increase monotonically at a
// constant rate, unlike time.Now() from the Go standard library, which may
// slow down, speed up, jump forward or backward, due to NTP activity or leap
// seconds.
func Now() Time {
	return Time(nanotime())
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Duss, Enum. Champ. Guadeloupe (Lons-le-Saunier) 28 (1903)

#### Original name
Polyporus carneopallens Berk.

### Remarks
null


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

    <dimen name="rbm_menu_width">200dp</dimen>

    <dimen name="rbm_item_padding_topbottom">16dp</dimen>
    <dimen name="rbm_item_padding_leftright">8dp</dimen>

    <dimen name="rbm_item_image_height">24dp</dimen>
    <dimen name="rbm_item_image_width">24dp</dimen>

    <dimen name="rbm_item_text_size">16sp</dimen>
    <dimen name="rbm_item_text_padding_left">10dp</dimen>

    <dimen name="rbm_item_text_width">152sp</dimen>

    <dimen name="rbm_tip_text_size">64sp</dimen>

    <!-- -->

    <dimen name="rbm_expanded_item_padding_topbottom">16dp</dimen>
    <dimen name="rbm_expanded_item_padding_leftright">8dp</dimen>

    <!--  -->

    <dimen name="empty">0dp</dimen>
    <dimen name="rbm_item_text_width_empty">128sp</dimen>

    <!--  -->

    <dimen name="rbm_quick_width">32dp</dimen>

    <dimen name="rbm_quick_padding_topbottom">1dp</dimen>
    <dimen name="rbm_quick_padding_leftright">1dp</dimen>

    <dimen name="rbm_quick_text_size">16sp</dimen>
    <dimen name="rbm_quick_text_padding_left">1dp</dimen>

    <!--  -->

    <dimen name="height_list">90dp</dimen>
    <dimen name="padding_default">0dp</dimen>
    <dimen name="size_list_image">64dp</dimen>
    <dimen name="font_size_title">17sp</dimen>
    <dimen name="font_size_description">15sp</dimen>

</resources>


text:
'use strict';

app.controller('UserAdsController',
    function ($scope, $location, $timeout, userService, adsService, notifyService, pageSize) {

        $scope.adsParams = {
            'startPage': 1,
            'pageSize': pageSize
        };

        $scope.reloadUserAds = function () {
            userService.getUserAds(
                $scope.adsParams,
                function success(data) {
                    $scope.ads = data;
                },
                function error(error) {
                    notifyService.showError('Cannot load ads', error)
                }
            )
        };

        $scope.deactivateUserAd = function (id) {
            userService.deactivateAd(id,
                function success() {
                    notifyService.showInfo('Successfully deactivated ad');
                    $scope.reloadUserAds();
                    $location.path('/user/ads')
                },
                function error(error) {
                    notifyService.showError('Cannot deactivate ad', error)
                })
        };

        $scope.publishAgainAd = function (id) {
            userService.publishAgainAd(id,
                function success() {
                    notifyService.showInfo('Successfully published again ad')
                    $scope.reloadUserAds();
                    $timeout(function () {
                        $location.path("/user/ads");
                    }, 5000);
                },
                function error() {
                    notifyService.showError('Cannot publish again ad', error)

                })
        };

        $scope.reloadUserAds();

    });


text:
class ProjectsController < ApplicationController
  before_filter :authenticate, only: [:edit, :destroy, :update]

  def show
    @project = Project.find(params[:id])
  end

  def new
    @project = Project.new
  end

  def edit
    @project = Project.find(params[:id])
  end

  def create
    @project = Project.new(params[:project])

    if @project.save
      redirect_to new_user_path,
                  flash: { success: 'Project was successfully created.' }
    else
      render "new"
    end
  end

  def update
    @project = Project.find(params[:id])

    if @project.update_attributes(params[:project])
      redirect_to @project,
                  flash: {success: 'Project was successfully updated.'}
    else
      render "edit"
    end
  end

  def destroy
    @project = Project.find(params[:id])
    @project.destroy

    redirect_to projects_url
  end
end


text:
'-------------------------------------------------------------------------------------------'
' Inicio del codigo
'-------------------------------------------------------------------------------------------'

'-------------------------------------------------------------------------------------------'
' Inicio de clase "rPrestamos_Trabajador"
'-------------------------------------------------------------------------------------------'
Partial Class rPrestamos_Trabajador
    Inherits vis2formularios.frmReporte

    Dim loObjetoReporte As CrystalDecisions.CrystalReports.Engine.ReportDocument

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Try
            Dim lcParametro0Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(0))
            Dim lcParametro0Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(0))
            Dim lcParametro1Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(1), goServicios.enuOpcionesRedondeo.KN_FechaInicioDelDia)
            Dim lcParametro1Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(1), goServicios.enuOpcionesRedondeo.KN_FechaFinDelDia)
            Dim lcParametro2Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(2))
            Dim lcParametro2Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(2))
            Dim lcParametro3Desde As String = goServicios.mObtenerListaFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(3))
            Dim lcParametro4Desde As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosIniciales(4))
            Dim lcParametro4Hasta As String = goServicios.mObtenerCampoFormatoSQL(cusAplicacion.goReportes.paParametrosFinales(4))

            Dim lcOrdenamiento As String = cusAplicacion.goReportes.pcOrden
            Dim loComandoSeleccionar As New StringBuilder()

            loComandoSeleccionar.AppendLine("SELECT		Prestamos.Documento	                AS Documento,	")
            loComandoSeleccionar.AppendLine("			Prestamos.fec_asi		            AS fec_asi,		")
            loComandoSeleccionar.AppendLine("			Prestamos.[Status]		            AS Estatus,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Cod_Tra		            AS Cod_Tra,		")
            loComandoSeleccionar.AppendLine("			Trabajadores.Nom_Tra	            AS Nom_Tra,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Mon_Bas		            AS Mon_Bas,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Por_Int		            AS Por_Int,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Mon_Int		            AS Mon_Int,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Mon_Net		            AS Mon_Net,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Mon_Pag		            AS Mon_Pag,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Mon_Sal		            AS Mon_Sal,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Cuotas		            AS Cuotas,		")
            loComandoSeleccionar.AppendLine("			(CASE WHEN (Prestamos.Cuotas>0)")
            loComandoSeleccionar.AppendLine("			    THEN Prestamos.Mon_Net/Prestamos.Cuotas")
            loComandoSeleccionar.AppendLine("			    ELSE Prestamos.Mon_Net")
            loComandoSeleccionar.AppendLine("			END)	                           AS Monto_Cuota,")
            loComandoSeleccionar.AppendLine("			Prestamos.Cod_Rev		            AS Cod_Rev,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Motivo		            AS Motivo,		")
            loComandoSeleccionar.AppendLine("			Prestamos.Comentario	            AS Comentario	")
            loComandoSeleccionar.AppendLine("FROM		Prestamos ")
            loComandoSeleccionar.AppendLine("	JOIN	Trabajadores ")
            loComandoSeleccionar.AppendLine("		ON	Trabajadores.cod_Tra = Prestamos.Cod_Tra")
            loComandoSeleccionar.AppendLine("WHERE		Prestamos.Documento BETWEEN " & lcParametro0Desde & " AND " & lcParametro0Hasta)
            loComandoSeleccionar.AppendLine("		AND	Prestamos.fec_asi BETWEEN " & lcParametro1Desde & " AND " & lcParametro1Hasta)
            loComandoSeleccionar.AppendLine("		AND	Prestamos.Cod_Tra BETWEEN " & lcParametro2Desde & " AND " & lcParametro2Hasta)
            loComandoSeleccionar.AppendLine("		AND	Prestamos.Status IN (" & lcParametro3Desde & ")")
            loComandoSeleccionar.AppendLine("		AND	Prestamos.Cod_Rev BETWEEN " & lcParametro4Desde & " AND " & lcParametro4Hasta)
            loComandoSeleccionar.AppendLine("ORDER BY	" & lcOrdenamiento)

            Dim loServicios As New cusDatos.goDatos

            'Me.mEscribirConsulta(loComandoSeleccionar.ToString())
            Dim laDatosReporte As DataSet = loServicios.mObtenerTodosSinEsquema(loComandoSeleccionar.ToString(), "curReportes")

            loObjetoReporte = cusAplicacion.goReportes.mCargarReporte("rPrestamos_Trabajador", laDatosReporte)

            Me.mTraducirReporte(loObjetoReporte)

            Me.mFormatearCamposReporte(loObjetoReporte)

            Me.crvrPrestamos_Trabajador.ReportSource = loObjetoReporte

        Catch loExcepcion As Exception

            Me.WbcAdministradorMensajeModal.mMostrarMensajeModal("Error", _
                 "No se pudo Completar el Proceso: " & loExcepcion.Message, _
                  vis3Controles.wbcAdministradorMensajeModal.enumTipoMensaje.KN_Error, _
                  "auto", _
                  "auto")

        End Try

    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload

        Try

            loObjetoReporte.Close()

        Catch loExcepcion As Exception

        End Try

    End Sub

End Class
'-------------------------------------------------------------------------------------------'
' Fin del codigo																			'
'-------------------------------------------------------------------------------------------'
' RJG: 16/02/13: Codigo inicial.																'
'-------------------------------------------------------------------------------------------'
' RJG: 03/02/14: Se agregó la columna Pagado, y los totales de los montos.																'
'-------------------------------------------------------------------------------------------'


text:
cask "reflector" do
  version "4.1.0,259"
  sha256 "88c59210d290abd21393c9711590c3f5ca5c5aee38568bb8f75d30031dc90089"

  url "https://download.airsquirrels.com/Reflector#{version.major}/Mac/Reflector-#{version.csv.first}.dmg"
  name "Reflector"
  desc "Wireless screen-mirroring application"
  homepage "https://www.airsquirrels.com/reflector/"

  livecheck do
    url "https://updates-prod.airsquirrels.com/Reflector#{version.major}/Mac/updateCheck/"
    strategy :sparkle
  end

  app "Reflector #{version.major}.app"

  zap trash: [
    "~/Library/Application Support/Logs/Reflector*.log*",
    "~/Library/Caches/com.squirrels.Reflector-*",
    "~/Library/Preferences/com.squirrels.Reflector-*.plist",
  ]
end


text:
package upacifico.ec.core.service;

import upacifico.ec.core.entity.Faculty;

import java.util.List;

/**
 * Pacific University http://upacifico.edu.ec
 *
 * @author Msc. Ing. Eduardo Alfonso Sanchez eddie.alfonso@gmail.com
 *         Date & Time: 23/1/2017 14:43
 */
public interface FacultyService {

    public void insert(Faculty entity) throws Throwable;

    public Faculty get(long id) throws Throwable;

    public List<Faculty> getAll() throws Throwable;

    public void update(Faculty entity) throws Throwable;

    public void delete(long id) throws Throwable;

    public void delete(Faculty entity) throws Throwable;
}


text:
void Storage::addDevice(Device *dev)
{
    if (dev == nullptr) return;
    if (m_devices == nullptr) {
        m_devices = (Device*)dev;
        return;
    }

    Device *tmp_dev = m_devices;
    while (tmp_dev->next != nullptr) {
        tmp_dev = tmp_dev->next;
    }

    tmp_dev->next = dev;
}

uint32_t Storage::numDevices()
{
    Device *dev = m_devices;
    if (dev == nullptr) {
        return 0;
    }

    uint32_t num = 1;

    while (dev->next != nullptr) {
        dev = dev->next;
        ++num;
    }
    return num;
}

Storage::Device *Storage::getDevice()
{
    return m_devices;
}

Storage::Device *Storage::nextDevice(Device *dev)
{
    if (dev == nullptr) {
        return nullptr;
    }

    return dev->next;
}


text:
var bridge = function (leafPath) {
    window.rhubarb.viewBridgeClasses.SelectionControlViewBridge.apply(this, arguments);

    if (this.model.SelectedItems.length === 0) {
        this.model.SelectedItems = {};
    }
};

bridge.prototype = new window.rhubarb.viewBridgeClasses.SelectionControlViewBridge();
bridge.prototype.constructor = bridge;

bridge.prototype.attachEvents = function () {
    window.rhubarb.viewBridgeClasses.SelectionControlViewBridge.prototype.attachEvents.apply(this, arguments);

    var self = this;

    $("a", this.element).click(function () {
        var item = $(this).data("item");
        var selectedValueKey = self.getSelectedKeyFromValue(item.value);

        if (selectedValueKey == -1) {
            self.model.SelectedItems.push(item);
        }
        else {
            delete self.model.SelectedItems[selectedValueKey];
        }

        self.saveState();
        self.updateSelectedItems();

        self.valueChanged();

        return false;
    });
};

bridge.prototype.updateSelectedItems = function () {
    var self = this;

    $("a", this.element).each(function () {
        var item = $(this).data("item");
        var selected = self.isValueSelected(item.value);
        if (selected == false) {
            $(this).removeClass("-is-selected");
        }
        else {
            $(this).addClass("-is-selected");
        }
    });
};

window.rhubarb.viewBridgeClasses.ItemToggleViewBridge = bridge;


text:
[![Travis](https://img.shields.io/travis/scaleway/image-app-minecraft.svg)](https://travis-ci.org/scaleway/image-app-minecraft)
[![Scaleway ImageHub](https://img.shields.io/badge/ImageHub-view-ff69b4.svg)](https://hub.scaleway.com/minecraft.html)

Scripts to build the official Minecraft image on Scaleway

This image is built using [Image Tools](https://github.com/scaleway/image-tools) and depends on the official [Java](https://github.com/scaleway/image-app-java) image.

![banner](https://pbs.twimg.com/media/COYa28cWgAE_Ngg.png:medium)

---

**This image is meant to be used on a C1 server.**

We use the Docker's building system and convert it at the end to a disk image that will boot on real servers without Docker. Note that the image is still runnable as a Docker container for debug or for inheritance.

[More info](https://github.com/scaleway/image-tools)

---

## How to connect to your C1 server

See the [documentation](https://www.scaleway.com/docs/create-and-connect-to-your-server/) to connect your to your C1 server.

## Install

Build and write the image to /dev/nbd1 (see [documentation](https://www.scaleway.com/docs/create_an_image_with_docker))

    $ make install

Full list of commands available at: [scaleway/image-tools](https://github.com/scaleway/image-tools/#commands)

## Test

On a running instance:

    $ SCRIPT=$(mktemp); curl -s https://raw.githubusercontent.com/scaleway/image-app-minecraft/master/test.bash > $SCRIPT; bash $SCRIPT

---

A project by [![Scaleway](https://avatars1.githubusercontent.com/u/5185491?v=3&s=42)](https://www.scaleway.com/)


text:
<!DOCTYPE html>

    <title>dc.js - Scatter Plot Example</title>
    <meta charset="UTF-8">
    <link rel="stylesheet" type="text/css" href="../css/dc.css"/>


text:
import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as R from 'ramda';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogContentText from '@mui/material/DialogContentText';
import DialogActions from '@mui/material/DialogActions';
import Button from '@mui/material/Button';
import IconButton from '@mui/material/IconButton';
import Slide from '@mui/material/Slide';
import { MoreVert } from '@mui/icons-material';
import Menu from '@mui/material/Menu';
import MenuItem from '@mui/material/MenuItem';
import { updateAudiencePlayers } from '../../../actions/Audience';
import { updatePlayer, deletePlayer } from '../../../actions/User';
import PlayerForm from './PlayerForm';
import inject18n from '../../../components/i18n';
import { storeHelper, tagsConverter } from '../../../actions/Schema';
import { isExerciseReadOnly } from '../../../utils/Exercise';

const Transition = React.forwardRef((props, ref) => (
  <Slide direction="up" ref={ref} {...props} />
));
Transition.displayName = 'TransitionSlide';

class PlayerPopover extends Component {
  constructor(props) {
    super(props);
    this.state = {
      openDelete: false,
      openEdit: false,
      openRemove: false,
      openPopover: false,
    };
  }

  handlePopoverOpen(event) {
    event.stopPropagation();
    this.setState({ anchorEl: event.currentTarget });
  }

  handlePopoverClose() {
    this.setState({ anchorEl: null });
  }

  handleOpenEdit() {
    this.setState({ openEdit: true });
    this.handlePopoverClose();
  }

  handleCloseEdit() {
    this.setState({ openEdit: false });
  }

  onSubmitEdit(data) {
    const inputValues = R.pipe(
      R.assoc(
        'user_organization',
        data.user_organization && data.user_organization.id
          ? data.user_organization.id
          : data.user_organization,
      ),
      R.assoc('user_tags', R.pluck('id', data.user_tags)),
    )(data);
    return this.props
      .updatePlayer(this.props.user.user_id, inputValues)
      .then(() => this.handleCloseEdit());
  }

  handleOpenDelete() {
    this.setState({ openDelete: true });
    this.handlePopoverClose();
  }

  handleCloseDelete() {
    this.setState({ openDelete: false });
  }

  submitDelete() {
    this.props.deletePlayer(this.props.user.user_id);
    this.handleCloseDelete();
  }

  handleOpenRemove() {
    this.setState({ openRemove: true });
    this.handlePopoverClose();
  }

  handleCloseRemove() {
    this.setState({ openRemove: false });
  }

  submitRemove() {
    this.props.updateAudiencePlayers(
      this.props.exerciseId,
      this.props.audienceId,
      {
        audience_users: R.filter(
          (n) => n !== this.props.user.user_id,
          this.props.audienceUsersIds,
        ),
      },
    );
    this.handleCloseRemove();
  }

  render() {
    const {
      t,
      userAdmin,
      user,
      organizationsMap,
      audienceId,
      exercise,
      tagsMap,
    } = this.props;
    const userOrganizationValue = organizationsMap[user.user_organization];
    const userOrganization = userOrganizationValue
      ? {
        id: userOrganizationValue.organization_id,
        label: userOrganizationValue.organization_name,
      }
      : null;
    const userTags = tagsConverter(user.user_tags, tagsMap);
    const initialValues = R.pipe(
      R.assoc('user_organization', userOrganization),
      R.assoc('user_tags', userTags),
      R.pick([
        'user_firstname',
        'user_lastname',
        'user_email',
        'user_organization',
        'user_phone',
        'user_phone2',
        'user_pgp_key',
        'user_tags',
      ]),
    )(user);
    const canDelete = user.user_email !== 'admin@openex.io' && (userAdmin || !user.user_admin);
    const canUpdateEmail = user.user_email !== 'admin@openex.io' && (userAdmin || !user.user_admin);
    return (
      <div>
        <IconButton
          onClick={this.handlePopoverOpen.bind(this)}
          aria-haspopup="true"
          size="large"
        >
          <MoreVert />
        </IconButton>
        <Menu
          anchorEl={this.state.anchorEl}
          open={Boolean(this.state.anchorEl)}
          onClose={this.handlePopoverClose.bind(this)}
        >
          <MenuItem onClick={this.handleOpenEdit.bind(this)}>
            {t('Update')}
          </MenuItem>
          {audienceId && (
            <MenuItem
              onClick={this.handleOpenRemove.bind(this)}
              disabled={isExerciseReadOnly(exercise)}
            >
              {t('Remove from the audience')}
            </MenuItem>
          )}
          {canDelete && (
            <MenuItem onClick={this.handleOpenDelete.bind(this)}>
              {t('Delete')}
            </MenuItem>
          )}
        </Menu>
        <Dialog
          open={this.state.openDelete}
          TransitionComponent={Transition}
          onClose={this.handleCloseDelete.bind(this)}
          PaperProps={{ elevation: 1 }}
        >
          <DialogContent>
            <DialogContentText>
              {t('Do you want to delete this player?')}
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={this.handleCloseDelete.bind(this)}>
              {t('Cancel')}
            </Button>
            <Button color="secondary" onClick={this.submitDelete.bind(this)}>
              {t('Delete')}
            </Button>
          </DialogActions>
        </Dialog>
        <Dialog
          TransitionComponent={Transition}
          open={this.state.openEdit}
          onClose={this.handleCloseEdit.bind(this)}
          fullWidth={true}
          maxWidth="md"
          PaperProps={{ elevation: 1 }}
        >
          <DialogTitle>{t('Update the player')}</DialogTitle>
          <DialogContent>
            <PlayerForm
              initialValues={initialValues}
              editing={true}
              organizations={R.values(organizationsMap)}
              onSubmit={this.onSubmitEdit.bind(this)}
              handleClose={this.handleCloseEdit.bind(this)}
              canUpdateEmail={canUpdateEmail}
            />
          </DialogContent>
        </Dialog>
        <Dialog
          open={this.state.openRemove}
          TransitionComponent={Transition}
          onClose={this.handleCloseRemove.bind(this)}
          PaperProps={{ elevation: 1 }}
        >
          <DialogContent>
            <DialogContentText>
              {t('Do you want to remove the player from the audience?')}
            </DialogContentText>
          </DialogContent>
          <DialogActions>
            <Button onClick={this.handleCloseRemove.bind(this)}>
              {t('Cancel')}
            </Button>
            <Button color="secondary" onClick={this.submitRemove.bind(this)}>
              {t('Remove')}
            </Button>
          </DialogActions>
        </Dialog>
      </div>
    );
  }
}

PlayerPopover.propTypes = {
  t: PropTypes.func,
  user: PropTypes.object,
  updatePlayer: PropTypes.func,
  deletePlayer: PropTypes.func,
  tags: PropTypes.object,
  userAdmin: PropTypes.bool,
  exerciseId: PropTypes.string,
  exercise: PropTypes.object,
  audienceId: PropTypes.string,
  audienceUsersIds: PropTypes.array,
  tagsMap: PropTypes.object,
  organizationsMap: PropTypes.object,
};

const select = (state, ownProps) => {
  const helper = storeHelper(state);
  const { exerciseId } = ownProps;
  return {
    userAdmin: helper.getMe()?.user_admin,
    exercise: helper.getExercise(exerciseId),
  };
};

export default R.compose(
  connect(select, { updatePlayer, deletePlayer, updateAudiencePlayers }),
  inject18n,
)(PlayerPopover);


text:
package org.collectionspace.csp.api.core;

import org.collectionspace.chain.csp.config.ConfigRoot;
import org.collectionspace.chain.csp.config.Configurable;
import org.collectionspace.csp.api.persistence.Storage;
import org.collectionspace.csp.api.persistence.StorageGenerator;
import org.collectionspace.csp.api.ui.UI;

public interface CSPContext {
	public static final String XXX_GENERAL_SERVICE_PREFIX="org.collectionspace.app.config.persistence.service.";
	public static String XXX_SERVICE_NAME=XXX_GENERAL_SERVICE_PREFIX+"xxxname";

	// Config
	public void addConfigRules(Configurable cfg);
	public void setConfigRoot(ConfigRoot cfg);
	public ConfigRoot getConfigRoot();

	// Storage
	public void addStorageType(String name,StorageGenerator store);

	// UI
	public void addUI(String name,UI ui);

	/* Only after configuration */

	// Storage
	public StorageGenerator getStorage(String name);

	// UI
	public UI getUI(String name);
}


text:
"""
https://pythonhosted.org/psycopg2/advanced.html#asynchronous-notifications

Psycopg allows asynchronous interaction with **other database sessions**

"""

import select
import psycopg2
import psycopg2.extensions

from time import strftime, localtime

def dispatch(notify):
    """ dispatch """

    try:
        v = strftime("%Y-%m-%d %H:%M:%S", localtime())
        print "%s, Got NOTIFY:%s %s %s" %(v, notify.pid, notify.channel, notify.payload )
    except:
        print "Exception"

def listen(DSN, channels):
    """ listen other database sessions

    NOTIFY schedule, 'func.run(''abc'')'
    NOTIFY test, 'run'
    """

    conn = psycopg2.connect(DSN)

    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

    curs = conn.cursor()

    for channel in channels:

        curs.execute("LISTEN %s" % (channel))

        # heartbeat here
        print "Waiting for notifications on channel '%s'" % (channel)

    while True:
        if select.select([conn], [], [], 10) == ([], [], []):
            print "%s : Timeout" % (strftime("%Y-%m-%d %H:%M:%S", localtime()))
        else:
            conn.poll()
            while conn.notifies:
                notify = conn.notifies.pop()
                dispatch(notify)

def main():
    """ main """

    DSN = "dbname=maboss user=mabotech password=mabouser port=6432"

    """
    NOTIFY channel [ , payload ]

    notify test, 'abc1';
    notify test, 'abc2';
    notify test, 'abc3';
    x
    2015-03-15 10:06:57, Got NOTIFY:9596 test abc3
    2015-03-15 10:06:57, Got NOTIFY:9596 test abc2
    2015-03-15 10:06:57, Got NOTIFY:9596 test abc1

    """

    channels = ["schedule", "test"]

    listen(DSN, channels)

if __name__ == "__main__":
    main()


text:
require 'googleauth'

module Maia
  module FCM
    class Credentials
      SCOPE = 'https://www.googleapis.com/auth/firebase.messaging'.freeze

      def initialize(path = ENV['GOOGLE_APPLICATION_CREDENTIALS'], cache: Rails.cache)
        @path  = path
        @cache = cache
      end

      def project
        @project ||= to_h['project_id']
      end

      def token
        @cache.fetch('maia-fcm-token', expires_in: 1.hour) do
          credentials.fetch_access_token!['access_token']
        end
      end

      def to_h
        @to_h ||= JSON.parse file.read
      end

      private
        def file
          if @path && File.exist?(@path)
            File.new @path
          else
            raise Maia::Error::NoCredentials
          end
        end

        def credentials
          @credentials ||= Google::Auth::ServiceAccountCredentials.make_creds(
            json_key_io: file,
            scope: SCOPE
          )
        end
    end
  end
end


text:
<?php

/**
 * @see Zend_Tool_Framework_Manifest_ProviderManifestable
 */
require_once 'Zend/Tool/Framework/Manifest/ProviderManifestable.php';

/**
 * @category   Zend
 * @package    Zend_Tool
 * @copyright  Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
 * @license    http://framework.zend.com/license/new-bsd     New BSD License
 */
class Zend_Tool_Project_Provider_Manifest implements
    Zend_Tool_Framework_Manifest_ProviderManifestable
{

    /**
     * getProviders()
     *
     * @return array Array of Providers
     */
    public function getProviders()
    {
        // the order here will represent what the output will look like when iterating a manifest

        return array(
            // top level project & profile providers
            'Zend_Tool_Project_Provider_Profile',
            'Zend_Tool_Project_Provider_Project',

            // app layer provider
            'Zend_Tool_Project_Provider_Application',

            // MVC layer providers
            'Zend_Tool_Project_Provider_Model',
            'Zend_Tool_Project_Provider_View',
            'Zend_Tool_Project_Provider_Controller',
            'Zend_Tool_Project_Provider_Action',

            // hMVC provider
            'Zend_Tool_Project_Provider_Module',

            // application problem providers
            'Zend_Tool_Project_Provider_Form',
            'Zend_Tool_Project_Provider_Layout',
            'Zend_Tool_Project_Provider_DbAdapter',
            'Zend_Tool_Project_Provider_DbTable',

            // provider within project provider
            'Zend_Tool_Project_Provider_ProjectProvider',

        );
    }
}


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using ONIT.VismaNetApi.Models;

namespace ONIT.VismaNetApi.Lib.Data
{
	public class CustomerInvoiceData : BaseCrudDataClass<CustomerInvoice>
	{
        /// <summary>
		///     This constructor is called by the client to create the data source.
		/// </summary>
		internal CustomerInvoiceData(VismaNetAuthorization auth) : base(auth)
		{
		    ApiControllerUri = VismaNetControllers.CustomerInvoice;
		}

	    protected CustomerInvoiceData() : base(null)
	    {
            ApiControllerUri = VismaNetControllers.CustomerInvoice;

	    }

        /// <summary>
        /// Fetches all invoices for a customer
        /// </summary>
        /// <param name="customerNumber">customerCd</param>
        /// <returns></returns>
        public async Task<List<CustomerInvoice>> ForCustomerAsyncTask(string customerNumber)
        {
            return await VismaNetApiHelper.FetchInvoicesForCustomerCd(customerNumber, Authorization);
        }

        /// <summary>
        /// Fetches all invoices for a given customer
        /// </summary>
        /// <param name="customer">An instance of Customer</param>
        /// <returns></returns>
        public async Task<List<CustomerInvoice>> ForCustomerAsyncTask(Customer customer)
        {
            return await ForCustomerAsyncTask(customer.number);
        }

        public List<CustomerInvoice> ForCustomer(string customerNumber)
        {
            try
            {
                return Task.Run(async () => await ForCustomerAsyncTask(customerNumber)).Result;
            }
            catch (AggregateException e)
            {
                VismaNetExceptionHandler.HandleException(e);
                return null;
            }
        }

	    public List<CustomerInvoice> ForCustomer(Customer customer)
        {
            try
            {
                return Task.Run(async () => await ForCustomerAsyncTask(customer)).Result;
            }
            catch (AggregateException e)
            {
                VismaNetExceptionHandler.HandleException(e);
                return null;
            }
        }

	    public async Task<VismaActionResult> ReleaseInvoice(CustomerInvoice invoice)
	    {
	        return await VismaNetApiHelper.InvoiceAction(invoice.GetIdentificator(), "release", Authorization);
	    }

        public async Task<VismaActionResult> ReverseInvoice(CustomerInvoice invoice)
        {
            return await VismaNetApiHelper.InvoiceAction(invoice.GetIdentificator(), "reverse", Authorization);
        }

	    public async Task<string> AddAttachmentToInvoice(string invoiceNumber, string content, string fileName)
	    {
	        using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
	        {
	            return await AddAttachmentToInvoice(invoiceNumber, memoryStream, fileName);
	        }
	    }
        public async Task<string> AddAttachmentToInvoice(string invoiceNumber, Stream stream, string fileName)
	    {
            if(stream == default(Stream))
                throw new ArgumentNullException(nameof(stream), "Stream is missing");
            if(string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(Path.GetExtension(fileName)))
                throw new ArgumentNullException(nameof(fileName), "File name must be provided and have an extention");
	        return await VismaNetApiHelper.AddAttachmentToInvoice(Authorization, invoiceNumber, stream, fileName);
	    }
    }
}


text:
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/allocator/allocator_shim.h"
#include "base/compiler_specific.h"

#include <dlfcn.h>
#include <malloc.h>

// This translation unit defines a default dispatch for the allocator shim which
// routes allocations to libc functions.
// The code here is strongly inspired from tcmalloc's libc_override_glibc.h.

extern "C" {
void* __libc_malloc(size_t size);
void* __libc_calloc(size_t n, size_t size);
void* __libc_realloc(void* address, size_t size);
void* __libc_memalign(size_t alignment, size_t size);
void __libc_free(void* ptr);
}  // extern "C"

namespace {

using base::allocator::AllocatorDispatch;

void* GlibcMalloc(const AllocatorDispatch*, size_t size, void* context) {
  return __libc_malloc(size);
}

void* GlibcCalloc(const AllocatorDispatch*,
                  size_t n,
                  size_t size,
                  void* context) {
  return __libc_calloc(n, size);
}

void* GlibcRealloc(const AllocatorDispatch*,
                   void* address,
                   size_t size,
                   void* context) {
  return __libc_realloc(address, size);
}

void* GlibcMemalign(const AllocatorDispatch*,
                    size_t alignment,
                    size_t size,
                    void* context) {
  return __libc_memalign(alignment, size);
}

void GlibcFree(const AllocatorDispatch*, void* address, void* context) {
  __libc_free(address);
}

NO_SANITIZE("cfi-icall")
size_t GlibcGetSizeEstimate(const AllocatorDispatch*,
                            void* address,
                            void* context) {
  // glibc does not expose an alias to resolve malloc_usable_size. Dynamically
  // resolve it instead. This should be safe because glibc (and hence dlfcn)
  // does not use malloc_size internally and so there should not be a risk of
  // recursion.
  using MallocUsableSizeFunction = decltype(malloc_usable_size)*;
  static MallocUsableSizeFunction fn_ptr =
      reinterpret_cast<MallocUsableSizeFunction>(
          dlsym(RTLD_NEXT, "malloc_usable_size"));

  return fn_ptr(address);
}

}  // namespace

const AllocatorDispatch AllocatorDispatch::default_dispatch = {
    &GlibcMalloc,          /* alloc_function */
    &GlibcCalloc,          /* alloc_zero_initialized_function */
    &GlibcMemalign,        /* alloc_aligned_function */
    &GlibcRealloc,         /* realloc_function */
    &GlibcFree,            /* free_function */
    &GlibcGetSizeEstimate, /* get_size_estimate_function */
    nullptr,               /* batch_malloc_function */
    nullptr,               /* batch_free_function */
    nullptr,               /* free_definite_size_function */
    nullptr,               /* aligned_malloc_function */
    nullptr,               /* aligned_realloc_function */
    nullptr,               /* aligned_free_function */
    nullptr,               /* next */
};


text:
'use strict';

import '../sass/admin.scss';
import AccountCreate from './components/AccountCreate.js';
import AccountEdit from './components/AccountEdit.js';
import AccountMerge from './components/AccountMerge.js';
import Groups from './components/Groups.js';
import SearchUser from './components/SearchUser.js';

(function() {
    window.NAILS.ADMIN.registerPlugin(
        'nails/module-auth',
        'AccountCreate',
        new AccountCreate()
    );
    window.NAILS.ADMIN.registerPlugin(
        'nails/module-auth',
        'AccountEdit',
        new AccountEdit()
    );
    window.NAILS.ADMIN.registerPlugin(
        'nails/module-auth',
        'AccountMerge',
        new AccountMerge()
    );
    window.NAILS.ADMIN.registerPlugin(
        'nails/module-auth',
        'Groups',
        new Groups()
    );
    window.NAILS.ADMIN.registerPlugin(
        'nails/module-auth',
        'SearchUser',
        new SearchUser(window.NAILS.ADMIN)
    );
})();


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

<TITLE>
B-Index
</TITLE>

<META NAME="date" CONTENT="2013-04-12">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M N O P R S T U V W

B

BAD_WORDS_FIELD_NAME -
Static variable in class com.oregonscientific.meep.permission.User

BadWord - Class in com.oregonscientific.meep.permission
The BadWord object that represents a badWord object in the underlying
 datastore
BadWord() -
Constructor for class com.oregonscientific.meep.permission.BadWord

BadWord(User, String) -
Constructor for class com.oregonscientific.meep.permission.BadWord

BitmapUtils - Class in com.oregonscientific.meep.util
A class containing utility methods related to Bitmaps
BitmapUtils() -
Constructor for class com.oregonscientific.meep.util.BitmapUtils

Blacklist - Class in com.oregonscientific.meep.permission
The Blacklist object that represents a blacklist object in the underlying
 datastore
Blacklist() -
Constructor for class com.oregonscientific.meep.permission.Blacklist

Blacklist(User, String, String) -
Constructor for class com.oregonscientific.meep.permission.Blacklist

BLACKLISTS_FIELD_NAME -
Static variable in class com.oregonscientific.meep.permission.User

      Overview
      Package
      Class
      Use
      Tree
      Deprecated
    Index
      Help

 PREV LETTER
 NEXT LETTER

  FRAMES
 NO FRAMES

  All Classes

A B C D E F G H I J L M N O P R S T U V W


text:
package io.druid.timeline.partition;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Range;

import io.druid.data.input.InputRow;
import io.druid.java.util.common.ISE;

import java.util.List;
import java.util.Map;

/**
 * Class uses getters/setters to work around http://jira.codehaus.org/browse/MSHADE-92
 *
 * Adjust to JsonCreator and final fields when resolved.
 */
public class SingleDimensionShardSpec implements ShardSpec
{
  private String dimension;
  private String start;
  private String end;
  private int partitionNum;

  public SingleDimensionShardSpec()
  {
    this(null, null, null, -1);
  }

  public SingleDimensionShardSpec(
      String dimension,
      String start,
      String end,
      int partitionNum
  )
  {
    this.dimension = dimension;
    this.start = start;
    this.end = end;
    this.partitionNum = partitionNum;
  }

  @JsonProperty("dimension")
  public String getDimension()
  {
    return dimension;
  }

  public void setDimension(String dimension)
  {
    this.dimension = dimension;
  }

  @JsonProperty("start")
  public String getStart()
  {
    return start;
  }

  public void setStart(String start)
  {
    this.start = start;
  }

  @JsonProperty("end")
  public String getEnd()
  {
    return end;
  }

  public void setEnd(String end)
  {
    this.end = end;
  }

  @JsonProperty("partitionNum")
  public int getPartitionNum()
  {
    return partitionNum;
  }

  @Override
  public ShardSpecLookup getLookup(final List<ShardSpec> shardSpecs)
  {
    return new ShardSpecLookup()
    {
      @Override
      public ShardSpec getShardSpec(long timestamp, InputRow row)
      {
        for (ShardSpec spec : shardSpecs) {
          if (spec.isInChunk(timestamp, row)) {
            return spec;
          }
        }
        throw new ISE("row[%s] doesn't fit in any shard[%s]", row, shardSpecs);
      }
    };
  }

  @Override
  public Map<String, Range<String>> getDomain()
  {
    Range<String> range;
    if (start == null && end == null) {
      range = Range.all();
    } else if (start == null) {
      range = Range.atMost(end);
    } else if (end == null) {
      range = Range.atLeast(start);
    } else {
      range = Range.closed(start, end);
    }
    return ImmutableMap.of(dimension, range);
  }

  public void setPartitionNum(int partitionNum)
  {
    this.partitionNum = partitionNum;
  }

  @Override
  public <T> PartitionChunk<T> createChunk(T obj)
  {
    return new StringPartitionChunk<T>(start, end, partitionNum, obj);
  }

  @Override
  public boolean isInChunk(long timestamp, InputRow inputRow)
  {
    final List<String> values = inputRow.getDimension(dimension);

    if (values == null || values.size() != 1) {
      return checkValue(null);
    } else {
      return checkValue(values.get(0));
    }
  }

  private boolean checkValue(String value)
  {
    if (value == null) {
      return start == null;
    }

    if (start == null) {
      return end == null || value.compareTo(end) < 0;
    }

    return value.compareTo(start) >= 0 &&
           (end == null || value.compareTo(end) < 0);
  }

  @Override
  public String toString()
  {
    return "SingleDimensionShardSpec{" +
           "dimension='" + dimension + '\'' +
           ", start='" + start + '\'' +
           ", end='" + end + '\'' +
           ", partitionNum=" + partitionNum +
           '}';
  }
}


text:
module SimpleFeed
  module Activity
    class Base
      attr_reader :feed

      def initialize(feed:)
        @feed = feed
      end
    end
  end
end

require_relative 'multi_user'
require_relative 'single_user'


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TextAdventures.Quest.Functions;

namespace TextAdventures.Quest.Scripts
{
    public class ForScriptConstructor : IScriptConstructor
    {
        #region IScriptConstructor Members

        public string Keyword
        {
            get { return "for"; }
        }

        public IScript Create(string script, ScriptContext scriptContext)
        {
            string afterExpr;
            string param = Utility.GetParameter(script, out afterExpr);
            string loop = Utility.GetScript(afterExpr);

            string[] parameters = Utility.SplitParameter(param).ToArray();
            IScript loopScript = ScriptFactory.CreateScript(loop);

            if (parameters.Count() == 3)
            {
                return new ForScript(scriptContext, ScriptFactory, parameters[0], new Expression<int>(parameters[1], scriptContext), new Expression<int>(parameters[2], scriptContext), loopScript);
            }
            else if (parameters.Count() == 4)
            {
                return new ForScript(scriptContext, ScriptFactory, parameters[0], new Expression<int>(parameters[1], scriptContext), new Expression<int>(parameters[2], scriptContext), new Expression<int>(parameters[3], scriptContext), loopScript);
            }
            else
            {
                throw new Exception(string.Format("'for' script should have 3 or 4 parameters: 'for ({0})'", param));
            }
        }

        public IScriptFactory ScriptFactory { get; set; }

        public WorldModel WorldModel { get; set; }

        #endregion
    }

    public class ForScript : ScriptBase
    {
        private ScriptContext m_scriptContext;
        private IFunction<int> m_from;
        private IFunction<int> m_to;
        private IFunction<int> m_step;
        private IScript m_loopScript;
        private string m_variable;
        private WorldModel m_worldModel;
        private IScriptFactory m_scriptFactory;

        public ForScript(ScriptContext scriptContext, IScriptFactory scriptFactory, string variable, IFunction<int> from, IFunction<int> to, IScript loopScript)
        {
            m_scriptContext = scriptContext;
            m_worldModel = scriptContext.WorldModel;
            m_scriptFactory = scriptFactory;
            m_variable = variable;
            m_from = from;
            m_to = to;
            m_loopScript = loopScript;
        }

        public ForScript(ScriptContext scriptContext, IScriptFactory scriptFactory, string variable, IFunction<int> from, IFunction<int> to, IFunction<int> step, IScript loopScript)
            : this(scriptContext, scriptFactory, variable, from, to, loopScript)
        {
            m_step = step;
        }

        protected override ScriptBase CloneScript()
        {
            return new ForScript(m_scriptContext, m_scriptFactory, m_variable, m_from.Clone(), m_to.Clone(), m_step == null ? null : m_step.Clone(), (IScript)m_loopScript.Clone());
        }

        protected override void ParentUpdated()
        {
            m_loopScript.Parent = Parent;
        }

        public override void Execute(Context c)
        {
            int from = m_from.Execute(c);
            int to = m_to.Execute(c);
            int step = m_step == null ? 1 : m_step.Execute(c);
            int count;
            c.Parameters[m_variable] = 0;

            for (count = from; (step > 0 && count <= to) || (step < 0 && count >= to); count += step)
            {
                c.Parameters[m_variable] = count;
                m_loopScript.Execute(c);
                if (c.IsReturned) break;

                object newCount = c.Parameters[m_variable];
                if (newCount is int)
                {
                    count = (int)newCount;
                }
                else
                {
                    // The type of the count variable has changed, so abort the loop
                    break;
                }
            }
        }

        public override string Save()
        {
            if (m_step == null)
            {
                return SaveScript("for", m_loopScript, m_variable, m_from.Save(), m_to.Save());
            }
            else
            {
                return SaveScript("for", m_loopScript, m_variable, m_from.Save(), m_to.Save(), m_step.Save());
            }
        }

        public override string Keyword
        {
            get
            {
                return "for";
            }
        }

        public override object GetParameter(int index)
        {
            switch (index)
            {
                case 0:
                    return m_variable;
                case 1:
                    return m_from.Save();
                case 2:
                    return m_to.Save();
                case 3:
                    return m_step == null ? null : m_step.Save();
                case 4:
                    return m_loopScript;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public override void SetParameterInternal(int index, object value)
        {
            switch (index)
            {
                case 0:
                    m_variable = (string)value;
                    break;
                case 1:
                    m_from = new Expression<int>((string)value, m_scriptContext);
                    break;
                case 2:
                    m_to = new Expression<int>((string)value, m_scriptContext);
                    break;
                case 3:
                    m_step = new Expression<int>((string)value, m_scriptContext);
                    break;
                case 4:
                    // any updates to the script should change the script itself - nothing should cause SetParameter to be triggered.
                    throw new InvalidOperationException("Attempt to use SetParameter to change the script of a 'for' loop");
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

        public override IEnumerable<string> GetDefinedVariables()
        {
            return new List<string> { m_variable };
        }
    }
}


text:
module('org.tests').requires('org.model', 'org.server', 'lively.TestFramework').toRun(function() {

Object.subclass('org.tests.DummySocket', {
    initialize: function(broadcast) {
        this.messages = [];
        if (broadcast) {
            this.broadcast = new org.tests.DummySocket();
        }
    },
    emit: function() {
        this.messages.push(Array.from(arguments));
    },
    transport: function(otherHub) {
        this.messages.each(function(m) {
            if (m[0] == 'change') {
                m.shift();
                otherHub.receiveChange.apply(otherHub, m);
            } else if (m[0] == 'ok') {
                m.shift();
                otherHub.successfulChange.apply(otherHub, m);
            }
        });
        this.messages = [];
    }
});

org.model.ClientHub.subclass('org.tests.ClientHub', {
    initialize: function($super) {
        $super();
        this.socket = new org.tests.DummySocket();
        this.pendingChanges = [];
    },
    sendPendingChanges: function() {
        this.pendingChanges.each(function(m) { m.timestamp = 13e11; });
    }
});

org.server.ServerHub.subclass('org.tests.ServerHub', {
    initialize: function($super) {
        $super();
        this.socket = new org.tests.DummySocket(true);
        this.mutex = {
            lock: function(fn) { fn(); },
            release: function() {}
        };
    },
    saveChange: function(change, cb) { cb(); },
    sendUpdates: function($super, socket, change, prevHash) {
        $super(this.socket, change, prevHash);
    }
});

TestCase.subclass('org.tests.Base',
'helping', {
    copyHub: function() {
        var data = this.hub.asData();
        this.hub.loadComplete(JSON.stringify(data));
    },
    createJohn: function() {
        var john = new org.model.User("PK1");
        john.setFirstName("John");
        john.setLastName("Doe");
        john.setEmail("john.doe@example.com");
        john.setCompany("ACME Inc.");
        john.setOffice("Sao Paulo, Brazil");
        john.setPhone("+1 555 664-2962");
        this.hub.addUser(john);
        return john;
    },
    createJane: function() {
        var jane = new org.model.User("PK2");
        jane.setFirstName("Jane");
        jane.setLastName("Doe");
        jane.setEmail("jane.doe@example.com");
        jane.setCompany("ACME Inc. Outer Rim");
        jane.setOffice("London, UK");
        this.hub.addUser(jane);
        return jane;
    },
    createOmega: function() {
        var omega = new org.model.Project("omega");
        omega.setName('Omega Project');
        omega.setDescription('An ACME project to explore the space beyond the Outer Rim.');
        this.hub.addProject(omega);
        return omega;
    },
},
'running', {
    setUp: function() {
        this.hub = new org.tests.ClientHub();
        this.john = this.createJohn();
        this.jane = this.createJane();
    }
});

org.tests.Base.subclass('org.tests.ModelTests',
'running', {
    setUp: function($super) {
        $super();
        this.omega = this.createOmega();
        this.john.addProject(this.omega);
    }
},
'testing', {
    testGetUser: function() {
        var john = this.hub.users["PK1"];
        this.assertIdentity(this.john, john);
        this.assertEquals("PK1", john.getId());
        this.assertEquals("John", john.getFirstName());
        this.assertEquals("Doe", john.getLastName());
        this.assertEquals("John Doe", john.getName());
        this.assertEquals("john.doe@example.com", john.getEmail());
        this.assertEquals("+1 555 664-2962", john.getPhone());
        this.assertEquals("ACME Inc.", john.getCompany());
        this.assertEquals("Sao Paulo, Brazil", john.getOffice());
    },
    testAnonymous: function() {
        var anon = this.hub.users["anonymous"];
        this.assert(anon.isAnonymous());
        this.assertEquals("Anonymous", anon.getFirstName());
        this.assertEquals("", anon.getLastName());
        this.assertEquals("Anonymous", anon.getName());
    },
    testGetWithType: function() {
        var type = org.model.User.prototype.typeCode;
        var john = this.hub.get(type, 'PK1');
        var john2 = this.hub.users['PK1'];
        this.assertIdentity(this.john, john);
        this.assertIdentity(john, john2);
    },
    testGetProject: function() {
        var omega = this.hub.getProjects().first();
        this.assertIdentity(this.omega, omega);
        this.assertEquals("Omega Project", omega.getName());
    },
    testGetProjectsOfUser: function() {
        this.assertEqualState([this.omega], this.john.getProjects());
        this.assertEqualState([], this.jane.getProjects());
    },
    testGetProjectMembers: function() {
        this.assertEqualState([this.john], this.omega.getMembers());
    },
    testUserImageURL: function() {
        this.assertEquals(
            URL.root + "nodejs/org/images/PK1",
            this.john.getImageURL());
        this.assertEquals(
            URL.root + "nodejs/org/images/PK2",
            this.jane.getImageURL());
    },
    testUpdateProject: function() {
        var desc = "A project to enable people to control their dreams.";
        this.omega.setDescription(desc);
        this.assertEquals(desc, this.omega.getDescription());
    },
    testSearchIndex: function() {
        var a = {getSearchDocument: function() { return 'aa'; }};
        this.hub.initializeIndex(); // reset index
        this.hub.indexEntity(a);
        this.assertEqualState({a: {_: [a]}, _: {}}, this.hub.index.a);
        this.assertEqualState([a], this.hub.lookup('aa'));
    },
    testUniversalSearch: function() {
        this.assertEqualState([this.omega], this.hub.search("omega"));
        this.assertEqualState([this.omega], this.hub.search("beyond"));
        this.assertEqualState([this.jane, this.omega], this.hub.search("outer rim"));
        this.assertEqualState([this.jane, this.omega], this.hub.search("Outer Rim"));
        this.assertEqualState([this.john, this.jane, this.omega], this.hub.search("ACME"));
        this.assertEqualState([this.john, this.jane], this.hub.search("doe"));
        this.assertEqualState([], this.hub.search("bfghz"));
    },
    testCreateNewNote: function() {
        var note = this.hub.createNote();
        var creator = note.getCreator();
        this.assertIdentity(this.hub.me(), creator);
        this.epsilon = 1000;
        this.assertEqualsEpsilon(new Date(), note.getCreationDate());
        var sameNote = this.hub.notes[note];
        note.setContent("foobar");
        this.assertEquals(sameNote.getContent(), note.getContent());
    },
    testFindNote: function() {
        var note = this.hub.createNote();
        note.setContent('Lorem ipsum dolor sit amet');
        this.assertEqualState([note], this.hub.search("Lorem"));
        this.assertEqualState([note], this.hub.search("lorem"));
        this.assertEqualState([], this.hub.search("loren"));
        this.assertEqualState([note], this.hub.search("lor"));
        this.assertEqualState([], this.hub.search("olo"));
        note.setContent('orem ipsum dolor sit amet');
        this.assertEqualState([], this.hub.search("Lorem"));
        this.assertEqualState([], this.hub.search("Lor"));
    },
    testAttachNote: function() {
        var note = this.hub.createNote();
        note.setContent('Lorem ipsum dolor sit amet');
        this.john.addNote(note);
        this.assertIdentity(this.john, note.getEntity());
        this.assertEqualState([note], this.john.getNotes());
    },
    testDetachNote: function() {
        var note = this.hub.createNote();
        note.setContent('Lorem ipsum dolor sit amet');
        this.john.addNote(note);
        this.john.removeNote(note);
        this.assertIdentity(null, note.getEntity());
        this.assertEqualState([], this.john.getNotes());
    },
    testNoteEnglishDate: function() {
        var note = this.hub.createNote(),
            now = new Date();

        var fiveMinutesAgo = new Date(now.getTime() - 5 * 60 * 1000);
        note.setCreationDate(fiveMinutesAgo);
        this.assertEquals("5 minutes ago", note.getCreationDateInEnglish());

        var halfADayAgo = new Date(now.getTime() - 13 * 60 * 60 * 1000);
        note.setCreationDate(halfADayAgo);
        var englishDay = /^(Yester|To)day at [0-2][0-9]?:[0-5][0-9]$/;
        this.assert(englishDay.test(note.getCreationDateInEnglish()));

        var sixMonthsAgo = new Date(now.getTime() - 180 * 24 * 60 * 60 * 1000);
        note.setCreationDate(sixMonthsAgo);
        var englishDate = sixMonthsAgo.format("d mmm yyyy");
        this.assertEquals(englishDate, note.getCreationDateInEnglish());
    },
    testRemoveNote: function() {
        var note = this.hub.createNote();
        note.setContent('Lorem ipsum dolor sit amet');
        this.john.addNote(note);
        this.hub.removeNote(note);
        this.assertIdentity(null, note.getEntity());
        this.assertEqualState([], this.john.getNotes());
        this.assertEqualState([], this.hub.getNotes());
        this.assertEqualState([], this.hub.search("Lorem"));
    },
    testAssignProject: function() {
        this.jane.addProject(this.omega);
        this.assertEqualState([this.omega], this.jane.getProjects());
        this.assertEqualState([this.john, this.jane], this.omega.getMembers());
    },
    testAddProjectMember: function() {
        this.omega.addMember(this.jane);
        this.assertEqualState([this.omega], this.jane.getProjects());
        this.assertEqualState([this.john, this.jane], this.omega.getMembers());
    },
    testUnassignProject: function() {
        this.john.removeProject(this.omega);
        this.assertEqualState([], this.john.getProjects());
        this.assertEqualState([], this.omega.getMembers());
    },
    testRemoveProjectMember: function() {
        this.omega.removeMember(this.john);
        this.assertEqualState([], this.john.getProjects());
        this.assertEqualState([], this.omega.getMembers());
    },
    testTags: function() {
        var note = this.hub.createNote();
        note.setContent('#Lorem() ipsum #dolor s#it #amet.');
        var expectedTags = ['#Lorem', '#dolor', '#amet'];
        this.assertEqualState(expectedTags, note.getTags());
        expectedTags.each(function(tag) {
            this.assert(note.hasTag(tag));
        }, this);
    },
    testSearchGroupsForNotes: function() {
        var note = this.hub.createNote();
        this.assertEquals('Today', note.getSearchGroup());
        note.setCreationDate(new Date(2008, 11, 24));
        this.assertEquals('24 Dec 2008', note.getSearchGroup());
    }
});

org.tests.Base.subclass('org.tests.ChangeTests',
'running', {
    setUp: function($super) {
        $super();
        this.omega = this.createOmega();
        this.tau = this.createTau();
        this.john.addProject(this.omega);
        this.hub.pendingChanges = [];
        var data = JSON.stringify(this.hub.asData());
        this.hub2 = new org.tests.ClientHub();
        this.hub2.loadComplete(data);
        this.omega2 = this.hub2.projects.omega;
        this.tau2 = this.hub2.projects.tau;
        this.server = new org.tests.ServerHub();
        this.server.loadComplete(data);
    }
},
'helping', {
    createTau: function() {
        var tau = this.hub.createProject('tau');
        tau.setName('Tau Project');
        tau.setDescription('A project to create products which reverse the human aging process.');
        return tau;
    },
    assertSync: function() {
        this.assertEqualState(this.hub.asData(), this.server.asData());
        this.assertEqualState(this.hub.asData(), this.hub2.asData());
        this.assertEqualState([], this.hub.pendingChanges);
        this.assertEqualState([], this.hub2.pendingChanges);
    },
    assertMessage: function(hub, subject, message, value, username, optPrevHash) {
        var msg = hub.socket.messages.shift();
        this.assertEqualState(subject, msg[1]);
        this.assertEqualState(message, msg[2]);
        this.assertEqualState(value, msg[3]);
        this.assertEqualState(username, msg[4]);
        if (optPrevHash !== undefined) {
            this.assertEqualState(optPrevHash, msg[6]);
        }
    },
    sync: function() {
        this.hub.sendPendingChangesImpl();
        this.hub.socket.transport(this.server);
        this.server.socket.transport(this.hub);
        this.server.socket.broadcast.transport(this.hub2);
        this.hub2.sendPendingChangesImpl();
        this.hub2.socket.transport(this.server);
        this.server.socket.transport(this.hub2);
        this.server.socket.broadcast.transport(this.hub);
        this.assertSync();
    }
},
'testing', {
    testSimpleChanges: function() {
        var desc = "A project to enable people to control their dreams.";
        this.omega.setDescription(desc);
        this.hub.sendPendingChangesImpl();
        this.assertMessage(this.hub, "pomega", "=description", desc, "anonymous", "00000000");
        var desc2 = "A project to create affordable personal levitation devices.";
        this.omega.setDescription(desc2);
        this.hub.sendPendingChangesImpl();
        this.assertMessage(this.hub, "pomega", "=description", desc2, "anonymous", "e96a8414");
    },
    testDiscardRedundantChanges: function() {
        var desc = "A project to enable people to control their dreams.";
        this.omega.setDescription(desc);
        var desc2 = "A project to create affordable personal levitation devices.";
        this.omega.setDescription(desc2);
        this.hub.sendPendingChangesImpl();
        this.assertMessage(this.hub, "pomega", "=description", desc2, "anonymous", "00000000");
    },
    testStartsSynced: function() {
        this.assertSync();
    },
    testUpdateProject: function() {
        var desc = "A project to enable people to control their dreams.";
        this.omega.setDescription(desc);
        this.sync();
    },
    testRollbackUpdateProject: function() {
        var oldDesc = this.omega.getDescription();
        var newDesc = "A project to enable people to control their dreams.";
        this.omega.setDescription(newDesc);
        this.assertEquals(1, this.hub.pendingChanges.length);
        var change = this.hub.pendingChanges[0];
        this.assertEquals(newDesc, this.omega.getDescription());
        this.hub.rollbackPendingChanges();
        this.assertEquals(oldDesc, this.omega.getDescription());
        change.apply();
        this.assertEquals(newDesc, this.omega.getDescription());
    },
    testConcurrentUpdates: function() {
        var desc2 = "A project to create affordable personal levitation devices.";
        var desc = "A project to enable people to control their dreams.";
        this.tau2.setDescription(desc2);
        this.omega.setDescription(desc);
        this.hub2.sendPendingChangesImpl();
        this.hub.sendPendingChangesImpl();
        this.hub2.socket.transport(this.server);
        this.hub.socket.transport(this.server);
        // both hub and hub2 have pending changes and wait for the servers' response
        this.assertEquals(1, this.hub.pendingChanges.length);
        this.assertEquals(1, this.hub2.pendingChanges.length);
        this.assertEqualState( // hub2 was first, so it gets ok
            [['ok', '2a4c7e0f']],
            this.server.socket.messages);
        this.assertEqualState( // hub2 was too late, it gets the other change
            [["change", "ptau", "=description", desc2, "anonymous", 13e11, "00000000"]],
            this.server.socket.broadcast.messages);
        // send messages from the server to hub and hub2
        this.server.socket.transport(this.hub2);
        this.server.socket.broadcast.transport(this.hub);
        // hub2 is already up-to-date
        this.assertEquals(this.server.hash, this.hub2.hash);
        this.assertEqualState([], this.hub2.pendingChanges);
        // hub got the change, applied it first and applied its own change on top of it
        this.assertEquals(desc, this.omega.getDescription());
        this.assertEquals(desc2, this.tau.getDescription());
        this.assertEquals(this.server.hash, this.hub.hash);
        this.assertEquals(1, this.hub.pendingChanges.length);
        this.assertEquals(this.omega, this.hub.pendingChanges[0].subject);
        this.assertEquals("=description", this.hub.pendingChanges[0].message);
        this.assertEquals(desc, this.hub.pendingChanges[0].value);
        // sending this pending change will sync server and hub2 again
        this.sync();
        this.assertEquals(desc, this.omega.getDescription());
        this.assertEquals(desc, this.omega2.getDescription());
        this.assertEquals(desc2, this.tau.getDescription());
        this.assertEquals(desc2, this.tau2.getDescription());
    },
    testConflictingUpdates: function() {
        var desc2 = "A project to create affordable personal levitation devices.";
        var desc = "A project to enable people to control their dreams.";
        this.omega2.setDescription(desc2);
        this.omega.setDescription(desc);
        this.hub2.sendPendingChangesImpl();
        this.hub.sendPendingChangesImpl();
        this.hub2.socket.transport(this.server);
        this.hub.socket.transport(this.server);
        // both hub and hub2 have pending changes and wait for the servers' response
        this.assertEquals(1, this.hub.pendingChanges.length);
        this.assertEquals(1, this.hub2.pendingChanges.length);
        this.assertEqualState( // hub2 was first, so it gets ok
            [['ok', '249c33f6']],
            this.server.socket.messages);
        this.assertEqualState( // hub2 was too late, it gets the other change
            [["change", "pomega", "=description", desc2, "anonymous", 13e11, "00000000"]],
            this.server.socket.broadcast.messages);
        // send messages from the server to hub and hub2
        this.server.socket.transport(this.hub2);
        this.server.socket.broadcast.transport(this.hub);
        // hub2 is already up-to-date
        this.assertEquals(this.server.hash, this.hub2.hash);
        this.assertEqualState([], this.hub2.pendingChanges);
        // hub got the change, applied it first and applied its own change on top of it
        this.assertEquals(this.server.hash, this.hub.hash);
        this.assertEquals(1, this.hub.pendingChanges.length);
        // sending this pending change will sync server and hub2 again
        this.sync();
        this.assertEquals(desc, this.omega.getDescription());
        this.assertEquals(desc, this.omega2.getDescription());
    },
    testCreateNote: function() {
        var note = this.hub.createNote();
        var str = "Lorem ipsum dolor sit amet.";
        note.setContent(str);
        this.hub.sendPendingChangesImpl();
        this.assertMessage(this.hub, "/", "+note", note.getReference(), "anonymous", "00000000");
        var nid = note.getTypedId();
        var me = this.hub.me().getReference();
        this.assertMessage(this.hub, nid, "=creator", me, "anonymous", "09dca58b");
        var creation = {$t: note.getCreationDate().getTime()};
        this.assertMessage(this.hub, nid, "=creationDate", creation, "anonymous");
        this.assertMessage(this.hub, nid, "=content", str, "anonymous");
    },
    testDeleteNote: function() {
        var note = this.hub.createNote();
        note.setContent("Lorem ipsum dolor sit amet.");
        this.sync();
        this.hub.deleteNote(note);
        this.sync();
    },
    testCreateProject: function() {
        var project = this.hub.createProject();
        project.setName("Aldabaran");
        project.setDescription("Lorem ipsum dolor sit amet.");
        this.sync();
    },
    testTwoNotesSimultaneously: function() {
        var noteA = this.hub.createNote();
        noteA.setContent("Lorem ipsum dolor sit amet.");
        var noteB = this.hub2.createNote();
        noteB.setContent("Example text.");
        this.hub.sendPendingChangesImpl();
        this.hub2.sendPendingChangesImpl();
        this.sync();
    },
    testAssignProject: function() {
        this.john.addProject(this.tau);
        this.sync();
    },
    testAddProjectMember: function() {
        this.tau.addMember(this.john);
        this.sync();
    },
    testUnassignProject: function() {
        this.john.removeProject(this.omega);
        this.sync();
    },
    testRemoveProjectMember: function() {
        this.omega.removeMember(this.john);
        this.sync();
    }
});

}) // end of module


text:
using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;
using SqlToRestApi.Services;

namespace SqlToRestApi.Filters
{
    public class AuthorizationRequiredAttribute : ActionFilterAttribute
    {
        private const string ApiKey = "ApiKey";

        public override void OnActionExecuting(HttpActionContext filterContext)
        {
            //  Get API key provider
            var provider = new ApiKeyService();

            var msgUnauthorized = new { Message = "Authorization required" };

            var reqOptions = filterContext.Request.GetQueryNameValuePairs().ToDictionary(x => x.Key, x => x.Value);

            var keyValue = "";

            if (!Config.AuthorizationRequired)
            {
                keyValue = "None";
            }
             else if (filterContext.Request.Headers.Contains(ApiKey))
            {
                keyValue = filterContext.Request.Headers.GetValues(ApiKey).First();
            }
            else if (reqOptions.ContainsKey(ApiKey))
            {
                keyValue = reqOptions[ApiKey];
            }

            // Validate Token
            if (string.IsNullOrEmpty(keyValue) || !provider.ValidateKey(keyValue))
            {
                filterContext.Response = filterContext.Request.CreateResponse(HttpStatusCode.Unauthorized, msgUnauthorized);
                filterContext.Response.ReasonPhrase = "Unauthorized";
            }
            else
            {
                var controller = filterContext.ControllerContext.Controller;

                var controllerUser = controller.GetType().GetProperty("CurrentUser");
                if (controllerUser != null)
                {
                    var user = provider.ApiKey.User;
                    controllerUser.SetValue(controller, user);
                }
            }

            base.OnActionExecuting(filterContext);
        }
    }
}


text:
<?php

namespace Knp\Component\Pager\Event\Subscriber\Paginate;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Knp\Component\Pager\Event\ItemsEvent;
use ArrayObject;

class ArraySubscriber implements EventSubscriberInterface
{
    public function items(ItemsEvent $event)
    {
        if (is_array($event->target)) {
            $event->count = count($event->target);
            $event->items = array_slice(
                $event->target,
                $event->getOffset(),
                $event->getLimit()
            );
            $event->stopPropagation();
        } elseif ($event->target instanceof ArrayObject) {
            $event->count = $event->target->count();
            $event->items = new ArrayObject(array_slice(
                $event->target->getArrayCopy(),
                $event->getOffset(),
                $event->getLimit()
            ));
            $event->stopPropagation();
        }
    }

    public static function getSubscribedEvents()
    {
        return array(
            'knp_pager.items' => array('items', 0)
        );
    }
}


text:
'use strict';

function ExampleService($http) {

  const service = {};

  service.get = function() {
    return new Promise((resolve, reject) => {
      $http.get('apiPath').success((data) => {
        resolve(data);
      }).error((err, status) => {
        reject(err, status);
      });
    });
  };

  return service;

}

export default {
  name: 'ExampleService',
  fn: ExampleService
};