text:
package org.locationtech.geomesa.accumulo.data

import org.geotools.data._
import org.geotools.util.factory.Hints
import org.geotools.filter.text.ecql.ECQL
import org.junit.runner.RunWith
import org.locationtech.geomesa.accumulo.TestWithDataStore
import org.locationtech.geomesa.features.ScalaSimpleFeature
import org.locationtech.geomesa.index.conf.QueryHints
import org.locationtech.geomesa.index.conf.partition.TimePartition
import org.locationtech.geomesa.index.index.attribute.AttributeIndex
import org.locationtech.geomesa.index.index.id.IdIndex
import org.locationtech.geomesa.index.index.z2.Z2Index
import org.locationtech.geomesa.index.index.z3.Z3Index
import org.locationtech.geomesa.index.utils.ExplainPrintln
import org.locationtech.geomesa.utils.collection.SelfClosingIterator
import org.locationtech.geomesa.utils.geotools.SimpleFeatureTypes.Configs
import org.opengis.feature.simple.SimpleFeature
import org.specs2.mutable.Specification
import org.specs2.runner.JUnitRunner

import scala.collection.JavaConversions._

@RunWith(classOf[JUnitRunner])
class AccumuloPartitioningTest extends Specification with TestWithDataStore {

  // note: using `Seq.foreach; ok` instead of `foreach(Seq)` shaves several seconds off the time to run this test

  sequential

  override val spec: String =
    s"name:String:index=true,attr:String,dtg:Date,*geom:Point:srid=4326;${Configs.TablePartitioning}=${TimePartition.Name}"

  val features = (0 until 10).map { i =>
    val sf = new ScalaSimpleFeature(sft, i.toString)
    sf.getUserData.put(Hints.USE_PROVIDED_FID, java.lang.Boolean.TRUE)
    sf.setAttribute(0, s"name$i")
    sf.setAttribute(1, s"name$i")
    sf.setAttribute(2, f"2018-01-${i + 1}%02dT00:00:01.000Z")
    sf.setAttribute(3, s"POINT(4$i 5$i)")
    sf
  }

  "AccumuloDataStore" should {
    "partition tables based on feature date" in {
      ds.getAllIndexTableNames(sftName) must beEmpty
      addFeatures(features)

      val indices = ds.manager.indices(sft)
      indices.map(_.name) must containTheSameElementsAs(Seq(Z3Index.name, Z2Index.name, IdIndex.name, AttributeIndex.name))
      foreach(indices)(_.getTableNames(None) must haveLength(2))

      val transformsList = Seq(null, Array("geom"), Array("geom", "dtg"), Array("name"), Array("dtg", "geom", "attr", "name"))

      transformsList.foreach { transforms =>
        testQuery("IN('0', '2')", transforms, Seq(features(0), features(2)))
        testQuery("bbox(geom,38,48,52,62) and dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z", transforms, features.dropRight(2))
        testQuery("bbox(geom,42,48,52,62) and dtg DURING 2017-12-15T00:00:00.000Z/2018-01-15T00:00:00.000Z", transforms, features.drop(2))
        testQuery("bbox(geom,42,48,52,62)", transforms, features.drop(2))
        testQuery("dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z", transforms, features.dropRight(2))
        testQuery("attr = 'name5' and bbox(geom,38,48,52,62) and dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z", transforms, Seq(features(5)))
        testQuery("name < 'name5'", transforms, features.take(5))
        testQuery("name = 'name5'", transforms, Seq(features(5)))
      }

      ds.getFeatureSource(sftName).removeFeatures(ECQL.toFilter("INCLUDE"))

      foreach(indices)(_.getTableNames(None) must beEmpty)

      Seq("INCLUDE",
        "IN('0', '2')",
        "bbox(geom,42,48,52,62)",
        "bbox(geom,38,48,52,62) and dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z",
        "bbox(geom,42,48,52,62) and dtg DURING 2017-12-15T00:00:00.000Z/2018-01-15T00:00:00.000Z",
        "dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z",
        "attr = 'name5' and bbox(geom,38,48,52,62) and dtg DURING 2018-01-01T00:00:00.000Z/2018-01-08T12:00:00.000Z",
        "name < 'name5'",
        "name = 'name5'").foreach { filter =>
        val fr = ds.getFeatureReader(new Query(sftName, ECQL.toFilter(filter)), Transaction.AUTO_COMMIT)
        SelfClosingIterator(fr).toList must beEmpty
      }
      ok
    }
  }

