text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.communication.sms;

import com.azure.communication.common.PhoneNumber;
import com.azure.communication.sms.models.SendSmsOptions;
import com.azure.communication.sms.models.SendSmsResponse;
import com.azure.core.annotation.ReturnType;
import com.azure.core.annotation.ServiceClient;
import com.azure.core.annotation.ServiceMethod;
import com.azure.core.http.rest.Response;
import com.azure.core.util.Context;
import com.azure.core.util.logging.ClientLogger;

import java.util.List;
import java.util.ArrayList;

/**
 * Client for sending SMS messages with Azure Communication SMS Services.
 */
@ServiceClient(builder = SmsClientBuilder.class)
public final class SmsClient {
    private final SmsAsyncClient smsAsyncClient;
    private final ClientLogger logger = new ClientLogger(SmsClient.class);

    SmsClient(SmsAsyncClient smsAsyncClient) {
        this.smsAsyncClient = smsAsyncClient;
    }

        /**
     * Sends an SMS message from a phone number that belongs to the authenticated account.
     *
     * @param from Number that is sending the message.
     * @param to The recipient's phone number. In this version, only one recipient in the list is supported.
     * @param message message to send to recipient.
     * @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
     * for this message to the Azure Resource Event Grid.
     * @param context the context of the request. Can also be null or Context.NONE.
     * @return response for a successful send Sms request.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public Response<SendSmsResponse> sendMessageWithResponse(PhoneNumber from, List<PhoneNumber> to, String message,
        SendSmsOptions smsOptions, Context context) {
        return this.smsAsyncClient.sendMessageWithResponse(from, to, message, smsOptions, context).block();
    }

    /**
     * Sends an SMS message from a phone number that belongs to the authenticated account.
     *
     * @param from Number that is sending the message.
     * @param to The recipient's phone number. In this version, only one recipient in the
     * list is supported.
     * @param message message to send to recipient.
     * @return response for a successful send Sms request.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public SendSmsResponse sendMessage(PhoneNumber from, List<PhoneNumber> to, String message) {
        return this.smsAsyncClient.sendMessage(from, to, message).block();
    }

    /**
     * Sends an SMS message from a phone number that belongs to the authenticated account.
     *
     * @param from Number that is sending the message.
     * @param to The recipient's phone number.
     * @param message message to send to recipient.
     * @return response for a successful send Sms request.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public SendSmsResponse sendMessage(PhoneNumber from, PhoneNumber to, String message) {
        if (to == null) {
            logger.logThrowableAsError(new NullPointerException("Argument 'to' cannot be null."));
        }

        List<PhoneNumber> toList = new ArrayList<PhoneNumber>();
        toList.add(to);

        return this.smsAsyncClient.sendMessage(from, toList, message).block();
    }

    /**
     * Sends an SMS message from a phone number that belongs to the authenticated account.
     *
     * @param from Number that is sending the message.
     * @param to The recipient's phone number. In this version, only one recipient in the
     * list is supported.
     * @param message message to send to recipient.
     * @param smsOptions set options on the SMS request, like enable delivery report, which sends a report
     * for this message to the Azure Resource Event Grid.
     * @return response for a successful send Sms request.
     */
    @ServiceMethod(returns = ReturnType.SINGLE)
    public SendSmsResponse sendMessage(PhoneNumber from, List<PhoneNumber> to, String message,
        SendSmsOptions smsOptions) {
        return this.smsAsyncClient.sendMessage(from, to, message, smsOptions).block();
    }
}


text:
Unesite novu Lozinku

        <form id="passwordchange-form" role="form" action="<?php echo site_url("home/attemptSetNewPassowrd"); ?>" method="post">
            <?php
            if ($failed & EMPTYPASSWORD):
                echo '
Unesite lozinku
';
            elseif ($failed & PASSWORDFORMAT):
                echo '
Lozinka mora da sadrži najmanje 8 karaktera i barem jedan broj
';
            endif;
            ?>

                Lozinka
                <input type="password" class="form-control" name="pass" id="email"/>

            <?php
            if ($failed & EMPTYPASSWORDCONFIRM):
                echo '
Morate potvrditi lozinku
';
            elseif ($failed & PASSWORDMATCH):
                echo '
Lozinke se moraju poklapati
';
            endif;
            ?>

                Ponovljena Lozinka
                <input type="password" name="pass1" class="form-control" id="password"/>

            <button type="submit"  class="btn btn-lg btn-primary">Promeni lozinku se</button>
        </form>

<img src="<?php echo base_url(); ?>img/sloth.png" class="img-responsive center-block" >

redpajama_set_name: RedPajamaGithub


text:
package org.apache.ignite.ml.xgboost;

import org.apache.ignite.ml.xgboost.parser.XGBoostModelParserTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;

/** Test suite for all module tests. */
@RunWith(Suite.class)
@Suite.SuiteClasses({
    XGBoostModelParserTest.class
})
public class IgniteMLXGBoostTestSuite {
    // No-op.
}


text:
import * as angular from 'angular';

class BrowserDetectorService{

	public isMobile;
	public isBrowser;

	constructor(){
		this.isMobile = {
			Android: () => {
				return navigator.userAgent.match(/Android/i);
			},
			BlackBerry: () => {
				return navigator.userAgent.match(/BlackBerry/i);
			},
			iOS: () => {
				return navigator.userAgent.match(/iPhone|iPad|iPod/i);
			},
			Opera: () => {
				return navigator.userAgent.match(/Opera Mini/i);
			},
			Windows: () => {
				return navigator.userAgent.match(/IEMobile/i);
			},
			any: () => {
				return (this.isMobile.Android() ||
				this.isMobile.BlackBerry() ||
				this.isMobile.iOS() ||
				this.isMobile.Opera() ||
				this.isMobile.Windows());
			}
		};

		this.isBrowser = {
			Firefox: () => {
				return navigator.userAgent.match(/Firefox/i);
			},
			Chrome: () => {
				return navigator.userAgent.match(/Chrome/i);
			},
			InternetExplorer: () => {
				return navigator.userAgent.match(/MSIE/i);
			},
			Opera: () => {
				return navigator.userAgent.match(/Opera/i);
			},
			PhantomJS: () => {
				return navigator.userAgent.match(/PhantomJS/i);
			},
			HeadlessChrome: () => {
				return navigator.userAgent.match(/HeadlessChrome/i);
			},
			Safari: () => {
				return Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
			},
			any: () => {
				return (this.isBrowser.Firefox() ||
				this.isBrowser.Chrome() ||
				this.isBrowser.InternetExplorer() ||
				this.isBrowser.Opera() ||
				this.isBrowser.Safari() ||
				this.isBrowser.PhantomJS());
			}
		};

	}

	public isMobileDevice() {
		var data = this.isMobile.any();
		if (data === null) {
			return false;
		}
		else {
			if (data.length > 0) {
				return true;
			}
			else {
				return false;
			}
		}
	};

	public isDesktopDevice () {
		var data = this.isBrowser.any();
		if (data === null) {
			return false;
		}
		else {
			if (data.length > 0) {
				return true;
			}
			else {
				return false;
			}
		}
	};

}

angular.module('emuwebApp')
.service('BrowserDetectorService', BrowserDetectorService);


text:
namespace MailMessaging.Plain.Contracts.Commands
{
    public enum ResponseResult
    {
        // ReSharper disable InconsistentNaming
        OK,
        NO,
        BAD
        // ReSharper restore InconsistentNaming
    }
}


text:
package org.apache.sis.console;

import java.net.URL;
import org.apache.sis.internal.storage.gpx.MetadataTest;
import org.apache.sis.metadata.xml.TestUsingFile;
import org.apache.sis.test.DependsOn;
import org.junit.Test;

import static org.junit.Assert.*;
import static org.apache.sis.metadata.iso.extent.DefaultExtentTest.FILENAME;

/**
 * Tests the {@link MimeTypeCommand} sub-command.
 *
 * @author  Martin Desruisseaux (Geomatys)
 * @version 1.0
 * @since   0.4
 * @module
 */
@DependsOn(CommandRunnerTest.class)
public final strictfp class MimeTypeCommandTest extends TestUsingFile {
    /**
     * Tests the sub-command on a metadata file.
     *
     * @throws Exception if an error occurred while reading the test file.
     */
    @Test
    public void testWithMetadataXML() throws Exception {
        final URL url = TestUsingFile.class.getResource(XML2007+FILENAME);
        final MimeTypeCommand test = new MimeTypeCommand(0, CommandRunner.TEST, url.toString());
        test.run();
        final String output = test.outputBuffer.toString().trim();
        assertTrue(output, output.endsWith(".xml: application/vnd.iso.19139+xml"));
    }

    /**
     * Tests the sub-command on a GPX file.
     *
     * @throws Exception if an error occurred while reading the test file.
     */
    @Test
    public void testWithMetadataGPX() throws Exception {
        final URL url = MetadataTest.class.getResource("1.1/metadata.xml");
        assertNotNull("1.1/metadata.xml", url);
        final MimeTypeCommand test = new MimeTypeCommand(0, CommandRunner.TEST, url.toString());
        test.run();
        final String output = test.outputBuffer.toString().trim();
        assertTrue(output, output.endsWith("metadata.xml: application/gpx+xml"));
    }
}


text:
@interface PodsDummy_Pods_ZXPopPresentation_Example : NSObject
@end
@implementation PodsDummy_Pods_ZXPopPresentation_Example
@end


text:
var searchData=
[
  ['betaplanemesh',['betaplanemesh',['../structbetaplanemeshmodule_1_1betaplanemesh.html',1,'betaplanemeshmodule']]],
  ['betaplanemeshmodule',['betaplanemeshmodule',['../classbetaplanemeshmodule.html',1,'']]],
  ['betaplanesolver',['betaplanesolver',['../structbetaplanesolvermodule_1_1betaplanesolver.html',1,'betaplanesolvermodule']]],
  ['betaplanesolvermodule',['betaplanesolvermodule',['../classbetaplanesolvermodule.html',1,'']]],
  ['bivarinterface',['bivarinterface',['../structbivarinterfacemodule_1_1bivarinterface.html',1,'bivarinterfacemodule']]],
  ['bivarinterfacemodule',['bivarinterfacemodule',['../classbivarinterfacemodule.html',1,'']]],
  ['bivarmodule',['bivarmodule',['../classbivarmodule.html',1,'']]],
  ['bivarremeshmodule',['bivarremeshmodule',['../classbivarremeshmodule.html',1,'']]],
  ['bvemesh',['bvemesh',['../structspherebvemodule_1_1bvemesh.html',1,'spherebvemodule']]],
  ['bveremeshsource',['bveremeshsource',['../structssrfpackremeshmodule_1_1bveremeshsource.html',1,'ssrfpackremeshmodule']]],
  ['bvesolver',['bvesolver',['../structspherebvesolvermodule_1_1bvesolver.html',1,'spherebvesolvermodule']]]
];


