text:
<?php namespace Unnutz\PhpLcid;

use Locale;
use Unnutz\PhpLcid\Enums;
use Unnutz\PhpLcid\Exceptions\InvalidSortException;
use Unnutz\PhpLcid\Exceptions\LocaleNotFoundException;

/**
 * Class Lcid
 * @package Unnutz\PhpLcid
 */
class Lcid implements LcidInterface
{
    /**
     * @var array
     */
    protected $data = [];

    /**
     *
     */
    function __construct()
    {
        $this->data = require __DIR__ . '/data/languages.php';
    }

    /**
     * Returns LCID based on language, region, script, variant and sort combination
     *
     * @param $language
     * @param null $region
     * @param null $script
     * @param null $variant
     * @param int $sort
     * @return int
     * @throws \Unnutz\PhpLcid\Exceptions\InvalidSortException
     * @throws \Unnutz\PhpLcid\Exceptions\LocaleNotFoundException
     */
    public function get($language, $region = null, $script = null, $variant = null, $sort = Enums\Sort::SORT_DEFAULT)
    {
        $tags = [];

        $tags[Locale::LANG_TAG] = $language;

        is_null($region) ?: $tags[Locale::REGION_TAG] = $region;
        is_null($script) ?: $tags[Locale::SCRIPT_TAG] = $script;
        is_null($variant) ?: $tags['variant0'] = $variant;

        return $this->getByLocale(Locale::composeLocale($tags), $sort);
    }

    /**
     * Returns LCID based on locale and sort combination
     *
     * @param $locale
     * @param int $sort
     * @return int
     * @throws \Unnutz\PhpLcid\Exceptions\InvalidSortException
     * @throws \Unnutz\PhpLcid\Exceptions\LocaleNotFoundException
     */
    public function getByLocale($locale, $sort = Enums\Sort::SORT_DEFAULT)
    {
        $locale = Locale::canonicalize($locale);

        if (!array_key_exists($locale, $this->data)) {
            throw new LocaleNotFoundException($locale);
        }

        $tags = Locale::parseLocale($locale);
        if (!array_key_exists(Locale::LANG_TAG, $tags))
            throw new LocaleNotFoundException($locale);

        $this->validateSort($tags[Locale::LANG_TAG], $sort);

        return $sort + $this->data[$locale];
    }

    /**
     * Returns locale based on LCID
     *
     * @param $lcid
     * @param bool $returnArray
     * @return array|mixed
     * @throws \Unnutz\PhpLcid\Exceptions\LocaleNotFoundException
     */
    public function findLocale($lcid, $returnArray = false)
    {
        $locale = array_search($lcid, $this->data, true);

        if (false === $locale) {
            throw new LocaleNotFoundException($lcid);
        }

        return $returnArray ? Locale::parseLocale($locale) : $locale;
    }

    /**
     * @param $language
     * @param $sort
     * @throws \Unnutz\PhpLcid\Exceptions\InvalidSortException
     */
    protected function validateSort($language, $sort)
    {
        switch ($sort) {

            case 0x00000000:

                break;

            case 0x00010000:

                if (!in_array($language, ['zh', 'ka', 'de', 'hu', 'ja', 'ko']))
                    throw new InvalidSortException($language, $sort);

                break;

            case 0x00020000:
            case 0x00030000:

                if (!in_array($language, ['zh']))
                    throw new InvalidSortException($language, $sort);

                break;

            case 0x00040000:

                if (!in_array($language, ['zh', 'ja']))
                    throw new InvalidSortException($language, $sort);

                break;

            default:
                throw new InvalidSortException($language, $sort);
        }

        return;
    }
}


text:
package org.apache.camel.builder.endpoint.dsl;

import javax.annotation.Generated;
import org.apache.camel.LoggingLevel;
import org.apache.camel.builder.EndpointConsumerBuilder;
import org.apache.camel.builder.EndpointProducerBuilder;
import org.apache.camel.builder.endpoint.AbstractEndpointBuilder;

/**
 * The exec component can be used to execute OS system commands.
 *
 * Generated by camel build tools - do NOT edit this file!
 */
@Generated("org.apache.camel.maven.packaging.EndpointDslMojo")
public interface ExecEndpointBuilderFactory {