  def testQuery(filter: String, transforms: Array[String], results: Seq[SimpleFeature]): Unit = {
    val query = new Query(sftName, ECQL.toFilter(filter), transforms)
    val fr = ds.getFeatureReader(query, Transaction.AUTO_COMMIT)
    val features = SelfClosingIterator(fr).toList
    if (features.length != results.length) {
      ds.getQueryPlan(query, explainer = new ExplainPrintln)
    }
    val attributes = Option(transforms).getOrElse(ds.getSchema(sftName).getAttributeDescriptors.map(_.getLocalName).toArray)
    features.map(_.getID) must containTheSameElementsAs(results.map(_.getID))
    forall(features) { feature =>
      feature.getAttributes must haveLength(attributes.length)
      forall(attributes.zipWithIndex) { case (attribute, i) =>
        feature.getAttribute(attribute) mustEqual feature.getAttribute(i)
        feature.getAttribute(attribute) mustEqual results.find(_.getID == feature.getID).get.getAttribute(attribute)
      }
    }
    query.getHints.put(QueryHints.EXACT_COUNT, java.lang.Boolean.TRUE)
    ds.getFeatureSource(sftName).getFeatures(query).size() mustEqual results.length
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mbean PUBLIC
   "-//JBoss//DTD JBOSS XMBEAN 1.1//EN"
   "http://www.jboss.org/j2ee/dtd/jboss_xmbean_1_1.dtd">

<mbean>
   <description>DICOM Modality Performed Procedure Step SCP</description>

   <descriptors>
      <persistence persistPolicy="OnUpdate" />
      <persistence-manager value="org.jboss.mx.persistence.DelegatingPersistenceManager" />
   </descriptors>

   <class>org.dcm4chex.archive.dcm.mwlscp.MWLScpService</class>

   <constructor>
      <description>The default constructor</description>
      <name>MWLScpService</name>
   </constructor>

   <!-- Attributes -->
   <attribute access="read-write"
      getMethod="getCalledAETs"
      setMethod="setCalledAETs">
      <description>Accepted Called AET(s). Separate multiple values by '\'(backslash).
      </description>
      <name>CalledAETs</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="MWL_SCP" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getCallingAETs"
      setMethod="setCallingAETs">
      <description>Accepted Calling AETs.
      "ANY" = accept any. Separate multiple values by '\'(backslash).
      </description>
      <name>CallingAETs</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="ANY" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="isAcceptExplicitVRLE"
      setMethod="setAcceptExplicitVRLE">
      <description>Accept DICOM objects encoded in Explicit Value Representation Little Endian Transfer Syntax.
      </description>
      <name>AcceptExplicitVRLE</name>
      <type>boolean</type>
      <descriptors>
         <value value="true" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getEjbProviderURL"
      setMethod="setEjbProviderURL">
      <description>Identifies JNDI (e.g: jnp://hostname:1099) with EJBs.
      "LOCAL", if EJBs are deployed in same JBoss instance.
      </description>
      <name>EjbProviderURL</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="LOCAL" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getDataSourceJndiName"
      setMethod="setDataSourceJndiName">
      <description>Used internally - do NOT modify.
      </description>
      <name>DataSourceJndiName</name>
      <type>java.lang.String</type>
      <descriptors>
         <value value="java:/DefaultDS" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getDcmServerName"
      setMethod="setDcmServerName">
      <description>Used internally - do NOT modify.
      </description>
      <name>DcmServerName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="dcm4chex:service=DcmServer" />
      </descriptors>
   </attribute>
   <attribute access="read-write"
      getMethod="getMppsScpServiceName"
      setMethod="setMppsScpServiceName">
      <description>Used internally - do NOT modify.
      </description>
      <name>MppsScpServiceName</name>
      <type>javax.management.ObjectName</type>
      <descriptors>
         <value value="dcm4chex:service=MPPSScp" />
      </descriptors>
   </attribute>
   &defaultAttributes;

   <!-- Operations -->
   &defaultOperations;
</mbean>

redpajama_set_name: RedPajamaGithub


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of index
 *
 * @author EL HAZARD
 */
class index extends CI_Controller{
    //put your code here
    public function __construct() {
        parent::__construct();
    }
    function index(){
        $data['nama'] = 'jamal dan ahmad ';
        $data['namanya'] = array('saya','kamu');
        $this->load->view('tampil1',$data);
    }
    function panggil($id){
        echo 'hai '.$id;
    }
}


text:
package com.justwayward.reader.bean;

import com.justwayward.reader.bean.base.Base;

import java.util.List;

/**
 * @author yuyh.
 * @date 2016/8/4.
 */
public class SearchDetail extends Base {

    /**
     * _id : 55e2850dbda85d9f74e6f73b
     * hasCp : false
     * title : w
     * cat : 奇幻
     * author : w
     * site : faloo
     * cover : /agent/http://img.faloo.com/Novel/166x235/0/71/000071091.jpg
     * shortIntro : 最终之海的传说,可怕的烧烧能力,危险的黑暗能力,还有恐怖的冰冰能力。  看小Down怎样找到去另一个世界的大门。本书绝对会全本,更新时间固定每周六晚 绝对大更。...
     * lastChapter : 抢劫海贼
     * retentionRatio : null
     * latelyFollower : 4
     * wordCount : 5075
     */

    public List<SearchBooks> books;

    public static class SearchBooks {
        public String _id;
        public boolean hasCp;
        public String title;
        public String cat;
        public String author;
        public String site;
        public String cover;
        public String shortIntro;
        public String lastChapter;
        public String retentionRatio;
        public int latelyFollower;
        public int wordCount;

        public SearchBooks(String _id, String title, String author, String cover, String retentionRatio, int latelyFollower) {
            this._id = _id;
            this.title = title;
            this.author = author;
            this.cover = cover;
            this.retentionRatio = retentionRatio;
            this.latelyFollower = latelyFollower;
        }

        public SearchBooks() {
        }
    }
}


text:
using UnityEngine;
using System.Collections;

public class TankMovement : BaseMovement {

    Rigidbody2D rb;

	// Use this for initialization
	void Start () {
        rb = GetComponent<Rigidbody2D>();
	}

	// Update is called once per frame
	void Update () {

        //float horizontal = Input.GetAxisRaw("Horizontal");

        //float horizontalMovement = horizontal;

        //float vertical = Input.GetAxisRaw("Vertical");

        //float verticalMovement = vertical;

        //movementDirection = new Vector2(horizontalMovement, verticalMovement);

        //Vector2 position = transform.position;

        //position.x += horizontalMovement;
        //position.y += verticalMovement;

        //transform.position = position;
	}

    public override void Move()
    {
        Vector2 velocity = transform.right * speed * movementDirection.y;
        rb.velocity = velocity;
    }

    void FixedUpdate()
    {
        if (moveDuringUpdate)
        {
            Move();
        }

        //Vector2 velocity = movementDirection * speed;
        //rb.velocity = velocity;

        //rb.AddRelativeForce(velocity);

        //if (rb.velocity.sqrMagnitude > maxSpeed * maxSpeed)
        //{
        //    rb.velocity = rb.velocity.normalized * maxSpeed;
        //}

    }
}


text:
// GalleryActivity.java
// twixelated image gallery
// TwixelCam - Copyright © 2016 Brigham Toskin

package com.ionoclast.twixelcam.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.MainThread;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

import com.ionoclast.twixelcam.camera.CameraTwixelator;
import com.ionoclast.twixelcam.R;

import java.io.File;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author btoskin <brigham@ionoclast.com> Ionoclast Laboratories, LLC.
 */
public class GalleryActivity extends Activity
{
	private static final String TAG = GalleryActivity.class.getSimpleName();

	private static final String KEY_SELECTED_PAGE = "selected_page";

	private ViewPager mPagerTwixelated;
	private File[] mFiles;
	private Bitmap[] mImages;

	private ThreadPoolExecutor mExecutor;

	private boolean mStopping = false;
	private int mSelected = -1;

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gallery);

		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		mPagerTwixelated = (ViewPager) findViewById(R.id.pager_gallery);
	}

	@Override
	protected void onRestoreInstanceState(Bundle savedInstanceState)
	{
		super.onRestoreInstanceState(savedInstanceState);

		mSelected = savedInstanceState.getInt(KEY_SELECTED_PAGE, 0);
		mPagerTwixelated.setCurrentItem(mSelected);
	}

	@Override
	protected void onSaveInstanceState(Bundle pOutState)
	{
		super.onSaveInstanceState(pOutState);

		mSelected = mPagerTwixelated.getCurrentItem();
		pOutState.putInt(KEY_SELECTED_PAGE, mSelected);
	}

	@Override
	public void onStart()
	{
		super.onStart();

		mFiles = list_files();
		mImages = new Bitmap[mFiles.length];
		mExecutor = new ThreadPoolExecutor(1, 4, 1000, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(4));
		mExecutor.execute(new LoadBitmapsTask(0, 4));

		mPagerTwixelated.setAdapter(new TwixelatedPageAdapter());
		if(mSelected > -1)
		{
			mPagerTwixelated.setCurrentItem(mSelected);
		}
	}

	@Override
	protected void onStop()
	{
		mStopping = true;

		mExecutor.shutdownNow();
		mExecutor = null;

		mPagerTwixelated.setAdapter(null);

		mFiles = null;
		for(int i = 0; i < mImages.length; ++i)
		{
			if(mImages[i] != null)
			{
				mImages[i].recycle();
			}
		}
		mImages = null;

		mStopping = false;

		super.onStop();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu pMenu)
	{
		getMenuInflater().inflate(R.menu.menu_gallery, pMenu);
		return super.onCreateOptionsMenu(pMenu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem pItem)
	{
		switch(pItem.getItemId())
		{
			case android.R.id.home:
				finish();
				return true;
			case R.id.menu_share:
				launch_share();
				return true;
		}
		return super.onOptionsItemSelected(pItem);
	}

	private File[] list_files()
	{
		File[] tFiles = CameraTwixelator.TWIXEL_DIR.listFiles();
		Arrays.sort(tFiles, new Comparator<File>()
		{
			@Override
			public int compare(File pLhs, File pRhs)
			{
				// sort newest first
				return Long.valueOf(pRhs.lastModified()).compareTo(pLhs.lastModified());
			}
		});
		return tFiles;
	}

	private void launch_share()
	{
		int tIndex = mPagerTwixelated.getCurrentItem();
		Uri tContentUri = CameraTwixelator.GetContentUri(this, mFiles[tIndex]);

		Intent tShareIntent = new Intent(Intent.ACTION_SEND);
		tShareIntent.putExtra(Intent.EXTRA_STREAM, tContentUri);
		tShareIntent.setType(MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(mFiles[tIndex].toString())));
		startActivity(Intent.createChooser(tShareIntent, "Share"));
	}

	private class LoadBitmapsTask implements Runnable
	{
		private int mStartIndex, mCount;

		public LoadBitmapsTask(int pStart, int pCount)
		{
			mStartIndex = pStart;
			mCount = pCount;
		}

		@Override
		public void run()
		{
			for(int i = mStartIndex; i < mStartIndex + mCount; ++i)
			{
				if(Thread.interrupted())
				{
					return;
				}

				synchronized(mImages)
				{
					if(mImages[i] == null)
					{
						String tFile = mFiles[i].toString();
						mImages[i] = BitmapFactory.decodeFile(tFile);
					}
				}
			}
		}
	}

	private class TwixelatedPageAdapter extends PagerAdapter
	{
		private Queue<ImageView> mRecycledViews = new ArrayDeque<ImageView>(4);

		@Override
		public int getCount()
		{
			return mImages.length;
		}

		@Override
		public Object instantiateItem(ViewGroup pParent, int pPosition)
		{
			ImageView tImageView = get_view();
			tImageView.setScaleType(ImageView.ScaleType.FIT_CENTER);

			synchronized(mImages)
			{
				if(mImages[pPosition] == null)
				{
					// load this one on demand, and queue up the next few on a thread
					mImages[pPosition] = BitmapFactory.decodeFile(mFiles[pPosition].toString());
					int tNumToLoad = Math.min(mFiles.length - pPosition - 1, 4);
					if(tNumToLoad > 0)
					{
						mExecutor.execute(new LoadBitmapsTask(pPosition + 1, tNumToLoad));
					}
				}
			}
			tImageView.setImageBitmap(mImages[pPosition]);
			pParent.requestLayout();

			pParent.addView(tImageView);
			return tImageView;
		}

		@Override
		public boolean isViewFromObject(View pView, Object pObject)
		{
			return pView == pObject;
		}

		@Override
		public void destroyItem(ViewGroup pParent, final int pPosition, final Object pObject)
		{
			if(mStopping)
			{
				return;
			}

			// clean up bitmap
			synchronized(mImages)
			{
				final Bitmap tBmp = mImages[pPosition];
				if(tBmp != null)
				{
					mImages[pPosition] = null;
					mExecutor.execute(new Runnable()
					{
						@Override
						public void run()
						{
							tBmp.recycle();
						}
					});
				}
			}

			// clear the image view
			Log.d(TAG, "Recycling view, " + (mRecycledViews.size() + 1) + " in queue");
			ImageView tImg = (ImageView)pObject;
			tImg.setImageDrawable(null);
			pParent.removeView(tImg);
			mRecycledViews.add(tImg);
		}

		@MainThread
		private ImageView get_view()
		{
			if(mRecycledViews.size() > 0)
			{
				Log.d(TAG, "Getting recycled view, " + (mRecycledViews.size() - 1) + " left in queue");
				return mRecycledViews.remove();
			}
			Log.d(TAG, "Getting new view instance.");
			return new ImageView(GalleryActivity.this);
		}
	}
}


text:
<?php

namespace Blogger\BlogBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints\NotBlank;

/**
 * @ORM\Entity(repositoryClass="Blogger\BlogBundle\Entity\Repository\CommentRepository")
 * @ORM\Table(name="comment")
 * @ORM\HasLifecycleCallbacks
 *
 * @author pkovalchuk
 */
class Comment {

    /**
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string")
     */
    protected $user;

    /**
     * @ORM\Column(type="text")
     */
    protected $comment;

    /**
     *
     * @ORM\Column(type="boolean")
     */
    protected $approved;

    /**
     *
     * @ORM\ManyToOne(targetEntity="Blog", inversedBy="comments")
     * @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
     */
    protected $blog;

    /**
     *
     * @ORM\Column(type="datetime")
     */
    protected $created;

    /**
     *
     * @ORM\Column(type="datetime")
     */
    protected $updated;

    public function __construct() {

        $this->setCreated(new \DateTime());
        $this->setUpdated(new \DateTime());

        $this->setApproved(true);

    }

    function __toString() {
//        return strval($this->getComment());
        return $this->getComment() ?: '';
    }

    /**
     * @ORM\preUpdate
     */
    public function setUpdatedValue(){

        $this->setUpdated(new \DateTime);

    }

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

    /**
     * Set user
     *
     * @param string $user
     *
     * @return Comment
     */
    public function setUser($user)
    {
        $this->user = $user;

        return $this;
    }

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

    /**
     * Set comment
     *
     * @param string $comment
     *
     * @return Comment
     */
    public function setComment($comment)
    {
        $this->comment = $comment;

        return $this;
    }

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

    /**
     * Set approved
     *
     * @param boolean $approved
     *
     * @return Comment
     */
    public function setApproved($approved)
    {
        $this->approved = $approved;

        return $this;
    }

