text:
import { Component, Directive, Input, Output, EventEmitter, ChangeDetectionStrategy, Injector, Renderer, ElementRef, ViewContainerRef, ComponentFactoryResolver, NgZone } from '@angular/core';
import { listenToTriggers } from '../util/triggers';
import { positionElements } from '../util/positioning';
import { PopupService } from '../util/popup';
import { NgbTooltipConfig } from './tooltip-config';
export var NgbTooltipWindow = (function () {
    function NgbTooltipWindow() {
        this.placement = 'top';
    }
    NgbTooltipWindow.decorators = [
        { type: Component, args: [{
                    selector: 'ngb-tooltip-window',
                    changeDetection: ChangeDetectionStrategy.OnPush,
                    host: { '[class]': '"tooltip show tooltip-" + placement', 'role': 'tooltip' },
                    template: "\n
<ng-content></ng-content>
\n    "
                },] },
    ];
    /** @nocollapse */
    NgbTooltipWindow.ctorParameters = function () { return []; };
    NgbTooltipWindow.propDecorators = {
        'placement': [{ type: Input },],
    };
    return NgbTooltipWindow;
}());
/**
 * A lightweight, extensible directive for fancy tooltip creation.
 */
export var NgbTooltip = (function () {
    function NgbTooltip(_elementRef, _renderer, injector, componentFactoryResolver, viewContainerRef, config, ngZone) {
        var _this = this;
        this._elementRef = _elementRef;
        this._renderer = _renderer;
        /**
       * Emits an event when the tooltip is shown
       */
        this.shown = new EventEmitter();
        /**
         * Emits an event when the tooltip is hidden
         */
        this.hidden = new EventEmitter();
        this.placement = config.placement;
        this.triggers = config.triggers;
        this.container = config.container;
        this._popupService = new PopupService(NgbTooltipWindow, injector, viewContainerRef, _renderer, componentFactoryResolver);
        this._zoneSubscription = ngZone.onStable.subscribe(function () {
            if (_this._windowRef) {
                positionElements(_this._elementRef.nativeElement, _this._windowRef.location.nativeElement, _this.placement, _this.container === 'body');
            }
        });
    }
    Object.defineProperty(NgbTooltip.prototype, "ngbTooltip", {
        get: function () { return this._ngbTooltip; },
        /**
         * Content to be displayed as tooltip. If falsy, the tooltip won't open.
         */
        set: function (value) {
            this._ngbTooltip = value;
            if (!value && this._windowRef) {
                this.close();
            }
        },
        enumerable: true,
        configurable: true
    });
    /**
     * Opens an element's tooltip. This is considered a "manual" triggering of the tooltip.
     * The context is an optional value to be injected into the tooltip template when it is created.
     */
    NgbTooltip.prototype.open = function (context) {
        if (!this._windowRef && this._ngbTooltip) {
            this._windowRef = this._popupService.open(this._ngbTooltip, context);
            this._windowRef.instance.placement = this.placement;
            if (this.container === 'body') {
                window.document.querySelector(this.container).appendChild(this._windowRef.location.nativeElement);
            }
            // we need to manually invoke change detection since events registered via
            // Renderer::listen() - to be determined if this is a bug in the Angular itself
            this._windowRef.changeDetectorRef.markForCheck();
            this.shown.emit();
        }
    };
    /**
     * Closes an element's tooltip. This is considered a "manual" triggering of the tooltip.
     */
    NgbTooltip.prototype.close = function () {
        if (this._windowRef != null) {
            this._popupService.close();
            this._windowRef = null;
            this.hidden.emit();
        }
    };
    /**
     * Toggles an element's tooltip. This is considered a "manual" triggering of the tooltip.
     */
    NgbTooltip.prototype.toggle = function () {
        if (this._windowRef) {
            this.close();
        }
        else {
            this.open();
        }
    };
    /**
     * Returns whether or not the tooltip is currently being shown
     */
    NgbTooltip.prototype.isOpen = function () { return this._windowRef != null; };
    NgbTooltip.prototype.ngOnInit = function () {
        this._unregisterListenersFn = listenToTriggers(this._renderer, this._elementRef.nativeElement, this.triggers, this.open.bind(this), this.close.bind(this), this.toggle.bind(this));
    };
    NgbTooltip.prototype.ngOnDestroy = function () {
        this.close();
        this._unregisterListenersFn();
        this._zoneSubscription.unsubscribe();
    };
    NgbTooltip.decorators = [
        { type: Directive, args: [{ selector: '[ngbTooltip]', exportAs: 'ngbTooltip' },] },
    ];
    /** @nocollapse */
    NgbTooltip.ctorParameters = function () { return [
        { type: ElementRef, },
        { type: Renderer, },
        { type: Injector, },
        { type: ComponentFactoryResolver, },
        { type: ViewContainerRef, },
        { type: NgbTooltipConfig, },
        { type: NgZone, },
    ]; };
    NgbTooltip.propDecorators = {
        'placement': [{ type: Input },],
        'triggers': [{ type: Input },],
        'container': [{ type: Input },],
        'shown': [{ type: Output },],
        'hidden': [{ type: Output },],
        'ngbTooltip': [{ type: Input },],
    };
    return NgbTooltip;
}());
//# sourceMappingURL=tooltip.js.map


text:
from setuptools import setup, find_packages
from io import open

with open('README.md', encoding='utf-8') as f:
    long_description = f.read()

setup(
  name = "interage_python_sdk",
  packages = find_packages(),
  version = "0.4.1",
  description = "SDK oficialmente mantido pela IntMed Software para auxiliar no desenvolvimento de aplicações em Python integradas ao serviço de interações medicamentosas do sistema Interage",
  long_description=long_description,
  long_description_content_type='text/markdown',
  author = "IntMed Software",
  author_email = "contato@intmed.com.br",
  url = "https://github.com/IntMed/interage_python_sdk",
  download_url = "https://github.com/IntMed/interage_python_sdk/archive/0.4.1.tar.gz",
  keywords = "interage intmed api python sdk interage-python-sdk health",
  classifiers=[
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'Topic :: Internet :: WWW/HTTP',
    'License :: OSI Approved :: MIT License',
    'Programming Language :: Python :: 3',
    'Programming Language :: Python :: 3.3',
    'Programming Language :: Python :: 3.4',
    'Programming Language :: Python :: 3.5',
    'Programming Language :: Python :: 3.6',
  ],
)

redpajama_set_name: RedPajamaGithub


text:
package yaml

import (
	"errors"
	"fmt"

	"github.com/docker/engine-api/types/strslice"
	"github.com/flynn/go-shlex"
)

// Command represents a docker command, can be a string or an array of strings.
type Command strslice.StrSlice

// UnmarshalYAML implements the Unmarshaller interface.
func (s *Command) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var stringType string
	if err := unmarshal(&stringType); err == nil {
		parts, err := shlex.Split(stringType)
		if err != nil {
			return err
		}
		*s = parts
		return nil
	}

	var sliceType []interface{}
	if err := unmarshal(&sliceType); err == nil {
		parts, err := toStrings(sliceType)
		if err != nil {
			return err
		}
		*s = parts
		return nil
	}

	var interfaceType interface{}
	if err := unmarshal(&interfaceType); err == nil {
		fmt.Println(interfaceType)
	}

	return errors.New("Failed to unmarshal Command")
}


text:
layout: default
title: Особенности работы с Flash баннерами
nav_order: 7
parent: Плагин «Баннерная система»
grand_parent: Руководство пользователя
---

# Особенности работы с Flash баннерами

Если баннер выполнен в виде Flash-ролика, то может возникнуть неприятная ситуация связанная с тем, что система не может отслеживать клики по ссылкам, жестко закодированным внутри баннера. В систему Fastsite CMS встроена возможность находить такие ссылки внутри Flash файлов и конвертировать их таким образом, чтобы можно было отслеживать клики.

Если баннер содержит Flash-ролик, отметьте пункт *проверять наличие жестко закодированных линков внутри Flash-файлов* на странице редактирования HTML-кода баннера. При сохранении баннера система проверит код на наличие ссылок на Flash-файл, и проанализирует найденный файл. Если будут найдены жестко закодированные ссылки, то откроется дополнительное окно со списком найденных ссылок и с предложением их преобразовать. Вы можете отметить, какие ссылки конвертировать, а какие оставить без изменений.

После нажатия на кнопку «Преобразовать», будут внесены изменения в Flash-файл и в HTML-код баннера. После этого при нажатии на преобразованные ссылки, система сможет регистрировать клик по баннеру. Преобразованные ссылки будут указывать на адрес, заданный в свойстве *URL перехода* баннера.


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

import java.net.URI;

public interface Node
{
    String getHost();

    HostAddress getHostAndPort();

    /**
     * @deprecated Connectors should not access the HTTP endpoints of other nodes.
     */
    @Deprecated
    URI getHttpUri();

    String getNodeIdentifier();

    String getVersion();

    boolean isCoordinator();

    boolean isResourceManager();

    boolean isCatalogServer();
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycol. Pap. 166: 110 (1993)

#### Original name
Meliolina novae-caledoniae S. Hughes

### Remarks
null


text:
package yu.storm.bolt;

import java.io.File;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.net.URL;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.search.spell.PlainTextDictionary;
import org.apache.lucene.search.spell.SpellChecker;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import backtype.storm.Config;
import backtype.storm.task.ShellBolt;
import backtype.storm.topology.IRichBolt;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.TopologyBuilder;
import backtype.storm.topology.base.BaseBasicBolt;
import backtype.storm.topology.base.BaseRichBolt;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Tuple;
import backtype.storm.tuple.Values;
import backtype.storm.utils.Utils;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.BasicOutputCollector;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.OutputCollector;

public class TermFilterBolt extends BaseRichBolt {

	private OutputCollector collector;
	private SpellChecker spellchecker;
	private List<String> filterTerms = Arrays.asList(new String[]{"http"});

	@Override
	public void prepare(
	Map                     map,
	TopologyContext         topologyContext,
	OutputCollector         outputCollector)
	{
		// save the collector for emitting tuples
		//queue = new LinkedBlockingQueue<String>(1000);
		collector = outputCollector;
		String fileLocation = TermFilterBolt.class.getProtectionDomain().getCodeSource().getLocation().getPath();
		File dir = new File(fileLocation + "../resources/dictionaries");
		Directory directory;
		try {
			directory = FSDirectory.open(dir);
			spellchecker = new SpellChecker(directory);
			StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_36);
			IndexWriterConfig config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
			URL dictionaryFile = TermFilterBolt.class.getResource("../resources/dictionaries/fulldictionary00.txt");
			spellchecker.indexDictionary(new PlainTextDictionary(new File(dictionaryFile.toURI())), config, true);
		} catch (Exception e) {
		}
	}

	private boolean shouldKeep(String stem){
		if(stem == null)
			return false;
		if(stem.equals(""))
			return false;
		if(filterTerms.contains(stem))
			return false;
		//we don't want integers
		try{
			Integer.parseInt(stem);
			return false;
		}catch(Exception e){}
		//or floating point numbers
		try{
			Double.parseDouble(stem);
			return false;
		}catch(Exception e){}
		try {
			return spellchecker.exist(stem);
		} catch (Exception e) {
			return false;
		}
		// return true;
	}

	@Override
	public void execute(Tuple tuple) {
		String term = tuple.getStringByField("dirtyTerm");
		String documentId = tuple.getStringByField("documentId");
		String source = tuple.getStringByField("source");
		Integer dCount = tuple.getIntegerByField("dCount");
		if(shouldKeep(term)){
			collector.emit(new Values(term, documentId, source, dCount));
		}

	}

	@Override
	public void declareOutputFields(OutputFieldsDeclarer outputFieldsDeclarer)
	{
		outputFieldsDeclarer.declare(new Fields("term", "documentId", "source", "dCount"));
	}

}


text:
Imports PlayerIOClient

Public NotInheritable Class FaceReceiveMessage
    Inherits ReceiveMessage

    '0
    Public ReadOnly UserID As Integer
    '1
    Public ReadOnly Face As Smiley

    Friend Sub New(message As Message)
        MyBase.New(message)

        UserID = message.GetInteger(0)
        Face = DirectCast(message.GetInteger(1), Smiley)
    End Sub
End Class


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using Xunit;

namespace System.Text.Json.Serialization.Tests
{
    public partial class NullTests
    {
        [Fact]
        public static void ClassWithNull()
        {
            TestClassWithNull obj = JsonSerializer.Parse<TestClassWithNull>(TestClassWithNull.s_json);
            obj.Verify();
        }

        [Fact]
        public static void DefaultReadValue()
        {
            TestClassWithNullButInitialized obj = JsonSerializer.Parse<TestClassWithNullButInitialized>(TestClassWithNullButInitialized.s_json);
            Assert.Equal(null, obj.MyString);
            Assert.Equal(null, obj.MyInt);
        }

        [Fact]
        public static void OverrideReadOnOption()
        {
            var options = new JsonSerializerOptions();
            options.IgnoreNullPropertyValueOnRead = true;

            TestClassWithNullButInitialized obj = JsonSerializer.Parse<TestClassWithNullButInitialized>(TestClassWithNullButInitialized.s_json, options);
            Assert.Equal("Hello", obj.MyString);
            Assert.Equal(1, obj.MyInt);
        }

        [Fact]
        public static void OverrideReadOnAttribute()
        {
            JsonSerializerOptions options = new JsonSerializerOptions();
            JsonPropertyValueAttribute attr = new JsonPropertyValueAttribute();
            attr.IgnoreNullValueOnRead = true;
            options.AddAttribute(typeof(TestClassWithNullButInitialized), attr);

            TestClassWithNullButInitialized obj = JsonSerializer.Parse<TestClassWithNullButInitialized>(TestClassWithNullButInitialized.s_json, options);
            Assert.Equal("Hello", obj.MyString);
            Assert.Equal(1, obj.MyInt);
        }
    }
}


text:
import { Headers, Http, Request, RequestMethod } from '@angular/http';
import { AppConfig } from '../app.config';
import { Model } from '../model/model';
import { User } from '../model/user';
import { Pagination } from '../entity/pagination';
import { QueryResult } from '../entity/query-result';

export abstract class Service {
    constructor(protected http: Http) {
        this.http = http;
    }

    requestText(path: string, method: RequestMethod, data: any = {}): Promise<string> {
        console.debug('Debug: Begin a text request. url:' + AppConfig.serviceUrlRoot + '/' + path + ';method:' + method + ';data:' + JSON.stringify(data));
        return new Promise<string>(resolve => {
            this.http.request(new Request({
                method: method,
                url: AppConfig.serviceUrlRoot + '/' + path,
                headers: new Headers({
                    'Content-Type': 'application/json'
                }),
                body: data
            })).subscribe(r => {
                var bodyText = r.text();
                console.debug('Debug: Request text successful. Return:' + bodyText);
                resolve(bodyText);
            }, e => {
                throw 'Request text error: ' + e;
            });
        });
    }

    requestJson<T>(path: string, method: RequestMethod, data: any = {}): Promise<T> {
        console.debug('Debug: Begin a json request. url:' + AppConfig.serviceUrlRoot + '/' + path + ';method:' + method + ';data:' + JSON.stringify(data));
        return new Promise<T>(resolve => {
            this.http.request(new Request({
                method: method,
                url: AppConfig.serviceUrlRoot + '/' + path,
                headers: new Headers({
                    'Content-Type': 'application/json'
                }),
                body: data
            })).subscribe(r => {
                var bodyText = r.text();
                console.debug('Debug: Request text successful. Return:' + bodyText);
                if (bodyText === '') {
                    resolve(null);
                }
                else {
                    resolve(<T>r.json());
                }
            }, e => {
                throw 'Request json error: ' + e;
            });
        });
    }
}

export abstract class TService<T extends Model> extends Service {
    constructor(protected http: Http, protected modelName: string) {
        super(http);
    }

    find(pagination: Pagination = null, text: string = null): Promise<QueryResult<T>> {
        var url = this.modelName + '?';
        if (text) {
            url += '&search-text=' + text;
        }
        if (pagination) {
            if (pagination.size) {
                url += '&size=' + pagination.size;
            }
            if (pagination.index) {
                url += '&index=' + pagination.index;
            }
        }
        return this.requestJson<QueryResult<T>>(url, RequestMethod.Get);
    }

    create(model: T): Promise<string> {
        var url = this.modelName;
        return this.requestText(url, RequestMethod.Post, model);
    }

    update(model: T): Promise<void> {
        var url = this.modelName + '/' + model.id;
        return this.requestJson<void>(url, RequestMethod.Put, model);
    }

    destroyById(id: string): Promise<void> {
        var url = this.modelName + '/' + id;
        return this.requestJson<void>(url, RequestMethod.Delete);
    }

    findById(id: string): Promise<T> {
        var url = this.modelName + '/' + id;
        return this.requestJson<T>(url, RequestMethod.Get);
    }
}


text:
package org.htrace.wrappers;

import org.htrace.Span;
import org.htrace.Trace;
import org.htrace.TraceScope;

import java.util.concurrent.Callable;

/**
 * Wrap a Callable with a Span that survives a change in threads.
 */
public class TraceCallable<V> implements Callable<V> {
  private final Callable<V> impl;
  private final Span parent;
  private final String description;

  public TraceCallable(Callable<V> impl) {
    this(Trace.currentSpan(), impl);
  }

  public TraceCallable(Span parent, Callable<V> impl) {
    this(parent, impl, null);
  }

  public TraceCallable(Span parent, Callable<V> impl, String description) {
    this.impl = impl;
    this.parent = parent;
    this.description = description;
  }

  @Override
  public V call() throws Exception {
    if (parent != null) {
      TraceScope chunk = Trace.startSpan(getDescription(), parent);

      try {
        return impl.call();
      } finally {
        chunk.close();
      }
    } else {
      return impl.call();
    }
  }

  public Callable<V> getImpl() {
    return impl;
  }

  private String getDescription() {
    return this.description == null ? Thread.currentThread().getName() : description;
  }
}


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

using System.Collections.Generic;
using System.Linq;

namespace Azure.Core.GeoJson
{
    /// <summary>
    /// Represents a polygon consisting of outer ring and optional inner rings.
    /// </summary>
    public sealed class GeoPolygon : GeoObject
    {
        /// <summary>
        /// Initializes new instance of <see cref="GeoPolygon"/>.
        /// </summary>
        /// <param name="positions">The positions that make up the outer ring of the polygon.</param>
        public GeoPolygon(IEnumerable<GeoPosition> positions): this(new[] { new GeoLinearRing(positions) }, null, DefaultProperties)
        {
        }

        /// <summary>
        /// Initializes new instance of <see cref="GeoPolygon"/>.
        /// </summary>
        /// <param name="rings">The collection of rings that make up the polygon, first ring is the outer ring others are inner rings.</param>
        public GeoPolygon(IEnumerable<GeoLinearRing> rings): this(rings, null, DefaultProperties)
        {
        }

        /// <summary>
        /// Initializes new instance of <see cref="GeoPolygon"/>.
        /// </summary>
        /// <param name="rings">The collection of rings that make up the polygon, first ring is the outer ring others are inner rings.</param>
        /// <param name="boundingBox">The <see cref="GeoBoundingBox"/> to use.</param>
        /// <param name="customProperties">The set of custom properties associated with the <see cref="GeoObject"/>.</param>
        public GeoPolygon(IEnumerable<GeoLinearRing> rings, GeoBoundingBox? boundingBox, IReadOnlyDictionary<string, object?> customProperties): base(boundingBox, customProperties)
        {
            Argument.AssertNotNull(rings, nameof(rings));

            Rings = rings.ToArray();
        }

        /// <summary>
        /// Gets a set of rings that form the polygon.
        /// </summary>
        public IReadOnlyList<GeoLinearRing> Rings { get; }

        /// <summary>
        /// Returns the outer right of the polygon
        /// </summary>
        public GeoLinearRing OuterRing => Rings[0];

        /// <summary>
        /// Returns a view over the coordinates array that forms this geometry.
        /// </summary>
        public GeoArray<GeoArray<GeoPosition>> Coordinates => new GeoArray<GeoArray<GeoPosition>>(this);

        /// <inheritdoc />
        public override GeoObjectType Type { get; } = GeoObjectType.Polygon;
    }
}


text:
package org.springframework.security.oauth2.provider.expression;

import java.util.Arrays;
import java.util.LinkedHashSet;
import java.util.Set;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.common.exceptions.InsufficientScopeException;

/**
 * A convenience object for security expressions in OAuth2 protected resources, providing public methods that act on the
 * current authentication.
 *
 * @author Dave Syer
 * @author Rob Winch
 * @author Radek Ostrowski
 *
 */
public class OAuth2SecurityExpressionMethods {

	private final Authentication authentication;

	private Set<String> missingScopes = new LinkedHashSet<String>();

	public OAuth2SecurityExpressionMethods(Authentication authentication) {
		this.authentication = authentication;
	}

	/**
	 * Check if any scope decisions have been denied in the current context and throw an exception if so. This method
	 * automatically wraps any expressions when using {@link OAuth2MethodSecurityExpressionHandler} or
	 * {@link OAuth2WebSecurityExpressionHandler}.
	 *
	 * OAuth2Example usage:
	 *
	 *

	 * access = "#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"
	 *

	 *
	 * Will automatically be wrapped to ensure that explicit errors are propagated rather than a generic error when
	 * returning false:
	 *
	 *

	 * access = "#oauth2.throwOnError(#oauth2.hasScope('read') or (#oauth2.hasScope('other') and hasRole('ROLE_USER'))"
	 *

	 *
	 * N.B. normally this method will be automatically wrapped around all your access expressions. You could use it
	 * explicitly to get more control, or if you have registered your own ExpressionParser you might need
	 * it.
	 *
	 * @param decision the existing access decision
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws InsufficientScopeException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean throwOnError(boolean decision) {
		if (!decision && !missingScopes.isEmpty()) {
			Throwable failure = new InsufficientScopeException("Insufficient scope for this resource", missingScopes);
			throw new AccessDeniedException(failure.getMessage(), failure);
		}
		return decision;
	}

	/**
	 * Check if the OAuth2 client (not the user) has the role specified. To check the user's roles see
	 * {@link #clientHasRole(String)}.
	 *
	 * @param role the role to check
	 * @return true if the OAuth2 client has this role
	 */
	public boolean clientHasRole(String role) {
		return clientHasAnyRole(role);
	}

	/**
	 * Check if the OAuth2 client (not the user) has one of the roles specified. To check the user's roles see
	 * {@link #clientHasAnyRole(String...)}.
	 *
	 * @param roles the roles to check
	 * @return true if the OAuth2 client has one of these roles
	 */
	public boolean clientHasAnyRole(String... roles) {
		return OAuth2ExpressionUtils.clientHasAnyRole(authentication, roles);
	}

