text:
<?php

namespace Sf\androidBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

use Sf\ContactBundle\Entity\Contact;
use Sf\UserBundle\Entity\Foyer;
use Sf\ContactBundle\Form\ContactType;
use Sf\ContactBundle\Form\SearchContactType;

use Sf\ShoppingBundle\Entity\ShoppingList;
use Sf\ShoppingBundle\Entity\Article;
use Sf\TodoBundle\Entity\Task;

class ShoppingListController extends Controller
{

    public function getShoppingListsAction() // OK
    {
		$content = $this->get("request")->getContent();
        $params = json_decode($content);
        $id = $params->id;

		$em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('SfUserBundle:User')->findOneById($id);

        $foyers = $user->getFoyers();

        $entities = $em->getRepository('SfShoppingBundle:ShoppingList')->findByFoyer($foyers[$user->getCurrentFoyer()]);
		if(!$entities) { return new JsonResponse(array('data' => "fail")); }

		foreach($entities as $shoppingList){

			$articles = $shoppingList->getArticles();
			foreach($articles as $singleArticle){
				$article = array('articleId' => $singleArticle->getId(),
				'articleName' => $singleArticle->getName(),
					'articleQuantity' => $singleArticle->getQuantity(),
				);
				$finalArticles[] = $article;
				$article = array();
			}

		    $tab = array('listId' => $shoppingList->getId(),
			'listName' => $shoppingList->getName(),
			'listDeadline' => $shoppingList->getDeadline(),
			'articles' => $finalArticles,

			);
			$finalArticles = array();
			$article = array();

		    $final[] = $tab;
			$tab = array();
		}
        return new JsonResponse(array('entities' => $final));
	}

    public function newShoppingListAction()
    {
        $content = $this->get("request")->getContent();
        $params = json_decode($content);
        //Dans ton JSON, il faut : ID user
        $userId = $params->userId;

        $listName = $params->listName;
        $listDeadline = $params->listDeadline;

        $shoppingList = new ShoppingList;
        $shoppingList->setName($listName);
		$shoppingList->setDeadline($listDeadline);

        $em = $this->getDoctrine()->getManager();

        $user = $em->getRepository('SfUserBundle:User')->findOneById($userId);
        $foyers = $user->getFoyers();

		$shoppingList->setCreationDate(new \DateTime());
		$shoppingList->setModificationDate(new \DateTime());
		$shoppingList->setCreatedBy($user->getId());
		$shoppingList->setPrivate(false);
		foreach ($foyers[$user->getCurrentFoyer()]->getUsers() as $u) {
			$shoppingList->addUser($u);
		}

        $foyers[$user->getCurrentFoyer()]->addShoppingList($entity);

		/*
			if($shoppingList->getDeadline() != null) {
			$task = new Task();
			$task->setName($shoppingList->getName());
			$task->setDeadline($shoppingList->getDeadline());
			$task->setCreatedBy($user->getId());
			$task->setCreationDate($shoppingList->getCreationDate());
			$task->setModificationDate($shoppingList->getModificationDate());
			$foyers[$user->getCurrentFoyer()]->addTask($task);
			$task->setVisible(false);
			foreach ($shoppingList->getUsers() as $u) {
				$task->addUser($u);
			}

			$em = $this->getDoctrine()->getManager();
			$em->persist($task);
			$em->flush();

			$shoppingList->setIdTask($task->getId());
		}

		$em = $this->getDoctrine()->getManager();
		$em->persist($shoppingList);
		$em->flush();
		*/

		$entities = $em->getRepository('SfShoppingBundle:ShoppingList')->findByFoyer($foyers[$user->getCurrentFoyer()]);
		if(!$entities) { return new JsonResponse(array('data' => "fail")); }

		foreach($entities as $shoppingList){

			$articles = $shoppingList->getArticles();
			foreach($articles as $singleArticle){
				$article = array('articleId' => $singleArticle->getId(),
				'articleName' => $singleArticle->getName(),
					'articleQuantity' => $singleArticle->getQuantity(),
				);
				$finalArticles[] = $article;
				$article = array();
			}

		    $tab = array('listId' => $shoppingList->getId(),
			'listName' => $shoppingList->getName(),
			'listDeadline' => $shoppingList->getDeadline(),
			'articles' => $finalArticles,

			);
			$finalArticles = array();
			$article = array();

		    $final[] = $tab;
			$tab = array();
		}
        return new JsonResponse(array('entities' => $final));
    }

	public function newShoppingItemAction() // OK
    {
        $content = $this->get("request")->getContent();
        $params = json_decode($content);
        //Dans ton JSON, il faut : ID user
        $userId = $params->idUser;
		$shoppingListId = $params->idShoppingList;

        $shoppingItem = new Article;
        $shoppingItemName = $params->shoppingItemName;
        $shoppingItemQuantity = $params->shoppingItemQuantity;

        $em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('SfUserBundle:User')->findOneById($userId);
        $foyers = $user->getFoyers();
        $shoppingList = $em->getRepository('SfShoppingBundle:ShoppingList')->findOneBy(array('id' => $shoppingListId, 'foyer' => $foyers[$user->getCurrentFoyer()]));

		$shoppingList->setModificationDate(new \DateTime());
		$shoppingItem->setAddBy($user->getId());
		$shoppingItem->setName($shoppingItemName);
		$shoppingItem->setQuantity($shoppingItemQuantity);
		$shoppingList->addArticle($shoppingItem);

		$em = $this->getDoctrine()->getManager();
		$em->persist($shoppingList);
		$em->persist($shoppingItem);
		$em->flush();

		$entities = $em->getRepository('SfShoppingBundle:ShoppingList')->findByFoyer($foyers[$user->getCurrentFoyer()]);
		if(!$entities) { return new JsonResponse(array('data' => "fail")); }

		foreach($entities as $shoppingList){

			$articles = $shoppingList->getArticles();
			foreach($articles as $singleArticle){
				$article = array('articleId' => $singleArticle->getId(),
				'articleName' => $singleArticle->getName(),
					'articleQuantity' => $singleArticle->getQuantity(),
				);
				$finalArticles[] = $article;
				$article = array();
			}

		    $tab = array('listId' => $shoppingList->getId(),
			'listName' => $shoppingList->getName(),
			'listDeadline' => $shoppingList->getDeadline(),
			'articles' => $finalArticles,

			);
			$finalArticles = array();
			$article = array();

		    $final[] = $tab;
			$tab = array();
		}
        return new JsonResponse(array('entities' => $final));
    }

    public function editShoppingItemAction()
    {
        $content = $this->get("request")->getContent();
        $params = json_decode($content);
        $idUser = $params->idUser;
        $idShoppingItem = $params->idShoppingItem;
		$shoppingListId = $params->idShoppingList;

        $shoppingItemName = $params->shoppingItemName;
        $shoppingItemQuantity = $params->shoppingItemQuantity;

		$em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('SfUserBundle:User')->findOneById($idUser);
        $foyers = $user->getFoyers();
        $shoppingList = $em->getRepository('SfShoppingBundle:ShoppingList')->findOneBy(array('id' => $shoppingListId, 'foyer' => $foyers[$user->getCurrentFoyer()]));

		$shoppingItem = $em->getRepository('SfShoppingBundle:Article')->findOneById($idShoppingItem);

		$shoppingList->setModificationDate(new \DateTime());
		$shoppingItem->setName($shoppingItemName);
		$shoppingItem->setQuantity($shoppingItemQuantity);

		$em->persist($shoppingItem);
        $em->flush();

        $entities = $em->getRepository('SfShoppingBundle:ShoppingList')->findByFoyer($foyers[$user->getCurrentFoyer()]);
		if(!$entities) { return new JsonResponse(array('data' => "fail")); }

		foreach($entities as $shoppingList){

			$articles = $shoppingList->getArticles();
			foreach($articles as $singleArticle){
				$article = array('articleId' => $singleArticle->getId(),
				'articleName' => $singleArticle->getName(),
					'articleQuantity' => $singleArticle->getQuantity(),
				);
				$finalArticles[] = $article;
				$article = array();
			}

		    $tab = array('listId' => $shoppingList->getId(),
			'listName' => $shoppingList->getName(),
			'listDeadline' => $shoppingList->getDeadline(),
			'articles' => $finalArticles,

			);
			$finalArticles = array();
			$article = array();

		    $final[] = $tab;
			$tab = array();
		}
        return new JsonResponse(array('entities' => $final));
    }

    public function deleteShoppingItemAction()
    {
        $content = $this->get("request")->getContent();
        $params = json_decode($content);
        $idUser = $params->idUser;
        $idShoppingItem = $params->idShoppingItem;

		$em = $this->getDoctrine()->getManager();
        $user = $em->getRepository('SfUserBundle:User')->findOneById($idUser);
        $foyers = $user->getFoyers();

        $entity = $em->getRepository('SfShoppingBundle:Article')->findOneBy(array('id' => $idShoppingItem));
        $em->remove($entity);
        $em->flush();

        $entities = $em->getRepository('SfShoppingBundle:ShoppingList')->findByFoyer($foyers[$user->getCurrentFoyer()]);
		if(!$entities) { return new JsonResponse(array('data' => "fail")); }

		foreach($entities as $shoppingList){

			$articles = $shoppingList->getArticles();
			foreach($articles as $singleArticle){
				$article = array('articleId' => $singleArticle->getId(),
				'articleName' => $singleArticle->getName(),
					'articleQuantity' => $singleArticle->getQuantity(),
				);
				$finalArticles[] = $article;
				$article = array();
			}

		    $tab = array('listId' => $shoppingList->getId(),
			'listName' => $shoppingList->getName(),
			'listDeadline' => $shoppingList->getDeadline(),
			'articles' => $finalArticles,

			);
			$finalArticles = array();
			$article = array();

		    $final[] = $tab;
			$tab = array();
		}
        return new JsonResponse(array('entities' => $final));
    }
}


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

