text:
from pytest import raises

from revscoring.dependencies.dependent import Dependent
from revscoring.dependencies.functions import (dig, draw, expand,
                                               normalize_context, solve)
from revscoring.errors import DependencyError, DependencyLoop

def test_solve():
    # Simple functions
    assert solve(lambda: "foo") == "foo"
    assert list(solve([lambda: "foo", lambda: "bar"])) == ["foo", "bar"]

    # Dependents
    foo = Dependent("foo", lambda: "foo")
    bar = Dependent("bar", lambda: "bar")
    foobar = Dependent("foobar", lambda foo, bar: foo + bar,
                       depends_on=[foo, bar])
    assert solve(foobar) == "foobar"
    assert list(solve([foo, bar, foobar])) == ["foo", "bar", "foobar"]

    # Cache
    assert solve(foobar, cache={foobar: "foobaz"}) == "foobaz"
    assert solve(foobar, cache={bar: "baz"}) == "foobaz"
    assert solve(foobar, cache={"dependent.bar": "baz"}) == "foobaz"

    # Context
    mybar = Dependent("bar", lambda: "baz")
    assert solve(foobar, context={mybar}) == "foobaz"
    assert solve(foobar, context={mybar: mybar}) == "foobaz"
    assert solve(foobar, context={bar: mybar}) == "foobaz"
    assert solve(foobar, context={bar: lambda: "baz"}) == "foobaz"

    solving_profile = {}
    solve(foobar, profile=solving_profile)
    # print(solving_profile)
    assert set(solving_profile.keys()) == {foo, bar, foobar}

    list(solve([foo, bar, foobar], profile=solving_profile))
    # print(solving_profile)
    assert len(solving_profile[foobar]) == 2

def test_unsolveable():
    with raises(RuntimeError):
        solve(5)

def test_dependency_loop():
    with raises(DependencyLoop):
        foo = Dependent("foo")
        bar = Dependent("bar", depends_on=[foo])
        my_foo = Dependent("foo", depends_on=[bar])

        solve(bar, context={my_foo})

def test_dependency_error():
    with raises(DependencyError):
        def derror():
            raise DependencyError()
        raises_error = Dependent("foo", derror)

        solve(raises_error)

def test_cache_preservation():
    foo = Dependent("foo")
    bar = Dependent("bar", depends_on=[foo], process=lambda foo: foo + "bar")
    fooz = Dependent("foo", process=lambda: "fooz")

    cache = {foo: "foo"}
    values = list(solve([foo, bar], cache=cache))
    assert values == ["foo", "foobar"]
    assert cache[bar] == "foobar"

    cache = {}
    values = list(solve([foo, bar], context={fooz}, cache=cache))
    assert values == ["fooz", "foozbar"]
    assert cache[bar] == "foozbar"

def test_expand():
    foo = Dependent("foo", lambda: "foo")
    bar = Dependent("bar", lambda: "bar")
    foobar = Dependent("foobar", lambda foo, bar: foo + bar,
                       depends_on=[foo, bar])

    derp = Dependent("derp", lambda: "derp")
    fooderp = Dependent("fooderp", lambda foo, derp: foo + derp,
                        depends_on=[foo, derp])

    dependents = list(expand(foobar))
    assert len(dependents) == 3
    assert set(dependents) == {foo, bar, foobar}

    dependents = list(expand([fooderp, foobar]))
    assert len(dependents) == 5
    assert set(dependents) == {derp, fooderp, foo, bar, foobar}

def test_dig():
    foo = Dependent("foo", lambda: "foo")
    bar = Dependent("bar", lambda: "bar")
    foobar = Dependent("foobar", lambda foo, bar: foo + bar,
                       depends_on=[foo, bar])
    foobar_foobar = Dependent("foobar_foobar",
                              lambda foobar1, foobar2: foobar1 + "_" + foobar2,
                              depends_on=[foobar, foobar])

    roots = list(dig(foobar_foobar))
    assert len(roots) == 2
    assert set(roots) == {foo, bar}

    roots = list(dig([foobar, foo, bar]))
    assert len(roots) == 2
    assert set(roots) == {foo, bar}

    roots = list(dig(foobar_foobar, cache={foo}))
    assert len(roots) == 1
    assert set(roots) == {bar}

    myfoobar = Dependent("foobar", lambda foo1, foo2: foo1 + foo2,
                         depends_on=[foo, foo])
    roots = list(dig(foobar_foobar, context={myfoobar}))
    assert len(roots) == 1
    assert set(roots) == {foo}

    def get_5():
        return 5

    myfoobar = Dependent("foobar", lambda my_5: 5 ** 2,
                         depends_on=[get_5])
    roots = list(dig(foobar_foobar, context={myfoobar}))
    assert len(roots) == 1
    assert set(roots) == {get_5}

def test_draw():
    foo = Dependent("foo", lambda: "foo")
    bar = Dependent("bar", lambda foo: foo + "bar", dependencies=[foo])

    draw(bar)  # Does not throw an error
    draw(bar, cache={foo: "CACHED"})  # Does not throw an error

def test_not_implemented_error():
    with raises(DependencyError):
        foo = Dependent("foo")
        solve(foo)

def test_normalize_context_fail():
    with raises(TypeError):
        normalize_context(15)


text:
package org.pentaho.di.ui.job.entries.writetofile;

import java.nio.charset.Charset;
import java.util.ArrayList;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.FocusListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.core.util.Utils;
import org.pentaho.di.i18n.BaseMessages;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.job.entries.writetofile.JobEntryWriteToFile;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.core.PropsUI;
import org.pentaho.di.ui.core.events.dialog.FilterType;
import org.pentaho.di.ui.core.events.dialog.SelectionAdapterFileDialogTextVar;
import org.pentaho.di.ui.core.events.dialog.SelectionAdapterOptions;
import org.pentaho.di.ui.core.events.dialog.SelectionOperation;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.ComboVar;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.ui.trans.step.BaseStepDialog;

/**
 * This dialog allows you to edit the Write to file job entry settings.
 *
 * @author Samatar Hassan
 * @since 28-01-2007
 */
public class JobEntryWriteToFileDialog extends JobEntryDialog implements JobEntryDialogInterface {
  private static Class<?> PKG = JobEntryWriteToFile.class; // for i18n purposes, needed by Translator2!!

  private static final String[] FILETYPES = new String[] { BaseMessages.getString(
    PKG, "JobWriteToFile.Filetype.All" ) };

  private Label wlName;
  private Text wName;
  private FormData fdlName, fdName;

  private Label wlFilename;
  private Button wbFilename;
  private TextVar wFilename;
  private FormData fdlFilename, fdbFilename, fdFilename;

  private Label wlCreateParentFolder;
  private Button wCreateParentFolder;
  private FormData fdlCreateParentFolder, fdCreateParentFolder;

  private Label wlAppendFile;
  private Button wAppendFile;
  private FormData fdlAppendFile, fdAppendFile;

  private Label wlEncoding;
  private ComboVar wEncoding;
  private FormData fdlEncoding, fdEncoding;

  private Group wFileGroup;
  private FormData fdFileGroup;

  private Group wContentGroup;
  private FormData fdContentGroup;

  private Label wlContent;
  private Text wContent;
  private FormData fdlContent, fdContent;

  private Button wOK, wCancel;
  private Listener lsOK, lsCancel;

  private JobEntryWriteToFile jobEntry;
  private Shell shell;

  private SelectionAdapter lsDef;

  private boolean changed;

  private boolean gotEncodings = false;

  public JobEntryWriteToFileDialog( Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta ) {
    super( parent, jobEntryInt, rep, jobMeta );
    jobEntry = (JobEntryWriteToFile) jobEntryInt;
    if ( this.jobEntry.getName() == null ) {
      this.jobEntry.setName( BaseMessages.getString( PKG, "JobWriteToFile.Name.Default" ) );
    }
  }