	/**
	 * Check if the current OAuth2 authentication has the scope specified.
	 *
	 * @param scope the scope to check
	 * @return true if the OAuth2 authentication has the required scope
	 */
	public boolean hasScope(String scope) {
		return hasAnyScope(scope);
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes specified.
	 *
	 * @param scopes the scopes to check
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean hasAnyScope(String... scopes) {
		boolean result = OAuth2ExpressionUtils.hasAnyScope(authentication, scopes);
		if (!result) {
			missingScopes.addAll(Arrays.asList(scopes));
		}
		return result;
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.
	 *
	 *

	 * access = "#oauth2.hasScopeMatching('.*_admin:manage_scopes')))"
	 *

	 *
	 * @param scopeRegex the scope regex to match
	 * @return true if the OAuth2 authentication has the required scope
	 */
	public boolean hasScopeMatching(String scopeRegex) {
		return hasAnyScopeMatching(scopeRegex);
	}

	/**
	 * Check if the current OAuth2 authentication has one of the scopes matching a specified regex expression.
	 *
	 *

	 * access = "#oauth2.hasAnyScopeMatching('admin:manage_scopes','.*_admin:manage_scopes','.*_admin:read_scopes')))"
	 *

	 *
	 * @param scopesRegex the scopes regex to match
	 * @return true if the OAuth2 token has one of these scopes
	 * @throws AccessDeniedException if the scope is invalid and we the flag is set to throw the exception
	 */
	public boolean hasAnyScopeMatching(String... scopesRegex) {

		boolean result = OAuth2ExpressionUtils.hasAnyScopeMatching(authentication, scopesRegex);
		if (!result) {
			missingScopes.addAll(Arrays.asList(scopesRegex));
		}
		return result;
	}

	/**
	 * Deny access to oauth requests, so used for example to only allow web UI users to access a resource.
	 *
	 * @return true if the current authentication is not an OAuth2 type
	 */
	public boolean denyOAuthClient() {
		return !OAuth2ExpressionUtils.isOAuth(authentication);
	}

	/**
	 * Permit access to oauth requests, so used for example to only allow machine clients to access a resource.
	 *
	 * @return true if the current authentication is not an OAuth2 type
	 */
	public boolean isOAuth() {
		return OAuth2ExpressionUtils.isOAuth(authentication);
	}

	/**
	 * Check if the current authentication is acting on behalf of an authenticated user.
	 *
	 * @return true if the current authentication represents a user
	 */
	public boolean isUser() {
		return OAuth2ExpressionUtils.isOAuthUserAuth(authentication);
	}

	/**
	 * Check if the current authentication is acting as an authenticated client application not on behalf of a user.
	 *
	 * @return true if the current authentication represents a client application
	 */
	public boolean isClient() {
		return OAuth2ExpressionUtils.isOAuthClientAuth(authentication);
	}
}


text:
/**
 * @file    NetworkHost.cpp
 * @author  Marvin Smith
 * @date    2/15/2014
*/
#include "NetworkHost.hpp"

namespace LLNMS{
namespace NETWORK{

/**
 * Default Constructor
*/
NetworkHost::NetworkHost( ){
    m_valid = false;
    m_ip4_address = "0.0.0.0";
}

/**
 * Parameterized constructor
*/
NetworkHost::NetworkHost( const std::string& ip4_address ){

    m_ip4_address = ip4_address;
}

/**
 * Return the ip4 address
*/
std::string NetworkHost::ip4_address()const{
    return m_ip4_address;
}

/**
 * Check validity
*/
bool NetworkHost::isValid()const{
    return m_valid;
}

} /// End of NETWORK Namespace
} /// End of LLNMS Namespace


text:
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="@dimen/spell_letter_box_size"
    android:layout_height="@dimen/spell_letter_box_size"
    android:gravity="center"
    android:layout_margin="@dimen/spell_letter_margin"
    android:textSize="@dimen/spell_letter_size" />


text:
package com.thanglequoc.aqicalculator;

import com.fasterxml.jackson.databind.JsonNode;

/**
 * Represent upper bound index (I-high) and lower bound
 * index (I-low) of a corresponding range in
 * <tt>PollutantBreakpoint</tt> of a pollutant
 *
 * @author ThangLeQuoc
 */
class Index {

    private int min;
    private int max;

    Index(int min, int max) {
        this.min = min;
        this.max = max;
    }

    int getMinIndex() {
        return min;
    }

    int getMaxIndex() {
        return max;
    }

    static Index fromIndexNode(JsonNode indexNode) {
        int minIndex = indexNode.path(AQICalculatorConstants.MIN).asInt();
        int maxIndex = indexNode.path(AQICalculatorConstants.MAX).asInt();
        return new Index(minIndex, maxIndex);
    }

}


text:
package tbeer

import (
	"fmt"
	"net/url"
	"strconv"
)

type Rectangle struct {
	MinLat  float64
	MinLong float64
	MaxLat  float64
	MaxLong float64
}

func getFormFloat(m url.Values, key string) (float64, error) {
	val, ok := m[key]
	if !ok {
		return 0.0, fmt.Errorf("missing key %s", key)
	}
	f, err := strconv.ParseFloat(val[0], 64)
	if err != nil {
		return 0.0, fmt.Errorf("could not parse number: %s", val[0])
	} else {
		return f, nil
	}
}

// Extract a rectangle from dispatched rest request
func GetRectangle(ctx *DispatchContext) (*Rectangle, error) {
	r := &Rectangle{}
	var err error
	keys := []string{"minlat", "minlong", "maxlat", "maxlong"}
	targets := []*float64{&r.MinLat, &r.MinLong, &r.MaxLat, &r.MaxLong}
	for i, t := range targets {
		*t, err = getFormFloat(ctx.request.Form, keys[i])
		if err != nil {
			return nil, err
		}
	}
	return r, nil
}


text:
package net.radai.beanz.properties;

import net.radai.beanz.api.BeanDescriptor;
import net.radai.beanz.api.PropertyDescriptor;

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

public abstract class CompositePropertyDescriptor extends PropertyDescriptorBase {
    private final PropertyDescriptor[] delegates;

    public CompositePropertyDescriptor(BeanDescriptor containingBeanDescriptor, String name, Type type, PropertyDescriptor[] delegates) {
        super(containingBeanDescriptor, name, type);
        if (delegates == null || delegates.length < 2) {
            throw new IllegalArgumentException();
        }
        for (PropertyDescriptor delegate : delegates) {
            if (!delegate.getType().equals(getType())) {
                throw new IllegalArgumentException();
            }
        }
        this.delegates = delegates;
    }

    @Override
    public boolean isReadable() {
        for (PropertyDescriptor delegate : delegates) {
            if (delegate.isReadable()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean isWritable() {
        for (PropertyDescriptor delegate : delegates) {
            if (delegate.isWritable()) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Object get(Object bean) {
        for (PropertyDescriptor delegate : delegates) {
            if (delegate.isReadable()) {
                return delegate.get(bean);
            }
        }
        throw new IllegalStateException(); //not readable
    }

    @Override
    public void set(Object bean, Object value) {
        for (PropertyDescriptor delegate : delegates) {
            if (delegate.isWritable()) {
                delegate.set(bean, value);
                return;
            }
        }
        throw new IllegalStateException(); //not writable
    }

    @Override
    public <A extends Annotation> A[] getAnnotations(Class<A> annotationClass) {
        A[] results = null;
        for (PropertyDescriptor delegate : delegates) {
            if ((results = delegate.getAnnotations(annotationClass)) != null) {
                break;
            }
        }
        return results;
    }
}


text:
export class ActivityNodeCollection {
  nodeList: ActivityNode[] = [];
  activeNodes: number = 0;

  constructor() {

  }

  updateCollection(data: ActivityNode) {
    let shouldBeAdded: boolean = true;
    this.activeNodes = 0;

    this.nodeList.forEach((node) => {
      if (node.appId == data.appId) {
        shouldBeAdded = false;
      }
      if (node.isOnline) {
        this.activeNodes++;
      }
    });

    if (shouldBeAdded) {
      this.nodeList.push(new ActivityNode(data));
    }

    this.nodeList.forEach((node) => {
      if (node.appId == data.appId) {
        node.updateNode(true, data.time, this.activeNodes);
      } else {
        node.updateNode(false, data.time, this.activeNodes);
      }
    })
  }
}

export class ActivityNode {
  appId: string = '';
  message: string = 'Not found';
  time: Date = new Date();
  inUse: boolean = false;
  status: string = '';

  tickCount: number = 0;
  isOnline: boolean = false;
  highlighted: boolean = false;
  blankHits: number = 0;
  version: string = '1.0';

  constructor(data?: any) {
    if (data) {
      this.appId = data.appId;
      this.message = data.message;
      if (this.message == 'Connected') {
        this.isOnline = true;
      }
      if (data.version) {
        this.version = data.version;
      }
      this.status = 'Connected';
      this.time = new Date(data.time);
      this.tickCount = 0;
      this.highlighted = true;
    }
  }

  updateNode(nodeFounded: boolean, date: Date, nodeCount: number): void {
    if (nodeFounded) {
      this.isOnline = true;
      this.tickCount++;
      this.time = date;
      this.blankHits = 0;
      this.status = 'Connected';
      if (!this.inUse) {
        this.inUse = true;
        this.highlighted = true;
        setTimeout(() => {
          this.highlighted = false;
          this.inUse = false;
        }, 1000);
      }
    } else {
      this.blankHits++;
      let tempCount = 0;
      if (nodeCount > 3) {
        tempCount = 2;
      } else {
        tempCount = 3;
      }
      if (this.blankHits >= nodeCount * tempCount) {
        this.isOnline = false;
        this.status = 'Disconnected';
        this.highlighted = false;
      }
    }
  }
}


text:
require_relative '../test_helper'

feature 'emails#offers_index' do
  before(:each) do
    @email = FactoryGirl.create :email
  end

  scenario 'offers_index for E-Mail with offers in section gets shown' do
    offer1 = FactoryGirl.create :offer, :family_section, :approved, name: 'baz'
    offer2 = FactoryGirl.create :offer, :refugee_section, :approved, name: 'fuz'
    offer3 = FactoryGirl.create :offer, :family_section, :approved, name: 'foo'
    offer1.contact_people.first.update_column :email_id, @email.id
    offer2.contact_people.first.update_column :email_id, @email.id
    offer3.contact_people.first.update_column :email_id, @email.id
    offer3.update_columns aasm_state: 'expired'
    visit emails_offers_path(section: 'family', id: @email.id, locale: 'de')
    page.must_have_content 'baz'
    page.must_have_content 'foo' # expired family offer
    page.wont_have_content 'fuz' # because it's in different section
    page.wont_have_content @email.address # because js obfuscated
  end

  scenario 'offers_index for E-Mail without offers in section gets shown' do
    @fam_offer1 = FactoryGirl.create(:offer,
                                     :family_section,
                                     :approved,
                                     name: 'baz')
    @fam_offer1.contact_people.first.update_column :email_id, @email.id
    visit emails_offers_path(section: 'refugees', id: @email.id, locale: 'de')
    page.wont_have_content 'baz' # because it's in different section
    page.must_have_content 'Es gibt derzeit keine veröffentlichten'\
                           ' clarat refugees-Angebote'
  end
end


text:
<element name="b-chart-axis">
    <style>

    </style>
    <script src="../node_modules/d3/d3.js"></script>
    <script>
        ({
            get axis() {
                return this.getAttribute('axis') === 'y' ? 'y' : 'x';
            },

            get horizontal() {
                return this.axis === 'x';
            },

            get vertical() {
                return this.axis === 'y';
            },

            get type() {
                return this.hasAttribute('type') ? this.getAttribute('type') : 'linear';
            },

            get label() {
                return this.getAttribute('label');
            },

            get orientation() {
                return this.hasAttribute('orientation')
                    ? this.getAttribute('orientation')
                    : (this.horizontal ? 'left' : 'bottom');
            },

            render: function(scale) {
                var chartAxis,
                    svg = d3.select(this.parentNode.chartElement),
                    axis = d3.svg.axis().scale(scale).orient(this.orientation);

                if (this.horizontal) {
                    chartAxis = svg.append("g")
                      .attr("class", "x axis")
                      .attr("transform", "translate(0," + this.parentNode.chartHeight + ")")
                      .call(axis);
                } else {
                    chartAxis = svg.append("g")
                      .attr("class", "y axis")
                      .call(axis)
                }

                if (this.label) {
                    if (this.vertical) {
                        chartAxis.append("text")
                          .attr("transform", "rotate(-90)")
                          .attr("y", 6)
                          .attr("dy", ".71em")
                          .style("text-anchor", "end")
                          .text(this.label);
                    }
                }
            }
        });
    </script>
</element>


text:
import json
import requests
import re
import logging
from datetime import datetime, timedelta
import time
from scrapy import Selector
from .fetch import fetch
from news import session, delete_news,save_news,save_cache, update_sites,reset_news

hackernews_url = 'https://news.layervault.com/'

Site="designernews"

def fetch_news(url, news_list):
	res = fetch(url)
	if res['code'] != 200:
		return []
	html = res['html']
	#print html
	hxs = Selector(text=html)
	lis = hxs.xpath('//div[@class="Content"]/div[@class="InnerPage"]/ol/li')
	cnt = len(lis)
	i=0
	logging.debug("fetch count: %d from %s" % (cnt, url))
	for li in lis:
		source_link = li.xpath('./a[@class="StoryUrl"]/@href').extract()
		title = li.xpath('./a[@class="StoryUrl"]/@story_title').extract()
		sub_title = li.xpath('./a/span/text()').extract()

		points = li.xpath('./div[@class="Below"]/span/text()').extract()

		comments = li.xpath('./div[@class="Below"]/span/a/text()').extract()
		comments_link = li.xpath('./div[@class="Below"]/span/a/@href').extract()

		nid = None
		if len(source_link)>0:
			#print source_link
			m = re.findall('(\d+)', source_link[0])
			if len(m)>0:
				nid = m[0]
		if nid is None:
			continue

		if len(source_link) > 0:
			source_link = source_link[0]
		else:
			source_link=None
		if len(title)>0:
			title = title[0]
		else:
			title = None

		if len(sub_title)>0:
			sub_title = sub_title[0]
		else:
			sub_title = None

		if len(points)>0:
			m = re.findall('(\d+) point', points[0])
			if len(m)>0:
				points = m[0]
			else:
				points = 0
		else:
			points = 0

		if len(comments)>0:
			m = re.findall('(\d+)', comments[0])
			if len(m)>0:
				comments = m[0]
			else:
				comments = 0
		else:
			comments = 0

		if len(comments_link)>0:
			comments_link = comments_link[0]
			comments_link = "https://news.layervault.com"+ comments_link
		else:
			comments_link = None

		news = dict()
		news['site'] = Site
		news['newsId'] = nid
		news['title'] = title
		news['subTitle']  = sub_title
		news['sourceUrl'] = source_link
		news['voteCount'] = points
		news['commentCount'] = comments
		news['url'] = comments_link
		news['createAt'] = None
		# print link, title, points, comments, news_link
		#print news
		news_list.append(news)

	return news_list

def run():
	# delete_news(Site)
	news_list = []
	fetch_news("https://news.layervault.com/", news_list)
	fetch_news("https://news.layervault.com/p/2", news_list)
	fetch_news("https://news.layervault.com/p/3", news_list)

	now = datetime.now()
	last_time = datetime(now.year, now.month, now.day, 23, 59,59)
	first_time = datetime(now.year, now.month, now.day, 0, 0,1)

	last_timestamp = int(time.mktime(last_time.timetuple()))
	for news in news_list:
		news['sorts'] = last_timestamp
		last_timestamp -= 1

	save_news(Site,news_list)
	update_sites(Site)
	#save_cache(Site, news_list)


text:
namespace content {

struct GATTConnectionAndServerClient {
  GATTConnectionAndServerClient(
      std::unique_ptr<device::BluetoothGattConnection> connection,
      mojo::AssociatedRemote<blink::mojom::WebBluetoothServerClient> client)
      : gatt_connection(std::move(connection)),
        server_client(std::move(client)) {}

  std::unique_ptr<device::BluetoothGattConnection> gatt_connection;
  mojo::AssociatedRemote<blink::mojom::WebBluetoothServerClient> server_client;
};

FrameConnectedBluetoothDevices::FrameConnectedBluetoothDevices(
    RenderFrameHost& rfh)
    : web_contents_impl_(static_cast<WebContentsImpl*>(
          WebContents::FromRenderFrameHost(&rfh))) {}

FrameConnectedBluetoothDevices::~FrameConnectedBluetoothDevices() {
  for (size_t i = 0; i < device_id_to_connection_map_.size(); i++) {
    DecrementDevicesConnectedCount();
  }
}

bool FrameConnectedBluetoothDevices::IsConnectedToDeviceWithId(
    const blink::WebBluetoothDeviceId& device_id) {
  auto connection_iter = device_id_to_connection_map_.find(device_id);
  if (connection_iter == device_id_to_connection_map_.end()) {
    return false;
  }
  DCHECK(connection_iter->second->gatt_connection->IsConnected());
  return true;
}

void FrameConnectedBluetoothDevices::Insert(
    const blink::WebBluetoothDeviceId& device_id,
    std::unique_ptr<device::BluetoothGattConnection> connection,
    mojo::AssociatedRemote<blink::mojom::WebBluetoothServerClient> client) {
  if (device_id_to_connection_map_.find(device_id) !=
      device_id_to_connection_map_.end()) {
    // It's possible for WebBluetoothServiceImpl to issue two successive
    // connection requests for which it would get two successive responses
    // and consequently try to insert two BluetoothGattConnections for the
    // same device. WebBluetoothServiceImpl should reject or queue connection
    // requests if there is a pending connection already, but the platform
    // abstraction doesn't currently support checking for pending connections.
    // TODO(ortuno): CHECK that this never happens once the platform
    // abstraction allows to check for pending connections.
    // http://crbug.com/583544
    return;
  }
  device_address_to_id_map_[connection->GetDeviceAddress()] = device_id;
  auto gatt_connection_and_client =
      std::make_unique<GATTConnectionAndServerClient>(std::move(connection),
                                                      std::move(client));
  device_id_to_connection_map_[device_id] =
      std::move(gatt_connection_and_client);
  IncrementDevicesConnectedCount();
}

void FrameConnectedBluetoothDevices::CloseConnectionToDeviceWithId(
    const blink::WebBluetoothDeviceId& device_id) {
  auto connection_iter = device_id_to_connection_map_.find(device_id);
  if (connection_iter == device_id_to_connection_map_.end()) {
    return;
  }
  CHECK(device_address_to_id_map_.erase(
      connection_iter->second->gatt_connection->GetDeviceAddress()));
  connection_iter->second->server_client->GATTServerDisconnected();
  device_id_to_connection_map_.erase(connection_iter);
  DecrementDevicesConnectedCount();
}

absl::optional<blink::WebBluetoothDeviceId>
FrameConnectedBluetoothDevices::CloseConnectionToDeviceWithAddress(
    const std::string& device_address) {
  auto device_address_iter = device_address_to_id_map_.find(device_address);
  if (device_address_iter == device_address_to_id_map_.end()) {
    return absl::nullopt;
  }
  blink::WebBluetoothDeviceId device_id = device_address_iter->second;
  auto device_id_iter = device_id_to_connection_map_.find(device_id);
  CHECK(device_id_iter != device_id_to_connection_map_.end());
  device_id_iter->second->server_client->GATTServerDisconnected();
  CHECK(device_address_to_id_map_.erase(device_address));
  device_id_to_connection_map_.erase(device_id);
  DecrementDevicesConnectedCount();
  return absl::make_optional(device_id);
}

void FrameConnectedBluetoothDevices::CloseConnectionsToDevicesNotInList(
    const std::set<blink::WebBluetoothDeviceId>& permitted_ids) {
  std::set<blink::WebBluetoothDeviceId> ids_to_delete;

  for (const auto& device_pair : device_id_to_connection_map_) {
    if (!base::Contains(permitted_ids, device_pair.first))
      ids_to_delete.insert(device_pair.first);
  }

  for (const auto& device_id : ids_to_delete)
    CloseConnectionToDeviceWithId(device_id);
}

void FrameConnectedBluetoothDevices::IncrementDevicesConnectedCount() {
  web_contents_impl_->IncrementBluetoothConnectedDeviceCount();
}

void FrameConnectedBluetoothDevices::DecrementDevicesConnectedCount() {
  web_contents_impl_->DecrementBluetoothConnectedDeviceCount();
}

}  // namespace content


text:
layout: post
date: 2018-03-10
title: "Sarah Houston Gown Name Monaco 2015"
category: Sarah Houston
tags: [Sarah Houston,2015]
---
### Sarah Houston Gown Name Monaco
Just **$339.99**
### 2015

BRANDS	Sarah Houston

Years	2015

Buy it: [https://www.readybrides.com/en/sarah-houston/47300-sarah-houston-gown-name-monaco.html](https://www.readybrides.com/en/sarah-houston/47300-sarah-houston-gown-name-monaco.html)


text:
package com.amazonaws.services.healthlake.model;

import java.io.Serializable;
import javax.annotation.Generated;

/**
 *
 * @see AWS
 *      API Documentation
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DescribeFHIRImportJobResult extends com.amazonaws.AmazonWebServiceResult<com.amazonaws.ResponseMetadata> implements Serializable, Cloneable {

    /**
     *

     * The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     *

     */
    private ImportJobProperties importJobProperties;

    /**
     *

     * The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     *

     *
     * @param importJobProperties
     *        The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     */

    public void setImportJobProperties(ImportJobProperties importJobProperties) {
        this.importJobProperties = importJobProperties;
    }

    /**
     *

     * The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     *

     *
     * @return The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     */

    public ImportJobProperties getImportJobProperties() {
        return this.importJobProperties;
    }

    /**
     *

     * The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     *

     *
     * @param importJobProperties
     *        The properties of the Import job request, including the ID, ARN, name, and the status of the job.
     * @return Returns a reference to this object so that method calls can be chained together.
     */

    public DescribeFHIRImportJobResult withImportJobProperties(ImportJobProperties importJobProperties) {
        setImportJobProperties(importJobProperties);
        return this;
    }

    /**
     * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be
     * redacted from this string using a placeholder value.
     *
     * @return A string representation of this object.
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        if (getImportJobProperties() != null)
            sb.append("ImportJobProperties: ").append(getImportJobProperties());
        sb.append("}");
        return sb.toString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;

        if (obj instanceof DescribeFHIRImportJobResult == false)
            return false;
        DescribeFHIRImportJobResult other = (DescribeFHIRImportJobResult) obj;
        if (other.getImportJobProperties() == null ^ this.getImportJobProperties() == null)
            return false;
        if (other.getImportJobProperties() != null && other.getImportJobProperties().equals(this.getImportJobProperties()) == false)
            return false;
        return true;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int hashCode = 1;

        hashCode = prime * hashCode + ((getImportJobProperties() == null) ? 0 : getImportJobProperties().hashCode());
        return hashCode;
    }

    @Override
    public DescribeFHIRImportJobResult clone() {
        try {
            return (DescribeFHIRImportJobResult) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e);
        }
    }

}


text:
package org.apache.ofbiz.base.util.cache;

import org.apache.ofbiz.base.concurrent.ExecutionPool;

public abstract class CacheLine<V> extends ExecutionPool.Pulse {
    protected CacheLine(long loadTimeNanos, long expireTimeNanos) {
        super(loadTimeNanos, expireTimeNanos);
    }

    abstract CacheLine<V> changeLine(boolean useSoftReference, long expireTimeNanos);
    abstract void remove();
    boolean differentExpireTime(long expireTimeNanos) {
        return this.expireTimeNanos - loadTimeNanos - expireTimeNanos != 0;
    }
    public abstract V getValue();

    void cancel() {
    }

    @Override
    public void run() {
        remove();
    }
}


text:
require 'spec_helper'

RSpec.describe Vpsa::Entity::Commercial::Product do
  describe "as_parameter" do

    let(:product_as_parameter) {{"descricao"=>"descricao", "classificacao"=>"classificacao", "origem"=>"origem", "fci"=>"fci", "metodoControle"=>"ESTOCAVEL",
      "unidade"=>"UN", "custoReferencial"=>BigDecimal.new("10.35"), "codigoNcm"=>"12", "cnpjFornecedores"=>"cnpjFornecedores", "especificacao"=>"especificacao",
      "codigoBarras"=>"codigoBarras", "codigoInterno"=>"codigoInterno", "codigoSistema"=>"codigoSistema", "estoqueMaximo"=>BigDecimal.new("10.0"), "estoqueMinimo"=>BigDecimal.new("2.0"),
      "ativo"=>true, "descontoMaximo"=>BigDecimal.new("1.0"), "comissao"=>BigDecimal.new("2.0"), "preco"=>BigDecimal.new("14.0") }}

    it "should return the product as parameter" do
      product = Vpsa::Entity::Commercial::Product.new({"descricao"=>"descricao", "classificacao"=>"classificacao", "origem"=>"origem", "fci"=>"fci", "metodoControle"=>"ESTOCAVEL",
      "unidade"=>"UN", "custoReferencial"=>BigDecimal.new("10.35"), "codigoNcm"=>"12", "cnpjFornecedores"=>"cnpjFornecedores", "especificacao"=>"especificacao",
      "codigoBarras"=>"codigoBarras", "codigoInterno"=>"codigoInterno", "codigoSistema"=>"codigoSistema", "estoqueMaximo"=>BigDecimal.new("10.0"), "estoqueMinimo"=>BigDecimal.new("2.0"),
      "ativo"=>true, "descontoMaximo"=>BigDecimal.new("1.0"), "comissao"=>BigDecimal.new("2.0"), "preco"=>BigDecimal.new("14.0") })

      expect(product.as_parameter).to eq(product_as_parameter)
    end

  end

end


text:
package com.apruve.test;

import java.util.ArrayList;
import java.util.List;

import com.apruve.models.LineItem;

public class LineItemOM {

	public static LineItem getMinimalLineItem() {
		LineItem line = new LineItem("A Line Item");
		line.setAmountCents(100);
		return line;
	}

	public static LineItem getLineItem() {
		LineItem line = new LineItem("Another Line Item");
		line.setAmountCents(100);
		line.setDescription("A discription for this line");
		line.setSku("A_SKU_NUMBER");
		return line;
	}

	public static List<LineItem> getLineItems() {
		ArrayList<LineItem> result = new ArrayList<LineItem>();
		result.add(getMinimalLineItem());
		result.add(getLineItem());

		return result;
	}
}


text:
owner_slack: "#govuk-developers"
title: Request tracing
section: Logging
layout: manual_layout
parent: "/manual.html"
type: learn
---

Request tracing makes it easier to understand how requests originating from users of publishing apps make their way through the system. For example, if a user publishes a piece of content, request tracing will "connect the dots" between that user's request and downstream requests that were made as a consequence of the publish.

## How it works

Nginx [sets a `GOVUK-Request-Id` HTTP header] on the initial request. Apps then pass the header to any APIs that they call.

For the most part, [gds-api-adapters][] handles this for you. The adapters read the `HTTP_GOVUK_REQUEST_ID` header and forward this onto backend services. A search can then be carried out against log files for a single request id to see all of the backend service requests that were made in consequence to the originating request.

For example, the nginx logs in `/var/log/nginx/<service>-json.event.access.log`will include a `govuk_request_id` field. You can also filter on `govuk_request_id` in [Kibana][].

[sets a `GOVUK-Request-Id` HTTP header]: https://github.com/alphagov/govuk-puppet/blob/05af15200690afdeb0f5a48c73601c3cabbadeae/modules/nginx/templates/proxy-vhost.conf#L7-L25
[gds-api-adapters]: https://github.com/alphagov/gds-api-adapters
[Kibana]: /manual/logit.html#viewing-kibana

## When it "just works"

If you are using [gds-api-adapters][] to speak to backend services and your requests are handled synchronously, you don't need to do anything. It should just work.

## When it doesn't "just work"

If you are running out-of-band processes via asynchronous workers (e.g. Sidekiq)the request id won't be available in the worker and will not be sent downstream. This also includes any rake tasks you may have, such as republishing tasks.

For many of these cases, there isn't an originating request and so it's fine not to send a request id downstream. The request id will be generated and populated once a subsequent downstream request hits a load balancer, this will result in a partial trace.

In cases where you do have a request id available, it is preferable to send this downstream as this could make it easier to debug in the future.

Use [govuk_sidekiq][] to do this. This gem injects middleware that will pass on the request id.

[govuk_sidekiq]: https://github.com/alphagov/govuk_sidekiq


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Fl. Champ. sup. France (Chalon-sur-Saône) 1: 409 (1909)

#### Original name
Boletus maximus Schumach., 1803

### Remarks
null


text:
package opentsdb

import "time"
import bulkQuerygen "github.com/influxdata/influxdb-comparisons/bulk_query_gen"

// OpenTSDBDevopsSingleHost produces OpenTSDB-specific queries for the devops single-host case.
type OpenTSDBDevopsSingleHost struct {
	OpenTSDBDevops
}

func NewOpenTSDBDevopsSingleHost(_ bulkQuerygen.DatabaseConfig, queriesFullRange bulkQuerygen.TimeInterval, queryInterval time.Duration, scaleVar int) bulkQuerygen.QueryGenerator {
	underlying := newOpenTSDBDevopsCommon(queriesFullRange, queryInterval, scaleVar).(*OpenTSDBDevops)
	return &OpenTSDBDevopsSingleHost{
		OpenTSDBDevops: *underlying,
	}
}

func (d *OpenTSDBDevopsSingleHost) Dispatch(i int) bulkQuerygen.Query {
	q := bulkQuerygen.NewHTTPQuery() // from pool
	d.MaxCPUUsageHourByMinuteOneHost(q)
	return q
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.castlemock.model</groupId>
    <artifactId>model</artifactId>
    <packaging>pom</packaging>

    <parent>
        <groupId>com.castlemock</groupId>
        <artifactId>castlemock</artifactId>
        <version>${project.version}</version>
        <relativePath>../</relativePath>
    </parent>

    <modules>
        <module>model-core</module>
        <module>model-expression</module>
        <module>model-mock</module>
    </modules>

</project>


text:
/*! \file $Id: CharEvent.h 64 2011-06-15 14:01:00Z caoym $
*  \author caoym
*  \brief CCharEvent
*/
#pragma once
#include "IInputEvent.h"
//! input character
/*
	keyboard input as if the corresponding character was generated on the keyboard
*/
class CCharEvent:public IInputEvent
{
public:
	CCharEvent(wchar_t c);
	void Input();
private:
	wchar_t m_char;
};


text:
package nishi_service::Web;
use strict;
use warnings;
use utf8;
use parent qw/nishi_service Amon2::Web/;
use File::Spec;
use nishi_service::DB;

# dispatcher
use nishi_service::Web::Dispatcher;
sub dispatch {
    return (nishi_service::Web::Dispatcher->dispatch($_[0]) or die "response is not generated");
}

# load plugins
__PACKAGE__->load_plugins(
    'Web::FillInFormLite',
    'Web::JSON',
    '+nishi_service::Web::Plugin::Session',
);

use nishi_service::Web::Request;
sub create_request { nishi_service::Web::Request->new($_[1], $_[0]) }

# setup view
use nishi_service::Web::View;
{
    sub create_view {
        my $view = nishi_service::Web::View->make_instance(__PACKAGE__);
        no warnings 'redefine';
        *nishi_service::Web::create_view = sub { $view }; # Class cache.
        $view
    }
}

# for your security
__PACKAGE__->add_trigger(
    AFTER_DISPATCH => sub {
        my ( $c, $res ) = @_;

        # http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
        $res->header( 'X-Content-Type-Options' => 'nosniff' );

        # http://blog.mozilla.com/security/2010/09/08/x-frame-options/
        $res->header( 'X-Frame-Options' => 'DENY' );

        # Cache control.
        $res->header( 'Cache-Control' => 'private' );
    },
);

__PACKAGE__->load_plugin('Web::Auth',{
    module => 'LINENotify',
    on_finished => sub {
    	my ($c, $access_token) = @_;
        $c->session->set('token' => $access_token);
    	return $c->redirect('/account/register');
    }
});

1;


text:
"""Accuracy tests for ICRS transformations, primarily to/from AltAz.

"""
import numpy as np

from astropy import units as u
from astropy.tests.helper import assert_quantity_allclose as assert_allclose
from astropy.time import Time
from astropy.coordinates import (
    EarthLocation, ICRS,  CIRS, AltAz, HADec, SkyCoord)

from astropy.coordinates.angle_utilities import golden_spiral_grid
from astropy.coordinates import frame_transform_graph

def test_icrs_altaz_consistency():
    """
    Check ICRS<->AltAz for consistency with ICRS<->CIRS<->AltAz

    The latter is extensively tested in test_intermediate_transformations.py
    """
    usph = golden_spiral_grid(200)
    dist = np.linspace(0.5, 1, len(usph)) * u.km * 1e5
    icoo = SkyCoord(ra=usph.lon, dec=usph.lat, distance=dist)

    observer = EarthLocation(28*u.deg, 23*u.deg, height=2000.*u.km)
    obstime = Time('J2010')
    aa_frame = AltAz(obstime=obstime, location=observer)

    # check we are going direct!
    trans = frame_transform_graph.get_transform(ICRS, AltAz).transforms
    assert(len(trans) == 1)

    # check that ICRS-AltAz and ICRS->CIRS->AltAz are consistent
    aa1 = icoo.transform_to(aa_frame)
    aa2 = icoo.transform_to(CIRS()).transform_to(aa_frame)
    assert_allclose(aa1.separation_3d(aa2), 0*u.mm, atol=1*u.mm)

    # check roundtrip
    roundtrip = icoo.transform_to(aa_frame).transform_to(icoo)
    assert_allclose(roundtrip.separation_3d(icoo), 0*u.mm, atol=1*u.mm)

    # check there and back via CIRS mish-mash
    roundtrip = icoo.transform_to(aa_frame).transform_to(
        CIRS()).transform_to(icoo)
    assert_allclose(roundtrip.separation_3d(icoo), 0*u.mm, atol=1*u.mm)

def test_icrs_hadec_consistency():
    """
    Check ICRS<->HADec for consistency with ICRS<->CIRS<->HADec
    """
    usph = golden_spiral_grid(200)
    dist = np.linspace(0.5, 1, len(usph)) * u.km * 1e5
    icoo = SkyCoord(ra=usph.lon, dec=usph.lat, distance=dist)

    observer = EarthLocation(28*u.deg, 23*u.deg, height=2000.*u.km)
    obstime = Time('J2010')
    hd_frame = HADec(obstime=obstime, location=observer)

    # check we are going direct!
    trans = frame_transform_graph.get_transform(ICRS, HADec).transforms
    assert(len(trans) == 1)

    # check that ICRS-HADec and ICRS->CIRS->HADec are consistent
    aa1 = icoo.transform_to(hd_frame)
    aa2 = icoo.transform_to(CIRS()).transform_to(hd_frame)
    assert_allclose(aa1.separation_3d(aa2), 0*u.mm, atol=1*u.mm)

    # check roundtrip
    roundtrip = icoo.transform_to(hd_frame).transform_to(icoo)
    assert_allclose(roundtrip.separation_3d(icoo), 0*u.mm, atol=1*u.mm)

    # check there and back via CIRS mish-mash
    roundtrip = icoo.transform_to(hd_frame).transform_to(
        CIRS()).transform_to(icoo)
    assert_allclose(roundtrip.separation_3d(icoo), 0*u.mm, atol=1*u.mm)


text:
#include "compile_time_macros.h"

extern "C" {
#include "atomic.h"
#include "clock.h"
#include "common.h"
#include "console.h"
#include "cryptoc/util.h"
#include "ec_commands.h"
#include "fpsensor.h"
#include "fpsensor_crypto.h"
#include "fpsensor_detect.h"
#include "fpsensor_private.h"
#include "fpsensor_state.h"
#include "gpio.h"
#include "host_command.h"
#include "link_defs.h"
#include "mkbp_event.h"
#include "overflow.h"
#include "spi.h"
#include "system.h"
#include "task.h"
#include "trng.h"
#include "util.h"
#include "watchdog.h"
}

#if !defined(CONFIG_RNG)
#error "fpsensor requires RNG"
#endif

#if defined(SECTION_IS_RO)
#error "fpsensor code should not be in RO image."
#endif

/* Ready to encrypt a template. */
static timestamp_t encryption_deadline;

/* raw image offset inside the acquired frame */
#ifndef FP_SENSOR_IMAGE_OFFSET
#define FP_SENSOR_IMAGE_OFFSET 0
#endif

#define FP_MODE_ANY_CAPTURE \
	(FP_MODE_CAPTURE | FP_MODE_ENROLL_IMAGE | FP_MODE_MATCH)
#define FP_MODE_ANY_DETECT_FINGER \
	(FP_MODE_FINGER_DOWN | FP_MODE_FINGER_UP | FP_MODE_ANY_CAPTURE)
#define FP_MODE_ANY_WAIT_IRQ (FP_MODE_FINGER_DOWN | FP_MODE_ANY_CAPTURE)

/* Delay between 2 s of the sensor to detect finger removal */
#define FINGER_POLLING_DELAY (100 * MSEC)

/* Timing statistics. */
static uint32_t capture_time_us;
static uint32_t matching_time_us;
static uint32_t overall_time_us;
static timestamp_t overall_t0;
static uint8_t timestamps_invalid;

BUILD_ASSERT(sizeof(struct ec_fp_template_encryption_metadata) % 4 == 0);

/* Interrupt line from the fingerprint sensor */
void fps_event(enum gpio_signal signal)
{
	task_set_event(TASK_ID_FPSENSOR, TASK_EVENT_SENSOR_IRQ);
}

static void send_mkbp_event(uint32_t event)
{
	atomic_or(&fp_events, event);
	mkbp_send_event(EC_MKBP_EVENT_FINGERPRINT);
}

static inline int is_raw_capture(uint32_t mode)
{
	int capture_type = FP_CAPTURE_TYPE(mode);

	return (capture_type == FP_CAPTURE_VENDOR_FORMAT ||
		capture_type == FP_CAPTURE_QUALITY_TEST);
}

__maybe_unused static bool fp_match_success(int match_result)
{
	return match_result == EC_MKBP_FP_ERR_MATCH_YES ||
	       match_result == EC_MKBP_FP_ERR_MATCH_YES_UPDATED ||
	       match_result == EC_MKBP_FP_ERR_MATCH_YES_UPDATE_FAILED;
}

#ifdef HAVE_FP_PRIVATE_DRIVER
static inline int is_test_capture(uint32_t mode)
{
	int capture_type = FP_CAPTURE_TYPE(mode);

	return (mode & FP_MODE_CAPTURE) &&
	       (capture_type == FP_CAPTURE_PATTERN0 ||
		capture_type == FP_CAPTURE_PATTERN1 ||
		capture_type == FP_CAPTURE_RESET_TEST);
}

/*
 * contains the bit FP_MODE_ENROLL_SESSION if a finger enrollment is on-going.
 * It is used to detect the ENROLL_SESSION transition when sensor_mode is
 * updated by the host.
 */
static uint32_t enroll_session;

static uint32_t fp_process_enroll(void)
{
	int percent = 0;
	int res;

	if (template_newly_enrolled != FP_NO_SUCH_TEMPLATE)
		CPRINTS("Warning: previously enrolled template has not been "
			"read yet.");

	/* begin/continue enrollment */
	CPRINTS("[%d]Enrolling ...", templ_valid);
	res = fp_finger_enroll(fp_buffer, &percent);
	CPRINTS("[%d]Enroll =>%d (%d%%)", templ_valid, res, percent);
	if (res < 0)
		return EC_MKBP_FP_ENROLL |
		       EC_MKBP_FP_ERRCODE(EC_MKBP_FP_ERR_ENROLL_INTERNAL);
	templ_dirty |= BIT(templ_valid);
	if (percent == 100) {
		res = fp_enrollment_finish(fp_template[templ_valid]);
		if (res) {
			res = EC_MKBP_FP_ERR_ENROLL_INTERNAL;
		} else {
			template_newly_enrolled = templ_valid;
			fp_enable_positive_match_secret(
				templ_valid, &positive_match_secret_state);
			templ_valid++;
		}
		sensor_mode &= ~FP_MODE_ENROLL_SESSION;
		enroll_session &= ~FP_MODE_ENROLL_SESSION;
	}
	return EC_MKBP_FP_ENROLL | EC_MKBP_FP_ERRCODE(res) |
	       (percent << EC_MKBP_FP_ENROLL_PROGRESS_OFFSET);
}

static uint32_t fp_process_match(void)
{
	timestamp_t t0 = get_time();
	int res = -1;
	uint32_t updated = 0;
	int32_t fgr = FP_NO_SUCH_TEMPLATE;

	/* match finger against current templates */
	fp_disable_positive_match_secret(&positive_match_secret_state);
	CPRINTS("Matching/%d ...", templ_valid);
	if (templ_valid) {
		res = fp_finger_match(fp_template[0], templ_valid, fp_buffer,
				      &fgr, &updated);
		CPRINTS("Match =>%d (finger %d)", res, fgr);

		if (fp_match_success(res)) {
			/*
			 * Match succeded! Let's check if template number
			 * is valid. If it is not valid, overwrite result
			 * with EC_MKBP_FP_ERR_MATCH_NO_INTERNAL.
			 */
			if (fgr >= 0 && fgr < FP_MAX_FINGER_COUNT) {
				fp_enable_positive_match_secret(
					fgr, &positive_match_secret_state);
			} else {
				res = EC_MKBP_FP_ERR_MATCH_NO_INTERNAL;
			}
		} else if (res < 0) {
			/*
			 * Negative result means that there is a problem with
			 * code responsible for matching. Overwrite it with
			 * MATCH_NO_INTERNAL to let upper layers know what
			 * happened.
			 */
			res = EC_MKBP_FP_ERR_MATCH_NO_INTERNAL;
		}

		if (res == EC_MKBP_FP_ERR_MATCH_YES_UPDATED)
			templ_dirty |= updated;
	} else {
		CPRINTS("No enrolled templates");
		res = EC_MKBP_FP_ERR_MATCH_NO_TEMPLATES;
	}

	if (!fp_match_success(res))
		timestamps_invalid |= FPSTATS_MATCHING_INV;

	matching_time_us = time_since32(t0);
	return EC_MKBP_FP_MATCH | EC_MKBP_FP_ERRCODE(res) |
	       ((fgr << EC_MKBP_FP_MATCH_IDX_OFFSET) &
		EC_MKBP_FP_MATCH_IDX_MASK);
}

static void fp_process_finger(void)
{
	timestamp_t t0 = get_time();
	int res;

	CPRINTS("Capturing ...");
	res = fp_sensor_acquire_image_with_mode(fp_buffer,
						FP_CAPTURE_TYPE(sensor_mode));
	capture_time_us = time_since32(t0);
	if (!res) {
		uint32_t evt = EC_MKBP_FP_IMAGE_READY;

		/* Clean up SPI before clocking up to avoid hang on the dsb
		 * in dma_go. Ignore the return value to let the WDT reboot
		 * the MCU (and avoid getting trapped in the loop).
		 * b/112781659 */
		res = spi_transaction_flush(&spi_devices[0]);
		if (res)
			CPRINTS("Failed to flush SPI: 0x%x", res);
		/* we need CPU power to do the computations */
		clock_enable_module(MODULE_FAST_CPU, 1);

		if (sensor_mode & FP_MODE_ENROLL_IMAGE)
			evt = fp_process_enroll();
		else if (sensor_mode & FP_MODE_MATCH)
			evt = fp_process_match();

		sensor_mode &= ~FP_MODE_ANY_CAPTURE;
		overall_time_us = time_since32(overall_t0);
		send_mkbp_event(evt);

		/* go back to lower power mode */
		clock_enable_module(MODULE_FAST_CPU, 0);
	} else {
		timestamps_invalid |= FPSTATS_CAPTURE_INV;
	}
}
#endif /* HAVE_FP_PRIVATE_DRIVER */

extern "C" void fp_task(void)
{
	int timeout_us = -1;

	CPRINTS("FP_SENSOR_SEL: %s",
		fp_sensor_type_to_str(get_fp_sensor_type()));

#ifdef HAVE_FP_PRIVATE_DRIVER
	/* Reset and initialize the sensor IC */
	fp_sensor_init();

	while (1) {
		uint32_t evt;
		enum finger_state st = FINGER_NONE;

		/* Wait for a sensor IRQ or a new mode configuration */
		evt = task_wait_event(timeout_us);

		if (evt & TASK_EVENT_UPDATE_CONFIG) {
			uint32_t mode = sensor_mode;

			gpio_disable_interrupt(GPIO_FPS_INT);
			if ((mode ^ enroll_session) & FP_MODE_ENROLL_SESSION) {
				if (mode & FP_MODE_ENROLL_SESSION) {
					if (fp_enrollment_begin())
						sensor_mode &=
							~FP_MODE_ENROLL_SESSION;
				} else {
					fp_enrollment_finish(NULL);
				}
				enroll_session = sensor_mode &
						 FP_MODE_ENROLL_SESSION;
			}
			if (is_test_capture(mode)) {
				fp_sensor_acquire_image_with_mode(
					fp_buffer, FP_CAPTURE_TYPE(mode));
				sensor_mode &= ~FP_MODE_CAPTURE;
				send_mkbp_event(EC_MKBP_FP_IMAGE_READY);
				continue;
			} else if (sensor_mode & FP_MODE_ANY_DETECT_FINGER) {
				/* wait for a finger on the sensor */
				fp_sensor_configure_detect();
			}
			if (sensor_mode & FP_MODE_DEEPSLEEP)
				/* Shutdown the sensor */
				fp_sensor_low_power();
			if (sensor_mode & FP_MODE_FINGER_UP)
				/* Poll the sensor to detect finger removal */
				timeout_us = FINGER_POLLING_DELAY;
			else
				timeout_us = -1;
			if (mode & FP_MODE_ANY_WAIT_IRQ) {
				gpio_enable_interrupt(GPIO_FPS_INT);
			} else if (mode & FP_MODE_RESET_SENSOR) {
				fp_reset_and_clear_context();
				sensor_mode &= ~FP_MODE_RESET_SENSOR;
			} else if (mode & FP_MODE_SENSOR_MAINTENANCE) {
				fp_maintenance();
				sensor_mode &= ~FP_MODE_SENSOR_MAINTENANCE;
			} else {
				fp_sensor_low_power();
			}
		} else if (evt & (TASK_EVENT_SENSOR_IRQ | TASK_EVENT_TIMER)) {
			overall_t0 = get_time();
			timestamps_invalid = 0;
			gpio_disable_interrupt(GPIO_FPS_INT);
			if (sensor_mode & FP_MODE_ANY_DETECT_FINGER) {
				st = fp_sensor_finger_status();
				if (st == FINGER_PRESENT &&
				    sensor_mode & FP_MODE_FINGER_DOWN) {
					CPRINTS("Finger!");
					sensor_mode &= ~FP_MODE_FINGER_DOWN;
					send_mkbp_event(EC_MKBP_FP_FINGER_DOWN);
				}
				if (st == FINGER_NONE &&
				    sensor_mode & FP_MODE_FINGER_UP) {
					sensor_mode &= ~FP_MODE_FINGER_UP;
					timeout_us = -1;
					send_mkbp_event(EC_MKBP_FP_FINGER_UP);
				}
			}

			if (st == FINGER_PRESENT &&
			    sensor_mode & FP_MODE_ANY_CAPTURE)
				fp_process_finger();

			if (sensor_mode & FP_MODE_ANY_WAIT_IRQ) {
				fp_sensor_configure_detect();
				gpio_enable_interrupt(GPIO_FPS_INT);
			} else {
				fp_sensor_low_power();
			}
		}
	}
#else /* !HAVE_FP_PRIVATE_DRIVER */
	while (1) {
		uint32_t evt = task_wait_event(timeout_us);

		send_mkbp_event(evt);
	}
#endif /* !HAVE_FP_PRIVATE_DRIVER */
}

static enum ec_status fp_command_passthru(struct host_cmd_handler_args *args)
{
	const struct ec_params_fp_passthru *params =
		static_cast<const ec_params_fp_passthru *>(args->params);
	uint8_t *out = static_cast<uint8_t *>(args->response);
	int rc;
	enum ec_status ret = EC_RES_SUCCESS;

	if (system_is_locked())
		return EC_RES_ACCESS_DENIED;

	if (params->len >
		    args->params_size +
			    offsetof(struct ec_params_fp_passthru, data) ||
	    params->len > args->response_max)
		return EC_RES_INVALID_PARAM;

	rc = spi_transaction_async(&spi_devices[0], params->data, params->len,
				   out, SPI_READBACK_ALL);
	if (params->flags & EC_FP_FLAG_NOT_COMPLETE)
		rc |= spi_transaction_wait(&spi_devices[0]);
	else
		rc |= spi_transaction_flush(&spi_devices[0]);

	if (rc == EC_ERROR_TIMEOUT)
		ret = EC_RES_TIMEOUT;
	else if (rc)
		ret = EC_RES_ERROR;

	args->response_size = params->len;
	return ret;
}
DECLARE_HOST_COMMAND(EC_CMD_FP_PASSTHRU, fp_command_passthru, EC_VER_MASK(0));

static enum ec_status fp_command_info(struct host_cmd_handler_args *args)
{
	struct ec_response_fp_info *r =
		static_cast<ec_response_fp_info *>(args->response);

#ifdef HAVE_FP_PRIVATE_DRIVER
	if (fp_sensor_get_info(r) < 0)
#endif
		return EC_RES_UNAVAILABLE;

	r->template_size = FP_ALGORITHM_ENCRYPTED_TEMPLATE_SIZE;
	r->template_max = FP_MAX_FINGER_COUNT;
	r->template_valid = templ_valid;
	r->template_dirty = templ_dirty;
	r->template_version = FP_TEMPLATE_FORMAT_VERSION;

	/* V1 is identical to V0 with more information appended */
	args->response_size = args->version ?
				      sizeof(*r) :
				      sizeof(struct ec_response_fp_info_v0);
	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_FP_INFO, fp_command_info,
		     EC_VER_MASK(0) | EC_VER_MASK(1));

BUILD_ASSERT(FP_CONTEXT_NONCE_BYTES == 12);

int validate_fp_buffer_offset(const uint32_t buffer_size, const uint32_t offset,
			      const uint32_t size)
{
	uint32_t bytes_requested;

	if (check_add_overflow(size, offset, &bytes_requested))
		return EC_ERROR_OVERFLOW;

	if (bytes_requested > buffer_size)
		return EC_ERROR_INVAL;

	return EC_SUCCESS;
}

static enum ec_status fp_command_frame(struct host_cmd_handler_args *args)
{
	const struct ec_params_fp_frame *params =
		static_cast<const struct ec_params_fp_frame *>(args->params);
	void *out = args->response;
	uint32_t idx = FP_FRAME_GET_BUFFER_INDEX(params->offset);
	uint32_t offset = params->offset & FP_FRAME_OFFSET_MASK;
	uint32_t size = params->size;
	uint32_t fgr;
	uint8_t key[SBP_ENC_KEY_LEN];
	struct ec_fp_template_encryption_metadata *enc_info;
	int ret;

	if (size > args->response_max)
		return EC_RES_INVALID_PARAM;

	if (idx == FP_FRAME_INDEX_RAW_IMAGE) {
		/* The host requested a frame. */
		if (system_is_locked())
			return EC_RES_ACCESS_DENIED;
		if (!is_raw_capture(sensor_mode))
			offset += FP_SENSOR_IMAGE_OFFSET;

		ret = validate_fp_buffer_offset(sizeof(fp_buffer), offset,
						size);
		if (ret != EC_SUCCESS)
			return EC_RES_INVALID_PARAM;

		memcpy(out, fp_buffer + offset, size);
		args->response_size = size;
		return EC_RES_SUCCESS;
	}

	/* The host requested a template. */

	/* Templates are numbered from 1 in this host request. */
	fgr = idx - FP_FRAME_INDEX_TEMPLATE;

	if (fgr >= FP_MAX_FINGER_COUNT)
		return EC_RES_INVALID_PARAM;
	if (fgr >= templ_valid)
		return EC_RES_UNAVAILABLE;
	ret = validate_fp_buffer_offset(sizeof(fp_enc_buffer), offset, size);
	if (ret != EC_SUCCESS)
		return EC_RES_INVALID_PARAM;

	if (!offset) {
		/* Host has requested the first chunk, do the encryption. */
		timestamp_t now = get_time();
		/* Encrypted template is after the metadata. */
		uint8_t *encrypted_template = fp_enc_buffer + sizeof(*enc_info);
		/* Positive match salt is after the template. */
		uint8_t *positive_match_salt =
			encrypted_template + sizeof(fp_template[0]);
		size_t encrypted_blob_size = sizeof(fp_template[0]) +
					     sizeof(fp_positive_match_salt[0]);

		/* b/114160734: Not more than 1 encrypted message per second. */
		if (!timestamp_expired(encryption_deadline, &now))
			return EC_RES_BUSY;
		encryption_deadline.val = now.val + (1 * SECOND);

		memset(fp_enc_buffer, 0, sizeof(fp_enc_buffer));
		/*
		 * The beginning of the buffer contains nonce, encryption_salt
		 * and tag.
		 */
		enc_info = (struct ec_fp_template_encryption_metadata
				    *)(fp_enc_buffer);
		enc_info->struct_version = FP_TEMPLATE_FORMAT_VERSION;
		trng_init();
		trng_rand_bytes(enc_info->nonce, FP_CONTEXT_NONCE_BYTES);
		trng_rand_bytes(enc_info->encryption_salt,
				FP_CONTEXT_ENCRYPTION_SALT_BYTES);
		trng_exit();

		/*
		 * TODO(http://b/244781166): Use consistent types so cast is
		 * not needed.
		 */
		if (fgr == (uint32_t)template_newly_enrolled) {
			/*
			 * Newly enrolled templates need new positive match
			 * salt, new positive match secret and new validation
			 * value.
			 */
			template_newly_enrolled = FP_NO_SUCH_TEMPLATE;
			trng_init();
			trng_rand_bytes(fp_positive_match_salt[fgr],
					FP_POSITIVE_MATCH_SALT_BYTES);
			trng_exit();
		}

		ret = derive_encryption_key(key, enc_info->encryption_salt);
		if (ret != EC_SUCCESS) {
			CPRINTS("fgr%d: Failed to derive key", fgr);
			return EC_RES_UNAVAILABLE;
		}

		/*
		 * Copy the payload to |fp_enc_buffer| where it will be
		 * encrypted in-place.
		 */
		memcpy(encrypted_template, fp_template[fgr],
		       sizeof(fp_template[0]));
		memcpy(positive_match_salt, fp_positive_match_salt[fgr],
		       sizeof(fp_positive_match_salt[0]));

		/* Encrypt the secret blob in-place. */
		ret = aes_gcm_encrypt(key, SBP_ENC_KEY_LEN, encrypted_template,
				      encrypted_template, encrypted_blob_size,
				      enc_info->nonce, FP_CONTEXT_NONCE_BYTES,
				      enc_info->tag, FP_CONTEXT_TAG_BYTES);
		always_memset(key, 0, sizeof(key));
		if (ret != EC_SUCCESS) {
			CPRINTS("fgr%d: Failed to encrypt template", fgr);
			return EC_RES_UNAVAILABLE;
		}
		templ_dirty &= ~BIT(fgr);
	}
	memcpy(out, fp_enc_buffer + offset, size);
	args->response_size = size;

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_FP_FRAME, fp_command_frame, EC_VER_MASK(0));

static enum ec_status fp_command_stats(struct host_cmd_handler_args *args)
{
	struct ec_response_fp_stats *r =
		static_cast<struct ec_response_fp_stats *>(args->response);

	r->capture_time_us = capture_time_us;
	r->matching_time_us = matching_time_us;
	r->overall_time_us = overall_time_us;
	r->overall_t0.lo = overall_t0.le.lo;
	r->overall_t0.hi = overall_t0.le.hi;
	r->timestamps_invalid = timestamps_invalid;
	/*
	 * Note that this is set to FP_NO_SUCH_TEMPLATE when positive match
	 * secret is read/disabled, and we are not using this field in biod.
	 */
	r->template_matched = positive_match_secret_state.template_matched;

	args->response_size = sizeof(*r);
	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_FP_STATS, fp_command_stats, EC_VER_MASK(0));

static bool template_needs_validation_value(
	struct ec_fp_template_encryption_metadata *enc_info)
{
	return enc_info->struct_version == 3 && FP_TEMPLATE_FORMAT_VERSION == 4;
}

static int
validate_template_format(struct ec_fp_template_encryption_metadata *enc_info)
{
	if (template_needs_validation_value(enc_info))
		/* The host requested migration to v4. */
		return EC_RES_SUCCESS;

	if (enc_info->struct_version != FP_TEMPLATE_FORMAT_VERSION) {
		CPRINTS("Invalid template format %d", enc_info->struct_version);
		return EC_RES_INVALID_PARAM;
	}
	return EC_RES_SUCCESS;
}

static enum ec_status fp_command_template(struct host_cmd_handler_args *args)
{
	const struct ec_params_fp_template *params =
		static_cast<const struct ec_params_fp_template *>(args->params);
	uint32_t size = params->size & ~FP_TEMPLATE_COMMIT;
	int xfer_complete = params->size & FP_TEMPLATE_COMMIT;
	uint32_t offset = params->offset;
	uint32_t idx = templ_valid;
	uint8_t key[SBP_ENC_KEY_LEN];
	struct ec_fp_template_encryption_metadata *enc_info;
	int ret;

	/* Can we store one more template ? */
	if (idx >= FP_MAX_FINGER_COUNT)
		return EC_RES_OVERFLOW;

	if (args->params_size !=
	    size + offsetof(struct ec_params_fp_template, data))
		return EC_RES_INVALID_PARAM;
	ret = validate_fp_buffer_offset(sizeof(fp_enc_buffer), offset, size);
	if (ret != EC_SUCCESS)
		return EC_RES_INVALID_PARAM;

	memcpy(&fp_enc_buffer[offset], params->data, size);

	if (xfer_complete) {
		/* Encrypted template is after the metadata. */
		uint8_t *encrypted_template = fp_enc_buffer + sizeof(*enc_info);
		/* Positive match salt is after the template. */
		uint8_t *positive_match_salt =
			encrypted_template + sizeof(fp_template[0]);
		size_t encrypted_blob_size;

		/*
		 * The complete encrypted template has been received, start
		 * decryption.
		 */
		fp_clear_finger_context(idx);
		/*
		 * The beginning of the buffer contains nonce, encryption_salt
		 * and tag.
		 */
		enc_info = (struct ec_fp_template_encryption_metadata *)
			fp_enc_buffer;
		ret = validate_template_format(enc_info);
		if (ret != EC_RES_SUCCESS) {
			CPRINTS("fgr%d: Template format not supported", idx);
			return EC_RES_INVALID_PARAM;
		}

		if (enc_info->struct_version <= 3) {
			encrypted_blob_size = sizeof(fp_template[0]);
		} else {
			encrypted_blob_size = sizeof(fp_template[0]) +
					      sizeof(fp_positive_match_salt[0]);
		}

		ret = derive_encryption_key(key, enc_info->encryption_salt);
		if (ret != EC_SUCCESS) {
			CPRINTS("fgr%d: Failed to derive key", idx);
			return EC_RES_UNAVAILABLE;
		}

		/* Decrypt the secret blob in-place. */
		ret = aes_gcm_decrypt(key, SBP_ENC_KEY_LEN, encrypted_template,
				      encrypted_template, encrypted_blob_size,
				      enc_info->nonce, FP_CONTEXT_NONCE_BYTES,
				      enc_info->tag, FP_CONTEXT_TAG_BYTES);
		always_memset(key, 0, sizeof(key));
		if (ret != EC_SUCCESS) {
			CPRINTS("fgr%d: Failed to decipher template", idx);
			/* Don't leave bad data in the template buffer */
			fp_clear_finger_context(idx);
			return EC_RES_UNAVAILABLE;
		}
		memcpy(fp_template[idx], encrypted_template,
		       sizeof(fp_template[0]));
		if (template_needs_validation_value(enc_info)) {
			CPRINTS("fgr%d: Generating positive match salt.", idx);
			trng_init();
			trng_rand_bytes(positive_match_salt,
					FP_POSITIVE_MATCH_SALT_BYTES);
			trng_exit();
		}
		if (bytes_are_trivial(positive_match_salt,
				      sizeof(fp_positive_match_salt[0]))) {
			CPRINTS("fgr%d: Trivial positive match salt.", idx);
			always_memset(fp_template[idx], 0,
				      sizeof(fp_template[0]));
			return EC_RES_INVALID_PARAM;
		}
		memcpy(fp_positive_match_salt[idx], positive_match_salt,
		       sizeof(fp_positive_match_salt[0]));

		templ_valid++;
	}

	return EC_RES_SUCCESS;
}
DECLARE_HOST_COMMAND(EC_CMD_FP_TEMPLATE, fp_command_template, EC_VER_MASK(0));

#ifdef CONFIG_CMD_FPSENSOR_DEBUG
/* --- Debug console commands --- */

/*
 * Send the current Fingerprint buffer to the host
 * it is formatted as an 8-bpp PGM ASCII file.
 *
 * In addition, it prepends a short Z-Modem download signature,
 * which triggers automatically your preferred viewer if you configure it
 * properly in "File transfer protocols" in the Minicom options menu.
 * (as triggered by Ctrl-A O)
 * +--------------------------------------------------------------------------+
 * |     Name             Program             Name U/D FullScr IO-Red. Multi  |
 * | A  zmodem     /usr/bin/sz -vv -b          Y    U    N       Y       Y    |
 *  [...]
 * | L  pgm        /usr/bin/display_pgm        N    D    N       Y       N    |
 * | M  Zmodem download string activates... L                                 |
 *
 * My /usr/bin/display_pgm looks like this:
 * #!/bin/sh
 * TMPF=$(mktemp)
 * ascii-xfr -rdv ${TMPF}
 * display ${TMPF}
 *
 * Alternative (if you're using screen as your terminal):
 *
 * From *outside* the chroot:
 *
 * Install ascii-xfr: sudo apt-get install minicom
 * Install imagemagick: sudo apt-get install imagemagick
 *
 * Add the following to your ${HOME}/.screenrc:
 *
 * zmodem catch
 * zmodem recvcmd '!!! bash -c "ascii-xfr -rdv /tmp/finger.pgm && display
 * /tmp/finger.pgm"'
 *
 * From *outside the chroot*, use screen to connect to UART console:
 *
 * sudo screen -c ${HOME}/.screenrc /dev/pts/NN 115200
 *
 */
static void upload_pgm_image(uint8_t *frame)
{
	int x, y;
	uint8_t *ptr = frame;

	/* fake Z-modem ZRQINIT signature */
	CPRINTF("#IGNORE for ZModem\r**\030B00");
	msleep(2000); /* let the download program start */
	/* Print 8-bpp PGM ASCII header */
	CPRINTF("P2\n%d %d\n255\n", FP_SENSOR_RES_X, FP_SENSOR_RES_Y);

	for (y = 0; y < FP_SENSOR_RES_Y; y++) {
		watchdog_reload();
		for (x = 0; x < FP_SENSOR_RES_X; x++, ptr++)
			CPRINTF("%d ", *ptr);
		CPRINTF("\n");
		cflush();
	}

	CPRINTF("\x04"); /* End Of Transmission */
}

static enum ec_error_list fp_console_action(uint32_t mode)
{
	int tries = 200;
	uint32_t mode_output = 0;
	int rc = 0;

	if (!(sensor_mode & FP_MODE_RESET_SENSOR))
		CPRINTS("Waiting for finger ...");

	rc = fp_set_sensor_mode(mode, &mode_output);

	if (rc != EC_RES_SUCCESS) {
		/*
		 * EC host command errors do not directly map to console command
		 * errors.
		 */
		return EC_ERROR_UNKNOWN;
	}

	while (tries--) {
		if (!(sensor_mode & FP_MODE_ANY_CAPTURE)) {
			CPRINTS("done (events:%x)", (int)fp_events);
			return EC_SUCCESS;
		}
		usleep(100 * MSEC);
	}
	return EC_ERROR_TIMEOUT;
}

static int command_fpcapture(int argc, const char **argv)
{
	int capture_type = FP_CAPTURE_SIMPLE_IMAGE;
	uint32_t mode;
	enum ec_error_list rc;

	/*
	 * TODO(b/142944002): Remove this redundant check for system_is_locked
	 * once we have unit-tests/integration-tests in place.
	 */
	if (system_is_locked())
		return EC_ERROR_ACCESS_DENIED;

	if (argc >= 2) {
		char *e;

		capture_type = strtoi(argv[1], &e, 0);
		if (*e || capture_type < 0)
			return EC_ERROR_PARAM1;
	}
	mode = FP_MODE_CAPTURE | ((capture_type << FP_MODE_CAPTURE_TYPE_SHIFT) &
				  FP_MODE_CAPTURE_TYPE_MASK);

	rc = fp_console_action(mode);
	if (rc == EC_SUCCESS)
		upload_pgm_image(fp_buffer + FP_SENSOR_IMAGE_OFFSET);

	return rc;
}
DECLARE_CONSOLE_COMMAND_FLAGS(fpcapture, command_fpcapture, NULL,
			      "Capture fingerprint in PGM format",
			      CMD_FLAG_RESTRICTED);

static int command_fpenroll(int argc, const char **argv)
{
	enum ec_error_list rc;
	int percent = 0;
	uint32_t event;
	static const char *const enroll_str[] = { "OK", "Low Quality",
						  "Immobile", "Low Coverage" };

	/*
	 * TODO(b/142944002): Remove this redundant check for system_is_locked
	 * once we have unit-tests/integration-tests in place.
	 */
	if (system_is_locked())
		return EC_ERROR_ACCESS_DENIED;

	do {
		int tries = 1000;

		rc = fp_console_action(FP_MODE_ENROLL_SESSION |
				       FP_MODE_ENROLL_IMAGE);
		if (rc != EC_SUCCESS)
			break;
		event = atomic_clear(&fp_events);
		percent = EC_MKBP_FP_ENROLL_PROGRESS(event);
		CPRINTS("Enroll capture: %s (%d%%)",
			enroll_str[EC_MKBP_FP_ERRCODE(event) & 3], percent);
		/* wait for finger release between captures */
		sensor_mode = FP_MODE_ENROLL_SESSION | FP_MODE_FINGER_UP;
		task_set_event(TASK_ID_FPSENSOR, TASK_EVENT_UPDATE_CONFIG);
		while (tries-- && sensor_mode & FP_MODE_FINGER_UP)
			usleep(20 * MSEC);
	} while (percent < 100);
	sensor_mode = 0; /* reset FP_MODE_ENROLL_SESSION */
	task_set_event(TASK_ID_FPSENSOR, TASK_EVENT_UPDATE_CONFIG);

	return rc;
}
DECLARE_CONSOLE_COMMAND_FLAGS(fpenroll, command_fpenroll, NULL,
			      "Enroll a new fingerprint", CMD_FLAG_RESTRICTED);

static int command_fpmatch(int argc, const char **argv)
{
	enum ec_error_list rc = fp_console_action(FP_MODE_MATCH);
	uint32_t event = atomic_clear(&fp_events);

	if (rc == EC_SUCCESS && event & EC_MKBP_FP_MATCH) {
		uint32_t match_errcode = EC_MKBP_FP_ERRCODE(event);

		CPRINTS("Match: %s (%d)",
			fp_match_success(match_errcode) ? "YES" : "NO",
			match_errcode);
	}

	return rc;
}
DECLARE_CONSOLE_COMMAND(fpmatch, command_fpmatch, NULL,
			"Run match algorithm against finger");

static int command_fpclear(int argc, const char **argv)
{
	/*
	 * We intentionally run this on the fp_task so that we use the
	 * same code path as host commands.
	 */
	enum ec_error_list rc = fp_console_action(FP_MODE_RESET_SENSOR);

	if (rc < 0)
		CPRINTS("Failed to clear fingerprint context: %d", rc);

	atomic_clear(&fp_events);

	return rc;
}
DECLARE_CONSOLE_COMMAND(fpclear, command_fpclear, NULL,
			"Clear fingerprint sensor context");

static int command_fpmaintenance(int argc, const char **argv)
{
#ifdef HAVE_FP_PRIVATE_DRIVER
	return fp_maintenance();
#else
	return EC_SUCCESS;
#endif /* #ifdef HAVE_FP_PRIVATE_DRIVER */
}
DECLARE_CONSOLE_COMMAND(fpmaintenance, command_fpmaintenance, NULL,
			"Run fingerprint sensor maintenance");

#endif /* CONFIG_CMD_FPSENSOR_DEBUG */


text:
<?php the_field("home-equipe-title") ?>

		<?php do_action('home_page_equipe') ?>

Ils ont parlé de nous

 		<?php do_action('home_page_medias') ?>

	<?php the_field('home-contact-form') ?>

	<a href="<?php the_field('home-mobile-discord') ?>">Discord