    /**
     * Builder for endpoint for the Exec component.
     */
    public interface ExecEndpointBuilder extends EndpointProducerBuilder {
        default AdvancedExecEndpointBuilder advanced() {
            return (AdvancedExecEndpointBuilder) this;
        }
        /**
         * The arguments may be one or many whitespace-separated tokens.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder args(String args) {
            doSetProperty("args", args);
            return this;
        }
        /**
         * A reference to a org.apache.commons.exec.ExecBinding in the Registry.
         *
         * The option is a:
         * org.apache.camel.component.exec.ExecBinding type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder binding(Object binding) {
            doSetProperty("binding", binding);
            return this;
        }
        /**
         * A reference to a org.apache.commons.exec.ExecBinding in the Registry.
         *
         * The option will be converted to a
         * org.apache.camel.component.exec.ExecBinding type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder binding(String binding) {
            doSetProperty("binding", binding);
            return this;
        }
        /**
         * A reference to a org.apache.commons.exec.ExecCommandExecutor in the
         * Registry that customizes the command execution. The default command
         * executor utilizes the commons-exec library, which adds a shutdown
         * hook for every executed command.
         *
         * The option is a:
         * org.apache.camel.component.exec.ExecCommandExecutor
         * type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder commandExecutor(Object commandExecutor) {
            doSetProperty("commandExecutor", commandExecutor);
            return this;
        }
        /**
         * A reference to a org.apache.commons.exec.ExecCommandExecutor in the
         * Registry that customizes the command execution. The default command
         * executor utilizes the commons-exec library, which adds a shutdown
         * hook for every executed command.
         *
         * The option will be converted to a
         * org.apache.camel.component.exec.ExecCommandExecutor
         * type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder commandExecutor(String commandExecutor) {
            doSetProperty("commandExecutor", commandExecutor);
            return this;
        }
        /**
         * Logging level to be used for commands during execution. The default
         * value is DEBUG. Possible values are TRACE, DEBUG, INFO, WARN, ERROR
         * or OFF. (Values of ExecCommandLogLevelType enum).
         *
         * The option is a: org.apache.camel.LoggingLevel type.
         *
         * Default: DEBUG
         * Group: producer
         */
        default ExecEndpointBuilder commandLogLevel(LoggingLevel commandLogLevel) {
            doSetProperty("commandLogLevel", commandLogLevel);
            return this;
        }
        /**
         * Logging level to be used for commands during execution. The default
         * value is DEBUG. Possible values are TRACE, DEBUG, INFO, WARN, ERROR
         * or OFF. (Values of ExecCommandLogLevelType enum).
         *
         * The option will be converted to a
         * org.apache.camel.LoggingLevel type.
         *
         * Default: DEBUG
         * Group: producer
         */
        default ExecEndpointBuilder commandLogLevel(String commandLogLevel) {
            doSetProperty("commandLogLevel", commandLogLevel);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: producer
         */
        default ExecEndpointBuilder lazyStartProducer(boolean lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * Whether the producer should be started lazy (on the first message).
         * By starting lazy you can use this to allow CamelContext and routes to
         * startup in situations where a producer may otherwise fail during
         * starting and cause the route to fail being started. By deferring this
         * startup to be lazy then the startup failure can be handled during
         * routing messages via Camel's routing error handlers. Beware that when
         * the first message is processed then creating and starting the
         * producer may take a little time and prolong the total processing time
         * of the processing.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: producer
         */
        default ExecEndpointBuilder lazyStartProducer(String lazyStartProducer) {
            doSetProperty("lazyStartProducer", lazyStartProducer);
            return this;
        }
        /**
         * The name of a file, created by the executable, that should be
         * considered as its output. If no outFile is set, the standard output
         * (stdout) of the executable will be used instead.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder outFile(String outFile) {
            doSetProperty("outFile", outFile);
            return this;
        }
        /**
         * The timeout, in milliseconds, after which the executable should be
         * terminated. If execution has not completed within the timeout, the
         * component will send a termination request.
         *
         * The option is a: long type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder timeout(long timeout) {
            doSetProperty("timeout", timeout);
            return this;
        }
        /**
         * The timeout, in milliseconds, after which the executable should be
         * terminated. If execution has not completed within the timeout, the
         * component will send a termination request.
         *
         * The option will be converted to a long type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder timeout(String timeout) {
            doSetProperty("timeout", timeout);
            return this;
        }
        /**
         * A boolean indicating that when stdout is empty, this component will
         * populate the Camel Message Body with stderr. This behavior is
         * disabled (false) by default.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: producer
         */
        default ExecEndpointBuilder useStderrOnEmptyStdout(
                boolean useStderrOnEmptyStdout) {
            doSetProperty("useStderrOnEmptyStdout", useStderrOnEmptyStdout);
            return this;
        }
        /**
         * A boolean indicating that when stdout is empty, this component will
         * populate the Camel Message Body with stderr. This behavior is
         * disabled (false) by default.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: producer
         */
        default ExecEndpointBuilder useStderrOnEmptyStdout(
                String useStderrOnEmptyStdout) {
            doSetProperty("useStderrOnEmptyStdout", useStderrOnEmptyStdout);
            return this;
        }
        /**
         * The directory in which the command should be executed. If null, the
         * working directory of the current process will be used.
         *
         * The option is a: java.lang.String type.
         *
         * Group: producer
         */
        default ExecEndpointBuilder workingDir(String workingDir) {
            doSetProperty("workingDir", workingDir);
            return this;
        }
    }

    /**
     * Advanced builder for endpoint for the Exec component.
     */
    public interface AdvancedExecEndpointBuilder
            extends
                EndpointProducerBuilder {
        default ExecEndpointBuilder basic() {
            return (ExecEndpointBuilder) this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedExecEndpointBuilder basicPropertyBinding(
                boolean basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Whether the endpoint should use basic property binding (Camel 2.x) or
         * the newer property binding with additional capabilities.
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedExecEndpointBuilder basicPropertyBinding(
                String basicPropertyBinding) {
            doSetProperty("basicPropertyBinding", basicPropertyBinding);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option is a: boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedExecEndpointBuilder synchronous(boolean synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
        /**
         * Sets whether synchronous processing should be strictly used, or Camel
         * is allowed to use asynchronous processing (if supported).
         *
         * The option will be converted to a boolean type.
         *
         * Default: false
         * Group: advanced
         */
        default AdvancedExecEndpointBuilder synchronous(String synchronous) {
            doSetProperty("synchronous", synchronous);
            return this;
        }
    }

    public interface ExecBuilders {
        /**
         * Exec (camel-exec)
         * The exec component can be used to execute OS system commands.
         *
         * Category: system
         * Since: 2.3
         * Maven coordinates: org.apache.camel:camel-exec
         *
         * Syntax: exec:executable
         *
         * Path parameter: executable (required)
         * Sets the executable to be executed. The executable must not be empty
         * or null.
         */
        default ExecEndpointBuilder exec(String path) {
            return ExecEndpointBuilderFactory.exec(path);
        }
    }
    /**
     * Exec (camel-exec)
     * The exec component can be used to execute OS system commands.
     *
     * Category: system
     * Since: 2.3
     * Maven coordinates: org.apache.camel:camel-exec
     *
     * Syntax: exec:executable
     *
     * Path parameter: executable (required)
     * Sets the executable to be executed. The executable must not be empty or
     * null.
     */
    static ExecEndpointBuilder exec(String path) {
        class ExecEndpointBuilderImpl extends AbstractEndpointBuilder implements ExecEndpointBuilder, AdvancedExecEndpointBuilder {
            public ExecEndpointBuilderImpl(String path) {
                super("exec", path);
            }
        }
        return new ExecEndpointBuilderImpl(path);
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.apache.shindig.gadgets.parse.caja;

import com.google.caja.parser.css.CssTree;

import org.apache.shindig.common.cache.LruCacheProvider;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * Basic CSS parse tests
 */
public class CajaCssParserTest extends Assert {

  private CajaCssParser cajaCssParser;

  @Before
  public void setUp() throws Exception {
    cajaCssParser = new CajaCssParser();
    cajaCssParser.setCacheProvider(new LruCacheProvider(10));
  }

  @Test
  public void testBasicCssParse() throws Exception {
    String css = ".xyz { font : bold; } A { color : #7f7f7f }";
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(css);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(styleSheet,
        CssTree.SimpleSelector.class);
    assertEquals(2, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  /**
   * These tests test Caja's parsing of "funky" CSS which are not legal
   * but accepted by commonly used browsers
   */
  @Test
  public void testCajaParseColonInRValue() throws Exception {
    String original = " A {\n"
        + " -moz-opacity: 0.80;\n"
        + " filter: alpha(opacity=40);\n"
        + " filter: progid:DXImageTransform.Microsoft.Alpha(opacity=80);\n"
        + '}';
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);
    assertEquals(1, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  @Test
  public void testCajaParseNoLValue() throws Exception {
    String original = "body, input, td {\n"
        + "  Arial, sans-serif;\n"
        + '}';
    cajaCssParser.parseDom(original);
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);
    assertEquals(3, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  @Test
  public void testCajaParseNoScheme() throws Exception {
    String original = "span { background-image:url('//www.example.org/image.gif'); }";
    cajaCssParser.parseDom(original);
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);

    // TODO: Remove with next caja update
    // This will break once Caja cloning works again
    assertEquals(1, selectorList.size());
    // assertEquals(3, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  @Test
  public void testCajaParseCommentInContent() throws Exception {
    String original = "body { font : bold; } \n//A comment\n A { font : bold; }";
    cajaCssParser.parseDom(original);
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);
    assertEquals(2, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  @Test
  public void testCajaParseDotInIdent() throws Exception {
    String original = "li{list-style:none;.padding-bottom:4px;}";
    cajaCssParser.parseDom(original);
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);
    assertEquals(1, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }

  @Test
  public void testCajaParseDotInFunction() throws Exception {
    String original = ".iepngfix {behavior: expression(IEPNGFIX.fix(this)); }";
    cajaCssParser.parseDom(original);
    CssTree.StyleSheet styleSheet = cajaCssParser.parseDom(original);
    List<CssTree.SimpleSelector> selectorList = CajaCssUtils.descendants(
        styleSheet, CssTree.SimpleSelector.class);
    assertEquals(1, selectorList.size());
    assertSame(CssTree.SimpleSelector.class, selectorList.get(0).getClass());
  }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<Tokens version="1.0">
	<File path="Classes/KWItNode.html">

		<Token>
			<TokenIdentifier>//apple_ref/occ/cl/KWItNode</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWItNode.h</DeclaredIn>

			<NodeRef refid="37"/>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instm/KWItNode/setExampleGroup:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWItNode.h</DeclaredIn>

			<Declaration>@property (nonatomic, assign) KWExampleGroup *exampleGroup</Declaration>

			<Anchor>//api/name/exampleGroup</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/instp/KWItNode/exampleGroup</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWItNode.h</DeclaredIn>

			<Declaration>@property (nonatomic, assign) KWExampleGroup *exampleGroup</Declaration>

			<Anchor>//api/name/exampleGroup</Anchor>
		</Token>

		<Token>
			<TokenIdentifier>//apple_ref/occ/clm/KWItNode/itNodeWithCallSite:description:block:</TokenIdentifier>
			<Abstract type="html"></Abstract>
			<DeclaredIn>KWItNode.h</DeclaredIn>

			<Declaration>+ (id)itNodeWithCallSite:(KWCallSite *)aCallSite description:(NSString *)aDescription block:(KWVoidBlock)aBlock</Declaration>

			<Anchor>//api/name/itNodeWithCallSite:description:block:</Anchor>
		</Token>

	</File>
</Tokens>


text:
package eus.ixa.ixa.pipe.ml.document;

import opennlp.tools.util.eval.EvaluationMonitor;

/**
 * {@link EvaluationMonitor} for the document classifier.
 */
public interface DocumentClassifierEvaluationMonitor extends
    EvaluationMonitor<DocSample> {
}


text:
require( "DotaHS_GameMode" )

--------------------------------------------------------------------------------
-- PRECACHE
--------------------------------------------------------------------------------
function Precache( context )
	PrecacheResource( "particle", "particles/loots/loot_rare_starfall.vpcf", context )
	PrecacheItemByNameSync( "item_tombstone", context )
--	PrecacheUnitByNameSync( "npc_dota_hero_naga_siren", context )
end

--------------------------------------------------------------------------------
-- ACTIVATE
--------------------------------------------------------------------------------
function Activate()
    GameRules.DotaHS = DotaHS()
    GameRules.DotaHS:InitGameMode()
end


text:
import { Article, Id, ObtenirArticle } from '../api/articles';
import { ajouterRoute, IRoutable } from '../../bacasable/bacasable/routage';
import { inject } from '../../bacasable/bacasable/injection';
import { ApplicationClient } from '../../bacasable/bacasable/applicationClient';

export class PageVoirArticle implements IRoutable<Id>
{
    static route = ajouterRoute('/article/:id', PageVoirArticle);

    app = inject(ApplicationClient);
    article: Article;
    async construire(id:Id)
    {
        this.article = await this.app.AppelerWebService(ObtenirArticle, id);
    }
}


text:
'use strict';

eventsApp.directive("dateKeys", function () {
    return {
        restrict: 'A',
        link: function(scope, element, attrs, controller) {
            angular.element(element).on('keydown', function(event) {
                return isNumericKeyCode(event.keyCode) ||
                        isForwardSlashKeyCode(event.keyCode) ||
                        isNavigationKeyCode(event.keyCode);
            })
        }
    };

    function isNumericKeyCode(keyCode) {
        return (keyCode >= 48 && keyCode <=57) || (keyCode >= 96 && keyCode <= 105);
    }

    function isForwardSlashKeyCode(keyCode) {
        return keyCode === 191;
    }

    function isNavigationKeyCode(keyCode) {
        switch (keyCode) {
            case 8:  // backspace
            case 35: // end
            case 36: // home
            case 37: // left
            case 38: // up
            case 39: // right
            case 40: // down
            case 45: // ins
            case 46: // del
                // need tab, enter, esc keys?
                return true;
            default:
                return false;
        }
    }
});


text:
use std::any::{Any, TypeId};
use std::borrow::Borrow;
use std::cell::RefCell;
use std::collections::HashMap;
use std::convert::AsRef;
use std::ffi::OsStr;
use std::fmt;
use std::hash::{Hash, Hasher};
use std::marker::PhantomData;
use std::mem;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::cmp::{PartialOrd, Ord, Ordering};

use crate::builder::Step;

pub struct Interned<T>(usize, PhantomData<*const T>);

impl Default for Interned<String> {
    fn default() -> Self {
        INTERNER.intern_string(String::default())
    }
}

impl Default for Interned<PathBuf> {
    fn default() -> Self {
        INTERNER.intern_path(PathBuf::default())
    }
}

impl<T> Copy for Interned<T> {}
impl<T> Clone for Interned<T> {
    fn clone(&self) -> Interned<T> {
        *self
    }
}

impl<T> PartialEq for Interned<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl<T> Eq for Interned<T> {}

impl PartialEq<str> for Interned<String> {
    fn eq(&self, other: &str) -> bool {
       *self == other
    }
}
impl<'a> PartialEq<&'a str> for Interned<String> {
    fn eq(&self, other: &&str) -> bool {
        **self == **other
    }
}
impl<'a, T> PartialEq<&'a Interned<T>> for Interned<T> {
    fn eq(&self, other: &&Self) -> bool {
        self.0 == other.0
    }
}
impl<'a, T> PartialEq<Interned<T>> for &'a Interned<T> {
    fn eq(&self, other: &Interned<T>) -> bool {
        self.0 == other.0
    }
}

unsafe impl<T> Send for Interned<T> {}
unsafe impl<T> Sync for Interned<T> {}

impl fmt::Display for Interned<String> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s: &str = &*self;
        f.write_str(s)
    }
}

impl fmt::Debug for Interned<String> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s: &str = &*self;
        f.write_fmt(format_args!("{:?}", s))
    }
}
impl fmt::Debug for Interned<PathBuf> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let s: &Path = &*self;
        f.write_fmt(format_args!("{:?}", s))
    }
}

impl Hash for Interned<String> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let l = INTERNER.strs.lock().unwrap();
        l.get(*self).hash(state)
    }
}

impl Hash for Interned<PathBuf> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        let l = INTERNER.paths.lock().unwrap();
        l.get(*self).hash(state)
    }
}

impl Deref for Interned<String> {
    type Target = str;
    fn deref(&self) -> &'static str {
        let l = INTERNER.strs.lock().unwrap();
        unsafe { mem::transmute::<&str, &'static str>(l.get(*self)) }
    }
}

impl Deref for Interned<PathBuf> {
    type Target = Path;
    fn deref(&self) -> &'static Path {
        let l = INTERNER.paths.lock().unwrap();
        unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self)) }
    }
}

impl AsRef<Path> for Interned<PathBuf> {
    fn as_ref(&self) -> &'static Path {
        let l = INTERNER.paths.lock().unwrap();
        unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self)) }
    }
}

impl AsRef<Path> for Interned<String> {
    fn as_ref(&self) -> &'static Path {
        let l = INTERNER.strs.lock().unwrap();
        unsafe { mem::transmute::<&Path, &'static Path>(l.get(*self).as_ref()) }
    }
}

impl AsRef<OsStr> for Interned<PathBuf> {
    fn as_ref(&self) -> &'static OsStr {
        let l = INTERNER.paths.lock().unwrap();
        unsafe { mem::transmute::<&OsStr, &'static OsStr>(l.get(*self).as_ref()) }
    }
}

impl AsRef<OsStr> for Interned<String> {
    fn as_ref(&self) -> &'static OsStr {
        let l = INTERNER.strs.lock().unwrap();
        unsafe { mem::transmute::<&OsStr, &'static OsStr>(l.get(*self).as_ref()) }
    }
}

impl PartialOrd<Interned<String>> for Interned<String> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        let l = INTERNER.strs.lock().unwrap();
        l.get(*self).partial_cmp(l.get(*other))
    }
}

impl Ord for Interned<String> {
    fn cmp(&self, other: &Self) -> Ordering {
        let l = INTERNER.strs.lock().unwrap();
        l.get(*self).cmp(l.get(*other))
    }
}

struct TyIntern<T: Hash + Clone + Eq> {
    items: Vec<T>,
    set: HashMap<T, Interned<T>>,
}

impl<T: Hash + Clone + Eq> Default for TyIntern<T> {
    fn default() -> Self {
        TyIntern {
            items: Vec::new(),
            set: Default::default(),
        }
    }
}

impl<T: Hash + Clone + Eq> TyIntern<T> {
    fn intern_borrow<B>(&mut self, item: &B) -> Interned<T>
    where
        B: Eq + Hash + ToOwned<Owned=T> + ?Sized,
        T: Borrow<B>,
    {
        if let Some(i) = self.set.get(&item) {
            return *i;
        }
        let item = item.to_owned();
        let interned =  Interned(self.items.len(), PhantomData::<*const T>);
        self.set.insert(item.clone(), interned);
        self.items.push(item);
        interned
    }