text:
/*
Package email allows for log messages to be sent via email.

Example

simple email

    package main

    import (
        "github.com/go-playground/log/v7"
        "github.com/go-playground/log/v7/handlers/email"
    )

    func main() {

        email := email.New("smtp.gmail.com", 587, "username", "password", "from@email.com", []string{"to@email.com"})

        log.AddHandler(email, log.WarnLevel, log.AlertLevel, log.PanicLevel)

        log.WithField("omg", "something went wrong").Alert("ALERT!")
    }
*/
package email


text:
from acq4.devices.OptomechDevice import OptomechDevice
from acq4.drivers.ThorlabsFW102C import FilterWheelDriver
from acq4.devices.FilterWheel.FilterWheelDevGui import FilterWheelDevGui
from acq4.devices.FilterWheel.FilterWheelTaskTemplate import Ui_Form
from acq4.devices.Microscope import Microscope
from acq4.util.SequenceRunner import SequenceRunner
from acq4.devices.Device import *
from acq4.devices.Device import TaskGui
from acq4.util.Mutex import Mutex
from acq4.util.Thread import Thread
import acq4.util.debug as debug
import acq4.pyqtgraph as pg
import time
from collections import OrderedDict

class FilterWheel(Device, OptomechDevice):
    """ Thorlabs motorized filter wheel (FW102C)
    The Filter wheel device class adds control and display for the filter wheel device status.

    * Maintains list of the filters in the six filter-wheel positions with their description
    * Support for selecting a filter wheel position
    * Support for filter wheel implementation during task : specific filter wheel position during one task, different positions as task sequence
    * Support to changing filter wheel speed and input/ouput modus

    Configuration examples:

    FilterWheel:
        driver: 'FilterWheel'
        port: COM4                         ## serial port connected to filter-wheel
        baud: 115200
        parentDevice: 'Microscope'
        filters: # filters in slots
            0:  # first slot
                name: 'green_and_shortpass'
                description: 'ET535/70m Chroma, FESH0700 ThorL'
            1:  # second slot
                name: 'red'
                description: 'ET630/75m-2p Chroma'
            2: # third slot
                name: 'shortpass'
                description: 'shortpass'

    """

    sigFilterChanged = QtCore.Signal(object)
    sigFilterWheelSpeedChanged = QtCore.Signal(object)
    sigFilterWheelTrigModeChanged = QtCore.Signal(object)
    sigFilterWheelSensorModeChanged = QtCore.Signal(object)

    def __init__(self, dm, config, name):

        Device.__init__(self, dm, config, name)
        OptomechDevice.__init__(self, dm, config, name)

        self.scopeDev = None
        self.currentFilter = None
        p = self
        while p is not None:
            p = p.parentDevice()
            if isinstance(p, Microscope):
                self.scopeDev = p

        self.port = config['port']  ## windows com ports start at COM1, pyserial ports start at 0
        self.baud = config.get('baud', 115200)
        #self.positionLabels = config.get('postionLabels')

        self.driver = FilterWheelDriver(self.port, self.baud)
        self.driverLock = Mutex(QtCore.QMutex.Recursive)  ## access to low level driver calls
        self.filterWheelLock = Mutex(QtCore.QMutex.Recursive)  ## access to self.attributes

        self.filters = OrderedDict()
        ## Format of self.filters is:
        ## {
        ##    filterWheelPosition1: {filterName: filter},
        ##    filterWheelPosition2: {filterName: filter},
        ## }
        nPos = self.getPositionCount()
        for k in range(nPos):  ## Set value for each filter
            filt = Filter(config['filters'],self,k)
            self.filters[k] = filt

        #print self.filters.values()
        #print self.filters[1].name(), self.filters[1].description()
        #if len(self.positionLabels) != self.getPositionCount():
        #    raise Exception("Number of FilterWheel positions %s must correspond to number of labels!" % self.getPositionCount())

        with self.driverLock:
            self.currentFWPosition = self.driver.getPos()
            self.currentFilter = self.getFilter()

        self.fwThread = FilterWheelThread(self, self.driver, self.driverLock)
        self.fwThread.fwPosChanged.connect(self.positionChanged)
        self.fwThread.start()

    def setTriggerMode(self, trigMode):
        with self.driverLock:
            self.driver.setTriggerMode(trigMode)
            self.sigFilterWheelTrigModeChanged.emit(trigMode)

    def getTriggerMode(self):
        with self.driverLock:
            return self.driver.getTriggerMode()

    def setSpeed(self, speed):
        with self.driverLock:
            self.driver.setSpeed(speed)
            self.sigFilterWheelSpeedChanged.emit(speed)

    def getSpeed(self):
        with self.driverLock:
            return self.driver.getSpeed()

    def setPosition(self, pos):
        with self.driverLock:
            self.driver.setPos(pos)

    def getSensorMode(self):
        with self.driverLock:
            return self.driver.getSensorMode()

    def setSensorMode(self, sensorMode):
        with self.driverLock:
            self.driver.setSensorMode(sensorMode)
            self.sigFilterWheelSensorModeChanged.emit(sensorMode)

    def getPosition(self):
        with self.driverLock:
            return self.driver.getPos()

    def getPositionCount(self):
        with self.driverLock:
            return self.driver.getPosCount()

    def positionChanged(self,newPos):
        with self.filterWheelLock:
            self.currentFWPosition = newPos
            self.currentFilter = self.getFilter()
            self.sigFilterChanged.emit(newPos)

    def createTask(self, cmd, parentTask):
        with self.filterWheelLock:
            return FilterWheelTask(self, cmd, parentTask)

    def taskInterface(self, taskRunner):
        with self.filterWheelLock:
            return FilterWheelTaskGui(self, taskRunner)

    def getFilter(self):
        """Return the currently active Filter."""
        with self.filterWheelLock:
            if (self.currentFWPosition-1) not in self.filters:
                return None
            return self.filters[(self.currentFWPosition-1)]
            #return self.objectives[self.currentSwitchPosition][selected]

    def listFilters(self):
        """
        Return a list of available filters.
        """
        with self.filterWheelLock:
            return self.filters.values()

    def _allFilters(self):
        ## used by (preferrably only) GUI interface
        return self.filters

    def deviceInterface(self, win):
        return FilterWheelDevGui(self)

class Filter(OptomechDevice):

    def __init__(self, config, fw, key):
        self._config = config
        self._fw = fw
        self._key = key
        #print config, key
        key = str(key)
        if key in config:
            name = '%s-%s' %((int(key)+1), config[key]['name'])
            self._description = config[key]['description']
        else:
            name = '%s-%s' %((int(key)+1), 'empty')
            self._description = '-'

        OptomechDevice.__init__(self, fw.dm, {}, name)

    def key(self):
        return self._key

    def description(self):
        return self._description

    def filterwheel(self):
        return self._fw

    def __repr__(self):
        return "<Filter %s.%s>" % (self._fw.name(), self.name())

class FilterWheelTask(DeviceTask):

    def __init__(self, dev, cmd, parentTask):
        DeviceTask.__init__(self, dev, cmd, parentTask)
        self.dev = dev
        self.cmd = cmd
        self.parentTask = parentTask
        #print parentTask

    def configure(self):

        with self.dev.filterWheelLock:
            #self.state = self.dev.getLastState()
            requiredPos = int(self.cmd['filterWheelPosition'][0]) # take the first character of string and convert it to int
            if self.dev.currentFWPosition != requiredPos:
                self.dev.setPosition(requiredPos)

    def start(self):
        pass

    def stop(self, abort):
        pass

    def isDone(self):
        return True

class FilterWheelTaskGui(TaskGui):

    def __init__(self, dev, taskRunner):

        TaskGui.__init__(self, dev, taskRunner)

        self.ui = Ui_Form()
        self.ui.setupUi(self)
        self.dev = dev

        filters = self.dev.listFilters()
        filterList = self.generatFilterList(filters)
        for i in range(len(filterList)):
            item = self.ui.filterCombo.addItem('%s' % filterList[i][1])

        item = self.ui.sequenceCombo.addItem('off')
        item = self.ui.sequenceCombo.addItem('list')
        self.ui.sequenceListEdit.hide()

        self.ui.sequenceCombo.currentIndexChanged.connect(self.sequenceChanged)
        self.ui.sequenceListEdit.editingFinished.connect(self.sequenceChanged)

        ## Create state group for saving/restoring state
        self.stateGroup = pg.WidgetGroup([
            (self.ui.filterCombo,),
            (self.ui.sequenceCombo,),
            (self.ui.sequenceListEdit,),
        ])

    def generateTask(self, params=None):
        state = self.stateGroup.state()

        if params is None or 'filterWheelPosition' not in params:
            target = state['filterCombo']
        else:
            target = self.filterTaskList[params['filterWheelPosition']]

        task = {}
        task['recordState'] = True
        task['filterWheelPosition'] = target #state['filterCombo']
        return task

    def saveState(self, saveItems=False):
        state = self.stateGroup.state()
        return state

    def restoreState(self, state):
        self.stateGroup.setState(state)
        self.ui.sequenceListEdit.setVisible(state['sequenceCombo'] != 'off')
        self.sequenceChanged()

    def storeConfiguration(self):
        state = self.saveState(saveItems=True)
        self.dev.writeConfigFile(state, 'lastConfig')

    def loadConfiguration(self):
        state = self.dev.readConfigFile('lastConfig')
        self.restoreState(state)

    def listSequence(self):
        if self.ui.sequenceCombo.currentIndex() == 1:
            filt = self.getFilterList()
            return OrderedDict([('filterWheelPosition', filt)])
        else:
            return []

    def sequenceChanged(self):
        self.filterTaskList = None
        self.sigSequenceChanged.emit(self.dev.name())
        if self.ui.sequenceCombo.currentIndex() == 1:
            self.ui.sequenceListEdit.show()
        else:
            self.ui.sequenceListEdit.hide()

    def getFilterList(self):
        self.filterTaskList = []
        pos = self.ui.sequenceListEdit.text()
        if pos == '':
            return self.filterTaskList
        else:
            pos = map( int, pos.split(',') )
            for i in range(len(pos)):
                self.filterTaskList.append(self.filterList[pos[i]-1])
            #print 'filterTaskList :', self.filterTaskList
            return self.filterTaskList

    def generatFilterList(self, filt):
        self.filterList = []
        for i in range(len(filt)):
            self.filterList.append([(i+1), filt[i].name()])
        #print 'filterList : ', self.filterList
        return self.filterList

class FilterWheelThread(Thread):

    fwPosChanged = QtCore.Signal(object)

    def __init__(self, dev, driver, lock):
        Thread.__init__(self)
        self.lock = Mutex(QtCore.QMutex.Recursive)
        self.dev = dev
        self.driver = driver
        self.driverLock = lock
        self.cmds = {}

    def run(self):
        self.stopThread = False
        with self.driverLock:
            self.fwPosChanged.emit(self.driver.getPos())
        while True:
            try:
                with self.driverLock:
                    pos = self.driver.getPos()
                self.fwPosChanged.emit(pos)
                time.sleep(0.5)
            except:
                debug.printExc("Error in Filter Wheel communication thread:")

            self.lock.lock()
            if self.stopThread:
                self.lock.unlock()
                break
            self.lock.unlock()
            time.sleep(0.02)

        self.driver.close()

    def stop(self, block=False):
        with self.lock:
            self.stopThread = True
        if block:
            if not self.wait(10000):
                raise Exception("Timed out while waiting for Filter Wheel thread exit!")