    /**
     * Get approved
     *
     * @return boolean
     */
    public function getApproved()
    {
        return $this->approved;
    }

    /**
     * Set created
     *
     * @param \DateTime $created
     *
     * @return Comment
     */
    public function setCreated($created)
    {
        $this->created = $created;

        return $this;
    }

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

    /**
     * Set updated
     *
     * @param \DateTime $updated
     *
     * @return Comment
     */
    public function setUpdated($updated)
    {
        $this->updated = $updated;

        return $this;
    }

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

    /**
     * Set blog
     *
     * @param \Blogger\BlogBundle\Entity\Blog $blog
     *
     * @return Comment
     */
    public function setBlog(\Blogger\BlogBundle\Entity\Blog $blog = null)
    {
        $this->blog = $blog;

        return $this;
    }

    /**
     * Get blog
     *
     * @return \Blogger\BlogBundle\Entity\Blog
     */
    public function getBlog()
    {
        return $this->blog;
    }

    public static function loadValidatorMetadata(ClassMetadata $metadata){

        $metadata->addPropertyConstraint('user', new NotBlank( array(
            'message' => 'You must enter your name'
        ) ));

        $metadata->addPropertyConstraint('comment', new NotBlank( array(
            'message' => 'You must enter a comment'
        ) ));

    }
}


text:
"""The TAR file entry implementation."""

from dfvfs.lib import definitions
from dfvfs.lib import errors
from dfvfs.lib import py2to3
from dfvfs.path import tar_path_spec
from dfvfs.vfs import file_entry
from dfvfs.vfs import vfs_stat

class TARDirectory(file_entry.Directory):
  """Class that implements a directory using tarfile."""

  def _EntriesGenerator(self):
    """Retrieves directory entries.

    Since a directory can contain a vast number of entries using
    a generator is more memory efficient.

    Yields:
      TARPathSpec: TAR path specification.
    """
    location = getattr(self.path_spec, u'location', None)

    if (location is None or
        not location.startswith(self._file_system.PATH_SEPARATOR)):
      return

    # The TAR info name does not have the leading path separator as
    # the location string does.
    tar_path = location[1:]

    # Set of top level sub directories that have been yielded.
    processed_directories = set()

    tar_file = self._file_system.GetTARFile()
    for tar_info in iter(tar_file.getmembers()):
      path = tar_info.name

      # Determine if the start of the TAR info name is similar to
      # the location string. If not the file TAR info refers to is not in
      # the same directory.
      if not path or not path.startswith(tar_path):
        continue

      # Ignore the directory itself.
      if path == tar_path:
        continue

      path_segment, suffix = self._file_system.GetPathSegmentAndSuffix(
          tar_path, path)
      if not path_segment:
        continue

      # Sometimes the TAR file lacks directories, therefore we will
      # provide virtual ones.
      if suffix:
        path_spec_location = self._file_system.JoinPath([
            location, path_segment])
        is_directory = True

      else:
        path_spec_location = self._file_system.JoinPath([path])
        is_directory = tar_info.isdir()

      if is_directory:
        if path_spec_location in processed_directories:
          continue
        processed_directories.add(path_spec_location)

      yield tar_path_spec.TARPathSpec(
          location=path_spec_location, parent=self.path_spec.parent)

class TARFileEntry(file_entry.FileEntry):
  """Class that implements a file entry using tarfile."""

  TYPE_INDICATOR = definitions.TYPE_INDICATOR_TAR

  def __init__(
      self, resolver_context, file_system, path_spec, is_root=False,
      is_virtual=False, tar_info=None):
    """Initializes the file entry.

    Args:
      resolver_context (Context): resolver context.
      file_system (FileSystem): file system.
      path_spec (PathSpec): path specification.
      is_root (Optional[bool]): True if the file entry is the root file entry
          of the corresponding file system.
      is_virtual (Optional[bool]): True if the file entry is a virtual file
          entry emulated by the corresponding file system.
      tar_info (Optional[tarfile.TARInfo]): TAR info.
    """
    super(TARFileEntry, self).__init__(
        resolver_context, file_system, path_spec, is_root=is_root,
        is_virtual=is_virtual)
    self._tar_info = tar_info

  def _GetDirectory(self):
    """Retrieves a directory.

    Returns:
      TARDirectory: directory or None.
    """
    if self._stat_object is None:
      self._stat_object = self._GetStat()

    if (self._stat_object and
        self._stat_object.type == self._stat_object.TYPE_DIRECTORY):
      return TARDirectory(self._file_system, self.path_spec)
    return

  def _GetLink(self):
    """Retrieves the link.

    Returns:
      str: link.

    Raises:
      BackEndError: when the TAR info is missing in a non-virtual file entry.
    """
    if self._link is None:
      tar_info = self.GetTARInfo()
      if not self._is_virtual and not tar_info:
        raise errors.BackEndError(
            u'Missing TAR info in non-virtual file entry.')

      if tar_info:
        self._link = tar_info.linkname

    return self._link

  def _GetStat(self):
    """Retrieves the stat object.

    Returns:
      VFSStat: stat object.

    Raises:
      BackEndError: when the TAR info is missing in a non-virtual file entry.
    """
    tar_info = self.GetTARInfo()
    if not self._is_virtual and tar_info is None:
      raise errors.BackEndError(u'Missing TAR info in non-virtual file entry.')

    stat_object = vfs_stat.VFSStat()

    # File data stat information.
    stat_object.size = getattr(tar_info, u'size', None)

    # Date and time stat information.
    stat_object.mtime = getattr(tar_info, u'mtime', None)

    # Ownership and permissions stat information.
    stat_object.mode = getattr(tar_info, u'mode', None)
    stat_object.uid = getattr(tar_info, u'uid', None)
    stat_object.gid = getattr(tar_info, u'gid', None)

    # TODO: implement support for:
    # stat_object.uname = getattr(tar_info, u'uname', None)
    # stat_object.gname = getattr(tar_info, u'gname', None)

    # File entry type stat information.

    # The root file entry is virtual and should have type directory.
    if self._is_virtual or tar_info.isdir():
      stat_object.type = stat_object.TYPE_DIRECTORY
    elif tar_info.isfile():
      stat_object.type = stat_object.TYPE_FILE
    elif tar_info.issym() or tar_info.islnk():
      stat_object.type = stat_object.TYPE_LINK
    elif tar_info.ischr() or tar_info.isblk():
      stat_object.type = stat_object.TYPE_DEVICE
    elif tar_info.isfifo():
      stat_object.type = stat_object.TYPE_PIPE

    # TODO: determine if this covers all the types:
    # REGTYPE, AREGTYPE, LNKTYPE, SYMTYPE, DIRTYPE, FIFOTYPE, CONTTYPE,
    # CHRTYPE, BLKTYPE, GNUTYPE_SPARSE

    # Other stat information.
    # tar_info.pax_headers

    return stat_object

  @property
  def name(self):
    """str: name of the file entry, which does not include the full path."""
    path = getattr(self.path_spec, u'location', None)
    if path is not None and not isinstance(path, py2to3.UNICODE_TYPE):
      try:
        path = path.decode(self._file_system.encoding)
      except UnicodeDecodeError:
        path = None
    return self._file_system.BasenamePath(path)

  @property
  def sub_file_entries(self):
    """generator(TARFileEntry): sub file entries."""
    tar_file = self._file_system.GetTARFile()

    if self._directory is None:
      self._directory = self._GetDirectory()

    if self._directory and tar_file:
      for path_spec in self._directory.entries:
        location = getattr(path_spec, u'location', None)
        if location is None:
          continue

        kwargs = {}
        try:
          kwargs[u'tar_info'] = tar_file.getmember(location[1:])
        except KeyError:
          kwargs[u'is_virtual'] = True

        yield TARFileEntry(
            self._resolver_context, self._file_system, path_spec, **kwargs)

  def GetParentFileEntry(self):
    """Retrieves the parent file entry.

    Returns:
      TARFileEntry: parent file entry or None.
    """
    location = getattr(self.path_spec, u'location', None)
    if location is None:
      return

    parent_location = self._file_system.DirnamePath(location)
    if parent_location is None:
      return
    if parent_location == u'':
      parent_location = self._file_system.PATH_SEPARATOR

    parent_path_spec = getattr(self.path_spec, u'parent', None)
    path_spec = tar_path_spec.TARPathSpec(
        location=parent_location, parent=parent_path_spec)
    return TARFileEntry(self._resolver_context, self._file_system, path_spec)

  def GetTARInfo(self):
    """Retrieves the TAR info.

    Returns:
      tarfile.TARInfo: TAR info or None if it does not exist.

    Raises:
      PathSpecError: if the path specification is incorrect.
    """
    if not self._tar_info:
      location = getattr(self.path_spec, u'location', None)
      if location is None:
        raise errors.PathSpecError(u'Path specification missing location.')

      if not location.startswith(self._file_system.LOCATION_ROOT):
        raise errors.PathSpecError(u'Invalid location in path specification.')

      if len(location) == 1:
        return

      tar_file = self._file_system.GetTARFile()
      try:
        self._tar_info = tar_file.getmember(location[1:])
      except KeyError:
        pass

    return self._tar_info


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

    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <title>Statistics of NumType in UD_Upper_Sorbian-UFAL</title>
    <link rel="root" href=""/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
    <link rel="stylesheet" type="text/css" href="../../css/jquery-ui-redmond.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/style-vis.css"/>
    <link rel="stylesheet" type="text/css" href="../../css/hint.css"/>

          home

          edit page
          issue tracker

          <gcse:search></gcse:search>

        This page pertains to UD version 2.