    fn intern(&mut self, item: T) -> Interned<T> {
        if let Some(i) = self.set.get(&item) {
            return *i;
        }
        let interned =  Interned(self.items.len(), PhantomData::<*const T>);
        self.set.insert(item.clone(), interned);
        self.items.push(item);
        interned
    }

    fn get(&self, i: Interned<T>) -> &T {
        &self.items[i.0]
    }
}

#[derive(Default)]
pub struct Interner {
    strs: Mutex<TyIntern<String>>,
    paths: Mutex<TyIntern<PathBuf>>,
}

impl Interner {
    pub fn intern_str(&self, s: &str) -> Interned<String> {
        self.strs.lock().unwrap().intern_borrow(s)
    }
    pub fn intern_string(&self, s: String) -> Interned<String> {
        self.strs.lock().unwrap().intern(s)
    }

    pub fn intern_path(&self, s: PathBuf) -> Interned<PathBuf> {
        self.paths.lock().unwrap().intern(s)
    }
}

lazy_static! {
    pub static ref INTERNER: Interner = Interner::default();
}

/// This is essentially a HashMap which allows storing any type in its input and
/// any type in its output. It is a write-once cache; values are never evicted,
/// which means that references to the value can safely be returned from the
/// get() method.
#[derive(Debug)]
pub struct Cache(
    RefCell<HashMap<
        TypeId,
        Box<dyn Any>, // actually a HashMap<Step, Interned<Step::Output>>
    >>
);

impl Cache {
    pub fn new() -> Cache {
        Cache(RefCell::new(HashMap::new()))
    }

    pub fn put<S: Step>(&self, step: S, value: S::Output) {
        let mut cache = self.0.borrow_mut();
        let type_id = TypeId::of::<S>();
        let stepcache = cache.entry(type_id)
                        .or_insert_with(|| Box::new(HashMap::<S, S::Output>::new()))
                        .downcast_mut::<HashMap<S, S::Output>>()
                        .expect("invalid type mapped");
        assert!(!stepcache.contains_key(&step), "processing {:?} a second time", step);
        stepcache.insert(step, value);
    }

    pub fn get<S: Step>(&self, step: &S) -> Option<S::Output> {
        let mut cache = self.0.borrow_mut();
        let type_id = TypeId::of::<S>();
        let stepcache = cache.entry(type_id)
                        .or_insert_with(|| Box::new(HashMap::<S, S::Output>::new()))
                        .downcast_mut::<HashMap<S, S::Output>>()
                        .expect("invalid type mapped");
        stepcache.get(step).cloned()
    }

    #[cfg(test)]
    pub fn all<S: Ord + Copy + Step>(&mut self) -> Vec<(S, S::Output)> {
        let cache = self.0.get_mut();
        let type_id = TypeId::of::<S>();
        let mut v = cache.remove(&type_id)
            .map(|b| b.downcast::<HashMap<S, S::Output>>().expect("correct type"))
            .map(|m| m.into_iter().collect::<Vec<_>>())
            .unwrap_or_default();
        v.sort_by_key(|&(a, _)| a);
        v
    }

    #[cfg(test)]
    pub fn contains<S: Step>(&self) -> bool {
        self.0.borrow().contains_key(&TypeId::of::<S>())
    }
}


text:
using UnityEngine;

public class SimpleRotator : MonoBehaviour
{
    public float RotationTime = 2.5f;

    // Use this for initialization
    void Start()
    {
        LeanTween.rotateAround(gameObject, Vector3.up, 360, RotationTime).setLoopClamp();
    }

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

    }
}


text:
<?xml version='1.0' encoding='UTF-8'?>
<project>
  <actions/>
  <description></description>
  <logRotator class="hudson.tasks.LogRotator">
    <daysToKeep>7</daysToKeep>
    <numToKeep>7</numToKeep>
    <artifactDaysToKeep>-1</artifactDaysToKeep>
    <artifactNumToKeep>-1</artifactNumToKeep>
  </logRotator>
  <keepDependencies>false</keepDependencies>
  <properties>
    <hudson.plugins.googlecode.GoogleCodeProjectProperty plugin="googlecode@1.7"/>
    <hudson.plugins.buildblocker.BuildBlockerProperty plugin="build-blocker-plugin@1.4.1">
      <useBuildBlocker>false</useBuildBlocker>
    </hudson.plugins.buildblocker.BuildBlockerProperty>
    <hudson.model.ParametersDefinitionProperty>
      <parameterDefinitions>
        <hudson.model.StringParameterDefinition>
          <name>HOST</name>
          <description></description>
          <defaultValue>PublicIP</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>DIST_PATH</name>
          <description></description>
          <defaultValue>/etc/fiware.d</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>BRANCH</name>
          <description></description>
          <defaultValue>develop</defaultValue>
        </hudson.model.StringParameterDefinition>
        <hudson.model.StringParameterDefinition>
          <name>LOCAL_IP</name>
          <description></description>
          <defaultValue>172.30.1.189:5000</defaultValue>
        </hudson.model.StringParameterDefinition>
      </parameterDefinitions>
    </hudson.model.ParametersDefinitionProperty>
    <hudson.plugins.disk__usage.DiskUsageProperty plugin="disk-usage@0.25"/>
  </properties>
  <scm class="hudson.scm.NullSCM"/>
  <canRoam>true</canRoam>
  <disabled>false</disabled>
  <blockBuildWhenDownstreamBuilding>false</blockBuildWhenDownstreamBuilding>
  <blockBuildWhenUpstreamBuilding>false</blockBuildWhenUpstreamBuilding>
  <triggers/>
  <concurrentBuild>false</concurrentBuild>
  <builders>
    <hudson.tasks.Shell>
      <command># KILLING PREVIOUS GUNICORN
ssh -i ~/.ssh/fiware_cloud_rsa root@$HOST "sh $DIST_PATH/facts_stop.sh"

# PIP INSTALL from PolicyManager repository ($BRANCH branch)
ssh -i ~/.ssh/fiware_cloud_rsa root@$HOST "sudo pip install git+https://github.com/telefonicaid/fiware-facts.git@$BRANCH --upgrade"
scp -i ~/.ssh/fiware_cloud_rsa ${JENKINS_JOB_RESOURCES_PATH}/fiware-facts.cfg policymanager@$HOST:$DIST_PATH/fiware-facts.cfg
ssh -i ~/.ssh/fiware_cloud_rsa root@$HOST "service rabbitmq-server restart"
ssh -i ~/.ssh/fiware_cloud_rsa root@$HOST "nohup sh $DIST_PATH/facts_start.sh > /dev/null &"
echo "Fiware-Facts is running"</command>
    </hudson.tasks.Shell>
  </builders>
  <publishers/>
  <buildWrappers>
    <hudson.plugins.ansicolor.AnsiColorBuildWrapper plugin="ansicolor@0.4.0">
      <colorMapName>xterm</colorMapName>
    </hudson.plugins.ansicolor.AnsiColorBuildWrapper>
    <hudson.plugins.setenv.SetEnvBuildWrapper plugin="setenv@1.1">
      <localVarText>JENKINS_JOB_RESOURCES_PATH=/home/develenv/fiware_cloud_job_resources/PolicyManager-Deploy</localVarText>
    </hudson.plugins.setenv.SetEnvBuildWrapper>
  </buildWrappers>
</project>


text:
package net.sf.cram.mask;

import java.util.Arrays;

public class RefMaskUtils {
	public static final byte[] bases = new byte[] { 'A', 'C', 'G', 'T' };
	public static final byte[] base2index = new byte[256];
	static {
		Arrays.fill(base2index, (byte) -1);
		base2index['A'] = 0;
		base2index['a'] = 0;
		base2index['C'] = 1;
		base2index['c'] = 1;
		base2index['G'] = 2;
		base2index['g'] = 2;
		base2index['T'] = 3;
		base2index['t'] = 3;
	}

	public static int minHits = 2;

	public static final int getBaseCount(byte mask, byte base) {
		return 3 & (mask >>> (2 * base2index[base]));
	}

	public static final byte addReadBase(byte mask, byte readBase, byte refBase) {
		byte baseMask = 0;
		switch (readBase) {
		case 'A':
		case 'a':
			// 00000011
			baseMask = 3;
			break;
		case 'C':
		case 'c':
			// 00001100
			baseMask = 12;
			break;
		case 'G':
		case 'g':
			// 00110000
			baseMask = 48;
			break;
		case 'T':
		case 't':
			// 11000000
			baseMask = ~63;
			break;

		default:
			// throw new IllegalArgumentException("Unkown base: " + readBase);
			return mask;
		}

		// byte count = (byte) ((baseMask & mask) >>> (2 * base2index[readBase])
		// & 3);
		int count = getBaseCount(mask, readBase);
		if (count < 3) {
			count++;
			mask &= ~baseMask;
			mask |= count << (2 * base2index[readBase]);
		}
		return mask;
	}

	public static final boolean shouldStore(byte mask, byte refBase) {
		for (byte base : bases) {
			if (base == refBase)
				continue;
			if (getBaseCount(mask, base) >= minHits)
				return true;
		}
		return false;
	}

	public static final int getBaseCount(short mask, byte base) {
		return 15 & (mask >>> (4 * base2index[base]));
	}

	public static final short addReadBase(short mask, byte readBase, byte refBase) {
		short baseMask = 0;
		switch (readBase) {
		case 'A':
		case 'a':
			// 00000000 00001111
			baseMask = 15;
			break;
		case 'C':
		case 'c':
			// 00000000 11110000
			baseMask = 240;
			break;
		case 'G':
		case 'g':
			// 00001111 00000000
			baseMask = 3840;
			break;
		case 'T':
		case 't':
			// 11110000 00000000
			baseMask = ~4095;
			break;

		default:
			// throw new IllegalArgumentException("Unkown base: " + readBase);
			return mask;
		}

		int count = getBaseCount(mask, readBase);
		if (count < 15) {
			count++;
			mask &= ~baseMask;
			mask |= count << (4 * base2index[readBase]);
		}
		return mask;
	}

	private static final int minCoverageEstimate(short mask) {
		int coverage = 15 & mask;
		coverage += 15 & (mask >>> 4);
		coverage += 15 & (mask >>> 8);
		coverage += 15 & (mask >>> 12);

		return coverage;
	}

	public static final boolean shouldStore(short mask, byte refBase) {
		if (minCoverageEstimate(mask) > 10)
			return false;
		int[] counts = new int[3];
		int i = 0;
		for (byte base : bases) {
			if (base == refBase)
				continue;
			counts[i] = getBaseCount(mask, base);
			if (counts[i] >= minHits)
				return true;
			i++;
		}

		// Arrays.sort(counts);
		// int depth = minCoverageEstimate(mask);
		// if (depth > 10 && ((float) counts[1] + counts[2]) / counts[0] > 0.3)
		// return true;

		return false;
	}

	public static class RefMask {
		private short[] mask;
		private int minHits;

		public RefMask(int len, int minHits) {
			super();
			this.mask = new short[len];
			Arrays.fill(mask, (short) 0);
			this.minHits = minHits;
		}

		public void addReadBase(int pos, byte readBase, byte refBase) {
			mask[pos] = RefMaskUtils.addReadBase(mask[pos], readBase, refBase);
		}

