text:
// *** SendandReceiveBinaryArguments ***

// This example expands the previous SendandReceiveArguments example. The PC will
//  send and receive multiple Binary values, demonstrating that this is more compact and faster. Since the output is not human readable any more,
//  the logging is disabled and the NewLines are removed
//
// It adds a demonstration of how to:
// - Receive multiple binary parameters,
// - Send multiple binary parameters
// - Callback events being handled while the main program waits
// - How to calculate milliseconds, similar to Arduino function Millis()

using System;
using System.Threading;
using CommandMessenger;
using CommandMessenger.Transport.Serial;

namespace SendAndReceiveBinaryArguments
{
    // This is the list of recognized commands. These can be commands that can either be sent or received.
    // In order to receive, attach a callback function to these events
    enum Command
    {
        RequestPlainTextFloatSeries , // Command Request to send series in plain text
        ReceivePlainTextFloatSeries , // Command to send an item in plain text
        RequestBinaryFloatSeries    , // Command Request to send series in binary form
        ReceiveBinaryFloatSeries    , // Command to send an item in binary form
    };

    public class SendAndReceiveBinaryArguments
    {
        public bool RunLoop { get; set; }
        private SerialTransport _serialTransport;
        private CmdMessenger _cmdMessenger;
        private int _receivedItemsCount;                        // Counter of number of plain text items received
        private int _receivedBytesCount;                        // Counter of number of plain text bytes received
        long _beginTime;                                        // Start time, 1st item of sequence received
        long _endTime;                                          // End time, last item of sequence received
        private bool _receivePlainTextFloatSeriesFinished;      // Indicates if plain text float series has been fully received
        private bool _receiveBinaryFloatSeriesFinished;         // Indicates if binary float series has been fully received
        const int SeriesLength = 2000;                          // Number of items we like to receive from the Arduino
        private const float SeriesBase = 1111111.111111F;       // Base of values to return: SeriesBase * (0..SeriesLength-1)

        // ------------------ M A I N  ----------------------

        // Setup function
        public void Setup()
        {
            // Create Serial Port object
            _serialTransport = new SerialTransport
            {
                CurrentSerialSettings = { PortName = "COM15", BaudRate = 115200 } // object initializer
            };

            // Initialize the command messenger with the Serial Port transport layer
            // Set if it is communicating with a 16- or 32-bit Arduino board
            _cmdMessenger = new CmdMessenger(_serialTransport, BoardType.Bit16);

            // Attach the callbacks to the Command Messenger
            AttachCommandCallBacks();

            // Start listening
            _cmdMessenger.Connect();

            _receivedItemsCount = 0;
            _receivedBytesCount = 0;

            // Clear queues
            _cmdMessenger.ClearReceiveQueue();
            _cmdMessenger.ClearSendQueue();

            Thread.Sleep(100);

            // Send command requesting a series of 100 float values send in plain text form
            var commandPlainText = new SendCommand((int)Command.RequestPlainTextFloatSeries);
            commandPlainText.AddArgument((UInt16)SeriesLength);
            commandPlainText.AddArgument((float)SeriesBase);
            // Send command
            _cmdMessenger.SendCommand(commandPlainText);

            // Now wait until all values have arrived
            while (!_receivePlainTextFloatSeriesFinished)
            {
                Thread.Sleep(100);
            }

            // Clear queues
            _cmdMessenger.ClearReceiveQueue();
            _cmdMessenger.ClearSendQueue();

            _receivedItemsCount = 0;
            _receivedBytesCount = 0;
            // Send command requesting a series of 100 float values send in binary form
            var commandBinary = new SendCommand((int)Command.RequestBinaryFloatSeries);
            commandBinary.AddBinArgument((UInt16)SeriesLength);
            commandBinary.AddBinArgument((float)SeriesBase);

            // Send command
            _cmdMessenger.SendCommand(commandBinary);

            // Now wait until all values have arrived
            while (!_receiveBinaryFloatSeriesFinished)
            {
                Thread.Sleep(100);
            }
        }

        // Loop function
        public void Loop()
        {
            RunLoop = false;
        }

        // Exit function
        public void Exit()
        {
            // Stop listening
            _cmdMessenger.Disconnect();

            // Dispose Command Messenger
            _cmdMessenger.Dispose();

            // Dispose Serial Port object
            _serialTransport.Dispose();

            // Pause before stop
            Console.WriteLine("Press any key to stop...");
            Console.ReadKey();
        }

        /// Attach command call backs.
        private void AttachCommandCallBacks()
        {
            _cmdMessenger.Attach(OnUnknownCommand);
            _cmdMessenger.Attach((int)Command.ReceivePlainTextFloatSeries, OnReceivePlainTextFloatSeries);
            _cmdMessenger.Attach((int)Command.ReceiveBinaryFloatSeries, OnReceiveBinaryFloatSeries);
        }

        // ------------------  C A L L B A C K S ---------------------

        // Called when a received command has no attached function.
        void OnUnknownCommand(ReceivedCommand arguments)
        {
            Console.WriteLine("Command without attached callback received");
        }

        // Callback function To receive the plain text float series from the Arduino
        void OnReceivePlainTextFloatSeries(ReceivedCommand arguments)
        {
            _receivedBytesCount += CountBytesInCommand(arguments, true);

            var count         = arguments.ReadInt16Arg();
            var receivedValue = arguments.ReadFloatArg();

            if (count != _receivedItemsCount)
            {
                Console.WriteLine("Values not matching: received {0} expected {1}", count, _receivedItemsCount);
            }
            if (_receivedItemsCount % (SeriesLength/10) == 0)
                Console.WriteLine("Received value: {0}", receivedValue);
            if (_receivedItemsCount == 0)
            {
                // Received first value, start stopwatch
                _beginTime = Millis;
            }
            else if (count == SeriesLength - 1)
            {
                // Received all values, stop stopwatch
                _endTime = Millis;
                var deltaTime = (_endTime - _beginTime);
                Console.WriteLine("{0} milliseconds per {1} items = is {2} ms/item, {3} Hz",
                    deltaTime,
                    SeriesLength,
                    (float)deltaTime / (float)SeriesLength,
                    (float)1000 * SeriesLength / (float)deltaTime
                    );
                Console.WriteLine("{0} milliseconds per {1} bytes = is {2} ms/byte,  {3} bytes/sec, {4} bps",
                    deltaTime,
                    _receivedBytesCount,
                    (float)deltaTime / (float)_receivedBytesCount,
                    (float)1000 * _receivedBytesCount / (float)deltaTime,
                    (float)8 * 1000 * _receivedBytesCount / (float)deltaTime
                    );
                _receivePlainTextFloatSeriesFinished = true;
           }
            _receivedItemsCount++;
        }

        private int CountBytesInCommand(CommandMessenger.Command command, bool printLfCr)
        {
            var bytes = command.CommandString().Length; // Command + command separator
            //var bytes = _cmdMessenger.CommandToString(command).Length + 1; // Command + command separator
            if (printLfCr) bytes += 2; // Add  bytes for carriage return ('\r') and /or a newline  ('\n')
            return bytes;
        }

        // Callback function To receive the binary float series from the Arduino
        void OnReceiveBinaryFloatSeries(ReceivedCommand arguments)
        {
            var count         = arguments.ReadBinUInt16Arg();
            var receivedValue = arguments.ReadBinFloatArg();

            _receivedBytesCount += CountBytesInCommand(arguments, false);

            if (count != _receivedItemsCount)
            {
                Console.WriteLine("Values not matching: received {0} expected {1}", count, _receivedItemsCount);
            }

            if (_receivedItemsCount % (SeriesLength / 10) == 0)
                Console.WriteLine("Received value: {0}", receivedValue);
            if (_receivedItemsCount == 0)
            {
                // Received first value, start stopwatch
                _beginTime = Millis;
            }
            else if (count == SeriesLength - 1)
            {
                // Received all values, stop stopwatch
                _endTime = Millis;
                var deltaTime = (_endTime - _beginTime);
                Console.WriteLine("{0} milliseconds per {1} items = is {2} ms/item, {3} Hz",
                    deltaTime,
                    SeriesLength,
                    (float)deltaTime / (float)SeriesLength,
                    (float)1000 * SeriesLength / (float)deltaTime
                    );
                Console.WriteLine("{0} milliseconds per {1} bytes = is {2} ms/byte,  {3} bytes/sec, {4} bps",
                    deltaTime,
                    _receivedBytesCount,
                    (float)deltaTime / (float)_receivedBytesCount,
                    (float)1000 * _receivedBytesCount / (float)deltaTime,
                    (float)8 * 1000 * _receivedBytesCount / (float)deltaTime
                    );
                _receiveBinaryFloatSeriesFinished = true;
            }
            _receivedItemsCount++;
        }

