text:
<?php

namespace Ekyna\Bundle\CommerceBundle\Service\Document;

use Ekyna\Component\Commerce\Document\Model\DocumentTypes;
use Ekyna\Component\Commerce\Exception\InvalidArgumentException;
use Ekyna\Component\Commerce\Exception\LogicException;
use Ekyna\Component\Commerce\Shipment\Model\ShipmentInterface;

/**
 * Class ShipmentRenderer
 * @package Ekyna\Bundle\CommerceBundle\Service\Document
 * @author  Etienne Dauvergne <contact@ekyna.com>
 */
class ShipmentRenderer extends AbstractRenderer
{
    /**
     * @var string
     */
    private $type;

    /**
     * @inheritdoc
     */
    public function __construct($subjects, $type)
    {
        if (!in_array($type, DocumentTypes::getShipmentTypes(), true)) {
            throw new InvalidArgumentException("Unexpected shipment document type '$type'.");
        }

        if ($type === DocumentTypes::TYPE_SHIPMENT_FORM) {
            $subjects = array_filter($subjects, function (ShipmentInterface $shipment) {
                return !$shipment->isReturn();
            });
        }

        parent::__construct($subjects);

        $this->type = $type;
    }

    /**
     * @inheritdoc
     */
    public function getFilename()
    {
        if (empty($this->subjects)) {
            throw new LogicException("Please add shipment(s) first.");
        }

        if (1 < count($this->subjects)) {
            return 'shipments';
        }

        /** @var ShipmentInterface $subject */
        $subject = reset($this->subjects);

        return 'shipment_' . $this->type . '_' . $subject->getNumber();
    }

    /**
     * @inheritDoc
     */
    protected function getContent(string $format): string
    {
        if ($this->type === DocumentTypes::TYPE_SHIPMENT_FORM) {
            return $this->templating->render('@EkynaCommerce/Document/shipment_form.html.twig', [
                'subjects' => $this->subjects,
            ]);
        }

        return parent::getContent($format);
    }

    /**
     * @inheritdoc
     */
    protected function getParameters()
    {
        return [
            'remaining_date' => $this->config['shipment_remaining_date'],
            'type'           => $this->type,
        ];
    }

    /**
     * @inheritdoc
     */
    protected function supports($subject)
    {
        return $subject instanceof ShipmentInterface;
    }

    /**
     * @inheritdoc
     */
    protected function getTemplate()
    {
        return '@EkynaCommerce/Document/shipment.html.twig';
    }
}


text:
<CrawlItem>
  <Text>korektno, brza dostava</Text>
  <Rating>6</Rating>
  <Source>http://pauza.hr/menu/sombrero-catering-savica</Source>
  <Sentences>
    <SentenceInfo>
      <Text>korektno , brza dostava </Text>
      <StartPosition>0</StartPosition>
      <TaggedWords>
        <CROTaggedWord>
          <Word>korektno</Word>
          <Lemma>korektno</Lemma>
          <MolexLemmas>
            <string>korektan</string>
          </MolexLemmas>
          <POSTag>R</POSTag>
          <BasicStem>korektn</BasicStem>
          <MSDs>
            <string>Afpnsan</string>
            <string>Afpnsay</string>
            <string>Afpnsnn</string>
            <string>Afpnsny</string>
            <string>Afpnsvn</string>
            <string>Afpnsvy</string>
          </MSDs>
          <Position>0</Position>
          <SentenceIndex>0</SentenceIndex>
        </CROTaggedWord>
        <CROTaggedWord>
          <Word>,</Word>
          <Lemma>,</Lemma>
          <MolexLemmas>
            <string>,</string>
          </MolexLemmas>
          <POSTag>Z</POSTag>
          <BasicStem>,</BasicStem>
          <MSDs />
          <Position>9</Position>
          <SentenceIndex>1</SentenceIndex>
        </CROTaggedWord>
        <CROTaggedWord>
          <Word>brza</Word>
          <Lemma>brz</Lemma>
          <MolexLemmas>
            <string>brzati</string>
            <string>brz</string>
          </MolexLemmas>
          <POSTag>A</POSTag>
          <BasicStem>brz</BasicStem>
          <MSDs>
            <string>Vmip3s</string>
            <string>Afpfsnn</string>
            <string>Afpfsny</string>
            <string>Afpfsvn</string>
            <string>Afpfsvy</string>
            <string>Afpmsgn</string>
            <string>Afpnpan</string>
            <string>Afpnpay</string>
            <string>Afpnpnn</string>
            <string>Afpnpny</string>
            <string>Afpnpvn</string>
            <string>Afpnpvy</string>
            <string>Afpnsgn</string>
          </MSDs>
          <Position>11</Position>
          <SentenceIndex>2</SentenceIndex>
        </CROTaggedWord>
        <CROTaggedWord>
          <Word>dostava</Word>
          <Lemma>dostava</Lemma>
          <MolexLemmas>
            <string>dostava</string>
          </MolexLemmas>
          <POSTag>N</POSTag>
          <BasicStem>dostav</BasicStem>
          <MSDs>
            <string>N=fpg</string>
            <string>N=fsn</string>
          </MSDs>
          <Position>16</Position>
          <SentenceIndex>3</SentenceIndex>
        </CROTaggedWord>
      </TaggedWords>
      <DependencyRelations>
        <DependencyRelation>
          <Governor>
            <Word>brza</Word>
            <Lemma>brz</Lemma>
            <MolexLemmas>
              <string>brzati</string>
              <string>brz</string>
            </MolexLemmas>
            <POSTag>A</POSTag>
            <BasicStem>brz</BasicStem>
            <MSDs>
              <string>Vmip3s</string>
              <string>Afpfsnn</string>
              <string>Afpfsny</string>
              <string>Afpfsvn</string>
              <string>Afpfsvy</string>
              <string>Afpmsgn</string>
              <string>Afpnpan</string>
              <string>Afpnpay</string>
              <string>Afpnpnn</string>
              <string>Afpnpny</string>
              <string>Afpnpvn</string>
              <string>Afpnpvy</string>
              <string>Afpnsgn</string>
            </MSDs>
            <Position>11</Position>
            <SentenceIndex>2</SentenceIndex>
          </Governor>
          <Dependent>
            <Word>korektno</Word>
            <Lemma>korektno</Lemma>
            <MolexLemmas>
              <string>korektan</string>
            </MolexLemmas>
            <POSTag>R</POSTag>
            <BasicStem>korektn</BasicStem>
            <MSDs>
              <string>Afpnsan</string>
              <string>Afpnsay</string>
              <string>Afpnsnn</string>
              <string>Afpnsny</string>
              <string>Afpnsvn</string>
              <string>Afpnsvy</string>
            </MSDs>
            <Position>0</Position>
            <SentenceIndex>0</SentenceIndex>
          </Dependent>
          <Relation>Oth</Relation>
        </DependencyRelation>
        <DependencyRelation>
          <Governor>
            <Word>korektno</Word>
            <Lemma>korektno</Lemma>
            <MolexLemmas>
              <string>korektan</string>
            </MolexLemmas>
            <POSTag>R</POSTag>
            <BasicStem>korektn</BasicStem>
            <MSDs>
              <string>Afpnsan</string>
              <string>Afpnsay</string>
              <string>Afpnsnn</string>
              <string>Afpnsny</string>
              <string>Afpnsvn</string>
              <string>Afpnsvy</string>
            </MSDs>
            <Position>0</Position>
            <SentenceIndex>0</SentenceIndex>
          </Governor>
          <Dependent>
            <Word>,</Word>
            <Lemma>,</Lemma>
            <MolexLemmas>
              <string>,</string>
            </MolexLemmas>
            <POSTag>Z</POSTag>
            <BasicStem>,</BasicStem>
            <MSDs />
            <Position>9</Position>
            <SentenceIndex>1</SentenceIndex>
          </Dependent>
          <Relation>Punc</Relation>
        </DependencyRelation>
        <DependencyRelation>
          <Governor>
            <Word>brza</Word>
            <Lemma>brz</Lemma>
            <MolexLemmas>
              <string>brzati</string>
              <string>brz</string>
            </MolexLemmas>
            <POSTag>A</POSTag>
            <BasicStem>brz</BasicStem>
            <MSDs>
              <string>Vmip3s</string>
              <string>Afpfsnn</string>
              <string>Afpfsny</string>
              <string>Afpfsvn</string>
              <string>Afpfsvy</string>
              <string>Afpmsgn</string>
              <string>Afpnpan</string>
              <string>Afpnpay</string>
              <string>Afpnpnn</string>
              <string>Afpnpny</string>
              <string>Afpnpvn</string>
              <string>Afpnpvy</string>
              <string>Afpnsgn</string>
            </MSDs>
            <Position>11</Position>
            <SentenceIndex>2</SentenceIndex>
          </Governor>
          <Dependent>
            <Word>dostava</Word>
            <Lemma>dostava</Lemma>
            <MolexLemmas>
              <string>dostava</string>
            </MolexLemmas>
            <POSTag>N</POSTag>
            <BasicStem>dostav</BasicStem>
            <MSDs>
              <string>N=fpg</string>
              <string>N=fsn</string>
            </MSDs>
            <Position>16</Position>
            <SentenceIndex>3</SentenceIndex>
          </Dependent>
          <Relation>Obj</Relation>
        </DependencyRelation>
      </DependencyRelations>
    </SentenceInfo>
  </Sentences>
  <TaggedWords>
    <CROTaggedWord>
      <Word>korektno</Word>
      <Lemma>korektno</Lemma>
      <MolexLemmas>
        <string>korektan</string>
      </MolexLemmas>
      <POSTag>R</POSTag>
      <BasicStem>korektn</BasicStem>
      <MSDs>
        <string>Afpnsan</string>
        <string>Afpnsay</string>
        <string>Afpnsnn</string>
        <string>Afpnsny</string>
        <string>Afpnsvn</string>
        <string>Afpnsvy</string>
      </MSDs>
      <Position>0</Position>
      <SentenceIndex>0</SentenceIndex>
    </CROTaggedWord>
    <CROTaggedWord>
      <Word>,</Word>
      <Lemma>,</Lemma>
      <MolexLemmas>
        <string>,</string>
      </MolexLemmas>
      <POSTag>Z</POSTag>
      <BasicStem>,</BasicStem>
      <MSDs />
      <Position>9</Position>
      <SentenceIndex>1</SentenceIndex>
    </CROTaggedWord>
    <CROTaggedWord>
      <Word>brza</Word>
      <Lemma>brz</Lemma>
      <MolexLemmas>
        <string>brzati</string>
        <string>brz</string>
      </MolexLemmas>
      <POSTag>A</POSTag>
      <BasicStem>brz</BasicStem>
      <MSDs>
        <string>Vmip3s</string>
        <string>Afpfsnn</string>
        <string>Afpfsny</string>
        <string>Afpfsvn</string>
        <string>Afpfsvy</string>
        <string>Afpmsgn</string>
        <string>Afpnpan</string>
        <string>Afpnpay</string>
        <string>Afpnpnn</string>
        <string>Afpnpny</string>
        <string>Afpnpvn</string>
        <string>Afpnpvy</string>
        <string>Afpnsgn</string>
      </MSDs>
      <Position>11</Position>
      <SentenceIndex>2</SentenceIndex>
    </CROTaggedWord>
    <CROTaggedWord>
      <Word>dostava</Word>
      <Lemma>dostava</Lemma>
      <MolexLemmas>
        <string>dostava</string>
      </MolexLemmas>
      <POSTag>N</POSTag>
      <BasicStem>dostav</BasicStem>
      <MSDs>
        <string>N=fpg</string>
        <string>N=fsn</string>
      </MSDs>
      <Position>16</Position>
      <SentenceIndex>3</SentenceIndex>
    </CROTaggedWord>
  </TaggedWords>