text:
package org.talend.dataprep.cache;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;

@RunWith(MockitoJUnitRunner.class)
public class ZippedContentCacheTest {

    @Mock
    private ContentCache delegate;

    @Test
    public void shouldReturnZippedOutputStream() {
        // given
        when(delegate.put(any(), any())).thenReturn(mock(OutputStream.class));
        ContentCache contentCache = new ZippedContentCache(delegate);

        // when
        final OutputStream stream = contentCache.put(() -> StringUtils.EMPTY, ContentCache.TimeToLive.DEFAULT);

        // then
        verify(delegate, times(1)).put(any(), any());
        assertEquals(GZIPOutputStream.class, stream.getClass());
    }

    @Test
    public void shouldReturnNullOutputStream() {
        // given
        when(delegate.put(any(), any())).thenReturn(null);
        ContentCache contentCache = new ZippedContentCache(delegate);

        // when
        final OutputStream stream = contentCache.put(() -> StringUtils.EMPTY, ContentCache.TimeToLive.DEFAULT);

        // then
        verify(delegate, times(1)).put(any(), any());
        assertNull(stream);
    }

    @Test
    public void shouldReadNonZippedInputStream() throws IOException {
        // given
        final String content = "non-zipped content";
        when(delegate.get(any()))
                .then((Answer<InputStream>) invocation -> new ByteArrayInputStream(content.getBytes()));
        ContentCache contentCache = new ZippedContentCache(delegate);

        // when
        final InputStream stream = contentCache.get(() -> StringUtils.EMPTY);

        // then
        verify(delegate, times(2)).get(any());
        assertEquals(ByteArrayInputStream.class, stream.getClass());
        assertEquals(content, IOUtils.toString(stream, "UTF-8"));
    }

    @Test
    public void shouldReturnZippedInputStream() throws IOException {
        // given
        final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try (GZIPOutputStream sampleContent = new GZIPOutputStream(outputStream)) {
            sampleContent.write('a');
        }
        when(delegate.get(any())).thenReturn(new ByteArrayInputStream(outputStream.toByteArray()));
        ContentCache contentCache = new ZippedContentCache(delegate);

        // when
        final InputStream stream = contentCache.get(() -> StringUtils.EMPTY);

        // then
        verify(delegate, times(1)).get(any());
        assertEquals(GZIPInputStream.class, stream.getClass());
    }

    @Test
    public void shouldReturnNullInputStream() {
        // given
        when(delegate.get(any())).thenReturn(null);
        ContentCache contentCache = new ZippedContentCache(delegate);

        // when
        final InputStream stream = contentCache.get(() -> StringUtils.EMPTY);

        // then
        verify(delegate, times(1)).get(any());
        assertNull(stream);
    }
}


text:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") return Reflect.decorate(decorators, target, key, desc);
    switch (arguments.length) {
        case 2: return decorators.reduceRight(function(o, d) { return (d && d(o)) || o; }, target);
        case 3: return decorators.reduceRight(function(o, d) { return (d && d(target, key)), void 0; }, void 0);
        case 4: return decorators.reduceRight(function(o, d) { return (d && d(target, key, o)) || o; }, desc);
    }
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import { isString, CONST, isBlank } from 'angular2/src/facade/lang';
import { Injectable } from 'angular2/src/core/di';
import { Pipe } from 'angular2/src/core/metadata';
import { InvalidPipeArgumentException } from './invalid_pipe_argument_exception';
/**
 * Implements lowercase transforms to text.
 *
 * ### Example
 *
 * In this example we transform the user text lowercase.
 *
 *  ```
 * @Component({
 *   selector: "username-cmp",
 *   template: "Username: {{ user | lowercase }}"
 * })
 * class Username {
 *   user:string;
 * }
 *
 * ```
 */
export let LowerCasePipe = class {
    transform(value, args = null) {
        if (isBlank(value))
            return value;
        if (!isString(value)) {
            throw new InvalidPipeArgumentException(LowerCasePipe, value);
        }
        return value.toLowerCase();
    }
};
LowerCasePipe = __decorate([
    CONST(),
    Pipe({ name: 'lowercase' }),
    Injectable(),
    __metadata('design:paramtypes', [])
], LowerCasePipe);
//# sourceMappingURL=lowercase_pipe.js.map


text:
require 'test_helper'
require 'tilt/template'

module Tilt
  class TemplateMetadataTest < Minitest::Test
    class MyTemplate < Template
      metadata[:global] = 1
      self.default_mime_type = 'text/html'

      def prepare
      end

      def allows_script?
        true
      end
    end

    test "global metadata" do
      assert MyTemplate.metadata
      assert_equal 1, MyTemplate.metadata[:global]
    end

    test "instance metadata" do
      tmpl = MyTemplate.new { '' }
      assert_equal 1, tmpl.metadata[:global]
    end

    test "gracefully handles default_mime_type" do
      assert_equal 'text/html', MyTemplate.metadata[:mime_type]
    end

    test "still allows .default_mime_type" do
      assert_equal 'text/html', MyTemplate.default_mime_type
    end

    test "gracefully handles allows_script?" do
      tmpl = MyTemplate.new { '' }
      assert_equal true, tmpl.metadata[:allows_script]
    end
  end
end


text:
var express = require('express');

var amazonRevoke = function(req, res, next) {
  if ( req.session.appuid )
  {
    if ( req.user )
    {
      if ( req.user.amazon && req.user.amazon.id )
      {
        var mongoose = require('mongoose');
        var UserExtAccount = mongoose.model('UserExtAccount');

        var amazon = {};
        amazon.id = req.user.amazon.id;
        UserExtAccount.revokeExtAccount( req.session.appuid, 'amazon', amazon, function(err,numberAffected) {
          if (err) { console.log(err); }
          next();
        });
      }
    }
  }
};

var googleTokenRevoke = function(req, res, next) {
  var mongoose = require('mongoose');
  var UserExtAccount = mongoose.model('UserExtAccount');

  var options = {
    criteria: { 'uid': req.session.appuid }
    , select: 'uid google'
  };
  UserExtAccount.load(options, function(err, data) {
    if (err) { return done(err); }

    console.log('google revoke: data');
    console.log(data);

    var strategy = req._passport.instance._strategy('google-openidconnect');
    console.log('google strategy');
    console.log(strategy);

    strategy.revoke( { accessToken: data.google.accessToken }, function(err, body, res ) {
      console.log('reovke');
      console.log(body);
      console.log(res);
      if (err) { console.log(err); }

      next();
    });
  });
};

var googleRevoke = function(req, res, next) {
  if ( req.session.appuid )
  {
    if ( req.user )
    {
      if ( req.user.google && req.user.google.id )
      {
        var mongoose = require('mongoose');
        var UserExtAccount = mongoose.model('UserExtAccount');

        var google = {};
        google.id = req.user.google.id;
        UserExtAccount.revokeExtAccount( req.session.appuid, 'google', google, function(err,numberAffected) {
          if (err) { console.log(err); }
          next();
        });
      }
    }
  }
};

exports.amazonRevoke = amazonRevoke;
exports.googleTokenRevoke = googleTokenRevoke;
exports.googleRevoke = googleRevoke;


text:
<module rename-to='hitsujun'>
  <inherits name='playn.PlayN'/>
  <inherits name='HitsujunAssets'/>

  <source path='core'/>
  <source path='html'/>

  <public path="resources" />

  <entry-point class='com.hitsujun.html.HitsujunHtml'/>

  <inherits name="playn.logging.Enhanced" />

  <inherits name="tripleplay.TriplePlay"/>
</module>


text:
using System;
using System.IO;
using System.Linq;
using NUnit.Framework;

namespace CapuchinSync.Core.Tests.FunctionalTests
{
    [TestFixture]
    public class FileSystemTests : FileTestBase
    {
        [Test]
        public void ShouldEnumerateFiles()
        {
            var testSet = TestSet1.ToList();
            WriteTestSet(testSet);

            var results = FileSystem.EnumerateFilesInDirectory(TestSourceFolder,null,null).ToList();

            var misMatches1 =
                results.Where(x => !testSet.Any(y => y.FilePath.Equals(x, StringComparison.InvariantCultureIgnoreCase)))
                    .ToArray();
            var misMatches2 = testSet.Where(x => !results.Any(y => y.Equals(x.FilePath, StringComparison.InvariantCultureIgnoreCase)))
                    .ToArray();

            if (misMatches1.Any())
            {
                Assert.Fail($"Found {misMatches1.Length} items in the results that were not in the test set: [{string.Join(", ", misMatches1)}].");
            }
            if (misMatches2.Any())
            {
                Assert.Fail($"Found {misMatches2.Length} items in the test set that were not in the results: [{string.Join(", ", misMatches2.Select(y=>y.FilePath))}].");
            }
        }

        [Test]
        public void DoesFileExist_ShouldBeSuccessful()
        {
            var testFile = TestSet1.First();
            CreateFile(testFile);
            Assert.IsTrue(FileSystem.DoesFileExist(testFile.FilePath), "Expected test file to be found.");
        }

        [Test]
        public void DoesDirectoryExist_ShouldBeSuccessful()
        {
            var testFile = TestSet1.First();
            CreateFile(testFile);
            var dir = Path.GetDirectoryName(testFile.FilePath);
            Assert.IsTrue(FileSystem.DoesDirectoryExist(dir), "Expected test directory to be found.");
        }

        [Test]
        public void CreateDirectory_ShouldBeSuccessful()
        {
            var directory = Path.Combine(TestSourceFolder, Guid.NewGuid().ToString("N"));
            var result = FileSystem.CreateDirectory(directory);
            Assert.IsTrue(result, "Expected CreateDirectory to return true.");
            Assert.IsTrue(Directory.Exists(directory), $"Expected directory {directory} to have been created.");
        }

        [Test]
        public void CopyFileAndOverwriteIfItExists_ShouldBeSuccessfulWhenTargetFileDoesNotExist()
        {
            var fileGuid = Guid.NewGuid();
            var source = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var contents = "Hello, I'm a file " + Guid.NewGuid().ToString("D");
            File.WriteAllText(source, contents);
            var target = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_target.txt");
            FileSystem.CopyFileAndOverwriteIfItExists(source, target);
            Assert.IsTrue(File.Exists(target), $"Expected target file to exist at {target}.");
            var actualContents = File.ReadAllText(target);
            Assert.AreEqual(contents, actualContents, $"Unexpected contents at {target}.");
        }

        [Test]
        public void CopyFileAndOverwriteIfItExists_ShouldBeSuccessfulWhenTargetFileExists()
        {
            var fileGuid = Guid.NewGuid();
            var source = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var contents = "Hello, I'm a file " + Guid.NewGuid().ToString("D");
            File.WriteAllText(source, contents);
            var target = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_target.txt");
            File.WriteAllText(target, "blah, this should get overwritten.");
            FileSystem.CopyFileAndOverwriteIfItExists(source, target);
            Assert.IsTrue(File.Exists(target), $"Expected target file to exist at {target}.");
            var actualContents = File.ReadAllText(target);
            Assert.AreEqual(contents, actualContents, $"Unexpected contents at {target}.");
        }

