text:
#include "mcp23s17.h"

#if defined(TESTING)
  #include "test/MOCK_wiring.h"
#elif defined(ARDUINO) && (ARDUINO <= 100)
  #include "Arduino.h"
#elif defined(SPARK)
  #include "application.h"
#else
  #include "WProgram.h"
#endif

mcp23s17::mcp23s17 (
    const HardwareAddress hw_addr_
) :
    _SPI_BUS_ADDRESS(SPI_BASE_ADDRESS | (static_cast<uint8_t>(hw_addr_) << 1)),
    _control_register{ 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
    _control_register_address{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 },
    _interrupt_service_routines{ nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }
{
    ::SPI.begin();

    //TODO: Load cache from chip registers (requires special handling if IOCON:HAEN is unset, or IOCON:BANK is set), or use a capture a reset pin so the chip can be put in a known state.

    // Set IOCON:HAEN bit
    _control_register[static_cast<uint8_t>(mcp23s17::ControlRegister::IOCONA)] |= static_cast<uint8_t>(IOConfigurationRegister::HAEN);

    ::digitalWrite(SS, LOW);
    ::SPI.transfer(SPI_BASE_ADDRESS);
    ::SPI.transfer(static_cast<uint8_t>(ControlRegister::IOCONA));
    ::SPI.transfer(static_cast<uint8_t>(IOConfigurationRegister::HAEN));
    ::digitalWrite(SS, HIGH);

    return;
}

void
mcp23s17::attachInterrupt (
    const uint8_t pin_,
    const isr_t interrupt_service_routine_,
    const InterruptMode mode_
) {
    uint16_t interrupt_control_cache(0x0000);
    uint16_t interrupt_enable_cache(0x0000);

    //if ( pin_ >= PIN_COUNT ) { return; }
    //if ( !interrupt_service_routine_ ) { return; }
    _interrupt_service_routines[pin_] = interrupt_service_routine_;

    // Check enable cache for existing data
    interrupt_enable_cache = _control_register[static_cast<uint8_t>(ControlRegister::GPINTENA)];
    interrupt_enable_cache |= (_control_register[static_cast<uint8_t>(ControlRegister::GPINTENB)] << 8);
    interrupt_enable_cache |= (1 << pin_);
    _control_register[static_cast<uint8_t>(ControlRegister::GPINTENA)] = interrupt_enable_cache;
    _control_register[static_cast<uint8_t>(ControlRegister::GPINTENB)] = (interrupt_enable_cache >> 8);

    // Check control cache for existing data
    interrupt_control_cache = _control_register[static_cast<uint8_t>(ControlRegister::INTCONA)];
    interrupt_control_cache |= (_control_register[static_cast<uint8_t>(ControlRegister::INTCONB)] << 8);
    if ( InterruptMode::CHANGE != mode_ ) {
        interrupt_control_cache |= (1 << pin_);
    } else {
        interrupt_control_cache &= ~(1 << pin_);
    }
    _control_register[static_cast<uint8_t>(ControlRegister::INTCONA)] = interrupt_control_cache;
    _control_register[static_cast<uint8_t>(ControlRegister::INTCONB)] = (interrupt_control_cache >> 8);

    // Three bytes are required to update a single register. Therefore, if a comparison-based interrupt is requested, then both ports of all three registers are written at once to optimize the transfer by one byte. Otherwise, if a change-based interrupt is requested, then it is more efficient to write two transactions to the to the specific ports and registers.
    ::digitalWrite(SS, LOW);
    ::SPI.transfer(_SPI_BUS_ADDRESS | static_cast<uint8_t>(RegisterTransaction::WRITE));
    ::SPI.transfer(static_cast<uint8_t>(ControlRegister::GPINTENA));
    ::SPI.transfer(interrupt_enable_cache);  // GPINTENA
    ::SPI.transfer(interrupt_enable_cache >> 8);  // GPINTENB
    if ( InterruptMode::HIGH == mode_ ) {
        ::SPI.transfer(1 << pin_);  // DEFVALA
        ::SPI.transfer(1 << (pin_ % 8));  // DEFVALB
        ::SPI.transfer(interrupt_control_cache);  // INTCONA
        ::SPI.transfer(interrupt_control_cache >> 8);  // INTCONB
    } else {
        ::SPI.transfer(0x00);  // DEFVALA
        ::SPI.transfer(0x00);  // DEFVALB
        if ( InterruptMode::CHANGE == mode_ ) {
            ::SPI.transfer(interrupt_control_cache);  // INTCONA
            ::SPI.transfer(interrupt_control_cache >> 8);  // INTCONB
        } else {
            ::SPI.transfer(interrupt_control_cache);  // INTCONA
            ::SPI.transfer(interrupt_control_cache >> 8);  // INTCONB
        }
    }
    ::digitalWrite(SS, HIGH);
}

mcp23s17::PinLatchValue
mcp23s17::digitalRead (
    const uint8_t pin_
) const {
    const unsigned int bit_pos(pin_ % 8);

    ControlRegister latch_register(ControlRegister::GPIOA_);
    ControlRegister direction_register(ControlRegister::IODIRA);
    uint8_t port_latch_values(0x00);

    // Select the appropriate port
    if ( pin_ / 8 ) {
        latch_register = ControlRegister::GPIOB_;
        direction_register = ControlRegister::IODIRB;
    }

    // Check to see if device is in the proper state
    if ( PinMode::OUTPUT == static_cast<PinMode>((_control_register[static_cast<uint8_t>(direction_register)] >> bit_pos) & 0x01) ) { return PinLatchValue::LOW; }

    // Send data
    ::digitalWrite(SS, LOW);
    ::SPI.transfer(_SPI_BUS_ADDRESS | static_cast<uint8_t>(RegisterTransaction::READ));
    ::SPI.transfer(static_cast<uint8_t>(latch_register));
    port_latch_values = ::SPI.transfer(static_cast<uint8_t>(latch_register));  // Arbitrary bit to flush result buffer. `latch_register` is selected, because it is guaranteed to be in active memory.
    ::digitalWrite(SS, HIGH);

    return static_cast<PinLatchValue>((port_latch_values >> bit_pos) & 0x01);
}

void
mcp23s17::digitalWrite (
    const uint8_t pin_,
    const PinLatchValue value_
) {
    const unsigned int bit_pos(pin_ % 8);
    const uint8_t bit_mask(static_cast<uint8_t>(1) << bit_pos);

    ControlRegister latch_register(ControlRegister::GPIOA_);
    ControlRegister direction_register(ControlRegister::IODIRA);
    uint8_t registry_value;

    // Select the appropriate port
    if ( pin_ / 8 ) {
        latch_register = ControlRegister::GPIOB_;
        direction_register = ControlRegister::IODIRB;
    }

    // Check to see if device is in the proper state
    if ( PinMode::INPUT == static_cast<PinMode>((_control_register[static_cast<uint8_t>(direction_register)] >> bit_pos) & 0x01) ) { return; }

    // Check cache for existing data
    registry_value = _control_register[static_cast<uint8_t>(latch_register)];
    if ( PinLatchValue::LOW == value_ ) {
        registry_value &= ~bit_mask;
    } else {
        registry_value |= bit_mask;
    }

    // Test to see if bit is already set
    if ( _control_register[static_cast<uint8_t>(latch_register)] == registry_value ) { return; }
    _control_register[static_cast<uint8_t>(latch_register)] = registry_value;

    // Send data
    ::digitalWrite(SS, LOW);
    ::SPI.transfer(_SPI_BUS_ADDRESS | static_cast<uint8_t>(RegisterTransaction::WRITE));
    ::SPI.transfer(static_cast<uint8_t>(latch_register));
    ::SPI.transfer(registry_value);
    ::digitalWrite(SS, HIGH);

    return;
}

void
mcp23s17::pinMode (
    const uint8_t pin_,
    const PinMode mode_
) {
    const unsigned int bit_pos(pin_ % 8);
    const uint8_t bit_mask(static_cast<uint8_t>(1) << bit_pos);

    ControlRegister latch_register(ControlRegister::IODIRA);
    ControlRegister pullup_register(ControlRegister::GPPUA);
    uint8_t latch_register_cache;
    uint8_t pullup_register_cache;

    // Select the appropriate port
    if ( pin_ / 8 ) {
        latch_register = ControlRegister::IODIRB;
        pullup_register = ControlRegister::GPPUB;
    }

    // Check cache for existing data
    latch_register_cache = _control_register[static_cast<uint8_t>(latch_register)];
    pullup_register_cache = _control_register[static_cast<uint8_t>(pullup_register)];
    switch ( mode_ ) {
      case PinMode::OUTPUT:
        latch_register_cache &= ~bit_mask;
        break;
      case PinMode::INPUT:
        pullup_register_cache &= ~bit_mask;
        latch_register_cache |= bit_mask;
        break;
      case PinMode::INPUT_PULLUP:
        pullup_register_cache |= bit_mask;
        latch_register_cache |= bit_mask;
        break;
    }

    //TODO: Move check up while creating tests to ensure no other state is modified
    if ( pin_ >= PIN_COUNT ) { return; }

    // Send data to IODIR[A|B] registers, if necessary
    if ( _control_register[static_cast<uint8_t>(latch_register)] != latch_register_cache ) {
        _control_register[static_cast<uint8_t>(latch_register)] = latch_register_cache;

        ::digitalWrite(SS, LOW);
        ::SPI.transfer(_SPI_BUS_ADDRESS | static_cast<uint8_t>(RegisterTransaction::WRITE));
        ::SPI.transfer(static_cast<uint8_t>(latch_register));
        ::SPI.transfer(latch_register_cache);
        ::digitalWrite(SS, HIGH);
    }

    // Send data to GPPU[A|B] registers, if necessary
    if ( _control_register[static_cast<uint8_t>(pullup_register)] != pullup_register_cache ) {
        _control_register[static_cast<uint8_t>(pullup_register)] = pullup_register_cache;

        ::digitalWrite(SS, LOW);
        ::SPI.transfer(_SPI_BUS_ADDRESS | static_cast<uint8_t>(RegisterTransaction::WRITE));
        ::SPI.transfer(static_cast<uint8_t>(pullup_register));
        ::SPI.transfer(pullup_register_cache);
        ::digitalWrite(SS, HIGH);
    }

    return;
}

/* Created and copyrighted by Zachary J. Fields. Offered as open source under the MIT License (MIT). */


text:
package com.github.drunlin.guokr.module.tool;

import com.github.drunlin.guokr.util.JavaUtil.Supplier;

import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

/**
 * 简单的缓存容器,无用的引用会自动删除。
 *
 * @author drunlin@outlook.com
 */
public class ReferenceMap<K, V> {
    private final ReferenceQueue<V> referenceQueue = new ReferenceQueue<>();
    private final Map<K, Reference<V>> referenceMap = new HashMap<>();
    private final Map<Reference<V>, K> keyMap = new HashMap<>();

    public V get(K key, Supplier<V> creator) {
        poll();

        V referent;
        Reference<V> reference = referenceMap.get(key);
        if (reference != null && (referent = reference.get()) != null) {
            return referent;
        } else {
            referent = creator.call();
            reference = new WeakReference<>(referent, referenceQueue);
            keyMap.put(reference, key);
            referenceMap.put(key, reference);
            return referent;
        }
    }

    private void poll() {
        Reference<V> reference;
        //noinspection unchecked
        while ((reference = (Reference<V>) referenceQueue.poll()) != null) {
            K key = keyMap.get(reference);
            if (reference == referenceMap.get(key)) {
                referenceMap.remove(key);
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.sleepycat.persist.evolve;

/**
 * The listener interface called during eager entity evolution.
 *
 * @see com.sleepycat.persist.evolve Class Evolution
 * @author Mark Hayes
 */
public interface EvolveListener {

    /**
     * The listener method called during eager entity evolution.
     *
     * @return true to continue evolution or false to stop.
     */
    boolean evolveProgress(EvolveEvent event);
}


text:
<?php

class PathFileForm extends CFormModel {

    public $DEBUG;
    public $D_LOGO;
    public $F_DEFAULT;
    public $F_PARAM;
    public $F_CERTIFICATE;
    public $F_CTYPE;

    /**
     * Declares the validation rules.
     * The rules state that username and password are required,
     * and password needs to be authenticated.
     */
    public function rules() {
        return array(
            array('D_LOGO, F_DEFAULT, F_PARAM, F_CERTIFICATE, F_CTYPE', 'required'),
            array('DEBUG', 'boolean'),
        );
    }

    /**
     * Declares attribute labels.
     */
    public function attributeLabels() {
        return array(
        );
    }

}


text:
package org.apache.lucene.search;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.FloatDocValuesField;
import org.apache.lucene.document.FloatField;
import org.apache.lucene.document.SortedDocValuesField;
import org.apache.lucene.index.BinaryDocValues;
import org.apache.lucene.index.DocValues;
import org.apache.lucene.index.FieldInvertState;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.NumericDocValues;
import org.apache.lucene.index.RandomIndexWriter;
import org.apache.lucene.index.SlowCompositeReaderWrapper;
import org.apache.lucene.index.SortedDocValues;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.BooleanClause.Occur;
import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.LuceneTestCase;

/**
 * Demonstrates an application of the {@link DiversifiedTopDocsCollector} in
 * assembling a collection of top results but without over-representation of any
 * one source (in this case top-selling singles from the 60s without having them
 * all be Beatles records...). Results are ranked by the number of weeks a
 * single is top of the charts and de-duped by the artist name.
 *
 */
public class TestDiversifiedTopDocsCollector extends LuceneTestCase {

  public void testNonDiversifiedResults() throws Exception {
    int numberOfTracksOnCompilation = 10;
    int expectedMinNumOfBeatlesHits = 5;
    TopDocs res = searcher.search(getTestQuery(), numberOfTracksOnCompilation);
    assertEquals(numberOfTracksOnCompilation, res.scoreDocs.length);
    // due to randomization of segment merging in tests the exact number of Beatles hits
    // selected varies between 5 and 6 but we prove the point they are over-represented
    // in our result set using a standard search.
    assertTrue(getMaxNumRecordsPerArtist(res.scoreDocs) >= expectedMinNumOfBeatlesHits);
  }

  public void testFirstPageDiversifiedResults() throws Exception {
    // Using a diversified collector we can limit the results from
    // any one artist.
    int requiredMaxHitsPerArtist = 2;
    int numberOfTracksOnCompilation = 10;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksOnCompilation, requiredMaxHitsPerArtist);
    ScoreDoc[] sd = tdc.topDocs(0).scoreDocs;
    assertEquals(numberOfTracksOnCompilation, sd.length);
    assertTrue(getMaxNumRecordsPerArtist(sd) <= requiredMaxHitsPerArtist);
  }

  public void testSecondPageResults() throws Exception {
    int numberOfTracksPerCompilation = 10;
    int numberOfCompilations = 2;
    int requiredMaxHitsPerArtist = 1;

    // Volume 2 of our hits compilation - start at position 10
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(
        numberOfTracksPerCompilation * numberOfCompilations,
        requiredMaxHitsPerArtist);
    ScoreDoc[] volume2 = tdc.topDocs(numberOfTracksPerCompilation,
        numberOfTracksPerCompilation).scoreDocs;
    assertEquals(numberOfTracksPerCompilation, volume2.length);
    assertTrue(getMaxNumRecordsPerArtist(volume2) <= requiredMaxHitsPerArtist);

  }

  public void testInvalidArguments() throws Exception {
    int numResults = 5;
    DiversifiedTopDocsCollector tdc = doDiversifiedSearch(numResults, 15);

    // start < 0
    assertEquals(0, tdc.topDocs(-1).scoreDocs.length);

    // start > pq.size()
    assertEquals(0, tdc.topDocs(numResults + 1).scoreDocs.length);

    // start == pq.size()
    assertEquals(0, tdc.topDocs(numResults).scoreDocs.length);

    // howMany < 0
    assertEquals(0, tdc.topDocs(0, -1).scoreDocs.length);

    // howMany == 0
    assertEquals(0, tdc.topDocs(0, 0).scoreDocs.length);

  }

  // Diversifying collector that looks up de-dup keys using SortedDocValues
  // from a top-level Reader
  private static final class DocValuesDiversifiedCollector extends
      DiversifiedTopDocsCollector {
    private final SortedDocValues sdv;

    public DocValuesDiversifiedCollector(int size, int maxHitsPerKey,
        SortedDocValues sdv) {
      super(size, maxHitsPerKey);
      this.sdv = sdv;
    }

    @Override
    protected NumericDocValues getKeys(final LeafReaderContext context) {

      return new NumericDocValues() {
        @Override
        public long get(int docID) {
          // Keys are always expressed as a long so we obtain the
          // ordinal for our String-based artist name here
          return sdv.getOrd(context.docBase + docID);
        }
      };
    }
  }

  // Alternative, faster implementation for converting String keys to longs
  // but with the potential for hash collisions
  private static final class HashedDocValuesDiversifiedCollector extends
      DiversifiedTopDocsCollector {

    private final String field;
    private BinaryDocValues vals;

    public HashedDocValuesDiversifiedCollector(int size, int maxHitsPerKey,
        String field) {
      super(size, maxHitsPerKey);
      this.field = field;
    }

    @Override
    protected NumericDocValues getKeys(LeafReaderContext context) {
      return new NumericDocValues() {
        @Override
        public long get(int docID) {
          return vals == null ? -1 : vals.get(docID).hashCode();
        }
      };
    }

    @Override
    public LeafCollector getLeafCollector(LeafReaderContext context)
        throws IOException {
      this.vals = DocValues.getBinary(context.reader(), field);
      return super.getLeafCollector(context);
    }
  }

  // Test data - format is artist, song, weeks at top of charts
  private static String[] hitsOfThe60s = {
      "1966\tSPENCER DAVIS GROUP\tKEEP ON RUNNING\t1",
      "1966\tOVERLANDERS\tMICHELLE\t3",
      "1966\tNANCY SINATRA\tTHESE BOOTS ARE MADE FOR WALKIN'\t4",
      "1966\tWALKER BROTHERS\tTHE SUN AIN'T GONNA SHINE ANYMORE\t4",
      "1966\tSPENCER DAVIS GROUP\tSOMEBODY HELP ME\t2",
      "1966\tDUSTY SPRINGFIELD\tYOU DON'T HAVE TO SAY YOU LOVE ME\t1",
      "1966\tMANFRED MANN\tPRETTY FLAMINGO\t3",
      "1966\tROLLING STONES\tPAINT IT, BLACK\t1",
      "1966\tFRANK SINATRA\tSTRANGERS IN THE NIGHT\t3",
      "1966\tBEATLES\tPAPERBACK WRITER\t5",
      "1966\tKINKS\tSUNNY AFTERNOON\t2",
      "1966\tGEORGIE FAME AND THE BLUE FLAMES\tGETAWAY\t1",
      "1966\tCHRIS FARLOWE\tOUT OF TIME\t1",
      "1966\tTROGGS\tWITH A GIRL LIKE YOU\t2",
      "1966\tBEATLES\tYELLOW SUBMARINE/ELEANOR RIGBY\t4",
      "1966\tSMALL FACES\tALL OR NOTHING\t1",
      "1966\tJIM REEVES\tDISTANT DRUMS\t5",
      "1966\tFOUR TOPS\tREACH OUT I'LL BE THERE\t3",
      "1966\tBEACH BOYS\tGOOD VIBRATIONS\t2",
      "1966\tTOM JONES\tGREEN GREEN GRASS OF HOME\t4",
      "1967\tMONKEES\tI'M A BELIEVER\t4",
      "1967\tPETULA CLARK\tTHIS IS MY SONG\t2",
      "1967\tENGELBERT HUMPERDINCK\tRELEASE ME\t4",
      "1967\tNANCY SINATRA AND FRANK SINATRA\tSOMETHIN' STUPID\t2",
      "1967\tSANDIE SHAW\tPUPPET ON A STRING\t3",
      "1967\tTREMELOES\tSILENCE IS GOLDEN\t3",
      "1967\tPROCOL HARUM\tA WHITER SHADE OF PALE\t4",
      "1967\tBEATLES\tALL YOU NEED IS LOVE\t7",
      "1967\tSCOTT MCKENZIE\tSAN FRANCISCO (BE SURE TO WEAR SOME FLOWERS INYOUR HAIR)\t4",
      "1967\tENGELBERT HUMPERDINCK\tTHE LAST WALTZ\t5",
      "1967\tBEE GEES\tMASSACHUSETTS (THE LIGHTS WENT OUT IN)\t4",
      "1967\tFOUNDATIONS\tBABY NOW THAT I'VE FOUND YOU\t2",
      "1967\tLONG JOHN BALDRY\tLET THE HEARTACHES BEGIN\t2",
      "1967\tBEATLES\tHELLO GOODBYE\t5",
      "1968\tGEORGIE FAME\tTHE BALLAD OF BONNIE AND CLYDE\t1",
      "1968\tLOVE AFFAIR\tEVERLASTING LOVE\t2",
      "1968\tMANFRED MANN\tMIGHTY QUINN\t2",
      "1968\tESTHER AND ABI OFARIM\tCINDERELLA ROCKEFELLA\t3",
      "1968\tDAVE DEE, DOZY, BEAKY, MICK AND TICH\tTHE LEGEND OF XANADU\t1",
      "1968\tBEATLES\tLADY MADONNA\t2",
      "1968\tCLIFF RICHARD\tCONGRATULATIONS\t2",
      "1968\tLOUIS ARMSTRONG\tWHAT A WONDERFUL WORLD/CABARET\t4",
      "1968\tGARRY PUCKETT AND THE UNION GAP\tYOUNG GIRL\t4",
      "1968\tROLLING STONES\tJUMPING JACK FLASH\t2",
      "1968\tEQUALS\tBABY COME BACK\t3", "1968\tDES O'CONNOR\tI PRETEND\t1",
      "1968\tTOMMY JAMES AND THE SHONDELLS\tMONY MONY\t2",
      "1968\tCRAZY WORLD OF ARTHUR BROWN\tFIRE!\t1",
      "1968\tTOMMY JAMES AND THE SHONDELLS\tMONY MONY\t1",
      "1968\tBEACH BOYS\tDO IT AGAIN\t1",
      "1968\tBEE GEES\tI'VE GOTTA GET A MESSAGE TO YOU\t1",
      "1968\tBEATLES\tHEY JUDE\t8",
      "1968\tMARY HOPKIN\tTHOSE WERE THE DAYS\t6",
      "1968\tJOE COCKER\tWITH A LITTLE HELP FROM MY FRIENDS\t1",
      "1968\tHUGO MONTENEGRO\tTHE GOOD THE BAD AND THE UGLY\t4",
      "1968\tSCAFFOLD\tLILY THE PINK\t3",
      "1969\tMARMALADE\tOB-LA-DI, OB-LA-DA\t1",
      "1969\tSCAFFOLD\tLILY THE PINK\t1",
      "1969\tMARMALADE\tOB-LA-DI, OB-LA-DA\t2",
      "1969\tFLEETWOOD MAC\tALBATROSS\t1", "1969\tMOVE\tBLACKBERRY WAY\t1",
      "1969\tAMEN CORNER\t(IF PARADISE IS) HALF AS NICE\t2",
      "1969\tPETER SARSTEDT\tWHERE DO YOU GO TO (MY LOVELY)\t4",
      "1969\tMARVIN GAYE\tI HEARD IT THROUGH THE GRAPEVINE\t3",
      "1969\tDESMOND DEKKER AND THE ACES\tTHE ISRAELITES\t1",
      "1969\tBEATLES\tGET BACK\t6", "1969\tTOMMY ROE\tDIZZY\t1",
      "1969\tBEATLES\tTHE BALLAD OF JOHN AND YOKO\t3",
      "1969\tTHUNDERCLAP NEWMAN\tSOMETHING IN THE AIR\t3",
      "1969\tROLLING STONES\tHONKY TONK WOMEN\t5",
      "1969\tZAGER AND EVANS\tIN THE YEAR 2525 (EXORDIUM AND TERMINUS)\t3",
      "1969\tCREEDENCE CLEARWATER REVIVAL\tBAD MOON RISING\t3",
      "1969\tJANE BIRKIN AND SERGE GAINSBOURG\tJE T'AIME... MOI NON PLUS\t1",
      "1969\tBOBBIE GENTRY\tI'LL NEVER FALL IN LOVE AGAIN\t1",
      "1969\tARCHIES\tSUGAR, SUGAR\t4" };

  private static final Map<String, Record> parsedRecords = new HashMap<String, Record>();
  private Directory dir;
  private IndexReader reader;
  private IndexSearcher searcher;
  private SortedDocValues artistDocValues;

  static class Record {
    String year;
    String artist;
    String song;
    float weeks;
    String id;

    public Record(String id, String year, String artist, String song,
        float weeks) {
      super();
      this.id = id;
      this.year = year;
      this.artist = artist;
      this.song = song;
      this.weeks = weeks;
    }

    @Override
    public String toString() {
      return "Record [id=" + id + ", artist=" + artist + ", weeks=" + weeks
          + ", year=" + year + ", song=" + song + "]";
    }

  }

  private DiversifiedTopDocsCollector doDiversifiedSearch(int numResults,
      int maxResultsPerArtist) throws IOException {
    // Alternate between implementations used for key lookups
    if (random().nextBoolean()) {
      // Faster key lookup but with potential for collisions on larger datasets
      return doFuzzyDiversifiedSearch(numResults, maxResultsPerArtist);
    } else {
      // Slower key lookup but 100% accurate
      return doAccurateDiversifiedSearch(numResults, maxResultsPerArtist);
    }
  }

  private DiversifiedTopDocsCollector doFuzzyDiversifiedSearch(int numResults,
      int maxResultsPerArtist) throws IOException {
    DiversifiedTopDocsCollector tdc = new HashedDocValuesDiversifiedCollector(
        numResults, maxResultsPerArtist, "artist");
    searcher.search(getTestQuery(), tdc);
    return tdc;
  }

  private DiversifiedTopDocsCollector doAccurateDiversifiedSearch(
      int numResults, int maxResultsPerArtist) throws IOException {
    DiversifiedTopDocsCollector tdc = new DocValuesDiversifiedCollector(
        numResults, maxResultsPerArtist, artistDocValues);
    searcher.search(getTestQuery(), tdc);
    return tdc;
  }

  private Query getTestQuery() {
    BooleanQuery.Builder testQuery = new BooleanQuery.Builder();
    testQuery.add(new BooleanClause(new TermQuery(new Term("year", "1966")),
        Occur.SHOULD));
    testQuery.add(new BooleanClause(new TermQuery(new Term("year", "1967")),
        Occur.SHOULD));
    testQuery.add(new BooleanClause(new TermQuery(new Term("year", "1968")),
        Occur.SHOULD));
    testQuery.add(new BooleanClause(new TermQuery(new Term("year", "1969")),
        Occur.SHOULD));
    return testQuery.build();
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();

    // populate an index with documents - artist, song and weeksAtNumberOne
    dir = newDirectory();
    RandomIndexWriter writer = new RandomIndexWriter(random(), dir);
    Document doc = new Document();

    Field yearField = newTextField("year", "", Field.Store.NO);
    SortedDocValuesField artistField = new SortedDocValuesField("artist",
        new BytesRef(""));
    Field weeksAtNumberOneField = new FloatDocValuesField("weeksAtNumberOne",
        0.0F);
    Field weeksStoredField = new FloatField("weeks", 0.0F, Store.YES);
    Field idField = newStringField("id", "", Field.Store.YES);
    Field songField = newTextField("song", "", Field.Store.NO);
    Field storedArtistField = newTextField("artistName", "", Field.Store.NO);

    doc.add(idField);
    doc.add(weeksAtNumberOneField);
    doc.add(storedArtistField);
    doc.add(songField);
    doc.add(weeksStoredField);
    doc.add(yearField);
    doc.add(artistField);

    parsedRecords.clear();
    for (int i = 0; i < hitsOfThe60s.length; i++) {
      String cols[] = hitsOfThe60s[i].split("\t");
      Record record = new Record(String.valueOf(i), cols[0], cols[1], cols[2],
          Float.valueOf(cols[3]));
      parsedRecords.put(record.id, record);
      idField.setStringValue(record.id);
      yearField.setStringValue(record.year);
      storedArtistField.setStringValue(record.artist);
      artistField.setBytesValue(new BytesRef(record.artist));
      songField.setStringValue(record.song);
      weeksStoredField.setFloatValue(record.weeks);
      weeksAtNumberOneField.setFloatValue(record.weeks);
      writer.addDocument(doc);
      if (i % 10 == 0) {
        // Causes the creation of multiple segments for our test
        writer.commit();
      }
    }
    reader = writer.getReader();
    writer.close();
    searcher = newSearcher(reader);
    LeafReader ar = SlowCompositeReaderWrapper.wrap(reader);
    artistDocValues = ar.getSortedDocValues("artist");

    // All searches sort by song popularity
    final Similarity base = searcher.getSimilarity(true);
    searcher.setSimilarity(new DocValueSimilarity(base, "weeksAtNumberOne"));
  }

  @Override
  public void tearDown() throws Exception {
    reader.close();
    dir.close();
    dir = null;
    super.tearDown();
  }

  private int getMaxNumRecordsPerArtist(ScoreDoc[] sd) throws IOException {
    int result = 0;
    HashMap<String, Integer> artistCounts = new HashMap<String, Integer>();
    for (int i = 0; i < sd.length; i++) {
      Document doc = reader.document(sd[i].doc);
      Record record = parsedRecords.get(doc.get("id"));
      Integer count = artistCounts.get(record.artist);
      int newCount = 1;
      if (count != null) {
        newCount = count.intValue() + 1;
      }
      result = Math.max(result, newCount);
      artistCounts.put(record.artist, newCount);
    }
    return result;
  }

  /**
   * Similarity that wraps another similarity and replaces the final score
   * according to whats in a docvalues field.
   *
   * @lucene.experimental
   */
  static class DocValueSimilarity extends Similarity {
    private final Similarity sim;
    private final String scoreValueField;

    public DocValueSimilarity(Similarity sim, String scoreValueField) {
      this.sim = sim;
      this.scoreValueField = scoreValueField;
    }

    @Override
    public long computeNorm(FieldInvertState state) {
      return sim.computeNorm(state);
    }

    @Override
    public SimWeight computeWeight(float queryBoost,
        CollectionStatistics collectionStats, TermStatistics... termStats) {
      return sim.computeWeight(queryBoost, collectionStats, termStats);
    }

    @Override
    public SimScorer simScorer(SimWeight stats, LeafReaderContext context)
        throws IOException {
      final SimScorer sub = sim.simScorer(stats, context);
      final NumericDocValues values = DocValues.getNumeric(context.reader(),
          scoreValueField);

      return new SimScorer() {
        @Override
        public float score(int doc, float freq) {
          return Float.intBitsToFloat((int) values.get(doc));
        }

        @Override
        public float computeSlopFactor(int distance) {
          return sub.computeSlopFactor(distance);
        }

        @Override
        public float computePayloadFactor(int doc, int start, int end,
            BytesRef payload) {
          return sub.computePayloadFactor(doc, start, end, payload);
        }

        @Override
        public Explanation explain(int doc, Explanation freq) {
          return Explanation.match(Float.intBitsToFloat((int) values.get(doc)),
              "indexDocValue(" + scoreValueField + ")");
        }
      };
    }
  }

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

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

    <title>yalgo - Documentation</title>
    <link rel="stylesheet" href="../ldoc.css" type="text/css" />

<big></big>

yalgo

Topics

README

Modules

yalgo

yalgo – Yet Another Lua GetOpts

A pure Lua module for command line argument parsing

I wrote this to handle command line arguments in a more table-centric manner.

yago can handle many styles of options, including GNU style long-options as well
as globbed short options. Such as:

<program> -a -b -c arg_to_c arg1 arg2

<program> —alpha -bc arg_to_c arg1 arg2

<program> -ab —gamma=arg_to_c arg1 arg2

<program> -a -b —gamma arg_to_c arg1 arg2

<program> -abcarg_to_c arg1 arg2

Usage

yalgo is easy to implement into your code, and returns a table indexed by option
names with the values found at the command line.

Example

local yalgo = require 'yalgo'
my_parser = yalgo.Parser:new('my program description')
my_parser:add_arg({
  name = 'alpha',
  l_opt = '--alpha',
  s_opt = '-a',
  descr = 'alpha option description' -- Option description used in disp_help
})
my_parser:add_arg({
  name = 'beta',
  l_opt = '--beta',
  s_opt = '-b',
  descr = 'beta option description'
})
my_parser:add_arg({
  name = 'gamma',
  l_opt = '-gamma',
  s_opt = '-c',
  has_arg = true, -- Option takes an argument
  is_reqd = true, -- Option is mandatory
  descr = 'gamma option description',
  meta_val = 'ARG' -- Option argument place holder used in disp_help
})
my_parser:add_arg({
  name = 'arg1',
  is_pos = true, -- Specifies positional argument
  is_reqd = true,
  descr = 'arg1 description',
  meta_val = 'ARG1'
})
my_parser:add_arg({
  name = 'arg2',
  is_pos = true,
  descr = 'arg2 description',
  meta_val = 'ARG2'
})
opts = my_parser:get_args()
if opts.help then
  my_parser:disp_help()
  os.exit(0)
end
if opts.alpha then
  -- code if --alpha or -a was given ...
end
if opts.gamma == 'arg_to_c' then
  -- code if --gamma or -c was given with 'arg_to_c'
end

Version & Changelog:

0.1.0 – Initial release

0.2.0 – Complete overhaul to more resemble Python’s argparse module

generated by LDoc 1.4.3
Last updated 2015-05-15 14:04:13


text:
<launch_control_xl>
	<template id="0">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="1">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="2">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="3">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="4">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="5">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="6">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="21" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="48" /></faders>
		<buttons>
			<top>
				<ch continuous="8" type="control" value="89" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="9" />
				<ch continuous="4" type="note" value="25" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="114" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="57" />
		</other_buttons>
	</template>
	<template id="7">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="8">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="9">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="10">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="11">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="12">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="13">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="14">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
	<template id="15">
		<knobs>
			<top><ch continuous="8" type="control" value="13" /></top>
			<ch continuous="8" type="control" value="29" />
			<bottom><ch continuous="8" type="control" value="49" /></bottom>
		</knobs>
		<faders><ch continuous="8" type="control" value="77" /></faders>
		<buttons>
			<top>
				<ch continuous="4" type="note" value="41" />
				<ch continuous="4" type="note" value="57" />
			</top>
			<bottom>
				<ch continuous="4" type="note" value="73" />
				<ch continuous="4" type="note" value="89" />
			</bottom>
		</buttons>
		<cursors>
			<ch continuous="4" type="control" value="104" />
		</cursors>
		<other_buttons>
			<ch continuous="4" type="note" value="105" />
		</other_buttons>
	</template>
</launch_control_xl>


text:
"""
NBA Game Thread Generator
Ben H
batsmasher@gmail.com
Created May 2017 - Updated July 2017
"""

import requests
import json
import bs4
from HTMLParser import HTMLParser
import time
import re
import nba_py
from nba_py import team, game
from pprint import pprint as pp

from flask import Flask, render_template, request

app = Flask(__name__)

Soup = bs4.BeautifulSoup
h = HTMLParser()
game_summaries = []

BASKETBALL_TEAMS = 2
BASE_URL = 'http://www.espn.com.au/nba/scoreboard/_/date/{0}'

teams = {
    'Atlanta Hawks': 1610612737,
    'Boston Celtics': 1610612738,
    'Brooklyn Nets': 1610612751,
    'Charlotte Hornets': 1610612766,
    'Chicago Bulls': 1610612741,
    'Cleveland Cavaliers': 1610612739,
    'Dallas Mavericks': 1610612742,
    'Denver Nuggets': 1610612743,
    'Detroit Pistons': 1610612765,
    'Golden State Warriors': 1610612744,
    'Houston Rockets': 1610612745,
    'Indiana Pacers': 1610612754,
    'LA Clippers': 1610612746,
    'LA Lakers': 1610612747,
    'Memphis Grizzlies': 1610612763,
    'Miami Heat': 1610612748,
    'Milwaukee Bucks': 1610612749,
    'Minnesota Timberwolves': 1610612750,
    'New Orleans Pelicans': 1610612740,
    'New York Knicks': 1610612752,
    'Oklahoma City Thunder': 1610612760,
    'Orlando Magic': 1610612753,
    'Philadelphia 76ers': 1610612755,
    'Phoenix Suns': 1610612756,
    'Portland Trail Blazers': 1610612757,
    'Sacramento Kings': 1610612758,
    'San Antonio Spurs': 1610612759,
    'Toronto Raptors': 1610612761,
    'Utah Jazz': 1610612762,
    'Washington Wizards': 1610612764
}

class GameSummary:
    def __init__(self, id, home, away, venue):
        self.id = id
        self.home = home
        self.away = away
        self.venue = venue

class TeamSummary:
    def __init__(self, name, id, record, logo, color1, color2, players, coaches, stats, last5):
        self.name = name
        self.id = id
        self.record = record
        self.logo = logo
        self.color1 = color1
        self.color2 = color2
        self.players = players
        self.coaches = coaches
        self.stats = stats
        self.last5 = last5

class Player:
    def __init__(self, name, age, height, weight, position, number):
        self.name = name
        self.age = age
        self.height = height
        self.weight = weight
        self.position = position
        self.number = number

class Coach:
    def __init__(self, name, coach_type):
        self.name = name
        self.coach_type = coach_type

class TeamStats:
    def __init__(self, fg, fgr, ft, ftr, tpp, tppr, pts, ptsr, reb, rebr, ast, astr, stl, stlr, blk, blkr):
        self.fg = fg
        self.fgr = fgr
        self.ft = ft
        self.ftr = ftr
        self.tpp = tpp
        self.tppr = tppr
        self.pts = pts
        self.ptsr = ptsr
        self.reb = reb
        self.rebr = rebr
        self.ast = ast
        self.astr = astr
        self.stl = stl
        self.stlr = stlr
        self.blk = blk
        self.blkr = blkr

class Last5:
    def __init__(self, record, stats):
        self.record = record
        self.stats = stats

def scrape_data(date):
    url = BASE_URL.format(date)
    print url
    # r = requests.get(url).text
    # open('C:\Users\ASUS\Downloads\espn.html')
    soup = Soup(open('C:\Users\ASUS\Downloads\espn4.html').read(), "html.parser")

    src = h.unescape(
        soup.find("script", text=re.compile("window.espn.scoreboardData")).text.split("=", 1)[1].rstrip(";"))
    game_data = []

    js = json.loads(src[:src.index(";")])
    for i in range(len(js["events"])):
        data = js["events"][i]["competitions"][0]
        game_data.append(data)
    return game_data

def print_data(game_data):
    for gd in game_data:
        pass  # pp(gd)

def get_game_summary(gid):
    for game_summary in game_summaries:
        if game_summary.id == gid:
            return game_summary
    return "Can\'t find the game"

def get_game_summaries(games_data):
    summaries = []
    for gd in games_data:
        team_summaries = get_team_summaries(gd)
        gs = GameSummary(gd['id'],
                         team_summaries[0],
                         team_summaries[1],
                         gd['venue']['fullName'])
        summaries.append(gs)
    return summaries

def get_team_summaries(game_data):
    """
    Lord help me when Basketball becomes a 3 team game
    :param game_data: The JSON to extract game data from
    :return: A list of TeamSummarys
    """

    summaries = []

    for i in range(BASKETBALL_TEAMS):
        t = TeamSummary(
            game_data['competitors'][i]['team']['displayName'],
            get_team_id(game_data['competitors'][i]['team']['displayName']),
            game_data['competitors'][i]['records'][0]['summary'],
            game_data['competitors'][i]['team']['logo'],
            game_data['competitors'][i]['team']['color'],
            game_data['competitors'][i]['team']['alternateColor'],
            None,
            None,
            None,
            None
        )
        summaries.append(t)

    return sorted(summaries, reverse=(game_data['competitors'][0]['homeAway'] == 'away'))

def get_team_id(name):
    """
    Finds the NBA team ID associated with the inputted name
    :param name: The string name of an NBA team
    :return: The NBA team ID
    """
    try:
        return teams[name]
    except LookupError:
        print "Team name not found"

def get_detailed_summary(game_summary):
    """
    Updates the basic GameSummary and returns a more detailed version
    :rtype: GameSummary
    :param game_summary:
    :return: An updated GameSummary with stats, players and coaches
    """

    game_summary.id
    return

def get_team_details(team_summary):
    # type: (TeamSummary) -> TeamSummary

    coaches = []
    players = []

    for coach in nba_py.team.TeamCommonRoster(team_summary.id).coaches():
        coaches.append(Coach(coach["COACH_NAME"],
                             coach["COACH_TYPE"]))

    for player in nba_py.team.TeamCommonRoster(team_summary.id).roster():
        players.append(Player(player["PLAYER"],
                              player["AGE"],
                              player["HEIGHT"],
                              player["WEIGHT"],
                              player["POSITION"],
                              player["NUM"]))

    team_summary.coaches = coaches
    team_summary.players = players

    last5record = ""

    for row in nba_py.team.TeamGameLogs(team_summary.id,season='2016-17', season_type='Regular Season').info()[:5].iterrows():
        last5record += row[1]['MATCHUP'] + " - " + row[1]['WL'] + "\n"

    team_summary.last5 = Last5(last5record,None)

    return team_summary

def get_game_stats(team_id, ngames=None):
    # type: (str, str) -> TeamStats

    if (ngames is not None) and ngames <82:
        pass

    return

@app.route("/get_games/")
def get_games():
    try:
        selected_date = request.args['date'].replace('-', '')

        gd = scrape_data(selected_date)
        pp(gd)
        games = get_game_summaries(gd)

        global game_summaries
        game_summaries = games

        return render_template('index.html', games=games)
    except LookupError:
        return render_template('index.html')

@app.route("/summary/", methods=["POST"])
def summary():
    try:
        gid = request.form['gid']
        gs = get_game_summary(gid)

        global game_summaries
        return render_template('index.html',
                               game=render_template('gamethread.txt', game=gs),
                               games=game_summaries)
    except LookupError:
        return render_template('index.html')

@app.route("/")
def main():
    return render_template('index.html')

if __name__ == "__main__":
    #print nba_py.team.TeamGeneralSplits(get_team_id('Phoenix Suns')).overall()['FG3_PCT_RANK']
    app.run()
    #print nba_py.team.TeamCommonRoster(get_team_id('Phoenix Suns')).coaches()["COACH_NAME"]


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.operator.aggregation;

import com.facebook.presto.block.Block;
import com.facebook.presto.block.BlockBuilder;
import com.facebook.presto.block.BlockCursor;
import com.facebook.presto.operator.GroupByIdBlock;
import com.facebook.presto.tuple.TupleInfo.Type;
import com.facebook.presto.util.array.DoubleBigArray;
import com.facebook.presto.util.array.LongBigArray;
import com.google.common.base.Optional;
import io.airlift.slice.Slice;
import io.airlift.slice.Slices;

import static com.facebook.presto.operator.aggregation.ApproximateUtils.formatApproximateResult;
import static com.facebook.presto.tuple.TupleInfo.SINGLE_VARBINARY;
import static com.facebook.presto.tuple.TupleInfo.Type.DOUBLE;
import static com.facebook.presto.tuple.TupleInfo.Type.FIXED_INT_64;
import static com.google.common.base.Preconditions.checkState;
import static io.airlift.slice.SizeOf.SIZE_OF_DOUBLE;
import static io.airlift.slice.SizeOf.SIZE_OF_LONG;

public class ApproximateAverageAggregation
        extends SimpleAggregationFunction
{
    private static final int COUNT_OFFSET = 0;
    private static final int SAMPLES_OFFSET = SIZE_OF_LONG;
    private static final int MEAN_OFFSET = 2 * SIZE_OF_LONG;
    private static final int M2_OFFSET = 2 * SIZE_OF_LONG + SIZE_OF_DOUBLE;

    private final boolean inputIsLong;

    public ApproximateAverageAggregation(Type parameterType)
    {
        // Intermediate type should be a fixed width structure
        super(SINGLE_VARBINARY, SINGLE_VARBINARY, parameterType);

        if (parameterType == FIXED_INT_64) {
            this.inputIsLong = true;
        }
        else if (parameterType == DOUBLE) {
            this.inputIsLong = false;
        }
        else {
            throw new IllegalArgumentException("Expected parameter type to be FIXED_INT_64 or DOUBLE, but was " + parameterType);
        }
    }

    @Override
    protected GroupedAccumulator createGroupedAccumulator(Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence, int valueChannel)
    {
        return new ApproximateAverageGroupedAccumulator(valueChannel, inputIsLong, maskChannel, sampleWeightChannel, confidence);
    }

    public static class ApproximateAverageGroupedAccumulator
            extends SimpleGroupedAccumulator
    {
        private final boolean inputIsLong;
        private final double confidence;

        private final LongBigArray counts;
        private final LongBigArray samples;
        private final DoubleBigArray means;
        private final DoubleBigArray m2s;

        private ApproximateAverageGroupedAccumulator(int valueChannel, boolean inputIsLong, Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence)
        {
            super(valueChannel, SINGLE_VARBINARY, SINGLE_VARBINARY, maskChannel, sampleWeightChannel);

            this.inputIsLong = inputIsLong;
            this.confidence = confidence;

            this.counts = new LongBigArray();
            this.samples = new LongBigArray();
            this.means = new DoubleBigArray();
            this.m2s = new DoubleBigArray();
        }

        @Override
        public long getEstimatedSize()
        {
            return counts.sizeOf() + samples.sizeOf() + means.sizeOf() + m2s.sizeOf();
        }

        @Override
        protected void processInput(GroupByIdBlock groupIdsBlock, Block valuesBlock, Optional<Block> maskBlock, Optional<Block> sampleWeightBlock)
        {
            counts.ensureCapacity(groupIdsBlock.getGroupCount());
            samples.ensureCapacity(groupIdsBlock.getGroupCount());
            means.ensureCapacity(groupIdsBlock.getGroupCount());
            m2s.ensureCapacity(groupIdsBlock.getGroupCount());

            BlockCursor values = valuesBlock.cursor();
            BlockCursor masks = null;
            if (maskBlock.isPresent()) {
                masks = maskBlock.get().cursor();
            }
            BlockCursor sampleWeights = null;
            if (sampleWeightBlock.isPresent()) {
                sampleWeights = sampleWeightBlock.get().cursor();
            }

            for (int position = 0; position < groupIdsBlock.getPositionCount(); position++) {
                checkState(values.advanceNextPosition());
                checkState(masks == null || masks.advanceNextPosition());
                checkState(sampleWeights == null || sampleWeights.advanceNextPosition());
                long sampleWeight = computeSampleWeight(masks, sampleWeights);

                if (!values.isNull() && sampleWeight > 0) {
                    long groupId = groupIdsBlock.getGroupId(position);
                    double inputValue;
                    if (inputIsLong) {
                        inputValue = values.getLong();
                    }
                    else {
                        inputValue = values.getDouble();
                    }

                    long currentCount = counts.get(groupId);
                    double currentMean = means.get(groupId);

                    // Use numerically stable variant
                    for (int i = 0; i < sampleWeight; i++) {
                        currentCount++;
                        double delta = inputValue - currentMean;
                        currentMean += (delta / currentCount);
                        // update m2 inline
                        m2s.add(groupId, (delta * (inputValue - currentMean)));
                    }

                    // write values back out
                    counts.set(groupId, currentCount);
                    means.set(groupId, currentMean);
                    samples.increment(groupId);
                }
            }
            checkState(!values.advanceNextPosition());
        }

        @Override
        protected void processIntermediate(GroupByIdBlock groupIdsBlock, Block valuesBlock)
        {
            counts.ensureCapacity(groupIdsBlock.getGroupCount());
            samples.ensureCapacity(groupIdsBlock.getGroupCount());
            means.ensureCapacity(groupIdsBlock.getGroupCount());
            m2s.ensureCapacity(groupIdsBlock.getGroupCount());

            BlockCursor values = valuesBlock.cursor();

            for (int position = 0; position < groupIdsBlock.getPositionCount(); position++) {
                checkState(values.advanceNextPosition());

                if (!values.isNull()) {
                    long groupId = groupIdsBlock.getGroupId(position);

                    Slice slice = values.getSlice();
                    long inputCount = slice.getLong(COUNT_OFFSET);
                    long inputSamples = slice.getLong(SAMPLES_OFFSET);
                    double inputMean = slice.getDouble(MEAN_OFFSET);
                    double inputM2 = slice.getDouble(M2_OFFSET);

                    long currentCount = counts.get(groupId);
                    double currentMean = means.get(groupId);
                    double currentM2 = m2s.get(groupId);

                    // Use numerically stable variant
                    if (inputCount > 0) {
                        long newCount = currentCount + inputCount;
                        double newMean = ((currentCount * currentMean) + (inputCount * inputMean)) / newCount;
                        double delta = inputMean - currentMean;
                        double newM2 = currentM2 + inputM2 + ((delta * delta) * (currentCount * inputCount)) / newCount;

                        counts.set(groupId, newCount);
                        samples.add(groupId, inputSamples);
                        means.set(groupId, newMean);
                        m2s.set(groupId, newM2);
                    }
                }
            }
            checkState(!values.advanceNextPosition());
        }

        @Override
        public void evaluateIntermediate(int groupId, BlockBuilder output)
        {
            output.append(createIntermediate(counts.get(groupId), samples.get(groupId), means.get(groupId), m2s.get(groupId)));
        }

        @Override
        public void evaluateFinal(int groupId, BlockBuilder output)
        {
            long count = counts.get((long) groupId);
            if (count == 0) {
                output.appendNull();
            }
            else {
                double mean = means.get((long) groupId);
                double m2 = m2s.get((long) groupId);
                double variance = m2 / count;

                String result = formatApproximateAverage(samples.get(groupId), mean, variance, confidence);
                output.append(result);
            }
        }
    }

    @Override
    protected Accumulator createAccumulator(Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence, int valueChannel)
    {
        return new ApproximateAverageAccumulator(valueChannel, inputIsLong, maskChannel, sampleWeightChannel, confidence);
    }

    public static class ApproximateAverageAccumulator
            extends SimpleAccumulator
    {
        private final boolean inputIsLong;
        private final double confidence;

        private long currentCount;
        private long currentSamples;
        private double currentMean;
        private double currentM2;

        private ApproximateAverageAccumulator(int valueChannel, boolean inputIsLong, Optional<Integer> maskChannel, Optional<Integer> sampleWeightChannel, double confidence)
        {
            super(valueChannel, SINGLE_VARBINARY, SINGLE_VARBINARY, maskChannel, sampleWeightChannel);

            this.inputIsLong = inputIsLong;
            this.confidence = confidence;
        }

        @Override
        protected void processInput(Block block, Optional<Block> maskBlock, Optional<Block> sampleWeightBlock)
        {
            BlockCursor values = block.cursor();
            BlockCursor masks = null;
            if (maskBlock.isPresent()) {
                masks = maskBlock.get().cursor();
            }
            BlockCursor sampleWeights = null;
            if (sampleWeightBlock.isPresent()) {
                sampleWeights = sampleWeightBlock.get().cursor();
            }

            for (int position = 0; position < block.getPositionCount(); position++) {
                checkState(values.advanceNextPosition());
                checkState(masks == null || masks.advanceNextPosition());
                checkState(sampleWeights == null || sampleWeights.advanceNextPosition());
                long sampleWeight = computeSampleWeight(masks, sampleWeights);

                if (!values.isNull() && sampleWeight > 0) {
                    double inputValue;
                    if (inputIsLong) {
                        inputValue = values.getLong();
                    }
                    else {
                        inputValue = values.getDouble();
                    }

                    for (int i = 0; i < sampleWeight; i++) {
                        // Use numerically stable variant
                        currentCount++;
                        double delta = inputValue - currentMean;
                        currentMean += (delta / currentCount);
                        // update m2 inline
                        currentM2 += (delta * (inputValue - currentMean));
                    }
                    currentSamples++;
                }
            }
            checkState(!values.advanceNextPosition());
        }

        @Override
        protected void processIntermediate(Block block)
        {
            BlockCursor values = block.cursor();

            for (int position = 0; position < block.getPositionCount(); position++) {
                checkState(values.advanceNextPosition());

                if (!values.isNull()) {
                    Slice slice = values.getSlice();
                    long inputCount = slice.getLong(COUNT_OFFSET);
                    long inputSamples = slice.getLong(SAMPLES_OFFSET);
                    double inputMean = slice.getDouble(MEAN_OFFSET);
                    double inputM2 = slice.getDouble(M2_OFFSET);

                    // Use numerically stable variant
                    if (inputCount > 0) {
                        long newCount = currentCount + inputCount;
                        double newMean = ((currentCount * currentMean) + (inputCount * inputMean)) / newCount;
                        double delta = inputMean - currentMean;
                        double newM2 = currentM2 + inputM2 + ((delta * delta) * (currentCount * inputCount)) / newCount;

                        currentCount = newCount;
                        currentMean = newMean;
                        currentM2 = newM2;
                        currentSamples += inputSamples;
                    }
                }
            }
            checkState(!values.advanceNextPosition());
        }

        @Override
        public void evaluateIntermediate(BlockBuilder output)
        {
            output.append(createIntermediate(currentCount, currentSamples, currentMean, currentM2));
        }

        @Override
        public void evaluateFinal(BlockBuilder output)
        {
            if (currentCount == 0) {
                output.appendNull();
            }
            else {
                String result = formatApproximateAverage(currentSamples, currentMean, currentM2 / currentCount, confidence);
                output.append(result);
            }
        }
    }

    private static String formatApproximateAverage(long samples, double mean, double variance, double confidence)
    {
        return formatApproximateResult(mean, Math.sqrt(variance / samples), confidence, false);
    }

    public static Slice createIntermediate(long count, long samples, double mean, double m2)
    {
        Slice slice = Slices.allocate(2 * SIZE_OF_LONG + 2 * SIZE_OF_DOUBLE);
        slice.setLong(COUNT_OFFSET, count);
        slice.setLong(SAMPLES_OFFSET, samples);
        slice.setDouble(MEAN_OFFSET, mean);
        slice.setDouble(M2_OFFSET, m2);
        return slice;
    }
}


text:
package main

import (
	"flag"
	"net/http"
	"os"
	"path/filepath"
	"testing"

	"github.com/stretchr/testify/assert"
)

var emulator *EmulatorClient

func TestMain(m *testing.M) {
	// to parse go test * flags m.Run consumes
	flag.Parse()

	emulator = makeEmulatorCiient()
	emulator.waitApi()

	os.Exit(m.Run())
}

func makeUserCodeRequest() UserCodeRequest {
	return UserCodeRequest{
		Files: []UserCodeFile{
			{Name: "main.py", Content: "import sys; sys.exit(0)", IsMain: true},
		},
		PipelineOptions: "some opts",
	}
}

func checkBadHttpCode(t *testing.T, err error, code int) {
	if err == nil {
		t.Fatal("error expected")
	}
	if err, ok := err.(*ErrBadResponse); ok {
		if err.Code == code {
			return
		}
	}
	t.Fatalf("Expected ErrBadResponse with code %v, got %v", code, err)
}

func TestSaveGetProgress(t *testing.T) {
	idToken := emulator.getIDToken()

	// postUnitCompleteURL
	port := os.Getenv(PORT_POST_UNIT_COMPLETE)
	if port == "" {
		t.Fatal(PORT_POST_UNIT_COMPLETE, "env not set")
	}
	postUnitCompleteURL := "http://localhost:" + port

	// postUserCodeURL
	port = os.Getenv(PORT_POST_USER_CODE)
	if port == "" {
		t.Fatal(PORT_POST_USER_CODE, "env not set")
	}
	postUserCodeURL := "http://localhost:" + port

	// getUserProgressURL
	port = os.Getenv(PORT_GET_USER_PROGRESS)
	if port == "" {
		t.Fatal(PORT_GET_USER_PROGRESS, "env not set")
	}
	getUserProgressURL := "http://localhost:" + port

	t.Run("save_complete_no_unit", func(t *testing.T) {
		resp, err := PostUnitComplete(postUnitCompleteURL, "python", "unknown_unit_id_1", idToken)
		checkBadHttpCode(t, err, http.StatusNotFound)
		assert.Equal(t, "NOT_FOUND", resp.Code)
		assert.Equal(t, "unit not found", resp.Message)
	})
	t.Run("save_complete", func(t *testing.T) {
		_, err := PostUnitComplete(postUnitCompleteURL, "python", "challenge1", idToken)
		if err != nil {
			t.Fatal(err)
		}
	})
	t.Run("save_code", func(t *testing.T) {
		req := makeUserCodeRequest()
		_, err := PostUserCode(postUserCodeURL, "python", "example1", idToken, req)
		if err != nil {
			t.Fatal(err)
		}
	})
	t.Run("save_code_playground_fail", func(t *testing.T) {
		req := makeUserCodeRequest()

		// empty content doesn't pass validation
		req.Files[0].Content = ""

		resp, err := PostUserCode(postUserCodeURL, "python", "example1", idToken, req)
		checkBadHttpCode(t, err, http.StatusInternalServerError)
		assert.Equal(t, "INTERNAL_ERROR", resp.Code)
		msg := "playground api error"
		assert.Equal(t, msg, resp.Message[:len(msg)])

	})
	t.Run("save_code_no_unit", func(t *testing.T) {
		req := makeUserCodeRequest()
		resp, err := PostUserCode(postUserCodeURL, "python", "unknown_unit_id_1", idToken, req)
		checkBadHttpCode(t, err, http.StatusNotFound)
		assert.Equal(t, "NOT_FOUND", resp.Code)
		assert.Equal(t, "unit not found", resp.Message)

	})
	t.Run("get", func(t *testing.T) {

		mock_path := filepath.Join("..", "samples", "api", "get_user_progress.json")
		var exp SdkProgress
		if err := loadJson(mock_path, &exp); err != nil {
			t.Fatal(err)
		}

		resp, err := GetUserProgress(getUserProgressURL, "python", idToken)
		if err != nil {
			t.Fatal(err)
		}
		assert.Equal(t, exp, resp)
	})
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!-- automatically produced by XMLAttributePersistenceManager -->
<attribute-list date="20131125093958" id="dcm4chee.web:service=EchoService">
<attribute name="CallingAETitle" type="java.lang.String">DCM4CHEE</attribute>
<attribute name="BindToCallingAET" type="java.lang.Boolean">true</attribute>
<attribute name="ConnectTimeout" type="java.lang.Integer">0</attribute>
<attribute name="AcceptTimeout" type="java.lang.Integer">10000</attribute>
<attribute name="DimseRspTimeout" type="java.lang.Integer">60000</attribute>
<attribute name="ReleaseTimeout" type="java.lang.Integer">5000</attribute>
<attribute name="SocketCloseDelay" type="java.lang.Integer">50</attribute>
<attribute name="MaximumPDULengthReceive" type="java.lang.Integer">16352</attribute>
<attribute name="getMaxOpsInvoked" type="java.lang.Integer">0</attribute>
<attribute name="TcpNoDelay" type="java.lang.Boolean">true</attribute>
<attribute name="TlsCfgServiceName" type="javax.management.ObjectName">dcm4chee.web:service=TlsConfig</attribute>
<attribute name="PingTimeout" type="java.lang.Integer">1000</attribute>
</attribute-list>


text:
'use strict';

var grunt = require('grunt');

exports.front_end_modules = {
  setUp: function(done) {
    done();
  },

  defaults: function(test) {
    test.expect(1);

    var source = grunt.file.read('test/fixtures/defaults/node_modules/defaults/dist/foo.js');
    var copied = grunt.file.read('tmp/test/dest/default/foo.js');
    test.equal(source, copied, 'should copy main file');

    test.done();
  },

  overrides: function(test) {
    test.expect(2);

    var source = grunt.file.read('test/fixtures/overrides/node_modules/overrides/cactus1.js');
    var copied = grunt.file.read('tmp/test/dest/overrides/cactus1.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/overrides/node_modules/overrides/cactus2.js');
    copied = grunt.file.read('tmp/test/dest/overrides/cactus2.js');
    test.equal(source, copied, 'should copy lib file');

    test.done();
  },

  globs1: function(test) {
    test.expect(3);

    var source = grunt.file.read('test/fixtures/globs1/node_modules/globs1/dist/cactus1.js');
    var copied = grunt.file.read('tmp/test/dest/globs1/cactus1.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/globs1/node_modules/globs1/dist/cactus2.js');
    copied = grunt.file.read('tmp/test/dest/globs1/cactus2.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/globs1/node_modules/globs1/dist/sub/cactus3.js');
    copied = grunt.file.read('tmp/test/dest/globs1/sub/cactus3.js');
    test.equal(source, copied, 'should copy lib file');

    test.done();
  },

  globs2: function(test) {
    test.expect(3);

    var source = grunt.file.read('test/fixtures/globs2/node_modules/globs2/cactus1.js');
    var copied = grunt.file.read('tmp/test/dest/globs2/cactus1.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/globs2/node_modules/globs2/dist/cactus2.js');
    copied = grunt.file.read('tmp/test/dest/globs2/cactus2.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/globs2/node_modules/globs2/dist/cactus3.js');
    copied = grunt.file.read('tmp/test/dest/globs2/cactus3.js');
    test.equal(source, copied, 'should copy lib file');

    test.done();
  },

  main: function(test) {
    test.expect(2);

    var source = grunt.file.read('test/fixtures/libs/node_modules/cactus/dist/cactus.js');
    var copied = grunt.file.read('tmp/test/dest/default/cactus.js');
    test.equal(source, copied, 'should copy lib file');
    source = grunt.file.read('test/fixtures/libs/node_modules/pear/dist/pear.js');
    copied = grunt.file.read('tmp/test/dest/default/pear.js');
    test.equal(source, copied, 'should copy lib file');

    test.done();
  },

  'pkg-specific-simple': function(test) {
    test.expect(1);

    var source = grunt.file.read('test/fixtures/pkg-specific-simple/node_modules/pkg-specific-simple/dist/pss.js');
    var copied = grunt.file.read('tmp/test/dest/pkg-specific-simple/pss.js');
    test.equal(source, copied, 'should copy dist file');

    test.done();
  },

  'pkg-specific': function(test) {
    test.expect(1);

    var source = grunt.file.read('test/fixtures/pkg-specific/node_modules/pkg-specific/dist/ps.js');
    var copied = grunt.file.read('tmp/test/dest/pkg-specific/ps.js');
    test.equal(source, copied, 'should copy main file');

    test.done();
  },

  cjs: function(test) {
    test.expect(1);

    var expected = grunt.file.read('test/expected/cjs/cjs.js');
    var bundled = grunt.file.read('tmp/test/dest/cjs/cjs.js');
    test.equal(expected, bundled, 'should browserify');

    test.done();
  },
};


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

  angular.module('components.user')
    .controller('UserPasswordFormController', Controller);

  /** @ngInject */
  function Controller() {
    var ctrl = this;

    ctrl.$onInit = onInit;
    ctrl.doEvent = doEvent;

    function onInit() {
      ctrl.model = ctrl.password.attributes;
    }

    function doEvent(event) {
      return ctrl['on' + event]({
        $event: {
          password: ctrl.password
        }
      });
    }
  }
})();


text:
package com.sun.java.swing.plaf.windows;

import javax.swing.*;
import javax.swing.plaf.basic.*;
import javax.swing.plaf.ComponentUI;
import java.awt.event.*;

/**
 * Windows desktop pane.
 *

 * Warning:
 * Serialized objects of this class will not be compatible with
 * future Swing releases.  The current serialization support is appropriate
 * for short term storage or RMI between applications running the same
 * version of Swing.  A future release of Swing will provide support for
 * long term persistence.
 *
 * @author David Kloba
 */
public class WindowsDesktopPaneUI extends BasicDesktopPaneUI
{
    public static ComponentUI createUI(JComponent c) {
        return new WindowsDesktopPaneUI();
    }

    protected void installDesktopManager() {
        desktopManager = desktop.getDesktopManager();
        if(desktopManager == null) {
            desktopManager = new WindowsDesktopManager();
            desktop.setDesktopManager(desktopManager);
        }
    }

    protected void installDefaults() {
        super.installDefaults();
    }

    protected void installKeyboardActions() {
        super.installKeyboardActions();

        // Request focus if it isn't set.
        if(!desktop.requestDefaultFocus()) {
            desktop.requestFocus();
        }
    }
}


text:
/**
 * `onDisconnected` will be called when network disconneted
 * The script must be run in the console of `TEST_URL`
 */

function detectNetworkAccessibility({ TEST_URL, DETECT_INTERVAL = 30 * 1000, TIMEOUT = 3 * 1000 }, onDisconnected = alert) {
  const RETRY_INTERVAL = 5 * 1000;
  console.log(`Detecting network accessibility by fetching ${TEST_URL} at every ${DETECT_INTERVAL / 1000}s`);

  timeoutableFetch(fetch(TEST_URL), { TIMEOUT })
    .then(({ status, statusText }) => {
      console.log('%s %s', status, statusText);
      setTimeout(() => {
        detectNetworkAccessibility({ TEST_URL, DETECT_INTERVAL, TIMEOUT }, onDisconnected);
      }, DETECT_INTERVAL);
    })
    .catch((error) => {
      onDisconnected(error);
      console.info(`The script will re-detect after ${RETRY_INTERVAL / 1000}s`);

      setTimeout(() => {
        detectNetworkAccessibility({ TEST_URL, DETECT_INTERVAL, TIMEOUT }, onDisconnected);
      }, RETRY_INTERVAL);
    });
}

function timeoutableFetch(fetchPromise, { TIMEOUT }) {
  let abort = null;

  const abortPromise = new Promise((resolve, reject) => {
    abort = (msg) => { reject(msg); };
  });

  const abortablePromise = Promise.race([fetchPromise, abortPromise]);

  if (TIMEOUT) {
    setTimeout(() => {
      abort(`NET_TIME_OUT after ${TIMEOUT / 1000}s`);
    }, TIMEOUT);
  }

  return abortablePromise;
}

detectNetworkAccessibility({ TEST_URL: 'https://www.baidu.com/' });


text:
import utils

# import Crypto.Random.random as random
import random

import ecb_cbc_detection

UNKNOWN_STRING = """Um9sbGluJyBpbiBteSA1LjAKV2l0aCBteSByYWctdG9wIGRvd24gc28gbXkg
aGFpciBjYW4gYmxvdwpUaGUgZ2lybGllcyBvbiBzdGFuZGJ5IHdhdmluZyBq
dXN0IHRvIHNheSBoaQpEaWQgeW91IHN0b3A/IE5vLCBJIGp1c3QgZHJvdmUg
YnkK"""

KEY = utils.ByteArray.random(utils.AES_BLOCKSIZE_BYTES)
PREFIX = utils.ByteArray.random(random.randrange(1, utils.AES_BLOCKSIZE_BYTES))

def oracle(input_data):
    plaintext = utils.ByteArray()
    plaintext.extend(PREFIX)
    plaintext.extend(utils.ByteArray.fromString(input_data))
    plaintext.extend(utils.ByteArray.fromBase64(UNKNOWN_STRING))
    plaintext.pkcs7pad(utils.AES_BLOCKSIZE_BYTES)

    ret = utils.aes_ecb_encrypt(plaintext, KEY)
    return ret

def find_prefix_length(bs):
    zeros = "0" * bs * 2

    for i in range(bs):
        prefix = "0" * i + zeros
        print prefix
        ctext = oracle(prefix)
        blocks = ctext.blocksAsHexStrings(bs)

        last_block = blocks[0]
        for bindex, block in enumerate(blocks):
            if bindex == 0:
                continue
            if block == last_block:
                return bs - i

            last_block = block

    print "Can't find prefix length"

if __name__ == "__main__":
    print oracle("subidubisubidubi").asHexString()

    bs = None
    padding = None

    l = min([len(oracle("")) for _ in range(8)])
    print l
    for i in range(32):
        ctext = oracle("A" * (i+1))
        if len(ctext) != l:
            bs = abs(len(ctext) - l)
            padding = i
            break

    print "block size", bs
    print "padding", padding

    if ecb_cbc_detection.detect_ecb_cbc(oracle) != "ECB":
        print "Not ECB"

    unknown_string = ""
    blocks = {}

    prefix_length = find_prefix_length(bs)
    print "prefix_length", prefix_length
    l = l - prefix_length
    print "l", l
    rest = bs - prefix_length

    for unknown_block in range(l / bs):
        print unknown_block
        for i in range(bs):
            blocks.clear()

            for c in range(256):
                attempt = "A" * rest + "A" * (bs - i - 1) + unknown_string + chr(c)
                ctext = oracle(attempt)
                block = ctext.block(bs, unknown_block + 1).asHexString()
                blocks[block] = attempt

            input_data = "A" * rest + "A" * (bs - i - 1)
            ctext = oracle(input_data).block(bs, unknown_block + 1).asHexString()
            block = blocks[ctext]
            unknown_string += block[-1]

            if len(unknown_string) == l - padding:
                break

    print unknown_string


text:
<?php namespace Anomaly\FizlPages\Support;

/**
 * Class KeyTrait
 *
 * @package Anomaly\FizlPages\Support
 */
trait KeyTrait
{

    public function key($key)
    {
        return __NAMESPACE__ . '.' . $key;
    }

}


text:
<?php
global $wpdb;
$settings           = get_option( 'sfn_cart_addons', array() );
$terms              = get_terms( 'product_cat' );
$categories         = array();
$category_addons    = get_option( 'sfn_cart_addons_categories', array() );
$product_addons     = get_option( 'sfn_cart_addons_products', array() );

foreach ( $terms as $term ) {
    $used = false;
    foreach ( $category_addons as $c_addon ) {
        if ( $c_addon['category_id'] == $term->term_id ) {
            $used = true;
            break;
        }
    }

    if ( !$used ) {
        $categories[] = array('id' => $term->term_id, 'name' => $term->name);
    }
}
$js_categories = json_encode($categories);
?>

<?php _e('Cart Add-Ons', 'sfn_cart_addons'); ?>

    <?php if (isset($_GET['updated'])): ?>

<?php _e('Settings updated', 'sfn_cart_addons'); ?>

    <?php endif; ?>

    <form action="admin-post.php" method="post">

                        <?php _e('Display Title', 'sfn_cart_addons'); ?>

                        <?php $settings['header_title'] = isset( $settings['header_title'] ) ? $settings['header_title'] : ''; ?>
                        <input type="text" name="header_title" id="heading" value="<?php echo esc_attr($settings['header_title']); ?>" class="regular-text" />

                        <?php _e('Maximum number of upsells to show in the cart.', 'sfn_cart_addons'); ?>

                        <?php $settings['upsell_number'] = isset( $settings['upsell_number'] ) ? $settings['upsell_number'] : ''; ?>
                        <input type="text" name="upsell_number" id="number" value="<?php echo esc_attr($settings['upsell_number']); ?>" class="small-text" placeholder="6" />

                        <?php _e('Default Add-Ons', 'sfn_cart_addons'); ?>

                        <select id="default_products" name="default_products[]" class="ajax_chosen_select_products_and_variations" multiple data-placeholder="<?php _e('Search for a product…', 'woocommerce'); ?>" style="width: 600px">
                        <?php if ( !empty($settings['default_addons'])) foreach ( $settings['default_addons'] as $product_id ): ?>
                            <option value="<?php echo esc_attr($product_id); ?>" selected><?php echo strip_tags(get_the_title($product_id) .' - #'. $product_id); ?></option>
                        <?php endforeach; ?>
                        </select>

                            <?php _e('These products will be displayed on the cart page if there are no matching products and/or categories in the shopping cart from the settings below.', 'sfn_cart_addons'); ?>

<?php _e('Category Matches', 'sfn_cart_addons'); ?>

            <?php _e('If a product in the shopping cart matches a category defined below, the cart upsells will display the matching products to show. Set the priority order to define which category upsells should be shown when items in the shopping cart match multiple categories. Categories with the highest priority will be the upsells that are displayed when there are multiple category matches in the cart.', 'sfn_cart_addons'); ?>

                    <?php _e('Priority', 'sfn_cart_addons'); ?>
                    <?php _e('Category', 'sfn_cart_addons'); ?>
                    <?php _e('Product Add-Ons', 'sfn_cart_addons'); ?>

                <?php
                if ( !empty($category_addons) ):
                    $p = 0;
                    foreach ( $category_addons as $x => $addons ):
                        $p++;
                        $category   = get_term( $addons['category_id'], 'product_cat' );
                ?>

                        <?php echo $p; ?>
                        <input type="hidden" name="category_priorities[]" value="<?php echo $x; ?>" size="3" />

                        <?php echo stripslashes($category->name); ?>
                        <input type="hidden" name="category[<?php echo $x; ?>]" value="<?php echo $addons['category_id']; ?>" />

                        <select id="cselect_<?php echo $x; ?>" name="category_products[<?php echo $x; ?>][]" class="ajax_chosen_select_products_and_variations" multiple data-placeholder="<?php _e('Search for a product…', 'woocommerce'); ?>" style="width: 95%">
                        <?php foreach ($addons['products'] as $product_id): ?>
                            <option value="<?php echo $product_id; ?>" selected><?php echo strip_tags(get_the_title($product_id) .' - #'. $product_id); ?></option>
                        <?php endforeach; ?>
                        </select>

                        remove row

                <?php
                    endforeach;
                else:
                ?>

                    No add-ons defined

                <?php endif; ?>

        <button type="button" id="add_category" class="button"><?php _e('+ Add Category', 'sfn_cart_addons'); ?></button>

<?php _e('Product Matches', 'sfn_cart_addons'); ?>

            <?php _e('If a product in the shopping cart matches one of the products defined below, the cart upsells will display the matching products below to show. Set the priority to define which product upsells should be shown when items in the shopping cart are all defined. Products with the highest priority will be the upsells that are displayed when there are multiple products in the cart.', 'sfn_cart_addons'); ?>

                    <?php _e('Priority', 'sfn_cart_addons'); ?>
                    <?php _e('Product', 'sfn_cart_addons'); ?>
                    <?php _e('Product Add-Ons', 'sfn_cart_addons'); ?>

                <?php
                if ( !empty($product_addons) ):
                    $p = 0;
                    foreach ( $product_addons as $x => $addons ):
                        $p++;
                        $product    = sfn_get_product( $addons['product_id'] );
                ?>

                        <?php echo $p; ?>
                        <input type="hidden" name="product_priorities[]" value="<?php echo $x; ?>" size="3" />

                        <?php echo get_the_title( $addons['product_id'] ); ?>
                        <input type="hidden" name="product[<?php echo $x; ?>]" value="<?php echo $addons['product_id']; ?>" />
                        <select name="product[<?php echo $x; ?>]" class="product-select" style="display:none;">
                            <option value="<?php echo $addons['product_id']; ?>" selected><?php echo $addons['product_id']; ?></option>
                        </select>

                        <select id="pselect_<?php echo $x; ?>" name="product_products[<?php echo $x; ?>][]" class="ajax_chosen_select_products_and_variations" multiple data-placeholder="<?php _e('Search for a product…', 'woocommerce'); ?>" style="width: 95%">
                        <?php foreach ($addons['products'] as $product_id): ?>
                            <option value="<?php echo $product_id; ?>" selected><?php echo strip_tags(get_the_title($product_id) .' - #'. $product_id); ?></option>
                        <?php endforeach; ?>
                        </select>

                        remove row

                <?php
                    endforeach;
                else:
                ?>

                    No add-ons defined

                <?php endif; ?>

        <button type="button" id="add_product" class="button"><?php _e('+ Add Product', 'sfn_cart_addons'); ?></button>

            <input type="hidden" name="action" value="sfn_cart_addons_update_settings" />
            <input type="submit" name="save" value="<?php _e('Update Settings', 'sfn_cart_addons'); ?>" class="button-primary" />

<?php _e('Use shortcodes on any page or post', 'sfn_cart_addons'); ?>

[display-addons length=5 mode=loop] - Will use your theme's template
[display-addons length=4 mode=images_name] - Shows the product image along with the product name
[display-addons length=8 mode=images_name_price] - Will display product images with name and price

<?php _e('Use directly in your theme', 'sfn_cart_addons'); ?>

<?php if ( function_exists('sfn_display_cart_addons') ) sfn_display_cart_addons($num, $display); ?>
$num = the maximum number of add-ons to display, and $display can be one of the following: 'loop', 'images', 'images_name', 'images_name_price', 'names', 'names_price'

    </form>


text:
package org.paumard.spliterators;

import java.util.Objects;
import java.util.Spliterator;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Predicate;

/**
 * See the documentation and patterns to be used in this class in the {@link MoreSpliterators} factory class.
 *
 * @author José
 */
public class GatingSpliterator<E> implements Spliterator<E> {

    private final Spliterator<E> spliterator;
    private final Predicate<E> gate;
    private final AtomicBoolean hasMore = new AtomicBoolean(false);

    public static <E> GatingSpliterator<E> of(Spliterator<E> spliterator, Predicate<E> gate) {
        Objects.requireNonNull(spliterator);
        Objects.requireNonNull(gate);

        return new GatingSpliterator<>(spliterator, gate);
    }

    private GatingSpliterator(Spliterator<E> spliterator, Predicate<E> gate) {
        this.spliterator = spliterator;
        this.gate = gate;
    }

    @Override
    public boolean tryAdvance(Consumer<? super E> action) {

        return spliterator.tryAdvance(e -> {
            if (!hasMore.get() && gate.test(e)) {
                hasMore.set(true);
            }
            if (hasMore.get()) {
                action.accept(e);
            }
        });
    }

    @Override
    public Spliterator<E> trySplit() {
        Spliterator<E> split = this.spliterator.trySplit();
        return split == null ? null : new GatingSpliterator<>(split, gate);
    }

    @Override
    public long estimateSize() {
        if (hasMore.get()) {
            return this.spliterator.estimateSize();
        } else {
            return 0;
        }
    }

    @Override
    public int characteristics() {
        return this.spliterator.characteristics() & ~Spliterator.SIZED & ~Spliterator.SUBSIZED;
    }
}


text:
test-$(TEST_ARENA) += test-arena
test-test-arena-$(TEST_ARENA) := test.c test-arena.c

test-$(TEST_MEMDESC) += test-memdesc
test-test-memdesc-$(TEST_MEMDESC) := test.c test-memdesc.c

test-internal-$(TEST_COAP) += test-coap
test-internal-test-coap-$(TEST_COAP) := test.c test-coap.c
test-internal-test-coap-$(TEST_COAP)-deps := lib/comms/coap.o

test-$(TEST_FBP) += test-fbp
test-test-fbp-$(TEST_FBP) := test.c test-fbp.c

test-$(TEST_FBP_SCANNER) += test-fbp-scanner
test-test-fbp-scanner-$(TEST_FBP_SCANNER) := test.c test-fbp-scanner.c

test-$(TEST_FLOW) += test-flow
test-test-flow-$(TEST_FLOW) := test.c test-flow.c
test-test-flow-$(TEST_FLOW)-deps := \
	int.mod \
	timer.mod

test-$(TEST_FLOW_BUILDER) += test-flow-builder
test-test-flow-builder-$(TEST_FLOW_BUILDER) := test.c test-flow-builder.c

test-$(TEST_FLOW_PARSER) += test-flow-parser
test-test-flow-parser-$(TEST_FLOW_PARSER) := test.c test-flow-parser.c

test-$(TEST_JAVASCRIPT) += test-javascript
test-test-javascript-$(TEST_JAVASCRIPT) := test.c test-javascript.c

test-$(TEST_MAINLOOP) += test-mainloop
test-test-mainloop-$(TEST_MAINLOOP) := test-mainloop.c

test-$(TEST_MAINLOOP_LINUX) += test-mainloop-linux
test-test-mainloop-linux-$(TEST_MAINLOOP_LINUX) := test-mainloop-linux.c

test-$(TEST_MAINLOOP_THREADS) += test-mainloop-threads
test-test-mainloop-threads-$(TEST_MAINLOOP_THREADS) := test-mainloop-threads.c
test-test-mainloop-threads-$(TEST_MAINLOOP_THREADS)-extra-ldflags += $(PTHREAD_H_LDFLAGS)

test-$(TEST_MAINLOOP_THREADS_SOL_RUN) += test-mainloop-threads-sol-run
test-test-mainloop-threads-sol-run-$(TEST_MAINLOOP_THREADS_SOL_RUN) := test-mainloop-threads-sol-run.c
test-test-mainloop-threads-sol-run-$(TEST_MAINLOOP_THREADS_SOL_RUN)-extra-ldflags += $(PTHREAD_H_LDFLAGS)

test-$(TEST_MAINLOOP_GLIB_INTEGRATION) += test-mainloop-glib-integration
test-test-mainloop-glib-integration-$(TEST_MAINLOOP_GLIB_INTEGRATION) := test-mainloop-glib-integration.c
test-test-mainloop-glib-integration-$(TEST_MAINLOOP_GLIB_INTEGRATION)-extra-cflags += $(GLIB_CFLAGS)
test-test-mainloop-glib-integration-$(TEST_MAINLOOP_GLIB_INTEGRATION)-extra-ldflags += $(GLIB_LDFLAGS)

test-$(TEST_MAINLOOP_IMPLEMENTATION) += test-mainloop-implementation
test-test-mainloop-implementation-$(TEST_MAINLOOP_IMPLEMENTATION) := test-mainloop-implementation.c

test-$(TEST_MONITORS) += test-monitors
test-test-monitors-$(TEST_MONITORS) := test.c test-monitors.c

test-$(TEST_STR_SLICE) += test-str-slice
test-test-str-slice-$(TEST_STR_SLICE) := test.c test-str-slice.c

test-$(TEST_STR_SPLIT) += test-str-split
test-test-str-split-$(TEST_STR_SPLIT) := test.c test-str-split.c

test-$(TEST_STR_TABLE) += test-str-table
test-test-str-table-$(TEST_STR_TABLE) := test.c test-str-table.c

test-$(TEST_VECTOR) += test-vector
test-test-vector-$(TEST_VECTOR) := test.c test-vector.c

test-$(TEST_LIST) += test-list
test-test-list-$(TEST_LIST) := test.c test-list.c

test-$(TEST_BUFFER) += test-buffer
test-test-buffer-$(TEST_BUFFER) := test.c test-buffer.c

test-$(TEST_JSON) += test-json
test-test-json-$(TEST_JSON) := test.c test-json.c

test-$(TEST_UTIL) += test-util
test-test-util-$(TEST_UTIL) := test.c test-util.c

test-$(TEST_COMPOSED_TYPE) += test-composed-type
test-test-composed-type-$(TEST_COMPOSED_TYPE) := test.c test-composed-type.c

test-$(TEST_MESSAGE_DIGEST) += test-message-digest
test-test-message-digest-$(TEST_MESSAGE_DIGEST) := test.c test-message-digest.c

test-$(TEST_PERSISTENCE_MEMMAP) += test-persistence-memmap
test-test-persistence-memmap-$(TEST_PERSISTENCE_MEMMAP) := test.c test-persistence-memmap.c

test-$(TEST_HTTP) += test-http
test-test-http-$(TEST_HTTP) := test.c test-http.c

test-$(TEST_CERTIFICATE) += test-certificate
test-test-certificate-$(TEST_CERTIFICATE) := test.c test-certificate.c

test-$(TEST_LWM2M) += test-lwm2m
test-test-lwm2m-$(TEST_LWM2M) := test.c test-lwm2m.c

test-$(TEST_NETWORK) += test-network
test-test-network-$(TEST_NETWORK) := test.c test-network.c

test-$(TEST_BLUETOOTH) += test-bluetooth
test-test-bluetooth-$(TEST_BLUETOOTH) := test.c test-bluetooth.c


text:
dir=$(dirname $0)

. $dir/common.sh

env=${1:-"dev"}

echo "Env is $env"

echo "Checking for unstaged changes...";
txt=$(git diff --name-only HEAD)
test -z "$txt" || { printerror "directory has unstaged changes:" "$txt" ; exit 1; }

logstr "Update started at `git rev-parse HEAD`"

git pull
. $dir/build.sh

logstr "Update finished at `git rev-parse HEAD`"


text:
package com.hkm.ezwebview.bridge;

public class DefaultHandler implements BridgeHandler{

	String TAG = "DefaultHandler";

	@Override
	public void handler(String data, CallBackFunction function) {
		if(function != null){
			function.onCallBack("DefaultHandler response data");
		}
	}

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>NcHIPertCompPB: NumCosmo Reference Manual</title>
<meta name="generator" content="DocBook XSL Stylesheets Vsnapshot" />
<link rel="home" href="index.html" title="NumCosmo Reference Manual" />
<link rel="up" href="ch07s02.html" title="Perturbation components" />
<link rel="prev" href="NcHIPertComp.html" title="NcHIPertComp" />
<link rel="next" href="ch07s03.html" title="CLASS Backend" />
<meta name="generator" content="GTK-Doc V1.33.1 (XML mode)" />
<link rel="stylesheet" href="style.css" type="text/css" />
<link rel="stylesheet" href="container.css" type="text/css" />

Top  |
                  Description  |
                  Object Hierarchy  |
                  Properties

NcHIPertCompPB

NcHIPertCompPB — Photon-Baryon plasma compoment

Functions

<colgroup>
<col width="150px" class="functions_proto_type" />
<col class="functions_proto_name" />
</colgroup>

#define

NC_HIPERT_COMP_PB_VAR_F_G()

NcHIPertCompPB *

nc_hipert_comp_pb_new ()

NcHIPertCompPB *

nc_hipert_comp_pb_ref ()

void

nc_hipert_comp_pb_free ()

void

nc_hipert_comp_pb_clear ()

void

nc_hipert_comp_pb_set_lmax ()

guint

nc_hipert_comp_pb_get_lmax ()

Properties

<colgroup>
<col width="150px" class="properties_type" />
<col width="300px" class="properties_name" />
<col width="200px" class="properties_flags" />
</colgroup>

guint
l-max
Read / Write / Construct

Types and Values

<colgroup>
<col width="150px" class="other_proto_type" />
<col class="other_proto_name" />
</colgroup>

enum
NcHIPertCompPBVar

Object Hierarchy

    GEnum
    ╰── NcHIPertCompPBVar
    GObject
    ╰── NcHIPertComp
        ╰── NcHIPertCompPB

Description

FIXME

Functions

NC_HIPERT_COMP_PB_VAR_F_G()

#define NC_HIPERT_COMP_PB_VAR_F_G(ell) (NC_HIPERT_COMP_PB_VAR_F_G3 + (ell) - 3)

nc_hipert_comp_pb_new ()

NcHIPertCompPB *
nc_hipert_comp_pb_new (void);

Creates a new NcHIPertCompPB.

Returns

the newly created NcHIPertCompPB.

[<acronym title="The caller owns the data, and is responsible for free it.">transfer full</acronym>]

nc_hipert_comp_pb_ref ()

NcHIPertCompPB *
nc_hipert_comp_pb_ref (NcHIPertCompPB *pb);

Increases the reference count of pb
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

pb

a NcHIPertCompPB

Returns

pb
.

[<acronym title="The caller owns the data, and is responsible for free it.">transfer full</acronym>]

nc_hipert_comp_pb_free ()

void
nc_hipert_comp_pb_free (NcHIPertCompPB *pb);

Decreases the reference count of pb
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

pb

a NcHIPertCompPB

nc_hipert_comp_pb_clear ()

void
nc_hipert_comp_pb_clear (NcHIPertCompPB **pb);

Decreases the reference count of *pb
 and sets the pointer *pb
 to NULL.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

pb

a NcHIPertCompPB

nc_hipert_comp_pb_set_lmax ()

void
nc_hipert_comp_pb_set_lmax (NcHIPertCompPB *pb,
                            guint lmax);

Sets the maximum momentum of the photon distribution to $\ell_\mathrm{max}=$lmax
.

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

pb

a NcHIPertCompPB

lmax

the maximum momentum of the photon distribution $\ell_\mathrm{max}$

nc_hipert_comp_pb_get_lmax ()

guint
nc_hipert_comp_pb_get_lmax (NcHIPertCompPB *pb);

Parameters

<colgroup>
<col width="150px" class="parameters_name" />
<col class="parameters_description" />
<col width="200px" class="parameters_annotations" />
</colgroup>

pb

a NcHIPertCompPB

Returns

 the maximum momentum of the photon distribution to $\ell_\mathrm{max}$.

Types and Values

enum NcHIPertCompPBVar

Photon-baryon component variables

Members

<colgroup>
<col width="300px" class="enum_members_name" />
<col class="enum_members_description" />
<col width="200px" class="enum_members_annotations" />
</colgroup>

NC_HIPERT_COMP_PB_VAR_DELTA_B

$\delta_b+3\psi$

NC_HIPERT_COMP_PB_VAR_V_B

$\mathcal{V}_b$

NC_HIPERT_COMP_PB_VAR_DELTA_G

$\delta_\gamma+3\psi$

NC_HIPERT_COMP_PB_VAR_V_G

$\mathcal{V}_\gamma$

NC_HIPERT_COMP_PB_VAR_THETA_G

$\theta_\gamma$

NC_HIPERT_COMP_PB_VAR_F_G3

$\mathcal{F}_{\gamma3}$

Property Details

The "l-max" property

  "l-max"                    guint

l_max.

Owner: NcHIPertCompPB

Flags: Read / Write / Construct

Allowed values: >= 4

Default value: 12

Generated by GTK-Doc V1.33.1