            It appears that you have Javascript disabled.
            Please consider enabling Javascript for this page to see the visualizations.

Treebank Statistics: UD_Upper_Sorbian-UFAL: Features: NumType

This feature is universal.
It occurs with 3 different values: Card, Mult, Ord.

476 tokens (4%) have a non-empty value of NumType.
243 types (6%) occur at least once with a non-empty value of NumType.
205 lemmas (7%) occur at least once with a non-empty value of NumType.
The feature is used with 5 part-of-speech tags: <tt>NUM</tt> (381; 3% instances), <tt>ADJ</tt> (52; 0% instances), <tt>ADV</tt> (21; 0% instances), <tt>DET</tt> (20; 0% instances), <tt>NOUN</tt> (2; 0% instances).

NUM

381 <tt>NUM</tt> tokens (100% of all NUM tokens) have a non-empty value of NumType.

NUM tokens may have the following values of NumType:

Card (381; 100% of non-empty NumType): 2, 1, 6, 4, 3, 5, 7, I, 000, 10

EMPTY (1): miliardow

NumType seems to be lexical feature of NUM. 100% lemmas (186) occur only with one value of NumType.

ADJ

52 <tt>ADJ</tt> tokens (4% of all ADJ tokens) have a non-empty value of NumType.

The most frequent other feature values with which ADJ and NumType co-occurred: <tt>Degree</tt><tt>=EMPTY</tt> (52; 100%), <tt>VerbForm</tt><tt>=EMPTY</tt> (52; 100%), <tt>Voice</tt><tt>=EMPTY</tt> (52; 100%), <tt>Animacy</tt><tt>=EMPTY</tt> (44; 85%), <tt>Number</tt><tt>=Sing</tt> (38; 73%).

ADJ tokens may have the following values of NumType:

Mult (2; 4% of non-empty NumType): dwójnu, trójnu

Ord (50; 96% of non-empty NumType): prěni, prěnje, druhe, druhich, Třećeho, druhi, druhej, 50tych, Druheje, Druhu

EMPTY (1369): serbski, najwjetše, serbskeje, Serbskeho, wulke, wulki, wulku, ablawtowych, dalše, wjacore

NumType seems to be lexical feature of ADJ. 100% lemmas (13) occur only with one value of NumType.

ADV

21 <tt>ADV</tt> tokens (4% of all ADV tokens) have a non-empty value of NumType.

The most frequent other feature values with which ADV and NumType co-occurred: <tt>PronType</tt><tt>=Ind</tt> (21; 100%), <tt>Degree</tt><tt>=Cmp</tt> (14; 67%).

ADV tokens may have the following values of NumType:

Card (21; 100% of non-empty NumType): wjace, wjele, mjenje, tróšku, mjeńše, najwjace

EMPTY (514): tež, tak, hišće, zwjetša, hač, něhdźe, hižo, tu, najprjedy, potom

DET

20 <tt>DET</tt> tokens (6% of all DET tokens) have a non-empty value of NumType.

The most frequent other feature values with which DET and NumType co-occurred: <tt>Abbr</tt><tt>=EMPTY</tt> (20; 100%), <tt>Animacy</tt><tt>=EMPTY</tt> (20; 100%), <tt>Number[psor]</tt><tt>=EMPTY</tt> (20; 100%), <tt>Person</tt><tt>=EMPTY</tt> (20; 100%), <tt>Poss</tt><tt>=EMPTY</tt> (20; 100%), <tt>Case</tt><tt>=EMPTY</tt> (19; 95%), <tt>Gender</tt><tt>=EMPTY</tt> (19; 95%), <tt>Number</tt><tt>=EMPTY</tt> (19; 95%), <tt>PronType</tt><tt>=Ind</tt> (18; 90%).

DET tokens may have the following values of NumType:

Card (20; 100% of non-empty NumType): wjele, mnoho, Wobě, mjenje, najwjace, tróšku, tójšto, wjace

EMPTY (307): n, kotrež, tute, jeho, jich, kotryž, kotraž, tutón, swoje, tuta

NOUN

2 <tt>NOUN</tt> tokens (0% of all NOUN tokens) have a non-empty value of NumType.

NOUN tokens may have the following values of NumType:

Card (2; 100% of non-empty NumType): stopjeń, třoch

EMPTY (2541): l, př, město, rěč, woda, rěčow, lěta, stolica, lěće, kilometrow

Relations with Agreement in NumType

The 10 most frequent relations where parent and child node agree in NumType:
<tt>NUM –[<tt>conj</tt>]–> NUM</tt> (39; 100%),
<tt>NUM –[<tt>compound</tt>]–> NUM</tt> (32; 97%),
<tt>NUM –[<tt>advmod</tt>]–> ADV</tt> (5; 100%),
<tt>NUM –[<tt>nummod</tt>]–> NUM</tt> (3; 100%),
<tt>ADJ –[<tt>conj</tt>]–> ADJ</tt> (1; 100%),
<tt>DET –[<tt>advmod</tt>]–> ADV</tt> (1; 100%).

© 2014–2021
            Universal Dependencies contributors.
            Site powered by Annodoc and brat
.


text:
package org.elasticsearch.index.mapper.core;

import org.apache.lucene.document.Field;
import org.apache.lucene.index.IndexOptions;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Terms;
import org.apache.lucene.search.LegacyNumericRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.LegacyNumericUtils;
import org.elasticsearch.Version;
import org.elasticsearch.action.fieldstats.FieldStats;
import org.elasticsearch.common.Explicit;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.joda.DateMathParser;
import org.elasticsearch.common.joda.FormatDateTimeFormatter;
import org.elasticsearch.common.joda.Joda;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.util.LocaleUtils;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexNumericFieldData.NumericType;
import org.elasticsearch.index.fielddata.plain.DocValuesIndexFieldData;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Mapper;
import org.elasticsearch.index.mapper.MapperParsingException;
import org.elasticsearch.index.mapper.ParseContext;
import org.elasticsearch.index.mapper.core.LegacyLongFieldMapper.CustomLongNumericField;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.search.internal.SearchContext;
import org.joda.time.DateTimeZone;

import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;

import static org.elasticsearch.index.mapper.core.TypeParsers.parseDateTimeFormatter;
import static org.elasticsearch.index.mapper.core.TypeParsers.parseNumberField;

public class LegacyDateFieldMapper extends LegacyNumberFieldMapper {

    public static final String CONTENT_TYPE = "date";

    public static class Defaults extends LegacyNumberFieldMapper.Defaults {
        public static final FormatDateTimeFormatter DATE_TIME_FORMATTER = Joda.forPattern("strict_date_optional_time||epoch_millis", Locale.ROOT);
        public static final TimeUnit TIME_UNIT = TimeUnit.MILLISECONDS;
        public static final DateFieldType FIELD_TYPE = new DateFieldType();

        static {
            FIELD_TYPE.freeze();
        }

        public static final String NULL_VALUE = null;
    }

    public static class Builder extends LegacyNumberFieldMapper.Builder<Builder, LegacyDateFieldMapper> {

        protected String nullValue = Defaults.NULL_VALUE;

        private Locale locale;

        public Builder(String name) {
            super(name, Defaults.FIELD_TYPE, Defaults.PRECISION_STEP_64_BIT);
            builder = this;
            // do *NOT* rely on the default locale
            locale = Locale.ROOT;
        }

        @Override
        public DateFieldType fieldType() {
            return (DateFieldType)fieldType;
        }

        public Builder timeUnit(TimeUnit timeUnit) {
            fieldType().setTimeUnit(timeUnit);
            return this;
        }

        public Builder nullValue(String nullValue) {
            this.nullValue = nullValue;
            return this;
        }

        public Builder dateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) {
            fieldType().setDateTimeFormatter(dateTimeFormatter);
            return this;
        }

        @Override
        public LegacyDateFieldMapper build(BuilderContext context) {
            if (context.indexCreatedVersion().onOrAfter(Version.V_5_0_0_alpha2)) {
                throw new IllegalStateException("Cannot use legacy numeric types after 5.0");
            }
            setupFieldType(context);
            fieldType.setNullValue(nullValue);
            LegacyDateFieldMapper fieldMapper = new LegacyDateFieldMapper(name, fieldType, defaultFieldType, ignoreMalformed(context),
                coerce(context), context.indexSettings(), multiFieldsBuilder.build(this, context), copyTo);
            return (LegacyDateFieldMapper) fieldMapper.includeInAll(includeInAll);
        }

        @Override
        protected void setupFieldType(BuilderContext context) {
            FormatDateTimeFormatter dateTimeFormatter = fieldType().dateTimeFormatter;
            if (!locale.equals(dateTimeFormatter.locale())) {
                fieldType().setDateTimeFormatter(new FormatDateTimeFormatter(dateTimeFormatter.format(), dateTimeFormatter.parser(), dateTimeFormatter.printer(), locale));
            }
            super.setupFieldType(context);
        }

        public Builder locale(Locale locale) {
            this.locale = locale;
            return this;
        }

        @Override
        protected int maxPrecisionStep() {
            return 64;
        }
    }

