text:
package com.sun.media.sound;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;

import javax.sound.midi.MidiMessage;
import javax.sound.midi.Patch;
import javax.sound.midi.ShortMessage;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;

/**
 * Software synthesizer main audio mixer.
 *
 * @author Karl Helgason
 */
public class SoftMainMixer {

    // A private class thats contains a ModelChannelMixer and it's private buffers.
    // This becomes necessary when we want to have separate delay buffers for each channel mixer.
    private class SoftChannelMixerContainer
    {
        ModelChannelMixer mixer;
        SoftAudioBuffer[] buffers;
    }

    public final static int CHANNEL_LEFT = 0;
    public final static int CHANNEL_RIGHT = 1;
    public final static int CHANNEL_MONO = 2;
    public final static int CHANNEL_DELAY_LEFT = 3;
    public final static int CHANNEL_DELAY_RIGHT = 4;
    public final static int CHANNEL_DELAY_MONO = 5;
    public final static int CHANNEL_EFFECT1 = 6;
    public final static int CHANNEL_EFFECT2 = 7;
    public final static int CHANNEL_DELAY_EFFECT1 = 8;
    public final static int CHANNEL_DELAY_EFFECT2 = 9;
    public final static int CHANNEL_LEFT_DRY = 10;
    public final static int CHANNEL_RIGHT_DRY = 11;
    public final static int CHANNEL_SCRATCH1 = 12;
    public final static int CHANNEL_SCRATCH2 = 13;
    protected boolean active_sensing_on = false;
    private long msec_last_activity = -1;
    private boolean pusher_silent = false;
    private int pusher_silent_count = 0;
    private long sample_pos = 0;
    protected boolean readfully = true;
    private Object control_mutex;
    private SoftSynthesizer synth;
    private float samplerate = 44100;
    private int nrofchannels = 2;
    private SoftVoice[] voicestatus = null;
    private SoftAudioBuffer[] buffers;
    private SoftReverb reverb;
    private SoftAudioProcessor chorus;
    private SoftAudioProcessor agc;
    private long msec_buffer_len = 0;
    private int buffer_len = 0;
    protected TreeMap<Long, Object> midimessages = new TreeMap<Long, Object>();
    private int delay_midievent = 0;
    private int max_delay_midievent = 0;
    double last_volume_left = 1.0;
    double last_volume_right = 1.0;
    private double[] co_master_balance = new double[1];
    private double[] co_master_volume = new double[1];
    private double[] co_master_coarse_tuning = new double[1];
    private double[] co_master_fine_tuning = new double[1];
    private AudioInputStream ais;
    private Set<SoftChannelMixerContainer> registeredMixers = null;
    private Set<ModelChannelMixer> stoppedMixers = null;
    private SoftChannelMixerContainer[] cur_registeredMixers = null;
    protected SoftControl co_master = new SoftControl() {

        double[] balance = co_master_balance;
        double[] volume = co_master_volume;
        double[] coarse_tuning = co_master_coarse_tuning;
        double[] fine_tuning = co_master_fine_tuning;

        public double[] get(int instance, String name) {
            if (name == null)
                return null;
            if (name.equals("balance"))
                return balance;
            if (name.equals("volume"))
                return volume;
            if (name.equals("coarse_tuning"))
                return coarse_tuning;
            if (name.equals("fine_tuning"))
                return fine_tuning;
            return null;
        }
    };