</CrawlItem>

redpajama_set_name: RedPajamaGithub


text:
package org.robolectric.res;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

import static android.os.Build.VERSION_CODES.N_MR1;
import static org.assertj.core.api.Assertions.assertThat;
import static org.robolectric.util.TestUtil.gradleAppResources;
import static org.robolectric.util.TestUtil.sdkResources;
import static org.robolectric.util.TestUtil.testResources;

@RunWith(JUnit4.class)
public class ResourceParserTest {

  private ResourceTable resourceTable;
  private ResourceTable gradleResourceTable;

  @Before
  public void setUp() {
    ResourceTableFactory resourceTableFactory = new ResourceTableFactory();
    resourceTable = resourceTableFactory.newResourceTable("org.robolectric", testResources());
    gradleResourceTable = resourceTableFactory.newResourceTable("org.robolectric.gradleapp", gradleAppResources());
  }

  @Test
  public void shouldLoadDrawableXmlResources() throws Exception {
    TypedResource value = resourceTable.getValue(new ResName("org.robolectric", "drawable", "rainbow"), "");
    assertThat(value).isNotNull();
    assertThat(value.getResType()).isEqualTo(ResType.DRAWABLE);
    assertThat(value.isFile()).isTrue();
    assertThat((String) value.getData()).contains("rainbow.xml");
  }

  @Test
  public void shouldLoadDrawableBitmapResources() throws Exception {
    TypedResource value = resourceTable.getValue(new ResName("org.robolectric", "drawable", "an_image"), "");
    assertThat(value).isNotNull();
    assertThat(value.getResType()).isEqualTo(ResType.DRAWABLE);
    assertThat(value.isFile()).isTrue();
    assertThat((String) value.getData()).contains("an_image.png");
  }

  @Test
  public void shouldLoadDrawableBitmapResourcesDefinedByItemTag() throws Exception {
    TypedResource value = resourceTable.getValue(new ResName("org.robolectric", "drawable", "example_item_drawable"), "");
    assertThat(value).isNotNull();
    assertThat(value.getResType()).isEqualTo(ResType.DRAWABLE);
    assertThat(value.isReference()).isTrue();
    assertThat((String) value.getData()).isEqualTo("@drawable/an_image");
  }

  @Test
  public void shouldLoadIdResourcesDefinedByItemTag() throws Exception {
    TypedResource value = resourceTable.getValue(new ResName("org.robolectric", "id", "id_declared_in_item_tag"), "");
    assertThat(value).isNotNull();
    assertThat(value.getResType()).isEqualTo(ResType.CHAR_SEQUENCE);
    assertThat(value.isReference()).isFalse();
    assertThat(value.asString()).isEqualTo("");
    assertThat((String) value.getData()).isEqualTo("");
  }

  @Test
  public void whenIdItemsHaveStringContent_shouldLoadIdResourcesDefinedByItemTag() throws Exception {
    TypedResource value2 = resourceTable.getValue(new ResName("org.robolectric", "id", "id_with_string_value"), "");
    assertThat(value2.asString()).isEqualTo("string value");
  }

  @Test
  public void shouldLoadResourcesFromGradleOutputDirectories() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "string", "from_gradle_output"), "");
    assertThat(value).describedAs("String from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("string example taken from gradle output directory");
  }

  @Test
  public void shouldLoadDimenResourcesFromGradleOutputDirectoriesDefinedByDimenTag() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "dimen", "example_dimen"), "");
    assertThat(value).describedAs("Dimen from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("8dp");
  }

  @Test
  public void shouldLoadDimenResourcesFromGradleOutputDirectoriesDefinedByItemTag() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "dimen", "example_item_dimen"), "");
    assertThat(value).describedAs("Item dimen from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("3.14");
  }

  @Test
  public void shouldLoadStringResourcesFromGradleOutputDirectoriesDefinedByItemTag() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "string", "item_from_gradle_output"), "");
    assertThat(value).describedAs("Item string from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("3.14");
  }

  @Test
  public void shouldLoadColorResourcesFromGradleOutputDirectoriesDefinedByColorTag() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "color", "example_color"), "");
    assertThat(value).describedAs("Color from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("#00FF00FF");
  }

  @Test
  public void shouldLoadColorResourcesFromGradleOutputDirectoriesDefinedByItemTag() {
    TypedResource value = gradleResourceTable.getValue(new ResName("org.robolectric.gradleapp", "color", "example_item_color"), "");
    assertThat(value).describedAs("Item color from gradle output is not loaded").isNotNull();
    assertThat(value.asString()).isEqualTo("1.0");
  }
}


text:
#ifndef MYUTILSIMAGE_HISTOGRAM_H
#define MYUTILSIMAGE_HISTOGRAM_H

#include "../myutilsimage_c.h"

#ifndef NO_OPENCV

#include <opencv2/core/core_c.h>

IplImage *my_image_newImageHistogram(int64_t num_bins, double *bin_values);

#endif
#endif


text:
namespace acl
{

class ACL_CPP_API CopyObjectRequest
{
public:
	CopyObjectRequest();
	~CopyObjectRequest();
};

} // namespace acl


text:
using UnityEngine;

public class Destroyer : MonoBehaviour {

	void Start () {	}

	void Update () {
		if (gameObject.transform.position.x + Config.Instance.TileWidth < GameManager.Instance.LeftCameraX) {
			Destroy(gameObject);
		}
	}
}


text:
package org.teckhooi.store.domain;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

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

/**
 *
 * @author Lim, Teck Hooi
 *
 *
 */

@Entity
@Table
public class LineItem implements Serializable {
    @Id
    @GeneratedValue
    private Long oid;

    private String name;
    private String description;
    private double price;
    private Date dateCreated;

    public LineItem(String name, String description, double price) {
        this(name, description, price, new Date());
    }

    public LineItem(String name, String description, double price, Date dateCreated) {
        this.name = name;
        this.description = description;
        this.price = price;
        this.dateCreated = dateCreated;
    }

    public LineItem() {}

    public Long getOid() {
        return oid;
    }

    public void setOid(Long oid) {
        this.oid = oid;
    }

    public Date getDateCreated() {
        return dateCreated;
    }

    public void setDateCreated(Date dateCreated) {
        this.dateCreated = dateCreated;
    }

    public double getPrice() {
        return price;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getName() {
        return name;
    }

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


text:
package namespaces

import "context"

// Store provides introspection about namespaces.
//
// Note that these are slightly different than other objects, which are record
// oriented. A namespace is really just a name and a set of labels. Objects
// that belong to a namespace are returned when the namespace is assigned to a
// given context.
//
//
type Store interface {
	Create(ctx context.Context, namespace string, labels map[string]string) error
	Labels(ctx context.Context, namespace string) (map[string]string, error)
	SetLabel(ctx context.Context, namespace, key, value string) error
	List(ctx context.Context) ([]string, error)

	// Delete removes the namespace. The namespace must be empty to be deleted.
	Delete(ctx context.Context, namespace string) error
}


text:
<!DOCTYPE html>

This test verifies resetting CSS translate to initial value doesn't result in a stacking context.


text:
FROM alpine:3.2

RUN apk add --update nginx && rm -rf /var/cache/apk/*

COPY nginx.conf /etc/nginx/nginx.conf
COPY index.html /usr/share/nginx/html/index.html

USER nobody

CMD ["nginx", "-g", "daemon off;"]


text:
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
                        print_function, unicode_literals)

from pants.backend.jvm.targets.scala_library import ScalaLibrary

class ScalacPlugin(ScalaLibrary):
  """Defines a target that produces a scalac_plugin."""

  def __init__(self, classname=None, plugin=None, *args, **kwargs):

    """
    :param classname: The fully qualified plugin class name - required.
    :param plugin: The name of the plugin which defaults to name if not supplied.
    """

    super(ScalacPlugin, self).__init__(*args, **kwargs)

    self.plugin = plugin or self.name
    self.classname = classname
    self.add_labels('scalac_plugin')


text:
package org.terasology.engine.rendering.assets.atlas;

import org.terasology.gestalt.assets.AbstractFragmentDataProducer;
import org.terasology.gestalt.assets.ResourceUrn;
import org.terasology.engine.rendering.assets.texture.subtexture.SubtextureData;
import org.terasology.gestalt.assets.management.AssetManager;
import org.terasology.gestalt.assets.module.annotations.RegisterAssetDataProducer;

import java.util.Collections;
import java.util.Optional;
import java.util.Set;

@RegisterAssetDataProducer
public class AltasTileProducer extends AbstractFragmentDataProducer<SubtextureData, Atlas, AtlasData> {

    public AltasTileProducer(AssetManager assetManager) {
        super(assetManager, Atlas.class, true);
    }

    @Override
    protected Optional<SubtextureData> getFragmentData(ResourceUrn urn, Atlas rootAsset) {
        return rootAsset.getSubtexture(urn);
    }

    @Override
    public Set<ResourceUrn> getAvailableAssetUrns() {
        return Collections.emptySet();
    }
}


text:
import invokeEach from '../utils/invokeEach';
import merge from '../utils/merge';

const noop = () => {};

export default class StateMachine {
  constructor(config, taskScheduler, contextFactory) {
    if (config === undefined || config === null) {
      throw new Error('Configuration must be specified.');
    }
    if (typeof config !== 'object') {
      throw new Error('Configuration must be an object.');
    }
    if (config.initialState === undefined || config.initialState === null) {
      throw new Error('Initial state must be specified.');
    }
    this.config = config;
    this.taskScheduler = taskScheduler;
    this.contextFactory = contextFactory;
    this.currentState = null;
    this.submachines = Object.create(null);
    this.timerIDs = null;
    this.asyncActionCancelers = null;
    this.handleAsyncActionComplete = ::this.handleAsyncActionComplete;
    this.handleTimeout = ::this.handleTimeout;
  }

  getCurrentState() {
    return this.currentState;
  }

  canHandle(event, eventPayload) {
    if (!this.isStarted()) {
      return false;
    }

    const context = this.createContextWithEvent(event, eventPayload);
    return !!this.getFirstAllowedTransitionForEvent(context);
  }

  tryHandle(event, eventPayload) {
    if (!this.isStarted()) {
      return false;
    }

    const context = this.createContextWithEvent(event, eventPayload);
    const transitionConfig = this.getFirstAllowedTransitionForEvent(context);
    if (transitionConfig) {
      this.executeTransition(transitionConfig, context);
      return true;
    }
    return false;
  }

  handleUnhandledEvent(event, eventPayload) {
    if (this.config.global.unhandledEventHooks.length > 0) {
      invokeEach(
        this.config.global.unhandledEventHooks,
        event,
        this.currentState,
        this.createContextWithEvent(event, eventPayload)
      );
    } else {
      throw new Error(`Unhandled event '${event}' in state '${this.currentState}'.`);
    }
  }

  isStarted() {
    return this.currentState !== null;
  }

  start() {
    if (!this.isStarted()) {
      this.enterState(this.config.initialState, this.createContext());
    }
  }

  stop() {
    if (this.isStarted()) {
      this.exitState(this.createContext());
      this.currentState = null;
    }
  }

  getSubmachine() {
    return this.isStarted() ? this.submachines[this.currentState] : null;
  }

  executeTransition(transitionConfig, context) {
    if (transitionConfig.ignore) {
      return;
    }

    if (!transitionConfig.isInternal) {
      this.exitState(context);
    }

    const nextState = transitionConfig.targetState !== null ?
      transitionConfig.targetState :
      this.currentState;

    invokeEach(this.config.global.transitionHooks, this.currentState, nextState, context);
    invokeEach(transitionConfig.actions, this.currentState, nextState, context);

    if (!transitionConfig.isInternal) {
      this.enterState(nextState, context);
    }
  }

  enterState(state, context) {
    invokeEach(this.config.global.stateEnterHooks, state, context);

    const stateConfig = this.config.states[state];
    if (stateConfig) {
      invokeEach(stateConfig.entryActions, state, context);
    }

    if (this.currentState !== null && this.currentState !== state) {
      invokeEach(this.config.global.stateChangeHooks, this.currentState, state, context);
    }

    try {
      this.startAsyncActions(state, context);
      this.startTimers(state);
      this.startSubmachines(state);
    } catch (error) {
      this.stopTimers();
      this.cancelAsyncActions();
      throw error;
    }

    this.currentState = state;
  }

  exitState(context) {
    this.stopSubmachines();
    this.stopTimers();
    this.cancelAsyncActions();

    invokeEach(this.config.global.stateExitHooks, this.currentState, context);

    const stateConfig = this.config.states[this.currentState];
    if (stateConfig) {
      invokeEach(stateConfig.exitActions, this.currentState, context);
    }
  }

  startAsyncActions(state, context) {
    const stateConfig = this.config.states[state];
    if (stateConfig) {
      stateConfig.asyncActions.forEach(
        asyncActionConfig => this.startAsyncAction(asyncActionConfig, state, context)
      );
    }
  }

  startAsyncAction(asyncActionConfig, state, context) {
    const { action, successTrigger, failureTrigger } = asyncActionConfig;
    let handleComplete = this.handleAsyncActionComplete;
    action(state, context).then(
      result => handleComplete(successTrigger, { result }),
      error => handleComplete(failureTrigger, { error })
    );
    this.asyncActionCancelers = this.asyncActionCancelers || [];
    this.asyncActionCancelers.push(() => {
      handleComplete = noop;
    });
  }

  cancelAsyncActions() {
    if (this.asyncActionCancelers) {
      invokeEach(this.asyncActionCancelers);
      this.asyncActionCancelers = null;
    }
  }

  handleAsyncActionComplete(triggerConfig, additionalContext) {
    const context = merge(this.createContext(), additionalContext);
    this.executeTrigger(triggerConfig, context);
  }

  startTimers(state) {
    const stateConfig = this.config.states[state];
    if (stateConfig && stateConfig.timers.length > 0) {
      this.timerIDs = stateConfig.timers.map(timerConfig => setTimeout(
        this.handleTimeout,
        timerConfig.timeout,
        timerConfig
      ));
    }
  }

  stopTimers() {
    if (this.timerIDs) {
      this.timerIDs.forEach(clearTimeout);
      this.timerIDs = null;
    }
  }

  handleTimeout(timerConfig) {
    this.executeTrigger(timerConfig, this.createContext());
  }

  startSubmachines(state) {
    const stateConfig = this.config.states[state];
    if (stateConfig && stateConfig.submachine) {
      if (!this.submachines[state]) {
        this.submachines[state] = new StateMachine(
          stateConfig.submachine, this.taskScheduler, this.contextFactory
        );
      }
      this.submachines[state].start();
    }
  }

  stopSubmachines() {
    const submachine = this.submachines[this.currentState];
    if (submachine) {
      submachine.stop();
    }
  }

  createContext() {
    return this.contextFactory(this);
  }

  createContextWithEvent(event, eventPayload) {
    const context = this.createContext();
    context.event = event;
    if (eventPayload !== undefined) {
      context.eventPayload = eventPayload;
    }
    return context;
  }

  static getFirstAllowedTransition(transitions, context) {
    for (let i = 0; i < transitions.length; i++) {
      if (!transitions[i].condition || transitions[i].condition(context)) {
        return transitions[i];
      }
    }
    return null;
  }

  getFirstAllowedTransitionForEvent(context) {
    const stateConfig = this.config.states[this.currentState];
    if (!stateConfig) {
      return null;
    }

    let transitionConfig = null;

    const eventConfig = stateConfig.events[context.event];
    if (eventConfig) {
      transitionConfig = StateMachine.getFirstAllowedTransition(eventConfig.transitions, context);
    }

    if (!transitionConfig && stateConfig.anyEventTrigger) {
      transitionConfig = StateMachine.getFirstAllowedTransition(
        stateConfig.anyEventTrigger.transitions, context
      );
    }

    return transitionConfig;
  }

  executeTrigger(triggerConfig, context) {
    this.taskScheduler.execute(() => {
      const transitionConfig = StateMachine.getFirstAllowedTransition(
        triggerConfig.transitions, context
      );
      if (transitionConfig) {
        this.executeTransition(transitionConfig, context);
      }
    });
  }
}


text:
package sx.lambda.voxel.world;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Mesh;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.TextureAttribute;
import com.badlogic.gdx.graphics.g3d.utils.MeshBuilder;
import com.badlogic.gdx.graphics.g3d.utils.MeshPartBuilder;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.utils.IntMap;
import sx.lambda.voxel.RadixClient;
import sx.lambda.voxel.api.RadixAPI;
import sx.lambda.voxel.api.events.worldgen.EventFinishChunkGen;
import sx.lambda.voxel.block.Block;
import sx.lambda.voxel.block.Side;
import sx.lambda.voxel.entity.Entity;
import sx.lambda.voxel.entity.EntityPosition;
import sx.lambda.voxel.util.Vec3i;
import sx.lambda.voxel.world.chunk.BlockStorage.CoordinatesOutOfBoundsException;
import sx.lambda.voxel.world.chunk.Chunk;
import sx.lambda.voxel.world.chunk.IChunk;
import sx.lambda.voxel.world.chunk.MeshQueueWorker;
import sx.lambda.voxel.world.generation.ChunkGenerator;
import sx.lambda.voxel.world.generation.SimplexChunkGenerator;

import java.util.*;
import java.util.concurrent.*;

public class World implements IWorld {

    private static final int CHUNK_SIZE = 16; // SHOULD ALWAYS BE 2^x
    private static final int WORLD_HEIGHT = 256;
    private static final int SEA_LEVEL = 64;
    private static final float GRAVITY = 32f;
    private static final float TERMINAL_VELOCITY = 78.4f;

    /**
     * The amount of lighting workers to have per light type (sunlight and blocklight)
     */
    private static final int LIGHTING_WORKERS = 2;

    private final IntMap<IChunk> chunkMap = new IntMap<>();
    private final Queue<IChunk> chunksToRerender = new ConcurrentLinkedQueue<>();

    private final boolean remote, server;
    private final ChunkGenerator chunkGen;
    private final ConcurrentHashMap<Integer, Entity> loadedEntities = new ConcurrentHashMap<>();

    // Light-related stuff
    private final ExecutorService sunlightPoolExecutor = Executors.newFixedThreadPool(LIGHTING_WORKERS);
    private final ExecutorService blocklightPoolExecutor = Executors.newFixedThreadPool(LIGHTING_WORKERS);
    private final Queue<int[]> sunlightQueue = new LinkedBlockingQueue<>();
    private final Queue<int[]> sunlightRemovalQueue = new LinkedBlockingQueue<>();
    private final Queue<int[]> blocklightQueue = new LinkedBlockingQueue<>();

    // Mesh related stuff
    // Manages meshing chunks off of the main thread
    private final Queue<Runnable> chunkMeshQueue = new LinkedBlockingQueue<>();
    // Manages uploading chunks on the gl thread
    private final Queue<Runnable> chunkUploadQueue = new LinkedList<>();

    // Skybox stuff
    private ModelBatch modelBatch;
    private ModelBatch wiremeshBatch;
    private ModelInstance skybox;
    private Model skyboxModel;
    private Texture skyboxTexture;

    public World(boolean remote, boolean server) {
        this.remote = remote;
        this.server = server;
        if (!remote) {
            this.chunkGen = new SimplexChunkGenerator(this, 200, new Random().nextInt());
        } else {
            this.chunkGen = null;
        }

        for(int i = 0; i < LIGHTING_WORKERS; i++) {
            sunlightPoolExecutor.submit(new SunlightQueueWorker(this, sunlightQueue));
        }
        for(int i = 0; i < LIGHTING_WORKERS; i++) {
            blocklightPoolExecutor.submit(new BlocklightQueueWorker(this, blocklightQueue));
        }

        new MeshQueueWorker(chunkMeshQueue).start();
    }

    public int getChunkSize() {
        return CHUNK_SIZE;
    }

    public int getHeight() {
        return WORLD_HEIGHT;
    }

    public IChunk getChunk(Vec3i position) {
        return getChunk(position.x, position.z);
    }

    private int getChunkKey(int x, int z) {
        short nx = (short)Math.floorDiv(x, getChunkSize());
        short nz = (short)Math.floorDiv(z, getChunkSize());

        return (nx << 16) | (nz & 0xFFFF);
    }

    @Override
    public IChunk getChunk(int x, int z) {
        try {
            return chunkMap.get(getChunkKey(x, z));
        } catch(ArrayIndexOutOfBoundsException ex) {
            return null;
        }
    }

    private void removeChunkFromMap(Vec3i pos) {
        removeChunkFromMap(pos.x, pos.z);
    }

    private void removeChunkFromMap(int x, int z) {
        chunkMap.remove(getChunkKey(x, z));
    }

    @Override
    public void render() {
        assert !server;

        if (modelBatch == null) {
            modelBatch = new ModelBatch(Gdx.files.internal("shaders/gdx/world.vert.glsl"), Gdx.files.internal("shaders/gdx/world.frag.glsl"));
            wiremeshBatch = new ModelBatch(Gdx.files.internal("shaders/gdx/world.vert.glsl"), Gdx.files.internal("shaders/gdx/wiremesh.frag.glsl"));
        }
        if(skybox == null) {
            skybox = createSkybox();
        }

        processChunkUploadQueue();

        processLightQueue(); // If a chunk is doing its rerender, we want it to have the most recent lighting possible

        {
            Queue<IChunk> skippedChunks = new LinkedList<>(); // Chunks that didn't rerender and need to be added back to the queue after iteration
            IChunk c;
            while((c = chunksToRerender.poll()) != null) {
                if(RadixClient.getInstance().getPlayer().getPosition().planeDistance(c.getStartPosition().x, c.getStartPosition().z) <=
                        RadixClient.getInstance().getSettingsManager().getVisualSettings().getViewDistance() * CHUNK_SIZE) {
                    c.rerender();
                } else {
                    skippedChunks.add(c); // Add back onto the queue
                }
            }

            while((c = skippedChunks.poll()) != null) {
                chunksToRerender.add(c);
            }
        }

        float playerX = RadixClient.getInstance().getPlayer().getPosition().getX(),
                playerY = RadixClient.getInstance().getPlayer().getPosition().getY(),
                playerZ = RadixClient.getInstance().getPlayer().getPosition().getZ();
        boolean wireframe = RadixClient.getInstance().isWireframe();
        if(wireframe) {
            RadixClient.getInstance().setWireframe(false);
        }
        modelBatch.begin(RadixClient.getInstance().getCamera());
        skybox.transform.translate(playerX, playerY, playerZ);
        modelBatch.render(skybox);
        skybox.transform.translate(-playerX, -playerY, -playerZ);
        if(chunkMap != null) {
            List<IChunk> visibleChunks = new LinkedList<>();
            for (IChunk c : chunkMap.values()) {
                if(c == null)
                    continue;

                int x = c.getStartPosition().x;
                int z = c.getStartPosition().z;
                int halfWidth = getChunkSize() / 2;
                int midX = x + halfWidth;
                int midZ = z + halfWidth;
                int midY = c.getHighestPoint() / 2;
                boolean visible = RadixClient.getInstance().getGameRenderer().getFrustum().boundsInFrustum(midX, midY, midZ, halfWidth, midY, halfWidth);
                if (visible) {
                    visibleChunks.add(c);
                    c.render(modelBatch);
                }
            }

            for (IChunk c : visibleChunks) {
                c.renderTranslucent(modelBatch);
            }
            modelBatch.end();
            if(wireframe) {
                RadixClient.getInstance().setWireframe(true);
                Gdx.gl.glLineWidth(2);
                wiremeshBatch.begin(RadixClient.getInstance().getCamera());
                for (IChunk c : visibleChunks) {
                    c.render(wiremeshBatch);
                }
                wiremeshBatch.end();
            }
        } else {
            modelBatch.end();
        }
    }

    @Override
    public void loadChunks(EntityPosition playerPosition, int viewDistance) {
        if (!remote) { //don't gen chunks if we're not local
            this.getChunksInRange(playerPosition, viewDistance);
        }

    }

    @Override
    public int getSeaLevel() {
        return SEA_LEVEL;
    }

    @Override
    public int getChunkPosition(float value) {
        int subtraction = MathUtils.floor(value) & (CHUNK_SIZE-1);
        return MathUtils.floor(value - subtraction);
    }

    @Override
    public float getGravity() {
        return GRAVITY;
    }

    @Override
    public float applyGravity(float velocity, long ms) {
        return Math.max(-TERMINAL_VELOCITY, velocity - getGravity() * (ms / 1000f));
    }

    @Override
    public void removeBlock(int x, int y, int z) {
        final IChunk c = this.getChunk(x, z);
        if (c != null) {
            x &= getChunkSize()-1;
            y &= getChunkSize()-1;
            try {
                c.removeBlock(x, y, z);
                c.setMeta((short) 0, x, y, z);
            } catch (CoordinatesOutOfBoundsException ex) {
                ex.printStackTrace();
            }
        }
    }

    @Override
    public void addBlock(int block, int x, int y, int z) {
        final IChunk c = this.getChunk(x, z);
        if(c != null) {
            try {
                c.setBlock(block, x & (getChunkSize() - 1), y, z * (getChunkSize() - 1));
            } catch (CoordinatesOutOfBoundsException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public IChunk[] getChunksInRange(EntityPosition epos, int viewDistance) {
        List<IChunk> chunkList = new ArrayList<>();
        int playerChunkX = getChunkPosition(epos.getX());
        int playerChunkZ = getChunkPosition(epos.getZ());
        int range = viewDistance * CHUNK_SIZE;
        for (int x = playerChunkX - range; x < playerChunkX + range; x += CHUNK_SIZE) {
            for (int z = playerChunkZ - range; z < playerChunkZ + range; z += CHUNK_SIZE) {
                chunkList.add(loadChunk(x, z));
            }
        }
        return chunkList.toArray(new IChunk[chunkList.size()]);
    }

    @Override
    public void addChunk(final IChunk chunk) {
        IChunk c = getChunk(chunk.getStartPosition());
        if (c != null) {
            removeChunkFromMap(chunk.getStartPosition());
        }
        addChunk(chunk, chunk.getStartPosition().x, chunk.getStartPosition().z);

        // Rerender neighbors
        for(int x = chunk.getStartPosition().x - getChunkSize(); x <= chunk.getStartPosition().x + getChunkSize(); x += getChunkSize()) {
            for (int z = chunk.getStartPosition().z - getChunkSize(); z <= chunk.getStartPosition().z + getChunkSize(); z += getChunkSize()) {
                if(x == chunk.getStartPosition().x && z == chunk.getStartPosition().z)
                    continue;
                IChunk neighbor = getChunk(x, z);
                if(neighbor != null) {
                    rerenderChunk(neighbor);
                }
            }
        }
    }

    @Override
    public ConcurrentHashMap<Integer, Entity> getLoadedEntities() {
        return this.loadedEntities;
    }

    private void addChunk(IChunk chunk, int x, int z) {
        this.chunkMap.put(getChunkKey(x, z), chunk);
    }

    private IChunk loadChunk(int startX, int startZ) {
        IChunk foundChunk = getChunk(startX, startZ);
        if (foundChunk == null && !remote) {
            final IChunk c = new Chunk(this, new Vec3i(startX, 0, startZ), RadixAPI.instance.getBiomeByID(0), true);
            RadixAPI.instance.getEventManager().push(new EventFinishChunkGen(c));
            addChunk(c, startX, startZ);
            return c;
        } else {
            return foundChunk;
        }
    }

    public void addEntity(int entityId, Entity e) {
        loadedEntities.put(entityId, e);
    }

    @Override
    public void rerenderChunk(IChunk c) {
        if(c == null)
            return;
        chunksToRerender.add(c);
    }

    @Override
    public ChunkGenerator getChunkGen() {
        return this.chunkGen;
    }

    @Override
    public void addToSunlightQueue(int x, int y, int z) {
        sunlightQueue.add(new int[]{x, y, z});
        synchronized(sunlightQueue) {
            sunlightQueue.notify();
        }
    }

    @Override
    public void addToBlocklightQueue(int x, int y, int z) {
        blocklightQueue.add(new int[]{x, y, z});
        synchronized(blocklightQueue) {
            blocklightQueue.notify();
        }
    }

    @Override
    public void addToSunlightRemovalQueue(int x, int y, int z) {
        sunlightRemovalQueue.add(new int[]{x, y, z});
    }

    @Override
    public void processLightQueue() {
        boolean noLightUpdatesQueued = sunlightQueue.isEmpty() && sunlightRemovalQueue.isEmpty();

        for(IChunk c : chunkMap.values()) {
            // If the chunk is not lighted and it is in range, setup lighting then set as lighted
            if(c == null)
                continue;

            if(!c.hasInitialSun()
                    && RadixClient.getInstance().getPlayer().getPosition().planeDistance(
                        c.getStartPosition().x, c.getStartPosition().z)
                        <= RadixClient.getInstance().getSettingsManager().getVisualSettings().getViewDistance() * CHUNK_SIZE) {
                setupLighting(c);
                c.finishAddingSun();
            }

            if(noLightUpdatesQueued && c.waitingOnLightFinish()) {
                c.finishChangingSunlight();
            }
        }

        processLightRemovalQueue();
    }

    private void processLightRemovalQueue() {
        if (!sunlightRemovalQueue.isEmpty()) {
            Side[] sides = Side.values();

            List<IChunk> changedChunks = new ArrayList<>();
            int[] pos;
            while ((pos = sunlightRemovalQueue.poll()) != null) {
                int x = pos[0];
                int cx = x & (CHUNK_SIZE-1);
                int y = pos[1];
                int z = pos[2];
                int cz = z & (CHUNK_SIZE-1);
                IChunk posChunk = getChunk(x, z);
                if (posChunk == null) {
                    continue;
                }
                int ll;
                try {
                    ll = posChunk.getSunlight(x & (CHUNK_SIZE-1), y, z & (CHUNK_SIZE-1));

                    // Spread off to each side
                    for(Side s : sides) {
                        int sx = x; // Side x coord
                        int sy = y; // Side y coord
                        int sz = z; // Side z coord
                        int scx = cx; // Chunk-relative side x coord
                        int scz = cz; // Chunk-relative side z coord
                        IChunk sChunk = posChunk;

                        // Offset values based on side
                        switch (s) {
                            case TOP:
                                sy += 1;
                                break;
                            case BOTTOM:
                                sy -= 1;
                                break;
                            case WEST:
                                sx -= 1;
                                scx -= 1;
                                break;
                            case EAST:
                                sx += 1;
                                scx += 1;
                                break;
                            case NORTH:
                                sz += 1;
                                scz += 1;
                                break;
                            case SOUTH:
                                sz -= 1;
                                scz -= 1;
                                break;
                        }
                        if (sy < 0)
                            continue;
                        if (sy > WORLD_HEIGHT - 1)
                            continue;

                        // Select the correct chunk
                        if(scz < 0) {
                            scz += CHUNK_SIZE;
                            sChunk = getChunk(sx, sz);
                        } else if(scz > CHUNK_SIZE-1) {
                            scz -= CHUNK_SIZE;
                            sChunk = getChunk(sx, sz);
                        }
                        if(scx < 0) {
                            scx += CHUNK_SIZE;
                            sChunk = getChunk(sx, sz);
                        } else if(scx > CHUNK_SIZE-1) {
                            scx -= CHUNK_SIZE;
                            sChunk = getChunk(sx, sz);
                        }

                        if(sChunk == null)
                            continue;

                        Block sBlock = sChunk.getBlock(scx, sy, scz);
                        int sSunlight = sChunk.getSunlight(scx, sy, scz);
                        if (sBlock == null || sBlock.doesLightPassThrough() || !sBlock.decreasesLight()) {
                            if ((sSunlight < ll || s == Side.BOTTOM) && sSunlight != 0) { // Reset lighting for blocks affected by this block
                                addToSunlightRemovalQueue(sx, sy, sz);
                            } else if (sSunlight >= ll && s != Side.BOTTOM) { // Add surrounding blocks to queue to restore lighting of the reset blocks
                                addToSunlightQueue(sx, sy, sz);
                            }
                        }
                    }

                    // Reset lighting for the block
                    posChunk.setSunlight(cx, y, cz, 0);
                    changedChunks.add(posChunk);
                } catch (CoordinatesOutOfBoundsException e) {
                    e.printStackTrace();
                }
            }
            changedChunks.forEach(IChunk::finishChangingSunlight);
        }
    }

    @Override
    public void cleanup() {
        chunkMap.values().forEach(IChunk::dispose);
        modelBatch.dispose();
        modelBatch = null;
        skyboxTexture.dispose();
        skyboxTexture = null;
        skyboxModel.dispose();
        skyboxModel = null;
    }

    @Override
    public void rerenderChunks() {
        // If the chunk is in range, rerender it
        for(IChunk c : chunkMap.values()) {
            if(RadixClient.getInstance().getPlayer().getPosition().planeDistance(c.getStartPosition().x, c.getStartPosition().z)
                    <= RadixClient.getInstance().getSettingsManager().getVisualSettings().getViewDistance() * CHUNK_SIZE) {
                rerenderChunk(c);
            }
        }
    }

    @Override
    public void rmChunk(IChunk chunk) {
        if(chunk == null)
            return;

        removeChunkFromMap(chunk.getStartPosition());
    }

    @Override
    public void addToMeshQueue(Runnable updateFaces) {
        chunkMeshQueue.add(updateFaces);
        synchronized (chunkMeshQueue) {
            chunkMeshQueue.notify();
        }
    }

    @Override
    public void addToChunkUploadQueue(Runnable upload) {
        chunkUploadQueue.add(upload);
    }

    private ModelInstance createSkybox() {
        if(skyboxModel != null) {
            skyboxModel.dispose();
        }
        if(skyboxTexture == null) {
            skyboxTexture = new Texture(Gdx.files.internal("textures/world/skybox.png"));
        }

        MeshBuilder builder = new MeshBuilder();
        builder.begin(VertexAttributes.Usage.Position | VertexAttributes.Usage.TextureCoordinates, GL20.GL_TRIANGLES);

        int x1 = -256;
        int y1 = -256;
        int z1 = -256;
        int x2 = 256;
        int y2 = 256;
        int z2 = 256;
        float sideU1 = 0;
        float sideU2 = 1/3f;
        float sideV1 = 0;
        float sideV2 = 1;
        float topU1 = sideU2;
        float topU2 = topU1+sideU2;
        float bottomU1 = topU2+sideU2;
        float bottomU2 = bottomU1+sideU2;
        float topV1 = 0;
        float topV2 = 1;
        float bottomV1 = 0;
        float bottomV2 = 1;
        MeshPartBuilder.VertexInfo bottomLeftBack = new MeshPartBuilder.VertexInfo().setPos(x1, y1, z1).setUV(sideU1, sideV2);
        MeshPartBuilder.VertexInfo bottomRightBack = new MeshPartBuilder.VertexInfo().setPos(x2, y1, z1).setUV(sideU2, sideV2);
        MeshPartBuilder.VertexInfo bottomRightFront = new MeshPartBuilder.VertexInfo().setPos(x2, y1, z2).setUV(sideU1, sideV2);
        MeshPartBuilder.VertexInfo bottomLeftFront = new MeshPartBuilder.VertexInfo().setPos(x1, y1, z2).setUV(sideU2, sideV2);
        MeshPartBuilder.VertexInfo topLeftBack = new MeshPartBuilder.VertexInfo().setPos(x1, y2, z1).setUV(sideU1, sideV1);
        MeshPartBuilder.VertexInfo topRightBack = new MeshPartBuilder.VertexInfo().setPos(x2, y2, z1).setUV(sideU2, sideV1);
        MeshPartBuilder.VertexInfo topRightFront = new MeshPartBuilder.VertexInfo().setPos(x2, y2, z2).setUV(sideU1, sideV1);
        MeshPartBuilder.VertexInfo topLeftFront = new MeshPartBuilder.VertexInfo().setPos(x1, y2, z2).setUV(sideU2, sideV1);
        // Negative Z
        builder.rect(bottomLeftBack, bottomRightBack, topRightBack, topLeftBack);
        // Positive Z
        builder.rect(topLeftFront, topRightFront, bottomRightFront, bottomLeftFront);
        // Negative X
        builder.rect(bottomLeftBack, topLeftBack, topLeftFront, bottomLeftFront);
        // Positive X
        builder.rect(bottomRightFront, topRightFront, topRightBack, bottomRightBack);
        // Positive Y
        builder.rect(topLeftBack.setUV(topU1, topV1),
                topRightBack.setUV(topU2, topV1),
                topRightFront.setUV(topU2, topV2),
                topLeftFront.setUV(topU1, topV2));
        // Negative Y
        builder.rect(bottomLeftFront.setUV(bottomU1, bottomV2),
                bottomRightFront.setUV(bottomU2, bottomV2),
                bottomRightBack.setUV(bottomU2, bottomV1),
                bottomLeftBack.setUV(bottomU1, bottomV1));
        Mesh skybox = builder.end();

        ModelBuilder modelBuilder = new ModelBuilder();
        modelBuilder.begin();
        modelBuilder.part("skybox", skybox, GL20.GL_TRIANGLES, new Material(
                TextureAttribute.createDiffuse(skyboxTexture)));
        return new ModelInstance(skyboxModel = modelBuilder.end());
    }

    private void setupLighting(IChunk c) {
        try {
            int y = WORLD_HEIGHT - 1;
            for (int z = 0; z < CHUNK_SIZE; z++) {
                for (int x = 0; x < CHUNK_SIZE; x++) {
                    if (c.getBlockId(x, y, z) > 0) {
                        break;
                    }
                    sunlightQueue.add(new int[]{c.getStartPosition().x + x, y, c.getStartPosition().z + z});
                    c.setSunlight(x, y, z, c.getMaxLightLevel());

                    for (int cy = 0; cy < getHeight(); cy++) {
                        int id = c.getBlockId(x, cy, z);
                        if (id > 0) {
                            Block blk = RadixAPI.instance.getBlock(id);
                            if (blk.getLightValue() > 0) {
                                c.setBlocklight(x, cy, z, blk.getLightValue());
                                addToBlocklightQueue(c.getStartPosition().x + x, c.getStartPosition().y + cy, c.getStartPosition().z + z);
                            }
                        }
                    }
                }
            }
            synchronized (sunlightQueue) {
                sunlightQueue.notifyAll();
            }
            synchronized (blocklightQueue) {
                blocklightQueue.notifyAll();
            }
        } catch (CoordinatesOutOfBoundsException ex) {
            ex.printStackTrace();
        }
    }

    private void processChunkUploadQueue() {
        while(!chunkUploadQueue.isEmpty()) {
            chunkUploadQueue.poll().run();
            if(RadixClient.getInstance().getSettingsManager().getVisualSettings().getSmoothChunkLoad().getValue())
                break; // distribute chunk uploads across frames (one chunkload per frame)
        }
    }

}


text:
/**
 * Created by 7KiLL on 27/06/16.
 * Updated by 7KiLL on 03/07/16. Buttons rework, parse mechanics rework, flexbox,
 * sticky footer, meta info, contacts.
 */

$( document ).ready(function() {
    //Global Objects
    var pattern = {
        log: /(.+), \[\d{2}\.\d{2}\.\d{2} \d{1,}:\d{1,}\]/,
        nick: /(.+)(?=(,|:) \[)/,
        date: /\[\d{2}\.\d{2}\.\d{2} \d{1,}:\d{1,}\]/,
        reply: /\[In reply to (.+)\]/i,
        coma: /(,|:)\B/
    };
    var parse = {
        name: function (str) {
            str = str.replace(pattern.nick,
            "$&	");
            return str;
        },
        date: function (str) {
            str = str.replace(pattern.date,
            "$&	");
            return str;
        },
        clearData: function (str) {
            str = str.replace(pattern.date,
            "");
            return str;
        },
        coma: function (str) {
            str = str.replace(pattern.coma,
            ""
            );
            return str;
        },
        reply: function (str) {
            str = str
                .replace(pattern.reply,
            '[In reply to $1]');
            return str;
        }
    };
    var check = {
        date: function (e) {
            return $(e).hasClass('checked');
        },
        //Deprecated
        coma: function (e) {
            return check.date(e);
        }
    };

    //Main function
    function Update(text) {
        //Check for empty textarea
        var stringArray = text.split('\n');
        var htmlTable = '';
        var reply = '';

        $.each(stringArray, function (line, string) {
            if(pattern.reply.test(string)) {
                reply = string;
                reply = parse.reply(reply);
                string = '';
            }
            if(string=='') {return true}
            else if(pattern.nick.test(string)&&pattern.date.test(string)){
                string = parse.name(string);
                string = parse.coma(string);
                check.date('.dateBox')?
                    string = parse.date(string) : string = parse.clearData(string);
                htmlTable += '
' + string;  //Open Table Row
            }
            else if(pattern.nick.test(string)) {
                string = parse.name(string);
                string = parse.coma(string);
                htmlTable += '
' + string;  //Open Table Row
            }
            else {
                if(reply) {
                    string = reply + ' ' + string;
                    reply = '';
                }
                string = '' + string + '	';
                htmlTable += string + '
'; //Close Table Row
            }
        });
        htmlTable = '

' + htmlTable + '

';
        return htmlTable;
    }

    //Updating buttons color
    updateBgColor('#nickColor', 'name');
    updateBgColor('#dateColor', 'date');
    updateBgColor('#textColor', 'text');

    //Local storage shit
    if(localStorage.getItem('textareaText'))
        $('#processedText').val(localStorage.getItem('textareaText'));
    //Updating textarea "cache"
    $('#processedText').on('change', function () {
       localStorage.setItem('textareaText', $(this).val());
    });
    //Start button event handler
    $('#startProcess').on('click', function(){
        var text = $('#processedText').val();
        if(!text) {
            showAlert("Empty field", 'danger', '#wrap', 1200);
            return false;
        }
        $('.form-group').hide();
        $('.table').show();
        $('.card-block').append(Update(text));

        updateColor('.nickname', 'name');
        updateColor('.date', 'date');
        updateColor('.text-col', 'text');
        $(this).hide();
        $('.inputs').show(300);
        $('#editProcess').show(300);
        $('#newProcess').show(300);
    });
    //Edit
    $('#editProcess').on('click', function () {
        $('table').remove();
        $('.form-group').show(300);
        $('#editProcess').hide(300);
        $('#newProcess').hide(300);
        $('#startProcess').show(300);

    });
    //Clear
    $('#newProcess').on('click', function () {
        $('#processedText').val('');
        $('table').remove();
        $('#editProcess').hide(300);
        $(this).hide(300);
        $('.form-group').show(300);
        $('#startProcess').show(300);

    });
    //Date
    $('.dateBox').on('click', function () {
        if(check.date(this)) {
            $(this)
                .removeClass('checked btn-success')
                .addClass('btn-danger')
                .html('Date ');
                $('#dateColor').fadeOut(300);
        }
        else {
            $(this)
                .removeClass('btn-danger')
                .addClass('checked btn-success')
                .html('Date ');
            $('#dateColor').fadeIn(300);
        }
       textUpdate();
    });

    //Other functions
    function updateColor(e, l) {
        if(localStorage.getItem(l)!==null) {
            console.log('localStorage: ' + l + ' has been found');
            $(e).each(function(i, item){
                $(this).css('color', localStorage.getItem(l));
            });
        }
    }
    function updateBgColor(e, l) {
        if(localStorage.getItem(l)) {
            $(e).css('background-color', localStorage.getItem(l));
        }
    }

    function showAlert(msg, type, where, time) {
        var alert = '
' +
            ''+ msg+'' +
        '
';
        $(where).prepend(alert);
        setTimeout(function() { $('.alert').fadeOut(300 , function(){$(this).remove()}) }, time);
        }

    function textUpdate() {
        var text = $('#processedText').val();
        if(!text) {
            showAlert("Empty field", 'danger', '#wrap', 1200);
            return false;
        }
        $('.form-group').hide();
        $('table>tbody').html(Update(text));
        updateColor('.nickname', 'name');
        updateColor('.date', 'date');
        updateColor('.text-col', 'text');
        $('.footer').addClass('sticky');
    }

});


text:
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/basictypes.h"
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/files/scoped_temp_dir.h"
#include "base/message_loop.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "webkit/browser/fileapi/file_system_mount_point_provider.h"
#include "webkit/fileapi/async_file_test_helper.h"
#include "webkit/fileapi/copy_or_move_file_validator.h"
#include "webkit/fileapi/external_mount_points.h"
#include "webkit/fileapi/file_system_context.h"
#include "webkit/fileapi/file_system_url.h"
#include "webkit/fileapi/file_system_util.h"
#include "webkit/fileapi/isolated_context.h"
#include "webkit/fileapi/mock_file_system_context.h"
#include "webkit/fileapi/test_mount_point_provider.h"
#include "webkit/quota/mock_special_storage_policy.h"

namespace fileapi {

namespace {

const FileSystemType kNoValidatorType = kFileSystemTypeTemporary;
const FileSystemType kWithValidatorType = kFileSystemTypeTest;

class CopyOrMoveFileValidatorTestHelper {
 public:
  CopyOrMoveFileValidatorTestHelper(
      const GURL& origin,
      FileSystemType src_type,
      FileSystemType dest_type)
      : origin_(origin),
        src_type_(src_type),
        dest_type_(dest_type) {}

  ~CopyOrMoveFileValidatorTestHelper() {
    file_system_context_ = NULL;
    base::MessageLoop::current()->RunUntilIdle();
  }

  void SetUp() {
    ASSERT_TRUE(base_.CreateUniqueTempDir());
    base::FilePath base_dir = base_.path();

    file_system_context_ = CreateFileSystemContextForTesting(NULL, base_dir);

    // Set up TestMountPointProvider to require CopyOrMoveFileValidator.
    FileSystemMountPointProvider* test_mount_point_provider =
        file_system_context_->GetMountPointProvider(kWithValidatorType);
    static_cast<TestMountPointProvider*>(test_mount_point_provider)->
        set_require_copy_or_move_validator(true);

    // Sets up source.
    FileSystemMountPointProvider* src_mount_point_provider =
        file_system_context_->GetMountPointProvider(src_type_);
    src_mount_point_provider->GetFileSystemRootPathOnFileThread(
        SourceURL(std::string()), true /* create */);
    ASSERT_EQ(base::PLATFORM_FILE_OK, CreateDirectory(SourceURL("")));

    // Sets up dest.
    DCHECK_EQ(kWithValidatorType, dest_type_);
    ASSERT_EQ(base::PLATFORM_FILE_OK, CreateDirectory(DestURL("")));

    copy_src_ = SourceURL("copy_src.jpg");
    move_src_ = SourceURL("move_src.jpg");
    copy_dest_ = DestURL("copy_dest.jpg");
    move_dest_ = DestURL("move_dest.jpg");

    ASSERT_EQ(base::PLATFORM_FILE_OK, CreateFile(copy_src_, 10));
    ASSERT_EQ(base::PLATFORM_FILE_OK, CreateFile(move_src_, 10));

    ASSERT_TRUE(FileExists(copy_src_, 10));
    ASSERT_TRUE(FileExists(move_src_, 10));
    ASSERT_FALSE(FileExists(copy_dest_, 10));
    ASSERT_FALSE(FileExists(move_dest_, 10));
  }

  void SetMediaCopyOrMoveFileValidatorFactory(
      scoped_ptr<CopyOrMoveFileValidatorFactory> factory) {
    FileSystemMountPointProvider* mount_point_provider =
        file_system_context_->GetMountPointProvider(kWithValidatorType);
    mount_point_provider->InitializeCopyOrMoveFileValidatorFactory(
        kWithValidatorType, factory.Pass());
  }

  void CopyTest(base::PlatformFileError expected) {
    ASSERT_TRUE(FileExists(copy_src_, 10));
    ASSERT_FALSE(FileExists(copy_dest_, 10));

    EXPECT_EQ(expected,
              AsyncFileTestHelper::Copy(file_system_context_, copy_src_,
                                        copy_dest_));

    EXPECT_TRUE(FileExists(copy_src_, 10));
    if (expected == base::PLATFORM_FILE_OK)
      EXPECT_TRUE(FileExists(copy_dest_, 10));
    else
      EXPECT_FALSE(FileExists(copy_dest_, 10));
  };

  void MoveTest(base::PlatformFileError expected) {
    ASSERT_TRUE(FileExists(move_src_, 10));
    ASSERT_FALSE(FileExists(move_dest_, 10));

    EXPECT_EQ(expected,
              AsyncFileTestHelper::Move(file_system_context_, move_src_,
                                        move_dest_));

    if (expected == base::PLATFORM_FILE_OK) {
      EXPECT_FALSE(FileExists(move_src_, 10));
      EXPECT_TRUE(FileExists(move_dest_, 10));
    } else {
      EXPECT_TRUE(FileExists(move_src_, 10));
      EXPECT_FALSE(FileExists(move_dest_, 10));
    }
  };

 private:
  FileSystemURL SourceURL(const std::string& path) {
    return file_system_context_->CreateCrackedFileSystemURL(
        origin_, src_type_,
        base::FilePath().AppendASCII("src").AppendASCII(path));
  }

  FileSystemURL DestURL(const std::string& path) {
    return file_system_context_->CreateCrackedFileSystemURL(
        origin_, dest_type_,
        base::FilePath().AppendASCII("dest").AppendASCII(path));
  }

  base::PlatformFileError CreateFile(const FileSystemURL& url, size_t size) {
    base::PlatformFileError result =
        AsyncFileTestHelper::CreateFile(file_system_context_, url);
    if (result != base::PLATFORM_FILE_OK)
      return result;
    return AsyncFileTestHelper::TruncateFile(file_system_context_, url, size);
  }

  base::PlatformFileError CreateDirectory(const FileSystemURL& url) {
    return AsyncFileTestHelper::CreateDirectory(file_system_context_, url);
  }

  bool FileExists(const FileSystemURL& url, int64 expected_size) {
    return AsyncFileTestHelper::FileExists(
        file_system_context_, url, expected_size);
  }

  base::ScopedTempDir base_;

  const GURL origin_;

  const FileSystemType src_type_;
  const FileSystemType dest_type_;
  std::string src_fsid_;
  std::string dest_fsid_;

  base::MessageLoop message_loop_;
  scoped_refptr<FileSystemContext> file_system_context_;

  FileSystemURL copy_src_;
  FileSystemURL copy_dest_;
  FileSystemURL move_src_;
  FileSystemURL move_dest_;

  DISALLOW_COPY_AND_ASSIGN(CopyOrMoveFileValidatorTestHelper);
};

class TestCopyOrMoveFileValidatorFactory
    : public CopyOrMoveFileValidatorFactory {
 public:
  // A factory that creates validators that accept everything or nothing.
  TestCopyOrMoveFileValidatorFactory(bool all_valid) : all_valid_(all_valid) {}
  virtual ~TestCopyOrMoveFileValidatorFactory() {}

  virtual CopyOrMoveFileValidator* CreateCopyOrMoveFileValidator(
      const FileSystemURL& /*src_url*/,
      const base::FilePath& /*platform_path*/) OVERRIDE {
    return new TestCopyOrMoveFileValidator(all_valid_);
  }

 private:
  class TestCopyOrMoveFileValidator : public CopyOrMoveFileValidator {
   public:
    TestCopyOrMoveFileValidator(bool all_valid)
        : result_(all_valid ? base::PLATFORM_FILE_OK
                            : base::PLATFORM_FILE_ERROR_SECURITY) {
    }
    virtual ~TestCopyOrMoveFileValidator() {}

    virtual void StartValidation(
        const ResultCallback& result_callback) OVERRIDE {
      // Post the result since a real validator must do work asynchronously.
      base::MessageLoop::current()->PostTask(
          FROM_HERE, base::Bind(result_callback, result_));
    }

   private:
    base::PlatformFileError result_;

    DISALLOW_COPY_AND_ASSIGN(TestCopyOrMoveFileValidator);
  };

  bool all_valid_;

  DISALLOW_COPY_AND_ASSIGN(TestCopyOrMoveFileValidatorFactory);
};

}  // namespace

TEST(CopyOrMoveFileValidatorTest, NoValidatorWithin6ameFSType) {
  // Within a file system type, validation is not expected, so it should
  // work for kWithValidatorType without a validator set.
  CopyOrMoveFileValidatorTestHelper helper(GURL("http://foo"),
                                           kWithValidatorType,
                                           kWithValidatorType);
  helper.SetUp();
  helper.CopyTest(base::PLATFORM_FILE_OK);
  helper.MoveTest(base::PLATFORM_FILE_OK);
}

TEST(CopyOrMoveFileValidatorTest, MissingValidator) {
  // Copying or moving into a kWithValidatorType requires a file
  // validator.  An error is expect if copy is attempted without a validator.
  CopyOrMoveFileValidatorTestHelper helper(GURL("http://foo"),
                                           kNoValidatorType,
                                           kWithValidatorType);
  helper.SetUp();
  helper.CopyTest(base::PLATFORM_FILE_ERROR_SECURITY);
  helper.MoveTest(base::PLATFORM_FILE_ERROR_SECURITY);
}

TEST(CopyOrMoveFileValidatorTest, AcceptAll) {
  CopyOrMoveFileValidatorTestHelper helper(GURL("http://foo"),
                                           kNoValidatorType,
                                           kWithValidatorType);
  helper.SetUp();
  scoped_ptr<CopyOrMoveFileValidatorFactory> factory(
      new TestCopyOrMoveFileValidatorFactory(true /*accept_all*/));
  helper.SetMediaCopyOrMoveFileValidatorFactory(factory.Pass());

  helper.CopyTest(base::PLATFORM_FILE_OK);
  helper.MoveTest(base::PLATFORM_FILE_OK);
}

TEST(CopyOrMoveFileValidatorTest, AcceptNone) {
  CopyOrMoveFileValidatorTestHelper helper(GURL("http://foo"),
                                           kNoValidatorType,
                                           kWithValidatorType);
  helper.SetUp();
  scoped_ptr<CopyOrMoveFileValidatorFactory> factory(
      new TestCopyOrMoveFileValidatorFactory(false /*accept_all*/));
  helper.SetMediaCopyOrMoveFileValidatorFactory(factory.Pass());

  helper.CopyTest(base::PLATFORM_FILE_ERROR_SECURITY);
  helper.MoveTest(base::PLATFORM_FILE_ERROR_SECURITY);
}

TEST(CopyOrMoveFileValidatorTest, OverrideValidator) {
  // Once set, you can not override the validator.
  CopyOrMoveFileValidatorTestHelper helper(GURL("http://foo"),
                                           kNoValidatorType,
                                           kWithValidatorType);
  helper.SetUp();
  scoped_ptr<CopyOrMoveFileValidatorFactory> reject_factory(
      new TestCopyOrMoveFileValidatorFactory(false /*accept_all*/));
  helper.SetMediaCopyOrMoveFileValidatorFactory(reject_factory.Pass());

  scoped_ptr<CopyOrMoveFileValidatorFactory> accept_factory(
      new TestCopyOrMoveFileValidatorFactory(true /*accept_all*/));
  helper.SetMediaCopyOrMoveFileValidatorFactory(accept_factory.Pass());

  helper.CopyTest(base::PLATFORM_FILE_ERROR_SECURITY);
  helper.MoveTest(base::PLATFORM_FILE_ERROR_SECURITY);
}

}  // namespace fileapi


text:
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <meta http-equiv="cache-control" content="no-cache"/>
    <meta http-equiv="pragma" content="no-cache"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

<link   rel="stylesheet"
        href="../../css/style.min.0a7442460ca45a8d1ffa9d4f0a0163976899fc7820ce2bb76f693ba0527afb57.css"
        integrity="sha256-CnRCRgykWo0f+p1PCgFjl2iZ/Hggziu3b2k7oFJ6+1c="
        type="text/css"
        media="screen">

<link   rel="stylesheet"
        href="../../css/mobile.min.9d1271f82d33327493aaf7c1818ceac101a822559d694bd14a222d686e28c391.css"
        integrity="sha256-nRJx+C0zMnSTqvfBgYzqwQGoIlWdaUvRSiItaG4ow5E="
        type="text/css"
        media="handheld, only screen and (max-device-width: 960px)">

    <link href="https://unwiredcouch.com/atom.xml" type="application/atom+xml" rel="alternate" title="unwiredcouch.com: All Posts" />

    <title>Weisse Nächte (Vollständige Deutsche Ausgabe) on unwiredcouch.com</title>

Writing

Reading

Setup

About

Drawing

Mastodon

 Weisse Nächte (Vollständige Deutsche Ausgabe)

 by
           Fyodor Dostoyevsky

 Read: Jan 24, 2020

I decided to give this book a try after poking around at the local book store. I realized I've never read a single Dostoyevsky. And I sure wasn't gonna read "War & Peace" just to give it a try and see how I like it. After some quick googling it seemed like "Weiße Nächte" was one of his fairly popular works, and they had it in the Reclam version which is about 4 Euros. So not a huge investment.

So I read the whole thing with not a lot of expectations. And overall I didn't hate it. It was slightly obnoxious at times, and Dostoyevsky seems to definitely have a thing for drama. Plus it has all the problems you can expect from a man during the 19th century when it comes to respecting women. The ending made up for a lot though.

Imprint


text: INI config plugin for Kore framework


text:
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;

class AddDisableOptionIndicators extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('indicators', function($table) {
            $table->boolean('enabled')->default(True);
        });
        DB::table('indicators')
            ->whereIn('id',[76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100])
            ->update(['enabled' => False]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('indicators', function($table) {
            $table->dropColumn('enabled');
        });
    }
}


text:
package io.github.siddharthgoel88.useragents.impl;

import io.github.siddharthgoel88.useragents.UserAgent;

/**
 * UserAgents from latest to oldest for MicrosoftUrlControl
 */
public class MicrosoftUrlControl extends UserAgent {

	public String[] getAllUserAgentStrings() {
		String [] userAgentStrings = {
			"Microsoft URL Control - 6.01.9782"
		};
		return userAgentStrings;
	}
}


text:
package com.song.utils;

import org.junit.Test;

/**
 * Created by song on 16/6/25.
 */
public class ClassUtilsTest {

  @Test
  public void testFindInterface() {
    System.out.println(ClassUtils.findInterfaces("com.song"));
  }

  @Test
  public void testFindSubClassesOfInterface() {
    System.out.println(ClassUtils.getInstance().findSubInterfaceOf(Iterable.class, "com.song"));
    System.out.println(ClassUtils.getInstance().findSubInterfaceOf(Object.class, "com.song"));
    System.out.println(ClassUtils.getInstance().findSubInterfaceOf(null, "com.song"));
  }

  interface A extends Iterable {
  }

  interface B extends A {
  }

  interface C extends B {
  }

  interface D extends C {
  }

}


text:
#include <sstmac/replacements/mpi.h>
#include <stdio.h>
#include <stdlib.h>
#include "mpitest.h"

namespace redscatbkinter {

int redscatbkinter( int argc, char **argv )
{
    int      err = 0;
    int      size, rsize, rank, i;
    int      recvcount, /** Each process receives this much data */
             sendcount, /** Each process contributes this much data */
	     basecount; /** Unit of elements - basecount *rsize is recvcount,
			   etc. */
    int      isLeftGroup;
    long long *sendbuf, *recvbuf;
    long long sumval;
    MPI_Comm comm;

    MTest_Init( &argc, &argv );
    comm = MPI_COMM_WORLD;

    basecount = 1024;

    while (MTestGetIntercomm( &comm, &isLeftGroup, 2 )) {
	if (comm == MPI_COMM_NULL) continue;

	MPI_Comm_remote_size( comm, &rsize );
	MPI_Comm_size( comm, &size );
	MPI_Comm_rank( comm, &rank );

	if (0) {
	    printf( "[%d] %s (%d,%d) remote %d\n", rank,
		    isLeftGroup ? "L" : "R",
		    rank, size, rsize );
	}

	recvcount = basecount * rsize;
	sendcount = basecount * rsize * size;

	sendbuf = (long long *) malloc( sendcount * sizeof(long long) );
	if (!sendbuf) {
	    fprintf( stderr, "Could not allocate %d ints for sendbuf\n",
		     sendcount );
	    MPI_Abort( MPI_COMM_WORLD, 1 );
	}

	for (i=0; i<sendcount; i++) {
	    sendbuf[i] = (long long)(rank*sendcount + i);
	}
	recvbuf = (long long *)malloc( recvcount * sizeof(long long) );
	if (!recvbuf) {
	    fprintf( stderr, "Could not allocate %d ints for recvbuf\n",
		     recvcount );
	    MPI_Abort( MPI_COMM_WORLD, 1 );
	}
	for (i=0; i<recvcount; i++) {
	    recvbuf[i] = (long long)(-i);
	}

	MPI_Reduce_scatter_block( sendbuf, recvbuf, recvcount, MPI_LONG_LONG,
				  MPI_SUM, comm );

	/** Check received data */
	for (i=0; i<recvcount; i++) {
	    sumval = (long long)(sendcount) * (long long)((rsize * (rsize-1))/2) +
		(long long)(i + rank * rsize * basecount) * (long long)rsize;
	    if (recvbuf[i] != sumval) {
		err++;
		if (err < 4) {
		    fprintf( stdout, "Did not get expected value for reduce scatter\n" );
		    fprintf( stdout, "[%d] %s recvbuf[%d] = %lld, expected %lld\n",
			     rank,
			     isLeftGroup ? "L" : "R",
			     i, recvbuf[i], sumval );
		}
	    }
	}

	free(sendbuf);
	free(recvbuf);

	MTestFreeComm( &comm );
    }

    MTest_Finalize( err );

    MPI_Finalize( );

    return 0;
}

}


text: typedef NSInteger LTFramerRulePriority;


text:
using base::Time;

const int kError = -1;
const int kExpectedCrash = 100;

// Starts a new process.
int RunSlave(int iteration) {
  base::FilePath exe;
  PathService::Get(base::FILE_EXE, &exe);

  base::CommandLine cmdline(exe);
  cmdline.AppendArg(base::IntToString(iteration));

  base::Process process = base::LaunchProcess(cmdline, base::LaunchOptions());
  if (!process.IsValid()) {
    printf("Unable to run test\n");
    return kError;
  }

  int exit_code;
  if (!process.WaitForExit(&exit_code)) {
    printf("Unable to get return code\n");
    return kError;
  }
  return exit_code;
}

// Main loop for the master process.
int MasterCode() {
  for (int i = 0; i < 100000; i++) {
    int ret = RunSlave(i);
    if (kExpectedCrash != ret)
      return ret;
  }

  printf("More than enough...\n");

  return 0;
}

// -----------------------------------------------------------------------

std::string GenerateStressKey() {
  char key[20 * 1024];
  size_t size = 50 + rand() % 20000;
  CacheTestFillBuffer(key, size, true);

  key[size - 1] = '\0';
  return std::string(key);
}

// kNumKeys is meant to be enough to have about 3x or 4x iterations before
// the process crashes.
#ifdef NDEBUG
const int kNumKeys = 4000;
#else
const int kNumKeys = 1200;
#endif
const int kNumEntries = 30;
const int kBufferSize = 2000;
const int kReadSize = 20;

// Things that an entry can be doing.
enum Operation { NONE, OPEN, CREATE, READ, WRITE, DOOM };

// This class encapsulates a cache entry and the operations performed on that
// entry. An entry is opened or created as needed, the current content is then
// verified and then something is written to the entry. At that point, the
// |state_| becomes NONE again, waiting for another write, unless the entry is
// closed or deleted.
class EntryWrapper {
 public:
  EntryWrapper() : entry_(nullptr), state_(NONE) {
    buffer_ = new net::IOBuffer(kBufferSize);
    memset(buffer_->data(), 'k', kBufferSize);
  }

  Operation state() const { return state_; }

  void DoOpen(int key);

 private:
  void OnOpenDone(int key, int result);
  void DoRead();
  void OnReadDone(int result);
  void DoWrite();
  void OnWriteDone(int size, int result);
  void DoDelete(const std::string& key);
  void OnDeleteDone(int result);
  void DoIdle();

  disk_cache::Entry* entry_;
  Operation state_;
  scoped_refptr<net::IOBuffer> buffer_;
};

// The data that the main thread is working on.
struct Data {
  Data() : pendig_operations(0), writes(0), iteration(0), cache(nullptr) {}

  int pendig_operations;  // Counter of simultaneous operations.
  int writes;             // How many writes since this iteration started.
  int iteration;          // The iteration (number of crashes).
  disk_cache::BackendImpl* cache;
  std::string keys[kNumKeys];
  EntryWrapper entries[kNumEntries];
};

Data* g_data = nullptr;

void EntryWrapper::DoOpen(int key) {
  DCHECK_EQ(state_, NONE);
  if (entry_)
    return DoRead();

  state_ = OPEN;
  int rv = g_data->cache->OpenEntry(
      g_data->keys[key], &entry_,
      base::Bind(&EntryWrapper::OnOpenDone, base::Unretained(this), key));
  if (rv != net::ERR_IO_PENDING)
    OnOpenDone(key, rv);
}

void EntryWrapper::OnOpenDone(int key, int result) {
  if (result == net::OK)
    return DoRead();

  CHECK_EQ(state_, OPEN);
  state_ = CREATE;
  result = g_data->cache->CreateEntry(
      g_data->keys[key], &entry_,
      base::Bind(&EntryWrapper::OnOpenDone, base::Unretained(this), key));
  if (result != net::ERR_IO_PENDING)
    OnOpenDone(key, result);
}

void EntryWrapper::DoRead() {
  int current_size = entry_->GetDataSize(0);
  if (!current_size)
    return DoWrite();

  state_ = READ;
  memset(buffer_->data(), 'k', kReadSize);
  int rv = entry_->ReadData(
      0, 0, buffer_.get(), kReadSize,
      base::Bind(&EntryWrapper::OnReadDone, base::Unretained(this)));
  if (rv != net::ERR_IO_PENDING)
    OnReadDone(rv);
}

void EntryWrapper::OnReadDone(int result) {
  DCHECK_EQ(state_, READ);
  CHECK_EQ(result, kReadSize);
  CHECK_EQ(0, memcmp(buffer_->data(), "Write: ", 7));
  DoWrite();
}

void EntryWrapper::DoWrite() {
  bool truncate = (rand() % 2 == 0);
  int size = kBufferSize - (rand() % 20) * kBufferSize / 20;
  state_ = WRITE;
  base::snprintf(buffer_->data(), kBufferSize,
                 "Write: %d iter: %d, size: %d, truncate: %d     ",
                 g_data->writes, g_data->iteration, size, truncate ? 1 : 0);
  int rv = entry_->WriteData(
      0, 0, buffer_.get(), size,
      base::Bind(&EntryWrapper::OnWriteDone, base::Unretained(this), size),
      truncate);
  if (rv != net::ERR_IO_PENDING)
    OnWriteDone(size, rv);
}

void EntryWrapper::OnWriteDone(int size, int result) {
  DCHECK_EQ(state_, WRITE);
  CHECK_EQ(size, result);
  if (!(g_data->writes++ % 100))
    printf("Entries: %d    \r", g_data->writes);

  int random = rand() % 100;
  std::string key = entry_->GetKey();
  if (random > 90)
    return DoDelete(key);  // 10% delete then close.

  if (random > 60) {  // 20% close.
    entry_->Close();
    entry_ = nullptr;
  }

  if (random > 80)
    return DoDelete(key);  // 10% close then delete.

  DoIdle();  // 60% do another write later.
}

void EntryWrapper::DoDelete(const std::string& key) {
  state_ = DOOM;
  int rv = g_data->cache->DoomEntry(
      key, base::Bind(&EntryWrapper::OnDeleteDone, base::Unretained(this)));
  if (rv != net::ERR_IO_PENDING)
    OnDeleteDone(rv);
}

void EntryWrapper::OnDeleteDone(int result) {
  DCHECK_EQ(state_, DOOM);
  if (entry_) {
    entry_->Close();
    entry_ = nullptr;
  }
  DoIdle();
}

void LoopTask();

void EntryWrapper::DoIdle() {
  state_ = NONE;
  g_data->pendig_operations--;
  DCHECK(g_data->pendig_operations);
  base::MessageLoop::current()->task_runner()->PostTask(FROM_HERE,
                                                        base::Bind(&LoopTask));
}

// The task that keeps the main thread busy. Whenever an entry becomes idle this
// task is executed again.
void LoopTask() {
  if (g_data->pendig_operations >= kNumEntries)
    return;

  int slot = rand() % kNumEntries;
  if (g_data->entries[slot].state() == NONE) {
    // Each slot will have some keys assigned to it so that the same entry will
    // not be open by two slots, which means that the state is well known at
    // all times.
    int keys_per_entry = kNumKeys / kNumEntries;
    int key = rand() % keys_per_entry + keys_per_entry * slot;
    g_data->pendig_operations++;
    g_data->entries[slot].DoOpen(key);
  }

  base::MessageLoop::current()->task_runner()->PostTask(FROM_HERE,
                                                        base::Bind(&LoopTask));
}

// This thread will loop forever, adding and removing entries from the cache.
// iteration is the current crash cycle, so the entries on the cache are marked
// to know which instance of the application wrote them.
void StressTheCache(int iteration) {
  int cache_size = 0x2000000;  // 32MB.
  uint32 mask = 0xfff;  // 4096 entries.

  base::FilePath path;
  PathService::Get(base::DIR_TEMP, &path);
  path = path.AppendASCII("cache_test_stress");

  base::Thread cache_thread("CacheThread");
  if (!cache_thread.StartWithOptions(
          base::Thread::Options(base::MessageLoop::TYPE_IO, 0)))
    return;

  g_data = new Data();
  g_data->iteration = iteration;
  g_data->cache = new disk_cache::BackendImpl(
      path, mask, cache_thread.task_runner().get(), NULL);
  g_data->cache->SetMaxSize(cache_size);
  g_data->cache->SetFlags(disk_cache::kNoLoadProtection);

  net::TestCompletionCallback cb;
  int rv = g_data->cache->Init(cb.callback());

  if (cb.GetResult(rv) != net::OK) {
    printf("Unable to initialize cache.\n");
    return;
  }
  printf("Iteration %d, initial entries: %d\n", iteration,
         g_data->cache->GetEntryCount());

  int seed = static_cast<int>(Time::Now().ToInternalValue());
  srand(seed);

  for (int i = 0; i < kNumKeys; i++)
    g_data->keys[i] = GenerateStressKey();

  base::MessageLoop::current()->task_runner()->PostTask(FROM_HERE,
                                                        base::Bind(&LoopTask));
  base::RunLoop().Run();
}

// We want to prevent the timer thread from killing the process while we are
// waiting for the debugger to attach.
bool g_crashing = false;

// RunSoon() and CrashCallback() reference each other, unfortunately.
void RunSoon(base::MessageLoop* target_loop);

void CrashCallback() {
  // Keep trying to run.
  RunSoon(base::MessageLoop::current());

  if (g_crashing)
    return;

  if (rand() % 100 > 30) {
    printf("sweet death...\n");
#if defined(OS_WIN)
    // Windows does more work on _exit() than we would like.
    base::Process::Current().Terminate(kExpectedCrash, false);
#elif defined(OS_POSIX)
    // On POSIX, _exit() will terminate the process with minimal cleanup,
    // and it is cleaner than killing.
    _exit(kExpectedCrash);
#endif
  }
}

void RunSoon(base::MessageLoop* target_loop) {
  const base::TimeDelta kTaskDelay = base::TimeDelta::FromSeconds(10);
  target_loop->task_runner()->PostDelayedTask(
      FROM_HERE, base::Bind(&CrashCallback), kTaskDelay);
}

// We leak everything here :)
bool StartCrashThread() {
  base::Thread* thread = new base::Thread("party_crasher");
  if (!thread->Start())
    return false;

  RunSoon(thread->message_loop());
  return true;
}

void CrashHandler(const std::string& str) {
  g_crashing = true;
  base::debug::BreakDebugger();
}

bool MessageHandler(int severity, const char* file, int line,
                    size_t message_start, const std::string& str) {
  const size_t kMaxMessageLen = 48;
  char message[kMaxMessageLen];
  size_t len = std::min(str.length() - message_start, kMaxMessageLen - 1);

  memcpy(message, str.c_str() + message_start, len);
  message[len] = '\0';
#if !defined(DISK_CACHE_TRACE_TO_LOG)
  disk_cache::Trace("%s", message);
#endif
  return false;
}

// -----------------------------------------------------------------------

#if defined(OS_WIN)
// {B9A153D4-31C3-48e4-9ABF-D54383F14A0D}
const GUID kStressCacheTraceProviderName = {
    0xb9a153d4, 0x31c3, 0x48e4,
        { 0x9a, 0xbf, 0xd5, 0x43, 0x83, 0xf1, 0x4a, 0xd } };
#endif

int main(int argc, const char* argv[]) {
  // Setup an AtExitManager so Singleton objects will be destructed.
  base::AtExitManager at_exit_manager;

  if (argc < 2)
    return MasterCode();

  logging::SetLogAssertHandler(CrashHandler);
  logging::SetLogMessageHandler(MessageHandler);

#if defined(OS_WIN)
  logging::LogEventProvider::Initialize(kStressCacheTraceProviderName);
#else
  base::CommandLine::Init(argc, argv);
  logging::LoggingSettings settings;
  settings.logging_dest = logging::LOG_TO_SYSTEM_DEBUG_LOG;
  logging::InitLogging(settings);
#endif

  // Some time for the memory manager to flush stuff.
  base::PlatformThread::Sleep(base::TimeDelta::FromSeconds(3));
  base::MessageLoopForIO message_loop;

  char* end;
  long int iteration = strtol(argv[1], &end, 0);

  if (!StartCrashThread()) {
    printf("failed to start thread\n");
    return kError;
  }

  StressTheCache(iteration);
  return 0;
}


text:
<!DOCTYPE html>

    <title>Shayan's blog</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="../styles/main.css" rel="stylesheet" type="text/css">

         Welcome to my EDA's blog

          Show Menu
          <input type="checkbox" id="show-menu" role="button">

Home

Blogs

Caltural blog

Reflection

Time and Habits

Emotional Intelligence

Daily Mindfulness

Self confidence

Control

motivation

motivation

Technical blog

HTML-CSS-DOM P1

HTML-CSS-DOM P2

Desing To Web Blog

Javascript Basic

Problem Solving

About me

Contact me

           Motivation

          How does life look through the 'pleasure, passion and purpose' lens?

         Completely opposite of what it has been till date. I mean I have
         always believed that happiness should be the sole motive of life but
         the sustainability factor never occurred to me before. My aim now
         will be to find a purpose and work towards it instead of doing things
         for pleasure.

         From the 'discovering values and higher purpose' exercise,

         One of my core values is helping people in need. I have always tried
         to help my family, friends or whoever I could whenever I could. I
         believe that when people are struggling and are in need, a helping
         hand can provide a huge support. Just knowing that you are not alone
         in the moment of adversity can give one a huge boost to keep fighting
         and can act as a great motivation.

         How did you find the resilience ideas and meditation exercise?

         The ideas were very effective. Having a calm body and mind (inner calm)
         , I found that I was a lot more emotionally stable during the exercise
         than the actual experience. I could convince myself easily to let go of
         grasping and aversion and that the experiences were only physiological
         sensations, something temporary (emotional resilience) and that whatever
         the experience there's always light at the end of the tunnel (cognitive
         resilience).