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

import com.google.common.collect.ImmutableList;
import io.airlift.units.DataSize;
import io.trino.RowPagesBuilder;
import io.trino.operator.Driver;
import io.trino.operator.DriverContext;
import io.trino.operator.OperatorFactories;
import io.trino.operator.OperatorFactory;
import io.trino.operator.PagesIndex;
import io.trino.operator.PipelineContext;
import io.trino.operator.TaskContext;
import io.trino.operator.ValuesOperator;
import io.trino.operator.exchange.LocalExchange;
import io.trino.operator.exchange.LocalExchangeSinkOperator;
import io.trino.operator.exchange.LocalExchangeSourceOperator.LocalExchangeSourceOperatorFactory;
import io.trino.operator.join.InternalJoinFilterFunction;
import io.trino.operator.join.JoinBridgeManager;
import io.trino.operator.join.LookupSource;
import io.trino.operator.join.StandardJoinFilterFunction;
import io.trino.operator.join.unspilled.HashBuilderOperator.HashBuilderOperatorFactory;
import io.trino.spi.Page;
import io.trino.spi.TrinoException;
import io.trino.spi.type.TypeOperators;
import io.trino.sql.gen.JoinFilterFunctionCompiler;
import io.trino.sql.planner.NodePartitioningManager;
import io.trino.sql.planner.plan.PlanNodeId;
import io.trino.type.BlockTypeOperators;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.function.Function;
import java.util.stream.IntStream;

import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.ImmutableList.toImmutableList;
import static io.airlift.concurrent.MoreFutures.getFutureValue;
import static io.trino.operator.HashArraySizeSupplier.incrementalLoadFactorHashArraySizeSupplier;
import static io.trino.operator.OperatorFactories.JoinOperatorType.innerJoin;
import static io.trino.sql.planner.SystemPartitioningHandle.FIXED_HASH_DISTRIBUTION;
import static java.util.Objects.requireNonNull;

public final class JoinTestUtils
{
    private static final int PARTITION_COUNT = 4;
    private static final BlockTypeOperators TYPE_OPERATOR_FACTORY = new BlockTypeOperators(new TypeOperators());

    private JoinTestUtils() {}

    public static OperatorFactory innerJoinOperatorFactory(
            OperatorFactories operatorFactories,
            JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager,
            RowPagesBuilder probePages,
            boolean hasFilter)
    {
        return innerJoinOperatorFactory(operatorFactories, lookupSourceFactoryManager, probePages, false, hasFilter);
    }

    public static OperatorFactory innerJoinOperatorFactory(
            OperatorFactories operatorFactories,
            JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager,
            RowPagesBuilder probePages,
            boolean outputSingleMatch,
            boolean hasFilter)
    {
        return operatorFactories.join(
                innerJoin(outputSingleMatch, false),
                0,
                new PlanNodeId("test"),
                lookupSourceFactoryManager,
                hasFilter,
                probePages.getTypes(),
                probePages.getHashChannels().orElseThrow(),
                getHashChannelAsInt(probePages),
                Optional.empty(),
                TYPE_OPERATOR_FACTORY);
    }

    public static void instantiateBuildDrivers(BuildSideSetup buildSideSetup, TaskContext taskContext)
    {
        PipelineContext buildPipeline = taskContext.addPipelineContext(1, true, true, false);
        List<Driver> buildDrivers = new ArrayList<>();
        List<HashBuilderOperator> buildOperators = new ArrayList<>();
        for (int i = 0; i < buildSideSetup.getPartitionCount(); i++) {
            DriverContext buildDriverContext = buildPipeline.addDriverContext();
            HashBuilderOperator buildOperator = buildSideSetup.getBuildOperatorFactory().createOperator(buildDriverContext);
            Driver driver = Driver.createDriver(
                    buildDriverContext,
                    buildSideSetup.getBuildSideSourceOperatorFactory().createOperator(buildDriverContext),
                    buildOperator);
            buildDrivers.add(driver);
            buildOperators.add(buildOperator);
        }

        buildSideSetup.setDriversAndOperators(buildDrivers, buildOperators);
    }

    public static BuildSideSetup setupBuildSide(
            NodePartitioningManager nodePartitioningManager,
            boolean parallelBuild,
            TaskContext taskContext,
            RowPagesBuilder buildPages,
            Optional<InternalJoinFilterFunction> filterFunction)
    {
        return setupBuildSide(nodePartitioningManager, parallelBuild, taskContext, buildPages, filterFunction, true);
    }

    public static BuildSideSetup setupBuildSide(
            NodePartitioningManager nodePartitioningManager,
            boolean parallelBuild,
            TaskContext taskContext,
            RowPagesBuilder buildPages,
            Optional<InternalJoinFilterFunction> filterFunction,
            boolean enableSingleChannelBigintLookupSource)
    {
        Optional<JoinFilterFunctionCompiler.JoinFilterFunctionFactory> filterFunctionFactory = filterFunction
                .map(function -> (session, addresses, pages) -> new StandardJoinFilterFunction(function, addresses, pages));

        int partitionCount = parallelBuild ? PARTITION_COUNT : 1;
        List<Integer> hashChannels = buildPages.getHashChannels().orElseThrow();
        LocalExchange localExchange = new LocalExchange(
                nodePartitioningManager,
                taskContext.getSession(),
                partitionCount,
                FIXED_HASH_DISTRIBUTION,
                hashChannels,
                buildPages.getTypes(),
                buildPages.getHashChannel(),
                DataSize.of(32, DataSize.Unit.MEGABYTE),
                TYPE_OPERATOR_FACTORY,
                taskContext::getPhysicalWrittenDataSize,
                DataSize.of(32, DataSize.Unit.MEGABYTE));

        // collect input data into the partitioned exchange
        DriverContext collectDriverContext = taskContext.addPipelineContext(0, true, true, false).addDriverContext();
        ValuesOperator.ValuesOperatorFactory valuesOperatorFactory = new ValuesOperator.ValuesOperatorFactory(0, new PlanNodeId("values"), buildPages.build());
        LocalExchangeSinkOperator.LocalExchangeSinkOperatorFactory sinkOperatorFactory = new LocalExchangeSinkOperator.LocalExchangeSinkOperatorFactory(localExchange.createSinkFactory(), 1, new PlanNodeId("sink"), Function.identity());
        Driver sourceDriver = Driver.createDriver(collectDriverContext,
                valuesOperatorFactory.createOperator(collectDriverContext),
                sinkOperatorFactory.createOperator(collectDriverContext));
        valuesOperatorFactory.noMoreOperators();
        sinkOperatorFactory.noMoreOperators();
        sinkOperatorFactory.localPlannerComplete();

        while (!sourceDriver.isFinished()) {
            sourceDriver.processUntilBlocked();
        }

        // build side operator factories
        LocalExchangeSourceOperatorFactory sourceOperatorFactory = new LocalExchangeSourceOperatorFactory(0, new PlanNodeId("source"), localExchange);
        PartitionedLookupSourceFactory factory = new PartitionedLookupSourceFactory(
                buildPages.getTypes(),
                rangeList(buildPages.getTypes().size()).stream()
                        .map(buildPages.getTypes()::get)
                        .collect(toImmutableList()),
                hashChannels.stream()
                        .map(buildPages.getTypes()::get)
                        .collect(toImmutableList()),
                partitionCount,
                false,
                TYPE_OPERATOR_FACTORY);
        JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = new JoinBridgeManager<PartitionedLookupSourceFactory>(
                false,
                factory,
                factory.getOutputTypes());

        HashBuilderOperatorFactory buildOperatorFactory = new HashBuilderOperatorFactory(
                1,
                new PlanNodeId("build"),
                lookupSourceFactoryManager,
                rangeList(buildPages.getTypes().size()),
                hashChannels,
                buildPages.getHashChannel()
                        .map(OptionalInt::of).orElse(OptionalInt.empty()),
                filterFunctionFactory,
                Optional.empty(),
                ImmutableList.of(),
                100,
                new PagesIndex.TestingFactory(false, enableSingleChannelBigintLookupSource),
                incrementalLoadFactorHashArraySizeSupplier(taskContext.getSession()));
        return new BuildSideSetup(lookupSourceFactoryManager, buildOperatorFactory, sourceOperatorFactory, partitionCount);
    }