		public boolean shouldStore(int pos, byte refBase) {
			short maskAtPos = mask[pos];
			if (maskAtPos == 0)
				return false;

			if (minCoverageEstimate(maskAtPos) > 10)
				return false;
			int[] counts = new int[3];
			int i = 0;
			for (byte base : bases) {
				if (base == refBase)
					continue;
				counts[i] = getBaseCount(maskAtPos, base);
				if (counts[i] >= minHits)
					return true;
				i++;
			}

			return false;
		}

		public int getMinHits() {
			return minHits;
		}

		public void setMinHits(int minHits) {
			this.minHits = minHits;
		}

	}
}


text:
/* globals describe, it, beforeEach, afterEach, sinon */
import { expect } from 'chai'
import bidfactory from 'src/bidfactory'
import bidmanager from 'src/bidmanager'
import * as utils from 'src/utils'
import { STATUS } from 'src/constants'
import { Renderer } from 'src/Renderer'
import createUnrulyAdapter from 'modules/unrulyBidAdapter'

describe('UnrulyAdapter', () => {
  function createBidRequestBid({ placementCode }) {
    return {
      'bidder': 'unruly',
      'params': {
        'uuid': '74544e00-d43b-4f3a-a799-69d22ce979ce',
        'siteId': 794599,
        'placementId': '5768085'
      },
      'placementCode': placementCode,
      'mediaTypes': { video: { context: 'outstream' } },
      'transactionId': '62890707-3770-497c-a3b8-d905a2d0cb98',
      'sizes': [
        640,
        480
      ],
      'bidId': '23b86d8f6335ce',
      'bidderRequestId': '1d5b7474eb5416',
      'requestId': '406fe12b-fa3b-4bd3-b3c8-043951b4dac1'
    }
  }

  function createParams(...bids) {
    return {
      'bidderCode': 'unruly',
      'requestId': '406fe12b-fa3b-4bd3-b3c8-043951b4dac1',
      'bidderRequestId': '1d5b7474eb5416',
      'bids': bids,
      'start': 1495794517251,
      'auctionStart': 1495794517250,
      'timeout': 3000
    }
  }

  function createOutStreamExchangeBid({ placementCode, statusCode = 1 }) {
    return {
      'ext': {
        'statusCode': statusCode,
        'renderer': {
          'id': 'unruly_inarticle',
          'config': {},
          'url': 'https://video.unrulymedia.com/native/prebid-loader.js'
        },
        'placementCode': placementCode
      },
      'cpm': 20,
      'bidderCode': 'unruly',
      'width': 323,
      'vastUrl': 'https://targeting.unrulymedia.com/in_article?uuid=74544e00-d43b-4f3a-a799-69d22ce979ce&supported_mime_type=application/javascript&supported_mime_type=video/mp4&tj=%7B%22site%22%3A%7B%22lang%22%3A%22en-GB%22%2C%22ref%22%3A%22%22%2C%22page%22%3A%22http%3A%2F%2Fdemo.unrulymedia.com%2FinArticle%2Finarticle_nypost_upbeat%2Ftravel_magazines.html%22%2C%22domain%22%3A%22demo.unrulymedia.com%22%7D%2C%22user%22%3A%7B%22profile%22%3A%7B%22quantcast%22%3A%7B%22segments%22%3A%5B%7B%22id%22%3A%22D%22%7D%2C%7B%22id%22%3A%22T%22%7D%5D%7D%7D%7D%7D&video_width=618&video_height=347',
      'bidId': 'foo',
      'height': 323
    }
  }

  function createInStreamExchangeBid({ placementCode, statusCode = 1 }) {
    return {
      'ext': {
        'statusCode': statusCode,
        'placementCode': placementCode
      },
      'cpm': 20,
      'bidderCode': 'unruly',
      'width': 323,
      'vastUrl': 'https://targeting.unrulymedia.com/in_article?uuid=74544e00-d43b-4f3a-a799-69d22ce979ce&supported_mime_type=application/javascript&supported_mime_type=video/mp4&tj=%7B%22site%22%3A%7B%22lang%22%3A%22en-GB%22%2C%22ref%22%3A%22%22%2C%22page%22%3A%22http%3A%2F%2Fdemo.unrulymedia.com%2FinArticle%2Finarticle_nypost_upbeat%2Ftravel_magazines.html%22%2C%22domain%22%3A%22demo.unrulymedia.com%22%7D%2C%22user%22%3A%7B%22profile%22%3A%7B%22quantcast%22%3A%7B%22segments%22%3A%5B%7B%22id%22%3A%22D%22%7D%2C%7B%22id%22%3A%22T%22%7D%5D%7D%7D%7D%7D&video_width=618&video_height=347',
      'bidId': 'foo',
      'height': 323
    }
  }

  function createExchangeResponse(...bids) {
    return {
      'bids': bids
    }
  }

  let adapter
  let server
  let sandbox
  let fakeRenderer

  beforeEach(() => {
    adapter = createUnrulyAdapter()
    adapter.exchangeUrl = 'http://localhost:9000/prebid'

    sandbox = sinon.sandbox.create()
    sandbox.stub(bidmanager, 'addBidResponse')
    sandbox.stub(bidfactory, 'createBid')
    sandbox.stub(utils, 'logError')

    fakeRenderer = {
      setRender: sinon.stub()
    }

    sandbox.stub(Renderer, 'install')
    Renderer.install.returns(fakeRenderer)

    server = sinon.fakeServer.create()
  })

  afterEach(() => {
    sandbox.restore()
    server.restore()
    delete parent.window.unruly
  })

  describe('callBids', () => {
    it('exists and is a function', () => {
      expect(adapter.callBids).to.exist.and.to.be.a('function')
    })

    it('requires bids to make request', () => {
      adapter.callBids({})
      expect(server.requests).to.be.empty
    })

    it('requires at least one bid to make request', () => {
      adapter.callBids({ bids: [] })
      expect(server.requests).to.be.empty
    })

    it('passes bids through to exchange', () => {
      const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))

      adapter.callBids(params)

      expect(server.requests).to.have.length(1)
      expect(server.requests[0].url).to.equal('http://localhost:9000/prebid')

      const requestBody = JSON.parse(server.requests[0].requestBody)
      expect(requestBody).to.deep.equal({
        'bidRequests': params.bids
      })
    })

    it('creates a bid response using status code from exchange for each bid and passes in the exchange response', () => {
      const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))

      const exchangeBid1 = createOutStreamExchangeBid({ placementCode: 'placement1' })
      const exchangeBid2 = createOutStreamExchangeBid({ placementCode: 'placement2', statusCode: 2 })
      const exchangeResponse = createExchangeResponse(exchangeBid1, exchangeBid2)

      server.respondWith(JSON.stringify(exchangeResponse))
      bidfactory.createBid.returns({})

      adapter.callBids(params)
      server.respond()

      sinon.assert.calledTwice(bidfactory.createBid)
      sinon.assert.calledWith(bidfactory.createBid, exchangeBid1.ext.statusCode, exchangeResponse.bids[0])
      sinon.assert.calledWith(bidfactory.createBid, exchangeBid2.ext.statusCode, exchangeResponse.bids[1])
    })

    it('adds the bid response to the bid manager', () => {
      const fakeBid = {}

      const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))
      const exchangeBid = createOutStreamExchangeBid({ placementCode: 'placement1' })
      const exchangeResponse = createExchangeResponse(exchangeBid)

      server.respondWith(JSON.stringify(exchangeResponse))
      bidfactory.createBid.withArgs(exchangeBid.ext.statusCode).returns(fakeBid)

      adapter.callBids(params)
      server.respond()

      sinon.assert.calledOnce(bidmanager.addBidResponse)
      sinon.assert.calledWith(bidmanager.addBidResponse, exchangeBid.ext.placementCode, fakeBid)
    })

    describe('on invalid exchange response', () => {
      it('should create NO_BID response for each bid request bid', () => {
        const bidRequestBid1 = createBidRequestBid({ placementCode: 'placement1' })
        const bidRequestBid2 = createBidRequestBid({ placementCode: 'placement2' })
        const params = createParams(bidRequestBid1, bidRequestBid2)
        const expectedBid = { 'some': 'props' }

        server.respondWith('this is not json')
        bidfactory.createBid.withArgs(STATUS.NO_BID).returns(expectedBid)

        adapter.callBids(params)
        server.respond()

        sinon.assert.calledOnce(utils.logError)
        sinon.assert.calledTwice(bidmanager.addBidResponse)
        sinon.assert.calledWith(bidmanager.addBidResponse, bidRequestBid1.placementCode, expectedBid)
        sinon.assert.calledWith(bidmanager.addBidResponse, bidRequestBid2.placementCode, expectedBid)
      })
    })

    describe('InStream', () => {
      it('merges bid response defaults', () => {
        const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))

        const fakeBidDefaults = { some: 'default' }
        const fakeBid = Object.assign({}, fakeBidDefaults)

        const exchangeBid = createInStreamExchangeBid({ placementCode: 'placement1' })
        const exchangeResponse = createExchangeResponse(exchangeBid)
        server.respondWith(JSON.stringify(exchangeResponse))

        bidfactory.createBid.withArgs(exchangeBid.ext.statusCode).returns(fakeBid)

        adapter.callBids(params)
        server.respond()

        sinon.assert.notCalled(Renderer.install)
        expect(fakeBid).to.deep.equal(Object.assign(
          {},
          fakeBidDefaults,
          exchangeBid
        ))
      })
    })

    describe('OutStream', () => {
      it('merges bid response defaults with exchange bid and renderer', () => {
        const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))

        const fakeBidDefaults = { some: 'default' }
        const fakeBid = Object.assign({}, fakeBidDefaults)

        const exchangeBid = createOutStreamExchangeBid({ placementCode: 'placement1' })
        const exchangeResponse = createExchangeResponse(exchangeBid)
        server.respondWith(JSON.stringify(exchangeResponse))

        bidfactory.createBid.withArgs(exchangeBid.ext.statusCode).returns(fakeBid)

        const fakeRenderer = {}
        Renderer.install.withArgs(Object.assign(
          {},
          exchangeBid.ext.renderer,
          { callback: sinon.match.func }
        )).returns(fakeRenderer)

        adapter.callBids(params)
        server.respond()

        expect(fakeBid).to.deep.equal(Object.assign(
          {},
          fakeBidDefaults,
          exchangeBid,
          { renderer: fakeRenderer }
        ))
      })

      it('bid is placed on the bid queue when render is called', () => {
        const params = createParams(createBidRequestBid({ placementCode: 'placement1' }))

        const fakeBidDefaults = { some: 'default' }
        const fakeBid = Object.assign({}, fakeBidDefaults)

        const exchangeBid = createOutStreamExchangeBid({ placementCode: 'placement1' })
        const exchangeResponse = createExchangeResponse(exchangeBid)
        server.respondWith(JSON.stringify(exchangeResponse))

        bidfactory.createBid.withArgs(exchangeBid.ext.statusCode).returns(fakeBid)

        adapter.callBids(params)
        server.respond()

        sinon.assert.calledOnce(fakeRenderer.setRender)
        fakeRenderer.setRender.firstCall.args[0]()

        expect(window.top).to.have.deep.property('unruly.native.prebid.uq');
        expect(window.top.unruly.native.prebid.uq).to.deep.equal([['render', fakeBid]])
      })
    })
  })
})


text:
package org.jboss.resteasy.spi;

/**
 * Implement this interface and annotate your class with @Provider to provide marshalling and unmarshalling
 * of string-based, @HeaderParam, @MatrixParam, @QueryParam, and/or @PathParam injected values.
 *

 * Use this when toString(), valueOf, and/or constructor(String) can not satisfy your marshalling requirements.
 *
 * @author Bill Burke
 * @version $Revision: 1 $
 */
@Deprecated
public interface StringConverter<T>
{
   T fromString(String str);