  public JobEntryInterface open() {
    Shell parent = getParent();
    Display display = parent.getDisplay();

    shell = new Shell( parent, props.getJobsDialogStyle() );
    props.setLook( shell );
    JobDialog.setShellImage( shell, jobEntry );

    ModifyListener lsMod = new ModifyListener() {
      public void modifyText( ModifyEvent e ) {
        jobEntry.setChanged();
      }
    };
    changed = jobEntry.hasChanged();

    FormLayout formLayout = new FormLayout();
    formLayout.marginWidth = Const.FORM_MARGIN;
    formLayout.marginHeight = Const.FORM_MARGIN;

    shell.setLayout( formLayout );
    shell.setText( BaseMessages.getString( PKG, "JobWriteToFile.Title" ) );

    int middle = props.getMiddlePct();
    int margin = Const.MARGIN;

    // Filename line
    wlName = new Label( shell, SWT.RIGHT );
    wlName.setText( BaseMessages.getString( PKG, "JobWriteToFile.Name.Label" ) );
    props.setLook( wlName );
    fdlName = new FormData();
    fdlName.left = new FormAttachment( 0, 0 );
    fdlName.right = new FormAttachment( middle, -margin );
    fdlName.top = new FormAttachment( 0, margin );
    wlName.setLayoutData( fdlName );
    wName = new Text( shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
    props.setLook( wName );
    wName.addModifyListener( lsMod );
    fdName = new FormData();
    fdName.left = new FormAttachment( middle, 0 );
    fdName.top = new FormAttachment( 0, margin );
    fdName.right = new FormAttachment( 100, 0 );
    wName.setLayoutData( fdName );

    wOK = new Button( shell, SWT.PUSH );
    wOK.setText( BaseMessages.getString( PKG, "System.Button.OK" ) );
    wCancel = new Button( shell, SWT.PUSH );
    wCancel.setText( BaseMessages.getString( PKG, "System.Button.Cancel" ) );

    BaseStepDialog.positionBottomButtons( shell, new Button[] { wOK, wCancel }, margin, null );

    // ////////////////////////
    // START OF File GROUP
    // ////////////////////////

    wFileGroup = new Group( shell, SWT.SHADOW_NONE );
    props.setLook( wFileGroup );
    wFileGroup.setText( BaseMessages.getString( PKG, "JobWriteToFile.Group.File.Label" ) );

    FormLayout FileGroupLayout = new FormLayout();
    FileGroupLayout.marginWidth = 10;
    FileGroupLayout.marginHeight = 10;
    wFileGroup.setLayout( FileGroupLayout );

    // Filename line
    wlFilename = new Label( wFileGroup, SWT.RIGHT );
    wlFilename.setText( BaseMessages.getString( PKG, "JobWriteToFile.Filename.Label" ) );
    props.setLook( wlFilename );
    fdlFilename = new FormData();
    fdlFilename.left = new FormAttachment( 0, 0 );
    fdlFilename.top = new FormAttachment( wName, margin );
    fdlFilename.right = new FormAttachment( middle, -margin );
    wlFilename.setLayoutData( fdlFilename );

    wbFilename = new Button( wFileGroup, SWT.PUSH | SWT.CENTER );
    props.setLook( wbFilename );
    wbFilename.setText( BaseMessages.getString( PKG, "System.Button.Browse" ) );
    fdbFilename = new FormData();
    fdbFilename.right = new FormAttachment( 100, 0 );
    fdbFilename.top = new FormAttachment( wName, 0 );
    wbFilename.setLayoutData( fdbFilename );

    wFilename = new TextVar( jobMeta, wFileGroup, SWT.SINGLE | SWT.LEFT | SWT.BORDER );
    props.setLook( wFilename );
    wFilename.addModifyListener( lsMod );
    fdFilename = new FormData();
    fdFilename.left = new FormAttachment( middle, 0 );
    fdFilename.top = new FormAttachment( wName, margin );
    fdFilename.right = new FormAttachment( wbFilename, -margin );
    wFilename.setLayoutData( fdFilename );

    // Whenever something changes, set the tooltip to the expanded version:
    wFilename.addModifyListener( new ModifyListener() {
      public void modifyText( ModifyEvent e ) {
        wFilename.setToolTipText( jobMeta.environmentSubstitute( wFilename.getText() ) );
      }
    } );

    wbFilename.addSelectionListener( new SelectionAdapterFileDialogTextVar( jobMeta.getLogChannel(), wFilename, jobMeta,
      new SelectionAdapterOptions( SelectionOperation.SAVE_TO,
        new FilterType[] { FilterType.ALL }, FilterType.ALL  ) ) );

    wlCreateParentFolder = new Label( wFileGroup, SWT.RIGHT );
    wlCreateParentFolder.setText( BaseMessages.getString( PKG, "JobWriteToFile.CreateParentFolder.Label" ) );
    props.setLook( wlCreateParentFolder );
    fdlCreateParentFolder = new FormData();
    fdlCreateParentFolder.left = new FormAttachment( 0, 0 );
    fdlCreateParentFolder.top = new FormAttachment( wFilename, margin );
    fdlCreateParentFolder.right = new FormAttachment( middle, -margin );
    wlCreateParentFolder.setLayoutData( fdlCreateParentFolder );
    wCreateParentFolder = new Button( wFileGroup, SWT.CHECK );
    props.setLook( wCreateParentFolder );
    wCreateParentFolder
      .setToolTipText( BaseMessages.getString( PKG, "JobWriteToFile.CreateParentFolder.Tooltip" ) );
    fdCreateParentFolder = new FormData();
    fdCreateParentFolder.left = new FormAttachment( middle, 0 );
    fdCreateParentFolder.top = new FormAttachment( wFilename, margin );
    fdCreateParentFolder.right = new FormAttachment( 100, 0 );
    wCreateParentFolder.setLayoutData( fdCreateParentFolder );
    wCreateParentFolder.addSelectionListener( new SelectionAdapter() {
      public void widgetSelected( SelectionEvent e ) {
        jobEntry.setChanged();
      }
    } );

    wlAppendFile = new Label( wFileGroup, SWT.RIGHT );
    wlAppendFile.setText( BaseMessages.getString( PKG, "JobWriteToFile.AppendFile.Label" ) );
    props.setLook( wlAppendFile );
    fdlAppendFile = new FormData();
    fdlAppendFile.left = new FormAttachment( 0, 0 );
    fdlAppendFile.top = new FormAttachment( wCreateParentFolder, margin );
    fdlAppendFile.right = new FormAttachment( middle, -margin );
    wlAppendFile.setLayoutData( fdlAppendFile );
    wAppendFile = new Button( wFileGroup, SWT.CHECK );
    props.setLook( wAppendFile );
    wAppendFile.setToolTipText( BaseMessages.getString( PKG, "JobWriteToFile.AppendFile.Tooltip" ) );
    fdAppendFile = new FormData();
    fdAppendFile.left = new FormAttachment( middle, 0 );
    fdAppendFile.top = new FormAttachment( wCreateParentFolder, margin );
    fdAppendFile.right = new FormAttachment( 100, 0 );
    wAppendFile.setLayoutData( fdAppendFile );
    wAppendFile.addSelectionListener( new SelectionAdapter() {
      public void widgetSelected( SelectionEvent e ) {
        jobEntry.setChanged();
      }
    } );

    fdFileGroup = new FormData();
    fdFileGroup.left = new FormAttachment( 0, margin );
    fdFileGroup.top = new FormAttachment( wName, margin );
    fdFileGroup.right = new FormAttachment( 100, -margin );
    wFileGroup.setLayoutData( fdFileGroup );

    // ///////////////////////////////////////////////////////////
    // / END OF File GROUP
    // ///////////////////////////////////////////////////////////

    // /////////////////////////
    // START OF Content GROUP
    // ////////////////////////

    wContentGroup = new Group( shell, SWT.SHADOW_NONE );
    props.setLook( wContentGroup );
    wContentGroup.setText( BaseMessages.getString( PKG, "JobWriteToFile.Group.Content.Label" ) );

    FormLayout ContentGroupLayout = new FormLayout();
    ContentGroupLayout.marginWidth = 10;
    ContentGroupLayout.marginHeight = 10;
    wContentGroup.setLayout( ContentGroupLayout );

    // Encoding
    wlEncoding = new Label( wContentGroup, SWT.RIGHT );
    wlEncoding.setText( BaseMessages.getString( PKG, "JobWriteToFile.Encoding.Label" ) );
    props.setLook( wlEncoding );
    fdlEncoding = new FormData();
    fdlEncoding.left = new FormAttachment( 0, -margin );
    fdlEncoding.top = new FormAttachment( wAppendFile, margin );
    fdlEncoding.right = new FormAttachment( middle, -margin );
    wlEncoding.setLayoutData( fdlEncoding );
    wEncoding = new ComboVar( jobMeta, wContentGroup, SWT.BORDER | SWT.READ_ONLY );
    wEncoding.setEditable( true );
    props.setLook( wEncoding );
    wEncoding.addModifyListener( lsMod );
    fdEncoding = new FormData();
    fdEncoding.left = new FormAttachment( middle, 0 );
    fdEncoding.top = new FormAttachment( wAppendFile, margin );
    fdEncoding.right = new FormAttachment( 100, 0 );
    wEncoding.setLayoutData( fdEncoding );
    wEncoding.addFocusListener( new FocusListener() {
      public void focusLost( org.eclipse.swt.events.FocusEvent e ) {
      }

      public void focusGained( org.eclipse.swt.events.FocusEvent e ) {
        setEncodings();
      }
    } );

    wlContent = new Label( wContentGroup, SWT.RIGHT );
    wlContent.setText( BaseMessages.getString( PKG, "JobWriteToFile.Content.Label" ) );
    props.setLook( wlContent );
    fdlContent = new FormData();
    fdlContent.left = new FormAttachment( 0, 0 );
    fdlContent.top = new FormAttachment( wEncoding, margin );
    fdlContent.right = new FormAttachment( middle, -margin );
    wlContent.setLayoutData( fdlContent );

    wContent = new Text( wContentGroup, SWT.MULTI | SWT.LEFT | SWT.BORDER | SWT.H_SCROLL | SWT.V_SCROLL );
    props.setLook( wContent, PropsUI.WIDGET_STYLE_FIXED );
    wContent.addModifyListener( lsMod );
    fdContent = new FormData();
    fdContent.left = new FormAttachment( middle, 0 );
    fdContent.top = new FormAttachment( wEncoding, margin );
    fdContent.right = new FormAttachment( 100, 0 );
    fdContent.bottom = new FormAttachment( 100, -margin );
    wContent.setLayoutData( fdContent );

    fdContentGroup = new FormData();
    fdContentGroup.left = new FormAttachment( 0, margin );
    fdContentGroup.top = new FormAttachment( wFileGroup, margin );
    fdContentGroup.right = new FormAttachment( 100, -margin );
    fdContentGroup.bottom = new FormAttachment( wOK, -margin );
    wContentGroup.setLayoutData( fdContentGroup );

    // ///////////////////////////////////////////////////////////
    // / END OF Content GROUP
    // ///////////////////////////////////////////////////////////

    // Add listeners
    lsCancel = new Listener() {
      public void handleEvent( Event e ) {
        cancel();
      }
    };
    lsOK = new Listener() {
      public void handleEvent( Event e ) {
        ok();
      }
    };

    wCancel.addListener( SWT.Selection, lsCancel );
    wOK.addListener( SWT.Selection, lsOK );

    lsDef = new SelectionAdapter() {
      public void widgetDefaultSelected( SelectionEvent e ) {
        ok();
      }
    };

    wName.addSelectionListener( lsDef );
    wFilename.addSelectionListener( lsDef );

    // Detect X or ALT-F4 or something that kills this window...
    shell.addShellListener( new ShellAdapter() {
      public void shellClosed( ShellEvent e ) {
        cancel();
      }
    } );

    getData();

    BaseStepDialog.setSize( shell );

    shell.open();
    while ( !shell.isDisposed() ) {
      if ( !display.readAndDispatch() ) {
        display.sleep();
      }
    }
    return jobEntry;
  }

  private void setEncodings() {
    // Encoding of the text file:
    if ( !gotEncodings ) {
      gotEncodings = true;

      wEncoding.removeAll();
      java.util.List<Charset> values = new ArrayList<Charset>( Charset.availableCharsets().values() );
      for ( Charset charSet : values ) {
        wEncoding.add( charSet.displayName() );
      }
      // Now select the default!
      String defEncoding = Const.getEnvironmentVariable( "file.encoding", "UTF-8" );
      int idx = Const.indexOfString( defEncoding, wEncoding.getItems() );
      if ( idx >= 0 ) {
        wEncoding.select( idx );
      }
    }
  }

  public void dispose() {
    WindowProperty winprop = new WindowProperty( shell );
    props.setScreen( winprop );
    shell.dispose();
  }

  /**
   * Copy information from the meta-data input to the dialog fields.
   */
  public void getData() {
    wName.setText( Const.nullToEmpty( jobEntry.getName() ) );
    wFilename.setText( Const.nullToEmpty( jobEntry.getFilename() ) );
    wCreateParentFolder.setSelection( jobEntry.isCreateParentFolder() );
    wAppendFile.setSelection( jobEntry.isAppendFile() );
    wContent.setText( Const.nullToEmpty( jobEntry.getContent() ) );
    wEncoding.setText( Const.nullToEmpty( jobEntry.getEncoding() ) );

    wName.selectAll();
    wName.setFocus();
  }

  private void cancel() {
    jobEntry.setChanged( changed );
    jobEntry = null;
    dispose();
  }

  private void ok() {
    if ( Utils.isEmpty( wName.getText() ) ) {
      MessageBox mb = new MessageBox( shell, SWT.OK | SWT.ICON_ERROR );
      mb.setText( BaseMessages.getString( PKG, "System.StepJobEntryNameMissing.Title" ) );
      mb.setMessage( BaseMessages.getString( PKG, "System.JobEntryNameMissing.Msg" ) );
      mb.open();
      return;
    }
    jobEntry.setName( wName.getText() );
    jobEntry.setFilename( wFilename.getText() );
    jobEntry.setCreateParentFolder( wCreateParentFolder.getSelection() );
    jobEntry.setAppendFile( wAppendFile.getSelection() );
    jobEntry.setContent( wContent.getText() );
    jobEntry.setEncoding( wEncoding.getText() );

    dispose();
  }

  public boolean evaluates() {
    return true;
  }

  public boolean isUnconditional() {
    return false;
  }
}

redpajama_set_name: RedPajamaGithub


text:
namespace xcdat {

//! A compressed string dictionary based on an improved double-array trie.
//! 'BcVector' is the data type of Base and Check vectors.
template <class BcVector>
class trie {
  public:
    using trie_type = trie<BcVector>;
    using bc_vector_type = BcVector;

    //! The type identifier.
    static constexpr std::uint32_t type_id = bc_vector_type::l1_bits;

  private:
    std::uint64_t m_num_keys = 0;
    code_table m_table;
    bit_vector m_terms;
    bc_vector_type m_bcvec;
    tail_vector m_tvec;

  public:
    //! Default constructor
    trie() = default;

    //! Default destructor
    virtual ~trie() = default;