        [Test]
        public void ReadAllLines_ShouldBeSuccessful()
        {
            var fileGuid = Guid.NewGuid();
            var source = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var line1 = "Hello, I'm a file";
            var line2 = Guid.NewGuid().ToString("D");
            File.WriteAllLines(source, new []{line1, line2});
            var lines = FileSystem.ReadAllLines(source).ToArray();
            Assert.AreEqual(2,lines.Length, "Expected two lines in in the file");
            Assert.AreEqual(line1, lines.First(), "Unexpected first line");
            Assert.AreEqual(line2, lines.Last(), "Unexpected second line");
        }

        [Test]
        public void DeleteFile_ShouldBeSuccessful()
        {
            var path = Path.Combine(TestSourceFolder, Guid.NewGuid().ToString("N") + ".txt");
            File.WriteAllText(path, "Hello");
            FileSystem.DeleteFile(path);
            Assert.IsFalse(File.Exists(path), "File was not deleted.");
        }

        [Test]
        public void MoveFile_ShouldBeSuccessful()
        {
            var fileGuid = Guid.NewGuid();
            var source = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var contents = "Hello, I'm a file " + Guid.NewGuid().ToString("D");
            File.WriteAllText(source, contents);
            var target = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_target.txt");
            FileSystem.MoveFile(source, target);
            Assert.IsTrue(File.Exists(target), $"Expected target file to exist at {target}.");
            var actualContents = File.ReadAllText(target);
            Assert.AreEqual(contents, actualContents, $"Unexpected contents at {target}.");
            Assert.IsFalse(File.Exists(source), "File still exists at original location.");
        }

        [Test]
        public void WriteAsUtf8_ShouldBeSuccessful()
        {
            var fileGuid = Guid.NewGuid();
            var target = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var contents = "Hello, I'm a file " + Guid.NewGuid().ToString("D");
            FileSystem.WriteAsUtf8TextFile(target, contents);
            var actualContents = File.ReadAllText(target);
            Assert.AreEqual(contents, actualContents, $"Unexpected contents at {target}.");
        }

        [Test]
        public void WriteLinesAsUtf8_ShouldBeSuccessful()
        {
            var fileGuid = Guid.NewGuid();
            var target = Path.Combine(TestSourceFolder, fileGuid.ToString("N") + "_source.txt");
            var lines = new [] {"line1", "line2", "line3"};
            FileSystem.WriteAllLinesAsUtf8TextFile(target, lines);
            var actualContents = File.ReadAllText(target);
            Assert.AreEqual(string.Join("\r\n",lines) + "\r\n", actualContents, $"Unexpected contents at {target}.");
        }
    }
}


text:
package service

import (
	"fmt"
	"math/rand"
	"strconv"
	"strings"

	"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/errors"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/api/validation"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/apiserver"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/cloudprovider"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/labels"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/registry/minion"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/runtime"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/util"
	"github.com/GoogleCloudPlatform/kubernetes/pkg/watch"
)

// REST adapts a service registry into apiserver's RESTStorage model.
type REST struct {
	registry Registry
	cloud    cloudprovider.Interface
	machines minion.Registry
}

// NewREST returns a new REST.
func NewREST(registry Registry, cloud cloudprovider.Interface, machines minion.Registry) *REST {
	return &REST{
		registry: registry,
		cloud:    cloud,
		machines: machines,
	}
}

func (rs *REST) Create(obj runtime.Object) (<-chan runtime.Object, error) {
	srv := obj.(*api.Service)
	if errs := validation.ValidateService(srv); len(errs) > 0 {
		return nil, errors.NewInvalid("service", srv.ID, errs)
	}

	srv.CreationTimestamp = util.Now()

	return apiserver.MakeAsync(func() (runtime.Object, error) {
		// TODO: Consider moving this to a rectification loop, so that we make/remove external load balancers
		// correctly no matter what http operations happen.
		if srv.CreateExternalLoadBalancer {
			if rs.cloud == nil {
				return nil, fmt.Errorf("requested an external service, but no cloud provider supplied.")
			}
			balancer, ok := rs.cloud.TCPLoadBalancer()
			if !ok {
				return nil, fmt.Errorf("The cloud provider does not support external TCP load balancers.")
			}
			zones, ok := rs.cloud.Zones()
			if !ok {
				return nil, fmt.Errorf("The cloud provider does not support zone enumeration.")
			}
			hosts, err := rs.machines.List()
			if err != nil {
				return nil, err
			}
			zone, err := zones.GetZone()
			if err != nil {
				return nil, err
			}
			err = balancer.CreateTCPLoadBalancer(srv.ID, zone.Region, srv.Port, hosts)
			if err != nil {
				return nil, err
			}
		}
		err := rs.registry.CreateService(srv)
		if err != nil {
			return nil, err
		}
		return rs.registry.GetService(srv.ID)
	}), nil
}

func (rs *REST) Delete(id string) (<-chan runtime.Object, error) {
	service, err := rs.registry.GetService(id)
	if err != nil {
		return nil, err
	}
	return apiserver.MakeAsync(func() (runtime.Object, error) {
		rs.deleteExternalLoadBalancer(service)
		return &api.Status{Status: api.StatusSuccess}, rs.registry.DeleteService(id)
	}), nil
}

func (rs *REST) Get(id string) (runtime.Object, error) {
	s, err := rs.registry.GetService(id)
	if err != nil {
		return nil, err
	}
	return s, err
}

func (rs *REST) List(selector labels.Selector) (runtime.Object, error) {
	list, err := rs.registry.ListServices()
	if err != nil {
		return nil, err
	}
	var filtered []api.Service
	for _, service := range list.Items {
		if selector.Matches(labels.Set(service.Labels)) {
			filtered = append(filtered, service)
		}
	}
	list.Items = filtered
	return list, err
}

// Watch returns Services events via a watch.Interface.
// It implements apiserver.ResourceWatcher.
func (rs *REST) Watch(label, field labels.Selector, resourceVersion uint64) (watch.Interface, error) {
	return rs.registry.WatchServices(label, field, resourceVersion)
}

func (*REST) New() runtime.Object {
	return &api.Service{}
}

// GetServiceEnvironmentVariables populates a list of environment variables that are use
// in the container environment to get access to services.
func GetServiceEnvironmentVariables(registry Registry, machine string) ([]api.EnvVar, error) {
	var result []api.EnvVar
	services, err := registry.ListServices()
	if err != nil {
		return result, err
	}
	for _, service := range services.Items {
		name := makeEnvVariableName(service.ID) + "_SERVICE_PORT"
		value := strconv.Itoa(service.Port)
		result = append(result, api.EnvVar{Name: name, Value: value})
		result = append(result, makeLinkVariables(service, machine)...)
	}
	result = append(result, api.EnvVar{Name: "SERVICE_HOST", Value: machine})
	return result, nil
}

func (rs *REST) Update(obj runtime.Object) (<-chan runtime.Object, error) {
	srv := obj.(*api.Service)
	if errs := validation.ValidateService(srv); len(errs) > 0 {
		return nil, errors.NewInvalid("service", srv.ID, errs)
	}
	return apiserver.MakeAsync(func() (runtime.Object, error) {
		// TODO: check to see if external load balancer status changed
		err := rs.registry.UpdateService(srv)
		if err != nil {
			return nil, err
		}
		return rs.registry.GetService(srv.ID)
	}), nil
}

// ResourceLocation returns a URL to which one can send traffic for the specified service.
func (rs *REST) ResourceLocation(id string) (string, error) {
	e, err := rs.registry.GetEndpoints(id)
	if err != nil {
		return "", err
	}
	if len(e.Endpoints) == 0 {
		return "", fmt.Errorf("no endpoints available for %v", id)
	}
	return "http://" + e.Endpoints[rand.Intn(len(e.Endpoints))], nil
}

func (rs *REST) deleteExternalLoadBalancer(service *api.Service) error {
	if !service.CreateExternalLoadBalancer || rs.cloud == nil {
		return nil
	}
	zones, ok := rs.cloud.Zones()
	if !ok {
		// We failed to get zone enumerator.
		// As this should have failed when we tried in "create" too,
		// assume external load balancer was never created.
		return nil
	}
	balancer, ok := rs.cloud.TCPLoadBalancer()
	if !ok {
		// See comment above.
		return nil
	}
	zone, err := zones.GetZone()
	if err != nil {
		return err
	}
	if err := balancer.DeleteTCPLoadBalancer(service.JSONBase.ID, zone.Region); err != nil {
		return err
	}
	return nil
}

func makeEnvVariableName(str string) string {
	return strings.ToUpper(strings.Replace(str, "-", "_", -1))
}

func makeLinkVariables(service api.Service, machine string) []api.EnvVar {
	prefix := makeEnvVariableName(service.ID)
	var port string
	if service.ContainerPort.Kind == util.IntstrString {
		port = service.ContainerPort.StrVal
	} else {
		port = strconv.Itoa(service.ContainerPort.IntVal)
	}
	portPrefix := prefix + "_PORT_" + makeEnvVariableName(port) + "_TCP"
	return []api.EnvVar{
		{
			Name:  prefix + "_PORT",
			Value: fmt.Sprintf("tcp://%s:%d", machine, service.Port),
		},
		{
			Name:  portPrefix,
			Value: fmt.Sprintf("tcp://%s:%d", machine, service.Port),
		},
		{
			Name:  portPrefix + "_PROTO",
			Value: "tcp",
		},
		{
			Name:  portPrefix + "_PORT",
			Value: strconv.Itoa(service.Port),
		},
		{
			Name:  portPrefix + "_ADDR",
			Value: machine,
		},
	}
}


text:
<?php