        // Return Milliseconds since 1970
        public static long Millis { get { return (long)((DateTime.Now.ToUniversalTime() - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds); } }
    }
}


text:
Baseball projection spreadsheets come (Steamer, PECOTA, GURU, etc)
in all shapes and sizes. This app allows users translate
distribution-specific data (e.g., component names ("mPA", "DBL", "3B"),
roles, names) to a normalized schema.

## Installation

This package is not yet in PyPI, so for now install via Pip:

```shell
$ pip install -e git@github.com:mattdennewitz/baseball-projection-schematics.git#egg=baseball-projection-schematics
```

or clone the repo and install with:

```shell
$ pip install /path/to/this/repo/
```

## Finding projections

You may find the projections here:

- :free: Steamer - scraped from [Fangraphs](http://www.fangraphs.com/projections.aspx?pos=all&stats=pit&type=steamer&team=0&lg=all&players=0&sort=20%2cd)
    using [this importer](https://github.com/mattdennewitz/mlb-fangraphs-steamer-importer).
- :free: [Guru](http://baseballguru.com/bbinside4.html)
- :free: ZiPS - coming soon
- :free: CAIRO - coming soon
- :moneybag: PECOTA - coming soon
- :free: Davenport - coming soon

## Schematics

Translation is accomplished by defining a map (here called a schematic)
between column names in a projection spreadsheet and an ideal, canonical schema.

Check out an example schematic here:
[GURU Schematic](https://github.com/mattdennewitz/baseball-projection-schematics/blob/develop/contrib/schematics/season-2016/guru.json).

## Schema generation

Schemas map fields with expectedly varying names to canonical representations,
e.g., mapping "AGE" from one system and "playerAge" from another to
simply "age" in your output.

Use `bb-generate-schema` to generate a empty schematics, and then
map field names from CSV headers to the fields in the schematic.

### Example usage

```shell
$ bb-generate-schema /path/to/output
```

## Translating projections

After defining a translation schematic, it's time to put it to use.
To translate projections, use `bb-process-projections`.

```shell
$ bb-process-projections        \
    -t batting                  \
    -s /path/to/schematic.json  \
    -i /path/to/projection.csv  \
    /path/to/output.csv
```

This will output the normalized projection in CSV format.

redpajama_set_name: RedPajamaGithub


text:
package com.fillumina.lcs;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;

/**
 * The Hirschberg linear space algorithm is very memory efficient (only
 * {@code 3 * (m+1)} int elements used) and fast for sequences which are
 * not similar. It can efficiently matches long sequences. In case the
 * sequences are known to be similar (6:4) the
 * {@link AbastractLinearSpaceMyersLcs} algorithm is more than twice faster.
 * To minimize the memory consumption set the smaller sequence to be the second
 * one.
 *
 * @see <a href='https://en.wikipedia.org/wiki/Hirschberg's_algorithm'>
 *  Wikipedia: Hirschberg's Algorithm
 * </a>
 * @author Francesco Illuminati
 */
public class HirschbergLinearSpaceLcs implements Lcs {
    public static final HirschbergLinearSpaceLcs INSTANCE =
            new HirschbergLinearSpaceLcs();

    @Override
    public <T> List<T> calculateLcs(T[] a, T[] b) {
        final Inner<T> inner = new Inner<>(false, a, b);
        List<LcsItem> lcs = inner.calculateLcs();
        return inner.extractLcsList(lcs);
    }

    @Override
    public List<LcsItem> calculateLcsIndexes(Object[] a, Object[] b) {
        return new Inner<>(false, a, b).calculateLcs();
    }

    @Override
    public int calculateLcsLength(Object[] a, Object[] b) {
        return new Inner<>(true, a, b).calculateLcsLength();
    }

    private static class Inner<T> extends AbstractHirschbergLinearSpaceLcs {
        private final T[] a, b;

        /**
         * Performs the LCS calculation and return an object that can be
         * queried for the results.
         * @param <T> type of the lists
         * @param a   first sequence
         * @param b   second sequence
         * @return    result object that can be queried for various data
         */
        @SuppressWarnings("unchecked")
        public Inner(boolean sizeOnly,
                final Collection<? extends T> a,
                final Collection<? extends T> b) {
            this(sizeOnly, a.toArray(), b.toArray());
        }

        @SuppressWarnings("unchecked")
        public Inner(boolean sizeOnly, final Object[] a, final Object[] b) {
            super(sizeOnly);
            this.a = (T[]) a;
            this.b = (T[]) b;
        }

        @SuppressWarnings("unchecked")
        public List<T> extractLcsList(List<LcsItem> lcsItem) {
            if (lcsItem == null) {
                return Collections.<T>emptyList();
            }
            final List<T> lcs = new ArrayList<>(lcsItem.size());
            for (int index : lcsItem.get(0).lcsIndexesOfTheFirstSequence()) {
                lcs.add(a[index]);
            }
            return lcs;
        }

        @Override
        public final boolean sameAtIndex(final int i, final int j) {
            final T x = a[i];
            final T y = b[j];
            return (x == y) || (x != null && x.equals(y));
        }

        @Override
        public int getFirstSequenceLength() {
            return a == null ? 0 : a.length;
        }

        @Override
        public int getSecondSequenceLength() {
            return b == null ? 0 : b.length;
        }
    }
}


text:
<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "doc_partner".
 *
 * @property integer $id
 * @property string $name
 * @property string $full_name
 * @property string $address
 * @property string $phone
 * @property string $comment
 *
 * @property DocDocument[] $docDocuments
 */
class DocPartner extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'doc_partner';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['comment'], 'string'],
            [['name', 'full_name', 'address', 'phone'], 'string', 'max' => 255],
            [['name'], 'unique'],
            [['full_name'], 'unique']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => 'Name',
            'full_name' => 'Full Name',
            'address' => 'Address',
            'phone' => 'Phone',
            'comment' => 'Comment',
        ];
    }

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


text:
//
//  environmentInfo.h
//  HelloOpenGL
//
//  Created by wantnon (yang chao) on 13-2-12.
//
//

#ifndef __HelloOpenGL__environmentInfo__
#define __HelloOpenGL__environmentInfo__

#include <iostream>
#include "c3d.h"
#include "mobilePlatform.h"
#include "archScene.h"
#include "ground.h"
#include "water.h"
//surface type
#define SURFACETYPE_WATER 0
#define SURFACETYPE_GROUND 1
#define SURFACETYPE_ARCH 2
#define SURFACETYPE_MOBILEPLATFORM 3
//ceil type
#define CEILTYPE_NON 0
#define CEILTYPE_ARCH 1
#define CEILTYPE_MOBILEPLATFORM 2
class CenvironmentInfo
{
public:
    //最近上下表面高度,法向和类型--abc
    float ceilH;//天花板高度--abc
    Cc3dVector4 ceilNorm;//天花板法向--abc
    float surfaceH;//表面高度--abc
    Cc3dVector4 surfaceNorm;//表面法向--abc
    int surfaceType;//表面类型--abc
    int ceilType;//天花板类型--abc
    //地面,水面,建筑,移动平台的各表面及法向数据也保存下来--abc
    float groundH;
    float waterH;
    float archSurfaceH;
    float archCeilH;
    float mobilePlatformSurfaceH;
    float mobilePlatformCeilH;
    Cc3dVector4 groundNorm;
    Cc3dVector4 waterNorm;
    Cc3dVector4 archSurfaceNorm;
    Cc3dVector4 archCeilNorm;
    Cc3dVector4 mobilePlatformSurfaceNorm;
    Cc3dVector4 mobilePlatformCeilNorm;
    CmobilePlatform*pSurfaceMobilePlatform;//指向当前所在surface的平台,仅surfaceType==SURFACETYPE_MOBILEPLATFORM时有效--abc
    CmobilePlatform*pCeilMobilePlatform;//指向当前所在ceil所属平台,仅ceilType==CEILTYPE_MOBILEPLATFORM时有效--abc
    CenvironmentInfo(){
        ceilH=c3d_INF;
        surfaceH=0;
        surfaceNorm.init(0,1,0,0);
        ceilNorm.init(0, -1, 0, 0);
        surfaceType=0;
        ceilType=0;
        groundH=0;
        waterH=0;
        archCeilH=0;
        archSurfaceH=0;
        mobilePlatformSurfaceH=0;
        mobilePlatformCeilH=0;
        groundNorm.init(0, 1, 0, 0);
        waterNorm.init(0,1,0,0);
        archSurfaceNorm.init(0,1,0,0);
        archCeilNorm.init(0,-1,0,0);
        mobilePlatformSurfaceNorm.init(0, 1, 0, 0);
        mobilePlatformCeilNorm.init(0,-1,0,0);
        pCeilMobilePlatform=NULL;
        pSurfaceMobilePlatform=NULL;

    }

    void updateInfo(const Cc3dVector4&pos,float Rc,float Rc_small,const Cground*ground,const Cwater*water,CarchScene*archScene,
                    const CmobilePlatformSet*mobilePlatformSet){
        //获得地面高度和法向--abc
        if(ground){
            groundH=ground->getHAndNormal(pos.x(), pos.z(), groundNorm);
        }else{
            groundH=-c3d_INF;
            //groundNorm不作处理--abc
        }
        //获得水面高度和法向--abc
        if(water){
           waterH=water->getHorizon();
            waterNorm.init(0, 1, 0, 0);
        }else{
            waterH=-c3d_INF;
            //waterNorm不作处理--abc
        }

        //获得arch表面高度和法线,天花板高度和法线--abc
        if(archScene){
            //(要用Rc而不是Rc_small,否则导致ship着陆下陷)
            archSurfaceH=archScene->getH_floor(pos,Rc,archSurfaceNorm);
            archCeilH=archScene->getH_ceil(pos, Rc, archCeilNorm);
        }else{
            archSurfaceH=-c3d_INF;
            archCeilH=c3d_INF;
        }
        //获得mobilePlatformSet的表面高度和法线,天花板高度和法线,及相应的mobilePlatform
        if(mobilePlatformSet){
            //(要用Rc而不是Rc_small,否则导致ship着陆下陷)
            mobilePlatformSurfaceH=mobilePlatformSet->getH_floor(pos,Rc,mobilePlatformSurfaceNorm,pSurfaceMobilePlatform);
            mobilePlatformCeilH=mobilePlatformSet->getH_ceil(pos, Rc, mobilePlatformCeilNorm,pCeilMobilePlatform);
        }else{
            mobilePlatformSurfaceH=-c3d_INF;
            mobilePlatformCeilH=c3d_INF;
        }
        //----ceilH取archCeil和mobilePlatformCeil中较低者,ceilNorm取较低者的norm
        if(archCeilH<=mobilePlatformCeilH){//如果archCeil低--abc
            ceilH=archCeilH;
            ceilNorm=archCeilNorm;
            ceilType=CEILTYPE_ARCH;
        }else{//如果mobilePlatformCeilH低--abc
            ceilH=mobilePlatformCeilH;
            ceilNorm=mobilePlatformCeilNorm;
            ceilType=CEILTYPE_MOBILEPLATFORM;
        }
        //----比较seabedH,groundH,waterH,archSurfaceH,mobilePlatformSurfaceH几者哪个高,则surfaceH就取谁--abc
        const int nSurface=4;
        float surfaceHList[nSurface]={groundH,waterH,archSurfaceH,mobilePlatformSurfaceH};
        int surfaceTypeList[nSurface]={SURFACETYPE_GROUND,SURFACETYPE_WATER,SURFACETYPE_ARCH,SURFACETYPE_MOBILEPLATFORM};
        Cc3dVector4 surfaceNormList[nSurface]={groundNorm,
            waterNorm,archSurfaceNorm,
            mobilePlatformSurfaceNorm};
        int imax=0;//surfaceH最高者的索引号--abc
        float Hmax=surfaceHList[0];//surfaceH的最大值--abc
        for(int i=1;i<nSurface;i++){//从1开始--abc
            if(surfaceHList[i]>Hmax){
                Hmax=surfaceHList[i];
                imax=i;
            }
        }//得到imax
        surfaceH=surfaceHList[imax];
        surfaceNorm=surfaceNormList[imax];
        surfaceType=surfaceTypeList[imax];
    }
};

#endif /* defined(__HelloOpenGL__environmentInfo__) */


text:
<!DOCTYPE HTML>

  <title>Test for Bug 669012</title>

  <link rel="stylesheet" type="text/css" href="/tests/SimpleTest/test.css"/>

Mozilla Bug 669012

<svg>

</svg>


text:
format compact
diary result.txt

[train, test] = datasets('TestFeatures/forest/','TestFeatures/mountain/','TestFeatures/opencountry/');

train = train';
test = test';

num_classes = length(train);

%%%%%%%%%%%%%%%TESTING%%%%%%%%%%%%%%%%%%%
display('Testing the model');
num_test_samples = 0;
num_train_samples = 0;

for i = 1:num_classes
	num_train_samples = num_train_samples + length(train{i});
end

confusionMatrix = cell(1,num_train_samples);
accuracy = zeros(1, num_train_samples);
confusionMatrix(:) = {zeros(num_classes, num_classes)};
for i = 1:num_classes %for each class
    for j=1:length(test{i}) %for each classes's test data
        display(['Testing for testSample = ', num2str(num_test_samples+1)]);
        sorted_train_dtw_dist = getSortedByDTW(test{i}{j}, train);	 %test{i}{j} is one (36*23) sample	%returned matrix's 1st value is the dist & 2nd is the classid
        class_count = zeros(num_train_samples, num_classes);
		for k = 1:num_train_samples
			if(k>1)
				for c = 1:num_classes
			    		class_count(k,:) = class_count(k-1,:);
				end
			end
			class_count(k,sorted_train_dtw_dist(k,2)) = class_count(k,sorted_train_dtw_dist(k,2)) + 1;
			[neighcount_with_predicted_label, predicted_label] = max(class_count(k,:));
			confusionMatrix{k}(i,predicted_label) = confusionMatrix{k}(i,predicted_label) + 1;
		end
		num_test_samples = num_test_samples + 1;
    end
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

%%%%%%%%%%%%%%%%%%%%STATS%%%%%%%%%%%%%%%%
for k=1:num_train_samples
	display(['Stats for k = ', num2str(k), ' nearest neighbours']);
	confusionMatrix{k}
	correct = sum(diag(confusionMatrix{k}))
	incorrect = num_test_samples - correct
	accuracy(k) = correct/num_test_samples;
end
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fig = figure('Visible', 'off');
plot(accuracy*100,'.b');
title('Accuracy vs K in KNN');
xlabel('K');
ylabel('Accuracy in %');
ylim([0 100]);
saveas(fig, 'accuracy with k.png');

diary off


text:
describe('flannel tests', function() {
  beforeEach(module('flannel'));
  afterEach(function() {
    localStorage.removeItem('flannel.loglevel');
  });

  it('should define flannel.logger', inject(['flannel.logger', function(logger) {
    expect(logger).toBeDefined();
  }]));

  it('should set a default logging level of error', inject(['flannel.logger', function(logger) {
    expect(logger.logLevel()).toBe(logger.logLevels.error);
  }]));

  it('should return the log level set in local storage', inject(['flannel.logger', function(logger) {
    localStorage.setItem('flannel.loglevel', 'info');
    expect(logger.logLevel()).toBe(logger.logLevels.info);
  }]));

});


text:
import React from 'react'
import Box from "@mui/material/Box";
import Title from "../components/Title";
import {get, isNil, set} from "lodash";
import Grid from "@mui/material/Grid";
import TextField from "../components/TextField";
import {FontAwesomeIcon} from "@fortawesome/react-fontawesome";
import BrowseOpenDialog from "../components/BrowseOpenDialog";
import Stack from "@mui/material/Stack";
import RedirectButton from "../components/RedirectButton";
import Button from "../components/Button";
import ConfirmDialog from "../components/ConfirmDialog";

const initialState = {
    confirmOpen: false,
    path: null
}

export default function Optimize() {
    const [state, setState] = React.useState({ ...initialState })

    const {
        confirmOpen,
        path
    } = state

    const handleOptimize = async () => {
        const response = await fetch('api/optimize', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                title: `Optimizing image file '${path}'`,
                path
            })
        });
        if (!response.ok) {
            console.error('Failed to optimize image')
        }
    }

    const handleChange = ({name, value}) => {
        set(state, name, value)
        setState({...state})
    }

    const handleCancel = () => {
        setState({ ...initialState })
    }

    const handleConfirm = async (confirmed) => {
        setState({
            ...state,
            confirmOpen: false
        })
        if (!confirmed) {
            return
        }
        await handleOptimize()
    }

    const optimizeDisabled = isNil(path)

    return (
        <Box>
            <ConfirmDialog
                id="confirm-optimize"
                open={confirmOpen}
                title="Optimize"
                description={`Do you want to optimize image file '${path}'?`}
                onClose={async (confirmed) => await handleConfirm(confirmed)}
            />
            <Title
                text="Optimize"
                description="Optimize image file."
            />
            <Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}>
                <Grid item xs={12} lg={6}>
                    <TextField
                        id="image-path"
                        label={
                            <div style={{display: 'flex', alignItems: 'center', verticalAlign: 'bottom'}}>
                                <FontAwesomeIcon icon="file" style={{marginRight: '5px'}} /> Image file
                            </div>
                        }
                        value={path || ''}
                        endAdornment={
                            <BrowseOpenDialog
                                id="browse-image-path"
                                title="Select image file"
                                onChange={(path) => handleChange({
                                    name: 'path',
                                    value: path
                                })}
                            />
                        }
                        onChange={(event) => handleChange({
                            name: 'path',
                            value: get(event, 'target.value'
                            )}
                        )}
                        onKeyDown={async (event) => {
                            if (event.key !== 'Enter') {
                                return
                            }
                            await handleOptimize()
                        }}
                    />
                </Grid>
            </Grid>
            <Grid container spacing="2" direction="row" alignItems="center" sx={{mt: 2}}>
                <Grid item xs={12} lg={6}>
                    <Box display="flex" justifyContent="flex-end">
                        <Stack direction="row" spacing={2} sx={{mt: 2}}>
                            <RedirectButton
                                path="/"
                                icon="ban"
                                onClick={async () => handleCancel()}
                            >
                                Cancel
                            </RedirectButton>
                            <Button
                                disabled={optimizeDisabled}
                                icon="magic"
                                onClick={async () => handleChange({
                                    name: 'confirmOpen',
                                    value: true
                                })}
                            >
                                Optimize image
                            </Button>
                        </Stack>
                    </Box>
                </Grid>
            </Grid>
        </Box>
    )
}