    //! Copy constructor (deleted)
    trie(const trie&) = delete;

    //! Copy constructor (deleted)
    trie& operator=(const trie&) = delete;

    //! Move constructor
    trie(trie&&) noexcept = default;

    //! Move constructor
    trie& operator=(trie&&) noexcept = default;

    //! Build the trie from the input keywords, which are lexicographically sorted and unique.
    //!
    //! If bin_mode = false, the NULL character is used for the termination of a keyword.
    //! If bin_mode = true, bit flags are used istead, and the keywords can contain NULL characters.
    //! If the input keywords contain NULL characters, bin_mode will be forced to be set to true.
    //!
    //! The type 'Strings' and 'Strings::value_type' should be a random iterable container such as std::vector.
    //! Precisely, they should support the following operations:
    //!  - size() returns the container size.
    //!  - operator[](i) accesses the i-th element.
    //!  - begin() returns the iterator to the beginning.
    //!  - end() returns the iterator to the end.
    //! The type 'Strings::value_type::value_type' should be one-byte integer type such as 'char'.
    template <class Strings>
    trie(const Strings& keys, bool bin_mode = false) : trie(trie_builder(keys, bc_vector_type::l1_bits, bin_mode)) {
        static_assert(sizeof(char) == sizeof(typename Strings::value_type::value_type));
    }

    //! Check if the binary mode.
    inline bool bin_mode() const {
        return m_tvec.bin_mode();
    }

    //! Get the number of stored keywords.
    inline std::uint64_t num_keys() const {
        return m_num_keys;
    }

    //! Get the alphabet size.
    inline std::uint64_t alphabet_size() const {
        return m_table.alphabet_size();
    }

    //! Get the maximum length of keywords.
    inline std::uint64_t max_length() const {
        return m_table.max_length();
    }

    //! Get the number of trie nodes.
    inline std::uint64_t num_nodes() const {
        return m_bcvec.num_nodes();
    }

    //! Get the number of DA units.
    inline std::uint64_t num_units() const {
        return m_bcvec.num_units();
    }

    //! Get the number of unused DA units.
    inline std::uint64_t num_free_units() const {
        return m_bcvec.num_free_units();
    }

    //! Get the length of TAIL vector.
    inline std::uint64_t tail_length() const {
        return m_tvec.size();
    }

    //! Lookup the ID of the keyword.
    inline std::optional<std::uint64_t> lookup(std::string_view key) const {
        std::uint64_t kpos = 0, npos = 0;
        while (!m_bcvec.is_leaf(npos)) {
            if (kpos == key.size()) {
                if (!m_terms[npos]) {
                    return std::nullopt;
                }
                return npos_to_id(npos);
            }
            const std::uint64_t cpos = m_bcvec.base(npos) ^ m_table.get_code(key[kpos++]);
            if (m_bcvec.check(cpos) != npos) {
                return std::nullopt;
            }
            npos = cpos;
        }

        const std::uint64_t tpos = m_bcvec.link(npos);
        if (!m_tvec.match(get_suffix(key, kpos), tpos)) {
            return std::nullopt;
        }
        return npos_to_id(npos);
    }

    //! Decode the keyword associated with the ID.
    inline std::string decode(std::uint64_t id) const {
        std::string decoded;
        decoded.reserve(max_length());
        decode(id, decoded);
        return decoded;
    }

    //! Decode the keyword associated with the ID and store it in 'decoded'.
    //! It can avoid reallocation of memory to store the result.
    inline void decode(std::uint64_t id, std::string& decoded) const {
        decoded.clear();

        if (num_keys() <= id) {
            return;
        }

        std::uint64_t npos = id_to_npos(id);
        std::uint64_t tpos = m_bcvec.is_leaf(npos) ? m_bcvec.link(npos) : UINT64_MAX;

        while (npos != 0) {
            const std::uint64_t ppos = m_bcvec.check(npos);
            decoded.push_back(m_table.get_char(m_bcvec.base(ppos) ^ npos));
            npos = ppos;
        }

        std::reverse(decoded.begin(), decoded.end());
        if (tpos != 0 && tpos != UINT64_MAX) {
            m_tvec.decode(tpos, [&](char c) { decoded.push_back(c); });
        }
    }

    //! An iterator class for common prefix search.
    //! It enumerates all the keywords contained as prefixes of a given string.
    //! It should be instantiated via the function 'make_prefix_iterator'.
    class prefix_iterator {
      private:
        const trie_type* m_obj = nullptr;
        std::string m_key;
        std::uint64_t m_id = 0;
        std::uint64_t m_kpos = 0;
        std::uint64_t m_npos = 0;
        bool is_beg = true;
        bool is_end = false;

      public:
        prefix_iterator() = default;

        //! Increment the iterator.
        //! Return false if the iteration is terminated.
        inline bool next() {
            return m_obj != nullptr && m_obj->next_prefix(this);
        }

        //! Get the result ID.
        inline std::uint64_t id() const {
            return m_id;
        }

        //! Get the result keyword.
        inline std::string decoded() const {
            return std::string(m_key.data(), m_kpos);
        }

        //! Get the reference to the result keyword.
        //! Note that the referenced data will be changed in the next iteration.
        inline std::string_view decoded_view() const {
            return std::string_view(m_key.data(), m_kpos);
        }

      private:
        prefix_iterator(const trie_type* obj, std::string_view key) : m_obj(obj), m_key(key) {}

        friend class trie;
    };

    //! Make the common prefix searcher for the given keyword.
    inline prefix_iterator make_prefix_iterator(std::string_view key) const {
        return prefix_iterator(this, key);
    }

    //! Preform common prefix search for the keyword.
    inline void prefix_search(std::string_view key,
                              const std::function<void(std::uint64_t, std::string_view)>& fn) const {
        auto itr = make_prefix_iterator(key);
        while (itr.next()) {
            fn(itr.id(), itr.decoded_view());
        }
    }

    //! An iterator class for predictive search.
    //! It enumerates all the keywords starting with a given string.
    //! It should be instantiated via the function 'make_predictive_iterator'.
    class predictive_iterator {
      public:
        struct cursor_type {
            char label;
            std::uint64_t kpos;
            std::uint64_t npos;
        };

      private:
        const trie_type* m_obj = nullptr;
        std::string m_key;
        std::uint64_t m_id = 0;
        std::string m_decoded;
        std::vector<cursor_type> m_stack;
        bool is_beg = true;
        bool is_end = false;

      public:
        predictive_iterator() = default;

        //! Increment the iterator.
        //! Return false if the iteration is terminated.
        inline bool next() {
            return m_obj != nullptr && m_obj->next_predictive(this);
        }

        //! Get the result ID.
        inline std::uint64_t id() const {
            return m_id;
        }

        //! Get the result keyword.
        inline std::string decoded() const {
            return m_decoded;
        }

        //! Get the reference to the result keyword.
        //! Note that the referenced data will be changed in the next iteration.
        inline std::string_view decoded_view() const {
            return m_decoded;
        }

      private:
        predictive_iterator(const trie_type* obj, std::string_view key) : m_obj(obj), m_key(key) {}

        friend class trie;
    };

    //! Make the predictive searcher for the keyword.
    inline predictive_iterator make_predictive_iterator(std::string_view key) const {
        return predictive_iterator(this, key);
    }

    //! Preform predictive search for the keyword.
    inline void predictive_search(std::string_view key,
                                  const std::function<void(std::uint64_t, std::string_view)>& fn) const {
        auto itr = make_predictive_iterator(key);
        while (itr.next()) {
            fn(itr.id(), itr.decoded_view());
        }
    }

    //! An iterator class for enumeration.
    //! It enumerates all the keywords stored in the trie.
    //! It should be instantiated via the function 'make_enumerative_iterator'.
    using enumerative_iterator = predictive_iterator;

    //! Make the enumerator.
    inline enumerative_iterator make_enumerative_iterator() const {
        return enumerative_iterator(this, "");
    }

    //! Enumerate all the keywords and their IDs stored in the trie.
    inline void enumerate(const std::function<void(std::uint64_t, std::string_view)>& fn) const {
        auto itr = make_enumerative_iterator();
        while (itr.next()) {
            fn(itr.id(), itr.decoded_view());
        }
    }

    //! Visit the members (commonly used for I/O).
    template <class Visitor>
    void visit(Visitor& visitor) {
        visitor.visit(m_num_keys);
        visitor.visit(m_table);
        visitor.visit(m_terms);
        visitor.visit(m_bcvec);
        visitor.visit(m_tvec);
    }

  private:
    template <class Strings>
    explicit trie(trie_builder<Strings>&& b)
        : m_num_keys(b.m_keys.size()), m_table(std::move(b.m_table)), m_terms(b.m_terms, true, true),
          m_bcvec(b.m_units, std::move(b.m_leaves)), m_tvec(std::move(b.m_suffixes)) {}

    template <class String>
    static constexpr String get_suffix(const String& s, std::uint64_t i) {
        assert(i <= s.size());
        return s.substr(i, s.size() - i);
    }

    inline std::uint64_t npos_to_id(std::uint64_t npos) const {
        return m_terms.rank(npos);
    };

    inline std::uint64_t id_to_npos(std::uint64_t id) const {
        return m_terms.select(id);
    };

    inline bool next_prefix(prefix_iterator* itr) const {
        if (itr->is_end) {
            return false;
        }

        if (itr->is_beg) {
            itr->is_beg = false;
            if (m_terms[itr->m_npos]) {
                itr->m_id = npos_to_id(itr->m_npos);
                return true;
            }
        }

        if (bin_mode() and itr->m_kpos == itr->m_key.size()) {
            // Is the key terminated at an inner term?
            itr->is_end = true;
            itr->m_id = num_keys();
            return false;
        }

        while (!m_bcvec.is_leaf(itr->m_npos)) {
            if (bin_mode() and itr->m_kpos == itr->m_key.size()) {
                // Is the key terminated at an internal node (not term)?
                itr->is_end = true;
                itr->m_id = num_keys();
                return false;
            }

            const std::uint64_t cpos = m_bcvec.base(itr->m_npos) ^ m_table.get_code(itr->m_key[itr->m_kpos++]);

            if (m_bcvec.check(cpos) != itr->m_npos) {
                itr->is_end = true;
                itr->m_id = num_keys();
                return false;
            }

            itr->m_npos = cpos;
            if (!m_bcvec.is_leaf(itr->m_npos) && m_terms[itr->m_npos]) {
                itr->m_id = npos_to_id(itr->m_npos);
                return true;
            }
        }
        itr->is_end = true;

        const std::uint64_t tpos = m_bcvec.link(itr->m_npos);
        if (!m_tvec.match(get_suffix(itr->m_key, itr->m_kpos), tpos)) {
            itr->m_id = num_keys();
            return false;
        }

        itr->m_kpos = itr->m_key.size();
        itr->m_id = npos_to_id(itr->m_npos);
        return true;
    }