    private void processSystemExclusiveMessage(byte[] data) {
        synchronized (synth.control_mutex) {
            activity();

            // Universal Non-Real-Time SysEx
            if ((data[1] & 0xFF) == 0x7E) {
                int deviceID = data[2] & 0xFF;
                if (deviceID == 0x7F || deviceID == synth.getDeviceID()) {
                    int subid1 = data[3] & 0xFF;
                    int subid2;
                    switch (subid1) {
                    case 0x08:  // MIDI Tuning Standard
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01:  // BULK TUNING DUMP
                        {
                            // http://www.midi.org/about-midi/tuning.shtml
                            SoftTuning tuning = synth.getTuning(new Patch(0,
                                    data[5] & 0xFF));
                            tuning.load(data);
                            break;
                        }
                        case 0x04:  // KEY-BASED TUNING DUMP
                        case 0x05:  // SCALE/OCTAVE TUNING DUMP, 1 byte format
                        case 0x06:  // SCALE/OCTAVE TUNING DUMP, 2 byte format
                        case 0x07:  // SINGLE NOTE TUNING CHANGE (NON REAL-TIME)
                                    // (BANK)
                        {
                            // http://www.midi.org/about-midi/tuning_extens.shtml
                            SoftTuning tuning = synth.getTuning(new Patch(
                                    data[5] & 0xFF, data[6] & 0xFF));
                            tuning.load(data);
                            break;
                        }
                        case 0x08:  // scale/octave tuning 1-byte form (Non
                                    // Real-Time)
                        case 0x09:  // scale/octave tuning 2-byte form (Non
                                    // Real-Time)
                        {
                            // http://www.midi.org/about-midi/tuning-scale.shtml
                            SoftTuning tuning = new SoftTuning(data);
                            int channelmask = (data[5] & 0xFF) * 16384
                                    + (data[6] & 0xFF) * 128 + (data[7] & 0xFF);
                            SoftChannel[] channels = synth.channels;
                            for (int i = 0; i < channels.length; i++)
                                if ((channelmask & (1 << i)) != 0)
                                    channels[i].tuning = tuning;
                            break;
                        }
                        default:
                            break;
                        }
                        break;
                    case 0x09:  // General Midi Message
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01:  // General Midi 1 On
                            synth.setGeneralMidiMode(1);
                            reset();
                            break;
                        case 0x02:  // General Midi Off
                            synth.setGeneralMidiMode(0);
                            reset();
                            break;
                        case 0x03:  // General MidI Level 2 On
                            synth.setGeneralMidiMode(2);
                            reset();
                            break;
                        default:
                            break;
                        }
                        break;
                    case 0x0A: // DLS Message
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01:  // DLS On
                            if (synth.getGeneralMidiMode() == 0)
                                synth.setGeneralMidiMode(1);
                            synth.voice_allocation_mode = 1;
                            reset();
                            break;
                        case 0x02:  // DLS Off
                            synth.setGeneralMidiMode(0);
                            synth.voice_allocation_mode = 0;
                            reset();
                            break;
                        case 0x03:  // DLS Static Voice Allocation Off
                            synth.voice_allocation_mode = 0;
                            break;
                        case 0x04:  // DLS Static Voice Allocation On
                            synth.voice_allocation_mode = 1;
                            break;
                        default:
                            break;
                        }
                        break;

                    default:
                        break;
                    }
                }
            }

            // Universal Real-Time SysEx
            if ((data[1] & 0xFF) == 0x7F) {
                int deviceID = data[2] & 0xFF;
                if (deviceID == 0x7F || deviceID == synth.getDeviceID()) {
                    int subid1 = data[3] & 0xFF;
                    int subid2;
                    switch (subid1) {
                    case 0x04: // Device Control

                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01: // Master Volume
                        case 0x02: // Master Balane
                        case 0x03: // Master fine tuning
                        case 0x04: // Master coarse tuning
                            int val = (data[5] & 0x7F)
                                    + ((data[6] & 0x7F) * 128);
                            if (subid2 == 0x01)
                                setVolume(val);
                            else if (subid2 == 0x02)
                                setBalance(val);
                            else if (subid2 == 0x03)
                                setFineTuning(val);
                            else if (subid2 == 0x04)
                                setCoarseTuning(val);
                            break;
                        case 0x05: // Global Parameter Control
                            int ix = 5;
                            int slotPathLen = (data[ix++] & 0xFF);
                            int paramWidth = (data[ix++] & 0xFF);
                            int valueWidth = (data[ix++] & 0xFF);
                            int[] slotPath = new int[slotPathLen];
                            for (int i = 0; i < slotPathLen; i++) {
                                int msb = (data[ix++] & 0xFF);
                                int lsb = (data[ix++] & 0xFF);
                                slotPath[i] = msb * 128 + lsb;
                            }
                            int paramCount = (data.length - 1 - ix)
                                    / (paramWidth + valueWidth);
                            long[] params = new long[paramCount];
                            long[] values = new long[paramCount];
                            for (int i = 0; i < paramCount; i++) {
                                values[i] = 0;
                                for (int j = 0; j < paramWidth; j++)
                                    params[i] = params[i] * 128
                                            + (data[ix++] & 0xFF);
                                for (int j = 0; j < valueWidth; j++)
                                    values[i] = values[i] * 128
                                            + (data[ix++] & 0xFF);

                            }
                            globalParameterControlChange(slotPath, params, values);
                            break;
                        default:
                            break;
                        }
                        break;

                    case 0x08:  // MIDI Tuning Standard
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x02:  // SINGLE NOTE TUNING CHANGE (REAL-TIME)
                        {
                            // http://www.midi.org/about-midi/tuning.shtml
                            SoftTuning tuning = synth.getTuning(new Patch(0,
                                    data[5] & 0xFF));
                            tuning.load(data);
                            SoftVoice[] voices = synth.getVoices();
                            for (int i = 0; i < voices.length; i++)
                                if (voices[i].active)
                                    if (voices[i].tuning == tuning)
                                        voices[i].updateTuning(tuning);
                            break;
                        }
                        case 0x07:  // SINGLE NOTE TUNING CHANGE (REAL-TIME)
                                    // (BANK)
                        {
                            // http://www.midi.org/about-midi/tuning_extens.shtml
                            SoftTuning tuning = synth.getTuning(new Patch(
                                    data[5] & 0xFF, data[6] & 0xFF));
                            tuning.load(data);
                            SoftVoice[] voices = synth.getVoices();
                            for (int i = 0; i < voices.length; i++)
                                if (voices[i].active)
                                    if (voices[i].tuning == tuning)
                                        voices[i].updateTuning(tuning);
                            break;
                        }
                        case 0x08:  // scale/octave tuning 1-byte form
                                    //(Real-Time)
                        case 0x09:  // scale/octave tuning 2-byte form
                                    // (Real-Time)
                        {
                            // http://www.midi.org/about-midi/tuning-scale.shtml
                            SoftTuning tuning = new SoftTuning(data);
                            int channelmask = (data[5] & 0xFF) * 16384
                                    + (data[6] & 0xFF) * 128 + (data[7] & 0xFF);
                            SoftChannel[] channels = synth.channels;
                            for (int i = 0; i < channels.length; i++)
                                if ((channelmask & (1 << i)) != 0)
                                    channels[i].tuning = tuning;
                            SoftVoice[] voices = synth.getVoices();
                            for (int i = 0; i < voices.length; i++)
                                if (voices[i].active)
                                    if ((channelmask & (1 << (voices[i].channel))) != 0)
                                        voices[i].updateTuning(tuning);
                            break;
                        }
                        default:
                            break;
                        }
                        break;
                    case 0x09:  // Control Destination Settings
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01: // Channel Pressure
                        {
                            int[] destinations = new int[(data.length - 7) / 2];
                            int[] ranges = new int[(data.length - 7) / 2];
                            int ix = 0;
                            for (int j = 6; j < data.length - 1; j += 2) {
                                destinations[ix] = data[j] & 0xFF;
                                ranges[ix] = data[j + 1] & 0xFF;
                                ix++;
                            }
                            int channel = data[5] & 0xFF;
                            SoftChannel softchannel = synth.channels[channel];
                            softchannel.mapChannelPressureToDestination(
                                    destinations, ranges);
                            break;
                        }
                        case 0x02: // Poly Pressure
                        {
                            int[] destinations = new int[(data.length - 7) / 2];
                            int[] ranges = new int[(data.length - 7) / 2];
                            int ix = 0;
                            for (int j = 6; j < data.length - 1; j += 2) {
                                destinations[ix] = data[j] & 0xFF;
                                ranges[ix] = data[j + 1] & 0xFF;
                                ix++;
                            }
                            int channel = data[5] & 0xFF;
                            SoftChannel softchannel = synth.channels[channel];
                            softchannel.mapPolyPressureToDestination(
                                    destinations, ranges);
                            break;
                        }
                        case 0x03: // Control Change
                        {
                            int[] destinations = new int[(data.length - 7) / 2];
                            int[] ranges = new int[(data.length - 7) / 2];
                            int ix = 0;
                            for (int j = 7; j < data.length - 1; j += 2) {
                                destinations[ix] = data[j] & 0xFF;
                                ranges[ix] = data[j + 1] & 0xFF;
                                ix++;
                            }
                            int channel = data[5] & 0xFF;
                            SoftChannel softchannel = synth.channels[channel];
                            int control = data[6] & 0xFF;
                            softchannel.mapControlToDestination(control,
                                    destinations, ranges);
                            break;
                        }
                        default:
                            break;
                        }
                        break;

                    case 0x0A:  // Key Based Instrument Control
                    {
                        subid2 = data[4] & 0xFF;
                        switch (subid2) {
                        case 0x01: // Basic Message
                            int channel = data[5] & 0xFF;
                            int keynumber = data[6] & 0xFF;
                            SoftChannel softchannel = synth.channels[channel];
                            for (int j = 7; j < data.length - 1; j += 2) {
                                int controlnumber = data[j] & 0xFF;
                                int controlvalue = data[j + 1] & 0xFF;
                                softchannel.controlChangePerNote(keynumber,
                                        controlnumber, controlvalue);
                            }
                            break;
                        default:
                            break;
                        }
                        break;
                    }
                    default:
                        break;
                    }
                }
            }

        }
    }

    private void processMessages(long timeStamp) {
        Iterator<Entry<Long, Object>> iter = midimessages.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<Long, Object> entry = iter.next();
            if (entry.getKey() >= (timeStamp + msec_buffer_len))
                return;
            long msec_delay = entry.getKey() - timeStamp;
            delay_midievent = (int)(msec_delay * (samplerate / 1000000.0) + 0.5);
            if(delay_midievent > max_delay_midievent)
                delay_midievent = max_delay_midievent;
            if(delay_midievent < 0)
                delay_midievent = 0;
            processMessage(entry.getValue());
            iter.remove();
        }
        delay_midievent = 0;
    }

    protected void processAudioBuffers() {

        if(synth.weakstream != null && synth.weakstream.silent_samples != 0)
        {
            sample_pos += synth.weakstream.silent_samples;
            synth.weakstream.silent_samples = 0;
        }

        for (int i = 0; i < buffers.length; i++) {
            if(i != CHANNEL_DELAY_LEFT &&
                    i != CHANNEL_DELAY_RIGHT &&
                    i != CHANNEL_DELAY_MONO &&
                    i != CHANNEL_DELAY_EFFECT1 &&
                    i != CHANNEL_DELAY_EFFECT2)
                buffers[i].clear();
        }

        if(!buffers[CHANNEL_DELAY_LEFT].isSilent())
        {
            buffers[CHANNEL_LEFT].swap(buffers[CHANNEL_DELAY_LEFT]);
        }
        if(!buffers[CHANNEL_DELAY_RIGHT].isSilent())
        {
            buffers[CHANNEL_RIGHT].swap(buffers[CHANNEL_DELAY_RIGHT]);
        }
        if(!buffers[CHANNEL_DELAY_MONO].isSilent())
        {
            buffers[CHANNEL_MONO].swap(buffers[CHANNEL_DELAY_MONO]);
        }
        if(!buffers[CHANNEL_DELAY_EFFECT1].isSilent())
        {
            buffers[CHANNEL_EFFECT1].swap(buffers[CHANNEL_DELAY_EFFECT1]);
        }
        if(!buffers[CHANNEL_DELAY_EFFECT2].isSilent())
        {
            buffers[CHANNEL_EFFECT2].swap(buffers[CHANNEL_DELAY_EFFECT2]);
        }

        double volume_left;
        double volume_right;

        SoftChannelMixerContainer[] act_registeredMixers;

        // perform control logic
        synchronized (control_mutex) {

            long msec_pos = (long)(sample_pos * (1000000.0 / samplerate));

            processMessages(msec_pos);

            if (active_sensing_on) {
                // Active Sensing
                // if no message occurs for max 1000 ms
                // then do AllSoundOff on all channels
                if ((msec_pos - msec_last_activity) > 1000000) {
                    active_sensing_on = false;
                    for (SoftChannel c : synth.channels)
                        c.allSoundOff();
                }

            }

            for (int i = 0; i < voicestatus.length; i++)
                if (voicestatus[i].active)
                    voicestatus[i].processControlLogic();
            sample_pos += buffer_len;

            double volume = co_master_volume[0];
            volume_left = volume;
            volume_right = volume;

            double balance = co_master_balance[0];
            if (balance > 0.5)
                volume_left *= (1 - balance) * 2;
            else
                volume_right *= balance * 2;

            chorus.processControlLogic();
            reverb.processControlLogic();
            agc.processControlLogic();

            if (cur_registeredMixers == null) {
                if (registeredMixers != null) {
                    cur_registeredMixers =
                            new SoftChannelMixerContainer[registeredMixers.size()];
                    registeredMixers.toArray(cur_registeredMixers);
                }
            }

            act_registeredMixers = cur_registeredMixers;
            if (act_registeredMixers != null)
                if (act_registeredMixers.length == 0)
                    act_registeredMixers = null;

        }

        if (act_registeredMixers != null) {

            // Make backup of left,right,mono channels
            SoftAudioBuffer leftbak = buffers[CHANNEL_LEFT];
            SoftAudioBuffer rightbak = buffers[CHANNEL_RIGHT];
            SoftAudioBuffer monobak = buffers[CHANNEL_MONO];
            SoftAudioBuffer delayleftbak = buffers[CHANNEL_DELAY_LEFT];
            SoftAudioBuffer delayrightbak = buffers[CHANNEL_DELAY_RIGHT];
            SoftAudioBuffer delaymonobak = buffers[CHANNEL_DELAY_MONO];

            int bufferlen = buffers[CHANNEL_LEFT].getSize();

            float[][] cbuffer = new float[nrofchannels][];
            float[][] obuffer = new float[nrofchannels][];
            obuffer[0] = leftbak.array();
            if (nrofchannels != 1)
                obuffer[1] = rightbak.array();

            for (SoftChannelMixerContainer cmixer : act_registeredMixers) {

                // Reroute default left,right output
                // to channelmixer left,right input/output
                buffers[CHANNEL_LEFT] =  cmixer.buffers[CHANNEL_LEFT];
                buffers[CHANNEL_RIGHT] = cmixer.buffers[CHANNEL_RIGHT];
                buffers[CHANNEL_MONO] = cmixer.buffers[CHANNEL_MONO];
                buffers[CHANNEL_DELAY_LEFT] = cmixer.buffers[CHANNEL_DELAY_LEFT];
                buffers[CHANNEL_DELAY_RIGHT] = cmixer.buffers[CHANNEL_DELAY_RIGHT];
                buffers[CHANNEL_DELAY_MONO] = cmixer.buffers[CHANNEL_DELAY_MONO];

                buffers[CHANNEL_LEFT].clear();
                buffers[CHANNEL_RIGHT].clear();
                buffers[CHANNEL_MONO].clear();

                if(!buffers[CHANNEL_DELAY_LEFT].isSilent())
                {
                    buffers[CHANNEL_LEFT].swap(buffers[CHANNEL_DELAY_LEFT]);
                }
                if(!buffers[CHANNEL_DELAY_RIGHT].isSilent())
                {
                    buffers[CHANNEL_RIGHT].swap(buffers[CHANNEL_DELAY_RIGHT]);
                }
                if(!buffers[CHANNEL_DELAY_MONO].isSilent())
                {
                    buffers[CHANNEL_MONO].swap(buffers[CHANNEL_DELAY_MONO]);
                }

                cbuffer[0] = buffers[CHANNEL_LEFT].array();
                if (nrofchannels != 1)
                    cbuffer[1] = buffers[CHANNEL_RIGHT].array();

                boolean hasactivevoices = false;
                for (int i = 0; i < voicestatus.length; i++)
                    if (voicestatus[i].active)
                        if (voicestatus[i].channelmixer == cmixer.mixer) {
                            voicestatus[i].processAudioLogic(buffers);
                            hasactivevoices = true;
                        }

                if(!buffers[CHANNEL_MONO].isSilent())
                {
                    float[] mono = buffers[CHANNEL_MONO].array();
                    float[] left = buffers[CHANNEL_LEFT].array();
                    if (nrofchannels != 1) {
                        float[] right = buffers[CHANNEL_RIGHT].array();
                        for (int i = 0; i < bufferlen; i++) {
                            float v = mono[i];
                            left[i] += v;
                            right[i] += v;
                        }
                    }
                    else
                    {
                        for (int i = 0; i < bufferlen; i++) {
                            left[i] += mono[i];
                        }
                    }
                }

                if (!cmixer.mixer.process(cbuffer, 0, bufferlen)) {
                    synchronized (control_mutex) {
                        registeredMixers.remove(cmixer);
                        cur_registeredMixers = null;
                    }
                }

                for (int i = 0; i < cbuffer.length; i++) {
                    float[] cbuff = cbuffer[i];
                    float[] obuff = obuffer[i];
                    for (int j = 0; j < bufferlen; j++)
                        obuff[j] += cbuff[j];
                }

                if (!hasactivevoices) {
                    synchronized (control_mutex) {
                        if (stoppedMixers != null) {
                            if (stoppedMixers.contains(cmixer)) {
                                stoppedMixers.remove(cmixer);
                                cmixer.mixer.stop();
                            }
                        }
                    }
                }

            }

            buffers[CHANNEL_LEFT] = leftbak;
            buffers[CHANNEL_RIGHT] = rightbak;
            buffers[CHANNEL_MONO] = monobak;
            buffers[CHANNEL_DELAY_LEFT] = delayleftbak;
            buffers[CHANNEL_DELAY_RIGHT] = delayrightbak;
            buffers[CHANNEL_DELAY_MONO] = delaymonobak;

        }

        for (int i = 0; i < voicestatus.length; i++)
            if (voicestatus[i].active)
                if (voicestatus[i].channelmixer == null)
                    voicestatus[i].processAudioLogic(buffers);

        if(!buffers[CHANNEL_MONO].isSilent())
        {
            float[] mono = buffers[CHANNEL_MONO].array();
            float[] left = buffers[CHANNEL_LEFT].array();
            int bufferlen = buffers[CHANNEL_LEFT].getSize();
            if (nrofchannels != 1) {
                float[] right = buffers[CHANNEL_RIGHT].array();
                for (int i = 0; i < bufferlen; i++) {
                    float v = mono[i];
                    left[i] += v;
                    right[i] += v;
                }
            }
            else
            {
                for (int i = 0; i < bufferlen; i++) {
                    left[i] += mono[i];
                }
            }
        }

        // Run effects
        if (synth.chorus_on)
            chorus.processAudio();

        if (synth.reverb_on)
            reverb.processAudio();

        if (nrofchannels == 1)
            volume_left = (volume_left + volume_right) / 2;

        // Set Volume / Balance
        if (last_volume_left != volume_left || last_volume_right != volume_right) {
            float[] left = buffers[CHANNEL_LEFT].array();
            float[] right = buffers[CHANNEL_RIGHT].array();
            int bufferlen = buffers[CHANNEL_LEFT].getSize();

            float amp;
            float amp_delta;
            amp = (float)(last_volume_left * last_volume_left);
            amp_delta = (float)((volume_left * volume_left - amp) / bufferlen);
            for (int i = 0; i < bufferlen; i++) {
                amp += amp_delta;
                left[i] *= amp;
            }
            if (nrofchannels != 1) {
                amp = (float)(last_volume_right * last_volume_right);
                amp_delta = (float)((volume_right*volume_right - amp) / bufferlen);
                for (int i = 0; i < bufferlen; i++) {
                    amp += amp_delta;
                    right[i] *= volume_right;
                }
            }
            last_volume_left = volume_left;
            last_volume_right = volume_right;

        } else {
            if (volume_left != 1.0 || volume_right != 1.0) {
                float[] left = buffers[CHANNEL_LEFT].array();
                float[] right = buffers[CHANNEL_RIGHT].array();
                int bufferlen = buffers[CHANNEL_LEFT].getSize();
                float amp;
                amp = (float) (volume_left * volume_left);
                for (int i = 0; i < bufferlen; i++)
                    left[i] *= amp;
                if (nrofchannels != 1) {
                    amp = (float)(volume_right * volume_right);
                    for (int i = 0; i < bufferlen; i++)
                        right[i] *= amp;
                }

            }
        }

        if(buffers[CHANNEL_LEFT].isSilent()
            && buffers[CHANNEL_RIGHT].isSilent())
        {

            int midimessages_size;
            synchronized (control_mutex) {
                midimessages_size = midimessages.size();
            }

            if(midimessages_size == 0)
            {
                pusher_silent_count++;
                if(pusher_silent_count > 5)
                {
                    pusher_silent_count = 0;
                    synchronized (control_mutex) {
                        pusher_silent = true;
                        if(synth.weakstream != null)
                            synth.weakstream.setInputStream(null);
                    }
                }
            }
        }
        else
            pusher_silent_count = 0;

        if (synth.agc_on)
            agc.processAudio();

    }

    // Must only we called within control_mutex synchronization
    public void activity()
    {
        long silent_samples = 0;
        if(pusher_silent)
        {
            pusher_silent = false;
            if(synth.weakstream != null)
            {
                synth.weakstream.setInputStream(ais);
                silent_samples = synth.weakstream.silent_samples;
            }
        }
        msec_last_activity = (long)((sample_pos + silent_samples)
                * (1000000.0 / samplerate));
    }

    public void stopMixer(ModelChannelMixer mixer) {
        if (stoppedMixers == null)
            stoppedMixers = new HashSet<ModelChannelMixer>();
        stoppedMixers.add(mixer);
    }

    public void registerMixer(ModelChannelMixer mixer) {
        if (registeredMixers == null)
            registeredMixers = new HashSet<SoftChannelMixerContainer>();
        SoftChannelMixerContainer mixercontainer = new SoftChannelMixerContainer();
        mixercontainer.buffers = new SoftAudioBuffer[6];
        for (int i = 0; i < mixercontainer.buffers.length; i++) {
            mixercontainer.buffers[i] =
                new SoftAudioBuffer(buffer_len, synth.getFormat());
        }
        mixercontainer.mixer = mixer;
        registeredMixers.add(mixercontainer);
        cur_registeredMixers = null;
    }

    public SoftMainMixer(SoftSynthesizer synth) {
        this.synth = synth;

        sample_pos = 0;

        co_master_balance[0] = 0.5;
        co_master_volume[0] = 1;
        co_master_coarse_tuning[0] = 0.5;
        co_master_fine_tuning[0] = 0.5;

        msec_buffer_len = (long) (1000000.0 / synth.getControlRate());
        samplerate = synth.getFormat().getSampleRate();
        nrofchannels = synth.getFormat().getChannels();

        int buffersize = (int) (synth.getFormat().getSampleRate()
                                / synth.getControlRate());

        buffer_len = buffersize;

        max_delay_midievent = buffersize;

        control_mutex = synth.control_mutex;
        buffers = new SoftAudioBuffer[14];
        for (int i = 0; i < buffers.length; i++) {
            buffers[i] = new SoftAudioBuffer(buffersize, synth.getFormat());
        }
        voicestatus = synth.getVoices();

        reverb = new SoftReverb();
        chorus = new SoftChorus();
        agc = new SoftLimiter();

        float samplerate = synth.getFormat().getSampleRate();
        float controlrate = synth.getControlRate();
        reverb.init(samplerate, controlrate);
        chorus.init(samplerate, controlrate);
        agc.init(samplerate, controlrate);

        reverb.setLightMode(synth.reverb_light);

        reverb.setMixMode(true);
        chorus.setMixMode(true);
        agc.setMixMode(false);

        chorus.setInput(0, buffers[CHANNEL_EFFECT2]);
        chorus.setOutput(0, buffers[CHANNEL_LEFT]);
        if (nrofchannels != 1)
            chorus.setOutput(1, buffers[CHANNEL_RIGHT]);
        chorus.setOutput(2, buffers[CHANNEL_EFFECT1]);

        reverb.setInput(0, buffers[CHANNEL_EFFECT1]);
        reverb.setOutput(0, buffers[CHANNEL_LEFT]);
        if (nrofchannels != 1)
            reverb.setOutput(1, buffers[CHANNEL_RIGHT]);

        agc.setInput(0, buffers[CHANNEL_LEFT]);
        if (nrofchannels != 1)
            agc.setInput(1, buffers[CHANNEL_RIGHT]);
        agc.setOutput(0, buffers[CHANNEL_LEFT]);
        if (nrofchannels != 1)
            agc.setOutput(1, buffers[CHANNEL_RIGHT]);

        InputStream in = new InputStream() {

            private SoftAudioBuffer[] buffers = SoftMainMixer.this.buffers;
            private int nrofchannels
                    = SoftMainMixer.this.synth.getFormat().getChannels();
            private int buffersize = buffers[0].getSize();
            private byte[] bbuffer = new byte[buffersize
                    * (SoftMainMixer.this.synth.getFormat()
                        .getSampleSizeInBits() / 8)
                    * nrofchannels];
            private int bbuffer_pos = 0;
            private byte[] single = new byte[1];

            public void fillBuffer() {
                /*
                boolean pusher_silent2;
                synchronized (control_mutex) {
                    pusher_silent2 = pusher_silent;
                }
                if(!pusher_silent2)*/
                processAudioBuffers();
                for (int i = 0; i < nrofchannels; i++)
                    buffers[i].get(bbuffer, i);
                bbuffer_pos = 0;
            }

            public int read(byte[] b, int off, int len) {
                int bbuffer_len = bbuffer.length;
                int offlen = off + len;
                int orgoff = off;
                byte[] bbuffer = this.bbuffer;
                while (off < offlen) {
                    if (available() == 0)
                        fillBuffer();
                    else {
                        int bbuffer_pos = this.bbuffer_pos;
                        while (off < offlen && bbuffer_pos < bbuffer_len)
                            b[off++] = bbuffer[bbuffer_pos++];
                        this.bbuffer_pos = bbuffer_pos;
                        if (!readfully)
                            return off - orgoff;
                    }
                }
                return len;
            }

            public int read() throws IOException {
                int ret = read(single);
                if (ret == -1)
                    return -1;
                return single[0] & 0xFF;
            }

            public int available() {
                return bbuffer.length - bbuffer_pos;
            }

            public void close() {
                SoftMainMixer.this.synth.close();
            }
        };

        ais = new AudioInputStream(in, synth.getFormat(), AudioSystem.NOT_SPECIFIED);

    }

    public AudioInputStream getInputStream() {
        return ais;
    }

    public void reset() {

        SoftChannel[] channels = synth.channels;
        for (int i = 0; i < channels.length; i++) {
            channels[i].allSoundOff();
            channels[i].resetAllControllers(true);

            if (synth.getGeneralMidiMode() == 2) {
                if (i == 9)
                    channels[i].programChange(0, 0x78 * 128);
                else
                    channels[i].programChange(0, 0x79 * 128);
            } else
                channels[i].programChange(0, 0);
        }
        setVolume(0x7F * 128 + 0x7F);
        setBalance(0x40 * 128 + 0x00);
        setCoarseTuning(0x40 * 128 + 0x00);
        setFineTuning(0x40 * 128 + 0x00);
        // Reset Reverb
        globalParameterControlChange(
                new int[]{0x01 * 128 + 0x01}, new long[]{0}, new long[]{4});
        // Reset Chorus
        globalParameterControlChange(
                new int[]{0x01 * 128 + 0x02}, new long[]{0}, new long[]{2});
    }

    public void setVolume(int value) {
        synchronized (control_mutex) {
            co_master_volume[0] = value / 16384.0;
        }
    }

    public void setBalance(int value) {
        synchronized (control_mutex) {
            co_master_balance[0] = value / 16384.0;
        }
    }

    public void setFineTuning(int value) {
        synchronized (control_mutex) {
            co_master_fine_tuning[0] = value / 16384.0;
        }
    }

    public void setCoarseTuning(int value) {
        synchronized (control_mutex) {
            co_master_coarse_tuning[0] = value / 16384.0;
        }
    }

    public int getVolume() {
        synchronized (control_mutex) {
            return (int) (co_master_volume[0] * 16384.0);
        }
    }

    public int getBalance() {
        synchronized (control_mutex) {
            return (int) (co_master_balance[0] * 16384.0);
        }
    }

    public int getFineTuning() {
        synchronized (control_mutex) {
            return (int) (co_master_fine_tuning[0] * 16384.0);
        }
    }

    public int getCoarseTuning() {
        synchronized (control_mutex) {
            return (int) (co_master_coarse_tuning[0] * 16384.0);
        }
    }

    public void globalParameterControlChange(int[] slothpath, long[] params,
            long[] paramsvalue) {
        if (slothpath.length == 0)
            return;

        synchronized (control_mutex) {

            // slothpath: 01xx are reserved only for GM2

            if (slothpath[0] == 0x01 * 128 + 0x01) {
                for (int i = 0; i < paramsvalue.length; i++) {
                    reverb.globalParameterControlChange(slothpath, params[i],
                            paramsvalue[i]);
                }
            }
            if (slothpath[0] == 0x01 * 128 + 0x02) {
                for (int i = 0; i < paramsvalue.length; i++) {
                    chorus.globalParameterControlChange(slothpath, params[i],
                            paramsvalue[i]);
                }

            }

        }
    }

    public void processMessage(Object object) {
        if (object instanceof byte[])
            processMessage((byte[]) object);
        if (object instanceof MidiMessage)
            processMessage((MidiMessage)object);
    }

    public void processMessage(MidiMessage message) {
        if (message instanceof ShortMessage) {
            ShortMessage sms = (ShortMessage)message;
            processMessage(sms.getChannel(), sms.getCommand(),
                    sms.getData1(), sms.getData2());
            return;
        }
        processMessage(message.getMessage());
    }

    public void processMessage(byte[] data) {
        int status = 0;
        if (data.length > 0)
            status = data[0] & 0xFF;

        if (status == 0xF0) {
            processSystemExclusiveMessage(data);
            return;
        }

        int cmd = (status & 0xF0);
        int ch = (status & 0x0F);

        int data1;
        int data2;
        if (data.length > 1)
            data1 = data[1] & 0xFF;
        else
            data1 = 0;
        if (data.length > 2)
            data2 = data[2] & 0xFF;
        else
            data2 = 0;

        processMessage(ch, cmd, data1, data2);

    }

    public void processMessage(int ch, int cmd, int data1, int data2) {
        synchronized (synth.control_mutex) {
            activity();
        }

        if (cmd == 0xF0) {
            int status = cmd | ch;
            switch (status) {
            case ShortMessage.ACTIVE_SENSING:
                synchronized (synth.control_mutex) {
                    active_sensing_on = true;
                }
                break;
            default:
                break;
            }
            return;
        }

        SoftChannel[] channels = synth.channels;
        if (ch >= channels.length)
            return;
        SoftChannel softchannel = channels[ch];

        switch (cmd) {
        case ShortMessage.NOTE_ON:
            if(delay_midievent != 0)
                softchannel.noteOn(data1, data2, delay_midievent);
            else
                softchannel.noteOn(data1, data2);
            break;
        case ShortMessage.NOTE_OFF:
            softchannel.noteOff(data1, data2);
            break;
        case ShortMessage.POLY_PRESSURE:
            softchannel.setPolyPressure(data1, data2);
            break;
        case ShortMessage.CONTROL_CHANGE:
            softchannel.controlChange(data1, data2);
            break;
        case ShortMessage.PROGRAM_CHANGE:
            softchannel.programChange(data1);
            break;
        case ShortMessage.CHANNEL_PRESSURE:
            softchannel.setChannelPressure(data1);
            break;
        case ShortMessage.PITCH_BEND:
            softchannel.setPitchBend(data1 + data2 * 128);
            break;
        default:
            break;
        }

    }

    public long getMicrosecondPosition() {
        if(pusher_silent)
        {
            if(synth.weakstream != null)
            {
                return (long)((sample_pos  + synth.weakstream.silent_samples)
                        * (1000000.0 / samplerate));
            }
        }
        return (long)(sample_pos * (1000000.0 / samplerate));
    }

    public void close() {
    }
}