    public static class TypeParser implements Mapper.TypeParser {
        @Override
        public Mapper.Builder<?, ?> parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException {
            LegacyDateFieldMapper.Builder builder = new LegacyDateFieldMapper.Builder(name);
            parseNumberField(builder, name, node, parserContext);
            boolean configuredFormat = false;
            for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry<String, Object> entry = iterator.next();
                String propName = entry.getKey();
                Object propNode = entry.getValue();
                if (propName.equals("null_value")) {
                    if (propNode == null) {
                        throw new MapperParsingException("Property [null_value] cannot be null.");
                    }
                    builder.nullValue(propNode.toString());
                    iterator.remove();
                } else if (propName.equals("format")) {
                    builder.dateTimeFormatter(parseDateTimeFormatter(propNode));
                    configuredFormat = true;
                    iterator.remove();
                } else if (propName.equals("numeric_resolution")) {
                    builder.timeUnit(TimeUnit.valueOf(propNode.toString().toUpperCase(Locale.ROOT)));
                    iterator.remove();
                } else if (propName.equals("locale")) {
                    builder.locale(LocaleUtils.parse(propNode.toString()));
                    iterator.remove();
                }
            }
            if (!configuredFormat) {
                builder.dateTimeFormatter(Defaults.DATE_TIME_FORMATTER);
            }
            return builder;
        }
    }

    public static class DateFieldType extends NumberFieldType {

        final class LateParsingQuery extends Query {

            final Object lowerTerm;
            final Object upperTerm;
            final boolean includeLower;
            final boolean includeUpper;
            final DateTimeZone timeZone;
            final DateMathParser forcedDateParser;

            public LateParsingQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, DateTimeZone timeZone, DateMathParser forcedDateParser) {
                this.lowerTerm = lowerTerm;
                this.upperTerm = upperTerm;
                this.includeLower = includeLower;
                this.includeUpper = includeUpper;
                this.timeZone = timeZone;
                this.forcedDateParser = forcedDateParser;
            }

            @Override
            public Query rewrite(IndexReader reader) throws IOException {
                Query rewritten = super.rewrite(reader);
                if (rewritten != this) {
                    return rewritten;
                }
                return innerRangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser);
            }

            // Even though we only cache rewritten queries it is good to let all queries implement hashCode() and equals():
            @Override
            public boolean equals(Object o) {
                if (this == o) return true;
                if (!super.equals(o)) return false;

                LateParsingQuery that = (LateParsingQuery) o;
                if (includeLower != that.includeLower) return false;
                if (includeUpper != that.includeUpper) return false;
                if (lowerTerm != null ? !lowerTerm.equals(that.lowerTerm) : that.lowerTerm != null) return false;
                if (upperTerm != null ? !upperTerm.equals(that.upperTerm) : that.upperTerm != null) return false;
                if (timeZone != null ? !timeZone.equals(that.timeZone) : that.timeZone != null) return false;

                return true;
            }

            @Override
            public int hashCode() {
                return Objects.hash(super.hashCode(), lowerTerm, upperTerm, includeLower, includeUpper, timeZone);
            }

            @Override
            public String toString(String s) {
                final StringBuilder sb = new StringBuilder();
                return sb.append(name()).append(':')
                    .append(includeLower ? '[' : '{')
                    .append((lowerTerm == null) ? "*" : lowerTerm.toString())
                    .append(" TO ")
                    .append((upperTerm == null) ? "*" : upperTerm.toString())
                    .append(includeUpper ? ']' : '}')
                    .toString();
            }
        }

        protected FormatDateTimeFormatter dateTimeFormatter = Defaults.DATE_TIME_FORMATTER;
        protected TimeUnit timeUnit = Defaults.TIME_UNIT;
        protected DateMathParser dateMathParser = new DateMathParser(dateTimeFormatter);

        public DateFieldType() {
            super(LegacyNumericType.LONG);
        }

        protected DateFieldType(DateFieldType ref) {
            super(ref);
            this.dateTimeFormatter = ref.dateTimeFormatter;
            this.timeUnit = ref.timeUnit;
            this.dateMathParser = ref.dateMathParser;
        }

        @Override
        public DateFieldType clone() {
            return new DateFieldType(this);
        }

        @Override
        public boolean equals(Object o) {
            if (!super.equals(o)) return false;
            DateFieldType that = (DateFieldType) o;
            return Objects.equals(dateTimeFormatter.format(), that.dateTimeFormatter.format()) &&
                   Objects.equals(dateTimeFormatter.locale(), that.dateTimeFormatter.locale()) &&
                   Objects.equals(timeUnit, that.timeUnit);
        }

        @Override
        public int hashCode() {
            return Objects.hash(super.hashCode(), dateTimeFormatter.format(), timeUnit);
        }

        @Override
        public String typeName() {
            return CONTENT_TYPE;
        }

        @Override
        public void checkCompatibility(MappedFieldType fieldType, List<String> conflicts, boolean strict) {
            super.checkCompatibility(fieldType, conflicts, strict);
            if (strict) {
                DateFieldType other = (DateFieldType)fieldType;
                if (Objects.equals(dateTimeFormatter().format(), other.dateTimeFormatter().format()) == false) {
                    conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [format] across all types.");
                }
                if (Objects.equals(dateTimeFormatter().locale(), other.dateTimeFormatter().locale()) == false) {
                    conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [locale] across all types.");
                }
                if (Objects.equals(timeUnit(), other.timeUnit()) == false) {
                    conflicts.add("mapper [" + name() + "] is used by multiple types. Set update_all_types to true to update [numeric_resolution] across all types.");
                }
            }
        }

        public FormatDateTimeFormatter dateTimeFormatter() {
            return dateTimeFormatter;
        }

        public void setDateTimeFormatter(FormatDateTimeFormatter dateTimeFormatter) {
            checkIfFrozen();
            this.dateTimeFormatter = dateTimeFormatter;
            this.dateMathParser = new DateMathParser(dateTimeFormatter);
        }

        public TimeUnit timeUnit() {
            return timeUnit;
        }

        public void setTimeUnit(TimeUnit timeUnit) {
            checkIfFrozen();
            this.timeUnit = timeUnit;
            this.dateMathParser = new DateMathParser(dateTimeFormatter);
        }

        protected DateMathParser dateMathParser() {
            return dateMathParser;
        }

        private long parseValue(Object value) {
            if (value instanceof Number) {
                return ((Number) value).longValue();
            }
            if (value instanceof BytesRef) {
                return dateTimeFormatter().parser().parseMillis(((BytesRef) value).utf8ToString());
            }
            return dateTimeFormatter().parser().parseMillis(value.toString());
        }

        protected long parseStringValue(String value) {
            return dateTimeFormatter().parser().parseMillis(value);
        }

        @Override
        public BytesRef indexedValueForSearch(Object value) {
            BytesRefBuilder bytesRef = new BytesRefBuilder();
            LegacyNumericUtils.longToPrefixCoded(parseValue(value), 0, bytesRef); // 0 because of exact match
            return bytesRef.get();
        }

        @Override
        public Object valueForSearch(Object value) {
            Long val = (Long) value;
            if (val == null) {
                return null;
            }
            return dateTimeFormatter().printer().print(val);
        }

        @Override
        public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper) {
            return rangeQuery(lowerTerm, upperTerm, includeLower, includeUpper, null, null);
        }

        @Override
        public FieldStats.Date stats(IndexReader reader) throws IOException {
            int maxDoc = reader.maxDoc();
            Terms terms = org.apache.lucene.index.MultiFields.getTerms(reader, name());
            if (terms == null) {
                return null;
            }
            long minValue = LegacyNumericUtils.getMinLong(terms);
            long maxValue = LegacyNumericUtils.getMaxLong(terms);
            return new FieldStats.Date(maxDoc, terms.getDocCount(),
                terms.getSumDocFreq(), terms.getSumTotalTermFreq(), isSearchable(), isAggregatable(),
                dateTimeFormatter(), minValue, maxValue);
        }

        public Query rangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable DateTimeZone timeZone, @Nullable DateMathParser forcedDateParser) {
            return new LateParsingQuery(lowerTerm, upperTerm, includeLower, includeUpper, timeZone, forcedDateParser);
        }

        private Query innerRangeQuery(Object lowerTerm, Object upperTerm, boolean includeLower, boolean includeUpper, @Nullable DateTimeZone timeZone, @Nullable DateMathParser forcedDateParser) {
            return LegacyNumericRangeQuery.newLongRange(name(), numericPrecisionStep(),
                lowerTerm == null ? null : parseToMilliseconds(lowerTerm, !includeLower, timeZone, forcedDateParser == null ? dateMathParser : forcedDateParser),
                upperTerm == null ? null : parseToMilliseconds(upperTerm, includeUpper, timeZone, forcedDateParser == null ? dateMathParser : forcedDateParser),
                includeLower, includeUpper);
        }

        @Override
        public Relation isFieldWithinQuery(IndexReader reader,
                Object from, Object to,
                boolean includeLower, boolean includeUpper,
                DateTimeZone timeZone, DateMathParser dateParser) throws IOException {
            if (dateParser == null) {
                dateParser = this.dateMathParser;
            }

            Terms terms = org.apache.lucene.index.MultiFields.getTerms(reader, name());
            if (terms == null) {
                // no terms, so nothing matches
                return Relation.DISJOINT;
            }

            long minValue = LegacyNumericUtils.getMinLong(terms);
            long maxValue = LegacyNumericUtils.getMaxLong(terms);

            long fromInclusive = Long.MIN_VALUE;
            if (from != null) {
                fromInclusive = parseToMilliseconds(from, !includeLower, timeZone, dateParser);
                if (includeLower == false) {
                    if (fromInclusive == Long.MAX_VALUE) {
                        return Relation.DISJOINT;
                    }
                    ++fromInclusive;
                }
            }

            long toInclusive = Long.MAX_VALUE;
            if (to != null) {
                toInclusive = parseToMilliseconds(to, includeUpper, timeZone, dateParser);
                if (includeUpper == false) {
                    if (toInclusive == Long.MIN_VALUE) {
                        return Relation.DISJOINT;
                    }
                    --toInclusive;
                }
            }

            if (minValue >= fromInclusive && maxValue <= toInclusive) {
                return Relation.WITHIN;
            } else if (maxValue < fromInclusive || minValue > toInclusive) {
                return Relation.DISJOINT;
            } else {
                return Relation.INTERSECTS;
            }
        }

        public long parseToMilliseconds(Object value, boolean inclusive, @Nullable DateTimeZone zone, @Nullable DateMathParser forcedDateParser) {
            if (value instanceof Long) {
                return ((Long) value).longValue();
            }

            DateMathParser dateParser = dateMathParser();
            if (forcedDateParser != null) {
                dateParser = forcedDateParser;
            }

            String strValue;
            if (value instanceof BytesRef) {
                strValue = ((BytesRef) value).utf8ToString();
            } else {
                strValue = value.toString();
            }
            return dateParser.parse(strValue, now(), inclusive, zone);
        }

        @Override
        public IndexFieldData.Builder fielddataBuilder() {
            failIfNoDocValues();
            return new DocValuesIndexFieldData.Builder().numericType(NumericType.LONG);
        }

        @Override
        public DocValueFormat docValueFormat(@Nullable String format, DateTimeZone timeZone) {
            FormatDateTimeFormatter dateTimeFormatter = this.dateTimeFormatter;
            if (format != null) {
                dateTimeFormatter = Joda.forPattern(format);
            }
            if (timeZone == null) {
                timeZone = DateTimeZone.UTC;
            }
            return new DocValueFormat.DateTime(dateTimeFormatter, timeZone);
        }
    }

    protected LegacyDateFieldMapper(String simpleName, MappedFieldType fieldType, MappedFieldType defaultFieldType, Explicit<Boolean> ignoreMalformed,Explicit<Boolean> coerce,
                              Settings indexSettings, MultiFields multiFields, CopyTo copyTo) {
        super(simpleName, fieldType, defaultFieldType, ignoreMalformed, coerce, indexSettings, multiFields, copyTo);
    }

    @Override
    public DateFieldType fieldType() {
        return (DateFieldType) super.fieldType();
    }

    private static Callable<Long> now() {
        return new Callable<Long>() {
            @Override
            public Long call() {
                final SearchContext context = SearchContext.current();
                return context != null
                    ? context.nowInMillis()
                    : System.currentTimeMillis();
            }
        };
    }

    @Override
    protected boolean customBoost() {
        return true;
    }

    @Override
    protected void innerParseCreateField(ParseContext context, List<Field> fields) throws IOException {
        String dateAsString = null;
        float boost = fieldType().boost();
        if (context.externalValueSet()) {
            Object externalValue = context.externalValue();
            dateAsString = (String) externalValue;
            if (dateAsString == null) {
                dateAsString = fieldType().nullValueAsString();
            }
        } else {
            XContentParser parser = context.parser();
            XContentParser.Token token = parser.currentToken();
            if (token == XContentParser.Token.VALUE_NULL) {
                dateAsString = fieldType().nullValueAsString();
            } else if (token == XContentParser.Token.VALUE_NUMBER) {
                dateAsString = parser.text();
            } else if (token == XContentParser.Token.START_OBJECT
                    && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) {
                String currentFieldName = null;
                while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
                    if (token == XContentParser.Token.FIELD_NAME) {
                        currentFieldName = parser.currentName();
                    } else {
                        if ("value".equals(currentFieldName) || "_value".equals(currentFieldName)) {
                            if (token == XContentParser.Token.VALUE_NULL) {
                                dateAsString = fieldType().nullValueAsString();
                            } else {
                                dateAsString = parser.text();
                            }
                        } else if ("boost".equals(currentFieldName) || "_boost".equals(currentFieldName)) {
                            boost = parser.floatValue();
                        } else {
                            throw new IllegalArgumentException("unknown property [" + currentFieldName + "]");
                        }
                    }
                }
            } else {
                dateAsString = parser.text();
            }
        }

        Long value = null;
        if (dateAsString != null) {
            if (context.includeInAll(includeInAll, this)) {
                context.allEntries().addText(fieldType().name(), dateAsString, boost);
            }
            value = fieldType().parseStringValue(dateAsString);
        }

        if (value != null) {
            if (fieldType().indexOptions() != IndexOptions.NONE || fieldType().stored()) {
                CustomLongNumericField field = new CustomLongNumericField(value, fieldType());
                if (boost != 1f && Version.indexCreated(context.indexSettings()).before(Version.V_5_0_0_alpha1)) {
                    field.setBoost(boost);
                }
                fields.add(field);
            }
            if (fieldType().hasDocValues()) {
                addDocValue(context, fields, value);
            }
        }
    }

    @Override
    protected String contentType() {
        return CONTENT_TYPE;
    }

    @Override
    protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException {
        super.doXContentBody(builder, includeDefaults, params);

        if (includeDefaults || fieldType().numericPrecisionStep() != Defaults.PRECISION_STEP_64_BIT) {
            builder.field("precision_step", fieldType().numericPrecisionStep());
        }
        builder.field("format", fieldType().dateTimeFormatter().format());
        if (includeDefaults || fieldType().nullValueAsString() != null) {
            builder.field("null_value", fieldType().nullValueAsString());
        }
        if (includeInAll != null) {
            builder.field("include_in_all", includeInAll);
        } else if (includeDefaults) {
            builder.field("include_in_all", false);
        }

        if (includeDefaults || fieldType().timeUnit() != Defaults.TIME_UNIT) {
            builder.field("numeric_resolution", fieldType().timeUnit().name().toLowerCase(Locale.ROOT));
        }
        // only serialize locale if needed, ROOT is the default, so no need to serialize that case as well...
        if (fieldType().dateTimeFormatter().locale() != null && fieldType().dateTimeFormatter().locale() != Locale.ROOT) {
            builder.field("locale", fieldType().dateTimeFormatter().locale());
        } else if (includeDefaults) {
            if (fieldType().dateTimeFormatter().locale() == null) {
                builder.field("locale", Locale.ROOT);
            } else {
                builder.field("locale", fieldType().dateTimeFormatter().locale());
            }
        }
    }
}