text:
<?php

namespace App\models;

use Illuminate\Database\Eloquent\Model;

class Postcode extends Model
{
    //
}


text:
namespace {

class MockNTPUserDataLogger : public NTPUserDataLogger {
 public:
  MockNTPUserDataLogger() : NTPUserDataLogger(NULL) {}
  virtual ~MockNTPUserDataLogger() {}

  MOCK_CONST_METHOD2(GetPercentError, size_t(size_t errors, size_t events));

 private:
  DISALLOW_COPY_AND_ASSIGN(MockNTPUserDataLogger);
};

}  // namespace

TEST(NTPUserDataLoggerTest, ThumbnailErrorRateDoesNotDivideByZero) {
  MockNTPUserDataLogger logger;
  EXPECT_CALL(logger, GetPercentError(testing::_, testing::_)).Times(0);
  logger.EmitThumbnailErrorRate();
}


text:
/**
 * @memberOf Jymfony.Component.Logger
 */
export default class LogLevel { }

/**
 * System is unusable.
 *
 * @type {int}
 */
LogLevel.EMERGENCY = 600;

/**
 * Action must be taken immediately.
 *
 * @type {int}
 */
LogLevel.ALERT = 550;

/**
 * Critical conditions.
 *
 * @type {int}
 */
LogLevel.CRITICAL = 500;

/**
 * Runtime errors that do not require immediate action but should typically
 * be logged and monitored.
 *
 * @type {int}
 */
LogLevel.ERROR = 400;

/**
 * Exceptional occurrences that are not errors.
 *
 * Example: Use of deprecated APIs, poor use of an API, undesirable things
 * that are not necessarily wrong.
 *
 * @type {int}
 */
LogLevel.WARNING = 300;

/**
 * Normal but significant events.
 *
 * @type {int}
 */
LogLevel.NOTICE = 250;

/**
 * Interesting events.
 *
 * @type {int}
 */
LogLevel.INFO = 200;

/**
 * Detailed debug information.
 *
 * @type {int}
 */
LogLevel.DEBUG = 100;


text:
#ifndef EZBAKE_COMMON_SECURITY_PBEMD5ANDDES_H_
#define EZBAKE_COMMON_SECURITY_PBEMD5ANDDES_H_

#include <ezbake/common/security/PbeStringEncryptor.h>
#include <openssl/des.h>

namespace ezbake { namespace common { namespace security {

class PbeMd5AndDesEncryptor : public PbeStringEncryptor<PbeMd5AndDesEncryptor> {
public:
    typedef struct {
        DES_key_schedule schedule;
        DES_cblock       ivec;
    }PbeMd5AndDesKey;

public:
    static const unsigned int ALGO_BLOCK_SIZE;

public:
    /**
     * Returns an encrypted string
     *
     * @param plaintext     the message to be encrypted
     * @param password      the password used in encrypting the message
     * @param salt          the salt used in the encryption algorithm.
     * @param iterations    number of passes in randomizing the password used in encryption.
     *
     * @throws StringEncryptorException if an error occurs while encrypting the message
     */
    static std::string encrypt(const std::string& plaintext, const std::string& password,
            const std::string salt="do provide default", long iterations=1000);

    /**
     * Returns a descrypted string
     *
     * @param encryptedtext the message to be decrypted
     * @param password      the password used in decrypting the message
     * @param salt          the salt used in the encryption algorithm.
     * @param iterations    number of passes in randomizing the password used in encryption.
     *
     * @throws StringEncryptorException if an error occurs while decrypting the message
     */
    static std::string decrypt(const std::string& encryptedtext, const std::string& password,
            const std::string salt="do provide default", long iterations=1000);

    /**
     * Generates a Pbe Md5 & Des Key
     *
     * @param password      required password for the key
     * @param salt          password salt.
     * @param iterations    number of passes in randomizing the password.
     *
     * @throws StringEncryptorException if an error occurs while decrypting the message
     */
    static PbeMd5AndDesKey generateKey(const std::string& password, const std::string salt, long iterations);

private:
    static std::string generateDataHash(const std::string& data, const std::string salt, long iterations);
};

}}} // ezbake::common::security

#endif /* EZBAKE_COMMON_SECURITY_PBEMD5ANDDES_H_ */


text:
#ifndef UNITTEST_H_
#define UNITTEST_H_

// gtest indirectly included inttypes.h, without __STDC_CONSTANT_MACROS.
#ifndef __STDC_CONSTANT_MACROS
#  define __STDC_CONSTANT_MACROS 1 // required by C++ standard
#endif

#ifdef _MSC_VER
#define _CRTDBG_MAP_ALLOC
#include <crtdbg.h>
#pragma warning(disable : 4996) // 'function': was declared deprecated
#endif

#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 2))
#if defined(__clang__) || (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
#pragma GCC diagnostic push
#endif
#pragma GCC diagnostic ignored "-Weffc++"
#endif