text:
#ifndef _NET_BATMAN_ADV_BITARRAY_H_
#define _NET_BATMAN_ADV_BITARRAY_H_

/* Returns 1 if the corresponding bit in the given seq_bits indicates true
 * and curr_seqno is within range of last_seqno. Otherwise returns 0.
 */
static inline int bat_test_bit(const unsigned long *seq_bits,
			       uint32_t last_seqno, uint32_t curr_seqno)
{
	int32_t diff;

	diff = last_seqno - curr_seqno;
	if (diff < 0 || diff >= TQ_LOCAL_WINDOW_SIZE)
		return 0;
	else
		return test_bit(diff, seq_bits) != 0;
}

/* turn corresponding bit on, so we can remember that we got the packet */
static inline void bat_set_bit(unsigned long *seq_bits, int32_t n)
{
	/* if too old, just drop it */
	if (n < 0 || n >= TQ_LOCAL_WINDOW_SIZE)
		return;

	set_bit(n, seq_bits); /* turn the position on */
}

/* receive and process one packet, returns 1 if received seq_num is considered
 * new, 0 if old  */
int bit_get_packet(void *priv, unsigned long *seq_bits,
		   int32_t seq_num_diff, int set_mark);

#endif /* _NET_BATMAN_ADV_BITARRAY_H_ */