text:
package com.tngtech.jgiven.junit5.test;

import com.tngtech.jgiven.annotation.Pending;
import com.tngtech.jgiven.annotation.ScenarioStage;
import com.tngtech.jgiven.junit5.JGivenExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

@ExtendWith(JGivenExtension.class)
class JUnit5ExtensionTest {

    @ScenarioStage
    GivenStage givenStage;

    @ScenarioStage
    WhenStage whenStage;

    @ScenarioStage
    ThenStage thenStage;

    @Test
    public void JGiven_works_with_JUnit5() {
        givenStage.some_state();
        whenStage.some_action();
        thenStage.some_outcome();
    }

    @Test
    @Pending
    public void Pending_works() {
        whenStage.some_failing_step();
    }
}


text:
namespace Nancy.Demo.Samples.Modules
{
    using System;
    using Authentication.Forms;

    public class Login : NancyModule
    {
        public Login(IUserDatabase userDatabase)
        {

            Get["/login"] = x =>
            {
                return View["login"];
            };

            Post["/login"] = parameters =>
            {
                var userGuid = userDatabase.ValidateUser((string)this.Request.Form.Password);

                if (userGuid == null)
                {
                    return Response.AsRedirect("/");
                }

                DateTime? expiry = null;

                return this.LoginAndRedirect(userGuid.Value, expiry);
            };

            Get["/logout"] = x =>
            {
                return this.LogoutAndRedirect("~/");
            };
        }
    }
}


text:
layout: page
title: Hawkins Industries Executive Retreat
date: 2016-05-24
author: Diana Murphy
tags: weekly links, java
status: published
summary: Integer ornare hendrerit nunc. Nullam ac.
banner: images/banner/leisure-04.jpg
booking:
  startDate: 03/11/2017
  endDate: 03/14/2017
  ctyhocn: EPHPAHX
  groupCode: HIER
published: true
---
Proin eget lorem sed nunc scelerisque placerat. Cras maximus risus in erat lacinia, in feugiat sapien auctor. In et mauris faucibus, blandit ipsum vel, fermentum orci. Etiam vestibulum pretium risus, ut sagittis ex eleifend sed. Fusce tempor nunc sit amet massa interdum tincidunt. Nunc a bibendum turpis. In ac consequat nisi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse odio massa, lobortis eget vulputate et, pellentesque nec tellus.
Nulla molestie, nulla cursus pharetra facilisis, turpis mauris ultrices erat, vitae aliquet mauris sem ac enim. Donec et dui vel mauris commodo iaculis nec eget erat. Suspendisse vulputate ex sapien, nec mattis erat elementum eu. Donec finibus massa id velit molestie sodales. Aenean vel condimentum erat, vitae pellentesque velit. Sed in lectus vitae orci cursus molestie. Aliquam ut vehicula justo. Etiam vel nulla ornare metus mattis faucibus sit amet vel metus. Nullam ex arcu, interdum non dui vel, sodales ultrices ligula.

1 Aliquam eu nibh nec tortor facilisis accumsan id non nibh
1 Aliquam sit amet sapien ac nibh posuere fringilla
1 Nam eget nulla egestas ipsum tincidunt pretium
1 Proin nec nunc non massa sodales pulvinar
1 Phasellus fringilla magna ut dolor finibus egestas
1 Nunc fermentum purus ac dolor viverra, eu cursus lectus tristique.

Integer bibendum quam id lectus accumsan, id maximus tellus blandit. Vestibulum consequat aliquam elit, ornare pulvinar est maximus et. Cras lobortis accumsan dolor vitae dapibus. Mauris sed lacus vitae erat aliquet placerat. Curabitur imperdiet dapibus erat eu luctus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Pellentesque sagittis, leo non venenatis aliquet, mi mauris scelerisque augue, non convallis leo sapien quis odio. Phasellus efficitur metus sit amet ante sodales luctus.


text:
package main

import (
	homedir "github.com/mitchellh/go-homedir"
	"github.com/pulcy/vault-monkey/service"
	"github.com/spf13/cobra"
)

var (
	cmdCAIssue = &cobra.Command{
		Use:   "issue",
		Short: "Create vault information for a new cluster specific CA",
		Run:   showUsage,
	}

	cmdCAIssueETCD = &cobra.Command{
		Use:   "etcd",
		Short: "Issue a certificate to access the ETCD cluster.",
		Run:   cmdCAIssueETCDRun,
	}

	cmdCAIssueK8s = &cobra.Command{
		Use:   "k8s",
		Short: "Issue a certificate to access the Kubernetes API server.",
		Run:   cmdCAIssueK8sRun,
	}

	caIssueFlags struct {
		serverLogin bool
		force       bool
		service.IssueConfig
	}
)