#include "gtest/gtest.h"
#include <stdexcept>

#if defined(__clang__) || defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 6))
#pragma GCC diagnostic pop
#endif

template <typename Ch>
inline unsigned StrLen(const Ch* s) {
    const Ch* p = s;
    while (*p) p++;
    return unsigned(p - s);
}

template<typename Ch>
inline int StrCmp(const Ch* s1, const Ch* s2) {
    while(*s1 && (*s1 == *s2)) { s1++; s2++; }
    return (unsigned)*s1 < (unsigned)*s2 ? -1 : (unsigned)*s1 > (unsigned)*s2;
}

template <typename Ch>
inline Ch* StrDup(const Ch* str) {
    size_t bufferSize = sizeof(Ch) * (StrLen(str) + 1);
    Ch* buffer = (Ch*)malloc(bufferSize);
    memcpy(buffer, str, bufferSize);
    return buffer;
}

inline FILE* TempFile(char *filename) {
#if _MSC_VER
    filename = tmpnam(filename);

    // For Visual Studio, tmpnam() adds a backslash in front. Remove it.
    if (filename[0] == '\\')
        for (int i = 0; filename[i] != '\0'; i++)
            filename[i] = filename[i + 1];

    return fopen(filename, "wb");
#else
    strcpy(filename, "/tmp/fileXXXXXX");
    int fd = mkstemp(filename);
    return fdopen(fd, "w");
#endif
}

// Use exception for catching assert
#if _MSC_VER
#pragma warning(disable : 4127)
#endif

class AssertException : public std::logic_error {
public:
    AssertException(const char* w) : std::logic_error(w) {}
};

#define RAPIDJSON_ASSERT(x) if (!(x)) throw AssertException(RAPIDJSON_STRINGIFY(x))

class Random {
public:
    Random(unsigned seed = 0) : mSeed(seed) {}

    unsigned operator()() {
        mSeed = 214013 * mSeed + 2531011;
        return mSeed;
    }

private:
    unsigned mSeed;
};

#endif // UNITTEST_H_


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package team1100.season2010.robot;

import edu.wpi.first.wpilibj.Solenoid;

/**
 *
 * @author team1100
 */
public class HookLift {
    private AdvJaguar lift_jaguar; //the winch
    private Solenoid hook_piston; //the hook on the end of the arm
    private Solenoid arm_piston; //the solenoid pushing the entire arm
    private boolean arm_dropped;
    private boolean hook_dropped;

    public HookLift()
    {
        //Default constructor
        this(4,8);
    }

    public HookLift(int slot, int channel)
    {
       lift_jaguar = new AdvJaguar(slot,channel);
       hook_piston = new Solenoid(8,7);
       arm_piston = new Solenoid(8,8);
       arm_dropped = false;
       hook_dropped = false;
       //raiseArm();
       //liftHook();
    }

    public void moveWinch(double speed)
    {
        lift_jaguar.set(speed);
    }

    public void stopWinch()
    {
        lift_jaguar.set(0);
    }

    public void dropHook()
    {
        hook_piston.set(false);
        hook_dropped = true;
    }
    public void liftHook()
    {
        // return hook to starting position
        hook_piston.set(true);
        hook_dropped = false;
    }

    public void dropArm()
    {
        arm_piston.set(true);
        arm_dropped = true;
    }

    public boolean isArmDropped()
    {
        return arm_dropped;
    }

    public boolean isHookDropped()
    {
        return hook_dropped;
    }

    public void raiseArm()
    {
        arm_piston.set(false);

    }
}


text:
package com.tassioauad.moviecheck.view;

import com.tassioauad.moviecheck.model.entity.Movie;

import java.util.List;

public interface ListUpcomingMoviesView {
    void showLoadingMovies();

    void warnAnyMovieFounded();

    void showMovies(List<Movie> movieList);

    void hideLoadingMovies();

    void warnFailedToLoadMovies();
}


text:
/**
 * Created by davidlum on 4/4/17.
 */

const twoPi = Math.PI*2;

class Waves {
    waves: Wave[] = [];
    yvals: number[];
    ampSum: number;

    constructor() {
        let initWave: Wave;
        initWave = new Wave();
        this.waves.push(initWave);
    }

    calcAmpSum() : number {
        this.ampSum = 0;
        for (let wave of this.waves) {
            this.ampSum += wave.amplitude;
        }
        return this.ampSum;
    }

    calcY(t: number) : number {
        let yval = 0;
        let phase: number;
        for (let wave of this.waves) {
            phase = wave.phase * Math.PI;
            if (wave.waveType == "cos") {
                phase += Math.PI/2;
            }
            yval += wave.amplitude * Math.sin(wave.frequency * twoPi * t + phase);
        }
        return yval
    }

    // Creates the current array of y values
    calcYVals(canv: Canvas, sig: Signal) : void {
        this.yvals = [];
        canv.animCounter = 0;
        let count = 0;
        let inc = 2/ canv.width;
        for (let x = 0; x < canv.width; x++){
            let y = this.calcY(count);
            count += inc;
            this.yvals.push(y);
        }
        sig.signal = this.yvals.slice();
        this.calcAmpSum();
        for (let x = 0; x < 3*canv.width; x++){
            this.yvals[x] = canv.origin - this.yvals[x]/(this.ampSum)*(180);
        }
    }
}

class Signal {
    signal: number[];

    // quick to write slow to run dft
    // will change to fft
    dft() : number[] {
        let real,
            imag: number;
        let coefs = [];
        let period = this.signal.length/2;
        let realArr = new Float32Array(period);
        let imagArr = new Float32Array(period);
        for (let bin = 0; bin < period; bin++) {
            real = 0;
            imag = 0;
            for (let n = 0; n < period; n++) {
                real += this.signal[n] * Math.cos(-2*Math.PI*n*bin/period);
                imag += this.signal[n] * Math.sin(-2*Math.PI*n*bin/period);
            }
            realArr[bin] = real;
            imagArr[bin] = imag;
        }
        coefs.push(realArr);
        coefs.push(imagArr);
        return coefs;
    }

}

class Wave {
    waveType: string;
    amplitude: number;
    frequency: number;
    phaseNum: number;
    phaseDenom: number;
    phase: number;

    constructor() {

        // parseInt returns NaN on zero sometimes.
        // This function kind of deals with that.
        let getAndParse = (id: string) : number => {
            let boolOrNum = parseInt($(id).val(), 10) || true;
            if (boolOrNum === true) {
                return 0;
            } else { return boolOrNum; }
        };

        this.waveType = $("#wavetype").val();
        this.amplitude = getAndParse("#amp");
        this.frequency = getAndParse("#freq");
        this.phaseNum =  getAndParse("#phaseNumerator");
        this.phaseDenom = getAndParse("#phaseDenominator");

        let check = () => {
            if (this.phaseNum === 0 || this.phaseDenom === 0) {
                return 0; }
            else {
                return this.phaseNum/this.phaseDenom; }
        };

        this.phase = check();
    }

    validateWave() : boolean {
        let test1 = (i: number): boolean => { return (i < 1 || 1 > 99) };
        let test2 = (i: number): boolean => { return (i < -99 || i > 99) };
        return (test1(this.amplitude) ||
                test1(this.frequency) ||
                test2(this.phaseDenom) ||
                test2(this.phaseNum))
    }
}

class Canvas {

    canvas: HTMLCanvasElement;
    ctx: CanvasRenderingContext2D;
    animCounter: number = 0;
    readonly height: number = 400;
    readonly width: number = this.height*2;
    readonly origin: number = this.height/2;

    constructor() {
        this.canvas = <HTMLCanvasElement> document.getElementById('canvas');
        this.ctx = <CanvasRenderingContext2D> this.canvas.getContext("2d");
        this.canvas.height = this.height;
        this.canvas.width = this.width;
    }

    // Plots the axis.
    plotGraph() : void {
        this.ctx.beginPath();
        this.ctx.lineWidth = 1;
        this.ctx.strokeStyle = 'black';
        this.ctx.moveTo(0, (this.origin));
        this.ctx.lineTo(this.width,(this.origin));
        this.ctx.stroke();

        this.ctx.beginPath();
        this.ctx.moveTo(0,0);
        this.ctx.lineTo(0,this.height);
        this.ctx.stroke();
    }

    // Plots the Wave
    plotWave(arr) : void {
        this.ctx.clearRect(0, 0, this.width, this.height);
        this.plotGraph();
        this.ctx.beginPath();
        this.ctx.moveTo(0, arr[this.animCounter]);
        for (let x = 0; x < this.width; x++){
            this.ctx.lineTo(x, arr[(x + this.animCounter) % this.width]);
        }
        this.animCounter += 1;
        if (this.animCounter > 799) { this.animCounter = 0;}
        this.ctx.lineWidth = 4;
        this.ctx.strokeStyle = '#4a7056';
        this.ctx.stroke();
    }

}

class Initializer {
    ws: Waves;
    canvas: Canvas;
    audio: AudioButton;
    intervalID: number; // the id of the current animation so we can clear it
    clearDiv: HTMLElement = document.getElementById("clearDiv");
    form: HTMLElement = document.getElementById("form"); // the form

    constructor(){
        this.ws = new Waves();
        this.canvas = new Canvas();
        this.audio = new AudioButton();

        // Adds a waveform to waves[] and then plots it.
        // Does nothing if input is no bueno.
        let addWave = (event: any) => {
            event.preventDefault(); // prevents page from reloading automatically
            let wave = new Wave();

            if (wave.validateWave()) {
                console.log("bad Inputs.")
            }
            else {
                this.ws.waves.push(wave);
                this.clearForm();
                this.init();
            }
        };
        this.form.addEventListener("submit", addWave, true);
    }

    // starts the animation
    init() : void {
        this.ws.calcYVals(this.canvas, this.audio.signal);
        clearInterval(this.intervalID);
        this.intervalID = setInterval( () => {
            this.canvas.plotWave(this.ws.yvals)
        }, 40);
    }

    // creates the set of buttons to clear individual waveforms
    clearForm() : void {
        while (this.clearDiv.firstChild) {
            this.clearDiv.removeChild(this.clearDiv.firstChild);
        }
        this.ws.calcAmpSum();
        let Idcounter = 0;
        for (let w of this.ws.waves) {
            let text: string;
            text = Math.round((w.amplitude/this.ws.ampSum)*100)/100+" \xD7 "+ w.waveType + "("+ w.frequency +" \xD7 "+"2\u03C0t";
            if (w.phase != 0 && (w.phaseNum != w.phaseDenom)) {
                text = text+" + "+w.phaseNum+"\u03C0/"+w.phaseDenom+")";
            } else {
                text = text + ")";
            }

            let newp = document.createElement("button");
            let br = document.createElement("br");
            newp.id = Idcounter.toString();
            let tnode = document.createTextNode(text);
            newp.appendChild(tnode);
            newp.addEventListener("click", (event: any) => {
                this.ws.waves.splice(parseInt((<HTMLElement>event.target).id), 1);
                this.clearForm();
                this.init();
            });
            Idcounter++;
            this.clearDiv.appendChild(newp);
            this.clearDiv.appendChild(br);
        }
    }
}