redpajama_set_name: RedPajamaGithub


text:
package org.corpus_tools.annis.gui.querybuilder;

/**
 *
 * @author Thomas Krause {@literal <krauseto@hu-berlin.de>}
 */
public enum AQLOperator {
    DIRECT_PRECEDENCE(".", "direct precedence"), INDIRECT_PRECEDENCE(".*", "indirect precedence"), DIRECT_DOMINANCE(">",
            "direct dominance"), INDIRECT_DOMINANCE(">*", "indirect dominance"), IDENT_COVERAGE("_=_",
                    "identical coverage"), INCLUSION("_i_", "inclusion"), OVERLAP("_o_", "overlap"), LEFT_ALIGNED("_l_",
                            "left aligned"), RIGHT_ALIGNED("_r_", "right aligned"), POINTING("->LABEL",
                                    "labeled pointing relation"), INDIRECT_POINTING("->LABEL *",
                                            "indirect pointing relation"), LEFT_MOST_CHILD(">@l",
                                                    "left-most child"), RIGHT_MOST_CHILD(">@r",
                                                            "right-most child"), COMMON_PARENT("$",
                                                                    "common parent node"), COMMON_ANCESTOR("$*",
                                                                            "common ancestor node"), DIRECT_NEAR("^",
                                                                                "directly near"), INDIRECT_NEAR(
                                                                                "^*", "indirectly near");

    private final String description;
    private final String op;

    private AQLOperator(String op, String description) {
        this.description = description;
        this.op = op;
    }

    public String getDescription() {
        return description;
    }

    public String getOp() {
        return op;
    }

}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="Hypergolix is programmable cloud sync. It's like Dropbox, except instead of using it from the filesystem, you embed it directly in your applications.">
    <meta name="author" content="Muterra, Inc">
    <link rel="canonical" href="https://www.hypergolix.com/mailing-confirmed.html">

    <meta property="og:title"              content="Hypergolix" />
    <meta property="og:description"        content="Hypergolix is programmable cloud sync. It's like Dropbox, except instead of using it from the filesystem, you embed it directly in your applications." />
    <meta property="og:image"              content="https://www.hypergolix.com/img/og-image.jpg" />
    <meta property="og:url"                content="https://www.hypergolix.com/mailing-confirmed.html" />
    <meta property="og:type"               content="website" />

    <title>Hypergolix - programmable cloud sync</title>

    <link href="/css/bootstrap.min.css" rel="stylesheet">

    <link href="/css/standardize.css" rel="stylesheet">

    <link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">

    <link rel="apple-touch-icon" sizes="57x57" href="/apple-touch-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-touch-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-touch-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-touch-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-touch-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-touch-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <link rel="mask-icon" href="/safari-pinned-tab.svg" color="#000000">
    <meta name="msapplication-TileColor" content="#b31b00">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">

                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-main-collapse">

                </button>

                    use hypergolix

                        Demo

                        About

                        Team

                        Contact

                        Register

Hypergolix

Programmable cloud sync.

Success! Welcome aboard.

Copyright © 2017 Muterra, Inc.


text:
package com.alice.application.subscriber.model;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 *
 * fee  说明内容
 *
 * TODO 现有问题及需完善的方向
 *
 * author: Alice, 2017年10月22日-上午10:59:08, based on @version 1.0.0
 *
 */
@Entity(name="fee_info")
@Table(name="fee_info")
public class FeeInfo {
	int id;
	int theme;
	String feeName;
	int num;
	int direction;
	String fromName;
	String notice;
	Date createTime;

	@Id
	@GeneratedValue
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	@Column(name="feeName")
	public String getFeeName() {
		return feeName;
	}
	public void setFeeName(String feeName) {
		this.feeName = feeName;
	}
	@Column(name="num")
	public int getNum() {
		return num;
	}
	public void setNum(int num) {
		this.num = num;
	}
	@Column(name="direction")
	public int getDirection() {
		return direction;
	}
	public void setDirection(int direction) {
		this.direction = direction;
	}
	@Column(name="fromName")
	public String getFromName() {
		return fromName;
	}
	public void setFromName(String fromName) {
		this.fromName = fromName;
	}
	@Column(name="notice")
	public String getNotice() {
		return notice;
	}
	public void setNotice(String notice) {
		this.notice = notice;
	}
	@Column(name="theme")
	public int getTheme() {
		return theme;
	}
	public void setTheme(int theme) {
		this.theme = theme;
	}
	@Column(name="createTime")
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}

}


text:
package com.siyeh.ipp.fqnames;

import com.intellij.openapi.project.Project;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
import com.intellij.psi.codeStyle.JavaCodeStyleSettings;
import com.intellij.psi.util.PsiTreeUtil;
import com.siyeh.ipp.base.PsiElementPredicate;
import com.siyeh.ipp.psiutils.ImportUtils;

class FullyQualifiedNamePredicate implements PsiElementPredicate {

  public boolean satisfiedBy(PsiElement element) {
    if (!(element instanceof PsiJavaCodeReferenceElement)) {
      return false;
    }
    final PsiJavaCodeReferenceElement referenceElement = (PsiJavaCodeReferenceElement)element;
    if (!referenceElement.isQualified()) {
      return false;
    }
    final PsiElement parent = referenceElement.getParent();
    if (parent instanceof PsiMethodCallExpression || parent instanceof PsiAssignmentExpression || parent instanceof PsiVariable) {
      return false;
    }
    if (PsiTreeUtil.getParentOfType(element, PsiImportStatementBase.class, PsiPackageStatement.class, JavaCodeFragment.class) != null) {
      return false;
    }
    final PsiElement qualifier = referenceElement.getQualifier();
    if (!(qualifier instanceof PsiJavaCodeReferenceElement)) {
      return false;
    }
    final PsiJavaCodeReferenceElement qualifierReferenceElement = (PsiJavaCodeReferenceElement)qualifier;
    final PsiElement resolved = qualifierReferenceElement.resolve();
    if (!(resolved instanceof PsiJavaPackage)) {
      if (!(resolved instanceof PsiClass)) {
        return false;
      }
      final Project project = element.getProject();
      final JavaCodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(project).getCustomSettings(JavaCodeStyleSettings.class);
      if (!codeStyleSettings.INSERT_INNER_CLASS_IMPORTS) {
        return false;
      }
    }
    final PsiElement target = referenceElement.resolve();
    if (!(target instanceof PsiClass)) {
      return false;
    }
    final PsiClass aClass = (PsiClass)target;
    final String fqName = aClass.getQualifiedName();
    if (fqName == null) {
      return false;
    }
    return ImportUtils.nameCanBeImported(fqName, element);
  }
}


text:
package com.vl.samples.animation;

import android.app.Activity;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.widget.ImageView;

import com.vl.samples.R;

public class DrawableAnimationActivity extends Activity {
	AnimationDrawable rocketAnimation;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.drawable_anim);
			ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);
		  rocketImage.setBackgroundResource(R.drawable.rocket_thrust);
		  rocketAnimation = (AnimationDrawable) rocketImage.getBackground();
	}

	/**
	 * If we need to start our animation, we have wait upto user interaction.
	 * Because we must call the start() method on AnimationDrawable object to start animation.
	 * Ex: rocketAnimation.start();
	 * */
	/*@Override
	public boolean onTouchEvent(MotionEvent event) {
		  if (event.getAction() == MotionEvent.ACTION_DOWN) {
		    rocketAnimation.start();
		    return true;
		  }
		  return super.onTouchEvent(event);
	}*/

	/**The below method will be called when the activity get/loss focus.
	 * So we can start our animation in this by without user interaction.
	 * */
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if(hasFocus){
			rocketAnimation.start();
		}
		super.onWindowFocusChanged(hasFocus);
	}
}