    inline bool next_predictive(predictive_iterator* itr) const {
        if (itr->is_end) {
            return false;
        }

        if (itr->is_beg) {
            itr->is_beg = false;

            std::uint64_t kpos = 0;
            std::uint64_t npos = 0;

            for (; kpos < itr->m_key.size(); ++kpos) {
                if (m_bcvec.is_leaf(npos)) {
                    itr->is_end = true;
                    const std::uint64_t tpos = m_bcvec.link(npos);
                    if (tpos == 0) {
                        return false;
                    }
                    if (!m_tvec.prefix_match(get_suffix(itr->m_key, kpos), tpos)) {
                        return false;
                    }
                    itr->m_id = npos_to_id(npos);
                    m_tvec.decode(tpos, [&](char c) { itr->m_decoded.push_back(c); });
                    return true;
                }

                const std::uint64_t cpos = m_bcvec.base(npos) ^ m_table.get_code(itr->m_key[kpos]);
                if (m_bcvec.check(cpos) != npos) {
                    itr->is_end = true;
                    return false;
                }

                npos = cpos;
                itr->m_decoded.push_back(itr->m_key[kpos]);
            }

            if (!itr->m_decoded.empty()) {
                itr->m_stack.push_back({itr->m_decoded.back(), kpos, npos});
            } else {
                itr->m_stack.push_back({'\0', kpos, npos});
            }
        }

        while (!itr->m_stack.empty()) {
            const char label = itr->m_stack.back().label;
            const std::uint64_t kpos = itr->m_stack.back().kpos;
            const std::uint64_t npos = itr->m_stack.back().npos;

            itr->m_stack.pop_back();

            if (0 < kpos) {
                itr->m_decoded.resize(kpos);
                itr->m_decoded.back() = label;
            }

            if (m_bcvec.is_leaf(npos)) {
                itr->m_id = npos_to_id(npos);
                m_tvec.decode(m_bcvec.link(npos), [&](char c) { itr->m_decoded.push_back(c); });
                return true;
            }

            const std::uint64_t base = m_bcvec.base(npos);

            for (auto cit = m_table.rbegin(); cit != m_table.rend(); ++cit) {
                const std::uint64_t cpos = base ^ m_table.get_code(*cit);
                if (m_bcvec.check(cpos) == npos) {
                    itr->m_stack.push_back({static_cast<char>(*cit), kpos + 1, cpos});
                }
            }

            if (m_terms[npos]) {
                itr->m_id = npos_to_id(npos);
                return true;
            }
        }

        itr->is_end = true;
        return false;
    }
};

}  // namespace xcdat


text:
package cap09_classi;

public class UsoEuclide {
	public static void main(String[] args) {

		System.out.println(Frazione.mcdEuclide(90, 8));
	}

}


text:
module Reports
  module Users
  end
end

require 'reports/users/backers'
require 'reports/users/projects'
require 'reports/users/emails'


text:
Edit course

  <form novalidate [formGroup]="editForm" *ngIf="course" name="form"  role="form">

        Title

          <input class="form-control" id="title" type="text" formControlName="courseName" [(ngModel)]="course.name">

        Description

          <textarea class="form-control" id="description" type="text" formControlName="courseDescription" [(ngModel)]="course.description"></textarea>

    <button type="submit" (click)="saveChanges()">Save</button>
    <button (click)="backToList($event)">Back to list</button>
  </form>


text:
package com.aerotron.aeropredictor.ui;

import android.view.View;

import java.util.ArrayList;

/**
 * Created by Aakash Kamble on 05-11-2016.
 */

public class Item {

    private String price;
    private String pledgePrice;
    private String fromAddress;
    private String toAddress;
    private String requestsCount;
    private String date;
    private String time;

    private String name;
    private String contact;
    private String email;

    private View.OnClickListener requestBtnClickListener;

    public Item() {
    }

    public Item(String price, String pledgePrice, String fromAddress, String toAddress, String requestsCount, String date, String time, String name, String contact, String email) {
        this.price = price;
        this.pledgePrice = pledgePrice;
        this.fromAddress = fromAddress;
        this.toAddress = toAddress;
        this.requestsCount = requestsCount;
        this.date = date;

        this.time = time;
        this.name = name;
        this.contact = contact;
        this.email = email;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getPledgePrice() {
        return pledgePrice;
    }

    public void setPledgePrice(String pledgePrice) {
        this.pledgePrice = pledgePrice;
    }

    public String getFromAddress() {
        return fromAddress;
    }

    public void setFromAddress(String fromAddress) {
        this.fromAddress = fromAddress;
    }

    public String getToAddress() {
        return toAddress;
    }

    public void setToAddress(String toAddress) {
        this.toAddress = toAddress;
    }

    public String getRequestsCount() {
        return requestsCount;
    }

    public void setRequestsCount(String requestsCount) {
        this.requestsCount = requestsCount;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Item item = (Item) o;

        if (requestsCount != item.requestsCount) return false;
        if (price != null ? !price.equals(item.price) : item.price != null) return false;
        if (pledgePrice != null ? !pledgePrice.equals(item.pledgePrice) : item.pledgePrice != null)
            return false;
        if (fromAddress != null ? !fromAddress.equals(item.fromAddress) : item.fromAddress != null)
            return false;
        if (toAddress != null ? !toAddress.equals(item.toAddress) : item.toAddress != null)
            return false;
        if (name != null ? !name.equals(item.name) : item.name != null) return false;
        if (contact != null ? !contact.equals(item.contact) : item.contact != null) return false;
        if (email != null ? !email.equals(item.email) : item.email != null) return false;
        if (date != null ? !date.equals(item.date) : item.date != null) return false;
        return !(time != null ? !time.equals(item.time) : item.time != null);

    }

    @Override
    public int hashCode() {
        int result = price != null ? price.hashCode() : 0;
        result = 31 * result + (pledgePrice != null ? pledgePrice.hashCode() : 0);
        result = 31 * result + (fromAddress != null ? fromAddress.hashCode() : 0);
        result = 31 * result + (toAddress != null ? toAddress.hashCode() : 0);
        result = 31 * result + (requestsCount != null ? date.hashCode() : 0);
        result = 31 * result + (date != null ? date.hashCode() : 0);
        result = 31 * result + (time != null ? time.hashCode() : 0);
        return result;
    }

    /**
     * @return List of elements prepared for tests
     */
    public static ArrayList<Item> getTestingList() {
        ArrayList<Item> items = new ArrayList<>();
        items.add(new Item("Aakash Kamble", "64", "Mumbai University", "Thakur College Of Engineering & Technology", "Information Technology", "", "", "Aakash Kamble", "+91 9619511353", "aakashk2910@gmail.com"));
        items.add(new Item("Darshan Vakharia", "65", "Mumbai University", "Thakur College Of Engineering & Technology", "Information Technology", "", "","Darshan Vakharia", "+91 9619992232", "dvakharia24@gmail.com"));
        items.add(new Item("Rachit   Verma", "78", "Mumbai University", "Thakur College Of Engineering & Technology", "Information Technology", "", "", "Rachit Verma", "+91 9967147969", "rachitverma94@gmail.com"));
/*        items.add(new Item("$19", "$150", "12th Ave, NY, 10012", "W 57th St, NY, 10048", 8, "TODAY", "4:15 AM"));
        items.add(new Item("$5", "$300", "56th Ave, NY, 10041", "W 36th St, NY, 10029", 0, "TODAY", "06:15 PM"));*/
        return items;

    }

}


text:
package com.nec.strudel.bench.micro.populate.base;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import com.nec.strudel.bench.micro.entity.Shared;
import com.nec.strudel.bench.micro.params.DataParam;
import com.nec.strudel.bench.micro.populate.ContentSet;
import com.nec.strudel.util.RandomSelector;
import com.nec.strudel.workload.api.PopulateParam;
import com.nec.strudel.workload.api.Populator;
import com.nec.strudel.workload.api.ValidateReporter;

public abstract class AbstractPopulateShared<T>
        implements Populator<T, ContentSet> {

    @Override
    public String getName() {
        return "Shared";
    }

    @Override
    public ContentSet createParameter(PopulateParam param) {
        int setId = param.getId();
        int length = param.getInt(DataParam.CONTENT_LENGTH);
        RandomSelector<String> selector = RandomSelector
                .createAlphaString(length);
        return ContentSet.create(setId,
                param.getInt(DataParam.ITEMS_PER_SET),
                selector, param.getRandom());
    }

    protected abstract List<Shared> getSharedBySetId(T db, int setId);

    @Override
    public boolean validate(T db, ContentSet param,
            ValidateReporter reporter) {
        int setId = param.getGroupId();

        List<Shared> items = getSharedBySetId(db, setId);
        return validate(param, items, reporter);
    }

    protected boolean validate(ContentSet param, List<Shared> items,
            ValidateReporter reporter) {
        String[] contents = param.getContents();
        Set<String> contentSet = new HashSet<String>();
        for (int i = 0; i < contents.length; i++) {
            contentSet.add(contents[i]);
        }
        if (items.size() != contents.length) {
            reporter.error(contents.length + " items expected but "
                    + items.size() + " found");
            return false;
        }
        for (Shared shared : items) {
            if (!contentSet.contains(shared.getContent())) {
                reporter.error("invalid content in an shared("
                        + shared.getSharedId() + ")");
                return false;
            }
        }
        return true;
    }
}


text:
title: Streamlining
layout: post
author: mika.stalley
permalink: /blog-13.9.18/
source-id: 131TOgQSR38OQoV-fm4ESJBFF3MoWq94281Bx4jx6faQ
published: true
---
This week, I attempted to make my coding spreadsheet a bit more complex and a bit more efficient, by nesting formulas and adding new features. The first thing added was a decryption and encryption system and a method so you can input a word and it will split it into individual characters. Sadly, for some reason, the spreadsheet would not decode the characters 'a' or 'b' and no teachers knew how to fix it. Next lesson, I need to try to implement Unicode or Ascii methods to bypass the glitch.

Now, let's see if RTL Override works here…

IF THIS WORKS THIS TEXT WILL BE BACKWARDS AND THE STUFF AFTER IT MAY BE INTERESTING!


text:
/* Author: Sonny Tarbouriech */

#include "ompl/base/objectives/HumanAwarenessObjective.h"
#include "ompl/tools/config/MagicConstants.h"
#include "ompl/geometric/PathGeometric.h"
#include <limits>

ompl::base::HumanAwarenessObjective::
HumanAwarenessObjective(const SpaceInformationPtr &si) :
OptimizationObjective(si)
{
	isMinMaxObjective_ = true;
	this->setCostThreshold(identityCost());

	ssvc_ = dynamic_cast<ompl::base::SafeStateValidityChecker*>(si_->getStateValidityChecker().get());
	if (!ssvc_)
		throw Exception("HumanAwarenessObjective requires SafeStateValidityChecker to work");
}

ompl::base::HumanAwarenessObjective::
HumanAwarenessObjective(const SpaceInformationPtr &si, Cost cost_threshold) :
OptimizationObjective(si)
{
	isMinMaxObjective_ = true;
	this->setCostThreshold(cost_threshold);

	ssvc_ = dynamic_cast<ompl::base::SafeStateValidityChecker*>(si_->getStateValidityChecker().get());
	if (!ssvc_)
		throw Exception("HumanAwarenessObjective requires SafeStateValidityChecker to work");
}

bool ompl::base::HumanAwarenessObjective::isSymmetric() const
{
	return true;
}

ompl::base::Cost ompl::base::HumanAwarenessObjective::stateCost(const State *s) const
{
	return Cost(ssvc_->humanAwareness(s));
}

ompl::base::Cost ompl::base::HumanAwarenessObjective::motionCost(const State *s1, const State *s2) const
{
	Cost worstCost = this->identityCost();
	int nd = si_->getStateSpace()->validSegmentCount(s1, s2) ;
	if (nd > 1)
	{
		State *test = si_->allocState();
		for (int j = 1; j < nd; ++j)
		{
			si_->getStateSpace()->interpolate(s1, s2, (double) j / (double) nd, test);
			Cost testStateCost = this->stateCost(test);
			if (this->isCostBetterThan(worstCost, testStateCost))
				worstCost = testStateCost;
		}
		si_->freeState(test);
	}
	// Lastly, check s2
	Cost lastCost = this->stateCost(s2);
	if (this->isCostBetterThan(worstCost, lastCost))
		worstCost = lastCost;

    return worstCost;
}

ompl::base::Cost ompl::base::HumanAwarenessObjective::combineCosts(Cost c1, Cost c2) const
{
    if (this->isCostBetterThan(c1, c2))
        return c2;
    else
        return c1;
}

ompl::base::Cost ompl::base::HumanAwarenessObjective::identityCost() const
{
	return Cost(0);
}

ompl::base::Cost ompl::base::HumanAwarenessObjective::infiniteCost() const
{
    return Cost(std::numeric_limits<double>::infinity());
}


text:
package cn.wz.algorithm.algs4;

import cn.wz.algorithm.stdlib.BinaryStdIn;
import cn.wz.algorithm.stdlib.BinaryStdOut;

/*************************************************************************
 *  Compilation:  javac Huffman.java
 *  Execution:    java Huffman - < input.txt   (compress)
 *  Execution:    java Huffman + < input.txt   (expand)
 *  Dependencies: BinaryIn.java BinaryOut.java
 *  Data files:   http://algs4.cs.princeton.edu/55compression/abra.txt
 *                http://algs4.cs.princeton.edu/55compression/tinytinyTale.txt
 *
 *  Compress or expand a binary input stream using the Huffman algorithm.
 *
 *  % java Huffman - < abra.txt | java BinaryDump 60
 *  010100000100101000100010010000110100001101010100101010000100
 *  000000000000000000000000000110001111100101101000111110010100
 *  120 bits
 *
 *  % java Huffman - < abra.txt | java Huffman +
 *  ABRACADABRA!
 *
 *************************************************************************/

public class Huffman {