/**
 * PHPExcel_Writer_Excel2007_Drawing
 *
 * @category   PHPExcel
 * @package    PHPExcel_Writer_Excel2007
 * @copyright  Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Writer_Excel2007_Drawing extends PHPExcel_Writer_Excel2007_WriterPart
{

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Worksheet $pWorksheet
     * @param    int                &$chartRef     Chart ID
     * @param    boolean            $includeCharts Flag indicating if we should include drawing details for charts
     *
     * @return    string                XML Output
     * @throws    PHPExcel_Writer_Exception
     */
    public function writeDrawings(PHPExcel_Worksheet $pWorksheet = null, &$chartRef, $includeCharts = false)
    {

        // Create XML writer
        $objWriter = null;
        if ($this->getParentWriter()->getUseDiskCaching()) {
            $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK,
                $this->getParentWriter()->getDiskCachingDirectory());
        } else {
            $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
        }

        // XML header
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');

        // xdr:wsDr
        $objWriter->startElement('xdr:wsDr');
        $objWriter->writeAttribute('xmlns:xdr',
            'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing');
        $objWriter->writeAttribute('xmlns:a', 'http://schemas.openxmlformats.org/drawingml/2006/main');

        // Loop through images and write drawings
        $i = 1;
        $iterator = $pWorksheet->getDrawingCollection()->getIterator();
        while ($iterator->valid()) {
            $this->_writeDrawing($objWriter, $iterator->current(), $i);

            $iterator->next();
            ++$i;
        }

        if ($includeCharts) {
            $chartCount = $pWorksheet->getChartCount();
            // Loop through charts and write the chart position
            if ($chartCount > 0) {
                for ($c = 0; $c < $chartCount; ++$c) {
                    $this->_writeChart($objWriter, $pWorksheet->getChartByIndex($c), $c + $i);
                }
            }
        }

        $objWriter->endElement();

        // Return
        return $objWriter->getData();
    }

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter      $objWriter XML Writer
     * @param    PHPExcel_Worksheet_BaseDrawing $pDrawing
     * @param    int                            $pRelationId
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeDrawing(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        PHPExcel_Worksheet_BaseDrawing $pDrawing = null,
        $pRelationId = -1
    ) {

        if ($pRelationId >= 0) {
            // xdr:oneCellAnchor
            $objWriter->startElement('xdr:oneCellAnchor');
            // Image location
            $aCoordinates = PHPExcel_Cell::coordinateFromString($pDrawing->getCoordinates());
            $aCoordinates[0] = PHPExcel_Cell::columnIndexFromString($aCoordinates[0]);

            // xdr:from
            $objWriter->startElement('xdr:from');
            $objWriter->writeElement('xdr:col', $aCoordinates[0] - 1);
            $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetX()));
            $objWriter->writeElement('xdr:row', $aCoordinates[1] - 1);
            $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getOffsetY()));
            $objWriter->endElement();

            // xdr:ext
            $objWriter->startElement('xdr:ext');
            $objWriter->writeAttribute('cx', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getWidth()));
            $objWriter->writeAttribute('cy', PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getHeight()));
            $objWriter->endElement();

            // xdr:pic
            $objWriter->startElement('xdr:pic');

            // xdr:nvPicPr
            $objWriter->startElement('xdr:nvPicPr');

            // xdr:cNvPr
            $objWriter->startElement('xdr:cNvPr');
            $objWriter->writeAttribute('id', $pRelationId);
            $objWriter->writeAttribute('name', $pDrawing->getName());
            $objWriter->writeAttribute('descr', $pDrawing->getDescription());
            $objWriter->endElement();

            // xdr:cNvPicPr
            $objWriter->startElement('xdr:cNvPicPr');

            // a:picLocks
            $objWriter->startElement('a:picLocks');
            $objWriter->writeAttribute('noChangeAspect', '1');
            $objWriter->endElement();

            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:blipFill
            $objWriter->startElement('xdr:blipFill');

            // a:blip
            $objWriter->startElement('a:blip');
            $objWriter->writeAttribute('xmlns:r',
                'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
            $objWriter->writeAttribute('r:embed', 'rId'.$pRelationId);
            $objWriter->endElement();

            // a:stretch
            $objWriter->startElement('a:stretch');
            $objWriter->writeElement('a:fillRect', null);
            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:spPr
            $objWriter->startElement('xdr:spPr');

            // a:xfrm
            $objWriter->startElement('a:xfrm');
            $objWriter->writeAttribute('rot', PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getRotation()));
            $objWriter->endElement();

            // a:prstGeom
            $objWriter->startElement('a:prstGeom');
            $objWriter->writeAttribute('prst', 'rect');

            // a:avLst
            $objWriter->writeElement('a:avLst', null);

            $objWriter->endElement();

//						// a:solidFill
//						$objWriter->startElement('a:solidFill');

//							// a:srgbClr
//							$objWriter->startElement('a:srgbClr');
//							$objWriter->writeAttribute('val', 'FFFFFF');

///* SHADE
//								// a:shade
//								$objWriter->startElement('a:shade');
//								$objWriter->writeAttribute('val', '85000');
//								$objWriter->endElement();
//*/

//							$objWriter->endElement();

//						$objWriter->endElement();
            /*
                                    // a:ln
                                    $objWriter->startElement('a:ln');
                                    $objWriter->writeAttribute('w', '88900');
                                    $objWriter->writeAttribute('cap', 'sq');

                                        // a:solidFill
                                        $objWriter->startElement('a:solidFill');

                                            // a:srgbClr
                                            $objWriter->startElement('a:srgbClr');
                                            $objWriter->writeAttribute('val', 'FFFFFF');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                        // a:miter
                                        $objWriter->startElement('a:miter');
                                        $objWriter->writeAttribute('lim', '800000');
                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */

            if ($pDrawing->getShadow()->getVisible()) {
                // a:effectLst
                $objWriter->startElement('a:effectLst');

                // a:outerShdw
                $objWriter->startElement('a:outerShdw');
                $objWriter->writeAttribute('blurRad',
                    PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getBlurRadius()));
                $objWriter->writeAttribute('dist',
                    PHPExcel_Shared_Drawing::pixelsToEMU($pDrawing->getShadow()->getDistance()));
                $objWriter->writeAttribute('dir',
                    PHPExcel_Shared_Drawing::degreesToAngle($pDrawing->getShadow()->getDirection()));
                $objWriter->writeAttribute('algn', $pDrawing->getShadow()->getAlignment());
                $objWriter->writeAttribute('rotWithShape', '0');

                // a:srgbClr
                $objWriter->startElement('a:srgbClr');
                $objWriter->writeAttribute('val', $pDrawing->getShadow()->getColor()->getRGB());

                // a:alpha
                $objWriter->startElement('a:alpha');
                $objWriter->writeAttribute('val', $pDrawing->getShadow()->getAlpha() * 1000);
                $objWriter->endElement();

                $objWriter->endElement();

                $objWriter->endElement();

                $objWriter->endElement();
            }
            /*

                                    // a:scene3d
                                    $objWriter->startElement('a:scene3d');

                                        // a:camera
                                        $objWriter->startElement('a:camera');
                                        $objWriter->writeAttribute('prst', 'orthographicFront');
                                        $objWriter->endElement();

                                        // a:lightRig
                                        $objWriter->startElement('a:lightRig');
                                        $objWriter->writeAttribute('rig', 'twoPt');
                                        $objWriter->writeAttribute('dir', 't');

                                            // a:rot
                                            $objWriter->startElement('a:rot');
                                            $objWriter->writeAttribute('lat', '0');
                                            $objWriter->writeAttribute('lon', '0');
                                            $objWriter->writeAttribute('rev', '0');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */
            /*
                                    // a:sp3d
                                    $objWriter->startElement('a:sp3d');

                                        // a:bevelT
                                        $objWriter->startElement('a:bevelT');
                                        $objWriter->writeAttribute('w', '25400');
                                        $objWriter->writeAttribute('h', '19050');
                                        $objWriter->endElement();

                                        // a:contourClr
                                        $objWriter->startElement('a:contourClr');

                                            // a:srgbClr
                                            $objWriter->startElement('a:srgbClr');
                                            $objWriter->writeAttribute('val', 'FFFFFF');
                                            $objWriter->endElement();

                                        $objWriter->endElement();

                                    $objWriter->endElement();
            */
            $objWriter->endElement();

            $objWriter->endElement();

            // xdr:clientData
            $objWriter->writeElement('xdr:clientData', null);

            $objWriter->endElement();
        } else {
            throw new PHPExcel_Writer_Exception("Invalid parameters passed.");
        }
    }

    /**
     * Write drawings to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter $objWriter XML Writer
     * @param    PHPExcel_Chart            $pChart
     * @param    int                       $pRelationId
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeChart(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        PHPExcel_Chart $pChart = null,
        $pRelationId = -1
    ) {

        $tl = $pChart->getTopLeftPosition();
        $tl['colRow'] = PHPExcel_Cell::coordinateFromString($tl['cell']);
        $br = $pChart->getBottomRightPosition();
        $br['colRow'] = PHPExcel_Cell::coordinateFromString($br['cell']);

        $objWriter->startElement('xdr:twoCellAnchor');

        $objWriter->startElement('xdr:from');
        $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($tl['colRow'][0]) - 1);
        $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['xOffset']));
        $objWriter->writeElement('xdr:row', $tl['colRow'][1] - 1);
        $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($tl['yOffset']));
        $objWriter->endElement();
        $objWriter->startElement('xdr:to');
        $objWriter->writeElement('xdr:col', PHPExcel_Cell::columnIndexFromString($br['colRow'][0]) - 1);
        $objWriter->writeElement('xdr:colOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['xOffset']));
        $objWriter->writeElement('xdr:row', $br['colRow'][1] - 1);
        $objWriter->writeElement('xdr:rowOff', PHPExcel_Shared_Drawing::pixelsToEMU($br['yOffset']));
        $objWriter->endElement();

        $objWriter->startElement('xdr:graphicFrame');
        $objWriter->writeAttribute('macro', '');
        $objWriter->startElement('xdr:nvGraphicFramePr');
        $objWriter->startElement('xdr:cNvPr');
        $objWriter->writeAttribute('name', 'Chart '.$pRelationId);
        $objWriter->writeAttribute('id', 1025 * $pRelationId);
        $objWriter->endElement();
        $objWriter->startElement('xdr:cNvGraphicFramePr');
        $objWriter->startElement('a:graphicFrameLocks');
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement('xdr:xfrm');
        $objWriter->startElement('a:off');
        $objWriter->writeAttribute('x', '0');
        $objWriter->writeAttribute('y', '0');
        $objWriter->endElement();
        $objWriter->startElement('a:ext');
        $objWriter->writeAttribute('cx', '0');
        $objWriter->writeAttribute('cy', '0');
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement('a:graphic');
        $objWriter->startElement('a:graphicData');
        $objWriter->writeAttribute('uri', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
        $objWriter->startElement('c:chart');
        $objWriter->writeAttribute('xmlns:c', 'http://schemas.openxmlformats.org/drawingml/2006/chart');
        $objWriter->writeAttribute('xmlns:r', 'http://schemas.openxmlformats.org/officeDocument/2006/relationships');
        $objWriter->writeAttribute('r:id', 'rId'.$pRelationId);
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();
        $objWriter->endElement();

        $objWriter->startElement('xdr:clientData');
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Write VML header/footer images to XML format
     *
     * @param    PHPExcel_Worksheet $pWorksheet
     *
     * @return    string                                XML Output
     * @throws    PHPExcel_Writer_Exception
     */
    public function writeVMLHeaderFooterImages(PHPExcel_Worksheet $pWorksheet = null)
    {

        // Create XML writer
        $objWriter = null;
        if ($this->getParentWriter()->getUseDiskCaching()) {
            $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_DISK,
                $this->getParentWriter()->getDiskCachingDirectory());
        } else {
            $objWriter = new PHPExcel_Shared_XMLWriter(PHPExcel_Shared_XMLWriter::STORAGE_MEMORY);
        }

        // XML header
        $objWriter->startDocument('1.0', 'UTF-8', 'yes');

        // Header/footer images
        $images = $pWorksheet->getHeaderFooter()->getImages();

        // xml
        $objWriter->startElement('xml');
        $objWriter->writeAttribute('xmlns:v', 'urn:schemas-microsoft-com:vml');
        $objWriter->writeAttribute('xmlns:o', 'urn:schemas-microsoft-com:office:office');
        $objWriter->writeAttribute('xmlns:x', 'urn:schemas-microsoft-com:office:excel');

        // o:shapelayout
        $objWriter->startElement('o:shapelayout');
        $objWriter->writeAttribute('v:ext', 'edit');

        // o:idmap
        $objWriter->startElement('o:idmap');
        $objWriter->writeAttribute('v:ext', 'edit');
        $objWriter->writeAttribute('data', '1');
        $objWriter->endElement();

        $objWriter->endElement();

        // v:shapetype
        $objWriter->startElement('v:shapetype');
        $objWriter->writeAttribute('id', '_x0000_t75');
        $objWriter->writeAttribute('coordsize', '21600,21600');
        $objWriter->writeAttribute('o:spt', '75');
        $objWriter->writeAttribute('o:preferrelative', 't');
        $objWriter->writeAttribute('path', 'm@4@5l@4@11@9@11@9@5xe');
        $objWriter->writeAttribute('filled', 'f');
        $objWriter->writeAttribute('stroked', 'f');

        // v:stroke
        $objWriter->startElement('v:stroke');
        $objWriter->writeAttribute('joinstyle', 'miter');
        $objWriter->endElement();

        // v:formulas
        $objWriter->startElement('v:formulas');

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'if lineDrawn pixelLineWidth 0');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'sum @0 1 0');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'sum 0 0 @1');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @2 1 2');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelWidth');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @3 21600 pixelHeight');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'sum @0 0 1');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @6 1 2');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelWidth');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'sum @8 21600 0');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'prod @7 21600 pixelHeight');
        $objWriter->endElement();

        // v:f
        $objWriter->startElement('v:f');
        $objWriter->writeAttribute('eqn', 'sum @10 21600 0');
        $objWriter->endElement();

        $objWriter->endElement();

        // v:path
        $objWriter->startElement('v:path');
        $objWriter->writeAttribute('o:extrusionok', 'f');
        $objWriter->writeAttribute('gradientshapeok', 't');
        $objWriter->writeAttribute('o:connecttype', 'rect');
        $objWriter->endElement();

        // o:lock
        $objWriter->startElement('o:lock');
        $objWriter->writeAttribute('v:ext', 'edit');
        $objWriter->writeAttribute('aspectratio', 't');
        $objWriter->endElement();

        $objWriter->endElement();

        // Loop through images
        foreach ($images as $key => $value) {
            $this->_writeVMLHeaderFooterImage($objWriter, $key, $value);
        }

        $objWriter->endElement();

        // Return
        return $objWriter->getData();
    }

    /**
     * Write VML comment to XML format
     *
     * @param    PHPExcel_Shared_XMLWriter              $objWriter  XML Writer
     * @param    string                                 $pReference Reference
     * @param    PHPExcel_Worksheet_HeaderFooterDrawing $pImage     Image
     *
     * @throws    PHPExcel_Writer_Exception
     */
    public function _writeVMLHeaderFooterImage(
        PHPExcel_Shared_XMLWriter $objWriter = null,
        $pReference = '',
        PHPExcel_Worksheet_HeaderFooterDrawing $pImage = null
    ) {

        // Calculate object id
        preg_match('{(\d+)}', md5($pReference), $m);
        $id = 1500 + ( substr($m[1], 0, 2) * 1 );

        // Calculate offset
        $width = $pImage->getWidth();
        $height = $pImage->getHeight();
        $marginLeft = $pImage->getOffsetX();
        $marginTop = $pImage->getOffsetY();

        // v:shape
        $objWriter->startElement('v:shape');
        $objWriter->writeAttribute('id', $pReference);
        $objWriter->writeAttribute('o:spid', '_x0000_s'.$id);
        $objWriter->writeAttribute('type', '#_x0000_t75');
        $objWriter->writeAttribute('style',
            "position:absolute;margin-left:{$marginLeft}px;margin-top:{$marginTop}px;width:{$width}px;height:{$height}px;z-index:1");

        // v:imagedata
        $objWriter->startElement('v:imagedata');
        $objWriter->writeAttribute('o:relid', 'rId'.$pReference);
        $objWriter->writeAttribute('o:title', $pImage->getName());
        $objWriter->endElement();

        // o:lock
        $objWriter->startElement('o:lock');
        $objWriter->writeAttribute('v:ext', 'edit');
        $objWriter->writeAttribute('rotation', 't');
        $objWriter->endElement();

        $objWriter->endElement();
    }

    /**
     * Get an array of all drawings
     *
     * @param    PHPExcel $pPHPExcel
     *
     * @return    PHPExcel_Worksheet_Drawing[]        All drawings in PHPExcel
     * @throws    PHPExcel_Writer_Exception
     */
    public function allDrawings(PHPExcel $pPHPExcel = null)
    {

        // Get an array of all drawings
        $aDrawings = array();

        // Loop through PHPExcel
        $sheetCount = $pPHPExcel->getSheetCount();
        for ($i = 0; $i < $sheetCount; ++$i) {
            // Loop through images and add to array
            $iterator = $pPHPExcel->getSheet($i)->getDrawingCollection()->getIterator();
            while ($iterator->valid()) {
                $aDrawings[] = $iterator->current();

                $iterator->next();
            }
        }

        return $aDrawings;
    }
}