text:
import os
import logging
import csv
import shutil
import glob
import pathlib

from datetime import datetime
from taca.utils.config import CONFIG
from taca.utils.transfer import RsyncAgent, RsyncError

logger = logging.getLogger(__name__)

class Nanopore(object):
    """General Nanopore run"""
    def __init__(self, run_dir):
        self.run_dir = run_dir
        self.run_id = os.path.basename(run_dir)
        self.summary_file = glob.glob(run_dir + '/final_summary*.txt')

    def is_not_transferred(self):
        """Return True if run id not in transfer.tsv, else False."""
        with open(self.transfer_log, 'r') as f:
            return self.run_id not in f.read()

    def transfer_run(self, transfer_details):
        """rsync dir to destination specified in config file."""
        destination = transfer_details.get('destination')
        rsync_opts = transfer_details.get('rsync_options')
        for k, v in rsync_opts.items():
            if v == 'None':
                rsync_opts[k] = None
        connection_details = transfer_details.get('analysis_server', None)
        logger.info('Transferring run {} to {}'.format(self.run_id,
                                                       connection_details['host'] if connection_details
                                                       else destination))
        if connection_details:
            transfer_object = RsyncAgent(self.run_dir,
                                        dest_path=destination,
                                        remote_host=connection_details.get('host'),
                                        remote_user=connection_details.get('user'),
                                        validate=False,
                                        opts=rsync_opts)
        else:
            transfer_object = RsyncAgent(self.run_dir,
                                        dest_path=destination,
                                        validate=False,
                                        opts=rsync_opts)
        try:
            transfer_object.transfer()
        except RsyncError:
            logger.warn('An error occurred while transferring {} to the '
                        'ananlysis server. Please check the logfiles'.format(self.run_dir))
            return False
        return True

    def update_transfer_log(self):
        """Update transfer log with run id and date."""
        try:
            with open(self.transfer_log, 'a') as f:
                tsv_writer = csv.writer(f, delimiter='\t')
                tsv_writer.writerow([self.run_id, str(datetime.now())])
                return True
        except IOError:
            logger.warn('Could not update the transfer logfile for run {}. '
                        'Please make sure it gets updated.'.format(self.run_id, self.transfer_log))
            return False

    def archive_run(self):
        """Move directory to nosync."""
        logger.info('Archiving run ' + self.run_id)
        top_dir = str(pathlib.Path(self.run_dir).parent.parent)  # Get the project folder to archive
        try:
            shutil.move(top_dir, self.archive_dir)
            logger.info('Successfully archived {}'.format(self.run_id))
            return True
        except shutil.Error:
            logger.warn('An error occurred when archiving {}. '
                        'Please check the logfile for more info.'.format(self.run_dir))
            return False


text:
"""Miscellenous
"""
import importlib
import itertools

_CHECK_OPT_MSG = "Option `{}` should be one of {}, but got '{}'."

def check_opt(name, value, valid):
    if value not in valid:
        raise ValueError(_CHECK_OPT_MSG.format(name, valid, value))

def find_library(x):
    """Check if library is installed.

    Parameters
    ----------
    x : str
        Name of library

    Returns
    -------
    bool
        If library is available.
    """
    return importlib.util.find_spec(x) is not None

def raise_cant_find_library_function(x, extra_msg=None):
    """Return function to flag up a missing necessary library.

    This is simplify the task of flagging optional dependencies only at the
    point at which they are needed, and not earlier.

    Parameters
    ----------
    x : str
        Name of library
    extra_msg : str, optional
        Make the function print this message as well, for additional
        information.

    Returns
    -------
    callable
        A mock function that when called, raises an import error specifying
        the required library.
    """

    def function_that_will_raise(*_, **__):
        error_msg = f"The library {x} is not installed. "
        if extra_msg is not None:
            error_msg += extra_msg
        raise ImportError(error_msg)

    return function_that_will_raise

FOUND_TQDM = find_library('tqdm')
if FOUND_TQDM:
    from tqdm import tqdm

    class continuous_progbar(tqdm):
        """A continuous version of tqdm, so that it can be updated with a float
        within some pre-given range, rather than a number of steps.

        Parameters
        ----------
        args : (stop) or (start, stop)
            Stopping point (and starting point if ``len(args) == 2``) of window
            within which to evaluate progress.
        total : int
            The number of steps to represent the continuous progress with.
        kwargs
            Supplied to ``tqdm.tqdm``
        """

        def __init__(self, *args, total=100, **kwargs):
            """
            """
            kwargs.setdefault('ascii', True)
            super(continuous_progbar, self).__init__(total=total,
                                                     unit="%", **kwargs)

            if len(args) == 2:
                self.start, self.stop = args
            else:
                self.start, self.stop = 0, args[0]

            self.range = self.stop - self.start
            self.step = 1

        def cupdate(self, x):
            """'Continuous' update of progress bar.

            Parameters
            ----------
            x : float
                Current position within the range ``[self.start, self.stop]``.
            """
            num_update = int(
                (self.total + 1) * (x - self.start) / self.range - self.step
            )
            if num_update > 0:
                self.update(num_update)
                self.step += num_update

    def progbar(*args, **kwargs):
        kwargs.setdefault('ascii', True)
        return tqdm(*args, **kwargs)

else:  # pragma: no cover
    extra_msg = "This is needed to show progress bars."
    progbar = raise_cant_find_library_function("tqdm", extra_msg)
    continuous_progbar = raise_cant_find_library_function("tqdm", extra_msg)

def deprecated(fn, old_name, new_name):

    def new_fn(*args, **kwargs):
        import warnings
        warnings.warn(f"The {old_name} function is deprecated in favor "
                      "of {new_name}", Warning)
        return fn(*args, **kwargs)

    return new_fn

def int2tup(x):
    return (x if isinstance(x, tuple) else
            (x,) if isinstance(x, int) else
            tuple(x))

def pairwise(iterable):
    """Iterate over each pair of neighbours in ``iterable``.
    """
    a, b = itertools.tee(iterable)
    next(b, None)
    return zip(a, b)

def three_line_multi_print(l1, l2, l3, max_width=None):
    if max_width is None:
        import shutil
        max_width, _ = shutil.get_terminal_size()

    if len(l2) <= max_width:
        print(l1)
        print(l2)
        print(l3)
    else:  # pragma: no cover
        max_width -= 10  # for ellipses and pad
        n_lines = (len(l2) - 1) // max_width + 1
        for i in range(n_lines):
            if i == 0:
                print("   ", l1[i * max_width:(i + 1) * max_width], "   ")
                print("   ", l2[i * max_width:(i + 1) * max_width], "...")
                print("   ", l3[i * max_width:(i + 1) * max_width], "   ")
                print(("{:^" + str(max_width) + "}").format("..."))
            elif i == n_lines - 1:
                print("   ", l1[i * max_width:(i + 1) * max_width])
                print("...", l2[i * max_width:(i + 1) * max_width])
                print("   ", l3[i * max_width:(i + 1) * max_width])
            else:
                print("   ", l1[i * max_width:(i + 1) * max_width], "   ")
                print("...", l2[i * max_width:(i + 1) * max_width], "...")
                print("   ", l3[i * max_width:(i + 1) * max_width], "   ")
                print(("{:^" + str(max_width) + "}").format("..."))

def functions_equal(fn1, fn2):
    """Check equality of the code in ``fn1`` and ``fn2``.
    """

    try:
        code1 = fn1.__code__.co_code
    except AttributeError:
        code1 = fn1.__func__.__code__.co_code

    try:
        code2 = fn2.__code__.co_code
    except AttributeError:
        code2 = fn2.__func__.__code__.co_code

    return code1 == code2

def save_to_disk(obj, fname, **dump_opts):
    """Save an object to disk using joblib.dump.
    """
    import joblib
    return joblib.dump(obj, fname, **dump_opts)

def load_from_disk(fname, **load_opts):
    """Load an object form disk using joblib.load.
    """
    import joblib
    return joblib.load(fname, **load_opts)

class Verbosify:  # pragma: no cover
    """Decorator for making functions print their inputs. Simply for
    illustrating a MPI example in the docs.
    """

    def __init__(self, fn, highlight=None, mpi=False):
        self.fn = fn
        self.highlight = highlight
        self.mpi = mpi

    def __call__(self, *args, **kwargs):
        if self.mpi:
            from mpi4py import MPI
            pre_msg = f"{MPI.COMM_WORLD.Get_rank()}: "
        else:
            pre_msg = ""

        if self.highlight is None:
            print(f"{pre_msg} args {args}, kwargs {kwargs}")
        else:
            print("{pre_msg}{self.highlight}={kwargs[self.highlight]}")
        return self.fn(*args, **kwargs)


text:
<?php

namespace RL\MainBundle\Entity\Repository;

/**
 * RL\MainBundle\Entity\Repository\SectionRepository
 *
 * @author Peter Vasilevsky <tuxoiduser@gmail.com> a.k.a. Tux-oid
 * @license BSDL
 */
class SectionRepository extends AbstractRepository
{

}


text:
namespace Accelerider.Windows.Modules.NetDisk.Constants
{
    public static class ConfigureKeys
    {
        public const string DownloadDirectory = "downloadDirectory";

        public const string NotDisplayDownloadDialog = "notDisplayDownloadDialog";
    }
}


text:
/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */

define( [ "core/eventmanager", "./header",
          "./unload-dialog", "crashreporter",
          "first-run", "./tray", "editor/ui-kit",
          "core/trackevent", "dialog/dialog",
          "util/dragndrop", "make-api",
          "./resizeHandler", "json!/api/butterconfig" ],
  function( EventManager, Header,
            UnloadDialog, CrashReporter,
            FirstRun, Tray, UIKitDummy,
            TrackEvent, Dialog,
            DragNDrop, Make,
            ResizeHandler, config ){

  var html = document.querySelector( "html" );
  var TRANSITION_DURATION = 500,
      BUTTER_CSS_FILE = "{css}/butter.ui." + html.dir + ".css";

  var __unwantedKeyPressElements = [
        "TEXTAREA",
        "INPUT",
        "VIDEO",
        "AUDIO"
      ],
      __disabledKeyRepeats = [
        32, // space key
        27, // esc key
        8   // del key
      ];

  var NUDGE_INCREMENT_SMALL = 0.25,
      NUDGE_INCREMENT_LARGE = 1;

  function UI( butter ){

    var _uiConfig = butter.config,
        _uiOptions = _uiConfig.value( "ui" ),
        _unloadDialog,
        _resizeHandler,
        _stageWrapper = document.querySelector( ".stage-wrapper" ),
        _this = this;

    // Top-level way to test our crash reporter.
    butter.simulateError = CrashReporter.simulateError;

    EventManager.extend( _this );

    this.contentStateLocked = false;

    this.tray = new Tray( butter );
    this.header = new Header( butter, _uiConfig );

    // Filled in by the editor module
    this.editor = null;

    if ( _uiOptions.enabled ) {
      if ( _uiOptions.onLeaveDialog ) {
        _unloadDialog = new UnloadDialog( butter );
        _this.unloadDialog = _unloadDialog;
      }
      document.body.classList.add( "butter-header-spacing" );
      document.body.classList.add( "butter-tray-spacing" );
    }

    _stageWrapper.addEventListener( "mousedown", function() {
      if( butter.selectedEvents.length ) {
        butter.deselectAllTrackEvents();
      }
    } );

    this.loadIcons = function( plugins ) {
      var path, img, div;

      plugins.forEach( function( plugin ) {
          path = plugin.icon;

          if ( !path ) {
            return;
          }

          img = new Image();
          img.id = plugin.type + "-icon";
          img.src = path;

          // We can't use "display: none", since that makes it
          // invisible, and thus not load.  Opera also requires
          // the image be in the DOM before it will load.
          div = document.createElement( "div" );
          div.className = "butter-image-preload";

          div.appendChild( img );
          document.body.appendChild( div );
      });
    };

    var make = new Make({
      apiURL: config.make_endpoint
    });

    function loadTutorials() {
      var tutorialUrl;

      if ( butter.project.publishUrl ) {
        tutorialUrl = butter.project.publishUrl;
      } else if ( butter.project.remixedFromUrl ) {
        tutorialUrl = butter.project.remixedFromUrl;
      }

      make.id( butter.project.makeid ).then( function( err, results ) {

        var urls = [],
            tutorials = [],
            tag = "";

        function addNext( url ) {
          if ( !url ) {
            if ( tutorials.length ) {
              butter.editor.openEditor( "tutorial-editor", {
                openData: tutorials
              });
            }
            return;
          }

          make.url( url ).then( function( err, results ) {
            var result = results[ 0 ];
            if ( !err ) {
              if ( result ) {
                tutorials.push({
                  url: result.url + "?details=hidden",
                  title: result.title || result.url
                });
              } else {
                tutorials.push({
                  url: url,
                  title: url
                });
              }
            }
            addNext( urls.pop() );
          });
        }

        if ( err || !results.length ) {
          return;
        }

        for ( var i = 0; i < results[ 0 ].tags.length; i++ ) {
          tag = results[ 0 ].tags[ i ];
          if ( tag.indexOf( "tutorial-" ) === 0 ) {
            urls.push( decodeURIComponent( tag.replace( "tutorial-", "" ) ) );
          }
        }

        addNext( urls.pop() );
      });
    }

    this.setEditor = function( editorAreaDOMRoot ) {
      _this.editor = editorAreaDOMRoot;
      document.body.appendChild( editorAreaDOMRoot );
    };

    this.load = function( onReady ) {
      var loadOptions = {
        type: "css",
        url: BUTTER_CSS_FILE
      };

      function loadUI() {
        butter.loader.load( [ loadOptions ], function() {
          // load things that need the css file in loadOptions
          // to be loaded before we do anything with it.
          _this.tray.attachToDOM();
          _this.header.attachToDOM();
          _this.loadIcons( _uiConfig.value( "plugin" ).plugins );

          // Spin-up the crash reporter
          CrashReporter.init( butter, _uiConfig );

          function firstRunInit() {
            butter.unlisten( "mediaready", firstRunInit );

            // Open the media-editor editor right after butter is finished starting up
            butter.editor.openEditor( "media-editor" );
            if ( butter.project.publishUrl ||
                 butter.project.remixedFromUrl ) {
              loadTutorials();
            }
            FirstRun.init();
          }

          butter.listen( "mediaready", firstRunInit );

          onReady();
        });
      }

      if ( _uiOptions.enabled ) {
        loadUI();
      }
      else {
        onReady();
      }
    };

    /**
     * Member: moveTrackEventLeft
     *
     * If possible, moves a TrackEvent to the left by a specified amount.
     *
     * @param {TrackEvent} trackEvent: TrackEvent to move
     * @param {Number} amount: Amount by which the event is to move.
     */
    function moveTrackEventLeft( trackEvent, amount ) {
      var currentPopcornOptions = trackEvent.popcornOptions,
          currentDuration = currentPopcornOptions.end - currentPopcornOptions.start,
          overlappingTrackEvent,
          popcornOptions;

      if ( currentPopcornOptions.start > amount ) {
        popcornOptions = {
          start: currentPopcornOptions.start - amount,
          end: currentPopcornOptions.end - amount
        };
      }
      else {
        popcornOptions = {
          start: 0,
          end: currentDuration
        };
      }

      // If an overlapping trackevent was found, position this trackevent such that its left side is snug against the right side
      // of the overlapping trackevent.
      overlappingTrackEvent = trackEvent.track.findOverlappingTrackEvent( popcornOptions.start, popcornOptions.end, trackEvent );

      if ( overlappingTrackEvent ) {
        popcornOptions.start = overlappingTrackEvent.popcornOptions.end;
        popcornOptions.end = popcornOptions.start + currentDuration;
      }

      trackEvent.update( popcornOptions );
    }

    /**
     * Member: shrinkTrackEvent
     *
     * If possible, shrinks a TrackEvent to the left by a specified amount.
     *
     * @param {TrackEvent} trackEvent: TrackEvent to move
     * @param {Number} amount: Amount by which the event is to shrink.
     */
    function shrinkTrackEvent( trackEvent, amount ) {
      var currentPopcornOptions = trackEvent.popcornOptions,
          popcornOptions;

      if ( currentPopcornOptions.end - currentPopcornOptions.start - amount >= TrackEvent.MINIMUM_TRACKEVENT_SIZE ) {
        popcornOptions = {
          end: currentPopcornOptions.end - amount
        };
      }
      else {
        popcornOptions = {
          end: currentPopcornOptions.start + TrackEvent.MINIMUM_TRACKEVENT_SIZE
        };
      }

      // No need to check for overlapping TrackEvents here, since you can't shrink your TrackEvent to overlap another. That's silly.

      trackEvent.update( popcornOptions );
    }

    /**
     * Member: moveTrackEventRight
     *
     * If possible, moves a TrackEvent to the right by a specified amount.
     *
     * @param {TrackEvent} trackEvent: TrackEvent to move
     * @param {Number} amount: Amount by which the event is to move.
     */
    function moveTrackEventRight( trackEvent, amount ) {
      var currentPopcornOptions = trackEvent.popcornOptions,
          currentMediaDuration = butter.currentMedia.duration,
          currentDuration = currentPopcornOptions.end - currentPopcornOptions.start,
          overlappingTrackEvent,
          popcornOptions;

      if ( currentPopcornOptions.end <= currentMediaDuration - amount ) {
        popcornOptions = {
          start: currentPopcornOptions.start + amount,
          end: currentPopcornOptions.end + amount
        };
      }
      else {
        popcornOptions = {
          start: currentMediaDuration - ( currentPopcornOptions.end - currentPopcornOptions.start ),
          end: currentMediaDuration
        };
      }

      overlappingTrackEvent = trackEvent.track.findOverlappingTrackEvent( popcornOptions.start, popcornOptions.end, trackEvent );

      // If an overlapping trackevent was found, position this trackevent such that its right side is snug against the left side
      // of the overlapping trackevent.
      if ( overlappingTrackEvent ) {
        popcornOptions.end = overlappingTrackEvent.popcornOptions.start;
        popcornOptions.start = popcornOptions.end - currentDuration;
      }
      trackEvent.update( popcornOptions );
    }

    /**
     * Member: growTrackEvent
     *
     * If possible, grows a TrackEvent to the by a specified amount.
     *
     * @param {TrackEvent} trackEvent: TrackEvent to grow is to shrink.
     */
    function growTrackEvent( trackEvent, amount ) {
      var currentPopcornOptions = trackEvent.popcornOptions,
          overlappingTrackEvent,
          popcornOptions;

      if ( currentPopcornOptions.end <= butter.currentMedia.duration - amount ) {
        popcornOptions = {
          end: currentPopcornOptions.end + amount
        };
      }
      else {
        popcornOptions = {
          end: butter.currentMedia.duration
        };
      }

      // If an overlapping trackevent was found, position this trackevent such that its left side is snug against the right side
      // of the overlapping trackevent.
      overlappingTrackEvent = trackEvent.track.findOverlappingTrackEvent( currentPopcornOptions.start, popcornOptions.end, trackEvent );

      if ( overlappingTrackEvent ) {
        popcornOptions.end = overlappingTrackEvent.popcornOptions.end;
      }

      trackEvent.update( popcornOptions );
    }

    Object.defineProperties( this, {
      enabled: {
        get: function() {
          return _uiOptions.enabled;
        }
      }
    });

    var orderedTrackEvents = butter.orderedTrackEvents = [],
        sortTrackEvents = function( a, b ) {
          return a.popcornOptions.start > b .popcornOptions.start;
        };

    butter.listen( "trackeventadded", function( e ) {
      var trackEvent = e.data;
      orderedTrackEvents.push( trackEvent );
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    butter.listen( "trackeventremoved", function( e ) {
      var trackEvent = e.data,
          index = orderedTrackEvents.indexOf( trackEvent );
      if( index > -1 ){
        orderedTrackEvents.splice( index, 1 );
      } // if
    }); // listen

    butter.listen( "trackeventupdated", function() {
      orderedTrackEvents.sort( sortTrackEvents );
    }); // listen

    var processKey = {
      32: function( e ) { // space key
        e.preventDefault();

        if( butter.currentMedia.ended ){
          butter.currentMedia.paused = false;
        }
        else{
          butter.currentMedia.paused = !butter.currentMedia.paused;
        }
      }, // space key

      // left key
      37: function( e ) {
        var amount = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL,

            // Sorted selected events are used here because they should be moved from right to left.
            // Otherwise, overlapping can occur instantly, producing unexpected results.
            selectedEvents = butter.sortedSelectedEvents,

            i, seLength;

        if( selectedEvents.length ) {
          e.preventDefault();
          if ( e.ctrlKey || e.metaKey ) {
            for( i = 0, seLength = selectedEvents.length; i < seLength; ++i ) {
              shrinkTrackEvent( selectedEvents[ i ], amount );
            }
          }
          else {
            for( i = selectedEvents.length - 1; i >= 0; --i ) {
              moveTrackEventLeft( selectedEvents[ i ], amount );
            }
          }
        }
        else {
          butter.currentTime -= amount;
        }
      },

      // up key
      38: function( e ) {
        var track,
            trackEvent,
            nextTrack,

            //copy this selectedEvents because it will change inside loop
            selectedEvents = butter.selectedEvents.slice();

        if ( selectedEvents.length ) {
          e.preventDefault();
        }

        for ( var i = 0, seLength = selectedEvents.length; i < seLength; i++ ) {
          trackEvent = selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = butter.currentMedia.getLastTrack( track );
          if ( nextTrack && !nextTrack.findOverlappingTrackEvent( trackEvent ) ) {
            track.removeTrackEvent( trackEvent, true );
            nextTrack.addTrackEvent( trackEvent );
          }
        }
      },

      // right key
      39: function( e ) {
        var amount = e.shiftKey ? NUDGE_INCREMENT_LARGE : NUDGE_INCREMENT_SMALL,

            // Sorted selected events are used here because they should be moved from right to left.
            // Otherwise, overlapping can occur instantly, producing unexpected results.
            selectedEvents = butter.sortedSelectedEvents,

            i, seLength;

        if( selectedEvents.length ) {
          e.preventDefault();
          if ( e.ctrlKey || e.metaKey ) {
            for( i = 0, seLength = selectedEvents.length; i < seLength; ++i ) {
              growTrackEvent( selectedEvents[ i ], amount );
            }
          }
          else {
            for( i = 0, seLength = selectedEvents.length; i < seLength; ++i ) {
              moveTrackEventRight( selectedEvents[ i ], amount );
            }
          }
        }
        else {
          butter.currentTime += amount;
        }
      },

      // down key
      40: function( e ) {
        var track,
            trackEvent,
            nextTrack,

            //copy this selectedEvents because it will change inside loop
            selectedEvents = butter.selectedEvents.slice();

        if ( selectedEvents.length ) {
          e.preventDefault();
        }

        for ( var i = 0, seLength = selectedEvents.length; i < seLength; i++ ) {
          trackEvent = selectedEvents[ i ];
          track = trackEvent.track;
          nextTrack = butter.currentMedia.getNextTrack( track );
          if ( nextTrack && !nextTrack.findOverlappingTrackEvent( trackEvent ) ) {
            track.removeTrackEvent( trackEvent, true );
            nextTrack.addTrackEvent( trackEvent );
          }
        }
      },

      27: function() { // esc key
        if ( !DragNDrop.isDragging ) {
          butter.deselectAllTrackEvents();
        }
      },

      8: function( e ) { // del key
        var selectedEvents = butter.selectedEvents.slice(),             // Copy selectedEvents array to circumvent it changing
                                                                        // if deletion actually occurs, while still taking
                                                                        // advantage of caching.
            selectedEvent,
            dialog,
            i, l = selectedEvents.length;

        e.preventDefault();

        if( selectedEvents.length ) {

          // If any event is being dragged or resized we don't want to
          // allow deletion.
          for( i = 0; i < l; i++ ) {
            if ( selectedEvents[ i ].uiInUse ) {
              return;
            }
          }

          // If we have one track event just delete it, otherwise display a warning dialog.
          if ( selectedEvents.length === 1 ) {
            selectedEvent = selectedEvents[ 0 ];
            selectedEvent.track.removeTrackEvent( selectedEvent );
            return;
          }

          // Delete the events with warning dialog.
          dialog = Dialog.spawn( "delete-track", {
            data: selectedEvents.length + " track events",
            events: {
              submit: function() {
                for( i = 0; i < l; i++ ) {
                  selectedEvent = selectedEvents[ i ];
                  selectedEvent.track.removeTrackEvent( selectedEvent );
                }
                dialog.close();
              },
              cancel: function() {
                dialog.close();
              }
            }
          });
          dialog.open();
        }
      },

      9: function( e ) { // tab key
        if( orderedTrackEvents.length && butter.selectedEvents.length <= 1 ){
          e.preventDefault();
          var index = 0,
              direction = e.shiftKey ? -1 : 1;
          if( orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] ) > -1 ){
            index = orderedTrackEvents.indexOf( butter.selectedEvents[ 0 ] );
            if( orderedTrackEvents[ index+direction ] ){
              index+=direction;
            } else if( !e.shiftKey ){
              index = 0;
            } else {
              index = orderedTrackEvents.length - 1;
            } // if
          } // if
          butter.deselectAllTrackEvents();
          orderedTrackEvents[ index ].selected = true;
        } // if
      }, // tab key

      67: function( e ) { // c key
        if ( e.ctrlKey || e.metaKey ) {
          butter.copyTrackEvents();
        }
      }, // c key

      86: function( e ) { // v key
        if ( e.ctrlKey || e.metaKey ) {
          butter.pasteTrackEvents();
        }
      }, // v key

      65: function( e ) {
        if ( e.ctrlKey || e.metaKey ) {
          e.preventDefault();

          var tracks = butter.currentMedia.tracks,
              i, k, trackEventLn, track,
              trackLn = tracks.length;

          for ( i = 0; i < trackLn; i++ ) {
            track = tracks[ i ];

            if ( track.trackEvents ) {
              trackEventLn = track.trackEvents.length;
            }

            for ( k = 0; k < trackEventLn; k++ ) {
              track.trackEvents[ k ].selected = true;
            }
          }
        }
      } // a key
    };

    function onKeyDown( e ){
      var key = e.which || e.keyCode,
          eTarget = e.target;
      // this allows backspace and del to do the same thing on windows and mac keyboards
      key = key === 46 ? 8 : key;
      if( processKey[ key ] && !eTarget.isContentEditable && __unwantedKeyPressElements.indexOf( eTarget.nodeName ) === -1 ){

        if ( __disabledKeyRepeats.indexOf( key ) > -1 ) {
          window.removeEventListener( "keydown", onKeyDown, false );
          window.addEventListener( "keyup", onKeyUp );
        }

        processKey[ key ]( e );
      } // if
    }

    function onKeyUp() {
      window.removeEventListener( "keyup", onKeyUp, false );
      window.addEventListener( "keydown", onKeyDown );
    }

    function unbindKeyDownListener() {
      window.removeEventListener( "keydown", onKeyDown, false );
    }

    function bindKeyDownListener() {
      window.addEventListener( "keydown", onKeyDown );
    }

    DragNDrop.listen( "dragstarted", unbindKeyDownListener );
    DragNDrop.listen( "dragstopped", bindKeyDownListener );
    DragNDrop.listen( "resizestarted", unbindKeyDownListener );
    DragNDrop.listen( "resizestopped", bindKeyDownListener );
    DragNDrop.listen( "sortstarted", unbindKeyDownListener );
    DragNDrop.listen( "sortstopped", bindKeyDownListener );

    this.TRANSITION_DURATION = TRANSITION_DURATION;

    butter.listen( "ready", function(){
      _resizeHandler = new ResizeHandler( { margin: 26, border: 15 } ),
      _resizeHandler.resize();
      window.addEventListener( "resize", _resizeHandler.resizee );
    });

    butter.listen( "mediaready", bindKeyDownListener );

    _this.dialogDir = butter.config.value( "dirs" ).dialogs || "";

    // This is an easter egg to open a UI kit editor. Hurrah
    _this.showUIKit = function() {
      butter.editor.openEditor( "ui-kit" );
    };

  } //UI

  UI.__moduleName = "ui";

  return UI;

});


text:
#ifndef __LOCCIONI_MODBUS_H
#define __LOCCIONI_MODBUS_H

#include "libohiboard.h"

/**
 * In this file you must define the MAP information:
 *     #define LOCCIONI_MODBUS_MAPSIZE NNN
 */
#include "board.h"

#define LOCCIONI_MODBUS_LIBRARY_VERSION     "1.3.0"
#define LOCCIONI_MODBUS_LIBRARY_VERSION_M   1
#define LOCCIONI_MODBUS_LIBRARY_VERSION_m   3
#define LOCCIONI_MODBUS_LIBRARY_VERSION_bug 0
#define LOCCIONI_MODBUS_LIBRARY_TIME        1522316846

/* The dma transfer is supported only for k12d5 and k64f12 uController */
// TODO: Insert in the preprocessor variables
//#define ENABLE_DMA_TRANSFER 1  //to improve velocity set to 1 and include DMA

#if ENABLE_DMA_TRANSFER
 #include "dma.h"
#endif

#define RX_BUFFER_LEN 300

typedef enum
{
    MODBUS_PHYSICALTYPE_RS232,
    MODBUS_PHYSICALTYPE_RS485
} Modbus_PhysicalType;

/**
 * Define receiver buffer type
 */
typedef union
{
    uint8_t raw[RX_BUFFER_LEN];

    struct
    {
	    uint8_t address;
	    uint8_t function;
	    uint8_t data[RX_BUFFER_LEN-2];
    }field;

} Modbus_RxBuffer;

/**
 * Define logical error type
 */
typedef enum
{
    MODBUS_LOGICERROR_NO_ERROR             = 0,
    MODBUS_LOGICERROR_ILLEGAL_FUNCTION     = 1,
    MODBUS_LOGICERROR_ILLEGAL_DATA_ADDRESS = 2,
    MODBUS_LOGICERROR_ILLEGAL_DATA_VALUE   = 3,
    MODBUS_LOGICERROR_NEG_ACK              = 7,
} Modbus_LogicError;

/**
 * Define transmission mode type
 */
typedef enum
{
    MODBUS_TRANSMISSIONMODE_RTU,
    MODBUS_TRANSMISSIONMODE_ASCII,
} Modbus_TransmissionMode;

/**
 * Define Modbus state type
 */
typedef enum
{
    MODBUS_STATE_IDLE,
    MODBUS_STATE_NEW_MESSAGE,
    MODBUS_STATE_IN_RECEPTION,
    MODBUS_STATE_PARITY_ERROR,
    MODBUS_STATE_SYNTAX_ERROR,
    MODBUS_STATE_CRC_ERROR
}Modbus_State;

/**
 * Define device type
 */
typedef enum
{
    MODBUS_DEVICETYPE_MASTER,
    MODBUS_DEVICETYPE_SLAVE,
}Modbus_DeviceType;

/**
 * Define serial configuration
 */
typedef enum
{
    MODBUS_SERIALCONFIG_1_8_1_ODD,  /**< 1 start, 8 data, Odd parity, 1 stop. */
} Modbus_SerialConfig;

/**
 * Define errors for modbus
 */
typedef enum
{
    MODBUS_ERRORS_NO_ERROR,
    MODBUS_ERRORS_NO_FREE_DEVICE,
    MODBUS_ERRORS_UART_OPEN,
    MODBUS_ERRORS_WRONG_LENGTH,
} Modbus_Errors;

/**
 * Define all the parameters to configure Modbus.
 */
typedef struct _Modbus_Config
{
    Modbus_DeviceType type;               /**< Select the type of the device. */

    Modbus_TransmissionMode txMode;            /**< The type of transmission. */

    Ftm_DeviceHandle counter;   /**< Timer device handler for delay counting. */

    Uart_DeviceHandle com;                           /**< UART device handle. */
    Uart_RxPins rx;
    Uart_TxPins	tx;
    Gpio_Pins   de;
    Modbus_PhysicalType phy;            /**< Physical type for communication. */
    uint32_t baudrate;                /**< Baudrate for serial communication. */
    Modbus_SerialConfig comConfig;

    uint8_t id;                                  /**< Id of the current node. */

#if ENABLE_DMA_TRANSFER
    Dma_Channel dmaCh;
    Dma_DeviceHandle dma;
#endif
} Modbus_Config;

typedef struct _Modbus_Device
{
    Ftm_DeviceHandle counter;   /**< Timer device handler for delay counting. */

    Uart_DeviceHandle com;                           /**< UART device handle. */
    Gpio_Pins de;

    uint8_t id;                                  /**< Id of the current node. */

    Modbus_State state;
    Modbus_LogicError logicError;
    uint8_t errorParity;

    uint8_t position;

    Modbus_RxBuffer buffer;
    uint8_t length;
    uint8_t timeout;

    uint8_t status;
    uint16_t map[LOCCIONI_MODBUS_MAPSIZE];

    Modbus_PhysicalType phy;            /**< Physical type for communication. */

#if ENABLE_DMA_TRANSFER

    Dma_Config dmaConfig;
    Dma_DeviceHandle dma;

#endif

} Modbus_Device;

Modbus_Errors Modbus_init (Modbus_Device *dev, Modbus_Config *config);
void Modbus_listener (Modbus_Device *dev);

uint16_t Modbus_get (Modbus_Device *dev, uint16_t position);
void Modbus_set (Modbus_Device *dev, uint16_t position, uint16_t value);
bool Modbus_getBit(Modbus_Device *dev, uint16_t position);
void Modbus_setBit(Modbus_Device *dev, uint16_t position, bool value);