   String toString(T value);
}


text:
<?php

namespace Twig\NodeVisitor;

use Twig\Environment;
use Twig\Node\Expression\AssignNameExpression;
use Twig\Node\Expression\ConstantExpression;
use Twig\Node\Expression\GetAttrExpression;
use Twig\Node\Expression\MethodCallExpression;
use Twig\Node\Expression\NameExpression;
use Twig\Node\ImportNode;
use Twig\Node\ModuleNode;
use Twig\Node\Node;

/**
 * @author Fabien Potencier <fabien@symfony.com>
 */
final class MacroAutoImportNodeVisitor implements NodeVisitorInterface
{
    private $inAModule = false;
    private $hasMacroCalls = false;

    public function enterNode(Node $node, Environment $env): Node
    {
        if ($node instanceof ModuleNode) {
            $this->inAModule = true;
            $this->hasMacroCalls = false;
        }

        return $node;
    }

    public function leaveNode(Node $node, Environment $env): Node
    {
        if ($node instanceof ModuleNode) {
            $this->inAModule = false;
            if ($this->hasMacroCalls) {
                $node->getNode('constructor_end')->setNode('_auto_macro_import', new ImportNode(new NameExpression('_self', 0), new AssignNameExpression('_self', 0), 0, 'import', true));
            }
        } elseif ($this->inAModule) {
            if (
                $node instanceof GetAttrExpression &&
                $node->getNode('node') instanceof NameExpression &&
                '_self' === $node->getNode('node')->getAttribute('name') &&
                $node->getNode('attribute') instanceof ConstantExpression
            ) {
                $this->hasMacroCalls = true;

                $name = $node->getNode('attribute')->getAttribute('value');
                $node = new MethodCallExpression($node->getNode('node'), 'macro_'.$name, $node->getNode('arguments'), $node->getTemplateLine());
                $node->setAttribute('safe', true);
            }
        }

        return $node;
    }

    public function getPriority(): int
    {
        // we must be ran before auto-escaping
        return -10;
    }
}


text:
{% extends 'base_info.html' %}

{% block title %}developer{% endblock %}

{% block description %}
	This page is under development.
{% endblock %}


text:
<?php

namespace TenilUser\Entity;

// Uso padrão do doctrine, criado na geração automática do arquivo por linha de comando.
use Doctrine\ORM\Mapping as ORM;
// Usado para geração de valores para o salt.
use Zend\Stdlib\Hydrator;

/**
 * @ORM\Entity
 * @ORM\Table(name="teniluser_tipo_tratamento")
 * @ORM\Entity(repositoryClass="TenilUser\Entity\PerfilTratamentoRepository")
 */
class PerfilTratamento {

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string
     *
     * @ORM\Column(name="nome", type="string", length=45, nullable=false)
     */
    private $nome;

    /**
     * @var string
     *
     * @ORM\Column(name="abreviacao", type="string", length=45, nullable=false)
     */
    private $abreviacao;

    /**
     * @param array $options
     */
    public function __construct(array $options = array()) {
        (new Hydrator\ClassMethods)->hydrate($options, $this);
    }

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

    /**
     * @return string
     */
    function getNome() {
        return $this->nome;
    }

    /**
     * @return string
     */
    function getAbreviacao() {
        return $this->abreviacao;
    }

    /**
     * @param $id
     * @return $this
     */
    function setId($id) {
        $this->id = $id;
        return $this;
    }

    /**
     * @param $nome
     * @return $this
     */
    function setNome($nome) {
        $this->nome = $nome;
        return $this;
    }

    /**
     * @param $abreviacao
     * @return $this
     */
    function setAbreviacao($abreviacao) {
        $this->abreviacao = $abreviacao;
        return $this;
    }

    /**
     * @return string
     */
    public function __toString() {
        return $this->getAbreviacao();
    }

    /**
     * @return array
     */
    public function __toArray() {
        return (new Hydrator\ClassMethods)->extract($this);
    }

}


text:
class StringControl : public ControlBase<Poly::String>
{
public:
	StringControl(QWidget* parent);

	void Reset() override;
	void UpdateControl() override;

	void SetText(String text) { Field->setText(text.GetCStr()); }

private:
	void UpdateObject();

	QLineEdit* Field;
};


text:
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.

/*=============================================================================
	EmptyVertexBuffer.cpp: Empty vertex buffer RHI implementation.
=============================================================================*/

#include "EmptyRHIPrivate.h"

FEmptyVertexBuffer::FEmptyVertexBuffer(uint32 InSize, uint32 InUsage)
	: FRHIVertexBuffer(InSize, InUsage)
{
}

void* FEmptyVertexBuffer::Lock(EResourceLockMode LockMode, uint32 Size)
{
	return NULL;
}

void FEmptyVertexBuffer::Unlock()
{

}

FVertexBufferRHIRef FEmptyDynamicRHI::RHICreateVertexBuffer(uint32 Size, uint32 InUsage, FRHIResourceCreateInfo& CreateInfo)
{
	// make the RHI object, which will allocate memory
	FEmptyVertexBuffer* VertexBuffer = new FEmptyVertexBuffer(Size, InUsage);

	if(CreateInfo.ResourceArray)
	{
		check(Size == CreateInfo.ResourceArray->GetResourceDataSize());

		// make a buffer usable by CPU
		void* Buffer = RHILockVertexBuffer(VertexBuffer, 0, Size, RLM_WriteOnly);

		// copy the contents of the given data into the buffer
		FMemory::Memcpy(Buffer, CreateInfo.ResourceArray->GetResourceData(), Size);

		RHIUnlockVertexBuffer(VertexBuffer);

		// Discard the resource array's contents.
		CreateInfo.ResourceArray->Discard();
	}

	return VertexBuffer;
}

void* FEmptyDynamicRHI::RHILockVertexBuffer(FVertexBufferRHIParamRef VertexBufferRHI, uint32 Offset, uint32 Size, EResourceLockMode LockMode)
{
	FEmptyVertexBuffer* VertexBuffer = ResourceCast(VertexBufferRHI);

	// default to vertex buffer memory
	return (uint8*)VertexBuffer->Lock(LockMode, Size) + Offset;
}

void FEmptyDynamicRHI::RHIUnlockVertexBuffer(FVertexBufferRHIParamRef VertexBufferRHI)
{
	FEmptyVertexBuffer* VertexBuffer = ResourceCast(VertexBufferRHI);

	VertexBuffer->Unlock();
}

void FEmptyDynamicRHI::RHICopyVertexBuffer(FVertexBufferRHIParamRef SourceBufferRHI,FVertexBufferRHIParamRef DestBufferRHI)
{

}


text:
pyflrtree
=========

Pure python implementation of factional cascading layered range tree

  - only depends on python standard libraries when using (needs setuptools for installing, of course)
  - `O(n*log(n)**d)` space complexity
  - `O(n*log(n)**d)` constructing time complexity
  - `O(log(n)**(d-1)+k)` querying time complexity

Only supports Python 3 now.

All comparable python objects are OK.

When limit to numpy 3d array with `len(x)>1000`, this query implementation is commonly faster than `scipy.spatial.KDTree`.(but is still slower than `scipy.spatial.cKDTree` due to Python intrinsic speed)

The construction time is much longer than kd-trees so this layered range tree is suitable for a large data set with an event larger number of query times.

checkout and install:
```bash
git clone https://github.com/epsilony/pyflrtree.git
pip install -e pyflrtree
```

query multi-dimensional data:
```python
from flrtree import LRTree

...
tree=LRTree(data)

indes=tree.query(lower,upper)
```

run some blackbox tests:
```
import flrtree
flrtree.test()
```