text:
(function() {
  'use strict';
  var app;

  app = angular.module('Chutter', ['ui.router', 'ngMaterial', 'templates-shared', 'ng-token-auth', 'ngResource', 'emguo.poller', 'hc.marked', 'angularMoment', 'ngMessages', 'angularytics']).constant('API', {
    baseURL: '/api/v1',
    makeURL: function(url) {
      return this.baseURL + url;
    }
  }).constant('angularMomentConfig', {
    preprocess: 'unix'
  }).config([
    '$locationProvider', '$authProvider', 'API', '$rootScopeProvider', function($locationProvider, $authProvider, API, $rootScopeProvider) {
      $rootScopeProvider.digestTtl(30);
      $authProvider.configure({
        apiUrl: API.baseURL
      });
      return $locationProvider.html5Mode(true);
    }
  ]).config([
    '$stateProvider', '$urlRouterProvider', '$compileProvider', 'AngularyticsProvider', function($stateProvider, $urlRouterProvider, $compileProvider, AngularyticsProvider) {
      AngularyticsProvider.setEventHandlers(['GoogleUniversal']);
      return $compileProvider.debugInfoEnabled(false);
    }
  ]).run([
    '$http', '$auth', '$rootScope', 'Angularytics', function($http, $auth, $rootScope, Angularytics) {
      var headers;
      headers = void 0;
      headers = $auth.retrieveData('auth_headers');
      $http.defaults.headers.common = $auth.retrieveData('auth_headers');
      return Angularytics.init();
    }
  ]);

}).call(this);


text:
.SILENT :
.PHONY : help build clean shell start stop rm logs

USERNAME:=ncarlier
APPNAME:=dynamic-ambassador
IMAGE:=$(USERNAME)/$(APPNAME)

define docker_run_flags
-e HOST_IP=172.17.42.1 \
-e ETCD_HOST=172.17.42.1:4001 \
-v /var/run/docker.sock:/tmp/docker.sock \
-p 80:80 -P
endef

all: build

## This help screen
help:
	printf "Available targets:\n\n"
	awk '/^[a-zA-Z\-\_0-9]+:/ { \
		helpMessage = match(lastLine, /^## (.*)/); \
		if (helpMessage) { \
			helpCommand = substr($$1, 0, index($$1, ":")); \
			helpMessage = substr(lastLine, RSTART + 3, RLENGTH); \
			printf "%-15s %s\n", helpCommand, helpMessage; \
		} \
	} \
	{ lastLine = $$0 }' $(MAKEFILE_LIST)

## Build the image
build:
	echo "Building $(IMAGE) docker image..."
	sudo docker build --rm -t $(IMAGE) .

## Remove the image (also stop and delete the container)
clean: stop rm
	echo "Removing $(IMAGE) docker image..."
	sudo docker rmi $(IMAGE)

## Start the container
start:
	echo "Starting $(IMAGE) docker image..."
	sudo docker run -d $(docker_run_flags) --name $(APPNAME) $(IMAGE)

## Stop the container
stop:
	echo "Stopping container $(APPNAME) ..."
	-sudo docker stop $(APPNAME)

## Delete the container
rm:
	echo "Deleting container $(APPNAME) ..."
	-sudo docker rm $(APPNAME)

## Run the container with shell access
shell:
	echo "Running $(IMAGE) docker image with shell access..."
	sudo docker run --rm -it $(docker_run_flags) --entrypoint="/bin/bash" $(IMAGE) -c /bin/bash

## Show container logs
logs:
	echo "Logs of the $(APPNAME) container..."
	sudo docker logs -f $(APPNAME)


text:
layout: documents
categories:
  - "Scripting"
title:  "Scripting Object Model"
alias: scripting-object-model
seqno: 20
selector: documents
permalink: "documents/scripting-object-model"
---

__SpectNetIde__ offers a set of .NET objects that you can use to create scripts that automate
everyday tasks with ZX Spectrum virtual machines. You can use these objects in any .NET Framework
application, or in scripting languages that allow accessing .NET Framework objects.

To use __SpectNetIde__ scripting, add these assemblies to your projects:

Assembly | Description
---------| -----------
`Spect.Net.Assembler` | The Z80 Assembler of __SpectNetIde__. With the help of this component, you can use Z80 source code in scripts.
`Spect.Net.RomResources` | This assembly stores the ROMs of the Spectrum models supported by __SpectNetIde__.
`SpectNet.SpectrumEmu` |  This assembly implements the ZX Spectrum emulator and the scripting object model.

## ZX Spectrum virtual machines

The scripting object model supports these ZX Spectrum models:
* ZX Spectrum 48K
* ZX Spectrum 128K
* ZX Spectrum +3E
* _ZX Spectrum Next (still in development)_

The virtual machines use a background thread for their execution cycle. You can run the machine
with synchronous methods, but you need to pause or stop them, or waiting while their cycle completes
with the `async/await` pattern.

## Scripting objects