    public static void buildLookupSource(ExecutorService executor, BuildSideSetup buildSideSetup)
    {
        requireNonNull(buildSideSetup, "buildSideSetup is null");

        PartitionedLookupSourceFactory lookupSourceFactory = buildSideSetup.getLookupSourceFactoryManager().getJoinBridge();
        Future<LookupSource> lookupSource = lookupSourceFactory.createLookupSource();
        List<Driver> buildDrivers = buildSideSetup.getBuildDrivers();

        while (!lookupSource.isDone()) {
            for (Driver buildDriver : buildDrivers) {
                buildDriver.processForNumberOfIterations(1);
            }
        }
        getFutureValue(lookupSource).close();

        for (Driver buildDriver : buildDrivers) {
            runDriverInThread(executor, buildDriver);
        }
    }

    /**
     * Runs Driver in another thread until it is finished
     */
    public static void runDriverInThread(ExecutorService executor, Driver driver)
    {
        executor.execute(() -> {
            if (!driver.isFinished()) {
                try {
                    driver.processUntilBlocked();
                }
                catch (TrinoException e) {
                    driver.getDriverContext().failed(e);
                    return;
                }
                runDriverInThread(executor, driver);
            }
        });
    }

    public static OptionalInt getHashChannelAsInt(RowPagesBuilder probePages)
    {
        return probePages.getHashChannel()
                .map(OptionalInt::of).orElse(OptionalInt.empty());
    }

    private static List<Integer> rangeList(int endExclusive)
    {
        return IntStream.range(0, endExclusive)
                .boxed()
                .collect(toImmutableList());
    }

    public static class BuildSideSetup
    {
        private final JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager;
        private final HashBuilderOperatorFactory buildOperatorFactory;
        private final LocalExchangeSourceOperatorFactory buildSideSourceOperatorFactory;
        private final int partitionCount;
        private List<Driver> buildDrivers;
        private List<HashBuilderOperator> buildOperators;

        public BuildSideSetup(JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager, HashBuilderOperatorFactory buildOperatorFactory, LocalExchangeSourceOperatorFactory buildSideSourceOperatorFactory, int partitionCount)
        {
            this.lookupSourceFactoryManager = requireNonNull(lookupSourceFactoryManager, "lookupSourceFactoryManager is null");
            this.buildOperatorFactory = requireNonNull(buildOperatorFactory, "buildOperatorFactory is null");
            this.buildSideSourceOperatorFactory = buildSideSourceOperatorFactory;
            this.partitionCount = partitionCount;
        }

        public void setDriversAndOperators(List<Driver> buildDrivers, List<HashBuilderOperator> buildOperators)
        {
            checkArgument(buildDrivers.size() == buildOperators.size());
            this.buildDrivers = ImmutableList.copyOf(buildDrivers);
            this.buildOperators = ImmutableList.copyOf(buildOperators);
        }

        public JoinBridgeManager<PartitionedLookupSourceFactory> getLookupSourceFactoryManager()
        {
            return lookupSourceFactoryManager;
        }

        public HashBuilderOperatorFactory getBuildOperatorFactory()
        {
            return buildOperatorFactory;
        }

        public LocalExchangeSourceOperatorFactory getBuildSideSourceOperatorFactory()
        {
            return buildSideSourceOperatorFactory;
        }

        public int getPartitionCount()
        {
            return partitionCount;
        }

        public List<Driver> getBuildDrivers()
        {
            checkState(buildDrivers != null, "buildDrivers is not initialized yet");
            return buildDrivers;
        }

        public List<HashBuilderOperator> getBuildOperators()
        {
            checkState(buildOperators != null, "buildDrivers is not initialized yet");
            return buildOperators;
        }
    }

    public static class TestInternalJoinFilterFunction
            implements InternalJoinFilterFunction
    {
        public interface Lambda
        {
            boolean filter(int leftPosition, Page leftPage, int rightPosition, Page rightPage);
        }

        private final Lambda lambda;

        public TestInternalJoinFilterFunction(Lambda lambda)
        {
            this.lambda = lambda;
        }

        @Override
        public boolean filter(int leftPosition, Page leftPage, int rightPosition, Page rightPage)
        {
            return lambda.filter(leftPosition, leftPage, rightPosition, rightPage);
        }
    }
}


text:
package org.apache.lucene.codecs.idversion;

import java.io.IOException;

import org.apache.lucene.codecs.BlockTermState;
import org.apache.lucene.codecs.CodecUtil;
import org.apache.lucene.codecs.PostingsReaderBase;
import org.apache.lucene.index.DocsAndPositionsEnum;
import org.apache.lucene.index.DocsEnum;
import org.apache.lucene.index.FieldInfo;
import org.apache.lucene.store.DataInput;
import org.apache.lucene.store.IndexInput;
import org.apache.lucene.util.BitUtil;
import org.apache.lucene.util.Bits;

final class IDVersionPostingsReader extends PostingsReaderBase {

  @Override
  public void init(IndexInput termsIn) throws IOException {
    // Make sure we are talking to the matching postings writer
    CodecUtil.checkHeader(termsIn,
                          IDVersionPostingsWriter.TERMS_CODEC,
                          IDVersionPostingsWriter.VERSION_START,
                          IDVersionPostingsWriter.VERSION_CURRENT);
  }

  @Override
  public BlockTermState newTermState() {
    return new IDVersionTermState();
  }

  @Override
  public void close() throws IOException {
  }