text:
_[www.codever.land/bookmarks/t/github-pages](https://www.codever.land/bookmarks/t/github-pages)_
---
#### [GitHub Pages home page](https://pages.github.com/)
_https://pages.github.com/_

Websites for you and your projects, hosted directly from your GitHub repository. Just edit, push, and your changes are live

Useful setup links:
- [Using a custom domain with GitHub Pages](https://hel...
* **tags**: [github](../tagged/github.md), [github-pages](../tagged/github-pages.md)
---
#### [Dependency versions](https://pages.github.com/versions/)
_https://pages.github.com/versions/_

GitHub Pages uses the following dependencies and versions
* **tags**: [github-pages](../tagged/github-pages.md)
---
#### [Using Jekyll as a static site generator with GitHub Pages - User Documentation        ](https://help.github.com/articles/using-jekyll-as-a-static-site-generator-with-github-pages/)
_https://help.github.com/articles/using-jekyll-as-a-static-site-generator-with-github-pages/_

If you use Jekyll as a static site generator with GitHub Pages, you benefit from more support with setting up, updating, and troubleshooting your site.

Hyperlinks to Github and Jekyll
* **tags**: [github-pages](../tagged/github-pages.md), [jekyll](../tagged/jekyll.md), [docs](../tagged/docs.md)
---
#### [Collection: GitHub Pages examples · GitHub](https://github.com/collections/github-pages-examples)
_https://github.com/collections/github-pages-examples_

Fine examples of projects using [GitHub Pages](https://pages.github.com/)
* **tags**: [github](../tagged/github.md), [github-pages](../tagged/github-pages.md)
---
#### [Staticman: Static sites with superpowers](https://staticman.net/)
_https://staticman.net/_

Staticman is a Node.js application that receives user-generated content and uploads it as data files to a GitHub repository. In practice, this allows you to have dynamic content (e.g. blog post commen...
* **tags**: [blogging](../tagged/blogging.md), [github-pages](../tagged/github-pages.md), [jekyll](../tagged/jekyll.md)
* :octocat: **[source code](https://github.com/eduardoboucas/staticman)**
---
#### [ GitHub Pages now faster and simpler with Jekyll 3.0 · GitHub](https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0)
_https://github.com/blog/2100-github-pages-now-faster-and-simpler-with-jekyll-3-0_

Describes enhancements on GitHub Pages that come with the update to [Jekyll 3.0](https://jekyllrb.com/news/2015/10/26/jekyll-3-0-released/)
* **tags**: [markdown](../tagged/markdown.md), [github-pages](../tagged/github-pages.md)
---
#### [Setting up your GitHub Pages site locally with Jekyll - User Documentation        ](https://help.github.com/articles/setting-up-your-github-pages-site-locally-with-jekyll/)
_https://help.github.com/articles/setting-up-your-github-pages-site-locally-with-jekyll/_

Guide on how to install Jekyll locally, build the website locally, keep site up to date etc.

* **tags**: [github-pages](../tagged/github-pages.md), [jekyll](../tagged/jekyll.md)
---


text:
package http

import (
	"context"
	"fmt"
	"net/http"
	"path"
	"regexp"
	"strings"
	"time"

	"github.com/go-chi/chi"
	"github.com/influxdata/influxdb/v2/kit/platform"
	"github.com/influxdata/influxdb/v2/kit/platform/errors"
	"github.com/influxdata/influxdb/v2/kit/tracing"
	ua "github.com/mileusna/useragent"
	"github.com/prometheus/client_golang/prometheus"
)

// Middleware constructor.
type Middleware func(http.Handler) http.Handler

// SetCORS configures various headers to relax CORS browser checks
//
// Browsers implement Cross-Origin Resource Sharing (CORS) checks to limit
// cross-origin accesses in HTTP requests. Various CORS headers can be used to
// relax the standard, strict browser behavior. For details on CORS, see:
// https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
//
// IMPORTANT: default CORS checks disallows attaching credentials (eg, session
// cookie) with cross-origin requests (even when Access-Control-Allow-Origin is
// set to the Origin) and we omit the 'Access-Control-Allow-Credentials' header
// here to preserve this behavior. Omitting this header provides security
// defense-in-depth.
func SetCORS(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if origin := r.Header.Get("Origin"); origin != "" {
			// Access-Control-Allow-Origin must be present in every response
			w.Header().Set("Access-Control-Allow-Origin", origin)
		}
		if r.Method == http.MethodOptions {
			// allow and stop processing in pre-flight requests
			w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, PATCH")
			w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, Authorization, User-Agent")
			w.WriteHeader(http.StatusNoContent)
			return
		}
		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func Metrics(name string, reqMetric *prometheus.CounterVec, durMetric *prometheus.HistogramVec) Middleware {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			statusW := NewStatusResponseWriter(w)

			defer func(start time.Time) {
				statusCode := statusW.Code()
				// only log metrics for 2XX or 5XX requests
				if !reportFromCode(statusCode) {
					return
				}

				label := prometheus.Labels{
					"handler":       name,
					"method":        r.Method,
					"path":          normalizePath(r.URL.Path),
					"status":        statusW.StatusCodeClass(),
					"response_code": fmt.Sprintf("%d", statusCode),
					"user_agent":    UserAgent(r),
				}

				durMetric.With(label).Observe(time.Since(start).Seconds())
				reqMetric.With(label).Inc()
			}(time.Now())

			next.ServeHTTP(statusW, r)
		}
		return http.HandlerFunc(fn)
	}
}

func SkipOptions(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		// Preflight CORS requests from the browser will send an options request,
		// so we need to make sure we satisfy them
		if origin := r.Header.Get("Origin"); origin == "" && r.Method == http.MethodOptions {
			w.WriteHeader(http.StatusMethodNotAllowed)
			return
		}

		next.ServeHTTP(w, r)
	}
	return http.HandlerFunc(fn)
}

func Trace(name string) Middleware {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			span, r := tracing.ExtractFromHTTPRequest(r, name)
			defer span.Finish()

			span.LogKV("user_agent", UserAgent(r))
			for k, v := range r.Header {
				if len(v) == 0 {
					continue
				}

				if k == "Authorization" || k == "User-Agent" {
					continue
				}

				// If header has multiple values, only the first value will be logged on the trace.
				span.LogKV(k, v[0])
			}

			next.ServeHTTP(w, r)
		}
		return http.HandlerFunc(fn)
	}
}

func UserAgent(r *http.Request) string {
	header := r.Header.Get("User-Agent")
	if header == "" {
		return "unknown"
	}

	return ua.Parse(header).Name
}

// Constants used for normalizing paths
const (
	fileSlug  = ":file_name"
	shardSlug = ":shard_id"
)

func normalizePath(p string) string {
	// Normalize any paths used during backup or restore processes
	p = normalizeBackupAndRestore(p)

	// Go through each part of the path and normalize IDs and UI assets
	var parts []string
	for head, tail := shiftPath(p); ; head, tail = shiftPath(tail) {
		piece := head

		// Normalize any ID's in the path as the ":id" slug
		if len(piece) == platform.IDLength {
			if _, err := platform.IDFromString(head); err == nil {
				piece = ":id"
			}
		}
		parts = append(parts, piece)

		if tail == "/" {
			// Normalize UI asset file names. The UI asset file is the last part of the path.
			parts[len(parts)-1] = normalizeAssetFile(parts[len(parts)-1])
			break
		}
	}
	return "/" + path.Join(parts...)
}

func shiftPath(p string) (head, tail string) {
	p = path.Clean("/" + p)
	i := strings.Index(p[1:], "/") + 1
	if i <= 0 {
		return p[1:], "/"
	}
	return p[1:i], p[i:]
}

// Normalize the file name for a UI asset
// For example: 838442d56d.svg will return as :file_id.svg
// Files names that do not have one of the listed extensions will be returned unchanged
func normalizeAssetFile(f string) string {
	exts := []string{
		".js",
		".svg",
		".woff2",
		".wasm",
		".map",
		".LICENSE",
		".ttf",
		".woff",
		".eot",
	}

	for _, ext := range exts {
		if strings.HasSuffix(f, ext) {
			return fileSlug + ext
		}
	}

	return f
}

// Normalize paths used during the backup and restore process.
// Paths not matching any of the patterns will be returned unchanged.
func normalizeBackupAndRestore(pth string) string {
	patterns := map[string]string{
		`restore/shards/\d+`: path.Join("restore/shards", shardSlug),
		`backup/shards/\d+`:  path.Join("backup/shards", shardSlug),
	}

	for p, s := range patterns {
		re := regexp.MustCompile(p)
		if re.MatchString(pth) {
			return re.ReplaceAllString(pth, s)
		}
	}

	return pth
}

type OrgContext string

const CtxOrgKey OrgContext = "orgID"

// ValidResource make sure a resource exists when a sub system needs to be mounted to an api
func ValidResource(api *API, lookupOrgByResourceID func(context.Context, platform.ID) (platform.ID, error)) Middleware {
	return func(next http.Handler) http.Handler {
		fn := func(w http.ResponseWriter, r *http.Request) {
			statusW := NewStatusResponseWriter(w)
			id, err := platform.IDFromString(chi.URLParam(r, "id"))
			if err != nil {
				api.Err(w, r, platform.ErrCorruptID(err))
				return
			}

			ctx := r.Context()

			orgID, err := lookupOrgByResourceID(ctx, *id)
			if err != nil {
				// if this function returns an error we will squash the error message and replace it with a not found error
				api.Err(w, r, &errors.Error{
					Code: errors.ENotFound,
					Msg:  "404 page not found",
				})
				return
			}

			// embed OrgID into context
			next.ServeHTTP(statusW, r.WithContext(context.WithValue(ctx, CtxOrgKey, orgID)))
		}
		return http.HandlerFunc(fn)
	}
}

// OrgIDFromContext ....
func OrgIDFromContext(ctx context.Context) *platform.ID {
	v := ctx.Value(CtxOrgKey)
	if v == nil {
		return nil
	}
	id := v.(platform.ID)
	return &id
}

// reportFromCode is a helper function to determine if telemetry data should be
// reported for this response.
func reportFromCode(c int) bool {
	return (c >= 200 && c <= 299) || (c >= 500 && c <= 599)
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>Refs (apache-cassandra API)</title>
<meta name="date" content="2016-04-13">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.cassandra.utils.concurrent

Class Refs<T extends RefCounted<T>>

java.lang.Object

java.util.AbstractCollection<T>

org.apache.cassandra.utils.concurrent.Refs<T>

All Implemented Interfaces:

java.lang.AutoCloseable, java.lang.Iterable<T>, java.util.Collection<T>

public final class Refs<T extends RefCounted<T>>
extends java.util.AbstractCollection<T>
implements java.lang.AutoCloseable

A collection of managed Ref references to RefCounted objects, and the objects they are referencing.
 Care MUST be taken when using this collection, as if a permanent reference to it leaks we will not
 be alerted to a lack of reference release.

 All of the java.util.Collection operations that modify the collection are unsupported.

Constructor Summary

Constructors

Constructor and Description

Refs()

Refs(java.util.Map<T,Ref<T>> references)

Method Summary

All Methods Static Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

Refs<T>
addAll(Refs<T> add)

Merge two sets of references, ensuring only one reference is retained between the two sets

void
close()

See release()

Ref<T>
get(T referenced)

java.util.Iterator<T>
iterator()

static <T extends RefCounted<T>>
Refs<T>
ref(java.lang.Iterable<T> reference)

void
relaseAllExcept(java.util.Collection<T> keep)

void
release()

Release ALL of the references held by this Refs collection

void
release(java.util.Collection<T> release)

Release a retained Ref to all of the provided objects; if any is not held, an exception will be thrown

static void
release(java.lang.Iterable<? extends Ref<?>> refs)

static java.lang.Throwable
release(java.lang.Iterable<? extends Ref<?>> refs,
       java.lang.Throwable accumulate)

void
release(T referenced)

boolean
releaseIfHolds(T referenced)

Release the retained Ref to the provided object, if held, return false otherwise

static <T extends SelfRefCounted<T>>
java.lang.Iterable<Ref<T>>
selfRefs(java.lang.Iterable<T> refs)

int
size()

static <T extends RefCounted<T>>
Refs<T>
tryRef(java.lang.Iterable<T> reference)

Acquire a reference to all of the provided objects, or none

boolean
tryRef(T t)

Attempt to take a reference to the provided object; if it has already been released, null will be returned

Methods inherited from class java.util.AbstractCollection

add, addAll, clear, contains, containsAll, isEmpty, remove, removeAll, retainAll, toArray, toArray, toString

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Methods inherited from interface java.util.Collection

equals, hashCode, parallelStream, removeIf, spliterator, stream

Methods inherited from interface java.lang.Iterable

forEach

Constructor Detail

Refs

public Refs()

Refs

public Refs(java.util.Map<T,Ref<T>> references)

Method Detail

release

public void release()

Release ALL of the references held by this Refs collection

close

public void close()

See release()

Specified by:

close in interface java.lang.AutoCloseable

get

public Ref<T> get(T referenced)

Parameters:

referenced - the object we have a Ref to

Returns:

the Ref to said object

release

public void release(T referenced)

Parameters:

referenced - the object we have a Ref to

releaseIfHolds

public boolean releaseIfHolds(T referenced)

Release the retained Ref to the provided object, if held, return false otherwise

Parameters:

referenced - the object we retain a Ref to

Returns:

return true if we held a reference to the object, and false otherwise

relaseAllExcept

public void relaseAllExcept(java.util.Collection<T> keep)

release

public void release(java.util.Collection<T> release)

Release a retained Ref to all of the provided objects; if any is not held, an exception will be thrown

Parameters:

release -

tryRef

public boolean tryRef(T t)

Attempt to take a reference to the provided object; if it has already been released, null will be returned

Parameters:

t - object to acquire a reference to

Returns:

true iff success

iterator

public java.util.Iterator<T> iterator()

Specified by:

iterator in interface java.lang.Iterable<T extends RefCounted<T>>

Specified by:

iterator in interface java.util.Collection<T extends RefCounted<T>>

Specified by:

iterator in class java.util.AbstractCollection<T extends RefCounted<T>>

size

public int size()

Specified by:

size in interface java.util.Collection<T extends RefCounted<T>>

Specified by:

size in class java.util.AbstractCollection<T extends RefCounted<T>>

addAll

public Refs<T> addAll(Refs<T> add)

Merge two sets of references, ensuring only one reference is retained between the two sets

tryRef

public static <T extends RefCounted<T>> Refs<T> tryRef(java.lang.Iterable<T> reference)

Acquire a reference to all of the provided objects, or none

ref

public static <T extends RefCounted<T>> Refs<T> ref(java.lang.Iterable<T> reference)

release

public static void release(java.lang.Iterable<? extends Ref<?>> refs)

release

public static java.lang.Throwable release(java.lang.Iterable<? extends Ref<?>> refs,
                                          java.lang.Throwable accumulate)

selfRefs

public static <T extends SelfRefCounted<T>> java.lang.Iterable<Ref<T>> selfRefs(java.lang.Iterable<T> refs)

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Copyright © 2016 The Apache Software Foundation


text:
package com.phonegap;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.phonegap.api.PhonegapActivity;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;

import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.content.Context;

/**
 * This class listens to the accelerometer sensor and stores the latest
 * acceleration values x,y,z.
 */
public class AccelListener extends Plugin implements SensorEventListener {

	public static int STOPPED = 0;
	public static int STARTING = 1;
    public static int RUNNING = 2;
    public static int ERROR_FAILED_TO_START = 3;

    public float TIMEOUT = 30000;		// Timeout in msec to shut off listener

    float x,y,z;						// most recent acceleration values
    long timestamp;						// time of most recent value
    int status;							// status of listener
    long lastAccessTime;				// time the value was last retrieved

    private SensorManager sensorManager;// Sensor manager
    Sensor mSensor;						// Acceleration sensor returned by sensor manager

    /**
     * Create an accelerometer listener.
     */
    public AccelListener() {
        this.x = 0;
        this.y = 0;
        this.z = 0;
        this.timestamp = 0;
        this.setStatus(AccelListener.STOPPED);
     }

	/**
	 * Sets the context of the Command. This can then be used to do things like
	 * get file paths associated with the Activity.
	 *
	 * @param ctx The context of the main Activity.
	 */
	public void setContext(PhonegapActivity ctx) {
		super.setContext(ctx);
        this.sensorManager = (SensorManager) ctx.getSystemService(Context.SENSOR_SERVICE);
	}

	/**
	 * Executes the request and returns PluginResult.
	 *
	 * @param action 		The action to execute.
	 * @param args 			JSONArry of arguments for the plugin.
	 * @param callbackId	The callback id used when calling back into JavaScript.
	 * @return 				A PluginResult object with a status and message.
	 */
	public PluginResult execute(String action, JSONArray args, String callbackId) {
		PluginResult.Status status = PluginResult.Status.OK;
		String result = "";

		try {
			if (action.equals("getStatus")) {
				int i = this.getStatus();
				return new PluginResult(status, i);
			}
			else if (action.equals("start")) {
				int i = this.start();
				return new PluginResult(status, i);
			}
			else if (action.equals("stop")) {
				this.stop();
				return new PluginResult(status, 0);
			}
			else if (action.equals("getAcceleration")) {
				// If not running, then this is an async call, so don't worry about waiting
				if (this.status != AccelListener.RUNNING) {
					int r = this.start();
					if (r == AccelListener.ERROR_FAILED_TO_START) {
						return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
					}
					// Wait until running
					long timeout = 2000;
					while ((this.status == STARTING) && (timeout > 0)) {
						timeout = timeout - 100;
						try {
							Thread.sleep(100);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
					if (timeout == 0) {
						return new PluginResult(PluginResult.Status.IO_EXCEPTION, AccelListener.ERROR_FAILED_TO_START);
					}
				}
	            this.lastAccessTime = System.currentTimeMillis();
				JSONObject r = new JSONObject();
				r.put("x", this.x);
				r.put("y", this.y);
				r.put("z", this.z);
				// TODO: Should timestamp be sent?
				r.put("timestamp", this.timestamp);
				return new PluginResult(status, r);
			}
			else if (action.equals("setTimeout")) {
				try {
					float timeout = Float.parseFloat(args.getString(0));
					this.setTimeout(timeout);
					return new PluginResult(status, 0);
				} catch (NumberFormatException e) {
					status = PluginResult.Status.INVALID_ACTION;
					e.printStackTrace();
				} catch (JSONException e) {
					status = PluginResult.Status.JSON_EXCEPTION;
					e.printStackTrace();
				}
			}
			else if (action.equals("getTimeout")) {
				float f = this.getTimeout();
				return new PluginResult(status, f);
			}
			return new PluginResult(status, result);
		} catch (JSONException e) {
			return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
		}
	}

	/**
	 * Identifies if action to be executed returns a value and should be run synchronously.
	 *
	 * @param action	The action to execute
	 * @return			T=returns value
	 */
	public boolean isSynch(String action) {
		if (action.equals("getStatus")) {
			return true;
		}
		else if (action.equals("getAcceleration")) {
			// Can only return value if RUNNING
			if (this.status == RUNNING) {
				return true;
			}
		}
		else if (action.equals("getTimeout")) {
			return true;
		}
		return false;
	}

    /**
     * Called by AccelBroker when listener is to be shut down.
     * Stop listener.
     */
    public void onDestroy() {
    	this.stop();
    }

    //--------------------------------------------------------------------------
    // LOCAL METHODS
    //--------------------------------------------------------------------------

    /**
     * Start listening for acceleration sensor.
     *
     * @return 			status of listener
     */
    public int start() {

		// If already starting or running, then just return
        if ((this.status == AccelListener.RUNNING) || (this.status == AccelListener.STARTING)) {
        	return this.status;
        }

        // Get accelerometer from sensor manager
        List<Sensor> list = this.sensorManager.getSensorList(Sensor.TYPE_ACCELEROMETER);

        // If found, then register as listener
        if ((list != null) && (list.size() > 0)) {
            this.mSensor = list.get(0);
            this.sensorManager.registerListener(this, this.mSensor, SensorManager.SENSOR_DELAY_FASTEST);
            this.setStatus(AccelListener.STARTING);
            this.lastAccessTime = System.currentTimeMillis();
        }

        // If error, then set status to error
        else {
            this.setStatus(AccelListener.ERROR_FAILED_TO_START);
        }

        return this.status;
    }

    /**
     * Stop listening to acceleration sensor.
     */
    public void stop() {
        if (this.status != AccelListener.STOPPED) {
        	this.sensorManager.unregisterListener(this);
        }
        this.setStatus(AccelListener.STOPPED);
    }

    /**
     * Called when the accuracy of the sensor has changed.
     *
     * @param sensor
     * @param accuracy
     */
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    /**
     * Sensor listener event.
     *
     * @param SensorEvent event
     */
    public void onSensorChanged(SensorEvent event) {

    	// Only look at accelerometer events
        if (event.sensor.getType() != Sensor.TYPE_ACCELEROMETER) {
            return;
        }

        // If not running, then just return
        if (this.status == AccelListener.STOPPED) {
        	return;
        }

        // Save time that event was received
        this.timestamp = System.currentTimeMillis();
        this.x = event.values[0];
        this.y = event.values[1];
        this.z = event.values[2];

        this.setStatus(AccelListener.RUNNING);

        // If values haven't been read for TIMEOUT time, then turn off accelerometer sensor to save power
		if ((this.timestamp - this.lastAccessTime) > this.TIMEOUT) {
			this.stop();
		}
    }

    /**
     * Get status of accelerometer sensor.
     *
     * @return			status
     */
	public int getStatus() {
		return this.status;
	}

	/**
	 * Set the timeout to turn off accelerometer sensor if getX() hasn't been called.
	 *
	 * @param timeout		Timeout in msec.
	 */
	public void setTimeout(float timeout) {
		this.TIMEOUT = timeout;
	}

	/**
	 * Get the timeout to turn off accelerometer sensor if getX() hasn't been called.
	 *
	 * @return timeout in msec
	 */
	public float getTimeout() {
		return this.TIMEOUT;
	}

	/**
	 * Set the status and send it to JavaScript.
	 * @param status
	 */
	private void setStatus(int status) {
		this.status = status;
	}

}


text:
xorg bdf angular font

![alt text](http://pixelmasochist.net/github/terminalpants-screenshot.png "terminalpants font")


text:
#include <assert.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <not-cancel.h>
#include "pthreadP.h"
#include <lowlevellock.h>
#include <stap-probe.h>

#ifndef LLL_MUTEX_LOCK
# define LLL_MUTEX_LOCK(mutex) \
  lll_lock ((mutex)->__data.__lock, PTHREAD_MUTEX_PSHARED (mutex))
# define LLL_MUTEX_TRYLOCK(mutex) \
  lll_trylock ((mutex)->__data.__lock)
# define LLL_ROBUST_MUTEX_LOCK(mutex, id) \
  lll_robust_lock ((mutex)->__data.__lock, id, \
		   PTHREAD_ROBUST_MUTEX_PSHARED (mutex))
#endif

static int __pthread_mutex_lock_full (pthread_mutex_t *mutex)
     __attribute_noinline__;

int
__pthread_mutex_lock (mutex)
     pthread_mutex_t *mutex;
{
  assert (sizeof (mutex->__size) >= sizeof (mutex->__data));

  unsigned int type = PTHREAD_MUTEX_TYPE (mutex);

  LIBC_PROBE (mutex_entry, 1, mutex);

  if (__builtin_expect (type & ~PTHREAD_MUTEX_KIND_MASK_NP, 0))
    return __pthread_mutex_lock_full (mutex);

  pid_t id = THREAD_GETMEM (THREAD_SELF, tid);

  if (__builtin_expect (type, PTHREAD_MUTEX_TIMED_NP)
      == PTHREAD_MUTEX_TIMED_NP)
    {
    simple:
      /* Normal mutex.  */
      LLL_MUTEX_LOCK (mutex);
      assert (mutex->__data.__owner == 0);
    }
  else if (__builtin_expect (type == PTHREAD_MUTEX_RECURSIVE_NP, 1))
    {
      /* Recursive mutex.  */

      /* Check whether we already hold the mutex.  */
      if (mutex->__data.__owner == id)
	{
	  /* Just bump the counter.  */
	  if (__builtin_expect (mutex->__data.__count + 1 == 0, 0))
	    /* Overflow of the counter.  */
	    return EAGAIN;

	  ++mutex->__data.__count;

	  return 0;
	}

      /* We have to get the mutex.  */
      LLL_MUTEX_LOCK (mutex);

      assert (mutex->__data.__owner == 0);
      mutex->__data.__count = 1;
    }
  else if (__builtin_expect (type == PTHREAD_MUTEX_ADAPTIVE_NP, 1))
    {
      if (! __is_smp)
	goto simple;

      if (LLL_MUTEX_TRYLOCK (mutex) != 0)
	{
	  int cnt = 0;
	  int max_cnt = MIN (MAX_ADAPTIVE_COUNT,
			     mutex->__data.__spins * 2 + 10);
	  do
	    {
	      if (cnt++ >= max_cnt)
		{
		  LLL_MUTEX_LOCK (mutex);
		  break;
		}

#ifdef BUSY_WAIT_NOP
	      BUSY_WAIT_NOP;
#endif
	    }
	  while (LLL_MUTEX_TRYLOCK (mutex) != 0);

	  mutex->__data.__spins += (cnt - mutex->__data.__spins) / 8;
	}
      assert (mutex->__data.__owner == 0);
    }
  else
    {
      assert (type == PTHREAD_MUTEX_ERRORCHECK_NP);
      /* Check whether we already hold the mutex.  */
      if (__builtin_expect (mutex->__data.__owner == id, 0))
	return EDEADLK;
      goto simple;
    }

  /* Record the ownership.  */
  mutex->__data.__owner = id;
#ifndef NO_INCR
  ++mutex->__data.__nusers;
#endif

  LIBC_PROBE (mutex_acquired, 1, mutex);

  return 0;
}

static int
__pthread_mutex_lock_full (pthread_mutex_t *mutex)
{
  int oldval;
  pid_t id = THREAD_GETMEM (THREAD_SELF, tid);

  switch (PTHREAD_MUTEX_TYPE (mutex))
    {
    case PTHREAD_MUTEX_ROBUST_RECURSIVE_NP:
    case PTHREAD_MUTEX_ROBUST_ERRORCHECK_NP:
    case PTHREAD_MUTEX_ROBUST_NORMAL_NP:
    case PTHREAD_MUTEX_ROBUST_ADAPTIVE_NP:
      THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending,
		     &mutex->__data.__list.__next);

      oldval = mutex->__data.__lock;
      do
	{
	again:
	  if ((oldval & FUTEX_OWNER_DIED) != 0)
	    {
	      /* The previous owner died.  Try locking the mutex.  */
	      int newval = id;
#ifdef NO_INCR
	      newval |= FUTEX_WAITERS;
#else
	      newval |= (oldval & FUTEX_WAITERS);
#endif

	      newval
		= atomic_compare_and_exchange_val_acq (&mutex->__data.__lock,
						       newval, oldval);

	      if (newval != oldval)
		{
		  oldval = newval;
		  goto again;
		}

	      /* We got the mutex.  */
	      mutex->__data.__count = 1;
	      /* But it is inconsistent unless marked otherwise.  */
	      mutex->__data.__owner = PTHREAD_MUTEX_INCONSISTENT;

	      ENQUEUE_MUTEX (mutex);
	      THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);

	      /* Note that we deliberately exit here.  If we fall
		 through to the end of the function __nusers would be
		 incremented which is not correct because the old
		 owner has to be discounted.  If we are not supposed
		 to increment __nusers we actually have to decrement
		 it here.  */
#ifdef NO_INCR
	      --mutex->__data.__nusers;
#endif

	      return EOWNERDEAD;
	    }

	  /* Check whether we already hold the mutex.  */
	  if (__builtin_expect ((oldval & FUTEX_TID_MASK) == id, 0))
	    {
	      int kind = PTHREAD_MUTEX_TYPE (mutex);
	      if (kind == PTHREAD_MUTEX_ROBUST_ERRORCHECK_NP)
		{
		  THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending,
				 NULL);
		  return EDEADLK;
		}

	      if (kind == PTHREAD_MUTEX_ROBUST_RECURSIVE_NP)
		{
		  THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending,
				 NULL);

		  /* Just bump the counter.  */
		  if (__builtin_expect (mutex->__data.__count + 1 == 0, 0))
		    /* Overflow of the counter.  */
		    return EAGAIN;

		  ++mutex->__data.__count;

		  return 0;
		}
	    }

	  oldval = LLL_ROBUST_MUTEX_LOCK (mutex, id);

	  if (__builtin_expect (mutex->__data.__owner
				== PTHREAD_MUTEX_NOTRECOVERABLE, 0))
	    {
	      /* This mutex is now not recoverable.  */
	      mutex->__data.__count = 0;
	      lll_unlock (mutex->__data.__lock,
			  PTHREAD_ROBUST_MUTEX_PSHARED (mutex));
	      THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);
	      return ENOTRECOVERABLE;
	    }
	}
      while ((oldval & FUTEX_OWNER_DIED) != 0);

      mutex->__data.__count = 1;
      ENQUEUE_MUTEX (mutex);
      THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);
      break;

    case PTHREAD_MUTEX_PI_RECURSIVE_NP:
    case PTHREAD_MUTEX_PI_ERRORCHECK_NP:
    case PTHREAD_MUTEX_PI_NORMAL_NP:
    case PTHREAD_MUTEX_PI_ADAPTIVE_NP:
    case PTHREAD_MUTEX_PI_ROBUST_RECURSIVE_NP:
    case PTHREAD_MUTEX_PI_ROBUST_ERRORCHECK_NP:
    case PTHREAD_MUTEX_PI_ROBUST_NORMAL_NP:
    case PTHREAD_MUTEX_PI_ROBUST_ADAPTIVE_NP:
      {
	int kind = mutex->__data.__kind & PTHREAD_MUTEX_KIND_MASK_NP;
	int robust = mutex->__data.__kind & PTHREAD_MUTEX_ROBUST_NORMAL_NP;

	if (robust)
	  /* Note: robust PI futexes are signaled by setting bit 0.  */
	  THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending,
			 (void *) (((uintptr_t) &mutex->__data.__list.__next)
				   | 1));

	oldval = mutex->__data.__lock;

	/* Check whether we already hold the mutex.  */
	if (__builtin_expect ((oldval & FUTEX_TID_MASK) == id, 0))
	  {
	    if (kind == PTHREAD_MUTEX_ERRORCHECK_NP)
	      {
		THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);
		return EDEADLK;
	      }

	    if (kind == PTHREAD_MUTEX_RECURSIVE_NP)
	      {
		THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);

		/* Just bump the counter.  */
		if (__builtin_expect (mutex->__data.__count + 1 == 0, 0))
		  /* Overflow of the counter.  */
		  return EAGAIN;

		++mutex->__data.__count;

		return 0;
	      }
	  }

	int newval = id;