/**
 * @fileoverview Directive for a schema-based editor for custom values.
 */

require('domain/utilities/UrlInterpolationService.ts');
require('services/NestedDirectivesRecursionTimeoutPreventionService.ts');

angular.module('oppia').directive('schemaBasedCustomEditor', [
  'NestedDirectivesRecursionTimeoutPreventionService',
  'UrlInterpolationService',
  function(
      NestedDirectivesRecursionTimeoutPreventionService,
      UrlInterpolationService) {
    return {
      restrict: 'E',
      scope: {},
      bindToController: {
        localValue: '=',
        // The class of the object being edited.
        objType: '='
      },
      templateUrl: UrlInterpolationService.getDirectiveTemplateUrl(
        '/components/forms/schema-based-editors/' +
        'schema-based-custom-editor.directive.html'),
      controllerAs: '$ctrl',
      compile: NestedDirectivesRecursionTimeoutPreventionService.compile,
      controller: [function() {}]
    };
  }
]);

redpajama_set_name: RedPajamaGithub


text:
/*
 * JobFile.java
 */
package org.ngbw.sdk.jobs;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.util.Date;

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAccessType;

/**
 * @author Terri Liebowitz Schwartz
 *
 */
/*
	This class is the info that's returned to a caller about an input or output
	file related to the job.  The class is used both to return info about the
	files in a job's working directory, while the job is running, or the result
	files produced by the job and stored in the db, once the job has finished.

	Rest api will add the url that can be used to retrieve the contents of the file.
*/
/*
@XmlRootElement(name="details")
@XmlAccessorType(XmlAccessType.PROPERTY)
*/
public class JobFile
{
	private static final Log log = LogFactory.getLog(Job.class.getName());

	// not sure if there's any reason for both pathname and filename.
	private String jobHandle;
	private String pathname;
	private String filename;
	private long length;
	private Date dateCreated;
	private Date dateModified;

	// only used for result files:
	private String parameterName;

	// This is the primary key of the TaskOutputSourceDocument table.  You can
	// create a TaskOutputSourceDocument from it.
	private long outputDocumentId;

	public JobFile() {;}

	public String getJobHandle() { return jobHandle; }
	public String getPathname() { return pathname; }
	public String getFilename() { return filename; }
	public long getLength() { return length; }
	public Date getDateCreated() { return dateCreated; }
	public Date getDateModified() { return dateModified; }
	public String getParameterName() { return parameterName; }
	public long getOutputDocumentId() { return outputDocumentId; }

	public void setJobHandle(String i) { this.jobHandle = i; }
	public void setPathname(String pathname) { this.pathname = pathname; }
	public void setFilename(String filename) { this.filename = filename; }
	public void setLength(long length) { this.length = length; }
	public void setDateCreated(Date date) { this.dateCreated = date; }
	public void setDateModified(Date date) { this.dateModified = date; }
	public void setParameterName(String parameterName) { this.parameterName = parameterName; }
	public void setOutputDocumentId(long id) { this.outputDocumentId = id; }

}


text:
package com.puresoltechnologies.ductiledb.engine;

import java.io.File;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.puresoltechnologies.ductiledb.storage.spi.Storage;

public class NamespaceDescriptor {

    private final String name;
    private final File directory;

    /**
     * This is the primary constructor for the namespace. The namespace name is
     * determined by {@link File#getName()} of the namespace directory.
     *
     * @param storage
     *            is the {@link Storage} to be used to put the data to.
     * @param directory
     *            is the directory in the storage to be used to put data into
     *            which belongs to the namespace.
     */
    @JsonCreator
    public NamespaceDescriptor(@JsonProperty("directory") File directory) {
	this.directory = directory;
	this.name = directory.getName();
	if (!directory.isAbsolute()) {
	    throw new IllegalArgumentException("An absolute path to directory is needed.");
	}
    }

    @JsonIgnore
    public final String getName() {
	return name;
    }

    public final File getDirectory() {
	return directory;
    }

    @Override
    public String toString() {
	return "namespace:" + name;
    }

    @Override
    public int hashCode() {
	final int prime = 31;
	int result = 1;
	result = prime * result + ((directory == null) ? 0 : directory.hashCode());
	result = prime * result + ((name == null) ? 0 : name.hashCode());
	return result;
    }

    @Override
    public boolean equals(Object obj) {
	if (this == obj)
	    return true;
	if (obj == null)
	    return false;
	if (getClass() != obj.getClass())
	    return false;
	NamespaceDescriptor other = (NamespaceDescriptor) obj;
	if (directory == null) {
	    if (other.directory != null)
		return false;
	} else if (!directory.equals(other.directory))
	    return false;
	if (name == null) {
	    if (other.name != null)
		return false;
	} else if (!name.equals(other.name))
	    return false;
	return true;
    }

}


text:
<com.tle.beans.mime.MimeEntry>
  <id>413709</id>
  <institution>
    <id>413481</id>
    <enabled>true</enabled>
  </institution>
  <extensions class="list">
    <string>sty</string>
    <string>cat</string>
    <string>ent</string>
    <string>xml</string>
  </extensions>
  <type>text/xml</type>
  <attributes>
    <entry>
      <string>PluginIconPath</string>
      <string>icons/doc.png</string>
    </entry>
  </attributes>
</com.tle.beans.mime.MimeEntry>


text:
package org.apache.jackrabbit.test.api.version;

import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.ConstraintViolationException;
import javax.jcr.version.Version;
import javax.jcr.version.VersionManager;
import javax.jcr.ItemVisitor;
import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Property;
import javax.jcr.UnsupportedRepositoryOperationException;
import javax.jcr.ItemNotFoundException;
import javax.jcr.PropertyIterator;
import javax.jcr.Value;
import javax.jcr.PropertyType;
import javax.jcr.Repository;
import javax.jcr.lock.LockException;
import javax.jcr.lock.LockManager;

import java.util.GregorianCalendar;
import java.util.Calendar;
import java.util.List;
import java.util.Arrays;
import java.io.InputStream;
import java.io.ByteArrayInputStream;

/**
 * VersionTest covers tests related to the methods of the {@link
 * javax.jcr.version.Version} class.
 *
 */
public class VersionTest extends AbstractVersionTest {

    private VersionManager versionManager;
    private Version version;
    private Version version2;

    /**
     * helper class used in testAccept()
     */
    private class ItemVisitorTest implements ItemVisitor {

        Node ivtNode;

        public ItemVisitorTest(Version v) {
            ivtNode = v;
        }

        public void visit(Node node) throws RepositoryException {
            assertTrue("Version.accept(ItemVisitor) does not provide the right node to the ItemVisitor", ivtNode.isSame(node));
        }

        public void visit(Property property) throws RepositoryException {
        }
    }

    protected void setUp() throws Exception {
        super.setUp();

        versionManager = versionableNode.getSession().getWorkspace().getVersionManager();

        // create two versions
        version = versionManager.checkin(versionableNode.getPath());
        versionManager.checkout(versionableNode.getPath());
        version2 = versionManager.checkin(versionableNode.getPath());
    }

    protected void tearDown() throws Exception {
        // check the node out, so that it can be removed
        versionManager.checkout(versionableNode.getPath());
        version = null;
        version2 = null;
        super.tearDown();
    }

    /**
     * Tests if Version.accept(ItemVisitor) accepts a ItemVisitor
     * and if the right Node is provided to that visitor.
     */
    public void testAccept() throws Exception {
        ItemVisitorTest ivt = new ItemVisitorTest(version);
        version.accept(ivt);
    }

    /**
     * Tests if Version.addMixin(String) throws a {@link
     * javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testAddMixin() throws Exception {
        try {
            version.addMixin(mixVersionable);
            fail("Version should be read-only: Version.addMixin(String) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.addNode(String) and
     * Version.addNode(String, String) throw a {@link
     * javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testAddNode() throws Exception {
        try {
            version.addNode(nodeName4);
            version.getSession().save();
            fail("Version should be read-only: Version.addNode(String) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.addNode(nodeName4, ntBase);
            version.getSession().save();
            fail("Version should be read-only: Version.addNode(String,String) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.canAddMixin(String) returns
     * false
     */
    public void testCanAddMixin() throws Exception {
        assertFalse("Version should be read-only: Version.canAddMixin(String) returned true", version.canAddMixin(mixVersionable));
    }

    /**
     * Tests if Version.cancelMerge(Version) throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCancelMerge() throws Exception {
        try {
            version.cancelMerge(version2);
            fail("Version.cancelMerge(Version) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.cancelMerge(Version) throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCancelMergeJcr2() throws Exception {
        try {
            versionManager.cancelMerge(version.getPath(), version2);
            fail("Version.cancelMerge(Version) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.checkin() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCheckin() throws Exception {
        try {
            version.checkin();
            fail("Version.checkin() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.checkin() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCheckinJcr2() throws Exception {
        try {
            versionManager.checkin(version.getPath());
            fail("Version.checkin() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.checkout() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCheckout() throws Exception {
        try {
            version.checkout();
            fail("Version.checkout() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.checkout() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testCheckoutJcr2() throws Exception {
        try {
            versionManager.checkout(version.getPath());
            fail("Version.checkout() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.doneMerge(Version) throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testDoneMerge() throws Exception {
        try {
            version.doneMerge(version2);
            fail("Version should not be versionable: Version.doneMerge(Version) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.doneMerge(Version) throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testDoneMergeJcr2() throws Exception {
        try {
            versionManager.doneMerge(version.getPath(), version2);
            fail("Version should not be versionable: Version.doneMerge(Version) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.getAncestor(int) returns the right
     * ancestor
     */
    public void testGetAncestor() throws Exception {
        assertTrue("Version.getAncestor(int) does not work", superuser.getRootNode().isSame(version.getAncestor(0)));
    }