    // alphabet size of extended ASCII
    private static final int R = 256;

    // Huffman trie node
    private static class Node implements Comparable<Node> {
        private final char ch;
        private final int freq;
        private final Node left, right;

        Node(char ch, int freq, Node left, Node right) {
            this.ch    = ch;
            this.freq  = freq;
            this.left  = left;
            this.right = right;
        }

        // is the node a leaf node?
        private boolean isLeaf() {
            assert (left == null && right == null) || (left != null && right != null);
            return (left == null && right == null);
        }

        // compare, based on frequency
        public int compareTo(Node that) {
            return this.freq - that.freq;
        }
    }

    // compress bytes from standard input and write to standard output
    public static void compress() {
        // read the input
        String s = BinaryStdIn.readString();
        char[] input = s.toCharArray();

        // tabulate frequency counts
        int[] freq = new int[R];
        for (int i = 0; i < input.length; i++)
            freq[input[i]]++;

        // build Huffman trie
        Node root = buildTrie(freq);

        // build code table
        String[] st = new String[R];
        buildCode(st, root, "");

        // print trie for decoder
        writeTrie(root);

        // print number of bytes in original uncompressed message
        BinaryStdOut.write(input.length);

        // use Huffman code to encode input
        for (int i = 0; i < input.length; i++) {
            String code = st[input[i]];
            for (int j = 0; j < code.length(); j++) {
                if (code.charAt(j) == '0') {
                    BinaryStdOut.write(false);
                }
                else if (code.charAt(j) == '1') {
                    BinaryStdOut.write(true);
                }
                else throw new RuntimeException("Illegal state");
            }
        }

        // flush output stream
        BinaryStdOut.flush();
    }

    // build the Huffman trie given frequencies
    private static Node buildTrie(int[] freq) {

        // initialze priority queue with singleton trees
        MinPQ<Node> pq = new MinPQ<Node>();
        for (char i = 0; i < R; i++)
            if (freq[i] > 0)
                pq.insert(new Node(i, freq[i], null, null));

        // merge two smallest trees
        while (pq.size() > 1) {
            Node left  = pq.delMin();
            Node right = pq.delMin();
            Node parent = new Node('\0', left.freq + right.freq, left, right);
            pq.insert(parent);
        }
        return pq.delMin();
    }

    // write bitstring-encoded trie to standard output
    private static void writeTrie(Node x) {
        if (x.isLeaf()) {
            BinaryStdOut.write(true);
            BinaryStdOut.write(x.ch);
            return;
        }
        BinaryStdOut.write(false);
        writeTrie(x.left);
        writeTrie(x.right);
    }

    // make a lookup table from symbols and their encodings
    private static void buildCode(String[] st, Node x, String s) {
        if (!x.isLeaf()) {
            buildCode(st, x.left,  s + '0');
            buildCode(st, x.right, s + '1');
        }
        else {
            st[x.ch] = s;
        }
    }

    // expand Huffman-encoded input from standard input and write to standard output
    public static void expand() {

        // read in Huffman trie from input stream
        Node root = readTrie();

        // number of bytes to write
        int length = BinaryStdIn.readInt();

        // decode using the Huffman trie
        for (int i = 0; i < length; i++) {
            Node x = root;
            while (!x.isLeaf()) {
                boolean bit = BinaryStdIn.readBoolean();
                if (bit) x = x.right;
                else     x = x.left;
            }
            BinaryStdOut.write(x.ch);
        }
        BinaryStdOut.flush();
    }

    private static Node readTrie() {
        boolean isLeaf = BinaryStdIn.readBoolean();
        if (isLeaf) {
            return new Node(BinaryStdIn.readChar(), -1, null, null);
        }
        else {
            return new Node('\0', -1, readTrie(), readTrie());
        }
    }

    public static void main(String[] args) {
        if      (args[0].equals("-")) compress();
        else if (args[0].equals("+")) expand();
        else throw new RuntimeException("Illegal command line argument");
    }

}


text:
"""
    Talon.One API

    Use the Talon.One API to integrate with your application and to manage applications and campaigns:  - Use the operations in the [Integration API section](#integration-api) are used to integrate with our platform - Use the operation in the [Management API section](#management-api) to manage applications and campaigns.  ## Determining the base URL of the endpoints  The API is available at the same hostname as your Campaign Manager deployment. For example, if you are reading this page at `https://mycompany.talon.one/docs/api/`, the URL for the [updateCustomerSession](https://docs.talon.one/integration-api/#operation/updateCustomerSessionV2) endpoint is `https://mycompany.talon.one/v2/customer_sessions/{Id}`   # noqa: E501

    The version of the OpenAPI document: 1.0.0
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from talon_one.configuration import Configuration

class Account(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'id': 'int',
        'created': 'datetime',
        'modified': 'datetime',
        'company_name': 'str',
        'domain_name': 'str',
        'state': 'str',
        'billing_email': 'str',
        'plan_name': 'str',
        'plan_expires': 'datetime',
        'application_limit': 'int',
        'user_limit': 'int',
        'campaign_limit': 'int',
        'api_limit': 'int',
        'application_count': 'int',
        'user_count': 'int',
        'campaigns_active_count': 'int',
        'campaigns_inactive_count': 'int',
        'attributes': 'object'
    }

    attribute_map = {
        'id': 'id',
        'created': 'created',
        'modified': 'modified',
        'company_name': 'companyName',
        'domain_name': 'domainName',
        'state': 'state',
        'billing_email': 'billingEmail',
        'plan_name': 'planName',
        'plan_expires': 'planExpires',
        'application_limit': 'applicationLimit',
        'user_limit': 'userLimit',
        'campaign_limit': 'campaignLimit',
        'api_limit': 'apiLimit',
        'application_count': 'applicationCount',
        'user_count': 'userCount',
        'campaigns_active_count': 'campaignsActiveCount',
        'campaigns_inactive_count': 'campaignsInactiveCount',
        'attributes': 'attributes'
    }

    def __init__(self, id=None, created=None, modified=None, company_name=None, domain_name=None, state=None, billing_email=None, plan_name=None, plan_expires=None, application_limit=None, user_limit=None, campaign_limit=None, api_limit=None, application_count=None, user_count=None, campaigns_active_count=None, campaigns_inactive_count=None, attributes=None, local_vars_configuration=None):  # noqa: E501
        """Account - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._id = None
        self._created = None
        self._modified = None
        self._company_name = None
        self._domain_name = None
        self._state = None
        self._billing_email = None
        self._plan_name = None
        self._plan_expires = None
        self._application_limit = None
        self._user_limit = None
        self._campaign_limit = None
        self._api_limit = None
        self._application_count = None
        self._user_count = None
        self._campaigns_active_count = None
        self._campaigns_inactive_count = None
        self._attributes = None
        self.discriminator = None

        self.id = id
        self.created = created
        self.modified = modified
        self.company_name = company_name
        self.domain_name = domain_name
        self.state = state
        self.billing_email = billing_email
        if plan_name is not None:
            self.plan_name = plan_name
        if plan_expires is not None:
            self.plan_expires = plan_expires
        if application_limit is not None:
            self.application_limit = application_limit
        if user_limit is not None:
            self.user_limit = user_limit
        if campaign_limit is not None:
            self.campaign_limit = campaign_limit
        if api_limit is not None:
            self.api_limit = api_limit
        self.application_count = application_count
        self.user_count = user_count
        self.campaigns_active_count = campaigns_active_count
        self.campaigns_inactive_count = campaigns_inactive_count
        if attributes is not None:
            self.attributes = attributes

    @property
    def id(self):
        """Gets the id of this Account.  # noqa: E501

        Unique ID for this entity. Not to be confused with the Integration ID, which is set by your integration layer and used in most endpoints.  # noqa: E501

        :return: The id of this Account.  # noqa: E501
        :rtype: int
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this Account.

        Unique ID for this entity. Not to be confused with the Integration ID, which is set by your integration layer and used in most endpoints.  # noqa: E501

        :param id: The id of this Account.  # noqa: E501
        :type: int
        """
        if self.local_vars_configuration.client_side_validation and id is None:  # noqa: E501
            raise ValueError("Invalid value for `id`, must not be `None`")  # noqa: E501

        self._id = id

    @property
    def created(self):
        """Gets the created of this Account.  # noqa: E501

        The exact moment this entity was created.  # noqa: E501

        :return: The created of this Account.  # noqa: E501
        :rtype: datetime
        """
        return self._created

    @created.setter
    def created(self, created):
        """Sets the created of this Account.

        The exact moment this entity was created.  # noqa: E501

        :param created: The created of this Account.  # noqa: E501
        :type: datetime
        """
        if self.local_vars_configuration.client_side_validation and created is None:  # noqa: E501
            raise ValueError("Invalid value for `created`, must not be `None`")  # noqa: E501

        self._created = created

    @property
    def modified(self):
        """Gets the modified of this Account.  # noqa: E501

        The exact moment this entity was last modified.  # noqa: E501

        :return: The modified of this Account.  # noqa: E501
        :rtype: datetime
        """
        return self._modified

    @modified.setter
    def modified(self, modified):
        """Sets the modified of this Account.

        The exact moment this entity was last modified.  # noqa: E501

        :param modified: The modified of this Account.  # noqa: E501
        :type: datetime
        """
        if self.local_vars_configuration.client_side_validation and modified is None:  # noqa: E501
            raise ValueError("Invalid value for `modified`, must not be `None`")  # noqa: E501

        self._modified = modified

    @property
    def company_name(self):
        """Gets the company_name of this Account.  # noqa: E501

        :return: The company_name of this Account.  # noqa: E501
        :rtype: str
        """
        return self._company_name