func init() {
	cmdCA.AddCommand(cmdCAIssue)
	cmdCAIssue.AddCommand(cmdCAIssueETCD)
	cmdCAIssue.AddCommand(cmdCAIssueK8s)

	defaultOutputDir, err := homedir.Expand("~/.pulcy/certs")
	if err != nil {
		Exitf("Failed to expand homedir: %#v\n", err)
	}
	cmdCAIssue.PersistentFlags().BoolVar(&caIssueFlags.serverLogin, "server", false, "If set, a server login is performed (instead of admin login)")
	cmdCAIssue.PersistentFlags().BoolVar(&caIssueFlags.force, "force", false, "If set, a new certificate will always be issued")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.IssueConfig.OutputDir, "destination", defaultOutputDir, "Where to store the issued certificates")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.CommonName, "common-name", caIssueFlags.CommonName, "CommonName of the user")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.Role, "role", caIssueFlags.Role, "Role used to issue certificate")
	cmdCAIssue.PersistentFlags().StringSliceVar(&caIssueFlags.AltNames, "alt-name", caIssueFlags.AltNames, "Alternate names of the user")
	cmdCAIssue.PersistentFlags().StringSliceVar(&caIssueFlags.IPSans, "ip-san", caIssueFlags.IPSans, "IP Subject Alternative Names")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.CertificateFileName, "cert-file-name", caIssueFlags.CertificateFileName, "Filename of the public key")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.KeyFileName, "key-file-name", caIssueFlags.KeyFileName, "Filename of the private key")
	cmdCAIssue.PersistentFlags().StringVar(&caIssueFlags.CAFileName, "ca-file-name", caIssueFlags.CAFileName, "Filename of the CA certificate")
	cmdCAIssue.PersistentFlags().Uint32Var(&caIssueFlags.FileMode, "file-mode", caIssueFlags.FileMode, "Mode of files that are created (defaults to 0600)")
}

func cmdCAIssueETCDRun(cmd *cobra.Command, args []string) {
	assertArgIsSet(caFlags.clusterID, "cluster-id")
	assertArgIsSet(caIssueFlags.OutputDir, "destination")
	assertArgIsSet(caIssueFlags.CommonName, "common-name")

	caIssueFlags.IssueConfig.SetupDefaults(caFlags.clusterID)
	if !caIssueFlags.force {
		if !caIssueFlags.IssueConfig.IssueIsNeeded(log) {
			log.Infof("Certificate already exists")
			return
		}
	}

	var c *service.AuthenticatedVaultClient
	var err error
	if caIssueFlags.serverLogin {
		c, _, err = serverLogin()
		if err != nil {
			Exitf("Server login failed: %v", err)
		}
	} else {
		_, c, err = adminLogin()
		if err != nil {
			Exitf("Admin login failed: %v", err)
		}
	}

	ca := c.CA()
	if err := ca.IssueETCDCertificate(caFlags.clusterID, caIssueFlags.IssueConfig); err != nil {
		Exitf("Failed to issue certificate: %v", err)
	}
}

func cmdCAIssueK8sRun(cmd *cobra.Command, args []string) {
	assertArgIsSet(caFlags.clusterID, "cluster-id")
	assertArgIsSet(caIssueFlags.OutputDir, "destination")
	assertArgIsSet(caIssueFlags.CommonName, "common-name")

	caIssueFlags.IssueConfig.SetupDefaults(caFlags.clusterID)
	if !caIssueFlags.force {
		if !caIssueFlags.IssueConfig.IssueIsNeeded(log) {
			log.Infof("Certificate already exists")
			return
		}
	}

	var c *service.AuthenticatedVaultClient
	var err error
	if caIssueFlags.serverLogin {
		c, _, err = serverLogin()
		if err != nil {
			Exitf("Server login failed: %v", err)
		}
	} else {
		_, c, err = adminLogin()
		if err != nil {
			Exitf("Admin login failed: %v", err)
		}
	}

	ca := c.CA()
	if err := ca.IssueK8sCertificate(caFlags.clusterID, caIssueFlags.IssueConfig); err != nil {
		Exitf("Failed to issue certificate: %v", err)
	}
}


text:
from flask import Blueprint, session, render_template, abort, request, jsonify
import mysql.connector
import secret
from handlers.pet import onePet
from handlers.moment import petMoments
from handlers.watch import searchWatch, deleteWatch, createWatch
from handlers.token import findUser

pets_routes = Blueprint('pets_routes', __name__, template_folder = 'templates')
config = secret.mysql()

#read data for one pet
#return 0 for error
#return 2 for pet not eixst
@pets_routes.route('/pets/readPet', methods = ['GET', 'POST'])
def petView():
    #only response for post request
    if request.method == 'POST':
        #get pet id of current page
        petId = request.json['id']
        cnx = mysql.connector.connect(**config)
        try:
            pet = onePet(petId, cnx)
            #return 1 if pet not exist
            if not pet:
                return '2'
            #return 0 for db error
            if pet == '0':
                return '0'
            #get all related moments of one pet
            moments = petMoments(petId, 0, cnx)
            #return 0 for db error
            if moments == "0":
                return '0'
            #get all watch ids of one pet
            watch = searchWatch(petId, cnx)
            #return 0 for db error
            if watch == '0':
                return '0'
        finally:
            cnx.close()
        #return data
        return jsonify([pet, moments, watch])
    else:
        abort(404)

#load more moment for one pet
@pets_routes.route('/pets/loadMoments', methods = ['GET', 'POST'])
def petLoad():
    if request.method == 'POST':
        id = request.json['id']
        pin = request.json['load'] * 20
        cnx = mysql.connector.connect(**config)
        try:
            moments = petMoments(id, pin, cnx)
        finally:
            cnx.close()
        if moments == "0":
            return '0'
        else:
            return jsonify(moments)
    else:
        abort(404)

#update watch pet or unwatch pet
#return 2 for not login
#return 1 for success
#return 0 for error
@pets_routes.route('/pets/updateWatch', methods = ['GET', 'POST'])
def updateWatch():
    #only response to post request
    if request.method == 'POST':
        token = request.json['userToken']
        id = request.json['userId']
        action = request.json['action']
        cnx = mysql.connector.connect(**config)
        try:
            user = findUser(token, cnx)
            if user == '0':
                return '0'
            elif user is None:
                return '2'
            else:
                userId = user[0]
            if userId != id:
                return '2'
            #unwatch when action is exist
            if action == 1:
                petId = request.json['petId']
                return deleteWatch(userId, petId, cnx)
            elif action == 0:
                petId = request.json['petId']
                return createWatch(userId, petId, cnx)
        finally:
            cnx.close()
    else:
        abort(404)


text:
from tempest.api.compute import base
from tempest import config
from tempest import test

CONF = config.CONF

class FixedIPsTestJson(base.BaseV2ComputeAdminTest):

    @classmethod
    def resource_setup(cls):
        super(FixedIPsTestJson, cls).resource_setup()
        if CONF.service_available.neutron:
            msg = ("%s skipped as neutron is available" % cls.__name__)
            raise cls.skipException(msg)
        cls.client = cls.os_adm.fixed_ips_client
        server = cls.create_test_server(wait_until='ACTIVE')
        server = cls.servers_client.get_server(server['id'])
        for ip_set in server['addresses']:
            for ip in server['addresses'][ip_set]:
                if ip['OS-EXT-IPS:type'] == 'fixed':
                    cls.ip = ip['addr']
                    break
            if cls.ip:
                break

    @test.attr(type='gate')
    @test.services('network')
    def test_list_fixed_ip_details(self):
        fixed_ip = self.client.get_fixed_ip_details(self.ip)
        self.assertEqual(fixed_ip['address'], self.ip)

    @test.attr(type='gate')
    @test.services('network')
    def test_set_reserve(self):
        body = {"reserve": "None"}
        self.client.reserve_fixed_ip(self.ip, body)

    @test.attr(type='gate')
    @test.services('network')
    def test_set_unreserve(self):
        body = {"unreserve": "None"}
        self.client.reserve_fixed_ip(self.ip, body)


text:
package View;

import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.Slider;
import javafx.scene.control.Tab;
import javafx.scene.control.TextField;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;

public class TabUserView extends Tab {
    public Label labelHello;
    public TextField fieldInputName;
    public Label labelInputHeight;
    public Userslider sliderInputHeight;
    public Label labelInputWeight;
    public Userslider sliderInputWeight;
    public Userbutton buttonSave;
    public Userbutton buttonPredict;
    public Userbutton buttonNew;
    public Label  labelComments;
    public Userbutton buttonOpenChart;
    public Userbutton buttonCloseChart;

    public BorderPane borderPane;

    public TabUserView (String name, int inputHeight, int inputWeight, int xSize){
        super();
        createTab(name, inputHeight,  inputWeight,  xSize);
    }

    private void createTab(String name,int inputHeight, int inputWeight, int xSize) {
        this.setText(name);
        VBox vbox = new VBox();
        borderPane = new BorderPane();

        labelHello = new Label("Tere");
        fieldInputName = new TextField();
        fieldInputName.setText("Priit");
        fieldInputName.setMaxWidth(100);

        labelInputHeight = new Label("Sinu pikkus sentimeetrites: "+inputHeight);
        sliderInputHeight = new Userslider(150,200,inputHeight,xSize);

        labelInputWeight= new Label("Sinu kaal kilogrammides: "+inputWeight);
        sliderInputWeight = new Userslider(40,120,inputWeight,xSize);

        buttonSave = new Userbutton("Salvesta andmed");
        buttonPredict = new Userbutton("Ennusta kaal pikkuse alusel");
        buttonNew = new Userbutton("Uus sisestus");
        labelComments= new Label("");
        buttonOpenChart = new Userbutton("Joonista graafik");
        buttonCloseChart = new Userbutton("Kustuta graafik");

        vbox.setSpacing(3);
        vbox.setAlignment(Pos.TOP_CENTER);
        vbox.getChildren().addAll(labelHello,fieldInputName, labelInputHeight,sliderInputHeight
                ,labelInputWeight,sliderInputWeight,buttonSave,buttonPredict,buttonNew,labelComments, buttonOpenChart,buttonCloseChart);
        borderPane.setCenter(vbox );
        this.setContent(borderPane);
        //disable some buttons
        buttonOpenChart.setClickedDisable();
        buttonPredict.setClickedDisable();
        buttonCloseChart.setClickedDisable();
    }
}


text:
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import argparse
import logging
import json
import os
import traceback
import time
import datetime
from socket import AddressFamily