    /**
     * Tests if Version.getBaseVersion() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testGetBaseVersion() throws Exception {
        try {
            version.getBaseVersion();
            fail("Version.getBaseVersion() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.getBaseVersion() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testGetBaseVersionJcr2() throws Exception {
        try {
            versionManager.getBaseVersion(version.getPath());
            fail("Version.getBaseVersion() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.getCorrespondingNodePath(String) returns
     * the right path
     */
    public void testGetCorrespondingNodePath() throws Exception {
        assertEquals("Version.getCorrespondingNodePath(String) did not return the right path", version.getPath(), version.getCorrespondingNodePath(workspaceName));
    }

    /**
     * Tests if Version.getDepth() returns the right depth
     */
    public void testGetDepth() throws Exception {
        assertTrue("Version.getDepth() mismatch", version.getDepth() >= 4);
    }

    /**
     * Tests if Version.getIndex() returns the right index
     */
    public void testGetIndex() throws Exception {
        assertEquals("Version.getIndex() mismatch", 1, version.getIndex());
    }

    /**
     * Tests if Version.getLock() throws a {@link
     * javax.jcr.lock.LockException}
     */
    public void testGetLock() throws Exception {
        try {
            version.getLock();
            fail("Version should not be lockable: Version.getLock() did not throw a LockException");
        } catch (LockException success) {
        } catch (UnsupportedRepositoryOperationException maybe) {
            assertFalse(isSupported(Repository.OPTION_LOCKING_SUPPORTED));
        }
    }

    /**
     * Tests if Version.getLock() throws a {@link
     * javax.jcr.lock.LockException}
     */
    public void testGetLockJcr2() throws Exception {
        ensureLockingSupported();
        try {
            version.getSession().getWorkspace().getLockManager().getLock(version.getPath());
            fail("Version should not be lockable: Version.getLock() did not throw a LockException");
        } catch (LockException success) {
        }
    }

    /**
     * Tests if Version.getMixinNodeTypes() does not return null.
     */
    public void testGetMixinNodeTypes() throws Exception {
        NodeType[] ntArray = version.getMixinNodeTypes();
        assertNotNull("Version.getMixinNodeTypes returns null array", ntArray);
    }

    /**
     * Tests if Version.getName() returns the right name
     */
    public void testGetName() throws Exception {
        assertTrue("Version.getName() does not return the right name", versionableNode.getVersionHistory().getVersion(version.getName()).isSame(version));
    }

    /**
     * Tests if Version.getNode(String) returns the right child
     * Node
     */
    public void testGetNode() throws Exception {
        assertTrue("Version.getNode(String) does not return a sub-node of type nt:frozenNode", version.getNode(jcrFrozenNode).isNodeType(ntFrozenNode));
    }

    /**
     * Tests if Version.getNodes() and Version.getNodes(String)
     * returns the right child Node
     */
    public void testGetNodes() throws Exception {
        assertTrue("Version.getNodes() does not return a sub-node of type nt:frozenNode", version.getNodes().nextNode().isNodeType(ntFrozenNode));
        assertTrue("Version.getNodes(String) does not return a sub-node of type nt:frozenNode", version.getNodes(superuser.getNamespacePrefix(NS_JCR_URI) + ":*").nextNode().isNodeType(ntFrozenNode));
    }

    /**
     * Tests if Version.getParent() returns the right parent Node
     */
    public void testGetParent() throws Exception {
        assertTrue("Version.getParent() does not return a parent-node of type nt:versionHistory", version.getParent().isNodeType(ntVersionHistory));
    }

    /**
     * Tests if Version.getPath() returns the right path
     */
    public void testGetPath() throws Exception {
        assertTrue("Version.getPath() does not return the right path", version.getPath().startsWith("/" + superuser.getNamespacePrefix(NS_JCR_URI) + ":system/" + superuser.getNamespacePrefix(NS_JCR_URI) + ":versionStorage/"));
    }

    /**
     * Tests if Version.getPrimaryItem() throws a {@link
     * javax.jcr.ItemNotFoundException}
     */
    public void testGetPrimaryItem() throws Exception {
        try {
            version.getPrimaryItem();
            fail("Version.getPrimaryItem() did not throw a ItemNotFoundException");
        } catch (ItemNotFoundException success) {
        }
    }

    /**
     * Tests if Version.getPrimaryNodeType() returns the right
     * primary node type nt:version
     */
    public void testGetPrimaryNodeType() throws Exception {
        assertEquals("Version does not have the primary node type nt:version", ntVersion, version.getPrimaryNodeType().getName());
    }

    /**
     * Tests if Version.getProperties() and
     * Version.getProperties(String) return the right property
     */
    public void testGetProperties() throws Exception {
        PropertyIterator pi = version.getProperties();
        boolean hasPropertyCreated = false;
        while (pi.hasNext()) {
            if (pi.nextProperty().getName().equals(jcrCreated)) {
                hasPropertyCreated = true;
            }
        }
        assertTrue("Version.getProperties() does not return property jcr:created", hasPropertyCreated);

        pi = version.getProperties(superuser.getNamespacePrefix(NS_JCR_URI) + ":*");
        hasPropertyCreated = false;
        while (pi.hasNext()) {
            if (pi.nextProperty().getName().equals(jcrCreated)) {
                hasPropertyCreated = true;
            }
        }
        assertTrue("Version.getProperties(String) does not return property jcr:created", hasPropertyCreated);
    }

    /**
     * Tests if Version.getProperty(String) returns the right
     * property
     */
    public void testGetProperty() throws Exception {
        assertTrue("Version.getProperty(String) does not return property jcr:created", version.getProperty(jcrCreated).getName().equals(jcrCreated));
    }

    /**
     * Tests if Version.getSession() returns the right session
     */
    public void testGetSession() throws Exception {
        assertSame("Version.getSession() did not return the right session", superuser, version.getSession());
    }

    /**
     * Tests if Version.getVersionHistory() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testGetVersionHistory() throws Exception {
        try {
            version.getVersionHistory();
            fail("Version.getVersionHistory() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.getVersionHistory() throws an {@link
     * javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testGetVersionHistoryJcr2() throws Exception {
        try {
            versionManager.getVersionHistory(version.getPath());
            fail("Version.getVersionHistory() did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.getUUID() returns the right UUID
     */
    public void testGetUUID() throws Exception {
        List<Value> successorValues = Arrays.asList(versionableNode.getVersionHistory().getRootVersion().getProperty(jcrSuccessors).getValues());
        assertTrue("Version.getUUID() did not return the right UUID", successorValues.contains(superuser.getValueFactory().createValue(version)));
    }

    /**
     * Tests if Version.hasNode(String) returns the right
     * boolean value
     */
    public void testHasNode() throws Exception {
        assertTrue("Version.hasNode(String) did not return true", version.hasNode(jcrFrozenNode));
    }

    /**
     * Tests if Version.hasNodes() returns true
     */
    public void testHasNodes() throws Exception {
        assertTrue("Version.hasNodes() did not return true", version.hasNodes());
    }

    /**
     * Tests if Version.hasProperties() returns true
     */
    public void testHasProperties() throws Exception {
        assertTrue("Version.hasProperties() did not return true", version.hasProperties());
    }

    /**
     * Tests if Version.hasProperty(String) returns the right
     * boolean value
     */
    public void testHasProperty() throws Exception {
        assertTrue("Version.hasProperty(String) did not return true", version.hasProperty(jcrCreated));
    }

    /**
     * Tests if Version.holdsLock() returns false
     */
    public void testHoldsLock() throws Exception {
        ensureLockingSupported();
        assertFalse("Version.holdsLock() did not return false", version.holdsLock());
    }

    /**
     * Tests if Version.holdsLock() returns false
     */
    public void testHoldsLockJcr2() throws Exception {
        ensureLockingSupported();
        assertFalse("Version.holdsLock() did not return false", version.getSession().getWorkspace().getLockManager().holdsLock(version.getPath()));
    }

    /**
     * Tests if Version.isCheckedOut() returns true
     */
    public void testIsCheckedOut() throws Exception {
        assertTrue("Version.isCheckedOut() did not return true", version.isCheckedOut());
    }

    /**
     * Tests if Version.isCheckedOut() returns true
     */
    public void testIsCheckedOutJcr2() throws Exception {
        assertTrue("Version.isCheckedOut() did not return true", versionManager.isCheckedOut(version.getPath()));
    }

    /**
     * Tests if Version.isLocked() returns false
     */
    public void testIsLocked() throws Exception {
        assertFalse("Version.isLocked() did not return false", version.isLocked());
    }

    /**
     * Tests if Version.isLocked() returns false
     */
    public void testIsLockedJcr2() throws Exception {
        ensureLockingSupported();
        assertFalse("Version.isLocked() did not return false", version.getSession().getWorkspace().getLockManager().isLocked(version.getPath()));
    }

    /**
     * Tests if Version.isModified() returns false
     */
    public void testIsModified() throws Exception {
        assertFalse("Version.isModified() did not return false", version.isModified());
    }

    /**
     * Tests if Version.isNew() returns false
     */
    public void testIsNew() throws Exception {
        assertFalse("Version.isNew() did not return false", version.isNew());
    }

    /**
     * Tests if Version.isNode() returns true
     */
    public void testIsNode() throws Exception {
        assertTrue("Version.isNode() did not return true", version.isNode());
    }

    /**
     * Tests if Version.isNodeType(String) returns the right
     * boolean value
     */
    public void testIsNodeType() throws Exception {
        assertTrue("Version.isNodeType(String) did not return true for nt:version", version.isNodeType(ntVersion));
    }

    /**
     * Tests if Version.isSame() returns the right
     * boolean value
     */
    public void testIsSame() throws Exception {
        assertTrue("Version.isSame(Item) did not return true", version2.isSame(versionableNode.getBaseVersion()));
    }

    /**
     * Tests if Version.isSame() returns the right
     * boolean value
     */
    public void testIsSameJcr2() throws Exception {
        assertTrue("Version.isSame(Item) did not return true", version2.isSame(versionManager.getBaseVersion(versionableNode.getPath())));
    }