class AudioButton {
    play: HTMLElement = document.getElementById("playsound"); // playing the sound
    ac: AudioContext;
    freq: number;
    signal: Signal;

    constructor(){
        this.signal = new Signal();
        //button for play Sound with Gain envelope
        this.play.addEventListener("submit", (event: any) => {
            if (this.ac !== undefined) { this.ac.close(); }
            event.preventDefault();
            let getAndParse = function() {
                let freq = parseInt($("#userFreq").val(), 10) || true;
                if (freq === true || freq < 100 || freq > 2000) {
                    freq = 220;
                }
                return freq;
            };
            this.freq = getAndParse();
            let coefs = this.signal.dft();
            this.ac = new AudioContext();
            let osc = this.ac.createOscillator();
            let wave = this.ac.createPeriodicWave(coefs[0], coefs[1]);
            osc.setPeriodicWave(wave);
            osc.frequency.value = this.freq;
            let gainNode = this.ac.createGain();
            osc.connect(gainNode);
            gainNode.connect(this.ac.destination);
            gainNode.gain.setValueAtTime(0, this.ac.currentTime);
            osc.start();
            gainNode.gain.linearRampToValueAtTime(1, this.ac.currentTime+0.1);
            gainNode.gain.linearRampToValueAtTime(0, this.ac.currentTime+4);
            osc.stop(4);
        });
    }
}

// run
$(document).ready(function(){
    let init: Initializer;
    init = new Initializer();
    init.init();
    init.clearForm();
});


text:
package com.libmailcore;

/** Operation to check authentication information. */
public class SMTPCheckAccountOperation extends SMTPOperation {
}


text:
<!doctype html>

		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

		<title>Please Enqueue Responbily - Ethan Clevenger</title>

		<link rel="stylesheet" href="dist/reset.css">
		<link rel="stylesheet" href="dist/reveal.css">
        <link rel="stylesheet" href="dist/theme/night.css">
		<link href='https://fonts.googleapis.com/css?family=Lobster' rel='stylesheet' type='text/css'>
		<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css">

		<link rel="stylesheet" href="plugin/hightlight/zenburn.css">

Please Enqueue Responsibly

Ethan Clevenger

A bit about me

								<svg version="1.1" id="Layer_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 153.62 22.795" style="enable-background:new 0 0 153.62 22.795;" xml:space="preserve">

									<polygon style="" class="webspec-fill" points="21.723,5.368 24.767,5.368 26.612,15.323 26.652,15.323 28.89,5.368 32.384,5.368
									34.505,15.323 34.544,15.323 36.312,5.368 39.218,5.368 36.077,19.546 32.796,19.546 30.579,9.177 30.539,9.177 28.084,19.546
									24.865,19.546 "></polygon>
									<polygon style="" class="webspec-fill" points="39.847,19.546 39.847,5.368 47.583,5.368 47.583,7.546 42.813,7.546 42.813,11.044
									47.21,11.044 47.21,13.224 42.813,13.224 42.813,17.366 47.742,17.366 47.742,19.546 "></polygon>
									<g>
									<defs>
									<rect id="SVGID_1_" width="153.62" height="22.795"></rect>
									</defs>
									<clipPath id="SVGID_2_">
									<use xlink:href="#SVGID_1_" style="overflow:visible;"></use>
									</clipPath>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M49.116,19.546V5.368h5.263c2.259,0,4.123,0.646,4.123,3.672
									c0,1.631-0.805,2.806-2.415,3.123V12.2c2.1,0.297,2.651,1.65,2.651,3.594c0,3.592-3.122,3.752-4.379,3.752H49.116z M52.082,11.161
									h1.982c0.649,0,1.552-0.434,1.552-1.807c0-1.041-0.706-1.808-1.708-1.808h-1.826V11.161z M52.082,17.366h1.649
									c0.628,0,2.042-0.02,2.042-2.006c0-1.254-0.472-2.021-1.964-2.021h-1.727V17.366z"></path>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M64.335,19.78c-3.672,0-4.361-2.16-4.203-4.615h2.965
									c0,1.357,0.058,2.494,1.687,2.494c1.002,0,1.494-0.648,1.494-1.608c0-2.556-5.969-2.712-5.969-6.931
									c0-2.219,1.06-3.988,4.673-3.988c2.885,0,4.321,1.296,4.124,4.263h-2.888c0-1.064-0.176-2.142-1.374-2.142
									c-0.961,0-1.53,0.531-1.53,1.509c0,2.692,5.968,2.457,5.968,6.914C69.282,19.351,66.592,19.78,64.335,19.78"></path>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M70.833,5.368h5.343c2.709,0,3.769,1.649,3.769,4.243
									c0,1.609-0.471,4.162-3.945,4.162h-2.2v5.773h-2.966V5.368z M73.799,11.591h1.649c0.883,0,1.493-0.961,1.493-1.902
									c0-1.161-0.315-2.143-1.649-2.143h-1.493V11.591z"></path>
									<polygon style="clip-path:url(#SVGID_2_);" class="webspec-fill" points="81.144,19.546 81.144,5.368 88.88,5.368 88.88,7.546
									84.109,7.546 84.109,11.044 88.506,11.044 88.506,13.224 84.109,13.224 84.109,17.366 89.038,17.366 89.038,19.546 	"></polygon>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M90.236,12.456c0-3.752,0-7.322,4.888-7.322
									c3.024,0,4.243,1.668,4.122,4.711h-2.902c0-1.885-0.336-2.592-1.22-2.592c-1.668,0-1.883,1.57-1.883,5.203s0.215,5.203,1.883,5.203
									c1.375,0,1.316-1.768,1.356-2.885h2.926c0,3.789-1.512,5.006-4.282,5.006C90.236,19.78,90.236,16.167,90.236,12.456"></path>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M102.332,5.368h3.75c3.964,0,4.456,2.316,4.456,7.146
									c0,4.711-0.687,7.031-4.967,7.031h-3.239V5.368z M103.587,18.485h1.529c3.791,0,4.164-1.021,4.164-6.814
									c0-4.065-0.549-5.243-4.046-5.243h-1.647V18.485z"></path>
									<polygon style="clip-path:url(#SVGID_2_);" class="webspec-fill" points="119.177,5.368 119.177,6.429 114.013,6.429 114.013,11.727
									118.942,11.727 118.942,12.79 114.013,12.79 114.013,18.485 119.314,18.485 119.314,19.546 112.758,19.546 112.758,5.368 	"></polygon>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M126.935,8.962c-0.041-1.748-0.472-2.811-2.396-2.811
									c-1.531,0-2.495,0.532-2.495,2.202c0,2.101,1.062,2.16,2.673,3.318c1.747,1.256,3.535,1.631,3.535,4.379
									c0,2.533-1.299,3.77-3.771,3.77c-2.77,0-4.007-1.494-3.89-4.262h1.297c0,1.574,0.117,3.201,2.65,3.201
									c1.647,0,2.453-0.885,2.453-2.512c0-1.924-1.275-2.475-3.316-3.732c-2.75-1.688-2.867-2.535-2.886-3.948
									c-0.021-2.453,1.529-3.472,3.848-3.472c2.946,0,3.573,1.824,3.573,3.867H126.935z"></path>
									<rect x="130.389" y="5.37" style="clip-path:url(#SVGID_2_);" class="webspec-fill" width="1.259" height="14.176"></rect>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M140.816,13.204h-2.867v-1.062h4.125v7.089
									c-1.258,0.393-2.574,0.588-3.908,0.588c-4.613,0-4.281-4.613-4.281-7.363s-0.332-7.361,4.281-7.361
									c2.711,0,4.104,1.156,4.045,3.906h-1.257c0-1.867-0.806-2.85-2.788-2.85c-3.062,0-3.022,2.731-3.022,6.305
									c0,3.574-0.04,6.303,3.022,6.303c1.079,0,1.982-0.156,2.65-0.409V13.204z"></path>
									<polygon style="clip-path:url(#SVGID_2_);" class="webspec-fill" points="144.646,19.546 144.646,5.368 146.57,5.368 152.324,17.817
									152.365,17.776 152.365,5.368 153.62,5.368 153.62,19.546 151.714,19.546 145.943,6.96 145.902,6.997 145.902,19.546 	"></polygon>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M1.753,11.272c-1.521,2.977,1.091,7.685,6.068,11.521h7.182V10.04
									C8.723,7.88,3.318,8.208,1.753,11.272"></path>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M0,16.088v6.707h6.58C3.663,20.702,1.396,18.312,0,16.088"></path>
									<path style="clip-path:url(#SVGID_2_);" class="webspec-fill" d="M15.003,9.277V0H0v8.424C2.674,6.397,8.49,6.752,15.003,9.277"></path>
									</g>
								</svg>

					beerPilgrimage

								ethanclevenger.com

								ethanclevenger91

								@ethanclevenger

								eclev91

					Hey, I'm Ethan Clevenger. I'm a frontend/backend web developer, designer, what-have-you from Des Moines, IA. I work for a company up there called Webspec Design where I do a lot of WordPress work, but also some custom stuff working with MVCs like Laravel. I run a website called BeerPilgrimage, I write for an new online publication called Finding the Forest, and I also do some freelance, I have a couple open-source libraries and contribute to others, so on and so forth. I've got one WordPress plugin out there, Picture Element Thumbnails, that does responsive images for WordPress. You might be saying "Well isn't that built into core now?" to which I would say that the conversation on the difference between responsive images and art-directed responsive images is a topic for another talk, because today I'm here to talk about scripts, styles, requests and performance.

"Beginner"

Internet - self-taught, chasm of best-practices

Talking about "basics" at WordCamp

Everyone's a beginner at something

Consider the requirements of your project

Don't do something because I said so

Agh, I don't want to say don't use the word beginner, because there is such a thing, but see, the web is a funny industry in that, and this might be a lot of you, it's very easy to teach yourself, start doing stuff for clients, never have a code review and do things totally "wrong" but be wildly successful doing it. So you end up with practices that someone like me might take for granted that you've never even thought about and, similarly, things you take for granted that I've never thought of, unlike many other industries where you pretty much have to have a formalized education.