  @Override
  public void decodeTerm(long[] longs, DataInput in, FieldInfo fieldInfo, BlockTermState _termState, boolean absolute)
    throws IOException {
    final IDVersionTermState termState = (IDVersionTermState) _termState;
    termState.docID = in.readVInt();
    if (absolute) {
      termState.idVersion = in.readVLong();
    } else {
      termState.idVersion += BitUtil.zigZagDecode(in.readVLong());
    }
  }

  @Override
  public DocsEnum docs(FieldInfo fieldInfo, BlockTermState termState, Bits liveDocs, DocsEnum reuse, int flags) throws IOException {
    SingleDocsEnum docsEnum;

    if (reuse instanceof SingleDocsEnum) {
      docsEnum = (SingleDocsEnum) reuse;
    } else {
      docsEnum = new SingleDocsEnum();
    }
    docsEnum.reset(((IDVersionTermState) termState).docID, liveDocs);

    return docsEnum;
  }

  @Override
  public DocsAndPositionsEnum docsAndPositions(FieldInfo fieldInfo, BlockTermState _termState, Bits liveDocs,
                                               DocsAndPositionsEnum reuse, int flags) {
    SingleDocsAndPositionsEnum posEnum;

    if (reuse instanceof SingleDocsAndPositionsEnum) {
      posEnum = (SingleDocsAndPositionsEnum) reuse;
    } else {
      posEnum = new SingleDocsAndPositionsEnum();
    }
    IDVersionTermState termState = (IDVersionTermState) _termState;
    posEnum.reset(termState.docID, termState.idVersion, liveDocs);
    return posEnum;
  }

  @Override
  public long ramBytesUsed() {
    return 0;
  }

  @Override
  public void checkIntegrity() throws IOException {
  }
}

redpajama_set_name: RedPajamaGithub


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

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-2" />
<title>MediCapital.pl - serwis medyczny z rejestracj� on-line do gabinet�w lekarskich </title>
<meta name="keywords" content="" />
<meta name="description" content="Digital Community" />
<link rel="home" href="http://pclab.pl" title="PCLab.pl" />
<link rel="alternate" type="application/rss+xml" title="Najnowsze artyku�y i aktualno�ci na portalu PCLab.pl" href="xml/rss.xml" />
<link rel="alternate" type="application/rss+xml" title="Najnowsze wiadomo�ci ze �wiata IT" href="xml/aktualnosci.xml" />
<link rel="alternate" type="application/rss+xml" title="Najnowsze artyku�y opublikowane na portalu PCLab.pl" href="xml/artykuly.xml" />
<link rel="alternate" type="application/rss+xml" title="Najnowsze dyskusje na forum PCLab.pl" href="xml/forum.xml" />
<link rel="alternate" type="application/rss+xml" title="Najnowsze pliki do pobrania z portalu PCLab.pl" href="xml/pliki.xml" />
<link rel="stylesheet" type="text/css" href="style3a.css" />
<link rel="stylesheet" type="text/css" href="style4p.css" />
<link rel="stylesheet" type="text/css" href="dokladka.css" />

<link rel="stylesheet" type="text/css" href="calendar.css" />
<link rel="stylesheet" type="text/css" href="ui.css" />

MediCapital

O nas

Bezpiecze�stwo

Reklama

Statystyki

Mapa strony

Oferta

Jak to dzia�a?

Korzy�ci

Dla u�ytkownika

Dla lekarzy

Dla aptek

Regulamin

Dla wszystkich

Dla u�ytkownika

Dla lekarzy

Dla aptek

Pomoc

Najcz�ciej zadawane pytania

Zadaj pytanie

Kontakt

Wy�lij do nas wiadomo��

Dane adresowe

Jak dojecha�

Newsletter MediCapital

Chcesz otrzymywa� od nas naj�wie�sze informacje
 dotycz�ce serwisu? To proste, zapisz si�!

							<input type="text" value="" class="inputNewsletter"/>
							<button type="image" class="buttonNewsletterApprove"></button>

					Copyright © MediCapital.pl, korzystanie z serwisu oznacza akceptacj� Regulaminu. Kopiowanie tre�ci oraz zdj�� zabronione.

					Valid XHTML | Valid CSS


text:
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2010 Hajime Tazaki
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Hajime Tazaki (tazaki@sfc.wide.ad.jp)
 */

//-----------------------------------------------------------------------------
// Unit tests
//-----------------------------------------------------------------------------

#include "ns3/test.h"
#include "ns3/rocketfuel-topology-reader.h"
#include "ns3/log.h"
#include "ns3/abort.h"
#include "ns3/attribute.h"
#include "ns3/object-factory.h"
#include "ns3/object-factory.h"
#include "ns3/simulator.h"

namespace ns3 {

class RocketfuelTopologyReaderTest : public TestCase
{
public:
  RocketfuelTopologyReaderTest ();
private:
  virtual void DoRun (void);
};

RocketfuelTopologyReaderTest::RocketfuelTopologyReaderTest ()
  : TestCase ("RocketfuelTopologyReaderTest")
{
}

void
RocketfuelTopologyReaderTest::DoRun (void)
{
  Ptr<RocketfuelTopologyReader> inFile;
  NodeContainer nodes;

  std::string input ("./src/topology-read/examples/RocketFuel_toposample_1239_weights.txt");

  inFile = CreateObject<RocketfuelTopologyReader> ();
  inFile->SetFileName (input);

  if (inFile != 0)
    {
      nodes = inFile->Read ();
    }

  NS_TEST_ASSERT_MSG_NE (nodes.GetN (), 0, "Problems reading node information the topology file..");

  NS_TEST_ASSERT_MSG_NE (inFile->LinksSize (), 0, "Problems reading the topology file.");

  NS_TEST_EXPECT_MSG_EQ (nodes.GetN (),315, "noes");
  NS_TEST_EXPECT_MSG_EQ (inFile->LinksSize (),972, "links");
  Simulator::Destroy ();
}

class RocketfuelTopologyReaderTestSuite : public TestSuite
{
public:
  RocketfuelTopologyReaderTestSuite ();
private:
};

RocketfuelTopologyReaderTestSuite::RocketfuelTopologyReaderTestSuite ()
  : TestSuite ("rocketfuel-topology-reader", UNIT)
{
  AddTestCase (new RocketfuelTopologyReaderTest (), TestCase::QUICK);
}

static RocketfuelTopologyReaderTestSuite rocketfuelTopologyReaderTestSuite;
}


text:
package org.apache.webdav.cmd;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * This class provides wrappers around an InputStream and
 * an OutputStream allowing you to spool both streams to a
 * shared OutputStream.
 *
 */
public class Spool
{
    private InputStream  in   = System.in;
    private OutputStream out  = System.out;
    private OutputStream spool= null;

    private InputStream  wrappedInputStream;
    private OutputStream wrappedOutputStream;

    private boolean echo=false;

    /**
     * Create a spool for these two streams
     */
    public Spool(InputStream in, OutputStream out)
    {
        this();
        this.in=in;
        this.out=out;
    }