    @company_name.setter
    def company_name(self, company_name):
        """Sets the company_name of this Account.

        :param company_name: The company_name of this Account.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and company_name is None:  # noqa: E501
            raise ValueError("Invalid value for `company_name`, must not be `None`")  # noqa: E501
        if (self.local_vars_configuration.client_side_validation and
                company_name is not None and len(company_name) < 1):
            raise ValueError("Invalid value for `company_name`, length must be greater than or equal to `1`")  # noqa: E501

        self._company_name = company_name

    @property
    def domain_name(self):
        """Gets the domain_name of this Account.  # noqa: E501

        Subdomain Name for yourcompany.talon.one.  # noqa: E501

        :return: The domain_name of this Account.  # noqa: E501
        :rtype: str
        """
        return self._domain_name

    @domain_name.setter
    def domain_name(self, domain_name):
        """Sets the domain_name of this Account.

        Subdomain Name for yourcompany.talon.one.  # noqa: E501

        :param domain_name: The domain_name of this Account.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and domain_name is None:  # noqa: E501
            raise ValueError("Invalid value for `domain_name`, must not be `None`")  # noqa: E501

        self._domain_name = domain_name

    @property
    def state(self):
        """Gets the state of this Account.  # noqa: E501

        State of the account (active, deactivated).  # noqa: E501

        :return: The state of this Account.  # noqa: E501
        :rtype: str
        """
        return self._state

    @state.setter
    def state(self, state):
        """Sets the state of this Account.

        State of the account (active, deactivated).  # noqa: E501

        :param state: The state of this Account.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and state is None:  # noqa: E501
            raise ValueError("Invalid value for `state`, must not be `None`")  # noqa: E501
        allowed_values = ["active", "deactivated"]  # noqa: E501
        if self.local_vars_configuration.client_side_validation and state not in allowed_values:  # noqa: E501
            raise ValueError(
                "Invalid value for `state` ({0}), must be one of {1}"  # noqa: E501
                .format(state, allowed_values)
            )

        self._state = state

    @property
    def billing_email(self):
        """Gets the billing_email of this Account.  # noqa: E501

        The billing email address associated with your company account.  # noqa: E501

        :return: The billing_email of this Account.  # noqa: E501
        :rtype: str
        """
        return self._billing_email

    @billing_email.setter
    def billing_email(self, billing_email):
        """Sets the billing_email of this Account.

        The billing email address associated with your company account.  # noqa: E501

        :param billing_email: The billing_email of this Account.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and billing_email is None:  # noqa: E501
            raise ValueError("Invalid value for `billing_email`, must not be `None`")  # noqa: E501

        self._billing_email = billing_email

    @property
    def plan_name(self):
        """Gets the plan_name of this Account.  # noqa: E501

        The name of your booked plan.  # noqa: E501

        :return: The plan_name of this Account.  # noqa: E501
        :rtype: str
        """
        return self._plan_name

    @plan_name.setter
    def plan_name(self, plan_name):
        """Sets the plan_name of this Account.

        The name of your booked plan.  # noqa: E501

        :param plan_name: The plan_name of this Account.  # noqa: E501
        :type: str
        """

        self._plan_name = plan_name

    @property
    def plan_expires(self):
        """Gets the plan_expires of this Account.  # noqa: E501

        The point in time at which your current plan expires.  # noqa: E501

        :return: The plan_expires of this Account.  # noqa: E501
        :rtype: datetime
        """
        return self._plan_expires

    @plan_expires.setter
    def plan_expires(self, plan_expires):
        """Sets the plan_expires of this Account.

        The point in time at which your current plan expires.  # noqa: E501

        :param plan_expires: The plan_expires of this Account.  # noqa: E501
        :type: datetime
        """

        self._plan_expires = plan_expires

    @property
    def application_limit(self):
        """Gets the application_limit of this Account.  # noqa: E501

        The maximum number of Applications covered by your plan.  # noqa: E501

        :return: The application_limit of this Account.  # noqa: E501
        :rtype: int
        """
        return self._application_limit

    @application_limit.setter
    def application_limit(self, application_limit):
        """Sets the application_limit of this Account.

        The maximum number of Applications covered by your plan.  # noqa: E501

        :param application_limit: The application_limit of this Account.  # noqa: E501
        :type: int
        """

        self._application_limit = application_limit

    @property
    def user_limit(self):
        """Gets the user_limit of this Account.  # noqa: E501

        The maximum number of Campaign Manager Users covered by your plan.  # noqa: E501

        :return: The user_limit of this Account.  # noqa: E501
        :rtype: int
        """
        return self._user_limit

    @user_limit.setter
    def user_limit(self, user_limit):
        """Sets the user_limit of this Account.

        The maximum number of Campaign Manager Users covered by your plan.  # noqa: E501

        :param user_limit: The user_limit of this Account.  # noqa: E501
        :type: int
        """

        self._user_limit = user_limit

    @property
    def campaign_limit(self):
        """Gets the campaign_limit of this Account.  # noqa: E501

        The maximum number of Campaigns covered by your plan.  # noqa: E501

        :return: The campaign_limit of this Account.  # noqa: E501
        :rtype: int
        """
        return self._campaign_limit

    @campaign_limit.setter
    def campaign_limit(self, campaign_limit):
        """Sets the campaign_limit of this Account.

        The maximum number of Campaigns covered by your plan.  # noqa: E501

        :param campaign_limit: The campaign_limit of this Account.  # noqa: E501
        :type: int
        """

        self._campaign_limit = campaign_limit

    @property
    def api_limit(self):
        """Gets the api_limit of this Account.  # noqa: E501

        The maximum number of Integration API calls covered by your plan per billing period.  # noqa: E501

        :return: The api_limit of this Account.  # noqa: E501
        :rtype: int
        """
        return self._api_limit

    @api_limit.setter
    def api_limit(self, api_limit):
        """Sets the api_limit of this Account.

        The maximum number of Integration API calls covered by your plan per billing period.  # noqa: E501

        :param api_limit: The api_limit of this Account.  # noqa: E501
        :type: int
        """

        self._api_limit = api_limit

    @property
    def application_count(self):
        """Gets the application_count of this Account.  # noqa: E501

        The current number of Applications in your account.  # noqa: E501

        :return: The application_count of this Account.  # noqa: E501
        :rtype: int
        """
        return self._application_count

    @application_count.setter
    def application_count(self, application_count):
        """Sets the application_count of this Account.

        The current number of Applications in your account.  # noqa: E501

        :param application_count: The application_count of this Account.  # noqa: E501
        :type: int
        """
        if self.local_vars_configuration.client_side_validation and application_count is None:  # noqa: E501
            raise ValueError("Invalid value for `application_count`, must not be `None`")  # noqa: E501

        self._application_count = application_count

    @property
    def user_count(self):
        """Gets the user_count of this Account.  # noqa: E501

        The current number of Campaign Manager Users in your account.  # noqa: E501

        :return: The user_count of this Account.  # noqa: E501
        :rtype: int
        """
        return self._user_count

    @user_count.setter
    def user_count(self, user_count):
        """Sets the user_count of this Account.

        The current number of Campaign Manager Users in your account.  # noqa: E501

        :param user_count: The user_count of this Account.  # noqa: E501
        :type: int
        """
        if self.local_vars_configuration.client_side_validation and user_count is None:  # noqa: E501
            raise ValueError("Invalid value for `user_count`, must not be `None`")  # noqa: E501

        self._user_count = user_count

    @property
    def campaigns_active_count(self):
        """Gets the campaigns_active_count of this Account.  # noqa: E501

        The current number of active Campaigns in your account.  # noqa: E501

        :return: The campaigns_active_count of this Account.  # noqa: E501
        :rtype: int
        """
        return self._campaigns_active_count

    @campaigns_active_count.setter
    def campaigns_active_count(self, campaigns_active_count):
        """Sets the campaigns_active_count of this Account.

        The current number of active Campaigns in your account.  # noqa: E501

        :param campaigns_active_count: The campaigns_active_count of this Account.  # noqa: E501
        :type: int
        """
        if self.local_vars_configuration.client_side_validation and campaigns_active_count is None:  # noqa: E501
            raise ValueError("Invalid value for `campaigns_active_count`, must not be `None`")  # noqa: E501

        self._campaigns_active_count = campaigns_active_count

    @property
    def campaigns_inactive_count(self):
        """Gets the campaigns_inactive_count of this Account.  # noqa: E501

        The current number of inactive Campaigns in your account.  # noqa: E501

        :return: The campaigns_inactive_count of this Account.  # noqa: E501
        :rtype: int
        """
        return self._campaigns_inactive_count

    @campaigns_inactive_count.setter
    def campaigns_inactive_count(self, campaigns_inactive_count):
        """Sets the campaigns_inactive_count of this Account.

        The current number of inactive Campaigns in your account.  # noqa: E501

        :param campaigns_inactive_count: The campaigns_inactive_count of this Account.  # noqa: E501
        :type: int
        """
        if self.local_vars_configuration.client_side_validation and campaigns_inactive_count is None:  # noqa: E501
            raise ValueError("Invalid value for `campaigns_inactive_count`, must not be `None`")  # noqa: E501

        self._campaigns_inactive_count = campaigns_inactive_count

    @property
    def attributes(self):
        """Gets the attributes of this Account.  # noqa: E501

        Arbitrary properties associated with this campaign.  # noqa: E501

        :return: The attributes of this Account.  # noqa: E501
        :rtype: object
        """
        return self._attributes

    @attributes.setter
    def attributes(self, attributes):
        """Sets the attributes of this Account.

        Arbitrary properties associated with this campaign.  # noqa: E501

        :param attributes: The attributes of this Account.  # noqa: E501
        :type: object
        """

        self._attributes = attributes

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, Account):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, Account):
            return True

        return self.to_dict() != other.to_dict()


text:
require 'handlebars'
require 'ringcentral_sdk'
require 'pp'
require 'mime_builder'

# Set your credentials in the .env file
# Use the rc_config_sample.env.txt file as a scaffold
client = RingCentralSdk::REST::Client.new do |config|
  config.dotenv = true
end

# CoverPage is a example coverpage page builder class
class CoverPage
  def build_coverpage
    MIMEBuilder::Text.new(
      build_template_html,
      content_type: 'text/html',
      content_id_disable: true,
      is_attachment: true
    ).mime
  end

  def build_template_html
    template = build_template
    html = template.call(
      fax_date: DateTime.now.to_s,
      fax_pages: ENV['RC_DEMO_FAX_PAGES'],
      fax_to_name: ENV['RC_DEMO_FAX_TO_NAME'],
      fax_to_phone: ENV['RC_DEMO_FAX_TO'],
      fax_to_fax: ENV['RC_DEMO_FAX_TO'],
      fax_from_name: ENV['RC_DEMO_FAX_FROM_NAME'],
      fax_from_phone: ENV['RC_DEMO_FAX_FROM'],
      fax_from_fax: ENV['RC_DEMO_FAX_FROM'],
      fax_coverpage_text: ENV['RC_DEMO_FAX_COVERPAGE_TEXT']
    )
    html
  end

  def build_template
    hbs = ENV['RC_DEMO_FAX_COVERPAGE_TEMPLATE'].strip
    raise "Coverpage Template Does Not Exist: #{hbs}" unless File.exist? hbs

    handlebars = Handlebars::Context.new
    template = handlebars.compile IO.read(hbs)
    template
  end
end

# Get the coverpage as a MIME::Media object to pass into
# Fax method as an file part
cover = CoverPage.new.build_coverpage

# Set coverIndex to 0 to remove standard template
# add MIME::Media object as first file attachment
res = client.messages.fax.create(
  to: ENV['RC_DEMO_FAX_TO'],
  coverIndex: 0,
  files: [cover, ENV['RC_DEMO_FAX_FILE']]
)
pp res.body

puts 'DONE'


text:
require 'tmpdir'

class Hbc::Container::Cab < Hbc::Container::Base
  def self.me?(criteria)
    (criteria.file.include?('application/octet-stream;') ||
     criteria.file.include?('application/vnd.ms-cab-compressed;')) &&
      !criteria.cabextract.nil? &&
        criteria.cabextract.include?('All done, no errors')
  end

  def extract
    cabextract = Hbc.homebrew_prefix.join('bin/cabextract')
    if !Pathname.new(cabextract).exist?
      raise Hbc::CaskError.new "Expected to find cabextract executable. Cask '#{@cask}' must add: depends_on :formula => 'cabextract'"
    end
    Dir.mktmpdir do |unpack_dir|
      @command.run!(cabextract, :args => ['-d', unpack_dir, '--', @path])
      @command.run!('/usr/bin/ditto', :args => ['--', unpack_dir, @cask.staged_path])
    end
  end
end


text:
#include <string.h>
#include "StringBuilder.h"
#include "Scanner.h"

namespace Coco {

void StringBuilder::Init(int capacity) {
	length = 0;
	this->capacity = capacity;
	data = new wchar_t[capacity + 1];
	data[0] = 0;
}

StringBuilder::StringBuilder(int capacity) {
	Init(capacity);
}

StringBuilder::StringBuilder(const wchar_t *val) {
	capacity = length = wcslen(val);
	Init(capacity);
	wcscpy(data, val);
}

StringBuilder::~StringBuilder() {
	if (data != NULL) {
		delete [] data;
		data = NULL;
		length = 0;
		capacity = 0;
	}
}

void StringBuilder::Append(const wchar_t value) {
	if (length == capacity) {
		int oldCap = capacity;
		capacity = capacity * 2;
		wchar_t *nData = new wchar_t[capacity + 1];
		memcpy(nData, data, oldCap * sizeof(int));
		delete [] data;
		data = nData;
	}

	data[length] = value;
	length++;
	data[length] = '\0';
}

void StringBuilder::Append(const wchar_t *value) {
	if (length + (int)wcslen(value) < capacity) {
		wcscpy(data + length, value);
		length += wcslen(value);
	}
}

wchar_t* StringBuilder::ToString() {
	return coco_string_create(data);
}

}; // namespace


text:
get "/deck/new" do
  @deck = Deck.find_or_initialize_by(id: Deck.maximum(:id).next)
  erb :"deck/create_deck"
end

post "/deck/:id/new" do
  @deck = Deck.find_or_initialize_by(id: params[:id])
  @deck.creator_id = session[:user_id]
  if @deck.update_attributes(params[:deck])
    redirect "/deck/#{@deck.id}/card/new"
  else
    redirect "/deck/new"
  end
end

get "/deck/:id/card/new" do
  @deck = Deck.find_by(id: params[:id])
  @add_card = true
  erb :"deck/create_deck"
end

post "/deck/:id/card/new" do
  @deck = Deck.find_by(id: params[:id])
  @deck.update_cards(params[:cards]) if params[:cards]
  redirect "/deck/#{@deck.id}/card/new"
end

post "/deck/:id/complete" do
  @deck = Deck.find_by(id: params[:id])
  @deck.update_cards(params[:cards]) if params[:cards]
  redirect "/"
end

delete "/decks/:id" do
  Deck.find_by(id: params[:id]).destroy
  redirect "/"
end


text:
#region License

//  	Copyright 2013-2014 Matthew Ducker
//
//  	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.

#endregion

namespace Obscur.Core.Packaging.Multiplexing
{
    /// <summary>
    ///     Mode controlling length of stripes of items.
    /// </summary>
    public enum FabricStripeMode
    {
        FixedLength,
        VariableLength
    }
}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

$lang['alpha_dot_dash']			= "%s 欄位只能包含一般英文數字、底線、點、破折號。"; //"The %s field may only contain alpha-numeric characters, underscores, dots and dashes.";
$lang['decimal']				= "%s 欄位只能包含十進位數字"; //"The %s field must contain only decimal numbers.";
$lang['csrf_bad_token']			= "不正確的 CSRF Token"; //"Invalid CSRF Token";

/* End of file extra_validation_lang.php */


text:
import contextlib

class CodeWriter(object):
  """Helper class for code indentation."""
  def __init__(self):
    self.indent = 0
    self.value = []
    self.errors = []

  def GetErrors(self):
    return self.errors

  @contextlib.contextmanager
  def AddIndent(self, indent=2):
    self.indent += indent
    yield 0
    self.indent -= indent

  def IncreaseIndent(self, indent=2):
    self.indent += indent

  def DecreaseIndent(self, indent=2):
    self.indent -= indent

  def Output(self, fmt, **kwargs):
    s = fmt.format(**kwargs)
    s = s.rstrip('\n')
    lines = s.split('\n')
    lines = map(lambda s: (' ' * self.indent + s).rstrip(), lines)
    self.value.extend(lines)

  def AddError(self, fmt, **kwargs):
    self.errors.append(fmt.format(**kwargs))

  def GetValue(self):
    return '\n'.join(self.value) + '\n'

  def WriteCStyleHeader(self):
    self.Output("// GENERATED FILE")
    self.Output("// This file generated by DomDistillerJs protoc plugin.")


text:
import os
import sys

import conf
import g

log = g.log.getLogger('ccp_export')

from merge.export_base import Export_Base
from merge.export_cyclop import Export_Cyclop

class Ccp_Export(Export_Cyclop):

   # *** Constructor

   def __init__(self, mjob, branch_defs):
      Export_Cyclop.__init__(self, mjob, branch_defs)

   # ***

   #
   def do_export(self):
      okay = self.do_merge_io(self.feature_classes_export)
      return okay


text:
import { ChangeDetectionStrategy, Component, ElementRef, forwardRef, Input, ViewChild } from '@angular/core';
import { FormControl } from '@angular/forms';
import { ALuOnOpenSubscriber, ILuOnOpenSubscriber } from '@lucca-front/ng/core';
import { combineLatest, merge, Observable, of } from 'rxjs';
import { map } from 'rxjs/operators';
import { ALuOptionOperator, ILuOptionOperator } from '../option-operator.model';

@Component({
	selector: 'lu-option-searcher',
	templateUrl: 'option-searcher.component.html',
	styleUrls: ['option-searcher.component.scss'],
	changeDetection: ChangeDetectionStrategy.OnPush,
	providers: [
		{
			provide: ALuOptionOperator,
			useExisting: forwardRef(() => LuOptionSearcherComponent),
			multi: true,
		},
		{
			provide: ALuOnOpenSubscriber,
			useExisting: forwardRef(() => LuOptionSearcherComponent),
			multi: true,
		},
	],
})
export class LuOptionSearcherComponent<T> extends ALuOptionOperator<T> implements ILuOptionOperator<T>, ILuOnOpenSubscriber {
	searchControl = new FormControl();
	clue$ = merge(of(''), this.searchControl.valueChanges) as Observable<string>;
	empty$: Observable<boolean>;
	@ViewChild('searchInput', { read: ElementRef, static: true })
	searchInput: ElementRef<HTMLElement>;
	outOptions$: Observable<T[]>;
	set inOptions$(in$: Observable<T[]>) {
		this.outOptions$ = combineLatest([in$, this.clue$]).pipe(
			map(([options, clue]) => {
				return clue ? (options || []).filter((o) => this.searchFn(o, clue)) : options || [];
			}),
		);
		this.empty$ = this.outOptions$.pipe(map((o) => !o || o.length === 0));
	}
	@Input() searchFn: (option: T, clue: string) => boolean = () => true;

	onOpen() {
		this.searchInput.nativeElement.focus();
		this.searchControl.setValue('');
	}
	resetClue() {
		this.searchControl.setValue('');
	}
}


text:
// IWYU pragma: private, include "third_party/tensorflow/stream_executor/stream_executor.h"

#ifndef TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_H_
#define TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_H_

#include "tensorflow/compiler/xla/statusor.h"

namespace stream_executor {
namespace port {

// Use XLA's StatusOr so we don't duplicate code.
template <typename T>
using StatusOr = ::xla::StatusOr<T>;

}  // namespace port
}  // namespace stream_executor

#endif  // TENSORFLOW_STREAM_EXECUTOR_LIB_STATUSOR_H_


text:
A documentação a seguir tenta explicar a migração do seu projeto deve ser realizada. Esse método não é a prova de falhas, já que a estrutura do projeto está sempre aberta a mudanças.

1. Inicie uma versão nova do electron-vue usando `vue init simulatedgreg/electron-vue my-project`
2. Copie a pasta `src` do seu projeto atual para a nova pasta do `src` gerada pelo _scaffold_
3. Copie sobre o `package.json` as dependencias do projeto atual para o novo `package.json` gerado pelo _scaffold_.
4. Instale as dependencias com `yarn` ou `npm install`
5. Rode o projeto no modo de desenvolvimento com \(`yarn run dev` ou `npm run dev`\)
6. Olhe para o terminal para encontrar erros.

Como previamente mencionado acima, não tem metodo sem erros para fazer a migração para a nova versão do _scaffold_ , mas é a melhor forma de se começar.
Qualquer modificação pessoal para a estrutura do projeto ou assets vai ser totalmente problema seu e de sua equipe para migrar.
Tenha total certeza de olhar toda a outra documentação, e veja se isso reflete a versão atual do electron-vue da branch `master`.


text:
package org.apache.tiles.autotag.core;

/**
 * Thrown if there is a problem when parsing a class source.
 *
 * @version $Rev$ $Date$
 */
public class ClassParseException extends AutotagRuntimeException {

	private static final long serialVersionUID = -8579521283073016196L;

	/**
     * Constructor.
     */
    public ClassParseException() {
    }

    /**
     * Constructor.
     *
     * @param message The message of the exception.
     */
    public ClassParseException(String message) {
        super(message);
    }

    /**
     * Constructor.
     *
     * @param cause The cause.
     */
    public ClassParseException(Throwable cause) {
        super(cause);
    }

    /**
     * Constructor.
     *
     * @param message The message of the exception.
     * @param cause The cause.
     */
    public ClassParseException(String message, Throwable cause) {
        super(message, cause);
    }

}


text:
<?php

namespace Point\Framework\Models;

use Illuminate\Database\Eloquent\Model;

class AccountPayableAndReceivable extends Model
{
    protected $table = 'account_payable_and_receivable';
    public $timestamps = false;

    public function accountId()
    {
        return $this->belongsTo('\Point\Framework\Models\Master\Coa', 'account_id');
    }

    public function person()
    {
        return $this->belongsTo('\Point\Framework\Models\Master\Person', 'person_id');
    }

    public function formulirReference()
    {
        return $this->belongsTo('\Point\Framework\Models\Formulir', 'formulir_reference_id');
    }

    public function detail()
    {
        return $this->hasMany('\Point\Framework\Models\AccountPayableAndReceivableDetail', 'account_payable_and_receivable_id');
    }
}


text:
/**
 * Module dependencies.
 */

try {
  var closest = require('closest');
} catch(err) {
  var closest = require('component-closest');
}

try {
  var event = require('event');
} catch(err) {
  var event = require('component-event');
}

/**
 * Delegate event `type` to `selector`
 * and invoke `fn(e)`. A callback function
 * is returned which may be passed to `.unbind()`.
 *
 * @param {Element} el
 * @param {String} selector
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @return {Function}
 * @api public
 */