So we come to WordCamp and we're like "Ah, the pinnacle of WordPress!" But we're having conversations, which we totally should, about "basic" things like wp_enqueue_scripts, which many people may be super familiar with and a lot of others may have never heard of. Conversely, I doubt they have presentations about "basic" things, like giving booster shots, at pediatrics conventions. The long and short of that whole spiel is that this talk is labeled intermediate but it's really for everybody and you can take it as far as you want. We're all beginners at something and you should never feel bad for not knowing something. Don't let someone say "Oh you don't know that, are you even a web developer?"

So today I'm going to chat with you about scripts and styles and give you lots of advice, but you should remember a couple things. The first is that I'm working on my site and you're working on yours, so take everything I say and then use your best judgement. You know your projects better than I do. The second thing to remember is that "because some guy at WordCamp said so" is a terrible reason to do anything. Especially for people who do client work, you should always be asking why you're doing something, so I'm actually going to start off talking about why this stuff is important and make a pitch for the relevence of my talk today.

Your site should be fast.

Bounce at 4-ish seconds, at mercy of computer between 1 and 10

Speed analyzers red

All content loaded - not TTFB

					*https://www.nngroup.com/articles/website-response-times/

Your site should be fast. This isn't new information to any of you I'm sure - there are piles of articles out there on the web that say bounce rates skyrocket after four-ish seconds. According to Nielsen Norman, your users not only bounce, but start to feel "at the mercy of the computer" beginning after just one second, and bounce definitely after 10 seconds.

And I am talking about users here, so like your site is loaded fast. Not just time-to-first-byte or stuff starts popping in. If ads are still loading, your site isn't done as far as I'm concerned, especially if they're bumping content around and marring up the scroll. Sorry.

If you've ever submitted a slow site to Google's page speed analyzer, you'll notice it gives you big red boxes as feedback, and that's pretty much the same for any service that does page speed analytics. That's because slow is, generally, bad.

Requests

Any time a site gets a resource from a server

FIFO, HOL-blocking

Images are a lost cause

So we're probably all on board with that. Here's the less-well-known part - why is your site slow? There can be lots of reasons, but generally, it has to do with requests - that is, any time your site gets a resource from a server.

Requests to any one server, using HTTP/1.1, are FIFO - first-in-first-out. Results must be returned in the order they were received. Sometimes this results in head-of-line blocking, and even when it doesn't, there's still a line. This means, generally, that more requests are more detrimental to the load speed of your website than big requests. Not that this totally excuses you for having 10MB images on your site, as that's bad for a host of other reasons, not limited to site speed.

And if you've been on the internet lately, you might have noticed that images are in vogue. They're engaging, they tell stories - people will even sell you pretty but generic ones to stuff into your website.

Unfortunately, these are the requests we have the least ability to optimize - they tie your hands. As a WordPress theme developer, you're probably creating spaces for the end user to upload images, and they can drop as many as they want into the WYSIWYG. Every one of those is a single request - you can't generate fancy spritesheets and have totally arbitrary images.

So if images are out there trashing our websites, we can at least cut our losses by making our CSS and JS efficient. If you aren't sold on the idea of making a fast website and doing it by getting smart with our requests, your probably not going to get much from this talk.

For everyone else, I'm going to apply this specifically to WordPress. The first thing we can do is start using these magic functions `wp_enqueue_script` and `wp_enqueue_style`.

wp_enqueue_script, wp_enqueue_style

Alert WordPress to scripts and styles your site will require

Dependency management

How many of you are already familiar with these functions?

Awesome, I had hoped so/this talk might go from 0 to advanced real quick then. Alternatively, how many of you are currently putting script and link tags right into your theme template files?

I feel like some of you raised your hands for both. I thought those were mutually exclusive…

So what do `wp_enqueue_script` and `wp_enqueue_style` do? These are functions that alert WordPress to the existence of scripts and styles that the site is going to require, where they should be dropped in, what version if the file it is and if it depends on any other scripts or styles. Then, when you call `wp_head()` in your header or `wp_footer()` in your footer, it's going resolve those dependencies and drop in your script and link tags for you.

Why do we use these? The dependency management is nice, and it keeps us from accidentally loading up some files more than once. It also keeps our template files template-y - focused on layout rather than making sure our scripts and styles are loaded in the right place in the right order from page to page to page. Let's look at some examples.

                </script>

Okay, so what's wrong here? First we've linked in our theme's styles, which is probably fine. Next, oh, well looks like we wanted to use WordPress's dashicons on the front end. Hope they don't move those on us. Next we've got our theme's scripts, once again, pretty unremarkable, and finally, ah, yes. We've loaded jQuery from a CDN like everyone tells us to, but there are a couple issues. First issue is our own scripts probably depend on jQuery but we've loaded them out of order. Furthermore, some plugin author is probably going to load WordPress's jQuery, so then we'll have two versions loaded together, which never pans out. Finally, you generally don't need to put your script tags in your header and hold up the rest of the site. That's called render-blocking content.

class Plz {
	function __construct() {
		add_action('wp_enqueue_scripts', [$this, 'wp_enqueue_scripts']);
	}

	function wp_enqueue_scripts() {
		wp_enqueue_script(
			'google-maps',
			'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap'
		);
		wp_enqueue_script(
			'theme-scripts',
			get_template_directory_uri() .'/js/scripts.js',
			['jquery'],
			filemtime(get_template_directory().'/js/scripts.js'),
			true
		);
		wp_enqueue_style(
			'theme-styles',
			get_template_directory_uri() . '/style.css',
			false,
			filemtime(get_template_directory().'/style.css')
		);
		wp_enqueue_style('dashicons');
	}
}
$plz = new Plz();

So like good PHP programmers, we're going to wrap our functions file or our plugin in a class and not clutter the global namespace. Then we can hook into the wp_enqueue_scripts action with our own function and queue up some stuff. You'll see we give our resource a handle and then a URL. In our second script here you'll see I've included a third argument, which is dependencies. Our theme's scripts depend on jQuery, so WordPress won't load them without jQuery. Then we've got our theme styles, and you can see here I haven't passed any dependencies, but I have passed a function for the write time of the file - this is a fun way to cache-bust your resources. Finally, WordPress also has already registered a handle for dashicons so we can enqueue that by itself. I'll explain registering a bit later.

Cool, okay, so what other WordPress stuff can we do? I vote we move jQuery to the footer. By default, WordPress sticks it in the header - gross. If your site depends on jQuery for the layout to be right or takes so long to load that the user is going to do something that should fire some jQuery logic before the page is loaded, you've got other problems. You might rethink your layout. This is also a great intro to manipulating third-party plugins' scripts and styles - another handy advantage of these functions. Here's how we can do that:

wp_deregister_script( 'jquery' );
wp_enqueue_script( 'jquery', includes_url( '/js/jquery/jquery.js' ), false, false, true );

Once again, WordPress already registers a handle for jQuery. You'll see with jQuery I've actually deregistered WordPress's default handle and re-registered it. The fifth argument is to load the resource in the footer so it isn't render-blocking. Not sure why this isn't default WordPress behavior, but I'd call it best practice. We're using the same file and handle so that when plugin developers enqueue jQuery, it doesn't get enqueued twice.

Enqueueing in Plugins

wp_enqueue_script is indiscriminate

wp_register_script

Various plugins you install to your site or that you develop are going to need their own scripts and styles. "Yeah! So I'll just hook into wp_enqueue_scripts() and enqueue my scripts!" Don't do that, probably.

By actually enqueuing your scripts on the enqueue scripts action, you're telling WordPress to load that script or style on every single page on the site. This probably isn't necessary. Fortunately, there's a solution.

wp_enqueue_script() and wp_enqueue_style() come with a couple of related functions called wp_register_script() and wp_register_style(). These functions take the same arguments as their enqueue counterparts, but don't actually tell WordPress to spit them out. Instead, it saves them for later, when you can call wp_enqueue_script() using the handle you registered and queues it up then - like dashicons and jQuery earlier. So the way this ends up working is you can register your script and then, at your plugin's entry point, be that a shortcode or a template file or a function call, enqueue the relevant scripts and styles. This prevents your scripts and styles from being loaded on every page, in particular those that your plugin isn't actually acting upon.

Unfortunately, a lot of plugins don't do this. I'd like to talk about one in particular that has a lot of the market despite being, in more than just request efficiency, generally really frustrating to work with as a dev. Say hi to NextGen Gallery.

So before you freak out, NextGen actually addressed this issue. According to the changelog, it was February of last year. That being said, this plus some other behavior I'm not super fond of kept me away from NextGen long enough that I wasn't around to hear it was fixed. It's also a great lesson to be learned.

Here's the story: at the point in time where this was a problem, NextGen loaded about 13 styles and scripts to do some of its basic gallery things. Now even if that's only showing up on one page, that's a lot. But here's the kicker - you could spin up a default WordPress site, base theme, not touch any settings. Install NextGen, don't even set up a gallery or upload photos. If you checked out the network tab on your home page, there were those 13 scripts and styles. On every page. Whew.

Like I said, they've cleaned it up, which is awesome, and if you peruse the changelog, they've been making a lot of efforts at being performant, which is nifty.

Here's another, less dramatic example - Contact Form 7. To this day, Contact Form 7 makes 3 requests on every page on your site - 2 scripts, dutifully in the footer, and one stylesheet. Let's go ahead and demo that.

Demo Time

					Clean up Contact Form 7 Scripts and Styles

There's even a blog post on the developer's website telling you how to turn it off. I don't know the intricacies of how Contact Form 7 works, but I'd like to think this could be avoided out of the box.

Level 2

Optimization

Thus far, we've talked about ways that WordPress allows us to make sure that the actual task of making a request is done intelligently - only when necessary and without duplication of resources. Now let's see what we can do with our code to make the files themselves more efficient.

CSS Preprocessors

Scss, LESS

PrePros, Crunch, CodeKit

First let's talk about CSS preprocessors. How many people in the room are writing vanilla CSS? Alright, a few of you. Many of you may be familiar with these and just don't care and for others, maybe this is news to you.

There are a couple of big CSS extension languages out there called LESS and Sass, or SCSS. Neither of them are technically required for using CSS preprocessors, but they sure are nice. They let us declare variables, use imports, nest selectors, define "functions", lots of fun stuff. Explore them if you haven't.

But the browser can't read any of these extension languages, so we use CSS preprocessors. I'm familiar with a few I've listed here, and your neighbor probably has their favorite. These will compile your scss or your less into browser-friendly CSS. In regards to our talk today, I'm going to talk about two big things we get out of these: concatenation and minification.

Open WordCamp demo theme

So here's a pretty basic WordPress theme. I've got a header, footer, index, functions and styles. Really about the bare minimum, you can ignore some of that other stuff for now. Now I can open my styles.css file and you see I've got some basic styles here, and if we open my functions.php file, you'll see I've enqueued it. Let's hop on the front of the site and, sure enough, I've got a pretty straightforward "Hello World". Great.