#ifdef NO_INCR
	newval |= FUTEX_WAITERS;
#endif
	oldval = atomic_compare_and_exchange_val_acq (&mutex->__data.__lock,
						      newval, 0);

	if (oldval != 0)
	  {
	    /* The mutex is locked.  The kernel will now take care of
	       everything.  */
	    int private = (robust
			   ? PTHREAD_ROBUST_MUTEX_PSHARED (mutex)
			   : PTHREAD_MUTEX_PSHARED (mutex));
	    INTERNAL_SYSCALL_DECL (__err);
	    int e = INTERNAL_SYSCALL (futex, __err, 4, &mutex->__data.__lock,
				      __lll_private_flag (FUTEX_LOCK_PI,
							  private), 1, 0);

	    if (INTERNAL_SYSCALL_ERROR_P (e, __err)
		&& (INTERNAL_SYSCALL_ERRNO (e, __err) == ESRCH
		    || INTERNAL_SYSCALL_ERRNO (e, __err) == EDEADLK))
	      {
		assert (INTERNAL_SYSCALL_ERRNO (e, __err) != EDEADLK
			|| (kind != PTHREAD_MUTEX_ERRORCHECK_NP
			    && kind != PTHREAD_MUTEX_RECURSIVE_NP));
		/* ESRCH can happen only for non-robust PI mutexes where
		   the owner of the lock died.  */
		assert (INTERNAL_SYSCALL_ERRNO (e, __err) != ESRCH || !robust);

		/* Delay the thread indefinitely.  */
		while (1)
		  pause_not_cancel ();
	      }

	    oldval = mutex->__data.__lock;

	    assert (robust || (oldval & FUTEX_OWNER_DIED) == 0);
	  }

	if (__builtin_expect (oldval & FUTEX_OWNER_DIED, 0))
	  {
	    atomic_and (&mutex->__data.__lock, ~FUTEX_OWNER_DIED);

	    /* We got the mutex.  */
	    mutex->__data.__count = 1;
	    /* But it is inconsistent unless marked otherwise.  */
	    mutex->__data.__owner = PTHREAD_MUTEX_INCONSISTENT;

	    ENQUEUE_MUTEX_PI (mutex);
	    THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);

	    /* Note that we deliberately exit here.  If we fall
	       through to the end of the function __nusers would be
	       incremented which is not correct because the old owner
	       has to be discounted.  If we are not supposed to
	       increment __nusers we actually have to decrement it here.  */