The table below contains a summary of the .NET types that constitute the ZX Spectrum scripting
object model. To get the shortest path to learn using them, I suggest starting with these documentations:
* [`SpectrumVmFactory`]({{ site.baseurl }}/documents/scripting-vms.html#the-spectrumvmfactory-class)
* [`SpectrumVm`]({{ site.baseurl }}/documents/scripting-vms.html#the-spectrumvm-class)
* [`CpuZ80`]({{ site.baseurl }}/documents/scripting-z80.html#the-cpuz80-class)

Object type | Description
------------|------------
[`AddressTrackingState`]({{ site.baseurl }}/documents/scripting-z80.html#the-addresstrackingstate-class) | This class represents tracking information regarding memory.
[`AssemblerOptions`]({{ site.baseurl }}/documents/scripting-vms.html#the-assembleroptions-class) | This class represents the options that can be used when the Z80 Assembler compiles the source code to machine code.
[`AudioSamples`]({{ site.baseurl }}/documents/scripting-audio.html#the-audiosamples-class) | This class stores audio samples for the currently rendered virtual machine frame.
[`CodeBreakpoints`]({{ site.baseurl }}/documents/scripting-vms.html#the-codebreakpoints-class) | Represents the breakpoint of the Spectrum virtual machine, at which execution should pause when running in debug mode.
[`CpuZ80`]({{ site.baseurl }}/documents/scripting-z80.html#the-cpuz80-class) | This class represents the Z80 CPU of a Spectrum virtual machine.
[`ExecuteCycleOptions`]({{ site.baseurl }}/documents/scripting-vms.html#the-executecycleoptions-class) | This class provides options for the execution cycle of the Spectrum virtual machine.
[`ExecutionCompletionReason`]({{ site.baseurl }}/documents/scripting-vms.html#the-executioncompletionreason-enum) | The values of this enumeration tell the reason why the virtual machine is in a paused or stopped state.
[`IAudioConfiguration`]({{ site.baseurl }}/documents/scripting-audio.html#the-iaudioconfiguration-interface) | This interface represents the configuration of the beeper/sound device.
[`KeyboardEmulator`]({{ site.baseurl }}/documents/scripting-vms.html#the-keyboardemulator-class) | This class is reserved for future extension. Right now, id does not offer any property or method for scripting.
[`MemoryPagingInfo`]({{ site.baseurl }}/documents/scripting-memory.html#the-memorypaginginfo-class) | This class provides properties and methods to obtain information about ROM and RAM paging.
[`MemorySlice`]({{ site.baseurl }}/documents/scripting-memory.html#the-memoryslice-class) | This class represents a slice of the memory in the Spectrum virtual machine.
[`ReadOnlyMemorySlice`]({{ site.baseurl }}/documents/scripting-memory.html#the-readonlymemoryslice-class) | This class represents a read-only slice of the memory in the Spectrum virtual machine.
[`ScreenBitmap`]({{ site.baseurl }}/documents/scripting-screen.html#the-screenbitmap-class) | This class represents the current screen's pixels, including the border area.
[`ScreenConfiguration`]({{ site.baseurl }}/documents/scripting-screen.html#the-screenconfiguration-class) | This class represents the configuration of the virtual machine's screen
[`ScreenRenderingStatus`]({{ site.baseurl }}/documents/scripting-screen.html#the-screenrenderingstatus-class) | Provides properties about the current screen rendering status of the machine
[`ScreenRenderingTable`]({{ site.baseurl }}/documents/scripting-screen.html#the-screenrenderingtable-class) | Represents the screen rendering table of the virtual machine.
[`ScreenRenderingTact`]({{ site.baseurl }}/documents/scripting-screen.html#the-screenrenderingtact-class) | Provides details about a screen rendering tact.
[`SpectrumMemoryContents`]({{ site.baseurl }}/documents/scripting-memory.html#the-spectrummemorycontents-class) | This class provides access to the addressable 64KBytes memory contents of the Spectrum virtual machine.
[`SpectrumModels`]({{ site.baseurl }}/documents/scripting-vms.html#the-spectrummodels-class) | This class is a repository of all Spectrum models and editions supported by __SpectNetIde__.
[`SpectrumVm`]({{ site.baseurl }}/documents/scripting-vms.html#the-spectrumvm-class) | This class represents a Spectrum virtual machine.
[`SpectrumVmFactory`]({{ site.baseurl }}/documents/scripting-vms.html#the-spectrumvmfactory-class) | This class provides methods you can use to create ZX Spectrum virtual machine instances.
[`VmState`]({{ site.baseurl }}/documents/scripting-vms.html#the-vmstate-enum) | The values of this enumeration show the possible states of a ZX Spectrum virtual machine.
[`Z80InstructionExecutionEventArgs`]({{ site.baseurl }}/documents/scripting-z80.html#the-z80instructionexecutioneventargs-class) | This class provides event arguments the the `OperationExecuting` and `OperationExecuted` events of the `CpuZ80` class


text:
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/wait.h>
#include <unistd.h>
#include <sched.h>
#include <errno.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include <stdint.h>
#include <stddef.h>

#include <sys/socket.h>
#include <linux/ioctl.h>
#include <linux/if_tun.h>
#include <linux/if.h>
#include <linux/sockios.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#define stackalign(x) (void*)((uintptr_t)(x) & ~(uintptr_t)0xf)
#define nelem(x) (int)(sizeof(x)/sizeof(x[0]))


text:
@interface JMTSwitchFormViewDescription : JMFormViewDescription
@property (assign, nonatomic) BOOL enable;
@property (assign, nonatomic) BOOL on;
@end

@interface JMSwitchFormView : JMFormView

@property (strong, nonatomic) UIColor *formViewSwitchTintColor UI_APPEARANCE_SELECTOR;

@end


text:
package de.uni_stuttgart.vis.vowl.owl2vowl.parser.visitors;

import de.uni_stuttgart.vis.vowl.owl2vowl.model.edges.properties.BaseProperty;
import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.MapData;
import de.uni_stuttgart.vis.vowl.owl2vowl.parser.container.OntologyInformation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.util.OWLObjectVisitorAdapter;

/**
 * Visitor implementation for the cardinalities.
 */
public class CardinalityVisitorImpl extends OWLObjectVisitorAdapter {
	private static final Logger logger = LogManager.getRootLogger();
	private MapData data;
	private OntologyInformation information;

	public CardinalityVisitorImpl(MapData mapData, OntologyInformation information) {
		this.data = mapData;
		this.information = information;
	}

	@Override
	public void visit(OWLDataMaxCardinality dataMaxCardinality) {
		BaseProperty property = getProperty(dataMaxCardinality);
		property.setMaxCardinality(dataMaxCardinality.getCardinality());
		super.visit(dataMaxCardinality);
		logger.info("Data Max Cardinality =[" + dataMaxCardinality.getCardinality() + "]");
	}

	@Override
	public void visit(OWLDataMinCardinality dataMinCardinality) {
		BaseProperty property = getProperty(dataMinCardinality);
		property.setMinCardinality(dataMinCardinality.getCardinality());
		super.visit(dataMinCardinality);
		logger.info("Data Min Cardinality =[" + dataMinCardinality.getCardinality() + "]");
	}

	@Override
	public void visit(OWLDataExactCardinality dataExactCardinality) {
		BaseProperty property = getProperty(dataExactCardinality);
		property.setExactCardinality(dataExactCardinality.getCardinality());
		super.visit(dataExactCardinality);
		logger.info("Data Exact Cardinality =[" + dataExactCardinality.getCardinality() + "]");
	}

	@Override
	public void visit(OWLObjectMaxCardinality objectMaxCardinality) {
		BaseProperty property = getProperty(objectMaxCardinality);
		property.setMaxCardinality(objectMaxCardinality.getCardinality());
		super.visit(objectMaxCardinality);
		logger.info("Object Max Cardinality =[" + objectMaxCardinality.getCardinality() + "]");
	}

	@Override
	public void visit(OWLObjectMinCardinality objectMinCardinality) {
		BaseProperty property = getProperty(objectMinCardinality);
		property.setMinCardinality(objectMinCardinality.getCardinality());
		super.visit(objectMinCardinality);
		logger.info("Object Min Cardinality =[" + objectMinCardinality.getCardinality() + "]");
	}

	@Override
	public void visit(OWLObjectExactCardinality objectExactCardinality) {
		BaseProperty property = getProperty(objectExactCardinality);
		property.setExactCardinality(objectExactCardinality.getCardinality());
		super.visit(objectExactCardinality);
		logger.info("Object Exact Cardinality =[" + objectExactCardinality.getCardinality() + "]");
	}

	public BaseProperty getProperty(OWLObjectCardinalityRestriction card) {
		OWLObjectPropertyExpression prop = card.getProperty();
		BaseProperty returnValue;

		if (prop.isAnonymous()) {
			returnValue = data.getMergedProperties().get(prop.getNamedProperty().getIRI().toString());
		} else {
			returnValue = data.getMergedProperties().get(prop.asOWLObjectProperty().getIRI().toString());
		}

		return returnValue;
	}

	public BaseProperty getProperty(OWLDataCardinalityRestriction card) {
		OWLDataPropertyExpression prop = card.getProperty();
		BaseProperty returnValue;

		if (prop.isAnonymous()) {
			//TODO
			returnValue = data.getMergedProperties().get(prop.asOWLDataProperty().getIRI().toString());
		} else {
			returnValue = data.getMergedProperties().get(prop.asOWLDataProperty().getIRI().toString());
		}

		return returnValue;
	}
}


text:
from tehbot.plugins import *
import urllib.request, urllib.parse, urllib.error
from random import *
import shlex
import irc.client
import re
from pony.orm import *
from functools import reduce

class BlamePlugin(StandardCommand):
    def commands(self):
        return "blame"

    def execute_parsed(self, connection, event, extra):
        try:
            botname = connection.get_nickname()
            forbidden = ["ChanServ", "NickServ", botname]
            two = [u for u,m in connection.tehbot.users[event.target] if u not in forbidden] if irc.client.is_channel(event.target) else ["spaceone"]
            goats = list(zip((two for one in range(23)), 42 * [ reduce(random, [], two) ]))
            shuffle(goats)
            goats.sort(key=lambda x: random())
            shuffle(goats)
            scapegoat = choice(goats[goats[randint(0, len(goats) - 1)][int(1337 * random()) % 2].index(choice(two))][0])
        except:
            try:
                print(goats)
                print(two)
            except:
                pass
            scapegoat = "spaceone"
        return "I blame %s." % scapegoat

class FamPlugin(StandardCommand):
    """This help at fam"""

    def commands(self):
        return "fam"

    def execute_parsed(self, connection, event, extra):
        return ".quoet fom"

class ListPlugin(StandardCommand):
    def __init__(self, db, what="item"):
        StandardCommand.__init__(self, db)
        self.what = what
        self.parser.add_argument("-a", "--add", metavar="who")

    def commands(self):
        return "list"

    def create_entities(self):
        if self.__class__.__name__ != ListPlugin.__name__:
            return

        class ListPluginData(self.db.Entity):
            what = Required(str, max_len=32)
            who = Required(str, max_len=32)
            composite_key(what, who)

    def execute_parsed(self, connection, event, extra):
        if self.pargs.add is None:
            with db_session:
                data = select(d for d in self.db.ListPluginData if d.what == self.what).order_by(self.db.ListPluginData.id)
                return ", ".join(d.who for d in data)

        who = self.pargs.add

        if not self.is_privileged(extra):
            return self.request_priv(extra)

        with db_session:
            if self.db.ListPluginData.exists(lambda d: d.who.lower() == who.lower()):
                return "Error: That %s has already been added!" % self.what

            try:
                self.db.ListPluginData(what=self.what, who=who)
            except:
                return "Error: Query failed. :("

        return "Okay"

class LiarsPlugin(ListPlugin):
    def __init__(self, db):
        ListPlugin.__init__(self, db, "liar")

    def commands(self):
        return "liars"

    def init(self):
        ListPlugin.init(self)
        with db_session:
            if not self.db.ListPluginData.select(lambda x: x.what == self.what):
                self.db.ListPluginData(what=self.what, who="roun")
                self.db.ListPluginData(what=self.what, who="Nimda3")
                self.db.ListPluginData(what=self.what, who="neoxquick")
                self.db.ListPluginData(what=self.what, who="dloser")
                self.db.ListPluginData(what=self.what, who="thefinder")

class PricksPlugin(ListPlugin):
    def __init__(self, db):
        ListPlugin.__init__(self, db, "prick")

    def commands(self):
        return "pricks"

    def init(self):
        ListPlugin.init(self)
        with db_session:
            if not self.db.ListPluginData.select(lambda x: x.what == self.what):
                self.db.ListPluginData(what=self.what, who="dloser")

class BeerPlugin(StandardCommand):
    """Serves the best beer on IRC (way better than Lamb3's!)"""

    def __init__(self, db):
        StandardCommand.__init__(self, db)
        group = self.parser.add_mutually_exclusive_group()
        group.add_argument("recipient", nargs="?")
        group.add_argument("--refill", action="store_true")
        group.add_argument("--status", action="store_true")

    def commands(self):
        return "beer"

    def create_entities(self):
        class BeerPluginData(self.db.Entity):
            key = Required(str, unique=True, max_len=32)
            value = Required(int)

    def init(self):
        StandardCommand.init(self)
        with db_session:
            if self.db.BeerPluginData.get(key="beers") is None:
                self.db.BeerPluginData(key="beers", value=10)

    @db_session
    def beers(self):
        return self.db.BeerPluginData.get(key="beers").value

    @db_session
    def get_beer(self):
        beers = self.db.BeerPluginData.get(key="beers")
        cnt = beers.value
        beers.value = max(0, beers.value - 1)
        return cnt

    @db_session
    def refill(self, beers=10):
        self.db.BeerPluginData.get(key="beers").value += beers

    def execute(self, connection, event, extra):
        self.parser.set_defaults(recipient=event.source.nick)

        try:
            pargs = self.parser.parse_args(extra["args"])
            m = self.parser.get_help_msg()
            if m:
                return m.strip()
        except Exception as e:
            msg = "Error: %s"
            return msg % str(e)

        if pargs.status:
            beers = self.beers()
            if beers < 1:
                msg = "has no beer left. :("
            elif beers == 1:
                msg = "has one beer left."
            else:
                msg = "has %d beers left." % beers
            return [("me", msg)]

        if pargs.refill:
            if not self.is_privileged(extra):
                return self.request_priv(extra)

            self.refill()
            msg = "Ok, beer refilled. That was easy, hu?"
            return msg

        beers = self.get_beer()
        if beers == 0:
            msg = "has no beer left. :("
            return [("me", msg)]

        if pargs.recipient == event.source.nick:
            if beers == 1:
                msg = "passes the last bottle of cold beer around to %s." % event.source.nick
            else:
                msg = "passes 1 of %d bottles of cold beer around to %s." % (beers, event.source.nick)
        else:
            if beers == 1:
                msg = "and %s pass the last bottle of cold beer around to %s." % (event.source.nick, pargs.recipient)
            else:
                msg = "and %s pass 1 of %d bottles of cold beer around to %s." % (event.source.nick, beers, pargs.recipient)
        return [("me", msg)]

class BeerGrabber(ChannelHandler):
    def execute(self, connection, event, extra):
        match = re.search(r'and (\w+) pass (\d+) of \d+ bottles of cold beer around to (\w+)\.', extra["msg"])
        if match is None:
            return

        donor = match.group(1)
        cnt = int(match.group(2))
        who = match.group(3)

        if cnt > 0 and who == connection.get_nickname():
            with db_session:
                beers = self.db.BeerPluginData.get(key="beers")
                beers.value += cnt
                total = beers.value

            return "Thanks, %s, I put it into my store! Beer count is %d now." % (donor, total)

from socket import *
import string
import time
class BOSPlugin(StandardCommand):
    """Can you solve The BrownOS? [WeChall]"""
    def __init__(self, db):
        StandardCommand.__init__(self, db)
        self.parser.add_argument("data", nargs="+")

    def commands(self):
        return "bos"

    def hexme(self, data):
        return " ".join("%02x" % x for x in data)

    def execute_parsed(self, connection, event, extra):
        data = " ".join(self.pargs.data).lower()

        sock = socket()
        sock.connect(("wc3.wechall.net", 61221))
        data = data.replace("qd", "05 00 FD 00 05 00 FD 03 FD FE FD 02 FD FE FD FE")
        #data = filter(lambda x: x in string.hexdigits, data)
        data = data.replace(" ", "")
        try:
            data = bytes.fromhex(data)
            if data[-1] != 0xff:
                data += b"\xff"
            ret = "> " + self.hexme(data) + "\n< "
            sock.send(data)
            data = b""
            while True:
                time.sleep(0.01)
                d = sock.recv(1024)
                if not d:
                    break
                data += d
            if data.isascii():
                ret += data.decode()
            else:
                ret += self.hexme(data)
        except Exception as e:
            return str(e)
        finally:
            sock.close()

        return Plugin.shorten(ret, 450)

class DecidePlugin(StandardCommand):
    def __init__(self, db):
        StandardCommand.__init__(self, db)
        self.parser.add_argument("choice", nargs="*")
        self.parser.add_argument("-o", "--or", action="store_true")

    def commands(self):
        return "decide"

    @staticmethod
    def partition(args):
        parts = []
        arg = []
        while args:
            c = args.pop(0)
            if c.lower() in ["or", "||"]:
                if arg:
                    parts.append(arg)
                    arg = []
            else:
                arg.append(c)

        if arg:
            parts.append(arg)

        return parts

    def execute_parsed(self, connection, event, extra):
        choices = ["Yes", "No"]

        if self.pargs.choice:
            if vars(self.pargs)["or"]:
                choices = self.pargs.choice
            else:
                parts = DecidePlugin.partition(self.pargs.choice)
                if len(parts) > 1:
                    choices = list(map(" ".join, parts))

        return choice(choices)

class HugPlugin(StandardCommand):
    """Use this command if you really like (or dislike) someone."""

    def __init__(self, db):
        StandardCommand.__init__(self, db)
        self.parser.add_argument("huggee")
        self.parser.add_argument("-l", "--long", action="store_true")
        self.parser.add_argument("-t", "--tight", action="store_true")
        self.parser.add_argument("-c", "--creepy", action="store_true")
        self.parser.add_argument("--with-a-certain-something", action="store_true")
        self.parser.add_argument("--from-behind", action="store_true")
        self.parser.add_argument("--surprise-me", action="store_true")

    def commands(self):
        return "hug"

    def execute_parsed(self, connection, event, extra):
        options = []

        if self.pargs.surprise_me:
            self.pargs.long = choice([True, False])
            self.pargs.tight = choice([True, False])
            self.pargs.creepy = choice([True, False])
            self.pargs.from_behind = choice([True, False])
            self.pargs.with_a_certain_something = choice([True, False])

        if self.pargs.long:
            options.append("long")
        if self.pargs.tight:
            options.append("tight")
        if self.pargs.creepy:
            options.append("creepy")

        if not options:
            msg = "hugs %s" % self.pargs.huggee
        else:
            msg = "gives %s a %s hug" % (self.pargs.huggee, " and ".join(options))

        if self.pargs.from_behind:
            msg += " from behind"

        if self.pargs.with_a_certain_something:
            msg += " with a certain something"

        return [("me", msg)]

class RoflcopterPlugin(Command):
    def commands(self):
        return "roflcopter"

    def execute(self, connection, event, extra):
        if not self.is_privileged(extra):
            return self.request_priv(extra)

        return r"""    ROFL:ROFL:ROFL:ROFL
         ___^___ _
 L    __/      [] \
LOL===__           \
 L      \___ ___ ___]
              I   I
          ----------/"""

class DestinyHandler(ChannelJoinHandler):
    def execute(self, connection, event, extra):
        if event.source.nick != "destiny":
            return

        return ">> https://www.youtube.com/watch?v=fNmDgRwNFsI <<"

class RouletteHandler(ChannelHandler):
    def execute(self, connection, event, extra):
        msg = extra["msg"]
        if msg.find("BANG") > -1 or msg.find("BOOM") > -1:
            return "!roulette"

class WixxerdPlugin(Command):
    def commands(self):
        return "wixxerd"

    def execute(self, connection, event, extra):
        if not self.is_privileged(extra):
            return self.request_priv(extra)

        return r"""       .##...##..######..##..##..##..##..######..#####...#####..
       .##...##....##.....####....####...##......##..##..##..##.
       .##.#.##....##......##......##....####....#####...##..##.
       .#######....##.....####....####...##......##..##..##..##.
       ..##.##...######..##..##..##..##..######..##..##..#####..
       .........................................................
                    .........  ... . ... . ..  . ........
                          .....   .. . .   . .  .....
                              ...  .  ...  .  .....
                               ``,           ,.,
                                `\\_  |    _//'
                                  \(  |\    )/
                                  //\ |_\  /\\
                                 (/ /\(" )/\ \)
                                  \/\ (  ) /\/
                                     |(  )|
                                     | \( \
                                     |  )  \
                                     |      \
                                     |       \
                                     |        `.__,
                                     \_________.-"""

class DeadHourPlugin(Command):
    def commands(self):
        return "dead_hour"

    def default_settings(self):
        return {
                "max_modes" : 20
                }

    def execute(self, connection, event, extra):
        if not self.is_privileged(extra):
            return self.request_priv(extra)

        if not irc.client.is_channel(event.target):
            return

        channel = event.target
        users = connection.tehbot.users[channel][:]
        botname = connection.get_nickname()
        idx = [u for u,m in users].index(botname)

        if not users[idx][1].intersection("qo"):
            return "I don't have enough privileges in this channel to do that."

        skip_users = ["Lamb3", "ChanServ", botname]

        try:
            max_modes = connection.features.modes
        except AttributeError:
            max_modes = self.settings["max_modes"]

        def modelist(users):
            def check(ulist, mlist):
                s = "-" + "".join(mlist) + " " + " ".join(ulist)
                return len(s) <= 450 and len(ulist) <= max_modes

            mlist = []
            ulist = []

            while users:
                u, mods = users.pop()
                if u in skip_users:
                    continue

                if "o" in mods:
                    m = "o"
                elif "h" in mods:
                    m = "h"
                elif "v" in mods:
                    m = "v"
                else:
                    continue

                if check(ulist + [u], mlist + [m]):
                    ulist.append(u)
                    mlist.append(m)
                else:
                    users.append((u, mods))
                    break

            return "-" + "".join(mlist) + " " + " ".join(ulist)

        res = []
        while users:
            modes = modelist(users)
            res.append(("mode", (connection, event.target, modes)))

        return res


text:
<?php

use Phinx\Migration\AbstractMigration;

class AutoAutologin extends AbstractMigration
{
    public function change()
    {
        $this->table('mail_templates')
            ->changeColumn('autologin', 'boolean', ['null' => false, 'default' => true])
            ->update();
    }
}