How about I want to load up another CSS file? I'm a good dev, I like to keep my code compartmentalized. Atomic design and all that. So I hop into my css folder directory and I've got a new styles.css here. Let's add something silly, like make my background orange, and then go over to functions and enqueue that. Refresh and the background is orange. Well that _works_, but now we're up a request. Yuck. How can we avoid that? Well we can put all our styles in one file, but that becomes unmanageable. How about a CSS extension language?

For this example, I'm using my extension of choice, scss. I'll hop into my scss directory, set up a new file here and copy over the code from my original stylesheet. Now if you're using a tool like Prepros, you can drag your theme right in here and it's going to automatically find your scss and compile it as soon as we save. Let's go back to our file, save, and sure enough, we get a quick notification that says everything went well. And if we open up our css folder, we see its contents have been replaced with the results of the compilation. Couldn't be much easier. Let's go over to functions and enqueue this sheet instead of the default one. Perfect.

Now let's get back to compartmentalized code: I want several files, but just one request. Well with scss, that becomes super easy. I can create a new directory here called partials, create a new file, for now we'll call it foo.scss or something, and we can make our background orange right here. Now back in our main styles.css, I can @import my other stylesheet right underneath my other styles. Let's save and refresh, sure enough, we've got an orange background.

And that scales very very well. I can also configure PrePros to minify my files when it's done so that I end up with the smallest filesize possible. It'll do the same kind of thing for Javascript files, too - concatenation and minification, and compilation if you're using something like CoffeeScript.

Level 3

Task Runners

Gulp

Grunt

							Now personally, I'm not much for these big GUI apps. They do what they do well, but there's a lot more out there you can do with your files of all kinds, and for that, you're going to need something more extensible. The solution is task runners. These have gotten super popular recently. These are command line tools generally based on Node.js, which is like server-side javascript. Gulp and Grunt are the two big ones, and I'm going to give you a quick look at Gulp by getting it configured to do the same stuff that PrePros was doing. This is going to be a super-fast crash course and you should definitely look for tutorials on getting started with this stuff. I'm just here to convince you it's awesome.

							First, you'll want to set up a package.json that says your project requires gulp. [Explain package.json] It does this via a tool called npm, which stands for node package manager. You can Google that for more information about getting set up.

							So gulp operates on the idea of plugins, all of which are also maintained on npm. I'm gone ahead and installed gulp-sass, which will compile our scss for us. Let's go ahead and pause PrePros, wipe our CSS directory to make sure I'm not fooling you, and then from the command line we can run `gulp sass`. Our CSS file is generated and boom, refresh, same result. You can see I've also set up a watch task, so we can have gulp watch for file changes just like PrePros was doing.

							How about minification? Auto-prefixing? All done via other gulp plugins that I've already installed. I'll go ahead and uncomment the autoprefixer stuff here, save, check out our CSS and our flexbox is set for a variety of browsers. Same for minification.

							Gulp can be extended to do all kinds of stuff with your CSS - create spritesheets, compare against your markup and prune unused selectors, it's awesome. It'll also do your Javascript, minify images - you can do a lot with this thing.

							Last thing on gulp, I'm going to show you the gulpfile I like to use for production. I've actually further abstracted gulp behind a wonderful library from Laravel called Elixir. Let's open that up and take a look at what it's doing really quickly.

CDN vs Self-hosted

							All right, so the last thing I want to talk about today is CDNs. Raise your hand if you aren't familiar with CDNs. Real quick, a CDN or content-delivery network is a strategy for dispersing commonly-used resources across the world to minimize latency and downtime for delivery. If you've ever used a third-party front-end library, you've probably seen getting started instructions that inclue fetching from a CDN like MaxCDN, Google, there are a bunch. There are a variety of advantages to this strategy.

CDN Advantages

Server potentially closer to the user

Potential pre-cache

One less request in your server's pipeline

Generally, high uptime

CDNs are awesome for a few reasons. The first is that the CDN's location is likely closer to your user and hosted on a pretty kicking server, so the latency is likely to be low.

							There's also the advantage that this could be the same resources that a variety of sites around the internet are using, including ones your user has already visited. That means, at least on the first page load, there's a possibility that the file is already cached on the user's browser, which is good news for you. If not, their browser wil cache it after that and hopefully it'll benefit someone else down the line.

							Remember when we talked about that HTTP pipeline and how you can only have 4 concurrent connections to any one server? With CDNs, you take a request out of your stack and put it in another. Neato.

							And finally, these are companies that make their money by providing high uptime and low latency across a distributed network, so they do it pretty well.

CDN disadvantages

Uptime? Who cares?

I'm lazy and upgrade-happy

No CSS optimization

Giving up control

$

							This all sounds pretty good. Any disadvantages? Some.

							So first, I don't really care about uptime if the alternative is hosting it myself. If my site is down, it's not going to matter if I can fetch Bootstrap from the CDN, my site is down. If my site is up, I'll be able to fetch my own site from my own server. Similarly, let's say the CDN _did_ go down - now my site may load without the basic CSS framework. If you've been thoughtful about it, this may fall back to something useable, but that's not always true, so now it just looks like your site is broken. Personally, I'd rather all or nothing.

							Next, I really like to upgrade libraries. If I'm doing work on an existing client site, the first thing I often do is an npm update and get all my front-end libraries up-to-date before building, testing locally and pushing out. I like to think this minimizes bugs and potential security holes, though with front-end libraries that isn't usually a concern. With CDNs, the URL you're hitting is generally versioned, but I don't really care to figure out which version is the latest and then bump all my URLs manually. By the same token, I don't want to use the "latest" URL if the CDN offers it, because then any updates hit the live site without my oversight.

							CSS optimization. Let's go back to that scss file we were working with earlier. You'll notice here I've commented out a _lot_ of bootstrap rather than just @include bootstrap. I often only use the grid - some of this stuff I never comment out on any sites I work on. This makes sure my CSS is only as big as it needs to be. With a CDN, it's all or nothing. Now a lot of libraries only have one file, so it really doesn't make a difference like it does here with Bootstrap or other CSS frameworks.

							Giving up control. While unlikely, there's a possibility that your CDN is compromised or goes rouge or whatever and suddenly you're served up alternative or even malicious files. Or maybe they're collecting referrer information and using it to track your users? The former is unlikely and the latter is a small drop in a pool of questionable big data practices, but if it's something you're worried about, a CDN probably isn't for you. A tinfoil hat, however, might be.

							Finally, if you're looking to host your own resources on a CDN, that's going to cost money. If that's something you or your client have budgeted for, great, and if not, this may not be an option.

							As with most of the stuff I've talked about today, use your best judgement. A CDN is great for some situations and not so much for others. To be honest, Google Fonts and Typekit are the only two that I regularly use, as I prefer to bundle all my resources together for a single request in most other situations.

In Review

Enqueue your requests, and enqueue them conditionally

Make fewer requests

Optimize your resources

Task runners are your friend

Consider a CDN

						And that about wraps it up. Let's review real quickly what we went over today: [blah]. Any questions?


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>SuperLU: SRC/zpivotgrowth.c File Reference</title>
<link href="doxygen.css" rel="stylesheet" type="text/css">
<link href="tabs.css" rel="stylesheet" type="text/css">

Main Page

Data Structures

Files

SRC/zpivotgrowth.c File Reference
Computes the reciprocal pivot growth factor. More...

#include <math.h>

#include "slu_zdefs.h"

Functions

double 	zPivotGrowth (int ncols, SuperMatrix *A, int *perm_c, SuperMatrix *L, SuperMatrix *U)

Detailed Description

 -- SuperLU routine (version 2.0) --
 Univ. of California Berkeley, Xerox Palo Alto Research Center,
 and Lawrence Berkeley National Lab.
 November 15, 1997

Function Documentation

          double zPivotGrowth
          (
          int
           ncols,

          SuperMatrix *
           A,

          int *
           perm_c,

          SuperMatrix *
           L,

          SuperMatrix *
           U

          )

 Purpose
 =======

 Compute the reciprocal pivot growth factor of the leading ncols columns
 of the matrix, using the formula:
     min_j ( max_i(abs(A_ij)) / max_i(abs(U_ij)) )

 Arguments
 =========

 ncols    (input) int
          The number of columns of matrices A, L and U.

 A        (input) SuperMatrix*
	    Original matrix A, permuted by columns, of dimension
          (A->nrow, A->ncol). The type of A can be:
          Stype = NC; Dtype = SLU_Z; Mtype = GE.

 L        (output) SuperMatrix*
          The factor L from the factorization Pr*A=L*U; use compressed row
          subscripts storage for supernodes, i.e., L has type:
          Stype = SC; Dtype = SLU_Z; Mtype = TRLU.

 U        (output) SuperMatrix*
	    The factor U from the factorization Pr*A*Pc=L*U. Use column-wise
          storage scheme, i.e., U has types: Stype = NC;
          Dtype = SLU_Z; Mtype = TRU.

<address style="text-align: right;">Generated on Mon Nov 22 10:23:48 2010 for SuperLU by

 1.5.5 </address>


text:
/* Includes ------------------------------------------------------------------*/
#include "stm32f0xx_hal.h"

/** @addtogroup STM32F0xx_HAL_Driver
  * @{
  */

/** @defgroup ADCEx ADCEx
  * @brief ADC HAL module driver
  * @{
  */

#ifdef HAL_ADC_MODULE_ENABLED

/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/** @defgroup ADCEx_Private_Constants ADCEx Private Constants
  * @{
  */

/* Fixed timeout values for ADC calibration, enable settling time, disable  */
  /* settling time.                                                           */
  /* Values defined to be higher than worst cases: low clock frequency,       */
  /* maximum prescaler.                                                       */
  /* Ex of profile low frequency : Clock source at 0.1 MHz, ADC clock         */
  /* prescaler 4.                                                             */
  /* Unit: ms                                                                 */
  #define ADC_DISABLE_TIMEOUT           2
  #define ADC_CALIBRATION_TIMEOUT       2
/**
  * @}
  */

/* Private macros -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/

/** @defgroup ADCEx_Exported_Functions ADCEx Exported Functions
  * @{
  */

/** @defgroup ADCEx_Exported_Functions_Group1 Extended Initialization/de-initialization functions
 *  @brief    Extended Initialization and Configuration functions
 *
@verbatim
 ===============================================================================
                      ##### IO operation functions #####
 ===============================================================================
    [..]  This section provides functions allowing to:
      (+) Perform the ADC calibration.
@endverbatim
  * @{
  */

/**
  * @brief  Perform an ADC automatic self-calibration
  *         Calibration prerequisite: ADC must be disabled (execute this
  *         function before HAL_ADC_Start() or after HAL_ADC_Stop() ).
  * @note   Calibration factor can be read after calibration, using function
  *         HAL_ADC_GetValue() (value on 7 bits: from DR[6;0]).
  * @param  hadc: ADC handle
  * @retval HAL status
  */