exports.bind = function(el, selector, type, fn, capture){
  return event.bind(el, type, function(e){
    var target = e.target || e.srcElement;
    e.delegateTarget = closest(target, selector, true, el);
    if (e.delegateTarget) fn.call(el, e);
  }, capture);
};

/**
 * Unbind event `type`'s callback `fn`.
 *
 * @param {Element} el
 * @param {String} type
 * @param {Function} fn
 * @param {Boolean} capture
 * @api public
 */

exports.unbind = function(el, type, fn, capture){
  event.unbind(el, type, fn, capture);
};


text:
package runtime

import (
	"bytes"
	"fmt"
	"sort"
	"strings"
	"sync"
	"time"

	"github.com/gogo/protobuf/types"

	mcp "istio.io/api/mcp/v1alpha1"

	"istio.io/istio/galley/pkg/config/monitoring"
	"istio.io/istio/galley/pkg/metadata"
	"istio.io/istio/galley/pkg/runtime/conversions"
	"istio.io/istio/galley/pkg/runtime/log"
	"istio.io/istio/galley/pkg/runtime/processing"
	"istio.io/istio/galley/pkg/runtime/resource"
	"istio.io/istio/pkg/mcp/snapshot"
)

var _ processing.Handler = &State{}

// State is the in-memory state of Galley.
type State struct {
	listener processing.Listener

	config *Config

	// version counter is a nonce that generates unique ids for each updated view of State.
	versionCounter int64

	// entries for per-message-type State.
	entriesLock sync.Mutex
	entries     map[resource.Collection]*resourceTypeState

	// Virtual version numbers for Gateways & VirtualServices for Ingress projected ones
	ingressGWVersion   int64
	ingressVSVersion   int64
	lastIngressVersion int64

	// pendingEvents counts the number of events awaiting publishing.
	pendingEvents int64

	// lastSnapshotTime records the last time a snapshot was published.
	lastSnapshotTime time.Time
}

// per-resource-type State.
type resourceTypeState struct {
	// The version number for the current State of the object. Every time entries or versions change,
	// the version number also change
	version  int64
	entries  map[resource.FullName]*mcp.Resource
	versions map[resource.FullName]resource.Version
}

func newState(cfg *Config, listener processing.Listener) *State {
	now := time.Now()
	s := &State{
		listener:         listener,
		config:           cfg,
		entries:          make(map[resource.Collection]*resourceTypeState),
		lastSnapshotTime: now,
	}

	// pre-populate state for all known types so that built snapshots
	// includes valid default version for empty resource collections.
	for _, info := range cfg.Schema.All() {
		s.entries[info.Collection] = &resourceTypeState{
			entries:  make(map[resource.FullName]*mcp.Resource),
			versions: make(map[resource.FullName]resource.Version),
		}
	}

	return s
}

// Handle implements the processing.Handler interface.
func (s *State) Handle(event resource.Event) {
	pks, found := s.getResourceTypeState(event.Entry.ID.Collection)
	if !found {
		return
	}

	switch event.Kind {
	case resource.Added, resource.Updated:

		// Check to see if the version has changed.
		if curVersion := pks.versions[event.Entry.ID.FullName]; curVersion == event.Entry.ID.Version {
			log.Scope.Debugf("Received event for the current, known version: %v", event)
			return
		}

		// TODO: Check for content-wise equality

		entry, ok := s.toResource(event.Entry)
		if !ok {
			return
		}

		pks.entries[event.Entry.ID.FullName] = entry
		pks.versions[event.Entry.ID.FullName] = event.Entry.ID.Version
		monitoring.RecordStateTypeCount(event.Entry.ID.Collection.String(), len(pks.entries))
		monitorEntry(event.Entry.ID, true)

	case resource.Deleted:
		delete(pks.entries, event.Entry.ID.FullName)
		delete(pks.versions, event.Entry.ID.FullName)
		monitoring.RecordStateTypeCount(event.Entry.ID.Collection.String(), len(pks.entries))
		monitorEntry(event.Entry.ID, false)

	default:
		log.Scope.Errorf("Unknown event kind: %v", event.Kind)
		return
	}

	s.versionCounter++
	pks.version = s.versionCounter

	log.Scope.Debugf("In-memory State has changed:\n%v\n", s)
	s.pendingEvents++
	s.listener.CollectionChanged(event.Entry.ID.Collection)
}

func (s *State) getResourceTypeState(name resource.Collection) (*resourceTypeState, bool) {
	s.entriesLock.Lock()
	defer s.entriesLock.Unlock()

	pks, found := s.entries[name]
	return pks, found
}

func (s *State) buildSnapshot() snapshot.Snapshot {
	s.entriesLock.Lock()
	defer s.entriesLock.Unlock()

	now := time.Now()
	monitoring.RecordProcessorSnapshotPublished(s.pendingEvents, now.Sub(s.lastSnapshotTime))
	s.lastSnapshotTime = now

	b := snapshot.NewInMemoryBuilder()

	for collection, state := range s.entries {
		entries := make([]*mcp.Resource, 0, len(state.entries))
		for _, entry := range state.entries {
			entries = append(entries, entry)
		}
		version := fmt.Sprintf("%d", state.version)
		b.Set(collection.String(), version, entries)
	}

	// Build entities that are derived from existing ones.
	s.buildProjections(b)

	sn := b.Build()
	s.pendingEvents = 0
	return sn
}

func (s *State) buildProjections(b *snapshot.InMemoryBuilder) {
	s.buildIngressProjectionResources(b)
}

func (s *State) buildIngressProjectionResources(b *snapshot.InMemoryBuilder) {
	ingressByHost := make(map[string]resource.Entry)

	// Build ingress projections
	state := s.entries[metadata.K8sExtensionsV1beta1Ingresses.Collection]
	if state == nil || len(state.entries) == 0 {
		return
	}

	if s.lastIngressVersion != state.version {
		// Ingresses has changed
		s.versionCounter++
		s.ingressGWVersion = s.versionCounter
		s.versionCounter++
		s.ingressVSVersion = s.versionCounter
		s.lastIngressVersion = state.version
	}

	versionStr := fmt.Sprintf("%d_%d",
		s.entries[metadata.IstioNetworkingV1alpha3Gateways.Collection].version, s.ingressGWVersion)
	b.SetVersion(metadata.IstioNetworkingV1alpha3Gateways.Collection.String(), versionStr)

	versionStr = fmt.Sprintf("%d_%d",
		s.entries[metadata.IstioNetworkingV1alpha3Virtualservices.Collection].version, s.ingressVSVersion)
	b.SetVersion(metadata.IstioNetworkingV1alpha3Virtualservices.Collection.String(), versionStr)

	// Order names for stable generation.
	var orderedNames []resource.FullName
	for name := range state.entries {
		orderedNames = append(orderedNames, name)
	}
	sort.Slice(orderedNames, func(i, j int) bool {
		return strings.Compare(orderedNames[i].String(), orderedNames[j].String()) < 0
	})

	for _, name := range orderedNames {
		entry := state.entries[name]

		ingress, err := conversions.ToIngressSpec(entry)
		if err != nil {
			// Shouldn't happen
			log.Scope.Errorf("error during ingress projection: %v", err)
			continue
		}

		key := extractKey(name, state.versions[name])
		meta := extractMetadata(entry)

		conversions.IngressToVirtualService(key, meta, ingress, s.config.DomainSuffix, ingressByHost)

		gw := conversions.IngressToGateway(key, meta, ingress)

		err = b.SetEntry(
			metadata.IstioNetworkingV1alpha3Gateways.Collection.String(),
			gw.ID.FullName.String(),
			string(gw.ID.Version),
			gw.Metadata.CreateTime,
			nil,
			nil,
			gw.Item)
		if err != nil {
			log.Scope.Errorf("Unable to set gateway entry: %v", err)
		}
	}

	for _, e := range ingressByHost {
		err := b.SetEntry(
			metadata.IstioNetworkingV1alpha3Virtualservices.Collection.String(),
			e.ID.FullName.String(),
			string(e.ID.Version),
			e.Metadata.CreateTime,
			nil,
			nil,
			e.Item)
		if err != nil {
			log.Scope.Errorf("Unable to set virtualservice entry: %v", err)
		}
	}
}

func extractKey(name resource.FullName, version resource.Version) resource.VersionedKey {
	return resource.VersionedKey{
		Key: resource.Key{
			Collection: metadata.K8sExtensionsV1beta1Ingresses.Collection,
			FullName:   name,
		},
		Version: version,
	}
}

func extractMetadata(entry *mcp.Resource) resource.Metadata {
	ts, err := types.TimestampFromProto(entry.Metadata.CreateTime)
	if err != nil {
		// It is an invalid timestamp. This shouldn't happen.
		log.Scope.Errorf("Error converting proto timestamp to time.Time: %v", err)
	}

	return resource.Metadata{
		CreateTime:  ts,
		Labels:      entry.Metadata.GetLabels(),
		Annotations: entry.Metadata.GetAnnotations(),
	}
}

func (s *State) toResource(e resource.Entry) (*mcp.Resource, bool) {
	body, err := types.MarshalAny(e.Item)
	if err != nil {
		log.Scope.Errorf("Error serializing proto from source e: %v:", e)
		return nil, false
	}

	createTime, err := types.TimestampProto(e.Metadata.CreateTime)
	if err != nil {
		log.Scope.Errorf("Error parsing resource create_time for event (%v): %v", e, err)
		return nil, false
	}

	entry := &mcp.Resource{
		Metadata: &mcp.Metadata{
			Name:        e.ID.FullName.String(),
			CreateTime:  createTime,
			Version:     string(e.ID.Version),
			Labels:      e.Metadata.Labels,
			Annotations: e.Metadata.Annotations,
		},
		Body: body,
	}

	return entry, true
}

// String implements fmt.Stringer
func (s *State) String() string {
	var b bytes.Buffer

	_, _ = fmt.Fprintf(&b, "[State @%v]\n", s.versionCounter)

	sn := s.buildSnapshot().(*snapshot.InMemory)
	_, _ = fmt.Fprintf(&b, "%v", sn)

	return b.String()
}

func monitorEntry(resourceKey resource.VersionedKey, added bool) {
	namespace, name := resourceKey.FullName.InterpretAsNamespaceAndName()
	value := 1
	if !added {
		value = 0
	}
	monitoring.RecordDetailedStateType(namespace, name, resourceKey.Collection, value)
}


text:
package com.evojam.nlp.util

import com.google.inject.Singleton
import net.codingwell.scalaguice.ScalaModule

object ObjectLoaderModule extends ScalaModule {
  override def configure() {
    bind[ObjectLoader].to[ObjectLoaderImpl].in[Singleton]
  }
}


text:
package gov.nasa.worldwind.applications.sar;

import gov.nasa.worldwind.geom.*;

/**
 * @author tag
 * @version $Id: SARPosition.java 3879 2007-12-11 07:47:29Z tgaskins $
 */
public class SARPosition extends Position
{
    public static class Info
    {
        private final String author;
        private final long editTime;
        private final String comment;

        public Info(String author, long editTime, String comment)
        {
            this.author = author;
            this.editTime = editTime;
            this.comment = comment;
        }
    }

    private Info info;

    public SARPosition()
    {
        super(Angle.ZERO, Angle.ZERO, 0d);
    }

    public SARPosition(Angle latitude, Angle longitude, double elevation)
    {
        super(latitude, longitude, elevation);
    }

    public SARPosition(Position pos)
    {
        super(pos.getLatitude(), pos.getLongitude(), pos.getElevation());
    }
}