try:
    import psutil
except ModuleNotFoundError:
    print("The reporter requires psutil to run.")
    import sys
    sys.exit(1)

import ray.ray_constants as ray_constants
import ray.utils

# Logger for this module. It should be configured at the entry point
# into the program using Ray. Ray provides a default configuration at
# entry/init points.
logger = logging.getLogger(__name__)

def recursive_asdict(o):
    if isinstance(o, tuple) and hasattr(o, "_asdict"):
        return recursive_asdict(o._asdict())

    if isinstance(o, (tuple, list)):
        L = []
        for k in o:
            L.append(recursive_asdict(k))
        return L

    if isinstance(o, dict):
        D = {k: recursive_asdict(v) for k, v in o.items()}
        return D

    return o

def jsonify_asdict(o):
    return json.dumps(recursive_asdict(o))

def running_worker(s):
    if "ray_worker" not in s:
        return False

    if s == "ray_worker":
        return False

    return True

def determine_ip_address():
    """Return the first IP address for an ethernet interface on the system."""
    addrs = [
        x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e"
        for x in v if x.family == AddressFamily.AF_INET
    ]
    return addrs[0]

def to_posix_time(dt):
    return (dt - datetime.datetime(1970, 1, 1)).total_seconds()

class Reporter(object):
    """A monitor process for monitoring Ray nodes.

    Attributes:
        host (str): The hostname of this machine. Used to improve the log
            messages published to Redis.
        redis_client: A client used to communicate with the Redis server.
    """

    def __init__(self, redis_address, redis_password=None):
        """Initialize the reporter object."""
        self.cpu_counts = (psutil.cpu_count(), psutil.cpu_count(logical=False))
        self.ip_addr = determine_ip_address()
        self.hostname = os.uname().nodename

        _ = psutil.cpu_percent()  # For initialization

        self.redis_key = "{}.{}".format(ray.gcs_utils.REPORTER_CHANNEL,
                                        self.hostname)
        self.redis_client = ray.services.create_redis_client(
            redis_address, password=redis_password)

        self.network_stats_hist = [(0, (0.0, 0.0))]  # time, (sent, recv)

    @staticmethod
    def get_cpu_percent():
        return psutil.cpu_percent()

    @staticmethod
    def get_boot_time():
        return psutil.boot_time()

    @staticmethod
    def get_network_stats():
        ifaces = [
            v for k, v in psutil.net_io_counters(pernic=True).items()
            if k[0] == "e"
        ]

        sent = sum((iface.bytes_sent for iface in ifaces))
        recv = sum((iface.bytes_recv for iface in ifaces))
        return sent, recv

    @staticmethod
    def get_mem_usage():
        vm = psutil.virtual_memory()
        return vm.total, vm.available, vm.percent

    @staticmethod
    def get_disk_usage():
        return {x: psutil.disk_usage(x) for x in ["/", "/tmp"]}

    @staticmethod
    def get_workers():
        return [
            x.as_dict(attrs=[
                "pid", "create_time", "cpu_times", "name", "memory_full_info"
            ]) for x in psutil.process_iter() if running_worker(x.name())
        ]

    def get_load_avg(self):
        load = os.getloadavg()
        per_cpu_load = tuple((round(x / self.cpu_counts[0], 2) for x in load))
        return load, per_cpu_load

    def get_all_stats(self):
        now = to_posix_time(datetime.datetime.utcnow())
        network_stats = self.get_network_stats()

        self.network_stats_hist.append((now, network_stats))
        self.network_stats_hist = self.network_stats_hist[-7:]
        then, prev_network_stats = self.network_stats_hist[0]
        netstats = ((network_stats[0] - prev_network_stats[0]) / (now - then),
                    (network_stats[1] - prev_network_stats[1]) / (now - then))

        return {
            "now": now,
            "hostname": self.hostname,
            "ip": self.ip_addr,
            "cpu": self.get_cpu_percent(),
            "cpus": self.cpu_counts,
            "mem": self.get_mem_usage(),
            "workers": self.get_workers(),
            "boot_time": self.get_boot_time(),
            "load_avg": self.get_load_avg(),
            "disk": self.get_disk_usage(),
            "net": netstats,
        }

    def perform_iteration(self):
        """Get any changes to the log files and push updates to Redis."""
        stats = self.get_all_stats()

        self.redis_client.publish(
            self.redis_key,
            jsonify_asdict(stats),
        )

    def run(self):
        """Run the reporter."""
        while True:
            try:
                self.perform_iteration()
            except Exception:
                traceback.print_exc()
                pass

            time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(
        description=("Parse Redis server for the "
                     "reporter to connect to."))
    parser.add_argument(
        "--redis-address",
        required=True,
        type=str,
        help="The address to use for Redis.")
    parser.add_argument(
        "--redis-password",
        required=False,
        type=str,
        default=None,
        help="the password to use for Redis")
    parser.add_argument(
        "--logging-level",
        required=False,
        type=str,
        default=ray_constants.LOGGER_LEVEL,
        choices=ray_constants.LOGGER_LEVEL_CHOICES,
        help=ray_constants.LOGGER_LEVEL_HELP)
    parser.add_argument(
        "--logging-format",
        required=False,
        type=str,
        default=ray_constants.LOGGER_FORMAT,
        help=ray_constants.LOGGER_FORMAT_HELP)
    args = parser.parse_args()
    ray.utils.setup_logger(args.logging_level, args.logging_format)

    reporter = Reporter(args.redis_address, redis_password=args.redis_password)

    try:
        reporter.run()
    except Exception as e:
        # Something went wrong, so push an error to all drivers.
        redis_client = ray.services.create_redis_client(
            args.redis_address, password=args.redis_password)
        traceback_str = ray.utils.format_error_message(traceback.format_exc())
        message = ("The reporter on node {} failed with the following "
                   "error:\n{}".format(os.uname()[1], traceback_str))
        ray.utils.push_error_to_driver_through_redis(
            redis_client, ray_constants.REPORTER_DIED_ERROR, message)
        raise e


text:
using DollarTracker.EF;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DollarTracker.Core.Infrastructure;

namespace DollarTracker.Core.Repository
{
	public interface IUserRepository: IRepository<User>
	{

	}
	public class UserRepository: RepositoryBase<User>, IUserRepository
	{
		public UserRepository(IDbFactory dbFactory)
			: base(dbFactory)
		{

		}
	}
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>My Playlist</title>

My awesome  playlist


text:
var API = require('../lib/api-helpers')
var Pastie = require('../models/pastie')
var Share = require('../models/share')
var PastiesAPI = module.exports = require('express').Router()

PastiesAPI.get('/pasties', API.requireAuth, API.fetchGroups, function(req, res) {
  Pastie.feedForUser( req.user.uid, req.groups.map(Object.pick('uid')))
    .then( API.prep(200, res) )
    .catch( Pastie.NotFound, API.prep(404, res) )
    .catch( API.catchUnexpectedErrors )
})

PastiesAPI.get('/pasties/public', function(req, res) {
  Pastie.getPublic()
    .then(API.prep(200, res))
    .catch( API.catchUnexpectedErrors )
});

PastiesAPI.get('/pasties/:id', API.fetchGroups, function (req, res) {
  Pastie.find(req.params.id, req.user.uid, req.groups.map(Object.pick('uid')))
  .then(API.prep(200, res))
  .catch(Pastie.NotFound, API.prep(404, res))
  .catch(Pastie.PermissionDenied, API.prep(403, res))
  .catch(API.catchUnexpectedErrors)
})

PastiesAPI.get('/groups/:group_uid/pasties', API.requireAuth, API.fetchGroups, function (req, res) {
  var group_uids = req.groups.map(Object.pick('uid'));
  if (~group_uids.indexOf(req.params.group_uid)) {
    Pastie.sharedWithGroup(req.params.group_uid)
      .then(API.prep(200, res))
      .catch(API.catchUnexpectedErrors(res));
  } else {
    API.prep(403, res)(new Pastie.PermissionDenied());
  }
});

PastiesAPI.post('/pasties', function(req, res) {
  Pastie.create(req.body, req.user.uid)
    .then(API.prep(201, res))
    .catch(Pastie.InvalidFormat, API.prep(400, res))
    .catch(API.catchUnexpectedErrors)
});

PastiesAPI.put(
  '/groups/:group_uid/pasties/:pastie_id',
  API.requireAuth,
  API.fetchGroups,
  function (req, res) {
    // create an array of group_ids that the user can share with

    var shareableGroups = req.groups.map(Object.pick('uid'));

    // NOTE: UNCOMMENT THE FOLLOWING TO DENY STUDENTS #REKT
    // var shareableGroups = req.groups.reduce((res, group) => {
    //   if (group.user_role === 'instructor' || group.user_role === 'fellow') {
    //     res.push(group.uid)
    //   }
    // }, []);
    //
    if (shareableGroups.includes(req.params.group_uid)) {
      Share.create(req.params.pastie_id, [{
        subject_type: 'Group',
        subject_uid: req.params.group_uid
      }])
      .then(() => res.status(200).send())
      .catch(Pastie.NotFound, API.prep(404, res))
      .catch(API.catchUnexpectedErrors)
    } else {
      API.prep(403, res)(new Pastie.PermissionDenied());
    }
  }
);

PastiesAPI.delete(
  '/groups/:group_uid/pasties/:pastie_id',
  API.requireAuth,
  API.fetchGroups,
  function (req, res) {
    var shareableGroups = req.groups.reduce((res, group) => {
      if (group.user_role === 'instructor' || group.user_role === 'fellow') {
        res.push(group.uid)
      }
    }, []);

    if (~shareableGroups.indexOf(req.params.group_uid)) {
      Share.delete(req.params.pastie_id, [{
        subject_type: 'Group',
        subject_uid: req.params.group_uid
      }])
      .then(() => res.status(200).send())
      .catch(API.catchUnexpectedErrors)
    } else {
      API.prep(403, res)(new Pastie.PermissionDenied());
    }
  }
);