    /**
     * Create a spool for System.in and System.out
     */
    public Spool()
    {
        wrappedInputStream = new InputStream()
        {
            public int read(byte b[]) throws IOException {
                int bytesRead = in.read(b);
                if (echo)
                    out.write(b,0,bytesRead);
                if (spool!=null)
                    spool.write(b,0,bytesRead);
                return bytesRead;
            }
            public int read(byte b[], int off, int len) throws IOException {
                int bytesRead = in.read(b,off,len);
                if (echo)
                    out.write(b,off,bytesRead);
                if (spool!=null)
                    spool.write(b,off,bytesRead);
                return bytesRead;
            }
            public int read() throws IOException {
                int nextByte = in.read();
                if ((nextByte!=-1) && (echo))
                    out.write(nextByte);
                if ((nextByte!=-1) && (spool!=null))
                    spool.write(nextByte);
                return nextByte;
            }
            public long skip(long n) throws IOException {
                return in.skip(n);
            }
            public int available() throws IOException {
                return in.available();
            }
            public void close() throws IOException {
                in.close();
            }
            public synchronized void mark(int readlimit) {
                in.mark(readlimit);
            }
            public synchronized void reset() throws IOException {
                in.reset();
            }
            public boolean markSupported() {
                return in.markSupported();
            }
        };
        wrappedOutputStream = new OutputStream()
        {
            public void write(int b) throws IOException {
                out.write(b);
                if (spool!=null)
                    spool.write(b);
            }
            public void write(byte b[]) throws IOException {
                out.write(b);
                if (spool!=null)
                    spool.write(b);
            }
            public void write(byte b[], int off, int len) throws IOException {
                out.write(b,off,len);
                if (spool!=null)
                    spool.write(b,off,len);
            }
            public void flush() throws IOException {
                out.flush();
                if (spool!=null)
                    spool.flush();
            }
            public void close() throws IOException {
                out.close();
            }
        };
    }

    /**
     * Echo the input stream to the output stream.
     */
    public void setEcho(boolean isEnabled)
    {
        this.echo=isEnabled;
    }

    /**
     * Enable spooling and spool to the given filename.
     */
    public void enable(String filename) throws FileNotFoundException
    {
        enable(new FileOutputStream(filename));
    }

    /**
     * Enable Spooling and spool to the given OutputStream.
     */
    public void enable(OutputStream spool)
    {
        if (isEnabled())
            disable();
        this.spool = spool;
    }

    /**
     * Disable spooling
     */
    public void disable()
    {
        try
        {
            if (spool!=null)
                spool.close();
        }
        catch (IOException ex)
        {
        }
        spool=null;
    }

    /**
     * Returns if spooling is enabled.
     */
    public boolean isEnabled()
    {
        return (spool!=null);
    }

    /**
     * Returns an InputStream wrapped around the real InputStream.
     * Use this stream to read from.
     */
    public InputStream getInputStream()
    {
        return wrappedInputStream;
    }