Modbus_Errors Modbus_clearMemoryArea (Modbus_Device* dev, uint16_t start, uint16_t length);

#endif /* __LOCCIONI_MODBUS_H */


text:
'use strict';

const { register: prometheusRegister } = require('prom-client');
const Controller = require('./controller');

class BackstageController extends Controller {
    constructor(config) {
        super();

        if (config.serverMetrics) {
            this.get('/prometheus', (req, res) => {
                res.set('Content-Type', prometheusRegister.contentType);
                res.end(prometheusRegister.metrics());
            });
        }
    }
}

module.exports = BackstageController;


text:
from setuptools import setup
requires = []
setup(
        name='hxsd',
        version='0.1.0',
        description="Simple Service discovering library",
        author="Ross Delinger",
        author_email="rossdylan@csh.rit.edu",
        url='https://github.com/rossdylan/Helixode-SD',
        packages=['hxsd'],
        install_requires=requires,
        entry_points="""
        [console_scripts]
        hxsd = hxsd:main
        """
    )


text:
using namespace ps;
using namespace ps::dir;
using namespace ps::opengl;
using namespace ps::utils;

void ReleaseShader(U32 shader) {
    if(glIsProgram(shader))
        glDeleteProgram(shader);
}

ShaderManager::ShaderManager() {

}

ShaderManager::~ShaderManager() {
    ShaderManagerParent::cleanup();
}

bool ShaderManager::add(const char* name, const char* vShaderCode, const char* fShaderCode, const char* gShaderCode) {
    GLShader* aShader = new GLShader(vShaderCode, fShaderCode, gShaderCode);
    if(aShader->isCompiled()) {
        if(ShaderManagerParent::add(aShader, name)) {
            if(gShaderCode != NULL)
                vloginfo("Added Vertex-Geometry-Fragment Shader from inline code. Name: %s.", name);
            else
                vloginfo("Added Vertex-Fragment Shader from inline code. Name: %s.", name);
            return true;
        }
        else {
            vlogerror("Unable to add inline shader named: %s", name);
            return false;
        }
    }
    else
    {
        SAFE_DELETE(aShader);
        return false;
    }
}

bool ShaderManager::addFromFile(const char* name,
                                const AnsiStr& strVShaderFP,
                                const AnsiStr& strFShaderFP) {
    AnsiStr strTitle = (name != NULL) ? AnsiStr(name) : ExtractFileTitleOnly(strVShaderFP);

    GLShader* aShader = new GLShader();
    if(aShader->compileFromFile(strVShaderFP, strFShaderFP)) {
        if(ShaderManagerParent::add(aShader, strTitle.cptr())) {
            AnsiStr strArg = TheEventLogger::Instance().shortenPathBasedOnRoot(strVShaderFP);
            vloginfo("Added Vertex-Fragment Shader from file: %s, Name: %s.", strArg.cptr(), name);
            return true;
        }
        else {
            SAFE_DELETE(aShader);
            vlogerror("Unable to add Vertex-Fragment Shader from file. Name: %s", name);
            return false;
        }
    }
    else {
        SAFE_DELETE(aShader);
        return false;
    }
}

bool ShaderManager::addFromFile(const char* name,
                                const AnsiStr& strVShaderFP,
                                const AnsiStr& strFShaderFP,
                                const AnsiStr& strGShaderFP) {

    AnsiStr strTitle = (name != NULL) ? AnsiStr(name) : ExtractFileTitleOnly(strVShaderFP);

    GLShader* aShader = new GLShader();
    if(aShader->compileFromFile(strVShaderFP, strFShaderFP, strGShaderFP)) {
        if(ShaderManagerParent::add(aShader, strTitle.cptr())) {
            AnsiStr strArg = TheEventLogger::Instance().shortenPathBasedOnRoot(strVShaderFP);
            vloginfo("Added Vertex-Geometry-Fragment Shader from file: %s, Name: %s.", strArg.cptr(), name);
            return true;
        }
        else {
            SAFE_DELETE(aShader);
            vlogerror("Unable to add Vertex-Geometry-Fragment Shader from file. Name: %s", name);
            return false;

        }
    }
    else {
        SAFE_DELETE(aShader);
        return false;
    }
}

int ShaderManager::addFromFolder(const char* chrShadersPath)
{
    int count = 0;
    vector<AnsiStr> vFiles;
    ListFilesInDir(vFiles, chrShadersPath, "vsh", true);

    for(int i=0; i<(int)vFiles.size(); i++) {
        AnsiStr strVShaderFP = vFiles[i];
        AnsiStr strFShaderFP = ChangeFileExt(strVShaderFP, AnsiStr(".fsh"));
        AnsiStr strGShaderFP = ChangeFileExt(strVShaderFP, AnsiStr(".gsh"));
        AnsiStr strTitle = ExtractFileTitleOnly(strVShaderFP);

        if(FileExists(strGShaderFP)) {
            if(addFromFile(strTitle.cptr(), strVShaderFP, strFShaderFP, strGShaderFP)) {
                count++;
            }
        }
        else {
            if(addFromFile(strTitle.cptr(), strVShaderFP, strFShaderFP)) {
                count++;
            }
        }
    }

    return count;
}


text:
package org.lwjgl.system;

import org.lwjgl.BufferUtils;
import org.testng.annotations.Test;

import java.nio.*;

import static org.lwjgl.system.MemoryUtil.*;
import static org.testng.Assert.*;

@Test
public class MemoryUtilTest {

	public void testMemSet() {
		ByteBuffer buffer = BufferUtils.createByteBuffer(32);
		for ( int i = 0; i < buffer.capacity(); i++ )
			buffer.put(i, (byte)i);

		memSet(memAddress(buffer), 0x7F, buffer.capacity());

		for ( int i = 0; i < buffer.capacity(); i++ )
			assertEquals(buffer.get(i), 0x7F);
	}

	public void testMemSet2() {
		for ( int i = 0; i < 16; i++ ) {
			for ( int j = 0; j <= (16 - i); j++ ) {
				long ref = nmemCalloc(1, 16);
				long mem = nmemCalloc(1, 16);

				// test misaligned memsets
				memSetReference(ref + i, (byte)0xFF, j);
				memSet(mem + i, (byte)0xFF, j);

				for ( int k = 0; k < 16; k++ ) {
					assertEquals(memGetByte(mem + k), memGetByte(ref + k));
				}

				nmemFree(mem);
				nmemFree(ref);
			}
		}
	}

	private static void memSetReference(long m, byte value, int bytes) {
		for ( int i = 0; i < bytes; i++ ) {
			memPutByte(m + i, value);
		}
	}

	public void testMemCopy() {
		ByteBuffer src = BufferUtils.createByteBuffer(32);
		ByteBuffer dst = BufferUtils.createByteBuffer(32);

		for ( int i = 0; i < src.capacity(); i++ )
			src.put(i, (byte)i);

		memCopy(memAddress(src), memAddress(dst), src.capacity());

		for ( int i = 0; i < src.capacity(); i++ )
			assertEquals(src.get(i), dst.get(i));
	}

	public void testJNINewBuffer() {
		ByteBuffer buffer = BufferUtils.createByteBuffer(32);
		for ( int i = 0; i < buffer.capacity(); i++ )
			buffer.put(i, (byte)i);

		long address = MemoryAccess.getDirectBufferAddress(buffer);
		assertTrue(address != NULL);

		ByteBuffer view = MemoryAccess.newDirectByteBuffer(address + 8, 16);
		assertEquals(view.order(), ByteOrder.BIG_ENDIAN);
		for ( int i = 0; i < view.capacity(); i++ )
			assertEquals(view.get(i), buffer.get(i + 8));
	}

	public void testAddress() {
		ByteBuffer buffer = BufferUtils.createByteBuffer(32);
		for ( int i = 0; i < buffer.capacity(); i++ )
			buffer.put(i, (byte)i);

		long address = memAddress(buffer);
		assertTrue(address != NULL);

		buffer.position(8);
		buffer.limit(8 + 16);

		FloatBuffer floatView = memSlice(buffer).asFloatBuffer();

		assertEquals(address + 8, memAddress(floatView));
	}

	public void testDirectAccess() {
		ByteBuffer buffer = BufferUtils.createByteBuffer(40);
		long address = memAddress(buffer);

		for ( int i = 0; i < buffer.capacity(); i++ )
			buffer.put(i, (byte)i);

		for ( int i = 0; i < buffer.capacity(); i++ )
			assertEquals(memGetByte(address + i), buffer.get(i));

		for ( int i = 0; i < buffer.capacity(); i++ )
			memPutByte(address + i, (byte)-i);

		for ( int i = 0; i < buffer.capacity(); i++ )
			assertEquals(-i, buffer.get(i));

		memPutAddress(address, address);
		memPutDouble(address + 8, Math.PI);
		memPutLong(address + 16, Integer.MAX_VALUE * 2L);
		memPutFloat(address + 24, (float)Math.PI);
		memPutInt(address + 28, Short.MAX_VALUE * 2);
		memPutShort(address + 32, (short)(Byte.MAX_VALUE * 2));
		memPutByte(address + 34, (byte)127);

		assertEquals(memGetAddress(address), address);
		assertEquals(memGetDouble(address + 8), Math.PI);
		assertEquals(memGetLong(address + 16), Integer.MAX_VALUE * 2L);
		assertEquals(memGetFloat(address + 24), (float)Math.PI);
		assertEquals(memGetInt(address + 28), Short.MAX_VALUE * 2);
		assertEquals(memGetShort(address + 32), (short)(Byte.MAX_VALUE * 2));
		assertEquals(memGetByte(address + 34), (byte)127);
	}

	public void testNewBuffer() {
		ByteBuffer buffer = BufferUtils.createByteBuffer(32);
		for ( int i = 0; i < buffer.capacity(); i++ )
			buffer.put(i, (byte)i);

		long address = memAddress(buffer);
		assertTrue(address != NULL);

		ByteBuffer view = memByteBuffer(address + 8, 16);
		assertEquals(view.order(), ByteOrder.nativeOrder());
		for ( int i = 0; i < view.capacity(); i++ )
			assertEquals(view.get(i), buffer.get(i + 8));

		ShortBuffer sb = memShortBuffer(address, 16);
		assertEquals(sb.capacity(), 16);
		for ( int i = 0; i < sb.capacity(); i++ )
			assertEquals(buffer.getShort(i << 1), sb.get(i));

		IntBuffer ib = memIntBuffer(address, 8);
		assertEquals(ib.capacity(), 8);
		for ( int i = 0; i < ib.capacity(); i++ )
			assertEquals(buffer.getInt(i << 2), ib.get(i));

		LongBuffer lb = memLongBuffer(address, 4);
		assertEquals(lb.capacity(), 4);
		for ( int i = 0; i < lb.capacity(); i++ )
			assertEquals(buffer.getLong(i << 3), lb.get(i));

		FloatBuffer fb = memFloatBuffer(address, 8);
		assertEquals(fb.capacity(), 8);
		for ( int i = 0; i < fb.capacity(); i++ )
			assertEquals(buffer.getFloat(i << 2), fb.get(i));

		DoubleBuffer db = memDoubleBuffer(address, 4);
		assertEquals(db.capacity(), 4);
		for ( int i = 0; i < db.capacity(); i++ )
			assertEquals(buffer.getDouble(i << 3), db.get(i));
	}

}