HAL_StatusTypeDef HAL_ADCEx_Calibration_Start(ADC_HandleTypeDef* hadc)
{
  HAL_StatusTypeDef tmp_hal_status = HAL_OK;
  uint32_t tickstart=0;

  /* Check the parameters */
  assert_param(IS_ADC_ALL_INSTANCE(hadc->Instance));

  /* Process locked */
  __HAL_LOCK(hadc);

  /* Calibration prerequisite: ADC must be disabled. */
  if (ADC_IS_ENABLE(hadc) == RESET)
  {
    /* Set ADC state */
    ADC_STATE_CLR_SET(hadc->State,
                      HAL_ADC_STATE_REG_BUSY,
                      HAL_ADC_STATE_BUSY_INTERNAL);

    /* Start ADC calibration */
    hadc->Instance->CR |= ADC_CR_ADCAL;

    tickstart = HAL_GetTick();

    /* Wait for calibration completion */
    while(HAL_IS_BIT_SET(hadc->Instance->CR, ADC_CR_ADCAL))
    {
      if((HAL_GetTick() - tickstart) > ADC_CALIBRATION_TIMEOUT)
      {
        /* Update ADC state machine to error */
        ADC_STATE_CLR_SET(hadc->State,
                          HAL_ADC_STATE_BUSY_INTERNAL,
                          HAL_ADC_STATE_ERROR_INTERNAL);

        /* Process unlocked */
        __HAL_UNLOCK(hadc);

        return HAL_ERROR;
      }
    }

    /* Set ADC state */
    ADC_STATE_CLR_SET(hadc->State,
                      HAL_ADC_STATE_BUSY_INTERNAL,
                      HAL_ADC_STATE_READY);
  }
  else
  {
    /* Update ADC state machine to error */
    SET_BIT(hadc->State, HAL_ADC_STATE_ERROR_CONFIG);

    tmp_hal_status = HAL_ERROR;
  }

  /* Process unlocked */
  __HAL_UNLOCK(hadc);

  /* Return function status */
  return tmp_hal_status;
}

/**
  * @}
  */

/**
  * @}
  */

#endif /* HAL_ADC_MODULE_ENABLED */
/**
  * @}
  */

/**
  * @}
  */

/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/


text:
namespace nall {

struct mmapstream : stream {
  inline bool seekable() const { return true; }
  inline bool readable() const { return true; }
  inline bool writable() const { return pwritable; }
  inline bool randomaccess() const { return false; }

  inline unsigned size() const { return pmmap.size(); }
  inline unsigned offset() const { return poffset; }
  inline void seek(unsigned offset) const { poffset = offset; }

  inline uint8_t read() const { return pdata[poffset++]; }
  inline void write(uint8_t data) const { pdata[poffset++] = data; }

  inline uint8_t read(unsigned offset) const { return pdata[offset]; }
  inline void write(unsigned offset, uint8_t data) const { pdata[offset] = data; }

  inline mmapstream(const string &filename) {
    pmmap.open(filename, filemap::mode::readwrite);
    pwritable = pmmap.open();
    if(!pwritable) pmmap.open(filename, filemap::mode::read);
    pdata = pmmap.data(), poffset = 0;
  }

private:
  mutable filemap pmmap;
  mutable uint8_t *pdata;
  mutable unsigned pwritable, poffset;
};

}

#endif


text:
package com.jetbrains.edu.coursecreator.handlers;

import com.intellij.ide.IdeView;
import com.intellij.ide.util.DirectoryChooserUtil;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.refactoring.move.MoveCallback;
import com.intellij.refactoring.move.MoveHandlerDelegate;
import com.intellij.util.Function;
import com.jetbrains.edu.coursecreator.CCUtils;
import com.jetbrains.edu.coursecreator.ui.CCMoveStudyItemDialog;
import com.jetbrains.edu.learning.StudyTaskManager;
import com.jetbrains.edu.coursecreator.CCUtils;
import com.jetbrains.edu.learning.core.EduNames;
import com.jetbrains.edu.learning.core.EduUtils;
import com.jetbrains.edu.learning.courseFormat.Course;
import com.jetbrains.edu.learning.courseFormat.Lesson;
import com.jetbrains.edu.learning.courseFormat.StudyItem;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.util.Collections;

public class CCLessonMoveHandlerDelegate extends MoveHandlerDelegate {

  private static final Logger LOG = Logger.getInstance(CCLessonMoveHandlerDelegate.class);

  @Override
  public boolean canMove(DataContext dataContext) {
    if (CommonDataKeys.PSI_FILE.getData(dataContext) != null) {
      return false;
    }
    IdeView view = LangDataKeys.IDE_VIEW.getData(dataContext);
    if (view == null) {
      return false;
    }
    PsiDirectory sourceDirectory = DirectoryChooserUtil.getOrChooseDirectory(view);
    return CCUtils.isLessonDir(sourceDirectory);
  }

  @Override
  public boolean canMove(PsiElement[] elements, @Nullable PsiElement targetContainer) {
    if (elements.length > 0 && elements[0] instanceof PsiDirectory) {
      return CCUtils.isLessonDir(((PsiDirectory)elements[0]));
    }
    return false;
  }

  @Override
  public boolean isValidTarget(PsiElement psiElement, PsiElement[] sources) {
    return true;
  }

  @Override
  public void doMove(final Project project,
                     PsiElement[] elements,
                     @Nullable PsiElement targetContainer,
                     @Nullable MoveCallback callback) {
    if (targetContainer == null || !(targetContainer instanceof PsiDirectory)) {
      return;
    }
    final Course course = StudyTaskManager.getInstance(project).getCourse();
    if (course == null) {
      return;
    }
    final PsiDirectory sourceDirectory = (PsiDirectory)elements[0];
    final Lesson sourceLesson = course.getLesson(sourceDirectory.getName());
    final Lesson targetLesson = course.getLesson(((PsiDirectory)targetContainer).getName());
    if (targetLesson == null) {
      Messages.showInfoMessage("Lessons can be moved only to other lessons", "Incorrect Target For Move");
      return;
    }
    final CCMoveStudyItemDialog dialog = new CCMoveStudyItemDialog(project, EduNames.LESSON, targetLesson.getName());
    dialog.show();
    if (dialog.getExitCode() != DialogWrapper.OK_EXIT_CODE) {
      return;
    }
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      @Override
      public void run() {
        try {
          sourceDirectory.getVirtualFile().rename(this, "tmp");
        }
        catch (IOException e) {
          LOG.error(e);
        }
      }
    });
    final VirtualFile[] lessonDirs = project.getBaseDir().getChildren();
    final Function<VirtualFile, StudyItem> getStudyItem = new Function<VirtualFile, StudyItem>() {
      @Override
      public StudyItem fun(VirtualFile file) {
        return course.getLesson(file.getName());
      }
    };

    int sourceLessonIndex = sourceLesson.getIndex();
    sourceLesson.setIndex(-1);
    CCUtils.updateHigherElements(lessonDirs, getStudyItem, sourceLessonIndex, EduNames.LESSON, -1);

    final int newItemIndex = targetLesson.getIndex() + dialog.getIndexDelta();

    CCUtils.updateHigherElements(lessonDirs, getStudyItem,
                                 newItemIndex - 1, EduNames.LESSON, 1);

    sourceLesson.setIndex(newItemIndex);
    Collections.sort(course.getLessons(), EduUtils.INDEX_COMPARATOR);
    ApplicationManager.getApplication().runWriteAction(new Runnable() {
      @Override
      public void run() {
        try {
          sourceDirectory.getVirtualFile().rename(this, EduNames.LESSON + newItemIndex);
        }
        catch (IOException e) {
          LOG.error(e);
        }
      }
    });
  }

  @Override
  public boolean tryToMove(PsiElement element,
                           Project project,
                           DataContext dataContext,
                           @Nullable PsiReference reference,
                           Editor editor) {
    return CCUtils.isCourseCreator(project);
  }
}


text:
package com.amazonaws.services.redshift.model;

import javax.annotation.Generated;

/**
 * <p>
 * The cluster snapshot schedule state is not valid.
 * </p>
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class InvalidClusterSnapshotScheduleStateException extends com.amazonaws.services.redshift.model.AmazonRedshiftException {
    private static final long serialVersionUID = 1L;

    /**
     * Constructs a new InvalidClusterSnapshotScheduleStateException with the specified error message.
     *
     * @param message
     *        Describes the error encountered.
     */
    public InvalidClusterSnapshotScheduleStateException(String message) {
        super(message);
    }

}


text:
const fs = require('fs')
const fse = require('fs-extra')

const appPaths = require('../app-paths')
const { log, warn } = require('../helpers/logger')
const { spawnSync } = require('../helpers/spawn')
const nodePackager = require('../helpers/node-packager')
const { bundlerIsInstalled } = require('../electron/bundler')

const electronDeps = {
  'electron': '^9.0.0',
  'electron-debug': '^3.0.1',
  'electron-devtools-installer': '^3.0.0',
  'devtron': '^1.4.0'
}

class Mode {
  get isInstalled () {
    return fs.existsSync(appPaths.electronDir)
  }

  add () {
    if (this.isInstalled) {
      warn(`Electron support detected already. Aborting.`)
      return
    }

    const cmdParam = nodePackager === 'npm'
      ? ['install', '--save-dev']
      : ['add', '--dev']

    log(`Installing Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(Object.keys(electronDeps).map(dep => {
        return `${dep}@${electronDeps[dep]}`
      })),
      { cwd: appPaths.appDir, env: { ...process.env, NODE_ENV: 'development' } },
      () => warn('Failed to install Electron dependencies')
    )

    log(`Creating Electron source folder...`)
    fse.copySync(
      appPaths.resolve.cli('templates/electron'),
      appPaths.electronDir
    )

    log(`Electron support was added`)
  }

  remove () {
    if (!this.isInstalled) {
      warn(`No Electron support detected. Aborting.`)
      return
    }

    log(`Removing Electron source folder`)
    fse.removeSync(appPaths.electronDir)

    const cmdParam = nodePackager === 'npm'
      ? ['uninstall', '--save-dev']
      : ['remove']

    const deps = Object.keys(electronDeps)

    ;['packager', 'builder'].forEach(bundlerName => {
      if (bundlerIsInstalled(bundlerName)) {
        deps.push(`electron-${bundlerName}`)
      }
    })

    log(`Uninstalling Electron dependencies...`)
    spawnSync(
      nodePackager,
      cmdParam.concat(deps),
      { cwd: appPaths.appDir, env: { ...process.env, NODE_ENV: 'development' } },
      () => warn('Failed to uninstall Electron dependencies')
    )

    log(`Electron support was removed`)
  }
}

module.exports = Mode