    /**
     * Returns an OutputStream wrapped around the real OutputStream.
     * Use this stream to write to.
     */
    public OutputStream getOutputStream()
    {
        return wrappedOutputStream;
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="blog,python,django,developer">
    <meta name="author" content="Derek Stegelman">

    <title>Derek.Stegelman.Com  | Work Life</title>

    <link rel="stylesheet" href='http://derek.stegelman.com/assets/bootstrap/css/bootstrap.min.css'>
    <link rel="stylesheet" href='http://derek.stegelman.com/assets/css/main.min.css'>
    <link href='https://fonts.googleapis.com/css?family=Raleway:200italic,200' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href='http://derek.stegelman.com/assets/font-awesome/css/font-awesome.min.css'>
    <link href='assets/css/prisim.min.css' rel='stylesheet' />

      <link href="http://derek.stegelman.com/categories/work-life/index.xml" rel="alternate" type="application/rss+xml" title="Derek.Stegelman.Com" />
      <link href="http://derek.stegelman.com/categories/work-life/index.xml" rel="feed" type="application/rss+xml" title="Derek.Stegelman.Com" />

    <meta property="og:title" content="Work Life" />
<meta property="og:description" content="" />
<meta property="og:type" content="website" />
<meta property="og:url" content="http://derek.stegelman.com/categories/work-life/" />

<meta property="og:updated_time" content="2014-08-14T00:00:00+00:00"/>

<meta itemprop="name" content="Work Life">
<meta itemprop="description" content="">

<meta name="twitter:card" content="summary"/><meta name="twitter:title" content="Work Life"/>
<meta name="twitter:description" content=""/>

Derek Stegelman

                Writing

                Technical Writing

              Thoughts

                About

Below you will find pages that utilize the taxonomy term "Work Life"

    Posts

        A Day in My Life

      Inspired by this lovely blog post by Colin Ross of Buffer app, I thought I’d document my day as a remote developer.
######Wake Up (5:50 - 6:30 AM)
I work on the central time schedule but live in the mountain time zone so I work one hour (and a bit earlier) than others here. This is great for me because I am a chronic early riser and get the best work done between 6:30 and 11 am everyday.

                                    Colophon

                                    Talks

                                    Hire

                                    Rocketry

                                    Essays

                                    Contact


text:
Spots2 integration/staging tree

http://www.theSPT.com/

Copyright (c) 2009-2013 Bitcoin Developers Copyright (c) 2011-2013 Litecoin Developers Copyright (c) 2014-2015 Spots2 Developers
What is Spots2?

Spots2 (SPT) is a lite version of Bitcoin using scrypt as a proof-of-work algorithm.

    70 second block targets
    reduction coins per block
    Retarget every block (Kimoto's gravity well)

For more information, as well as an immediately useable, binary version of the Spots2 client sofware, see http://www.theSPT.com/
License

Spots2 is released under the terms of the MIT license. See COPYING for more information or see http://opensource.org/licenses/MIT.
Ports / Important Details

    RPCPORT=5587
    P2PPORT=4588 (Note: Even though documented otherwise Spots has always been on port 4588 due to an error in the v1 code)
    RPC Test Net = 15587
    P2P Test Net = 15588

Scrypt & Kimoto's Gravity Well Fork - September 20, 2014 00:00:00 GMT
Web Pages

Main Page - http://spt.22web.org/ Block Explorer - http://www.crypto2.net/spots/ Official Pool - http://Mine.theSPT.com/ Paper Wallet - Coming Soon Forums - Comining Soon Spots Marketplace - Phase 2


text:
layout: post
title: "Generate crud in php"
permalink: generate-crud-in-php
date: 2013-03-03 18:52:21
comments: true
description: "generate crud in php"
keywords: "crud, scaffold"
categories: "php"

tags:

---

Recently, i've worked on an old PHP project trying to quickly add some new features to the application. As part of this task, i am supposed to write code that performs basic CRUD operations on a MySQL  table. Having achieved this like a charm using Rails, i've wondered if i can do scaffolding even in php. With some quick googling i've came across the service [PHPScaffold](http://www.phpscaffold.com/ "phpscaffold").

PHP Scaffold is an online utility where you can quickly generate your CRUD scaffold pages for PHP and MySQL. Follow the below steps to generate the scaffold pages.

Create the table of your interest in the MySQL database.

Copy the export SQL queries for the table.

Visit PHPScaffold and paste the export SQL in the big text area on the homepage.

Rename the scaffold pages that are to be created (Default is always fine).

Click on "Make my pages" button to create the scaffold pages.

There is no next step.

Happy coding 🙂


text:
author: robmyers
comments: true
date: 2013-12-09 07:23:36+00:00
layout: page
slug: postscript-viruses
title: PostScript Viruses
permalink: /postscript-viruses/
wordpress_id: 2422
---

* ![fractal1](/assets/2013/12/fractal1.png)
* ![fractal2](/assets/2013/12/fractal2.png)
* ![linofset](/assets/2013/12/linofset.png)

**PostScript Viruses, 1993, PostScript code.**

An excercise in aesthetic intervention in networked society.

You can download the code [here](https://gitorious.org/robmyers/postscript-viruses/).


text:
( function ( M, $ ) {
	var Infobox,
		md5fn = M.require( 'hex_md5' ),
		WikiDataApi = M.require( 'modules/WikiDataApi' ),
		View = M.require( 'View' ),
		user = M.require( 'user' ),
		icons = M.require( 'icons' ),
		months = [
			'january-date',
			'february-date',
			'march-date',
			'april-date',
			'may-date',
			'june-date',
			'july-date',
			'august-date',
			'september-date',
			'october-date',
			'november-date',
			'december-date'
		];

	/**
	 * A Wikidata generated infobox.
	 * Emits photo-loaded event when images in the infobox have loaded.
	 * @class Infobox
	 * @extends View
	 */
	Infobox = View.extend( {
		template: mw.template.get( 'mobile.infobox', 'Infobox.hogan' ),

		className: 'wikidata-infobox',
		/**
		 * @cfg {Object} defaults Default options hash.
		 * @cfg {String} defaults.spinner HTML of the spinner icon.
		 * @cfg {String} defaults.description WikiData description.
		 * Defaults to 'A Wikipedia page in need of a description.'
		 * @cfg {Array} defaults.rows Description of rows to show in Wikidata infobox
		 * e.g. [
		 * {
		 *   id: "P18",
		 *   isEmpty: false,
		 *   values: [
		 *     {
		 *       src: "https://upload.wikimedia.org/wikipedia/commons/thumb/e/ed/" +
		 *            "Anne_Dallas_Dudley_LOC.jpg/160px-Anne_Dallas_Dudley_LOC.jpg",
		 *       url: "/wiki/File:Anne_Dallas_Dudley_LOC.jpg"
		 *     }
		 *   ]
		 * },
		 * {
		 *   id: "P569",
		 *   isEmpty: false,
		 *   label: "Born"
		 * }
		 * ]
		 */
		defaults: {
			spinner: icons.spinner().toHtmlString(),
			description: mw.config.get( 'wgMFDescription' ) ||
				'A Wikipedia page in need of a description.',
			rows: []
		},
		typeDefaults: mw.config.get( 'wgMFInfoboxConfig' ),
		/** @inheritdoc */
		events: {
			'click .more': 'onExpandInfobox'
		},
		/**
		 * Given a title work out the url to the thumbnail for that image
		 * FIXME: This should not make its way into stable.
		 * @method
		 * @param {String} title of file page without File: prefix
		 * @return {String} url corresponding to thumbnail (size 160px)
		 */
		getImageUrl: function ( title ) {
			var md5, filename, source,
				path = 'https://upload.wikimedia.org/wikipedia/commons/';

			// uppercase first letter in file name
			filename = title.charAt( 0 ).toUpperCase() + title.substr( 1 );
			// replace spaces with underscores
			filename = filename.replace( / /g, '_' );
			md5 = md5fn( filename );
			source = md5.charAt( 0 ) + '/' + md5.substr( 0, 2 ) + '/' + filename;
			if ( filename.substr( filename.length - 3 ) !== 'svg' ) {
				return path + 'thumb/' + source + '/160px-' + filename;
			} else {
				return path + source;
			}
		},
		/**
		 * Parses a list of claims
		 *
		 * @private
		 * @method
		 * @param {Object} claims as returned by WikiData#getClaims
		 * @return {Array} List of values matching that claim
		 */
		_getValues: function ( claims ) {
			var values = [],
				self = this;

			$.each( claims, function ( i, claim ) {
				var snak = claim.mainsnak,
					value = snak.datavalue;
				if ( snak.snaktype === 'novalue' ) {
					values.push( {
						value: 'None'
					} );
				} else if ( snak.datatype === 'commonsMedia' ) {
					values.push( {
						type: 'commonsMedia',
						url: mw.util.getUrl( 'File:' + value.value ),
						src: self.getImageUrl( value.value )
					} );
				} else if ( value.type === 'string' ) {
					values.push( {
						value: value.value
					} );
				} else if ( value.type === 'time' ) {
					values.push( {
						value: self._getFormattedTime( value.value )
					} );
				} else if ( value.type === 'wikibase-entityid' ) {
					values.push( {
						type: 'item',
						id: 'Q' + value.value[ 'numeric-id' ],
						isLink: true
					} );
				} else if ( value.type === 'globecoordinate' ) {
					values.push( {
						value: value.value.latitude + ', ' + value.value.longitude
					} );
				} else if ( value.type === 'quantity' ) {
					// FIXME: Deal with qualifiers
					values.push( {
						value: value.value.amount
					} );
				} else {
					console.log( value.type + ' unknown', value );
				}
			} );
			return values;
		},
		/**
		 * Return a user friendly version of time.
		 * @param {Object} time
		 * Example:
		 * {
		 *     after: 0,
		 *     before: 0,
		 *     calendarmodel: "http://www.wikidata.org/entity/Q1985727",
		 *     precision: 9,
		 *     time: "-00000000550-01-01T00:00:00Z",
		 *     timezone: 0
		 * }
		 * @returns {String} Formatted time
		 * Example: '550 BCE'
		 * @private
		 * FIXME: timezone is assumed to be UTC. Explore using http://momentjs.com/timezone/
		 */
		_getFormattedTime: function ( time ) {
			var formattedTime,
				date = new Date( time.time.substr( 8 ) ),
				year = date.getUTCFullYear().toString(),
				isBCE = time.time.charAt( 0 ) === '-',
				eraMessage = 'mobile-frontend-time-precision-' +
					( isBCE ? 'BCE-' : '' );
			// Precision Values:
			// 0 - billion years
			// 1 - hundred million years
			// 2...
			// 6 - millennium
			// 7 - century
			// 8 - decade
			// 9 - year
			// 10 - month
			// 11 - day
			// 12 - hour
			// 13 - minute
			// 14 - second
			switch ( time.precision ) {
				case 0:
					formattedTime = mw.msg( eraMessage + 'Gannum', year );
					break;
				case 1:
				case 2:
				case 3:
				case 4:
					formattedTime = mw.msg( eraMessage + 'Mannum', year );
					break;
				case 5:
					formattedTime = mw.msg( eraMessage + 'annum', year );
					break;
				case 6:
					formattedTime = mw.msg( eraMessage + 'millennium', year );
					break;
				case 7:
					formattedTime = mw.msg( eraMessage + 'century', year );
					break;
				case 8:
					formattedTime = mw.msg( eraMessage + '10annum', year );
					break;
				default:
					formattedTime = mw.msg( eraMessage + '0annum', year );
					break;
			}
			// month
			if ( time.precision === 10 ) {
				formattedTime = $.trim( mw.msg(
					months[date.getUTCMonth()],
					''
				) ) + ' ' + formattedTime;
				// date
			} else if ( time.precision > 10 ) {
				formattedTime = mw.msg(
					months[ date.getUTCMonth() ],
					date.getUTCDate().toString()
				) + ' ' + formattedTime;
			}
			// ignore time
			return formattedTime;
		},
		/**
		 * Translates IDs in the current row value to human readable text
		 *
		 * @private
		 * @method
		 * @param {Array} rows with id and label
		 * @return {Array} rows with human readable values
		 */
		_mapLabels: function ( rows ) {
			var labelIds = [];

			// collect all the label ids
			$.each( rows, function ( i, row ) {
				labelIds.push( row.id );
				$.each( row.values, function ( i, value ) {
					if ( value.id ) {
						labelIds.push( value.id );
					}
				} );
			} );

			// work out what they all mean
			return this.api.getExpandedItemsData( labelIds ).then( function ( labels ) {
				// map the property id to the actual label.
				$.each( rows, function ( i, row ) {
					var meta = labels[ row.id ];
					if ( meta ) {
						row.label = meta.label;
						row.type = meta.type;
					} else {
						row.label = 'No label.';
					}

					$.each( row.values, function ( j, value ) {
						var item = labels[ value.id ];
						if ( item ) {
							value.value = item.label;
							value.url = item.url;
						}
					} );
				} );
				return rows;
			} );
		},
		/**
		 * Decides based on the type of item what infobox to render
		 *
		 * @private
		 * @method
		 * @param {Object} claims as returned by WikiData#getClaims
		 * @return {Object} default option values
		 */
		getDefaultsFromClaims: function ( claims ) {
			var defaults,
				self = this,
				fallback = this.typeDefaults['default'] ||
					{
						rows: []
					};

			// Iterate through instances assuming priority order
			$.each( claims.instanceTypes, function () {
				// Pick the first match
				if ( !defaults ) {
					defaults = self.typeDefaults[this];
				}
			} );
			return defaults || fallback;
		},
		/**
		 * Get the deferred object associated with the infobox
		 *
		 * @return {jQuery.Deferred}
		 */
		getDeferred: function () {
			return this.$deferred;
		},
		/**
		 * @inheritdoc
		 */
		initialize: function ( options ) {
			this.$deferred = $.Deferred();
			this.api = new WikiDataApi( {
				itemId: options.itemId
			} );

			View.prototype.initialize.apply( this, arguments );
			this.on( 'load', $.proxy( this, '_loadRest', options ) );
		},
		/**
		 * Get an instance of the wikidata api
		 *
		 * @return {WikiDataApi}
		 */
		getApi: function () {
			return this.api;
		},
		/**
		 * @inheritdoc
		 */
		postRender: function () {
			if ( user.isAnon() ) {
				this.$( '.edit' ).remove();
			}
			this.$( '.spinner' ).hide();
		},
		/**
		 * Event handler that runs when the more button is clicked.
		 * @param {jQuery.Event} ev
		 */
		onExpandInfobox: function ( ev ) {
			$( ev.target ).remove();
			this.emit( 'load' );
			this.postRender( this.options );
		},
		/**
		 * Decides based on the type of item what infobox to render
		 *
		 * @private
		 * @method
		 * @param {Object} options for overlay
		 */
		_loadRest: function ( options ) {
			var self = this,
				_super = View.prototype.render;

			this.$( '.spinner' ).show();
			this.api.getClaims().done( function ( claims ) {
				var rows,
					isEmptyInfobox = true,
					commonsCategory = mw.config.get( 'wgWikiBasePropertyConfig' ).commonsCategory;

				options = $.extend( options, self.getDefaultsFromClaims( claims ) );
				if ( options.rows ) {
					rows = options.rows;
				} else {
					// FIXME: Show toast?
					throw 'Invalid configuration for infobox on this page.';
				}
				if ( claims.description ) {
					options.description = claims.description;
				}
				$.each( rows, function ( i, row ) {
					var claimRow = claims.entities[ row.id ];
					if ( claims.entities && claims.entities[ row.id ] ) {
						row.values = self._getValues( claimRow );
					} else {
						row.values = [];
					}
					if ( row.values && row.values.length ) {
						isEmptyInfobox = false;
					} else {
						row.isEmpty = true;
					}
				} );

				// check, if the wikidata item has a commons category and add the link to it
				if ( claims.entities.hasOwnProperty( commonsCategory ) ) {
					options.commonsLink = '#/commons-category/' + claims.entities[commonsCategory][0].mainsnak.datavalue.value;
				}

				options.isEmptyInfobox = isEmptyInfobox;
				self._mapLabels( rows ).done( function ( rows ) {
					options.rows = rows;

					self.options = options;
					self.$deferred.resolve();
					_super.call( self, options );
					self.$( '.hidden' ).removeClass( 'hidden' );
					M.emit( 'photo-loaded', self.$el );
				} );
			} ).fail( function () {
				// remove spinner
				self.$el.remove();
			} );
		}
	} );

	M.define( 'modules/Infobox', Infobox );

}( mw.mobileFrontend, jQuery ) );


text:
package org.jibx.binding.def;

import org.apache.bcel.classfile.Utility;

import org.jibx.binding.classes.*;
import org.jibx.runtime.JiBXException;

/**
 * String conversion handling. Defines serialization handling for converting
 * to and from a String value. This uses an inheritance approach,
 * where each serialization definition is initialized based on the handling
 * set for the containing definition of the same (or parent class) type.
 *
 * @author Dennis M. Sosnoski
 */
public abstract class StringConversion
{
    //
    // Constants for code generation.

    protected static final String UNMARSHAL_OPT_ATTRIBUTE =
        "org.jibx.runtime.impl.UnmarshallingContext.attributeText";
    protected static final String UNMARSHAL_OPT_ELEMENT =
        "org.jibx.runtime.impl.UnmarshallingContext.parseElementText";
    protected static final String UNMARSHAL_OPT_SIGNATURE =
        "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)" +
        "Ljava/lang/String;";
    protected static final String UNMARSHAL_REQ_ATTRIBUTE =
        "org.jibx.runtime.impl.UnmarshallingContext.attributeText";
    protected static final String UNMARSHAL_REQ_ELEMENT =
        "org.jibx.runtime.impl.UnmarshallingContext.parseElementText";
    protected static final String UNMARSHAL_REQ_SIGNATURE =
        "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;";
    protected static final String MARSHAL_ATTRIBUTE =
        "org.jibx.runtime.impl.MarshallingContext.attribute";
    protected static final String MARSHAL_ELEMENT =
        "org.jibx.runtime.impl.MarshallingContext.element";
    protected static final String MARSHAL_SIGNATURE =
        "(ILjava/lang/String;Ljava/lang/String;)" +
        "Lorg/jibx/runtime/impl/MarshallingContext;";
    protected static final String COMPARE_OBJECTS_METHOD =
        "org.jibx.runtime.Utility.isEqual";
    protected static final String COMPARE_OBJECTS_SIGNATURE =
        "(Ljava/lang/Object;Ljava/lang/Object;)Z";
    protected static final String[] WHITESPACE_CONVERT_SIGNATURES =
    {
        "(Ljava/lang/String;)Ljava/lang/String;"
    };
    protected static final String[] DESERIALIZER_SIGNATURES =
    {
        "(Ljava/lang/String;)",
        "(Ljava/lang/String;Lorg/jibx/runtime/IUnmarshallingContext;)"
    };

    // values used for name in marshalling; must be 1 or 2
    public static final int MARSHAL_NAME_VALUES = 2;

    //
    // Actual instance data

    /** Default value used for this type (wrapper for primitives, otherwise
     String or null). */
    protected Object m_default;

    /** Serializer method information. */
    protected ClassItem m_serializer;

    /** Whitespace conversion method information. */
    protected ClassItem m_converter;

    /** Deserializer method information. */
    protected ClassItem m_deserializer;

    /** Fully qualified name of class handled by conversion. */
    protected String m_typeName;

    /** Signature of class handled by conversion. */
    protected String m_typeSignature;

    /**
     * Constructor. This internal form only initializes the type information.
     *
     * @param type fully qualified name of class handled by conversion
     */
    private StringConversion(String type) {
        m_typeName = type;
        m_typeSignature = Utility.getSignature(type);
    }

    /**
     * Constructor. Initializes conversion handling based on the supplied
     * inherited handling.
     *
     * @param type fully qualified name of class handled by conversion
     * @param inherit conversion information inherited by this conversion
     */
    protected StringConversion(String type, StringConversion inherit) {
        this(type);
        m_default = inherit.m_default;
        m_serializer = inherit.m_serializer;
        m_converter = inherit.m_converter;
        m_deserializer = inherit.m_deserializer;
    }

    /**
     * Constructor. Initializes conversion handling based on argument values.
     * This form is only used for constructing the default set of conversions.
     * Because of this, it throws an unchecked exception on error.
     *
     * @param dflt default value object (wrapped value for primitive types,
     * otherwise String)
     * @param ser fully qualified name of serialization method
     * (null if none)
     * @param conv fully qualified name of whitespace conversion method
     * (null if none)
     * @param deser fully qualified name of deserialization method
     * (null if none)
     * @param type fully qualified name of class handled by conversion
     */
    /*package*/ StringConversion(Object dflt, String ser, String conv,
        String deser, String type) {
        this(type);
        m_default = dflt;
        try {
            if (ser != null) {
                setSerializer(ser, false);
            }
            if (conv != null) {
                setWhitespaceConverter(conv);
            }
            if (deser != null) {
                setDeserializer(deser);
            }
        } catch (JiBXException ex) {
            throw new IllegalArgumentException(ex.getMessage());
        }
    }

    /**
     * Get name of type handled by this conversion.
     *
     * @return fully qualified class name of type handled by conversion
     */
    public String getTypeName() {
        return m_typeName;
    }

    /**
     * Generate code to convert String representation. The
     * code generated by this method assumes that the String
     * value has already been pushed on the stack. It consumes this and
     * leaves the converted value on the stack.
     *
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public abstract void genFromText(ContextMethodBuilder mb)
        throws JiBXException;

    /**
     * Generate code to parse and convert optional attribute or element. This
     * abstract base class method must be implemented by every subclass. The
     * code generated by this method assumes that the unmarshalling context
     * and name information for the attribute or element have already
     * been pushed on the stack. It consumes these and leaves the converted
     * value (or converted default value, if the item itself is missing) on
     * the stack.
     *
     * @param attr item is an attribute (vs element) flag
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public abstract void genParseOptional(boolean attr, ContextMethodBuilder mb)
        throws JiBXException;

    /**
     * Generate code to parse and convert required attribute or element. This
     * abstract base class method must be implemented by every subclass. The
     * code generated by this method assumes that the unmarshalling context and
     * name information for the attribute or element have already been pushed
     * on the stack. It consumes these and leaves the converted value on the
     * stack.
     *
     * @param attr item is an attribute (vs element) flag
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public abstract void genParseRequired(boolean attr, ContextMethodBuilder mb)
        throws JiBXException;

    /**
     * Generate code to write String value to generated document.
     * The code generated by this method assumes that the marshalling context,
     * the name information, and the actual value to be converted have already
     * been pushed on the stack. It consumes these, leaving the marshalling
     * context on the stack.
     *
     * @param attr item is an attribute (vs element) flag
     * @param mb method builder
     */
    public void genWriteText(boolean attr, ContextMethodBuilder mb) {

        // append code to call the appropriate generic marshalling context
        //  String method
        String name = attr ? MARSHAL_ATTRIBUTE : MARSHAL_ELEMENT;
        mb.appendCallVirtual(name, MARSHAL_SIGNATURE);
    }

    /**
     * Generate code to pop values from stack.
     *
     * @param count number of values to be popped
     * @param mb method builder
     */
    public void genPopValues(int count, ContextMethodBuilder mb) {
        while (--count >= 0) {
            if (mb.isStackTopLong()) {
                mb.appendPOP2();
            } else {
                mb.appendPOP();
            }
        }
    }

    /**
     * Generate code to check if an optional value is not equal to the default.
     * This abstract base class method must be implemented by every subclass.
     * The code generated by this method assumes that the actual value to be
     * converted has already been pushed on the stack. It consumes this,
     * leaving the converted text reference on the stack if it's not equal to
     * the default value.
     *
     * @param type fully qualified class name for value on stack
     * @param mb method builder
     * @param extra count of extra words to be popped from stack if missing
     * @return handle for branch taken when value is equal to the default
     * (target must be set by caller)
     * @throws JiBXException if error in configuration
     */
    protected abstract BranchWrapper genToOptionalText(String type,
        ContextMethodBuilder mb, int extra) throws JiBXException;

    /**
     * Generate code to convert value to a String. The code
     * generated by this method assumes that the actual value to be converted
     * has already been pushed on the stack. It consumes this, leaving the
     * converted text reference on the stack.
     *
     * @param type fully qualified class name for value on stack
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public void genToText(String type, ContextMethodBuilder mb)
        throws JiBXException {

        // check if a serializer is used for this type
        if (m_serializer != null) {

            // just generate call to the serializer (adding any checked
            //  exceptions thrown by the serializer to the list needing
            //  handling)
            if (!isPrimitive()) {
                mb.appendCreateCast(type, m_serializer.getArgumentType(0));
            }
            mb.addMethodExceptions(m_serializer);
            if (m_serializer.getArgumentCount() > 1) {
                mb.loadContext();
            }
            mb.appendCall(m_serializer);

        } else {

            // make sure this is a string
            mb.appendCreateCast(type, "java.lang.String");
        }
    }

    /**
     * Generate code to convert and write optional value to generated document.
     * The generated code first tests if the value is the same as the supplied
     * default, and if so skips writing. The code assumes that the marshalling
     * context, the name information, and the actual value to be converted have
     * already been pushed on the stack. It consumes these, leaving only the
     * marshalling context on the stack.
     *
     * @param attr item is an attribute (vs element) flag
     * @param type fully qualified class name for value on stack
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public void genWriteOptional(boolean attr, String type,
        ContextMethodBuilder mb) throws JiBXException {

        // start with code to convert value to String, if it's not equal to the
        //  default value
        BranchWrapper toend = genToOptionalText(type, mb, MARSHAL_NAME_VALUES);

        // next use standard write code, followed by targeting branch
        genWriteText(attr, mb);
        if (toend != null) {
            mb.targetNext(toend);
        }
    }

    /**
     * Generate code to convert and write required value to generated document.
     * The code generated by this method assumes that the marshalling context,
     * the name information, and the actual value to be converted have already
     * been pushed on the stack. It consumes these, leaving the returned
     * marshalling context on the stack.
     *
     * @param attr item is an attribute (vs element) flag
     * @param type fully qualified class name for value on stack
     * @param mb method builder
     * @throws JiBXException if error in configuration
     */
    public void genWriteRequired(boolean attr, String type,
        ContextMethodBuilder mb) throws JiBXException {

        // generate code to convert to text, followed by code to marshal text
        genToText(type, mb);
        genWriteText(attr, mb);
    }

    /**
     * Check if the type handled by this conversion is of a primitive type.
     *
     * @return true if a primitive type, false if an
     * object type
     */
    public abstract boolean isPrimitive();

    /**
     * Set serializer for conversion. This finds the named static method and
     * sets it as the serializer to be used for this conversion. The serializer
     * method is expected to take a single argument of either the handled
     * type or a superclass or interface of the handled type, and to return a
     * String result.
     *
     * @param ser fully qualified class and method name of serializer
     * @param variant allow variants of the specified type
     * @throws JiBXException if serializer not found or not usable
     */
    protected void setSerializer(String ser, boolean variant) throws JiBXException {

        // build all possible signature variations
        String[] tsigs;
        if (variant) {
            tsigs = ClassItem.getSignatureVariants(m_typeName);
        } else {
            tsigs = new String[] { Utility.getSignature(m_typeName) };
        }
        String[] msigs = new String[tsigs.length*2];
        for (int i = 0; i < tsigs.length; i++) {
            msigs[i*2] = "(" + tsigs[i] + ")Ljava/lang/String;";
            msigs[i*2+1] = "(" + tsigs[i] +
                "Lorg/jibx/runtime/IMarshallingContext;)Ljava/lang/String;";
        }

        // find a matching static method
        ClassItem method = ClassItem.findStaticMethod(ser, msigs);

        // report error if method not found
        if (method == null) {
            throw new JiBXException("Serializer " + ser + " not found");
        } else {
            m_serializer = method;
        }
    }

    /**
     * Set whitespace converter for conversion. This finds the named static
     * method and sets it as the whitespace converter to be used for this
     * conversion. The whitespace converter method is expected to take a
     * single argument of type String, and to return the same.
     *
     * @param wsconv fully qualified class and method name of whitespace
     * converter
     * @throws JiBXException if whitespace converter not found or not usable
     */
    protected void setWhitespaceConverter(String wsconv) throws JiBXException {

        // find a matching static method
        m_converter =
            ClassItem.findStaticMethod(wsconv, WHITESPACE_CONVERT_SIGNATURES);

        // report error if method not found or incompatible
        if (m_converter == null) {
            throw new JiBXException("Whitespace converter " + wsconv + " not found");
        }
    }

    /**
     * Set deserializer for conversion. This finds the named static method and
     * sets it as the deserializer to be used for this conversion. The
     * deserializer method is expected to take a single argument of type
     * String, and to return a value of the handled type or a
     * subtype of that type.
     *
     * @param deser fully qualified class and method name of deserializer
     * @throws JiBXException if deserializer not found or not usable
     */
    protected void setDeserializer(String deser) throws JiBXException {

        // find a matching static method
        ClassItem method =
            ClassItem.findStaticMethod(deser, DESERIALIZER_SIGNATURES);

        // report error if method not found or incompatible
        if (method == null) {
            throw new JiBXException("Deserializer " + deser + " not found");
        } else if (ClassItem.isAssignable(method.getTypeName(), m_typeName)) {
            m_deserializer = method;
        } else {
            throw new JiBXException("Deserializer " + deser +
                " returns wrong type");
        }
    }

    /**
     * Convert text representation into default value object. Each subclass
     * must implement this with the appropriate conversion handling.
     *
     * @param text value representation to be converted
     * @return converted default value object
     * @throws JiBXException on conversion error
     */
    protected abstract Object convertDefault(String text) throws JiBXException;

    /**
     * Derive from existing formatting information. This abstract base class
     * method must be implemented by every subclass. It allows constructing
     * a new instance from an existing format of the same or an ancestor
     * type, with the properties of the existing format copied to the new
     * instance except where overridden by the supplied values.
     *
     * @param type fully qualified name of class handled by conversion
     * (null if inherited)
     * @param ser fully qualified name of serialization method
     * (null if inherited)
     * @param conv fully qualified name of whitespace conversion method
     * (null if inherited)
     * @param dser fully qualified name of deserialization method
     * (null if inherited)
     * @param dflt default value text (null if inherited)
     * @return new instance initialized from existing one
     * @throws JiBXException if error in configuration information
     */
    public abstract StringConversion derive(String type, String ser,
        String conv, String dser, String dflt) throws JiBXException;
}


text:
<!DOCTYPE html>

    Username:
    <input id="username" name="user" type="text"/>
    <input id="connect" type='button' value='connect'/>

    Message:
    <input id="message" name="message" type="text"/>
    <input id="send" type="button" value="send" />

    <textarea id="chat" rows="20" cols="40" readonly> </textarea>

Try This!!! Type blue, pink, or white to change the room color

Users Online: