text:
<?php
# Generated by the protocol buffer compiler.  DO NOT EDIT!
# source: google/cloud/dialogflow/v2/entity_type.proto

namespace Google\Cloud\Dialogflow\V2;

use Google\Protobuf\Internal\GPBType;
use Google\Protobuf\Internal\RepeatedField;
use Google\Protobuf\Internal\GPBUtil;

/**
 * The request message for [EntityTypes.UpdateEntityType][google.cloud.dialogflow.v2.EntityTypes.UpdateEntityType].
 *
 * Generated from protobuf message google.cloud.dialogflow.v2.UpdateEntityTypeRequest
 */
class UpdateEntityTypeRequest extends \Google\Protobuf\Internal\Message
{
    /**
     * Required. The entity type to update.
     * Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.EntityType entity_type = 1;
     */
    private $entity_type = null;
    /**
     * Optional. The language of entity synonyms defined in `entity_type`. If not
     * specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     */
    private $language_code = '';
    /**
     * Optional. The mask to control which fields get updated.
     *
     * Generated from protobuf field .google.protobuf.FieldMask update_mask = 3;
     */
    private $update_mask = null;

    public function __construct() {
        \GPBMetadata\Google\Cloud\Dialogflow\V2\EntityType::initOnce();
        parent::__construct();
    }

    /**
     * Required. The entity type to update.
     * Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.EntityType entity_type = 1;
     * @return \Google\Cloud\Dialogflow\V2\EntityType
     */
    public function getEntityType()
    {
        return $this->entity_type;
    }

    /**
     * Required. The entity type to update.
     * Format: `projects/<Project ID>/agent/entityTypes/<EntityType ID>`.
     *
     * Generated from protobuf field .google.cloud.dialogflow.v2.EntityType entity_type = 1;
     * @param \Google\Cloud\Dialogflow\V2\EntityType $var
     * @return $this
     */
    public function setEntityType($var)
    {
        GPBUtil::checkMessage($var, \Google\Cloud\Dialogflow\V2\EntityType::class);
        $this->entity_type = $var;

        return $this;
    }

    /**
     * Optional. The language of entity synonyms defined in `entity_type`. If not
     * specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     * @return string
     */
    public function getLanguageCode()
    {
        return $this->language_code;
    }

    /**
     * Optional. The language of entity synonyms defined in `entity_type`. If not
     * specified, the agent's default language is used.
     * [More than a dozen
     * languages](https://dialogflow.com/docs/reference/language) are supported.
     * Note: languages must be enabled in the agent, before they can be used.
     *
     * Generated from protobuf field string language_code = 2;
     * @param string $var
     * @return $this
     */
    public function setLanguageCode($var)
    {
        GPBUtil::checkString($var, True);
        $this->language_code = $var;

        return $this;
    }

    /**
     * Optional. The mask to control which fields get updated.
     *
     * Generated from protobuf field .google.protobuf.FieldMask update_mask = 3;
     * @return \Google\Protobuf\FieldMask
     */
    public function getUpdateMask()
    {
        return $this->update_mask;
    }

    /**
     * Optional. The mask to control which fields get updated.
     *
     * Generated from protobuf field .google.protobuf.FieldMask update_mask = 3;
     * @param \Google\Protobuf\FieldMask $var
     * @return $this
     */
    public function setUpdateMask($var)
    {
        GPBUtil::checkMessage($var, \Google\Protobuf\FieldMask::class);
        $this->update_mask = $var;

        return $this;
    }

}


text:
unlink <job_dagman_rescue_recov-node*.works>;

# Lower-level nodeB1 should work the first time through.
system("touch job_dagman_rescue_recov-nodeB1.works");

# Lower-level nodeC should work the first time through.
system("touch job_dagman_rescue_recov-nodeC.works");

redpajama_set_name: RedPajamaGithub


text:
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>W28832_text</title>
        <link rel="stylesheet" type="text/css" href="style.css" />

                «

    <p class="styleSans1.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">

    <p class="styleSans30.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">PATHFINDER"
A Schlumberger Company

    <p class="styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Emerald Oil Inc
McKenzie County, ND Sec.08 - T149N - R102W Mongoose 6-8-5H
Original Hole Rev 2

    <p class="styleSans16.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Anticollision

    <p class="styleSans15.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">Report

    <p class="styleSans9.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">26 September, 2014

    <p class="styleSans20.0000<enum PANGO_WEIGHT_NORMAL of type PangoWeight><enum PANGO_STYLE_NORMAL of type PangoStyle>">EM ERALD
OIL INC.


text:
<?php

namespace AppBundle\Importer\Feed;

use Symfony\Component\Console\Output\OutputInterface;
use AppBundle\Importer\Importer;
use AppBundle\Entity\Activity;
use AppBundle\Entity\ActivityAttribute;
use AppBundle\Entity\Source;

class FeedImporter extends Importer
{
    protected $feedParser;

    public function getName() {

        return 'Feed';
    }

    public function getDescription() {

        return "Récupère l'activité à partir d'un flux RSS ou Atom";
    }

    public function getParameters() {

        return array(
            'path' => array("required" => true, "label" => "Uri", "help" => "Url ou chemin vers un flux rss"),
            'name' => array("required" => true, "label" => "Name", "help" => "Nom du flux (optionnelle)"),
        );
    }

    public function updateTitle(Source $source) {
        $source->setTitle($source->getParameter('path'));
    }

    public function __construct($am, $em, $feedParser)
    {
        parent::__construct($am, $em);

        $this->feedParser = $feedParser;
    }

    public function run(Source $source, OutputInterface $output, $dryrun = false, $checkExist = true, $limit = false) {
        $output->writeln(sprintf("<comment>Started import feed %s</comment>", $source->getTitle()));

        $parser = $this->getParser($source);

        $feed = $parser->execute();

        $nb = 0;

        foreach($feed->getItems() as $item) {
            $author = $item->getAuthor() ? $item->getAuthor() : null;

            $activity = new Activity();
            $activity->setExecutedAt($item->getDate());
            $activity->setTitle($item->getTitle());
            $activity->setContent($item->getContent());

            if($source->getParameter('name')) {
                $name = new ActivityAttribute();
                $name->setName("Name");
                $name->setValue($source->getParameter('name'));
            }

            if($item->getAuthor()) {
                $author = new ActivityAttribute();
                $author->setName("Author");
                $author->setValue($item->getAuthor());
            }

            if(isset($name)) {
                $activity->addAttribute($name);
            }

            if(isset($author)) {
                $activity->addAttribute($author);
            }

            try {
                $this->am->addFromEntity($activity, $checkExist);

                if(isset($name)) {
                    $this->em->persist($name);
                }
                if(isset($author)) {
                    $this->em->persist($author);
                }
                $this->em->persist($activity);

                if(!$dryrun) {
                    $this->em->flush($activity);
                }

                $nb++;

                if($limit && $nb > $limit) {
                    break;
                }

                if($output->isVerbose()) {
                    $output->writeln(sprintf("<info>Imported</info>;%s;%s", $item->getDate()->format('c'), $item->getTitle()));
                }

            } catch (\Exception $e) {
                if($output->isVerbose()) {
                    $output->writeln(sprintf("<error>%s</error>;%s;%s", $e->getMessage(), $item->getDate()->format('c'), $item->getTitle()));
                }
            }

        }

        $output->writeln(sprintf("<info>%s new activity imported</info>", $nb));
    }

    public function getParser($source) {
        if(preg_match("|^file://|", $source->getParameter('path'))) {
            $content = file_get_contents($source->getParameter('path'));

            return $this->feedParser->getParser(
                $source->getParameter('path'),
                file_get_contents($source->getParameter('path')),
                mb_detect_encoding($content)
            );
        }

        $resource = $this->feedParser->download($source->getParameter('path'));

        return $this->feedParser->getParser(
            $resource->getUrl(),
            $resource->getContent(),
            $resource->getEncoding()
        );
    }

    public function getRootDir() {

        return dirname(__FILE__);
    }

    public function check(Source $source) {
        parent::check($source);

        try {
            $resource = $this->feedParser->download($source->getSource());
            $parser = $this->feedParser->getParser($resource->getUrl(), $resource->getContent(), $resource->getEncoding());
        } catch(\Exception $e) {

            throw new \Exception(sprintf("Feed Url %s isn't valid : %s", $source->getSource(), $e->getMessage()));
        }
    }

}


text:
<!DOCTYPE frameset SYSTEM "frameset.dtd">
<frameset>
    <note/>
    <predicate lemma="embrace">
        <note/>
        <roleset framnet="" id="embrace.01" name="accept enthusiastically or include" vncls="">
            <roles>
                <role descr="includer, agent" f="" n="0"/>
                <note/>
                <role descr="entity embraced" f="ppt" n="1"/>
                <role descr="embraced as" f="prd" n="2"/>
            </roles>
            <note>Based on sentences in nouns-00040. Comparison to 'embrace.01-v'. No VN or FN classes. Framed by Katie.</note>
            <example name="args 0 and 1" src="" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>Its passionate embrace of this reporter who after all was facing jail</text>
                <note/>
                <arg f="" n="0">Its</arg>
                <arg f="mnr" n="m">passionate</arg>
                <rel f="">embrace</rel>
                <arg f="" n="1">of this reporter who after all was facing jail</arg>
            </example>
            <example name="arg 1 only" src="" type="">
                <inflection aspect="ns" form="ns" person="ns" tense="ns" voice="ns"/>
                <text>an embrace of tolerance and diversity</text>
                <note/>
                <rel f="">embrace</rel>
                <arg f="" n="1">of tolerance adn diversity</arg>
            </example>
        </roleset>
    </predicate>
</frameset>


text:
{% extends "layout.html" %}

{% block body %}

		{% if values.id %}

				Delete

		{% endif %}

{% block wording %}Edit{% endblock %} Purchase

		<form action="{% block formaction %}{{ url_for('purchases_edit', id=values.id) }}{% endblock %}" method="post" autocomplete="off">
			<input type="text" name="title" placeholder="Title" value="{{ values.title }}">
			<input type="text" name="amount" placeholder="Amount" value="{{ values.amount }}">
			<input type="text" name="date" class="datepicker" placeholder="Purchase Date (YYYY-MM-DD)" value="{{ values.date }}">
			<input type="submit" class="button main" value="{% block buttonvalue %}Save{% endblock %}">
		</form>

{% endblock %}


text:
{% include 'header.html' %}

choose a db on the left

{% include 'footer.html'%}


text:
namespace redmine {
namespace util {
std::string getcwd();

result rm(const std::string &filename);
}
}

#endif


text:
macro_rules! try_opt_clone {
    ($expr:expr) => (match $expr {
        ::std::option::Option::Some(ref val) => val.clone(),
        ::std::option::Option::None => return None
    })
}


text:
package users

import (
	"testing"

	"github.com/halverneus/sample/common/db"
	"github.com/halverneus/sample/sql/usersql"
)

// NOTE: Testing requires a schema that can be accessed with the following
// settings prior to execution:
var (
	host     = "127.0.0.1"
	port     = 3306
	schema   = "sample"
	user     = "sample"
	password = "sample"
)

func TestUpgrade(t *testing.T) {

	// Happy path...
	if err := db.Connect(host, port, schema, user, password); nil != err {
		t.Errorf("Unable to connect to database: %v", err)
	}
	db.Execute("DROP SCHEMA sample")
	if err := db.Execute("CREATE SCHEMA sample DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); nil != err {
		t.Errorf("Unable to create database: %v", err)
	}
	if err := db.Connect(host, port, schema, user, password); nil != err {
		t.Errorf("Unable to reconnect to database: %v", err)
	}

	if err := Upgrade(); nil != err {
		t.Errorf("Upgrade failed: %v", err)
	}

	// Error path...
	db.Execute("DROP SCHEMA sample")
	if err := db.Execute("CREATE SCHEMA sample DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); nil != err {
		t.Errorf("Unable to create database: %v", err)
	}
	if err := db.Connect(host, port, schema, user, password); nil != err {
		t.Errorf("Unable to reconnect to database: %v", err)
	}

	if err := db.Execute(usersql.CreateEncryptionFunction); nil != err {
		t.Errorf("Unable to add pre-existing function: %v", err)
	}

	if err := Upgrade(); nil == err {
		t.Error("Upgrade succeeded when it should have failed")
	}

	// Restore database...
	db.Execute("DROP SCHEMA sample")
	if err := db.Execute("CREATE SCHEMA sample DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci"); nil != err {
		t.Errorf("Unable to create database: %v", err)
	}
}


text:
export default function counter(state = 0, action){
  switch(action.type){
    case 'INCREMENT':
      state += 1 ; break;
    case 'DECREMENT':
      state -= 1 ; break;
  }

  return state;
}


text:
import { PipeTransform, Pipe, NgModule } from '@angular/core';
import { isUndefined } from '../utils/utils';

@Pipe({
  name: 'isDefined',
})
export class IsDefinedPipe implements PipeTransform {
  transform(value: any): boolean {
    return !isUndefined(value);
  }
}

@NgModule({
  declarations: [IsDefinedPipe],
  exports: [IsDefinedPipe],
})
export class NgIsDefinedPipeModule {}


text:
namespace cc {

scoped_refptr<PictureImageLayer> PictureImageLayer::Create(
    const LayerSettings& settings) {
  return make_scoped_refptr(new PictureImageLayer(settings));
}

PictureImageLayer::PictureImageLayer(const LayerSettings& settings)
    : PictureLayer(settings, this) {
}

PictureImageLayer::~PictureImageLayer() {
  ClearClient();
}

scoped_ptr<LayerImpl> PictureImageLayer::CreateLayerImpl(
    LayerTreeImpl* tree_impl) {
  return PictureImageLayerImpl::Create(tree_impl, id(), is_mask());
}

bool PictureImageLayer::HasDrawableContent() const {
  return image_ && PictureLayer::HasDrawableContent();
}

void PictureImageLayer::SetImage(skia::RefPtr<const SkImage> image) {
  // SetImage() currently gets called whenever there is any
  // style change that affects the layer even if that change doesn't
  // affect the actual contents of the image (e.g. a CSS animation).
  // With this check in place we avoid unecessary texture uploads.
  if (image_.get() == image.get())
    return;

  image_ = image.Pass();
  UpdateDrawsContent(HasDrawableContent());
  SetNeedsDisplay();
}

scoped_refptr<DisplayItemList> PictureImageLayer::PaintContentsToDisplayList(
    const gfx::Rect& clip,
    ContentLayerClient::PaintingControlSetting painting_control) {
  DCHECK(image_);
  DCHECK_GT(image_->width(), 0);
  DCHECK_GT(image_->height(), 0);

  // Picture image layers can be used with GatherPixelRefs, so cached SkPictures
  // are currently required.
  DisplayItemListSettings settings;
  settings.use_cached_picture = true;
  scoped_refptr<DisplayItemList> display_list =
      DisplayItemList::Create(clip, settings);

  SkPictureRecorder recorder;
  SkCanvas* canvas = recorder.beginRecording(gfx::RectToSkRect(clip));

  SkScalar content_to_layer_scale_x =
      SkFloatToScalar(static_cast<float>(bounds().width()) / image_->width());
  SkScalar content_to_layer_scale_y =
      SkFloatToScalar(static_cast<float>(bounds().height()) / image_->height());
  canvas->scale(content_to_layer_scale_x, content_to_layer_scale_y);

  // Because Android WebView resourceless software draw mode rasters directly
  // to the root canvas, this draw must use the kSrcOver_Mode so that
  // transparent images blend correctly.
  canvas->drawImage(image_.get(), 0, 0);

  skia::RefPtr<SkPicture> picture =
      skia::AdoptRef(recorder.endRecordingAsPicture());
  auto* item = display_list->CreateAndAppendItem<DrawingDisplayItem>();
  item->SetNew(picture.Pass());

  display_list->Finalize();
  return display_list;
}

bool PictureImageLayer::FillsBoundsCompletely() const {
  return false;
}

size_t PictureImageLayer::GetApproximateUnsharedMemoryUsage() const {
  return 0;
}

}  // namespace cc


text: <?php include $this->partial('website_edit_form')?>


text:
package org.jenkinsci.plugins.coordinator.model;

import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class TreeNode implements Serializable{

	private static final String[] REFLECTION_EXCLUDE_FIELDS = new String[] {"chidlren"};
	static final JsonConfig JSON_CONFIG;
	static final TreeNode EMPTY_ROOT;	// for every tree initialization
	private static final long serialVersionUID = 1L;

	static {
		JSON_CONFIG = new JsonConfig();
		JSON_CONFIG.setRootClass(TreeNode.class);
		HashMap<String, Class<?>> classMap = new HashMap<String, Class<?>>(3);
		classMap.put("children", TreeNode.class);
		classMap.put("state", State.class);
		JSON_CONFIG.setClassMap(classMap);
		// save the output log from unnecessary large size
		JSON_CONFIG.setExcludes(new String[]{"parent", "jsonString", "leaf"});

		EMPTY_ROOT = new TreeNode();
		EMPTY_ROOT.setText("Root");

		// ROOT default is breaking serial node
		// EMPTY_ROOT.setType("serial");
		EMPTY_ROOT.state.breaking = true;
		EMPTY_ROOT.state.execPattern = "serial";

	}

	private String id;
	private String text;
	private String type;	// TODO target be deprecated in 1.5.0

	private transient TreeNode parent;

	private List<TreeNode> children = new ArrayList<TreeNode>();

	private State state = new State();

	private int buildNumber;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getText() {
		return text;
	}

	public void setText(String text) {
		this.text = text.trim();
	}

	public List<TreeNode> getChildren() {
		return this.children;
	}

	public void setChildren(List<TreeNode> children) {
		this.children = children;
	}

	public State getState() {
		return state;
	}

	public void setState(State state) {
		this.state = state;
	}

	public boolean isLeaf() {
		return getChildren().size() == 0;
	}

	public int getBuildNumber() {
		return buildNumber;
	}

	public void setBuildNumber(int buildNumber) {
		this.buildNumber = buildNumber;
	}

	public TreeNode getParent() {
		return parent;
	}

	public void setParent(TreeNode parent) {
		this.parent = parent;
	}

	public String toString() {
		return ToStringBuilder.reflectionToString(this);
	}

	public boolean equals(Object obj) {
		// since we have id a more significant field
		if(! (obj instanceof TreeNode)){
			return false;
		}
		TreeNode node = (TreeNode) obj;
		return EqualsBuilder.reflectionEquals(this, node, REFLECTION_EXCLUDE_FIELDS);
	}

	public int hashCode() {
		return HashCodeBuilder.reflectionHashCode(this, REFLECTION_EXCLUDE_FIELDS);
	}

	public String getJsonString(){
		return JSONObject.fromObject(this, JSON_CONFIG).toString();
	}

	public TreeNode clone(boolean deep){
		TreeNode clone = new TreeNode();
		clone.id = this.id;
		clone.text = this.text;
		clone.type = this.type;
		clone.state = this.state;
		clone.parent = this.parent;
		clone.buildNumber = this.buildNumber;
		if(deep){
			for(TreeNode c: this.children){
				clone.children.add(c.clone(deep));
			}
		} else {
			clone.children = this.children;
		}
		return clone;
	}

	/**
	 * Making this a calculated string based on {@code TreeNode.state.breaking, TreeNode.state.execPattern}
	 * @return A calculated String as {@code leaf, breaking-serial,breaking-parallel,non-breaking-serial,non-breaking-parallel}
	 */
	public String getType() {
		if(this.isLeaf()){
			return "leaf";
		}
		String result;
		if(StringUtils.isEmpty(this.state.execPattern)){
			// default is breaking
			result = "breaking-"+type;
		} else {
			String breakingStype = this.state.breaking? "breaking-": "non-breaking-";
			result = breakingStype+this.state.execPattern;
		}
		return result;
	}

	/**
	 * For compatible sake
	 * Since it's a calculated field from now on,
	 * please use {@link #State}{@code .breaking} and {@link #State}{@code .execPattern} instead
	 * @param type
	 */
	@Deprecated
	public void setType(String type) {
		this.type = type;
	}

	public boolean shouldChildrenSerialRun(){
		// TODO replace by {@code "serial".equals(TreeNode.state.execPattern) }
		if(StringUtils.isEmpty(this.state.execPattern)) {
			return this.getType().contains("serial");
		} else {
			return "serial".equals(this.state.execPattern);
		}
	}

	public boolean shouldChildrenParallelRun(){
		// TODO replace by {@code "parallel".equals(TreeNode.state.execPattern) }
		if(StringUtils.isEmpty(this.state.execPattern)) {
			return this.getType().contains("parallel");
		} else {
			return "parallel".equals(this.state.execPattern);
		}
	}

	public static class State implements Serializable{
		private static final long serialVersionUID = 1L;

		public boolean opened = true;
		public boolean disabled = false;
	    public boolean selected = true;
	    public boolean checked = false;

	    // as I could not find out where to save this status
	    // it's mainly for actually doing atomic job to get the child job linked
	    // only used for server side, client side has its own mechanism to work well
	    public boolean undetermined = false;

	    //public String type; // it's weird that type in state doesnot change as ui changes
	    // TreeNode.getType() is composed by below two options
	    public boolean breaking = true;
	    public String execPattern = "";

	    public State(){}
	}

	public static TreeNode fromString(String jsonStr){
		JSONObject jsonObject = JSONObject.fromObject(jsonStr, TreeNode.JSON_CONFIG);
		return (TreeNode)JSONObject.toBean(jsonObject, TreeNode.JSON_CONFIG);
	}
}


text:
<?xml version="1.0" ?>

<container xmlns="http://symfony.com/schema/dic/services"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

    <services>
        <service id="snide_travinizer.repo_manager" class="%snide_travinizer.repo_manager.class%" public="true">
            <argument type="service" id="travinizer_repo.repo_repository"/>
            <argument>%snide_travinizer.model.repo.class%</argument>
            <argument type="service" id="snide_travinizer.travis_loader"/>
            <argument type="service" id="snide_travinizer.scrutinizer_loader"/>
            <argument type="service" id="snide_travinizer.composer_reader"/>
            <argument type="service" id="snide_travinizer.version_eye_loader" />
            <argument type="service" id="security.context" />
        </service>
    </services>
</container>


text:
package org.apache.cassandra.cql3.statements;

import java.nio.ByteBuffer;
import java.util.*;

import org.apache.cassandra.config.Schema;
import org.apache.cassandra.cql3.*;
import org.apache.cassandra.config.CFMetaData;
import org.apache.cassandra.db.*;
import org.apache.cassandra.db.marshal.*;
import org.apache.cassandra.exceptions.*;
import org.apache.cassandra.thrift.ThriftValidation;

/**
 * A DELETE parsed from a CQL query statement.
 */
public class DeleteStatement extends ModificationStatement
{
    private CFDefinition cfDef;
    private final List<Operation.RawDeletion> deletions;
    private final List<Relation> whereClause;

    private final List<Operation> toRemove;
    private final Map<ColumnIdentifier, List<Term>> processedKeys = new HashMap<ColumnIdentifier, List<Term>>();

    public DeleteStatement(CFName name, List<Operation.RawDeletion> deletions, List<Relation> whereClause, Attributes attrs)
    {
        super(name, attrs);

        this.deletions = deletions;
        this.whereClause = whereClause;
        this.toRemove = new ArrayList<Operation>(deletions.size());
    }

    protected void validateConsistency(ConsistencyLevel cl) throws InvalidRequestException
    {
        if (type == Type.COUNTER)
            cl.validateCounterForWrite(cfDef.cfm);
        else
            cl.validateForWrite(cfDef.cfm.ksName);
    }

    public Collection<RowMutation> getMutationsInternal(List<ByteBuffer> variables, boolean local, ConsistencyLevel cl, long now, boolean isBatch)
    throws RequestExecutionException, RequestValidationException
    {
        // keys
        List<ByteBuffer> keys = UpdateStatement.buildKeyNames(cfDef, processedKeys, variables);

        // columns
        ColumnNameBuilder builder = cfDef.getColumnNameBuilder();
        CFDefinition.Name firstEmpty = UpdateStatement.buildColumnNames(cfDef, processedKeys, builder, variables, false);

        boolean fullKey = builder.componentCount() == cfDef.columns.size();
        boolean isRange = cfDef.isCompact ? !fullKey : (!fullKey || toRemove.isEmpty());

        if (!toRemove.isEmpty() && isRange)
            throw new InvalidRequestException(String.format("Missing mandatory PRIMARY KEY part %s since %s specified", firstEmpty, toRemove.iterator().next().columnName));

        Set<ByteBuffer> toRead = null;
        for (Operation op : toRemove)
        {
            if (op.requiresRead())
            {
                if (toRead == null)
                    toRead = new TreeSet<ByteBuffer>(UTF8Type.instance);
                toRead.add(op.columnName.key);
            }
        }

        Map<ByteBuffer, ColumnGroupMap> rows = toRead != null ? readRows(keys, builder, toRead, (CompositeType)cfDef.cfm.comparator, local, cl) : null;

        Collection<RowMutation> rowMutations = new ArrayList<RowMutation>(keys.size());
        UpdateParameters params = new UpdateParameters(cfDef.cfm, variables, getTimestamp(now), -1, rows);

        for (ByteBuffer key : keys)
            rowMutations.add(mutationForKey(cfDef, key, builder, isRange, params, isBatch));

        return rowMutations;
    }

    public RowMutation mutationForKey(CFDefinition cfDef, ByteBuffer key, ColumnNameBuilder builder, boolean isRange, UpdateParameters params, boolean isBatch)
    throws InvalidRequestException
    {
        QueryProcessor.validateKey(key);
        ColumnFamily cf = TreeMapBackedSortedColumns.factory.create(Schema.instance.getCFMetaData(cfDef.cfm.ksName, columnFamily()));

        if (toRemove.isEmpty() && builder.componentCount() == 0)
        {
            // No columns specified, delete the row
            cf.delete(new DeletionInfo(params.timestamp, params.localDeletionTime));
        }
        else
        {
            if (isRange)
            {
                assert toRemove.isEmpty();
                ByteBuffer start = builder.build();
                ByteBuffer end = builder.buildAsEndOfRange();
                cf.addAtom(params.makeRangeTombstone(start, end));
            }
            else
            {
                // Delete specific columns
                if (cfDef.isCompact)
                {
                    ByteBuffer columnName = builder.build();
                    cf.addColumn(params.makeTombstone(columnName));
                }
                else
                {
                    for (Operation op : toRemove)
                        op.execute(key, cf, builder.copy(), params);
                }
            }
        }

        RowMutation rm;
        if (isBatch)
        {
            // we might group other mutations together with this one later, so make it mutable
            rm = new RowMutation(cfDef.cfm.ksName, key);
            rm.add(cf);
        }
        else
        {
            rm = new RowMutation(cfDef.cfm.ksName, key, cf);
        }
        return rm;
    }

    public ParsedStatement.Prepared prepare(ColumnSpecification[] boundNames) throws InvalidRequestException
    {
        CFMetaData metadata = ThriftValidation.validateColumnFamily(keyspace(), columnFamily());
        type = metadata.getDefaultValidator().isCommutative() ? Type.COUNTER : Type.LOGGED;

        cfDef = metadata.getCfDef();
        UpdateStatement.processKeys(cfDef, whereClause, processedKeys, boundNames);

        for (Operation.RawDeletion deletion : deletions)
        {
            CFDefinition.Name name = cfDef.get(deletion.affectedColumn());
            if (name == null)
                throw new InvalidRequestException(String.format("Unknown identifier %s", deletion.affectedColumn()));

            // For compact, we only have one value except the key, so the only form of DELETE that make sense is without a column
            // list. However, we support having the value name for coherence with the static/sparse case
            if (name.kind != CFDefinition.Name.Kind.COLUMN_METADATA && name.kind != CFDefinition.Name.Kind.VALUE_ALIAS)
                throw new InvalidRequestException(String.format("Invalid identifier %s for deletion (should not be a PRIMARY KEY part)", name));

            Operation op = deletion.prepare(name);
            op.collectMarkerSpecification(boundNames);
            toRemove.add(op);
        }

        return new ParsedStatement.Prepared(this, Arrays.<ColumnSpecification>asList(boundNames));
    }

    public ParsedStatement.Prepared prepare() throws InvalidRequestException
    {
        ColumnSpecification[] boundNames = new ColumnSpecification[getBoundsTerms()];
        return prepare(boundNames);
    }

    public String toString()
    {
        return String.format("DeleteStatement(name=%s, columns=%s, keys=%s)",
                             cfName,
                             deletions,
                             whereClause);
    }
}


text:
constexpr auto USAGE = R"(USAGE
    uwt [-h | --help] (-w <id> | --wid <id>) (-a <attr> | --attrs <attr>)

DESCRIPTION
    uwt gets attributes of a window, such as position,
    size, mapping status etc. Attributes will be printed in the
    order in which attribute options are placed.

    e.g. printing position and size, respectively: uwt -w $(ufw) -a xywh

OPTIONS
    -a <attr>, --attrs <attr>
        Attributes to be printed out. The order is relative to
        how options are placed. For instance, `yh` will print
        the y window's position, then the window's height.

        x   x position
        y   y position
        w   width
        h   height
        b   border width
        i   ignoreness state
        m   mapping state

    -w <id>, --wid <id>
        The window to get attributes from.

    -r, --root
        gets attributes from screen (root window).

    -h, --help
        Shows this help.)";

int main(int argc, char** argv)
{
    const auto basename = *argv++;

    try
    {
        optional<xcb_window_t> opt_wid{nullopt};
        optional<string_view> opt_attrs{nullopt};
        bool root = false;

        while(*argv)
        {
            if(auto p = args::getopt(argv, "-w", "--wid"))
            {
                opt_wid = std::stoul(p, nullptr, 16);
                continue;
            }
            if(auto p = args::getopt(argv, "-a", "--attrs"))
            {
                opt_attrs = string_view{p};
                continue;
            }
            if(args::getopt(argv, "-r", "--root", args::no_value))
            {
                root = true;
                continue;
            }
            if(args::getopt(argv, "-h", "--help", args::no_value))
            {
                std::puts(USAGE);
                return 0;
            }

            throw args::invalid_option{format("unknown `{}' option.", *argv)};
        }

        auto conn = muxx::make_connection();
        xcb_window_t wid;

        if(root)
        {
            wid = muxx::get_screen(conn).root;
        }
        else if(opt_wid)
        {
            wid = *opt_wid;
        }
        else
        {
            throw args::invalid_option{"missing 'window id' option (expected -w <wid> or -r)."};
        }

        if(opt_attrs)
        {
            auto conn_guard = muxx::make_flush_guard(conn);

            assert(muxx::get_screen(conn).root == wid || muxx::is_alive(conn, wid));

            std::for_each(std::begin(*opt_attrs), std::end(*opt_attrs), [&](char a)
            {
                switch(a)
                {
                    case 'w': std::printf("%d ", muxx::get_window_size(conn, wid)->x); break;
                    case 'h': std::printf("%d ", muxx::get_window_size(conn, wid)->y); break;
                    case 'x': std::printf("%d ", muxx::get_window_position(conn, wid)->x); break;
                    case 'y': std::printf("%d ", muxx::get_window_position(conn, wid)->y); break;
                    case 'b': std::printf("%d ", muxx::get_window_border(conn, wid).value()); break;
                    case 'm': std::printf("%d ", muxx::is_mapped(conn, wid)); break;
                    case 'i': std::printf("%d ", muxx::is_ignored(conn, wid)); break;
                    default:
                        throw args::invalid_option{format("`{c}' is not a valid attribute option.", a)};
                }
            });
        }
        else
            throw args::invalid_option{"missing 'attributes' option (expected -a <attrs>)."};

    }
    catch(const args::invalid_option& e)
    {
        std::fprintf(stderr, "%s: %s\n", basename, e.what());
        return 1;
    }
    return 0;
}


text:
@implementation ExternalShareManager

+ (instancetype)sharedInstance {
    DEFINE_SHARED_INSTANCE_USING_BLOCK(^ {
        return [[self alloc] init];
    })
}

- (void)shareToSNSWithImage:(UIImage *)image
                    content:(NSString *)content
                  shareType:(ShareType)type
                     result:(SSPublishContentEventHandler)result {
    id<ISSContent> publishContent = [ShareSDK content:content
                                       defaultContent:@"【来自天购】 http://www.t-go.biz/"
                                                image:(image ? [ShareSDK jpegImageWithImage:image quality:0.8] : nil)
                                                title:(content ? content : @"天购——这就是生活习惯")
                                                  url:@"http://www.t-go.biz/"
                                          description:nil
                                            mediaType:SSPublishContentMediaTypeNews];

    id<ISSAuthOptions> authOptions = [ShareSDK authOptionsWithAutoAuth:YES
                                                         allowCallback:NO
                                                         authViewStyle:SSAuthViewStylePopup
                                                          viewDelegate:nil
                                               authManagerViewDelegate:nil];
    [authOptions setPowerByHidden:YES];

    [ShareSDK shareContent:publishContent
                      type:type
               authOptions:authOptions
             statusBarTips:YES
                    result:result];
}

@end


text:
package shinro;

import java.util.ArrayList;

/**
 * Data structure and methods to represent a shinro puzzle
 * @author Joseph Eib
 * @since December 2014
 */
public class ShinroPuzzle implements Cloneable{
	private int[][] puzzleGrid;
	private int[] rowHeaderNum, colHeaderNum;
	private int size, numPoints;

	public static final int SIZE = 8, POINTS = 12;
	public static final int EMPTY = 0, POINT = 9, X = -9,
			N = 1, NE = 2, E = 3, SE = 4, S = 5, SW = 6, W = 7, NW = 8,
			n = -1, ne = -2, e = -3, se = -4, s = -5, sw = -6, w = -7, nw = -8;

	/**
	 * Creates a new empty ShinroPuzzle
	 *

	 * All spaces are initialized to be EMPTY.
	 * All header numbers and numPoints are initialized to be zero.
	 */
	public ShinroPuzzle() {
		int i, j;
		this.size = SIZE;
		this.numPoints = 0;
		this.puzzleGrid = new int[this.size][this.size];
		this.rowHeaderNum = new int[this.size];
		this.colHeaderNum = new int[this.size];

		for (i = 0; i < this.size; i++)
			for (j = 0; j < this.size; j++)
				this.puzzleGrid[i][j] = 0;

		for (i = 0; i < this.size; i++) {
			this.rowHeaderNum[i] = this.colHeaderNum[i] = 0;
		}
	}

	/**
	 * Creates a new ShinroPuzzle with the specified layout.
	 *

	 * Once the puzzle is initialized, any points are removed by initPuzzle().
	 * @param intMatrix  the two-dimensional array containing the layout of the
	 * puzzle.
	 */
	public ShinroPuzzle(int[][] intMatrix) {
		this();
		this.initPuzzle(intMatrix);
	}

	/**
	 * GridPos-based convenience method for {@link #atPos(int, int)}
	 * @param pos  the GridPos of the desired location
	 * @return the int value at the desired coordinates
	 */
	public int atPos(GridPos pos) {
		return this.atPos(pos.getRow(), pos.getCol());
	}

	/**
	 * Gets a value from the puzzleGrid by the row and column indices
	 * @param row  the row index of the space to get
	 * @param col  the column index of the space to get
	 * @return the int value at the desired coordinates
	 */
	public int atPos(int row, int col) {
		return this.puzzleGrid[row][col];
	}

	/**
	 * GridPos-based convenience method for {@link #clearSpace(int, int)}
	 * @param pos  the GridPos of the desired location
	 */
	public void clearSpace(GridPos pos) {
		this.clearSpace(pos.getRow(), pos.getCol());
	}

	/**
	 * Deletes the contents of a specified space unless it is an arrow
	 * If the space contains a point, then any arrows satisfied by the point will
	 * be unsatisfied.
	 *

	 * This method does nothing if the space is already EMPTY
	 * @param row  the row index of the space to clear
	 * @param col  the column index of the space to clear
	 */
	public void clearSpace(int row, int col) {
		if (!this.isArrow(row, col)) {
			if (this.atPos(row, col) == POINT) {
				for (GridPos arrow : this.getPointingArrows(row, col)) {
					if (this.getTypeInList(POINT,
							this.getArrowToEdge(arrow)).size() == 1) {
						this.unsatsifyArrow(arrow);
					}
				}
			}
			this.puzzleGrid[row][col] = EMPTY;
		}
	}

	/**
	 * Returns a clone of this ShinroPuzzle instance
	 * @return the copied ShinroPuzzle
	 */
	@Override
	public ShinroPuzzle clone() {
		ShinroPuzzle copy = new ShinroPuzzle();
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				copy.setPos(i, j, this.atPos(i, j));
			}
			copy.setRowHeaderNum(i, this.getRowHeaderNum(i));
			copy.setColHeaderNum(i, this.getColHeaderNum(i));
		}
		return copy;
	}

	/**
	 * Tests for logical equality between two ShinroPuzzles
	 *

	 * This means an equal puzzle must have the same row and column header numbers
	 * as well as the same numbers of arrows and points in the same places
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	@Override
	public boolean equals(Object obj) {
		if (obj == null) return false;
		else if (obj == this) return true;

		if (obj instanceof ShinroPuzzle) {
			ShinroPuzzle p = (ShinroPuzzle)obj;
			//same size?
			if (this.size() != p.size()) return false;
			else {
				for (int i = 0; i < this.size; i++) {
					//same headers?
					if (this.getRowHeaderNum(i) != p.getRowHeaderNum(i)) {
						return false;
					}
					if (this.getColHeaderNum(i) != p.getColHeaderNum(i)) {
						return false;
					}
					for (int j = 0; j < this.size; j++) {
						//same object at (i, j)?
						if (this.atPos(i, j) != p.atPos(i, j)) {
							//has X where space is?
							if ((this.atPos(i, j) == X && p.atPos(i, j) == EMPTY)
									|| (this.atPos(i, j) == EMPTY
											&& p.atPos(i, j) == X)) {
								continue;
							}
							return false;
						}
					}
				}
				return true;
			}
		}
		else return false;
	}

	/**
	 * Fills a ArrayList of spaces with an X
	 *

	 * This method does nothing to ShinroSquares that are not empty.
	 * @see ShinroPuzzle#putX(int, int)
	 * @param spaces  an ArrayList of GridPos to fill with Xs
	 */
	public void fillSpacesWithX(ArrayList<GridPos> spaces) {
		for (int i = 0; i < spaces.size(); i++) {
			this.putX(spaces.get(i));
		}
	}

	/**
	 * GridPos-based convenience method for {@link #getArrowToEdge(int, int)}
	 * @param pos the GridPos of the desired arrow
	 * @return an ArrayList of the GridPos of all elements from a specified arrow
	 * to the edge it points to
	 */
	public ArrayList<GridPos> getArrowToEdge(GridPos pos) {
		return this.getArrowToEdge(pos.getRow(), pos.getCol());
	}

	/**
	 * Gets an ArrayList of GridPos from an arrow to the edge the edge of the
	 * puzzleGrid
	 *

	 * The list includes the arrow.
	 * If the item at the specified location is not an arrow, an empty ArrayList
	 * is returned.
	 * @param row  the row index of the specified arrow
	 * @param col  the column index of the specified arrow
	 * @return an ArrayList of the GridPos of all elements from a specified arrow
	 * to the edge it points to
	 */
	public ArrayList<GridPos> getArrowToEdge(int row, int col) {
		ArrayList<GridPos> result = new ArrayList<GridPos>();
		int myRow = row;
		int myCol = col;

		while ((myRow >= 0 && myRow < this.size)
				&& (myCol >= 0 && myCol < this.size)) {
			result.add(new GridPos(myRow, myCol));

			switch(this.puzzleGrid[row][col]) {
			case n: //pass through
			case N: myRow--;
					break;
			case s: //pass through
			case S: myRow++;
					break;
			case e: //pass through
			case E: myCol++;
					break;
			case w: //pass through
			case W: myCol--;
					break;
			case ne: //pass through
			case NE: myRow--; myCol++;
					break;
			case nw: //pass through
			case NW: myRow--; myCol--;
					break;
			case se: //pass through
			case SE: myRow++; myCol++;
					break;
			case sw: //pass through
			case SW: myRow++; myCol--;
					break;
			default: break;
			}
		}
		return result;
	}

	/**
	 * Gets an ArrayList of all coordinate pairs in a specified column
	 * @param col  the column whose list of spaces is to be returned
	 * @return an ArrayList of GridPos representing the contents of the column
	 */
	public ArrayList<GridPos> getCol(int col) {
		ArrayList<GridPos> result = new ArrayList<GridPos>();
		for (int i = 0; i < this.size; i++) {
			result.add(new GridPos(i, col));
		}
		return result;
	}

	/**
	 * Gets the number of points in the specified column
	 * @param col  the column whose header number is to be returned
	 * @return an integer representing the number of points in the column
	 */
	public int getColHeaderNum(int col) {
		return this.colHeaderNum[col];
	}

	/**
	 * GridPos-based convenience method for {@link #getDiagsFromPoint(int, int)}
	 * @param pos  the GridPos of the desired location
	 * @return an ArrayList of GridPos of spaces to the NW, NE, SW, and SE of the
	 * desired location
	 */
	public ArrayList<GridPos> getDiagsFromPoint(GridPos pos) {
		return this.getDiagsFromPoint(pos.getRow(), pos.getCol());
	}

	/**
	 * Gets an ArrayList of the GridPos of any point diagonally intersecting a
	 * desired location
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @return an ArrayList of GridPos of spaces to the NW, NE, SW, and SE of the
	 * desired location
	 */
	public ArrayList<GridPos> getDiagsFromPoint(int row, int col) {
		ArrayList<GridPos> myList = new ArrayList<GridPos>();
		myList.add(new GridPos(row, col));
		int myRow, myCol, mySize = this.size();
		//NW
		myRow = row - 1;
		myCol = col - 1;
		while (myRow >= 0 && myCol >= 0) {
			myList.add(new GridPos(myRow, myCol));
			myRow--;
			myCol--;
		}
		//NE
		myRow = row - 1;
		myCol = col + 1;
		while (myRow >= 0 && myCol < mySize) {
			myList.add(new GridPos(myRow, myCol));
			myRow--;
			myCol++;
		}
		//SW
		myRow = row + 1;
		myCol = col - 1;
		while (myRow < mySize && myCol >= 0) {
			myList.add(new GridPos(myRow, myCol));
			myRow++;
			myCol--;
		}
		//SE
		myRow = row + 1;
		myCol = col + 1;
		while (myRow < mySize && myCol < mySize) {
			myList.add(new GridPos(myRow, myCol));
			myRow++;
			myCol++;
		}
		return myList;
	}

	/**
	 * Gets a list of all GridPos that contain a specified ItemType
	 * @param type  the type of the spaces to get a list of
	 * @return an ArrayList of GridPos containing every instance of the
	 * desired type in the puzzleGrid.
	 */
	public ArrayList<GridPos> getListByType(int type) {
		ArrayList<GridPos> result = new ArrayList<GridPos>();
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				if ((this.isArrow(type) && this.isArrow(i, j))
						|| this.atPos(i, j) == type) {
					result.add(new GridPos(i, j));
				}
			}
		}
		return result;
	}

	/**
	 * Gets the number of points the puzzle was initialized with.
	 * @return the number of points needed to solve this puzzle
	 */
	public int getNumPoints() {
		return this.numPoints;
	}

	/**
	 * Gets the opposing arrow of its parameter
	 * @param arrow  the arrow value to get the opposite of
	 * @return the opposing arrow value
	 * @throws IllegalArgumentException if not a valid arrow or a "satisfied" arrow
	 */
	public int getOpposingArrow(int arrow) throws IllegalArgumentException {
		if (!this.isArrow(arrow) || arrow < 0) {
			throw new IllegalArgumentException("getOpposingArrow: Invalid arrow");
		}
		if (arrow <= 4) {
			return arrow + 4;
		}
		else {
			return arrow - 4;
		}
	}

	/**
	 * GridPos-based convenience method for {@link #getPointingArrows(int, int)}
	 * @param pos the GridPos of the desired location
	 * @return an ArrayList of the GridPos of any arrow pointing to the location
	 */
	public ArrayList<GridPos> getPointingArrows(GridPos pos) {
		return this.getPointingArrows(pos.getRow(), pos.getCol());
	}

	/**
	 * Gets a list of all arrows which point to a desired location
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @return an ArrayList of the GridPos of any arrow pointing to the location
	 */
	public ArrayList<GridPos> getPointingArrows(int row, int col) {
		ArrayList<GridPos> result = new ArrayList<GridPos>(),
				myList = new ArrayList<GridPos>();

		if (this.atPos(row, col) == POINT) {
			//row
			myList = this.getTypeInList(N, this.getRow(row)); // any arrow
			if (myList.size() > 0) {
				for (GridPos pos : myList) {
					if ((this.atPos(pos) == E || this.atPos(pos) == e) &&
							col > pos.getCol()) {
						result.add(pos);
					}
					else if ((this.atPos(pos) == W || this.atPos(pos) == w) &&
							col < pos.getCol()) {
						result.add(pos);
					}
				}
			}
			//col
			myList = this.getTypeInList(N, this.getCol(col)); // any arrow
			if (myList.size() > 0) {
				for (GridPos pos : myList) {
					if ((this.atPos(pos) == S || this.atPos(pos) == s) &&
							row > pos.getRow()) {
						result.add(pos);
					}
					else if ((this.atPos(pos) == N || this.atPos(pos) == n) &&
							row < pos.getRow()) {
						result.add(pos);
					}
				}
			}
			//diags
			myList = this.getTypeInList(N, //any arrow
					this.getDiagsFromPoint(row, col));
			if (myList.size() > 0) {
				for (GridPos pos : myList) {
					if ((this.atPos(pos) == SE || this.atPos(pos) == se) &&
							row > pos.getRow() &&
							col > pos.getCol()) {
						result.add(pos);
					}
					else if ((this.atPos(pos) == SW || this.atPos(pos) == sw) &&
							row > pos.getRow() &&
							col < pos.getCol()) {
						result.add(pos);
					}
					else if ((this.atPos(pos) == NW || this.atPos(pos) == nw) &&
							row < pos.getRow() &&
							col < pos.getCol()) {
						result.add(pos);
					}
					else if ((this.atPos(pos) == NE || this.atPos(pos) == ne) &&
							row < pos.getRow() &&
							col > pos.getCol()) {
						result.add(pos);
					}
				}
			}
		}

		return result;
	}

	/**
	 * Gets an ArrayList of all coordinate pairs in a desired row
	 * @param row  the row whose list of spaces is to be returned
	 * @return an ArrayList of GridPos representing the contents of the row
	 */
	public ArrayList<GridPos> getRow(int row) {
		ArrayList<GridPos> result = new ArrayList<GridPos>();
		for (int i = 0; i < this.size; i++) {
			result.add(new GridPos(row, i));
		}
		return result;
	}

	/**
	 * Gets the number of points in the specified row
	 * @param row  the row whose header number is to be returned
	 * @return an integer representing the number of points in the row
	 */
	public int getRowHeaderNum(int row) {
		return this.rowHeaderNum[row];
	}

	/**
	 * Gets all the spaces from a given space to the edge of the puzzle along a
	 * given direction
	 * @param row  the row index of the space to start with
	 * @param col  the column index of the space to start with
	 * @param dir  the direction to collect spaces in
	 * @return an ArrayList of GridPos of all the spaces from the starting space to
	 * the edge of the puzzle in the specified direction
	 */
	public ArrayList<GridPos> getSpacesToEdge(int row, int col, int dir) {
		ArrayList<GridPos> result = new ArrayList<GridPos>();
		int mRow = row, mCol = col, mDir = dir;
		if (mDir < 0) {
			mDir *= -1;
		}
		while ((mRow >= 0 && mRow < SIZE) && (mCol >= 0 && mCol < SIZE)) {
			result.add(new GridPos(mRow, mCol));
			switch (mDir) {
			case N: mRow--;
					break;
			case S: mRow++;
					break;
			case E: mCol++;
					break;
			case W: mCol--;
					break;
			case NE: mRow--;
					 mCol++;
					 break;
			case NW: mRow--;
					 mCol--;
					 break;
			case SE: mRow++;
					 mCol++;
					 break;
			case SW: mRow++;
					 mCol--;
					 break;
			}
		}
		return result;
	}

	/** GridPos-based convenience method for {@link #getSpacesToEdge(int, int, int)}
	 * @param pos  the GridPos of the space to start at
	 * @param dir  the direction to collect spaces in
	 * @return an ArrayList of GridPos of all the spaces from the starting space to
	 * the edge of the puzzle in the specified direction
	 */
	public ArrayList<GridPos> getSpacesToEdge(GridPos pos, int dir) {
		return this.getSpacesToEdge(pos.getRow(), pos.getCol(), dir);
	}

	/**
	 * Gets all elements of a specified type in a list of GridPos
	 * @param type  the type of element to get
	 * @param list  the ArrayList to get elements from
	 * @return an ArrayList of GridPos containing all the elements of the desired
	 * type from the original list.
	 */
	public ArrayList<GridPos> getTypeInList(int type, ArrayList<GridPos> list) {
		ArrayList<GridPos> myList = new ArrayList<GridPos>();
		for (GridPos pos : list) {
			if ((this.isArrow(type) && this.isArrow(pos))
					|| this.atPos(pos) == type) {
				myList.add(pos);
			}
		}
		return myList;
	}

	/**
	 * Populates a ShinroPuzzle's spaces based on the content of an integer matrix.
	 *

	 * A point will increment the relevant row and column header numbers as well as
	 * numPoints.
	 * @param intMatrix  a two-dimensional array if ints containing values to
	 * assign to corresponding spaces in the puzzleGrid
	 */
	public void initPuzzle(int[][] intMatrix) {
		for (int i = 0; i < this.size; i++) {
			for (int j = 0; j < this.size; j++) {
				int atPos = intMatrix[i][j];
				this.puzzleGrid[i][j] = atPos;
				if (intMatrix[i][j] == 9) {
					this.numPoints++;
					this.rowHeaderNum[i]++;
					this.colHeaderNum[j]++;
				}
			}
		}
	}

	/**
	 * GridPos-based convenience method for {@link #isArrow(int, int)}
	 * @param pos  the GridPos of the desired location
	 * @return true if the space contains an arrow, false otherwise
	 */
	public boolean isArrow(GridPos pos) {
		return this.isArrow(pos.getRow(), pos.getCol());
	}

	/**
	 * Determined whether or not the specified int value is an arrow
	 * @param arrow  the value of the quantity to check for arrowness
	 * @return true if the value is an arrow, false otherwise
	 */
	public boolean isArrow(int arrow) {
		if ((arrow > 0 && arrow < 9) || (arrow < 0 && arrow > -9)) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Determines whether or not a specified space contains an arrow
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @return true if the space contains an arrow, false otherwise
	 */
	public boolean isArrow(int row, int col) {
		int arrow = this.puzzleGrid[row][col];
		if ((arrow > 0 && arrow < 9) || (arrow < 0 && arrow > -9)) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * GridPos-based convenience method for {@link #isSatisfied(int, int)}
	 * @param pos  the position of the arrow to check for satisfaction
	 * @return true if the arrow is satisfied, false otherwise
	 */
	public boolean isSatisfied(GridPos pos) {
		return this.isSatisfied(pos.getRow(), pos.getCol());
	}

	/**
	 * Checks if an int value represents a satisfied arrow
	 * @param arrow  the value to check for satisfied arrowness
	 * @return true if the value represents a satsified arrow, false otherwise
	 */
	public boolean isSatisfied(int arrow) {
		if (arrow < 0 && arrow > -9) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Checks whether or not an arrow at a given location is satisfied
	 * @param row  the row index of the location to check
	 * @param col  the column index of the location to check
	 * @return true if the arrow is satisfied, false otherwise
	 */
	public boolean isSatisfied(int row, int col) {
		if (this.atPos(row, col) < 0 && this.atPos(row, col) > -9) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * GridPos-based convenience method for {@link #putArrow(int, int, int)}
	 * @param pos the GridPos of the desired location
	 * @param dir the direction value of the new arrow
	 * @throws IllegalArgumentException if dir is not a valid arrow value
	 * @see ShinroPuzzle#isArrow(int)
	 */
	public void putArrow(GridPos pos, int dir)
			throws IllegalArgumentException {
		this.putArrow(pos.getRow(), pos.getCol(), dir);
	}

	/**
	 * Places the desired arrow value into the space at the specified location
	 *

	 * This method will overwrite whatever contents the space may already have.
	 * @param row  the row index of the space in which to place the arrow
	 * @param col  the column index of the space in which to place the arrow
	 * @param dir  the direction value of the new arrow
	 * @throws IllegalArgumentException if dir is not a valid arrow value
	 * @see ShinroPuzzle#isArrow(int)
	 */
	public void putArrow(int row, int col, int dir)
			throws IllegalArgumentException {
		if (!this.isArrow(dir)) {
			throw new IllegalArgumentException("putArrow: dir is not valid "
					+ "arrow value.");
		}
		this.puzzleGrid[row][col] = dir;
	}

	/**
	 * GridPos-based convenience method for {@link #putPoint(int, int)}
	 * @param pos  the GridPos of the desired location
	 */
	public void putPoint(GridPos pos) {
		this.putPoint(pos.getRow(), pos.getCol());
	}

	/**
	 * Places a new point at the specified location
	 *

	 * Placing a point will satisfy any pointing arrows.
	 * This method does nothing if the specified space contains an arrow.
	 * @param row  the row index of the space in which to place the point
	 * @param col  the column index of the space in which to place the point
	 */
	public void putPoint(int row, int col) {
		if (!this.isArrow(row, col)) {
			this.puzzleGrid[row][col] = POINT;
			ArrayList<GridPos> myArrows = this.getPointingArrows(row, col);
			for (GridPos pos: myArrows) {
				this.satsifyArrow(pos);
			}
		}
	}

	/**
	 * GridPos-based convenience method for {@link #putX(int, int)}
	 * @param pos  the GridPos of the desired location
	 */
	public void putX(GridPos pos) {
		this.putX(pos.getRow(), pos.getCol());
	}

	/**
	 * Places a new X at the specified location
	 *

	 * This method does nothing if the specified space contains a arrow or point
	 * @param row  the row index of the space in which to place the X
	 * @param col  the column index of the space in which to place the X
	 */
	public void putX(int row, int col) {
		if (!this.isArrow(row, col) && this.atPos(row, col) != POINT) {
			this.puzzleGrid[row][col] = X;
		}
	}

	/**
	 * Checks to see whether or not the puzzleGrid is full
	 * @return true if the puzzle grid has no more empty spaces
	 */
	public boolean puzzleGridFull() {
		if (this.getListByType(EMPTY).size() == 0) {
			return true;
		}
		else {
			return false;
		}
	}

	/**
	 * Clears all spaces in the puzzleGrid that do not contain an arrow
	 * @see ShinroPuzzle#clearSpace(int, int)
	 */
	public void reset() {
		for (int i = 0; i < this.size; i ++) {
			for (int j = 0; j < this.size; j++) {
				this.clearSpace(i, j);
			}
		}
	}

	/**
	 * GridPos-based convenience method for {@link #satsifyArrow(int, int)}
	 * @param pos  the position of the the arrow to satisfy
	 * @throws IllegalArgumentException if the location is not an arrow
	 */
	public void satsifyArrow(GridPos pos) throws IllegalArgumentException {
		this.satsifyArrow(pos.getRow(), pos.getCol());
	}

	/**
	 * Marks an arrow as satisfied at a desired location
	 *

	 * The value at the location is negated.
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @throws IllegalArgumentException if the location is not an arrow
	 */
	public void satsifyArrow(int row, int col) throws IllegalArgumentException {
		if (!this.isArrow(row, col)) {
			throw new IllegalArgumentException("satisfyArrow: pos specified not "
					+ "an arrow");
		}
		if (!this.isSatisfied(row, col)) {
			this.puzzleGrid[row][col] *= -1;
		}
	}

	/**
	 * Sets the number of points in the specified column
	 * @param col  the column whose header number is to be set
	 * @param value  the value to set the specified column header
	 */
	public void setColHeaderNum(int col, int value) {
		this.colHeaderNum[col] = value;
	}

	/**
	 * Sets the row and column header nums by analyzing the puzzleGrid
	 *

	 * This method is provided for convenience in {@link shinro.ShinroSolver}
	 */
	public void setHeaders() {
		for (int i = 0; i < this.size; i++) {
			this.rowHeaderNum[i] = this.getTypeInList(POINT, this.getRow(i)).size();
			this.colHeaderNum[i] = this.getTypeInList(POINT, this.getCol(i)).size();
		}
	}
	/**
	 * GridPos-based convenience method for {@link #setPos(int, int, int)}
	 * @param pos  the GridPos of the value to set
	 * @param value the value to set at the desired position.
	 * @throws IllegalArgumentException if value is less than zero or greater
	 * than 9
	 */

	public void setPos(GridPos pos, int value) throws IllegalArgumentException{
		this.setPos(pos.getRow(), pos.getCol(), value);
	}

	/**
	 * Directly sets a specified position to a specific value
	 *

	 * This method is provided for convenience in {@link shinro.ShinroSolver}
	 * @param row  the row index of the position to set
	 * @param col  the column index of the position to set
	 * @param value  the desired integer value to set the position to
	 * @throws IllegalArgumentException if value is less than EMPTY(0) or greater
	 * than POINT(9)
	 */
	public void setPos(int row, int col, int value) throws IllegalArgumentException {
		if (value < EMPTY || value > POINT) {
			throw new IllegalArgumentException("setPos: Illegal value --> " + value);
		}
		else {
			this.puzzleGrid[row][col] = value;
		}
	}

	/**
	 * Sets the number of points in the specified row
	 * @param row  the row whose header number is to be set
	 * @param value  the value to set the specified row header
	 */
	public void setRowHeaderNum(int row, int value) {
		this.rowHeaderNum[row] = value;
	}

	/**
	 * Gets the size (side length) of this ShinroPuzzle
	 * @return the size field of this ShinroPuzzle
	 */
	public int size() {
		return this.size;
	}

	/**
	 * Gets the String representation of a specified space's value
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @return  a String representing the value at the specified location
	 */
	public String spaceToString(int row, int col) {
		switch(this.puzzleGrid[row][col]) {
		case 0: return "[  ]";
		case 9: return "[++]";
		case -9: return "[XX]";
		case 1: return "[ N]";
		case 2: return "[NE]";
		case 3: return "[ E]";
		case 4: return "[SE]";
		case 5: return "[ S]";
		case 6: return "[SW]";
		case 7: return "[ W]";
		case 8: return "[NW]";
		case -8: return "[nw]";
		case -7: return "[ w]";
		case -6: return "[sw]";
		case -5: return "[ s]";
		case -4: return "[se]";
		case -3: return "[ e]";
		case -2: return "[ne]";
		case -1: return "[ n]";
		default: return "[  ]";
		}
	}

	/**
	 * Gets the puzzle in the form of a matrix of ints.
	 * @return an int matrix of size SIZE X SIZE with the current values of each
	 * puzzle space.
	 */
	public int[][] toIntMatrix() {
		return this.puzzleGrid;
	}

	/**
	 * Prints a String representation of this ShinroPuzzle.
	 *

	 * The printout includes indices and values of row and column headers.
	 * Spaces are enclosed in square brackets with a two-character representation
	 * of their contents.
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		int positionCount = 0;
		String result = "/  /";
		for (int i : this.colHeaderNum) {
			result += positionCount++ + ":" + i + "/";
		}
		positionCount = 0;
		result += "\n";
		for (int i = 0; i < this.size; i++) {
			result += positionCount++ + ":" + this.rowHeaderNum[i];
			for (int j = 0; j < this.size; j++) {
				result += this.spaceToString(i, j);
			}
			result += "\n";
		}
		return result;
	}

	/**
	 * Removes Xs, it present, from a list of spaces
	 *

	 * This method does nothing to ShinroSquares that do not contain Xs.
	 * @see ShinroPuzzle#clearSpace(int, int)
	 * @param spaces  an ArrayList of GridPos to remove Xs from.
	 */
	public void unfillSpacesWithX(ArrayList<GridPos> spaces) {
		for (int i = 0; i < spaces.size(); i++) {
			if (this.atPos(spaces.get(i)) != POINT) {
				this.clearSpace(spaces.get(i));
			}
		}
	}

	/**
	 * GridPos-based convenience method for {@link #unsatsifyArrow(int, int)}
	 * @param pos  the GridPos of the desired location
	 * @throws IllegalArgumentException if the location does not contain an arrow
	 */
	public void unsatsifyArrow(GridPos pos) throws IllegalArgumentException {
		this.unsatsifyArrow(pos.getRow(), pos.getCol());
	}

	/**
	 * Marks as unsatisfied an arrow at a desired location
	 * @param row  the row index of the desired location
	 * @param col  the column index of the desired location
	 * @throws IllegalArgumentException if the location does not contain an arrow
	 */
	public void unsatsifyArrow(int row, int col) throws IllegalArgumentException {
		if (!this.isArrow(row, col)) {
			throw new IllegalArgumentException("unsatisfyArrow: pos specified not "
					+ "an arrow");
		}
		if (this.isSatisfied(row, col)) {
			this.puzzleGrid[row][col] *= -1;
		}
	}

	/**
	 * Determines whether or not a ShinroPuzzle is in a solved state
	 *

	 * The puzzle is solved if the number of points in each row and column match
	 * the number in the corresponding row or column header AND all arrows are
	 * satisfied. As a consequence, puzzles with multiple solutions will be counted
	 * as solved if the puzzle is in ANY valid solution state.
	 * @return true if the puzzle is in a solved state, false otherwise
	 */
	public boolean verifySolution() {
		if (this.getListByType(POINT).size() < this.getNumPoints()) {
			return false;
		}
		else {
			for (int i = 0; i < this.size(); i++) {
				if (this.getRowHeaderNum(i)
						!= this.getTypeInList(POINT, this.getRow(i)).size()) {
					return false;
				}
				if (this.getColHeaderNum(i)
						!= this.getTypeInList(POINT, this.getCol(i)).size()) {
					return false;
				}
			}
			for (GridPos arrow : this.getListByType(N)) { //all arrows
				if (!this.isSatisfied(arrow)) {
					return false;
				}
			}
			return true;
		}
	}
}


text:
module Typus

  module Authentication

    protected

    # Require login checks if the user is logged on Typus, otherwise
    # is sent to the sign in page with a :back_to param to return where
    # she tried to go.
    def require_login

      # Uncomment the following line for demo purpouses.
      # session[:typus_user_id] = Typus.user_class.find(:first)

      if session[:typus_user_id]
        set_current_user
      else
        back_to = (request.env['REQUEST_URI'] == admin_dashboard_path) ? nil : request.env['REQUEST_URI']
        redirect_to admin_sign_in_path(:back_to => back_to)
      end

    end

    # Return the current user. If role does not longer exist on the
    # system @current_user will be signed out from Typus.
    def set_current_user

      @current_user = Typus.user_class.find(session[:typus_user_id])

      unless Typus::Configuration.roles.has_key?(@current_user.role)
        raise _("Role does no longer exists.")
      end

      unless @current_user.status
        back_to = (request.env['REQUEST_URI'] == admin_dashboard_path) ? nil : request.env['REQUEST_URI']
        raise _("Typus user has been disabled.")
      end

    rescue Exception => error
      flash[:notice] = error.message
      session[:typus_user_id] = nil
      redirect_to admin_sign_in_path(:back_to => back_to)
    end

    # Action is available on: edit, update, toggle and destroy
    def check_if_user_can_perform_action_on_user

      return unless @item.kind_of?(Typus.user_class)

      current_user = (@current_user == @item)

      message = case params[:action]
                when 'edit'

                  # Only admin and owner of Typus User can edit.
                  if @current_user.is_not_root? && !current_user
                    _("As you're not the admin or the owner of this record you cannot edit it.")
                  end

                when 'update'

                  # current_user cannot change her role.
                  if current_user && !(@item.role == params[@object_name][:role])
                    _("You can't change your role.")
                  end

                when 'toggle'

                  # Only admin can toggle typus user status, but not herself.
                  if @current_user.is_root? && current_user
                    _("You can't toggle your status.")
                  elsif @current_user.is_not_root?
                    _("You're not allowed to toggle status.")
                  end

                when 'destroy'

                  # Admin can remove anything except herself.
                  if @current_user.is_root? && current_user
                    _("You can't remove yourself.")
                  elsif @current_user.is_not_root?
                    _("You're not allowed to remove Typus Users.")
                  end

                end

      if message
        flash[:notice] = message
        redirect_to request.referer || admin_dashboard_path
      end

    end

    # This method checks if the user can perform the requested action.
    # It works on models, so its available on the admin_controller.
    def check_if_user_can_perform_action_on_resource

      message = case params[:action]
                when 'index', 'show'
                  "{{current_user_role}} can't display items."
                when 'destroy'
                  "{{current_user_role}} can't delete this item."
                else
                  "{{current_user_role}} can't perform action. ({{action}})"
                end

      message = _(message,
                  :current_user_role => @current_user.role.capitalize,
                  :action => params[:action])

      unless @current_user.can?(params[:action], @resource[:class])
        flash[:notice] = message
        redirect_to request.referer || admin_dashboard_path
      end

    end

    # This method checks if the user can perform the requested action.
    # It works on resources, which are not models, so its available on
    # the typus_controller.
    def check_if_user_can_perform_action_on_resource_without_model
      controller = params[:controller].split('/').last
      action = params[:action]
      unless @current_user.can?(action, controller.camelize, { :special => true })
        flash[:notice] = _("{{current_user_role}} can't go to {{action}} on {{controller}}.",
                           :current_user_role => @current_user.role.capitalize,
                           :action => action,
                           :controller => controller.humanize.downcase)
        redirect_to request.referer || admin_dashboard_path
      end
    end

  end

end


text:
package org.apache.cloudstack.api.command.iam;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import org.apache.cloudstack.iam.IAMApiService;
import org.apache.cloudstack.api.ACL;
import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiCommandJobType;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseAsyncCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.iam.IAMGroupResponse;
import org.apache.cloudstack.api.response.iam.IAMPolicyResponse;
import org.apache.cloudstack.context.CallContext;
import org.apache.cloudstack.iam.api.IAMGroup;

import com.cloud.event.EventTypes;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.user.Account;

@APICommand(name = "attachIAMPolicyToIAMGroup", description = "attach iam policy to an iam group", responseObject = IAMGroupResponse.class)
public class AttachIAMPolicyToIAMGroupCmd extends BaseAsyncCmd {
    public static final Logger s_logger = Logger.getLogger(AttachIAMPolicyToIAMGroupCmd.class.getName());
    private static final String s_name = "attachiampolicytoiamgroupresponse";

    @Inject
    public IAMApiService _iamApiSrv;

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @ACL
    @Parameter(name = ApiConstants.ID, type = CommandType.UUID, entityType = IAMGroupResponse.class,
 required = true, description = "The ID of the iam group")
    private Long id;

    @ACL
    @Parameter(name = ApiConstants.IAM_POLICIES, type = CommandType.LIST, collectionType = CommandType.UUID, entityType = IAMPolicyResponse.class, description = "comma separated list of iam policy id that are going to be applied to the iam group.")
    private List<Long> policyIdList;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getId() {
        return id;
    }

    public List<Long> getPolicyIdList() {
        return policyIdList;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        return Account.ACCOUNT_ID_SYSTEM; // no account info given, parent this command to SYSTEM so ERROR events are tracked
    }

    @Override
    public void execute() throws ResourceUnavailableException,
            InsufficientCapacityException, ServerApiException {
        CallContext.current().setEventDetails("IAM group Id: " + getId());
        IAMGroup result = _iamApiSrv.attachIAMPoliciesToGroup(policyIdList, id);
        if (result != null){
            IAMGroupResponse response = _iamApiSrv.createIAMGroupResponse(result);
            response.setResponseName(getCommandName());
            setResponseObject(response);
        } else {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add roles to iam group");
        }
    }

    @Override
    public String getEventType() {
        return EventTypes.EVENT_IAM_GROUP_UPDATE;
    }

    @Override
    public String getEventDescription() {
        return "adding iam roles to iam group";
    }

    @Override
    public ApiCommandJobType getInstanceType() {
        return ApiCommandJobType.IAMGroup;
    }

}


text:
class CRPCTable;

void RegisterWalletRPCCommands(CRPCTable &tableRPC);

#endif //STARDUST_WALLET_RPCWALLET_H


text:
<?php

namespace Volley\Bundle\FaceBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * Player
 *
 * @ORM\Table()
 * @ORM\Entity
 * @ORM\HasLifecycleCallbacks
 */
class Player
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="first_name", type="string", length=255)
     */
    private $firstName;

    /**
     * @var string
     *
     * @ORM\Column(name="middle_name", type="string", length=255, nullable=true)
     */
    private $middleName;

    /**
     * @var string
     *
     * @ORM\Column(name="last_name", type="string", length=255)
     */
    private $lastName;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="birth_date", type="date", nullable=true)
     */
    private $birthDate;

    /**
     * @var integer
     *
     * @ORM\Column(name="height", type="smallint", nullable=true)
     */
    private $height;

    /**
     * @var integer
     *
     * @ORM\Column(name="weight", type="smallint", nullable=true)
     */
    private $weight;

    /**
     * @var integer
     *
     * @ORM\Column(name="spike", type="smallint", nullable=true)
     */
    private $spike;

    /**
     * @var integer
     *
     * @ORM\Column(name="block", type="smallint", nullable=true)
     */
    private $block;

    /**
     * @var string
     *
     * @ORM\Column(name="nationality", type="string", length=255)
     */
    private $nationality;

    /**
     * @var string
     *
     * @ORM\Column(name="position", type="string", length=255, nullable=true)
     */
    private $position;

    /**
     * @var integer
     *
     * @ORM\Column(name="number", type="integer", nullable=true)
     */
    private $number;

    /**
     * @var string
     *
     * @ORM\Column(name="grade", type="string", length=255, nullable=true)
     */
    private $grade;

    /**
     * @ORM\Column(name="descr", type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\ManyToMany(targetEntity="Team", inversedBy="users")
     * @ORM\JoinTable(name="players_teams")
     **/
//    private $teams;

    /**
     * @ORM\OneToMany(targetEntity="Volley\Bundle\FaceBundle\Entity\Team", mappedBy="playerOne")
     **/
    private $teamsOne;

    /**
     * @ORM\OneToMany(targetEntity="Volley\Bundle\FaceBundle\Entity\Team", mappedBy="playerTwo")
     **/
    private $teamsTwo;

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

    /**
     * @var string
     *
     * @ORM\Column(name="image", type="string", length=255)
     */
    private $image;

    /**
     * @Assert\File(maxSize="6000000")
     */
    private $file;

    /**
     * Get file.
     *
     * @return UploadedFile
     */
    public function getFile()
    {
        return $this->file;
    }

    private $temp;
    private $cache;

    /**
     * Sets file.
     *
     * @param UploadedFile $file
     */
    public function setFile(UploadedFile $file = null)
    {
        $this->file = $file;
        // check if we have an old image path
//        print_r($this->getAbsolutePath());

        if (is_file($this->getAbsolutePath())) {
            // store the old name to delete after the update
            $this->temp = $this->getAbsolutePath();
            print_r("1");
//            print_r("<br>");
//            print_r($this->getAbsolutePath());
//            exit;

            $this->cache = $this->getAbsoluteCachePath();
        } else {
            print_r("2");
            $this->image = 'initial';
        }
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload()
    {
        if (null !== $this->getFile()) {
            $this->image = $this->getFile()->guessExtension();
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload()
    {

        if (null === $this->getFile()) {
            return;
        }

        // check if we have an old image
        if (isset($this->temp)) {
            // delete the old image
            unlink($this->temp);
            unlink($this->cache);
            // clear the temp image path
            $this->temp = null;
            $this->cache = null;
        }

        // you must throw an exception here if the file cannot be moved
        // so that the entity is not persisted to the database
        // which the UploadedFile move() method does
        $this->getFile()->move(
            $this->getUploadRootDir(),
            $this->id . '.' . $this->getFile()->guessExtension()
        );

        $this->setFile(null);
    }

    /**
     * @ORM\PreRemove()
     */
    public function storeFilenameForRemove()
    {
        $this->temp = $this->getAbsolutePath();
    }

    /**
     * @ORM\PostRemove()
     */
    public function removeUpload()
    {
        if (isset($this->temp)) {
            unlink($this->temp);
        }
    }

    public function getAbsolutePath()
    {
        return null === $this->image
            ? null
            : $this->getUploadRootDir() . '/' . $this->id . '.' . $this->image;
    }

    public function getAbsoluteCachePath()
    {
        return null === $this->image
            ? null
            : $this->getCacheUploadRootDir() . '/' . $this->id . '.' . $this->image;
    }

    public function getWebPath()
    {
        return null === $this->image
            ? null
            : $this->getUploadDir() . '/' . $this->id .".". $this->image;
    }

    public function getUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__ . '/../../../../../web/' . $this->getUploadDir();
    }

    public function getCacheUploadRootDir()
    {
        // the absolute directory path where uploaded
        // documents should be saved
        return __DIR__ . '/../../../../../web/' . $this->getUploadCacheDir();
    }

    public function getUploadDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return '/uploads/players';
    }

    public function getUploadCacheDir()
    {
        // get rid of the __DIR__ so it doesn't screw up
        // when displaying uploaded doc/image in the view.
        return 'media\cache\events_logo\uploads\players';
    }

    public function __construct() {
        $this->teams = new ArrayCollection();
    }

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set firstName
     *
     * @param string $firstName
     * @return Player
     */
    public function setFirstName($firstName)
    {
        $this->firstName = $firstName;

        return $this;
    }

    /**
     * Get firstName
     *
     * @return string
     */
    public function getFirstName()
    {
        return $this->firstName;
    }

    /**
     * Set middleName
     *
     * @param string $middleName
     * @return Player
     */
    public function setMiddleName($middleName)
    {
        $this->middleName = $middleName;

        return $this;
    }

    /**
     * Get middleName
     *
     * @return string
     */
    public function getMiddleName()
    {
        return $this->middleName;
    }

    /**
     * Set lastName
     *
     * @param string $lastName
     * @return Player
     */
    public function setLastName($lastName)
    {
        $this->lastName = $lastName;

        return $this;
    }

    /**
     * Get lastName
     *
     * @return string
     */
    public function getLastName()
    {
        return $this->lastName;
    }

    /**
     * Set birthDate
     *
     * @param \DateTime $birthDate
     * @return Player
     */
    public function setBirthDate($birthDate)
    {
        $this->birthDate = $birthDate;

        return $this;
    }

    /**
     * Get birthDate
     *
     * @return \DateTime
     */
    public function getBirthDate()
    {
        return $this->birthDate;
    }

    /**
     * Set height
     *
     * @param integer $height
     * @return Player
     */
    public function setHeight($height)
    {
        $this->height = $height;

        return $this;
    }

    /**
     * Get height
     *
     * @return integer
     */
    public function getHeight()
    {
        return $this->height;
    }

    /**
     * Set weight
     *
     * @param integer $weight
     * @return Player
     */
    public function setWeight($weight)
    {
        $this->weight = $weight;

        return $this;
    }

    /**
     * Get weight
     *
     * @return integer
     */
    public function getWeight()
    {
        return $this->weight;
    }

    /**
     * Set spike
     *
     * @param integer $spike
     * @return Player
     */
    public function setSpike($spike)
    {
        $this->spike = $spike;

        return $this;
    }

    /**
     * Get spike
     *
     * @return integer
     */
    public function getSpike()
    {
        return $this->spike;
    }

    /**
     * Set block
     *
     * @param integer $block
     * @return Player
     */
    public function setBlock($block)
    {
        $this->block = $block;

        return $this;
    }

    /**
     * Get block
     *
     * @return integer
     */
    public function getBlock()
    {
        return $this->block;
    }

    /**
     * Set nationality
     *
     * @param string $nationality
     * @return Player
     */
    public function setNationality($nationality)
    {
        $this->nationality = $nationality;

        return $this;
    }

    /**
     * Get nationality
     *
     * @return string
     */
    public function getNationality()
    {
        return $this->nationality;
    }

    /**
     * Set position
     *
     * @param string $position
     * @return Player
     */
    public function setPosition($position)
    {
        $this->position = $position;

        return $this;
    }

    /**
     * Get position
     *
     * @return string
     */
    public function getPosition()
    {
        return $this->position;
    }

    /**
     * Set number
     *
     * @param integer $number
     * @return Player
     */
    public function setNumber($number)
    {
        $this->number = $number;

        return $this;
    }

    /**
     * Get number
     *
     * @return integer
     */
    public function getNumber()
    {
        return $this->number;
    }

    /**
     * Set grade
     *
     * @param string $grade
     * @return Player
     */
    public function setGrade($grade)
    {
        $this->grade = $grade;

        return $this;
    }

    /**
     * Get grade
     *
     * @return string
     */
    public function getGrade()
    {
        return $this->grade;
    }

    /**
     * Add teams
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teams
     * @return Player
     */
    public function addTeam(\Volley\Bundle\FaceBundle\Entity\Team $teams)
    {
        $this->teams[] = $teams;

        return $this;
    }

    /**
     * Remove teams
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teams
     */
    public function removeTeam(\Volley\Bundle\FaceBundle\Entity\Team $teams)
    {
        $this->teams->removeElement($teams);
    }

    /**
     * Get teams
     *
     * @return \Doctrine\Common\Collections\Collection
     */
    public function getTeams()
    {
        return $this->teams;
    }

    function __toString()
    {
        return $this->getFirstName()." ".$this->getLastName();
    }

    /**
     * Set path
     *
     * @param string $path
     * @return Player
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Player
     */
    public function setImage($image)
    {
        $this->image = $image;

        return $this;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set teamsOne
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsOne
     * @return Player
     */
    public function setTeamsOne(\Volley\Bundle\FaceBundle\Entity\Team $teamsOne = null)
    {
        $this->teamsOne = $teamsOne;

        return $this;
    }

    /**
     * Get teamsOne
     *
     * @return \Volley\Bundle\FaceBundle\Entity\Team
     */
    public function getTeamsOne()
    {
        return $this->teamsOne;
    }

    /**
     * Set teamsTwo
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsTwo
     * @return Player
     */
    public function setTeamsTwo(\Volley\Bundle\FaceBundle\Entity\Team $teamsTwo = null)
    {
        $this->teamsTwo = $teamsTwo;

        return $this;
    }

    /**
     * Get teamsTwo
     *
     * @return \Volley\Bundle\FaceBundle\Entity\Team
     */
    public function getTeamsTwo()
    {
        return $this->teamsTwo;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Player
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Add teamsOne
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsOne
     * @return Player
     */
    public function addTeamsOne(\Volley\Bundle\FaceBundle\Entity\Team $teamsOne)
    {
        $this->teamsOne[] = $teamsOne;

        return $this;
    }

    /**
     * Remove teamsOne
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsOne
     */
    public function removeTeamsOne(\Volley\Bundle\FaceBundle\Entity\Team $teamsOne)
    {
        $this->teamsOne->removeElement($teamsOne);
    }

    /**
     * Add teamsTwo
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsTwo
     * @return Player
     */
    public function addTeamsTwo(\Volley\Bundle\FaceBundle\Entity\Team $teamsTwo)
    {
        $this->teamsTwo[] = $teamsTwo;

        return $this;
    }

    /**
     * Remove teamsTwo
     *
     * @param \Volley\Bundle\FaceBundle\Entity\Team $teamsTwo
     */
    public function removeTeamsTwo(\Volley\Bundle\FaceBundle\Entity\Team $teamsTwo)
    {
        $this->teamsTwo->removeElement($teamsTwo);
    }
}


text:
/**
 * A simple molfile reader adapted from TwirlyMol (http://github.com/baoilleach/twirlymol)
 * by Noel O'Boyle, licensed under the MIT License.
 *
 * @constructor
 */
m3d.MolfileReader = function() {

};

/**
 * @param {string} molfile
 * @return {Object}
 */
m3d.MolfileReader.prototype.read = function(molfile) {
  var lines = molfile.split("\n");
  var atomCount = parseFloat(lines[3].substring(0, 3));
  var atoms = [];

  for (var i = 0; i < atomCount; i++) {
    atoms.push({
      x: parseFloat(lines[i + 4].substring(0, 10)),
      y: parseFloat(lines[i + 4].substring(10, 20)),
      z: parseFloat(lines[i + 4].substring(20, 30))
    });
  }

  return { atoms: atoms };
};