#ifdef NO_INCR
	    --mutex->__data.__nusers;
#endif

	    return EOWNERDEAD;
	  }

	if (robust
	    && __builtin_expect (mutex->__data.__owner
				 == PTHREAD_MUTEX_NOTRECOVERABLE, 0))
	  {
	    /* This mutex is now not recoverable.  */
	    mutex->__data.__count = 0;

	    INTERNAL_SYSCALL_DECL (__err);
	    INTERNAL_SYSCALL (futex, __err, 4, &mutex->__data.__lock,
			      __lll_private_flag (FUTEX_UNLOCK_PI,
						  PTHREAD_ROBUST_MUTEX_PSHARED (mutex)),
			      0, 0);

	    THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);
	    return ENOTRECOVERABLE;
	  }

	mutex->__data.__count = 1;
	if (robust)
	  {
	    ENQUEUE_MUTEX_PI (mutex);
	    THREAD_SETMEM (THREAD_SELF, robust_head.list_op_pending, NULL);
	  }
      }
      break;

    case PTHREAD_MUTEX_PP_RECURSIVE_NP:
    case PTHREAD_MUTEX_PP_ERRORCHECK_NP:
    case PTHREAD_MUTEX_PP_NORMAL_NP:
    case PTHREAD_MUTEX_PP_ADAPTIVE_NP:
      {
	int kind = mutex->__data.__kind & PTHREAD_MUTEX_KIND_MASK_NP;

	oldval = mutex->__data.__lock;

	/* Check whether we already hold the mutex.  */
	if (mutex->__data.__owner == id)
	  {
	    if (kind == PTHREAD_MUTEX_ERRORCHECK_NP)
	      return EDEADLK;

	    if (kind == PTHREAD_MUTEX_RECURSIVE_NP)
	      {
		/* Just bump the counter.  */
		if (__builtin_expect (mutex->__data.__count + 1 == 0, 0))
		  /* Overflow of the counter.  */
		  return EAGAIN;

		++mutex->__data.__count;

		return 0;
	      }
	  }

	int oldprio = -1, ceilval;
	do
	  {
	    int ceiling = (oldval & PTHREAD_MUTEX_PRIO_CEILING_MASK)
			  >> PTHREAD_MUTEX_PRIO_CEILING_SHIFT;

	    if (__pthread_current_priority () > ceiling)
	      {
		if (oldprio != -1)
		  __pthread_tpp_change_priority (oldprio, -1);
		return EINVAL;
	      }

	    int retval = __pthread_tpp_change_priority (oldprio, ceiling);
	    if (retval)
	      return retval;

	    ceilval = ceiling << PTHREAD_MUTEX_PRIO_CEILING_SHIFT;
	    oldprio = ceiling;

	    oldval
	      = atomic_compare_and_exchange_val_acq (&mutex->__data.__lock,
#ifdef NO_INCR
						     ceilval | 2,
#else
						     ceilval | 1,
#endif
						     ceilval);

	    if (oldval == ceilval)
	      break;

	    do
	      {
		oldval
		  = atomic_compare_and_exchange_val_acq (&mutex->__data.__lock,
							 ceilval | 2,
							 ceilval | 1);

		if ((oldval & PTHREAD_MUTEX_PRIO_CEILING_MASK) != ceilval)
		  break;

		if (oldval != ceilval)
		  lll_futex_wait (&mutex->__data.__lock, ceilval | 2,
				  PTHREAD_MUTEX_PSHARED (mutex));
	      }
	    while (atomic_compare_and_exchange_val_acq (&mutex->__data.__lock,
							ceilval | 2, ceilval)
		   != ceilval);
	  }
	while ((oldval & PTHREAD_MUTEX_PRIO_CEILING_MASK) != ceilval);

	assert (mutex->__data.__owner == 0);
	mutex->__data.__count = 1;
      }
      break;

    default:
      /* Correct code cannot set any other type.  */
      return EINVAL;
    }

  /* Record the ownership.  */
  mutex->__data.__owner = id;
#ifndef NO_INCR
  ++mutex->__data.__nusers;
#endif

  LIBC_PROBE (mutex_acquired, 1, mutex);

  return 0;
}
#ifndef __pthread_mutex_lock
strong_alias (__pthread_mutex_lock, pthread_mutex_lock)
hidden_def (__pthread_mutex_lock)
#endif

#ifdef NO_INCR
void
__pthread_mutex_cond_lock_adjust (mutex)
     pthread_mutex_t *mutex;
{
  assert ((mutex->__data.__kind & PTHREAD_MUTEX_PRIO_INHERIT_NP) != 0);
  assert ((mutex->__data.__kind & PTHREAD_MUTEX_ROBUST_NORMAL_NP) == 0);
  assert ((mutex->__data.__kind & PTHREAD_MUTEX_PSHARED_BIT) == 0);

  /* Record the ownership.  */
  pid_t id = THREAD_GETMEM (THREAD_SELF, tid);
  mutex->__data.__owner = id;

  if (mutex->__data.__kind == PTHREAD_MUTEX_PI_RECURSIVE_NP)
    ++mutex->__data.__count;
}
#endif