    /**
     * Tests if Version.lock(boolean, boolean) throws a {@link
     * LockException}
     */
    public void testLock() throws Exception {
        ensureLockingSupported();
        try {
            version.lock(true, true);
            fail("Version should not be lockable: Version.lock(true,true) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            version.lock(true, false);
            fail("Version should not be lockable: Version.lock(true,false) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            version.lock(false, true);
            fail("Version should not be lockable: Version.lock(false,true) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            version.lock(false, false);
            fail("Version should not be lockable: Version.lock(false,false) did not throw a LockException");
        } catch (LockException success) {
        }
    }

    /**
     * Tests if Version.lock(boolean, boolean) throws a {@link
     * LockException}
     */
    public void testLockJcr2() throws Exception {
        ensureLockingSupported();
        LockManager lockManager = version.getSession().getWorkspace().getLockManager();
        String path = version.getPath();
        try {
            lockManager.lock(path, true, true, 60, "");
            fail("Version should not be lockable: Version.lock(true,true) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            lockManager.lock(path, true, false, 60, "");
            fail("Version should not be lockable: Version.lock(true,false) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            lockManager.lock(path, false, true, 60, "");
            fail("Version should not be lockable: Version.lock(false,true) did not throw a LockException");
        } catch (LockException success) {
        }
        try {
            lockManager.lock(path, false, false, 60, "");
            fail("Version should not be lockable: Version.lock(false,false) did not throw a LockException");
        } catch (LockException success) {
        }
    }

    /**
     * Tests if Version.merge(String) throws an
     * {@link javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testMerge() throws Exception {
        try {
            version.merge(workspaceName, true);
            fail("Version.merge(String, true) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.merge(workspaceName, false);
            fail("Version.merge(String, false) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.merge(String) throws an
     * {@link javax.jcr.nodetype.ConstraintViolationException}
     */
/*
    TODO: check why this fails
    public void testMergeJcr2() throws Exception {
        try {
            versionManager.merge(version.getPath(), workspaceName, true);
            fail("Version.merge(String, true) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            versionManager.merge(version.getPath(),workspaceName, false);
            fail("Version.merge(String, false) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }
*/
    /**
     * Tests if Version.orderBefore(String, String) throws an
     * {@link javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testOrderBefore() throws Exception {
        try {
            version.orderBefore(jcrFrozenNode, null);
            fail("Version.orderBefore(String,String) did not throw an UnsupportedRepositoryOperationException or a ConstraintViolationException");
        } catch (UnsupportedRepositoryOperationException success) {
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.refresh(boolean) works as expected (do
     * nothing and return quietly)
     */
    public void testRefresh() throws Exception {
        // should do nothing and return quietly
        version.refresh(true);
        version.refresh(false);
    }

    /**
     * Tests if Version.remove() throws an {@link
     * javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testRemove() throws Exception {
        try {
            version.remove();
            versionableNode.getSession().save();
            fail("Version should be read-only: Version.remove() did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.removeMixin(String) throws an {@link
     * javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testRemoveMixin() throws Exception {
        try {
            version.removeMixin(mixVersionable);
            fail("Version should be read-only: Version.removeMixin(String) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.restore(String, boolean) and
     * Version.restore(Version, boolean) throw an
     * {@link UnsupportedRepositoryOperationException} and
     * Version.restore(Version, String, boolean) throws a
     * {@link ConstraintViolationException}.
     */
    public void testRestore() throws Exception {
        try {
            version.restore("abc", true);
            fail("Version.restore(String,boolean) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
        try {
            version.restore(version2, true);
            fail("Version.restore(Version,boolean) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
        try {
            version.restore(version2, "abc", true);
            fail("Version.restore(Version,String,boolean) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.restore(String, boolean) and
     * Version.restore(Version, boolean) throw an
     * {@link UnsupportedRepositoryOperationException} and
     * Version.restore(Version, String, boolean) throws a
     * {@link ConstraintViolationException}.
     */
    public void testRestoreJcr2() throws Exception {
        try {
            versionManager.restore(version.getPath(), "abc", true);
            fail("Version.restore(String,boolean) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.restoreByLabel(String, boolean) throws an
     * {@link javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testRestoreByLabel() throws Exception {
        try {
            version.restoreByLabel("abc", true);
            fail("Version.restoreByLabel(String,boolean) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if Version.restoreByLabel(String, boolean) throws an
     * {@link javax.jcr.UnsupportedRepositoryOperationException}
     */
    public void testRestoreByLabelJcr2() throws Exception {
        try {
            versionManager.restoreByLabel(version.getPath(), "abc", true);
            fail("Version.restoreByLabel(String,boolean) did not throw an UnsupportedRepositoryOperationException");
        } catch (UnsupportedRepositoryOperationException success) {
        }
    }

    /**
     * Tests if
     *

Version.setProperty(String, String[])

     *
Version.setProperty(String, String[], int)

     *
Version.setProperty(String, Value[])

     *
Version.setProperty(String, Value[], int)

     *
Version.setProperty(String, boolean)

     *
Version.setProperty(String, double)

     *
Version.setProperty(String, InputStream)

     *
Version.setProperty(String, String)

     *
Version.setProperty(String, Calendar)

     *
Version.setProperty(String, Node)

     *
Version.setProperty(String, Value)

     *
Version.setProperty(String, long)

     *
 all throw a
     * {@link javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testSetProperty() throws Exception {

        // create Value[] object
        Value[] vArray = new Value[3];
        vArray[0] = superuser.getValueFactory().createValue("abc");
        vArray[1] = superuser.getValueFactory().createValue("xyz");
        vArray[2] = superuser.getValueFactory().createValue("123");

        // create String array
        String[] s = {"abc", "xyz", "123"};

        try {
            version.setProperty(propertyName1, s);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,String[]) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, s, PropertyType.STRING);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,String[],int) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, vArray);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,Value[]) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, vArray, PropertyType.STRING);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,Value[],int]) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, true);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,boolean) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, 123);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,double) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            byte[] bytes = {73, 26, 32, -36, 40, -43, -124};
            InputStream inpStream = new ByteArrayInputStream(bytes);
            version.setProperty(propertyName1, inpStream);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,InputStream) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, "abc");
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,String) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            Calendar c = new GregorianCalendar(1945, 1, 6, 16, 20, 0);
            version.setProperty(propertyName1, c);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,Calendar) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, version);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,Node) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            Value v = superuser.getValueFactory().createValue("abc");
            version.setProperty(propertyName1, v);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,Value) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
        try {
            version.setProperty(propertyName1, -2147483650L);
            version.getSession().save();
            fail("Version should be read-only: Version.setProperty(String,long) did not throw a ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if Version.unlock() throws a {@link
     * javax.jcr.lock.LockException}
     */
    public void testUnlock() throws Exception {
        try {
            version.unlock();
            fail("Version should not be lockable: Version.unlock() did not throw a LockException");
        } catch (LockException success) {
        } catch (UnsupportedRepositoryOperationException maybe) {
            assertFalse(isSupported(Repository.OPTION_LOCKING_SUPPORTED));
        }
    }

    /**
     * Tests if Version.unlock() throws a {@link
     * javax.jcr.lock.LockException}
     */
    public void testUnlockJcr2() throws Exception {
        ensureLockingSupported();
        try {
            version.getSession().getWorkspace().getLockManager().unlock(version.getPath());
            fail("Version should not be lockable: Version.unlock() did not throw a LockException");
        } catch (LockException success) {
        }
    }

    /**
     * Tests if VersionHistory.update(String) throws an
     * {@link javax.jcr.nodetype.ConstraintViolationException}
     */
    public void testUpdate() throws Exception {
        try {
            version.update(workspaceName);
            fail("VersionHistory.update(String) did not throw an ConstraintViolationException");
        } catch (ConstraintViolationException success) {
        }
    }

    /**
     * Tests if the jcr:frozenUuid property has the correct type
     * @throws Exception
     */
    public void testFrozenUUID() throws Exception {
        Property p = version.getNode(jcrFrozenNode).getProperty(jcrFrozenUuid);
        assertEquals("jcr:fronzenUuid should be of type string", PropertyType.TYPENAME_STRING, PropertyType.nameFromValue(p.getType()));
    }
}


text:
package com.github.danzx.zekke.persistence.internal.mongo;

import static org.assertj.core.api.Assertions.assertThat;

import javax.inject.Inject;

import com.github.danzx.zekke.test.mongo.BaseSpringMongoTest;

import org.junit.Test;

public class MongoSequenceManagerTest extends BaseSpringMongoTest {

    private static final MongoSequence TEST_SEQUENCE = MongoSequence.WAYPOINT_ID;

    @Inject private MongoSequenceManager sequenceManager;

    @Override
    public void before() throws Exception {
        super.before();
        assertThat(sequenceManager).isNotNull();
    }

    @Test
    public void shouldRetunCurrentValue() {
        long currentValue = sequenceManager.getCurrentSequenceValue(TEST_SEQUENCE);
        assertThat(currentValue).isEqualTo(8L);
    }

    @Test
    public void shouldSetValue() {
        long newValue = 666L;
        sequenceManager.setSequenceValue(TEST_SEQUENCE, newValue);
        long currentValue = sequenceManager.getCurrentSequenceValue(TEST_SEQUENCE);
        assertThat(currentValue).isEqualTo(newValue);
    }

    @Test
    public void shouldRetunNextValue() {
        long currentValue = sequenceManager.getNextSequenceValue(TEST_SEQUENCE);
        assertThat(currentValue).isEqualTo(9L);
    }
}


text:
import logging
import re

from streamlink.plugin import Plugin
from streamlink.plugin.api import useragents, validate
from streamlink.plugin.api.utils import itertags
from streamlink.stream import HLSStream
from streamlink.utils import parse_json

log = logging.getLogger(__name__)

class Reuters(Plugin):
    _url_re = re.compile(r'https?://(?:www\.)?reuters\.tv')
    _hls_re = re.compile(r'''(?<!')https://[^"';!<>]+\.m3u8''')
    _json_re = re.compile(r'''(?P<data>{.*});''')
    _data_schema = validate.Schema(
        validate.transform(_json_re.search),
        validate.any(
            None,
            validate.all(
                validate.get('data'),
                validate.transform(parse_json),
                {
                    'title': validate.text,
                    'items': [
                        {
                            'title': validate.text,
                            'type': validate.text,
                            'resources': [
                                {
                                    'mimeType': validate.text,
                                    'uri': validate.url(),
                                    validate.optional('protocol'): validate.text,
                                    validate.optional('entityType'): validate.text,
                                }
                            ]
                        }
                    ],
                }
            )
        )
    )

    def __init__(self, url):
        super(Reuters, self).__init__(url)
        self.session.http.headers.update({'User-Agent': useragents.FIREFOX})
        self.title = None

    @classmethod
    def can_handle_url(cls, url):
        return cls._url_re.match(url) is not None

    def get_title(self):
        if not self.title:
            self._get_data()
        return self.title

    def _get_data(self):
        res = self.session.http.get(self.url)
        for script in itertags(res.text, 'script'):
            if script.attributes.get('type') == 'text/javascript' and 'RTVJson' in script.text:
                data = self._data_schema.validate(script.text)
                if not data:
                    continue
                self.title = data['title']
                for item in data['items']:
                    if data['title'] == item['title']:
                        log.trace('{0!r}'.format(item))
                        log.debug('Type: {0}'.format(item['type']))
                        for res in item['resources']:
                            if res['mimeType'] == 'application/x-mpegURL':
                                return res['uri']

        # fallback
        for title in itertags(res.text, 'title'):
            self.title = title.text
        m = self._hls_re.search(res.text)
        if not m:
            log.error('Unsupported PageType.')
            return
        return m.group(0)

    def _get_streams(self):
        hls_url = self._get_data()
        if not hls_url:
            return
        log.debug('URL={0}'.format(hls_url))
        return HLSStream.parse_variant_playlist(self.session, hls_url)

__plugin__ = Reuters


text:
int main(int argc, char** argv)
{
  ROS_INFO("vision_test_node starting...");
  ros::init(argc, argv, "vision_test_node");
  ros::NodeHandle n;
  vision_test test_handle(n);

  ROS_INFO("vision_test_node ready...");

  while(ros::ok())
  {
    ros::spinOnce();
  }

}


text:
import jestMock from 'jest-mock';
import {act, render} from '@testing-library/preact';

import {timers} from '../../core/test/test-env/fake-timers.js';
import {FlowStepThumbnail} from '../src/common';

let lhr: LH.Result;

timers.useFakeTimers();

describe('FlowStepThumbnail', () => {
  beforeEach(() => {
    global.console.warn = jestMock.fn();

    lhr = {
      gatherMode: 'navigation',
      configSettings: {screenEmulation: {width: 400, height: 600}},
      audits: {
        'full-page-screenshot': {
          details: {
            type: 'full-page-screenshot',
            screenshot: {data: 'FPS', width: 400, height: 600},
            nodes: {},
          },
        },
        'screenshot-thumbnails': {
          details: {
            type: 'filmstrip',
            items: [
              {data: 'frame1'},
              {data: 'frame2'},
            ],
          },
        },
      },
    } as any;
  });

  it('renders a thumbnail', () => {
    const root = render(<FlowStepThumbnail lhr={lhr} width={200} height={200} />);

    const thumbnail = root.getByAltText(/Screenshot/);
    expect(thumbnail.style.width).toEqual('200px');
    expect(thumbnail.style.height).toEqual('200px');
  });

  it('renders nothing without dimensions', () => {
    const root = render(<FlowStepThumbnail lhr={lhr} />);

    expect(() => root.getByAltText(/Screenshot/)).toThrow();
    expect(global.console.warn).toHaveBeenCalled();
  });

  it('interpolates height', () => {
    const root = render(<FlowStepThumbnail lhr={lhr} width={200} />);

    const thumbnail = root.getByAltText(/Screenshot/);
    expect(thumbnail.style.width).toEqual('200px');
    expect(thumbnail.style.height).toEqual('300px');
  });

  it('interpolates width', () => {
    const root = render(<FlowStepThumbnail lhr={lhr} height={150} />);

    const thumbnail = root.getByAltText(/Screenshot/);
    expect(thumbnail.style.width).toEqual('100px');
    expect(thumbnail.style.height).toEqual('150px');
  });

  it('uses last filmstrip thumbnail', () => {
    const root = render(<FlowStepThumbnail lhr={lhr} height={150} />);

    const thumbnail = root.getByAltText(/Screenshot/) as HTMLImageElement;
    expect(thumbnail.src).toContain('frame2');
  });

  it('uses full page screenshot if filmstrip unavailable', () => {
    delete lhr.audits['screenshot-thumbnails'];
    const root = render(<FlowStepThumbnail lhr={lhr} height={150} />);

    const thumbnail = root.getByAltText(/Screenshot/) as HTMLImageElement;
    expect(thumbnail.src).toContain('FPS');
  });

  it('renders animated thumbnail for timespan', async () => {
    lhr.gatherMode = 'timespan';
    const root = render(<FlowStepThumbnail lhr={lhr} height={150} />);

    const thumbnail = root.getByAltText(/Animated/) as HTMLImageElement;
    expect(thumbnail.style.width).toEqual('100px');
    expect(thumbnail.style.height).toEqual('150px');

    expect(thumbnail.src).toContain('frame1');
    await act(() => {
      timers.advanceTimersByTime(501);
    });
    expect(thumbnail.src).toContain('frame2');
  });
});


text:
DifficultyRecipes [![Build Status](http://ci.tterrag.com/job/CustomThings/badge/icon)](http://ci.tterrag.com/job/DifficultyRecipes/)
============

Allows easy creation of recipes which can change based on the current world difficulty.


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="ButtonStyle" parent="Base.Widget.AppCompat.Button.Colored">
        <item name="colorButtonNormal">@color/colorAccent</item>
    </style>

    <!-- 二级头部设置 -->
    <style name="homebac2">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">50dp</item>
        <item name="android:background">@android:color/white</item>
    </style>

    <!-- 二级头 -->
    <style name="TextTheme">
        <item name="android:layout_centerVertical">true</item>
        <item name="android:layout_centerHorizontal">true</item>
        <item name="android:singleLine">true</item>
        <item name="android:textSize">22dp</item>
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>


text:
@interface PeerViewController ()
@property (nonatomic, retain) PlayerController *playerController;
@property (nonatomic, retain) NSMutableArray *peers;
@property (nonatomic, retain) NSMutableDictionary *imageCache;

- (void)shrinkLabel:(UILabel *)label;
@end

@implementation PeerViewController

@synthesize
tableViewCell = tableViewCell_,
contentView = contentView_,
peers = peers_,
mainController = mainController,
imageCache = imageCache_,
playerController = playerController_;

+ (BSInitializer *)blinsideInitializer {
    return [BSInitializer initializerWithClass:self
                                      selector:@selector(initWithPlayerController:)
                                  argumentKeys:[PlayerController class], nil];
}

+ (NSDictionary *)blindsideProperties {
    return [NSDictionary dictionaryWithObjectsAndKeys:[MainController class], [MainController class], nil];
}

- (id)initWithPlayerController:(PlayerController *)playerController {
    if (self = [super init]) {
        self.playerController = playerController;
        self.peers = [NSMutableArray array];
        self.imageCache = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)dealloc {
    self.peers = nil;
    self.playerController = nil;
    self.imageCache = nil;
    [super dealloc];
}

- (void)viewDidLoad {
    self.tableView.backgroundColor = [UIColor colorWithRed:163/255.0 green:179/255.0 blue:193/255.0 alpha:1.0];
    self.tableView.separatorColor = [UIColor colorWithRed:163/255.0 green:179/255.0 blue:193/255.0 alpha:1.0];
}

#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.peers.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"PeerCell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        [[NSBundle mainBundle] loadNibNamed:@"TrackView" owner:self options:nil];
        cell = self.tableViewCell;
        [cell.contentView addSubview:self.contentView];
        self.tableViewCell = nil;
        self.contentView = nil;
    } else {
        AsyncImageView* oldArtistImage = (AsyncImageView*) [cell.contentView viewWithTag:999];
        [oldArtistImage removeFromSuperview];
        AsyncImageView* oldPeerImage = (AsyncImageView*) [cell.contentView viewWithTag:998];
        [oldPeerImage removeFromSuperview];
    }

    UIView *realContentView = [cell.contentView.subviews lastObject];
    UILabel *topLabel    = (UILabel *)[realContentView viewWithTag:1];
    UILabel *bottomLabel = (UILabel *)[realContentView viewWithTag:2];
    [self shrinkLabel:topLabel];
    [self shrinkLabel:bottomLabel];

    Peer *peer = [self.peers objectAtIndex:indexPath.row];

    CGRect frame = CGRectMake(5, 4, 30, 30);
	AsyncImageView* artistImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
	artistImage.tag = 999;
	[artistImage loadImageFromURL:[NSURL URLWithString:peer.track.iconURL] withCache:self.imageCache];
	[realContentView addSubview:artistImage];

    frame = CGRectMake(285, 4, 30, 30);
	AsyncImageView* peerImage = [[[AsyncImageView alloc] initWithFrame:frame] autorelease];
	peerImage.tag = 998;
	[peerImage loadImageFromURL:[NSURL URLWithString:peer.iconURL] withCache:self.imageCache];
	cell.accessoryView = peerImage;

    if (peer.track != nil) {
        topLabel.text = peer.track.name;
        bottomLabel.text = peer.track.artist;
    } else {
        topLabel.text = peer.name;
        bottomLabel.text = @"";
    }

    return cell;
}

- (void)shrinkLabel:(UILabel *)label {
    CGRect frame = label.frame;
    label.frame = CGRectMake(frame.origin.x, frame.origin.y, 240, frame.size.height);
}

#pragma mark PeerWatcherDelegage

- (void)peerDidLeave:(Peer *)peer {
    [self.peers removeObject:peer];
    [self.tableView reloadData];
}

- (void)allPeersDidLeave {
    NSLog(@"allPeersDidLeave; removing all objects");
    [self.peers removeAllObjects];
    [self.tableView reloadData];
}

- (void)peerDidArrive:(Peer *)peer {
    NSUInteger index = [self.peers indexOfObject:peer];
    if (index == NSNotFound) {
        [self.peers addObject:peer];
    } else {
        [self.peers replaceObjectAtIndex:index withObject:peer];
    }

    [self.tableView reloadData];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    Peer *peer = [self.peers objectAtIndex:indexPath.row];
    if (peer.track != nil) {
        [self.playerController playTrack:peer.track];
    }
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"accessory button tapped");
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 40;
}

@end


text:
namespace sim {

// Wrapper for the static call to State::getInstance()
class State;
State* S();

class State {

public:

    // Returns a pointer to the singleton state object
    static State* getInstance();

    std::string runId();
    void setRunId(const std::string& runId);

    bool crashed();
    void setCrashed();

    LayoutType layoutType();
    void setLayoutType(LayoutType layoutType);

    bool rotateZoomedMap();
    void setRotateZoomedMap(bool rotateZoomedMap);

    double zoomedMapScale();
    void setZoomedMapScale(double zoomedMapScale);

    bool wallTruthVisible();
    void setWallTruthVisible(bool wallTruthVisible);

    bool tileColorsVisible();
    void setTileColorsVisible(bool tileColorsVisible);

    bool tileFogVisible();
    void setTileFogVisible(bool tileFogVisible);

    bool tileTextVisible();
    void setTileTextVisible(bool tileTextVisible);

    bool tileDistanceVisible();
    void setTileDistanceVisible(bool tileDistanceVisible);

    bool headerVisible();
    void setHeaderVisible(bool headerVisible);

    bool wireframeMode();
    void setWireframeMode(bool wireframeMode);

    bool paused();
    void setPaused(bool paused);

    double simSpeed();
    void setSimSpeed(double simSpeed);

    bool inputButtonWasPressed(int inputButton);
    void setInputButtonWasPressed(int inputButton, bool pressed);

    bool arrowKeyIsPressed(Key key);
    void setArrowKeyIsPressed(Key key, bool pressed);

private:

    // A private constructor is used to ensure only one instance of this class exists
    State();

    // A pointer to the actual instance of the class
    static State* INSTANCE;

    std::string m_runId;
    bool m_crashed;
    LayoutType m_layoutType;
    bool m_rotateZoomedMap;
    double m_zoomedMapScale;
    bool m_wallTruthVisible;
    bool m_tileColorsVisible;
    bool m_tileFogVisible;
    bool m_tileTextVisible;
    bool m_tileDistanceVisible;
    bool m_headerVisible;
    bool m_wireframeMode;
    bool m_paused;
    double m_simSpeed;
    std::map<int, bool> m_inputButtons;
    std::map<Key, bool> m_arrowKeys;

    // Returns true if defaultValue lies between current and next
    bool crossesDefault(double current, double next, double defaultValue);
};

} // namespace sim


text:
	<a href="<?php echo site_url('auction')?>"><img src="<?php echo base_url('assets/images/login-regas-logo.jpg');?>">

<a href="<?php echo site_url('auction')?>">Welcome, <?php echo $name?>

<a href="<?php echo site_url('main/logout')?>"> Keluar


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Elaphomyces sulphureopallidus Vacek

### Remarks
null


text:
    <button type="button" class="close" data-dismiss="modal" aria-label="Close" ng-click="close()">
        ×</button>

{{'COMMON.FILTER_GROUP'|translate}}

                {{'CONFIG.WIDGET.COLUMN'|translate}}

                {{o.alias?o.alias:o.column}}

                {{'CONFIG.WIDGET.FILTER'|translate}}

                            <button type="button" class="btn btn-default btn-sm"
                                    style="cursor: move;">
                                {{o.col}}
                            </button>
                            <button type="button"
                                    class="btn btn-default btn-sm dropdown-toggle"
                                    ng-click="editFilter(o)">

                            </button>
                            <button type="button"
                                    class="btn btn-default btn-sm dropdown-toggle"
                                    ng-click="data.filters.splice($index, 1)">

                            </button>

                {{'CONFIG.WIDGET.ALIAS'|translate}}

                    <input class="form-control" ng-model="data.group">

    <button type="button" class="btn btn-default pull-left" data-dismiss="modal" ng-click="close()">
        {{'COMMON.CANCEL'|translate}}
    </button>
    <button type="button" class="btn btn-primary" ng-click="ok()">{{'COMMON.OK'|translate}}</button>


text:
package com.baasbox.android;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import com.baasbox.android.impl.DiskLruCache;
import com.baasbox.android.impl.Logger;

import java.io.*;

/**
 * Created by Andrea Tortorella on 05/02/14.
 */
final class Cache {
// ------------------------------ FIELDS ------------------------------

    private static final String BAASBOX_CACHE_DIR = "baasbox-cache-dir";
    private static final long MAX_CACHE_SIZE = 10 * 1024 * 1024;

    private final DiskLruCache mLruCache;

// --------------------------- CONSTRUCTORS ---------------------------
    Cache(Context context) {
        try {
            mLruCache = DiskLruCache.open(getCacheDir(context),
                    appVersion(context),
                    1,
                    MAX_CACHE_SIZE);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private static File getCacheDir(Context context) {
        return new File(context.getCacheDir(), BAASBOX_CACHE_DIR);
    }

    private static int appVersion(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            throw new AssertionError(e);
        }
    }

// -------------------------- OTHER METHODS --------------------------

    public CacheStream beginStream(String id) throws BaasException {
        DiskLruCache.Editor editor = null;
        OutputStream out = null;
        try {
            editor = mLruCache.edit(id);
            out = editor.newOutputStream(0);
            return new CacheStream(out, editor);
        } catch (IOException e) {
            throw new BaasIOException(e);
        }
    }

    public byte[] get(String id) {
        DiskLruCache.Snapshot s = null;
        DataInputStream din = null;

        try {
            s = mLruCache.get(id);
            if (s == null) return null;
            int len = (int) s.getLength(0);
            byte[] bytes = new byte[len];
            din = new DataInputStream(s.getInputStream(0));
            din.readFully(bytes);
            return bytes;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (din != null) {
                try {
                    din.close();
                } catch (IOException e) {
                    // ignored
                }
            }

            if (s != null) {
                s.close();
            }
        }
    }

    public BaasStream getStream(String id) throws BaasIOException {
        DiskLruCache.Snapshot s = null;
        try {
            s = mLruCache.get(id);
            if (s == null) return null;
            return new BaasStream(id, s);
        } catch (IOException e) {
            throw new BaasIOException("Error while reading from cache", e);
        }
    }

    public void put(String id, byte[] data) {
        DiskLruCache.Editor edit = null;
        OutputStream out = null;
        try {
            edit = mLruCache.edit(id);
            out = edit.newOutputStream(0);
            out.write(data);
            out.flush();
            edit.commit();
        } catch (IOException e) {
            Logger.error(e, "Error using cache");
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // ignored
                }
            }
            if (edit != null) {
                edit.abortUnlessCommitted();
            }
        }
    }

// -------------------------- INNER CLASSES --------------------------

    static class CacheStream extends FilterOutputStream {
        private final DiskLruCache.Editor editor;

        CacheStream(OutputStream out, DiskLruCache.Editor editor) {
            super(out);
            this.editor = editor;
        }

        public void commit() throws BaasException {
            try {
                editor.commit();
            } catch (IOException e) {
                throw new BaasException(e);
            }
        }

        @Override
        public void close() throws IOException {
            super.close();
            if (editor != null) {
                editor.abortUnlessCommitted();
            }
        }
    }
}


text:
import {Component, OnInit} from "@angular/core";
import {FormControl, FormGroup, Validators} from "@angular/forms";
import {debounceTime, take} from "rxjs/operators";
import {LocalRepositoryService} from "../../../repository/local-repository.service";
import {DirectiveBase} from "../../../util/directive-base/directive-base";
import {ProxySettings} from "../../../../../electron/src/storage/types/proxy-settings";

@Component({
    selector: "ct-proxy-settings",
    styleUrls: ["./proxy-settings.component.scss"],
    template: `

        <form [formGroup]="form" *ngIf="form">

                    Use Proxy Server

                        <ct-toggle-slider formControlName="useProxy"
                                          name="useProxy">
                                          [on]="'Yes'"
                                          [off]="'No'">
                        </ct-toggle-slider>

                         HTTP proxy server:

                        <input class="form-control" type="text" formControlName="server" name="server"/>

                            Proxy server should start with http|https

                        Port:
                        <input class="form-control"
                               type="number" min="0" max="65535" formControlName="port"
                               name="port"/>

                            Port number should be 0-65535

                    Use Proxy Server Basic Authentication

                        <ct-toggle-slider formControlName="useAuth"
                                          name="auth">
                                          [on]="'Yes'"
                                          [off]="'No'">
                        </ct-toggle-slider>

                            Username:
                            <input class="form-control" type="text" formControlName="username" name="username"/>

                            Password:
                            <input class="form-control" type="password" formControlName="password" name="password"/>

        </form>
    `,
})
export class ProxySettingsComponent extends DirectiveBase implements OnInit {

    form: FormGroup;

    constructor(private localRepository: LocalRepositoryService) {
        super();
    }

    ngOnInit() {

        this.localRepository.getProxySettings().pipe(
            take(1)
        ).subscribeTracked(this, (proxySettings: ProxySettings) => {
            this.form = new FormGroup({
                useProxy: new FormControl(proxySettings.useProxy),
                server: new FormControl(proxySettings.server, [Validators.pattern("^(http|https):\\/\\/.*")]),
                port: new FormControl(proxySettings.port, [Validators.min(0), Validators.max(65535)]),
                useAuth: new FormControl(proxySettings.useAuth),
                username: new FormControl(proxySettings.username),
                password: new FormControl(proxySettings.password)
            });

            this.form.valueChanges.pipe(
                debounceTime(500)
            ).subscribeTracked(this, () => {
                this.localRepository.setProxySettings(this.form.getRawValue()).then(() => {
                }, (e) => {
                    console.warn("Setting proxy error", e);
                })
            });

        });
    }
}


text:
<core-block-course-blocks [courseId]="siteHomeId" [downloadEnabled]="downloadEnabled">
    <core-loading [hideUntil]="dataLoaded">
            <ion-list>
                <!-- Site home main contents. -->
                <ng-container *ngIf="section && section.hasContent">
                    <ion-item text-wrap *ngIf="section.summary">
                        <core-format-text [text]="section.summary" contextLevel="course" [contextInstanceId]="siteHomeId"></core-format-text>
                    </ion-item>

                    <core-course-module *ngFor="let module of section.modules" [module]="module" [courseId]="siteHomeId" [downloadEnabled]="downloadEnabled" [section]="section"></core-course-module>
                </ng-container>

                <!-- Site home items: news, categories, courses, etc. -->
                <ng-container *ngIf="items.length > 0">
                    <ion-item-divider *ngIf="section && section.hasContent"></ion-item-divider>
                    <ng-container *ngFor="let item of items">
                        <core-sitehome-all-course-list class="item" *ngIf="item == 'all-course-list'"></core-sitehome-all-course-list>
                        <core-sitehome-categories  *ngIf="item == 'categories'"></core-sitehome-categories>
                        <core-sitehome-course-search *ngIf="item == 'course-search'"></core-sitehome-course-search>
                        <core-sitehome-enrolled-course-list *ngIf="item == 'enrolled-course-list'"></core-sitehome-enrolled-course-list>
                        <core-sitehome-news *ngIf="item == 'news'"></core-sitehome-news>
                    </ng-container>
                </ng-container>
            </ion-list>

        <core-empty-box *ngIf="!hasContent" icon="qr-scanner" [message]="'core.course.nocontentavailable' | translate"></core-empty-box>
    </core-loading>
</core-block-course-blocks>


text:
.. highlight:: python
    :linenothreshold: 10

.. toctree::
    :maxdepth: 2

.. _cpp_and_unicode:

====================================
Python Unicode Strings and C++
====================================

Yes Unicode is a pain but it here to stay, particularly with Python 3. This section looks at how you can bridge between Python and C++ unicode in Python extensions. This section is only about Python 3+ and C++11 or more.

Whilst Python is Unicode aware C++ is not, well C++11 added ``std::basic_string`` specialisations for 2 and 4 byte 'Unicode' characters but these are just containers, they have no real awareness of what they contain.

------------------------------------
Basic Handling of Unicode
------------------------------------

The task here is to:

#. Take any Python Unicode string as an argument.
#. Convert it into an appropriate C++ container.
#. Dump that C++ container out to ``std::cout``.
#. Create and new Python Unicode string from that C++ container and return it.

This is just show that we can round-trip between the internal representations of the two languages.

Here is the despatch function that takes a single Unicode argument (note the ``"U"`` specification) and calls the appropriate handling function:

.. code-block:: cpp

    /* Handler functions, defined later. */
    PyObject *unicode_1_to_string_and_back(PyObject *py_str);
    PyObject *unicode_2_to_string_and_back(PyObject *py_str);
    PyObject *unicode_4_to_string_and_back(PyObject *py_str);

    PyObject*
    unicode_to_string_and_back(PyObject * /* module */, PyObject *args) {
        PyObject *py_str = NULL;
        PyObject *ret_val = NULL;
        if (PyArg_ParseTuple(args, "U", &py_str)) {
            switch (PyUnicode_KIND(py_str)) {
                case PyUnicode_1BYTE_KIND:
                    ret_val = unicode_1_to_string_and_back(py_str);
                    break;
                case PyUnicode_2BYTE_KIND:
                    ret_val = unicode_2_to_string_and_back(py_str);
                    break;
                case PyUnicode_4BYTE_KIND:
                    ret_val = unicode_4_to_string_and_back(py_str);
                    break;
                default:
                    PyErr_Format(PyExc_ValueError,
                                 "In %s argument is not recognised as a Unicode 1, 2, 4 byte string",
                                 __FUNCTION__);
                    break;
            }
        }
        return ret_val;
    }

The three handler functions are here, they use ``std::string``, ``std::u16string`` and ``std::u32string`` as appropriate:

.. code-block:: c

    PyObject*
    unicode_1_to_string_and_back(PyObject *py_str) {
        assert(PyUnicode_KIND(py_str) == PyUnicode_1BYTE_KIND);
        std::string result = std::string((char*)PyUnicode_1BYTE_DATA(py_str));
        dump_string(result);
        return PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND,
                                         result.c_str(),
                                         result.size());
    }

    PyObject*
    unicode_2_to_string_and_back(PyObject *py_str) {
        assert(PyUnicode_KIND(py_str) == PyUnicode_2BYTE_KIND);
        // std::u16string is a std::basic_string<char16_t>
        std::u16string result = std::u16string((char16_t*)PyUnicode_2BYTE_DATA(py_str));
        dump_string(result);
        return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
                                         result.c_str(),
                                         result.size());
    }

    PyObject*
    unicode_4_to_string_and_back(PyObject *py_str) {
        assert(PyUnicode_KIND(py_str) == PyUnicode_4BYTE_KIND);
        // std::u32string is a std::basic_string<char32_t>
        std::u32string result = std::u32string((char32_t*)PyUnicode_4BYTE_DATA(py_str));
        dump_string(result);
        return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
                                         result.c_str(),
                                         result.size());
    }

Each of these calls ``dump_string`` which is a template function:

.. code-block:: cpp

    template <typename T>
    void dump_string(const std::basic_string<T> &str) {
        std::cout << "String size: " << str.size();
        std::cout << " word size: " << sizeof(T) << std::endl;
        for (size_t i = 0; i < str.size(); ++i) {
            std::cout << std::setfill('0');
            std::cout << "0x" << std::hex;
            std::cout << std::setw(2 * sizeof(T)) << static_cast<int>(str[i]);
            std::cout << " " << std::dec << std::setw(8) << static_cast<int>(str[i]);
            std::cout << std::setfill(' ');
            std::cout << " \"" << str[i] << "\""<< std::endl;
        }
    }

For completeness here is the module code that creates a ``cUnicode`` module with a single ``show()`` function:

.. code-block:: c

    static PyMethodDef cUnicode_Methods[] = {
        {"show", (PyCFunction)unicode_to_string_and_back, METH_VARARGS,
            "Convert a Python unicode string to std::string and back."},
        {NULL, NULL, 0, NULL}        /* Sentinel */
    };

    static PyModuleDef cUnicodemodule = {
        PyModuleDef_HEAD_INIT,
        "cUnicode",
        "cUnicode works with unicode strings.",
        -1,
        cUnicode_Methods,
        NULL, NULL, NULL, NULL
    };

    PyMODINIT_FUNC
    PyInit_cUnicode(void)
    {
        PyObject* m;

        m = PyModule_Create(&cUnicodemodule);
        if (m == NULL)
            return NULL;
        return m;
    }

Here is an example of using this module:

.. code-block:: py

    >>> import cUnicode
    >>> cUnicode.show('Hello')
    String size: 5 word size: 1
    0x00000048       72 "H"
    0x00000065      101 "e"
    0x0000006c      108 "l"
    0x0000006c      108 "l"
    0x0000006f      111 "o"
    'Hello'
    >>> s = "a\xac\u1234\u20ac\U00008000"
    >>> r = cUnicode.show(s)
    String size: 5 word size: 2
    0x00000061       97 "97"
    0x000000ac      172 "172"
    0x00001234     4660 "4660"
    0x000020ac     8364 "8364"
    0x00008000    32768 "32768"
    >>> r == s
    True
    >>> s = "a\xac\u1234\u20ac\U00018000"
    >>> r = cUnicode.show(s)
    String size: 5 word size: 4
    0x00000061       97 "97"
    0x000000ac      172 "172"
    0x00001234     4660 "4660"
    0x000020ac     8364 "8364"
    0x00018000    98304 "98304"
    >>> r == s
    True

-----------------------------------------------------------------------
Working with ``bytes``, ``bytearray`` and UTF-8 Unicode Arguments
-----------------------------------------------------------------------

It is fairly common to want to convert an argumennt that is ``bytes``, ``bytearray`` or UTF-8 to a ``std::string``. This function willl do just that:

.. code-block:: c

    /* Convert a PyObject to a std::string and return 0 if succesful.
     * If py_str is Unicode than treat it as UTF-8.
     * This works with Python 2.7 and Python 3.4 onwards.
     */
    int py_string_to_std_string(const PyObject *py_str,
                                std::string &result,
                                bool utf8_only=true) {
        result.clear();
        if (PyBytes_Check(py_str)) {
            result = std::string(PyBytes_AS_STRING(py_str));
            return 0;
        }
        if (PyByteArray_Check(py_str)) {
            result = std::string(PyByteArray_AS_STRING(py_str));
            return 0;
        }
        // Must be unicode then.
        if (! PyUnicode_Check(py_str)) {
            PyErr_Format(PyExc_ValueError,
                         "In %s \"py_str\" failed PyUnicode_Check()",
                         __FUNCTION__);
            return -1;
        }
        if (PyUnicode_READY(py_str)) {
            PyErr_Format(PyExc_ValueError,
                         "In %s \"py_str\" failed PyUnicode_READY()",
                         __FUNCTION__);
            return -2;
        }
        if (utf8_only && PyUnicode_KIND(py_str) != PyUnicode_1BYTE_KIND) {
            PyErr_Format(PyExc_ValueError,
                         "In %s \"py_str\" not utf-8",
                         __FUNCTION__);
            return -3;
        }
        // Python 3 and its minor versions (they vary)
        //    const Py_UCS1 *pChrs = PyUnicode_1BYTE_DATA(pyStr);
        //    result = std::string(reinterpret_cast<const char*>(pChrs));
    #if PY_MAJOR_VERSION >= 3
        result = std::string((char*)PyUnicode_1BYTE_DATA(py_str));
    #else
        // Nasty cast away constness because PyString_AsString takes non-const in Py2
        result = std::string((char*)PyString_AsString(const_cast<PyObject *>(py_str)));
    #endif
        return 0;
    }

And these three do the reverse:

.. code-block:: c

    PyObject*
    std_string_to_py_bytes(const std::string &str) {
        return PyBytes_FromStringAndSize(str.c_str(), str.size());
    }

    PyObject*
    std_string_to_py_bytearray(const std::string &str) {
        return PyByteArray_FromStringAndSize(str.c_str(), str.size());
    }

    PyObject*
    std_string_to_py_utf8(const std::string &str) {
        // Equivelent to:
        // PyUnicode_FromKindAndData(PyUnicode_1BYTE_KIND, str.c_str(), str.size());
        return PyUnicode_FromStringAndSize(str.c_str(), str.size());
    }


text:
<?php
declare(strict_types=1);

namespace Genkgo\Xsl\Xsl\Functions;

use Genkgo\Xsl\Callback\Arguments;
use Genkgo\Xsl\Xsl\Functions;

final class DateFormatting
{
    /**
     * @var Formatter\FormatterInterface
     */
    private $formatter;

    /**
     * @param Formatter\FormatterInterface $formatter
     */
    public function __construct(Functions\Formatter\FormatterInterface $formatter)
    {
        $this->formatter = $formatter;
    }

    /**
     * @param Arguments $arguments
     * @return string
     */
    public function formatDate(Arguments $arguments)
    {
        if ($arguments->get(0) === []) {
            return '';
        }

        $arguments->assertSchemaType(0, 'date');

        try {
            $locale = $arguments->castFromSchemaType(2);
        } catch (\InvalidArgumentException $e) {
            $locale = \Locale::getDefault();
        }

        return $this->formatter->formatDate($arguments->castFromSchemaType(0), $arguments->castFromSchemaType(1), $locale, 'AD');
    }

    /**
     * @param Arguments $arguments
     * @return string
     */
    public function formatTime(Arguments $arguments)
    {
        if ($arguments->get(0) === []) {
            return '';
        }

        $arguments->assertSchemaType(0, 'time');

        try {
            $locale = $arguments->castFromSchemaType(2);
        } catch (\InvalidArgumentException $e) {
            $locale = \Locale::getDefault();
        }

        return $this->formatter->formatTime(
            $arguments->castFromSchemaType(0),
            $arguments->castFromSchemaType(1),
            $locale,
            'AD'
        );
    }

    /**
     * @param Arguments $arguments
     * @return string
     */
    public function formatDateTime(Arguments $arguments)
    {
        if ($arguments->get(0) === []) {
            return '';
        }

        $arguments->assertSchemaType(0, 'dateTime');

        try {
            $locale = $arguments->castFromSchemaType(2);
        } catch (\InvalidArgumentException $e) {
            $locale = \Locale::getDefault();
        }

        return $this->formatter->formatDateTime(
            $arguments->castFromSchemaType(0),
            $arguments->castFromSchemaType(1),
            $locale,
            'AD'
        );
    }
}


text:
package com.planet_ink.coffee_mud.Commands;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

@SuppressWarnings("unchecked")
public class WizInv extends StdCommand
{
	public WizInv(){}

	private String[] access={"WIZINVISIBLE","WIZINV","NOWIZINV"};
	public String[] getAccessWords(){return access;}
	public boolean execute(MOB mob, Vector commands, int metaFlags)
		throws java.io.IOException
	{
		String str=(String)commands.firstElement();
		if(Character.toUpperCase(str.charAt(0))!='W')
			commands.insertElementAt("OFF",1);
		commands.removeElementAt(0);
		int abilityCode=EnvStats.IS_NOT_SEEN|EnvStats.IS_CLOAKED;
		str="Prop_WizInvis";
		Ability A=mob.fetchEffect(str);
		if((commands.size()>0)&&("NOCLOAK".startsWith(CMParms.combine(commands,0).trim().toUpperCase())))
		    abilityCode=EnvStats.IS_NOT_SEEN;
		if(CMParms.combine(commands,0).trim().equalsIgnoreCase("OFF"))
		{
		   if(A!=null)
			   A.unInvoke();
		   else
			   mob.tell("You are not wizinvisible!");
		   return false;
		}
		else
		if(A!=null)
		{
		    if(CMath.bset(A.abilityCode(),abilityCode))
		    {
				mob.tell("You have already faded from view!");
				return false;
		    }
		}

		// it worked, so build a copy of this ability,
		// and add it to the affects list of the
		// affected MOB.  Then tell everyone else
		// what happened.
		if(A==null)
			A=CMClass.getAbility(str);
		if(A!=null)
		{
            if(mob.location()!=null)
    			mob.location().show(mob,null,CMMsg.MSG_OK_VISUAL,"<S-NAME> fade(s) from view!");
			if(mob.fetchEffect(A.ID())==null)
				mob.addPriorityEffect((Ability)A.copyOf());
			A=mob.fetchEffect(A.ID());
			if(A!=null) A.setAbilityCode(abilityCode);

			mob.recoverEnvStats();
			mob.location().recoverRoomStats();
			mob.tell("You may uninvoke WIZINV with 'WIZINV OFF'.");
			return false;
		}
		mob.tell("Wizard invisibility is not available!");
		return false;
	}

	public boolean canBeOrdered(){return true;}
	public boolean securityCheck(MOB mob){return CMSecurity.isAllowed(mob,mob.location(),"WIZINV");}

}


text:
@implementation FFCustomViewCell

@end


text:
<?php

/**
 * @xmlNamespace http://schema.intuit.com/finance/v3
 * @xmlType
 * @xmlName IPPFinanceChargePrefs
 * @var IPPFinanceChargePrefs
 */
class IPPFinanceChargePrefs
	{

		/**
		* Initializes this object, optionally with pre-defined property values
		*
		* Initializes this object and it's property members, using the dictionary
		* of key/value pairs passed as an optional argument.
		*
		* @param dictionary $keyValInitializers key/value pairs to be populated into object's properties
		* @param boolean $verbose specifies whether object should echo warnings
		*/
		public function __construct($keyValInitializers=array(), $verbose=FALSE)
		{
			foreach($keyValInitializers as $initPropName => $initPropVal)
			{
				if (property_exists('IPPFinanceChargePrefs',$initPropName))
				{
					$this->{$initPropName} = $initPropVal;
				}
				else
				{
					if ($verbose)
						echo "Property does not exist ($initPropName) in class (".get_class($this).")";
				}
			}
		}

	/**
	 * @Definition
						Product:QBW
						Annual Interest Rate in percent
	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName AnnualInterestRate
	 * @var float
	 */
	public $AnnualInterestRate;
	/**
	 * @Definition
						Product:QBW

	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName MinFinChrg
	 * @var float
	 */
	public $MinFinChrg;
	/**
	 * @Definition
						Product:QBW

	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName GracePeriod
	 * @var integer
	 */
	public $GracePeriod;
	/**
	 * @Definition
						Product:QBW
						If true, the Finance Charges are calculated from the transaction date (Invoice, or Bill).[br /]
						If false, the Finance Charges are calculated from the due date.

	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName CalcFinChrgFromTxnDate
	 * @var boolean
	 */
	public $CalcFinChrgFromTxnDate;
	/**
	 * @Definition
						Product:QBW
						true if finance charges should apply to overdue charges, in which case the charges will be applied to the account referenced in FinChrgAccountRef

	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName AssessFinChrgForOverdueCharges
	 * @var boolean
	 */
	public $AssessFinChrgForOverdueCharges;
	/**
	 * @Definition
						Product:QBW
						[b]QuickBooks Notes[/b][br /]
						Max Length: 31 or 159 (for a fully qualified name)

	 * @xmlType element
	 * @xmlNamespace http://schema.intuit.com/finance/v3
	 * @xmlMinOccurs 0
	 * @xmlName FinChrgAccountRef
	 * @var com\intuit\schema\finance\v3\IPPReferenceType
	 */
	public $FinChrgAccountRef;

} // end class IPPFinanceChargePrefs


text:
namespace bbe
{
	namespace INTERNAL
	{
		namespace vulkan
		{
			class VulkanDevice;

			class VulkanShader
			{
			private:
				VkShaderModule m_shaderModule = VK_NULL_HANDLE;
				VkDevice       m_device       = VK_NULL_HANDLE;

			public:
				VulkanShader();

				void init(const bbe::String& path);
				void init(const VulkanDevice &device, const bbe::String &path);
				void init(const VulkanDevice &device, const bbe::List<unsigned char> &code);

				void destroy();

				VkShaderModule getModule();
			};
		}
	}
}


text:
package org.wso2.carbon.p2.touchpoint;

import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;

public class Utils {

    public static IStatus createError(String message) {
        return createError(message, null);
    }

    public static IStatus createError(String message, Exception e) {
        return new Status(IStatus.ERROR, TouchpointActionConstants.PLUGIN_ID, message, e);

    }
}


text:
<?php

// phpBB 2.x auto-generated config file
// Do not change anything in this file!

$dbms = 'mysql';

$dbhost = 'localhost';
$dbname = 'thespot_forums';
$dbuser = 'thespot_admin';
$dbpasswd = 'softworks';

$table_prefix = 'phpbb_';

define('PHPBB_INSTALLED', true);

?>