code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright (c) Facebook, Inc. and its affiliates. * * 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.buck.android; import com.facebook.buck.core.build.buildable.context.BuildableContext; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.build.execution.context.ExecutionContext; import com.facebook.buck.core.model.BuildTarget; import com.facebook.buck.core.model.impl.BuildTargetPaths; import com.facebook.buck.core.rulekey.AddToRuleKey; import com.facebook.buck.core.rules.BuildRule; import com.facebook.buck.core.rules.SourcePathRuleFinder; import com.facebook.buck.core.rules.common.BuildableSupport; import com.facebook.buck.core.rules.impl.AbstractBuildRule; import com.facebook.buck.core.sourcepath.ExplicitBuildTargetSourcePath; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.io.BuildCellRelativePath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.step.AbstractExecutionStep; import com.facebook.buck.step.Step; import com.facebook.buck.step.StepExecutionResult; import com.facebook.buck.step.StepExecutionResults; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import com.google.common.collect.Ordering; import java.io.IOException; import java.nio.file.Path; import java.util.SortedSet; import javax.annotation.Nullable; /** * Copy filtered string resources (values/strings.xml) files to output directory. These will be used * by i18n to map resource_id to fbt_hash with resource_name as the intermediary */ public class GenerateStringResources extends AbstractBuildRule { @AddToRuleKey private final ImmutableList<SourcePath> filteredResources; private final ImmutableList<FilteredResourcesProvider> filteredResourcesProviders; private final SourcePathRuleFinder ruleFinder; private static final String VALUES = "values"; private static final String STRINGS_XML = "strings.xml"; private static final String NEW_RES_DIR_FORMAT = "%04x"; // "4 digit hex" => 65536 files // we currently have around 1000 "values/strings.xml" files in fb4a protected GenerateStringResources( BuildTarget buildTarget, ProjectFilesystem projectFilesystem, SourcePathRuleFinder ruleFinder, ImmutableList<FilteredResourcesProvider> filteredResourcesProviders) { super(buildTarget, projectFilesystem); this.ruleFinder = ruleFinder; this.filteredResourcesProviders = filteredResourcesProviders; this.filteredResources = filteredResourcesProviders.stream() .flatMap(provider -> provider.getResDirectories().stream()) .collect(ImmutableList.toImmutableList()); } @Override public SortedSet<BuildRule> getBuildDeps() { return BuildableSupport.deriveDeps(this, ruleFinder) .collect(ImmutableSortedSet.toImmutableSortedSet(Ordering.natural())); } @Override public ImmutableList<? extends Step> getBuildSteps( BuildContext buildContext, BuildableContext buildableContext) { ImmutableList.Builder<Step> steps = ImmutableList.builder(); // Make sure we have a clean output directory Path outputDirPath = getPathForStringResourcesDirectory(); steps.addAll( MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( buildContext.getBuildCellRootPath(), getProjectFilesystem(), outputDirPath))); // Copy `values/strings.xml` files from resource directories to hex-enumerated resource // directories under output directory, retaining the input order steps.add( new AbstractExecutionStep("copy_string_resources") { @Override public StepExecutionResult execute(ExecutionContext context) throws IOException { ProjectFilesystem fileSystem = getProjectFilesystem(); int i = 0; for (Path resDir : filteredResourcesProviders.stream() .flatMap( provider -> provider .getRelativeResDirectories( fileSystem, buildContext.getSourcePathResolver()) .stream()) .collect(ImmutableList.toImmutableList())) { Path stringsFilePath = resDir.resolve(VALUES).resolve(STRINGS_XML); if (fileSystem.exists(stringsFilePath)) { // create <output_dir>/<new_res_dir>/values Path newStringsFileDir = outputDirPath.resolve(String.format(NEW_RES_DIR_FORMAT, i++)).resolve(VALUES); fileSystem.mkdirs(newStringsFileDir); // copy <res_dir>/values/strings.xml -> // <output_dir>/<new_res_dir>/values/strings.xml fileSystem.copyFile(stringsFilePath, newStringsFileDir.resolve(STRINGS_XML)); } } return StepExecutionResults.SUCCESS; } }); // Cache the outputDirPath with all the required string resources buildableContext.recordArtifact(outputDirPath); return steps.build(); } private Path getPathForStringResourcesDirectory() { return BuildTargetPaths.getScratchPath(getProjectFilesystem(), getBuildTarget(), "__%s__"); } @Nullable @Override public SourcePath getSourcePathToOutput() { return ExplicitBuildTargetSourcePath.of(getBuildTarget(), getPathForStringResourcesDirectory()); } }
facebook/buck
src/com/facebook/buck/android/GenerateStringResources.java
Java
apache-2.0
6,092
var exec = require('shelljs').exec; var isWin = /^win/.test(process.platform); var isPortOpen = function (port) { var cmd; if (isWin) cmd = 'netstat -an | find /i ":' + port + '" | find /i "listening"'; else cmd = 'lsof -i:' + port + " | tail -n 1 | awk '{print $2}'"; var portResponse = exec(cmd, { silent: true }).output; return portResponse ? false : true; } module.exports = function (startPort) { while (!isPortOpen(startPort)) { startPort += 1; } return startPort; }
goxhaj/gastronomee
src/main/webapp/bower_components/ui-leaflet/grunt/utils/getAvailPort.js
JavaScript
apache-2.0
545
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-5.js * @description Array.prototype.every - thisArg is object from object template */ function testcase() { var res = false; function callbackfn(val, idx, obj) { return this.res; } function foo(){} var f = new foo(); f.res = true; var arr = [1]; if(arr.every(callbackfn,f) === true) return true; } runTestCase(testcase);
hippich/typescript
tests/Fidelity/test262/suite/ch15/15.4/15.4.4/15.4.4.16/15.4.4.16-5-5.js
JavaScript
apache-2.0
814
package com.google.api.ads.adwords.jaxws.v201502.mcm; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Contains a list of AccountLabels. * * * <p>Java class for AccountLabelPage complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="AccountLabelPage"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="labels" type="{https://adwords.google.com/api/adwords/mcm/v201502}AccountLabel" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "AccountLabelPage", propOrder = { "labels" }) public class AccountLabelPage { protected List<AccountLabel> labels; /** * Gets the value of the labels property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the labels property. * * <p> * For example, to add a new item, do as follows: * <pre> * getLabels().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AccountLabel } * * */ public List<AccountLabel> getLabels() { if (labels == null) { labels = new ArrayList<AccountLabel>(); } return this.labels; } }
stoksey69/googleads-java-lib
modules/adwords_appengine/src/main/java/com/google/api/ads/adwords/jaxws/v201502/mcm/AccountLabelPage.java
Java
apache-2.0
1,900
import {createElementWithAttributes} from '#core/dom'; import {setStyles, toggle} from '#core/dom/style'; import {isObject} from '#core/types'; import {parseJson} from '#core/types/object/json'; import {Services} from '#service'; import {getData} from '#utils/event-helper'; import {addParamsToUrl, parseUrlDeprecated} from '../../../../src/url'; import {COOKIELESS_API_SERVER} from '../constants'; const RE_IFRAME = /#iframe$/; const pixelatorFrameTitle = 'Pxltr Frame'; /** * Returns a sorted array of objects like [{delay: 1000, pixels: [...]}] * @param {Array<{ * delay: number, * id: string, * url: string * }>} pixelList * @return {Array} */ const groupPixelsByTime = (pixelList) => { // Clean delay value; if it's empty/doesn't exist, default to [0] const cleanedPixels = pixelList.map((pixel) => { const {delay} = pixel; return { ...pixel, delay: Array.isArray(delay) && delay.length ? delay : [0], }; }); const delayMap = cleanedPixels .map((pixel) => { const delays = pixel.delay; return delays.map((delay) => ({ delay, pixels: [pixel], })); }) .reduce((a, b) => a.concat(b), []) // flatten .reduce((currentDelayMap, curDelay) => { const {delay, pixels} = curDelay; if (!currentDelayMap[delay]) { currentDelayMap[delay] = []; } currentDelayMap[delay] = currentDelayMap[delay].concat(pixels); return currentDelayMap; }, {}); return Object.keys(delayMap).map((delay) => ({ delay: Number(delay), pixels: delayMap[delay], })); }; export const pixelDrop = (url, ampDoc) => { const doc = ampDoc.win.document; const ampPixel = createElementWithAttributes(doc, 'amp-pixel', { 'layout': 'nodisplay', 'referrerpolicy': 'no-referrer', 'src': url, }); doc.body.appendChild(ampPixel); }; const getIframeName = (url) => parseUrlDeprecated(url) .host.split('.') .concat(pixelatorFrameTitle.toLowerCase().replace(/\s/, '_')); const iframeDrop = (url, ampDoc, data) => { const {name, title} = data; const doc = ampDoc.win.document; const iframe = createElementWithAttributes(doc, 'iframe', { 'frameborder': 0, 'width': 0, 'height': 0, 'name': name, 'title': title, 'src': url, }); toggle(iframe, false); setStyles(iframe, { position: 'absolute', clip: 'rect(0px 0px 0px 0px)', }); doc.body.appendChild(iframe); }; const dropPixelatorPixel = (url, ampDoc) => { const requiresIframe = RE_IFRAME.test(url); // if it's not an absolute URL, don't pixelate if (url.indexOf('//') === -1) { return; } if (requiresIframe) { const name = getIframeName(url); return iframeDrop(url, ampDoc, {name, title: pixelatorFrameTitle}); } return pixelDrop(url, ampDoc); }; /** * Requests groups of pixels at specified delays * @param {Array<{delay: number, id: string,url: string}>} pixels * @param {{sid: string, ampDoc: *}} options */ const dropPixelGroups = (pixels, options) => { const {ampDoc, sid} = options; const pixelGroups = groupPixelsByTime(pixels); pixelGroups.forEach((pixelGroup) => { const {delay, pixels} = pixelGroup; setTimeout(() => { const pids = pixels.map((pixel) => { dropPixelatorPixel(pixel.url, ampDoc); return pixel.id; }); const data = { 'delay': `${delay}`, 'ids': pids.join('-'), 'sid': sid, }; const url = addParamsToUrl(`${COOKIELESS_API_SERVER}/live/prender`, data); if (ampDoc.win.navigator.sendBeacon) { ampDoc.win.navigator.sendBeacon(url, '{}'); } else { pixelDrop(url, ampDoc); } }, delay * 1000); }); }; /** * Requests groups of pixels at specified delays * @param {(?JsonObject|string|undefined|null)} object * @return {!JsonObject} */ function getJsonObject_(object) { const params = {}; if (object === undefined || object === null) { return params; } const stringifiedObject = typeof object === 'string' ? object : JSON.stringify(object); try { const parsedObject = parseJson(stringifiedObject); if (isObject(parsedObject)) { for (const key in parsedObject) { params[key] = parsedObject[key]; } } } catch (error) {} return params; } export const callPixelEndpoint = (event) => { const {ampDoc, endpoint} = event; const eventData = getJsonObject_(getData(event)); const url = addParamsToUrl(endpoint, eventData); Services.xhrFor(ampDoc.win) .fetchJson(url, { mode: 'cors', method: 'GET', // This should be cacheable across publisher domains, so don't append // __amp_source_origin to the URL. ampCors: false, credentials: 'include', }) .then((res) => res.json()) .then( (json) => { const {pixels = []} = json; if (pixels.length > 0) { dropPixelGroups(pixels, { sid: eventData['sid'], ampDoc, }); } }, () => {} ); };
alanorozco/amphtml
extensions/amp-addthis/0.1/addthis-utils/pixel.js
JavaScript
apache-2.0
5,045
# # This is a project Makefile. It is assumed the directory this Makefile resides in is a # project subdirectory. # PROJECT_NAME := iperf EXTRA_COMPONENT_DIRS := $(IDF_PATH)/examples/system/console/components include $(IDF_PATH)/make/project.mk
mashaoze/esp-idf
examples/wifi/iperf/Makefile
Makefile
apache-2.0
248
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you 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. import warnings from selenium.webdriver.common import utils from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from .service import Service from .options import Options DEFAULT_TIMEOUT = 30 DEFAULT_PORT = 0 DEFAULT_HOST = None DEFAULT_LOG_LEVEL = None DEFAULT_LOG_FILE = None class WebDriver(RemoteWebDriver): """ Controls the IEServerDriver and allows you to drive Internet Explorer """ def __init__(self, executable_path='IEDriverServer.exe', capabilities=None, port=DEFAULT_PORT, timeout=DEFAULT_TIMEOUT, host=DEFAULT_HOST, log_level=DEFAULT_LOG_LEVEL, log_file=DEFAULT_LOG_FILE, options=None, ie_options=None): """ Creates a new instance of the chrome driver. Starts the service and then creates new instance of chrome driver. :Args: - executable_path - path to the executable. If the default is used it assumes the executable is in the $PATH - capabilities: capabilities Dictionary object - port - port you would like the service to run, if left as 0, a free port will be found. - log_level - log level you would like the service to run. - log_file - log file you would like the service to log to. - options: IE Options instance, providing additional IE options """ if ie_options: warnings.warn('use options instead of ie_options', DeprecationWarning) options = ie_options self.port = port if self.port == 0: self.port = utils.free_port() self.host = host self.log_level = log_level self.log_file = log_file if options is None: # desired_capabilities stays as passed in if capabilities is None: capabilities = self.create_options().to_capabilities() else: if capabilities is None: capabilities = options.to_capabilities() else: capabilities.update(options.to_capabilities()) self.iedriver = Service( executable_path, port=self.port, host=self.host, log_level=self.log_level, log_file=self.log_file) self.iedriver.start() if capabilities is None: capabilities = DesiredCapabilities.INTERNETEXPLORER RemoteWebDriver.__init__( self, command_executor='http://localhost:%d' % self.port, desired_capabilities=capabilities) self._is_remote = False def quit(self): RemoteWebDriver.quit(self) self.iedriver.stop() def create_options(self): return Options()
xmhubj/selenium
py/selenium/webdriver/ie/webdriver.py
Python
apache-2.0
3,588
/* * Copyright 2013-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.internal; import java.util.ArrayList; import java.util.Collection; /** * List with auto construct flag to indicate whether it is auto constructed by Java SDK. */ public class ListWithAutoConstructFlag<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; /** * Auto construct flag to indicate whether the list is auto constructed by Java SDK. */ private boolean autoConstruct; public ListWithAutoConstructFlag() { super(); } public ListWithAutoConstructFlag(Collection<? extends T> c) { super(c); } public ListWithAutoConstructFlag(int initialCapacity) { super(initialCapacity); } public void setAutoConstruct(boolean autoConstruct) { this.autoConstruct = autoConstruct; } /** * Return true if the list is auto constructed by Java SDK */ public boolean isAutoConstruct() { return autoConstruct; } }
trasa/aws-sdk-java
aws-java-sdk-core/src/main/java/com/amazonaws/internal/ListWithAutoConstructFlag.java
Java
apache-2.0
1,557
<?php /* Template Name: Contact Page */ $divertheme_page_layout_private = get_post_meta( get_the_ID(), "divertheme_page_layout_private", true ); if ( $divertheme_page_layout_private != 'default' ) { $layout = get_post_meta( get_the_ID(), "divertheme_page_layout_private", true ); } else { $layout = get_theme_mod( 'site_layout', site_layout ); } get_header(); ?> <?php if ( $layout == 'full-width' ) { ?> <div class="content-wrapper"> <main class="content" role="main"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?> itemscope="itemscope" itemtype="http://schema.org/CreativeWork"> <div id="map-canvas" data-address="<?php echo get_post_meta( get_the_ID(), "divertheme_contact_address", true ) ?>"></div> <?php if ( ! get_post_meta( get_the_ID(), "divertheme_disable_title", true ) ) { ?> <header class="entry-header align-center"> <div class="container"> <?php the_title( '<h1 class="entry-title heading-title-2" itemprop="headline">', '</h1>' ); ?> </div> </header> <?php } ?> <div class="entry-content" itemprop="text"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'divertheme' ), 'after' => '</div>', ) ); ?> </div> <!-- .entry-content --> </article><!-- #post-## --> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main> <!-- .content --> </div> <?php } else { ?> <div class="content-wrapper"> <div id="map-canvas" data-address="<?php echo get_post_meta( get_the_ID(), "divertheme_contact_address", true ) ?>"></div> <div class="container"> <div class="row"> <?php if ( $layout == 'sidebar-content' ) { ?> <?php get_sidebar(); ?> <?php } ?> <?php if ( $layout == 'sidebar-content' || $layout == 'content-sidebar' ) { ?> <?php $class = 'col-md-9'; ?> <?php } else { ?> <?php $class = 'col-md-12'; ?> <?php } ?> <div class="<?php echo esc_attr( $class ); ?>"> <main class="content" role="main" itemprop="mainContentOfPage"> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?> itemscope="itemscope" itemtype="http://schema.org/CreativeWork"> <?php if ( ! get_post_meta( get_the_ID(), "divertheme_disable_title", true ) ) { ?> <header class="entry-header align-center"> <div class="container"> <?php the_title( '<h1 class="entry-title heading-title-2" itemprop="headline">', '</h1>' ); ?> </div> </header> <?php } ?> <div class="entry-content" itemprop="text"> <?php the_content(); ?> <?php wp_link_pages( array( 'before' => '<div class="page-links">' . __( 'Pages:', 'divertheme' ), 'after' => '</div>', ) ); ?> </div> <!-- .entry-content --> </article><!-- #post-## --> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main> <!-- .content --> </div> <?php if ( $layout == 'content-sidebar' ) { ?> <?php get_sidebar(); ?> <?php } ?> </div> </div> </div> <?php } ?> <?php get_footer(); ?>
sipa-mict/localgov59
public_html/wp-content/themes/LocalTwo/template-contact.php
PHP
apache-2.0
3,711
// @generated // Generated by the protocol buffer compiler. DO NOT EDIT! // source: src/com/facebook/buck/remoteexecution/proto/metadata.proto package com.facebook.buck.remoteexecution.proto; /** * Protobuf type {@code facebook.remote_execution.DebugInfo} */ @javax.annotation.Generated(value="protoc", comments="annotations:DebugInfo.java.pb.meta") public final class DebugInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:facebook.remote_execution.DebugInfo) DebugInfoOrBuilder { private static final long serialVersionUID = 0L; // Use DebugInfo.newBuilder() to construct. private DebugInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private DebugInfo() { } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private DebugInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 8: { pauseBeforeCleanTimeout_ = input.readUInt32(); break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_DebugInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_DebugInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.DebugInfo.class, com.facebook.buck.remoteexecution.proto.DebugInfo.Builder.class); } public static final int PAUSE_BEFORE_CLEAN_TIMEOUT_FIELD_NUMBER = 1; private int pauseBeforeCleanTimeout_; /** * <code>uint32 pause_before_clean_timeout = 1;</code> */ public int getPauseBeforeCleanTimeout() { return pauseBeforeCleanTimeout_; } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (pauseBeforeCleanTimeout_ != 0) { output.writeUInt32(1, pauseBeforeCleanTimeout_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (pauseBeforeCleanTimeout_ != 0) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, pauseBeforeCleanTimeout_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.facebook.buck.remoteexecution.proto.DebugInfo)) { return super.equals(obj); } com.facebook.buck.remoteexecution.proto.DebugInfo other = (com.facebook.buck.remoteexecution.proto.DebugInfo) obj; if (getPauseBeforeCleanTimeout() != other.getPauseBeforeCleanTimeout()) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + PAUSE_BEFORE_CLEAN_TIMEOUT_FIELD_NUMBER; hash = (53 * hash) + getPauseBeforeCleanTimeout(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.facebook.buck.remoteexecution.proto.DebugInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.facebook.buck.remoteexecution.proto.DebugInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code facebook.remote_execution.DebugInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:facebook.remote_execution.DebugInfo) com.facebook.buck.remoteexecution.proto.DebugInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_DebugInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_DebugInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.facebook.buck.remoteexecution.proto.DebugInfo.class, com.facebook.buck.remoteexecution.proto.DebugInfo.Builder.class); } // Construct using com.facebook.buck.remoteexecution.proto.DebugInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); pauseBeforeCleanTimeout_ = 0; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.facebook.buck.remoteexecution.proto.RemoteExecutionMetadataProto.internal_static_facebook_remote_execution_DebugInfo_descriptor; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.DebugInfo getDefaultInstanceForType() { return com.facebook.buck.remoteexecution.proto.DebugInfo.getDefaultInstance(); } @java.lang.Override public com.facebook.buck.remoteexecution.proto.DebugInfo build() { com.facebook.buck.remoteexecution.proto.DebugInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.DebugInfo buildPartial() { com.facebook.buck.remoteexecution.proto.DebugInfo result = new com.facebook.buck.remoteexecution.proto.DebugInfo(this); result.pauseBeforeCleanTimeout_ = pauseBeforeCleanTimeout_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.facebook.buck.remoteexecution.proto.DebugInfo) { return mergeFrom((com.facebook.buck.remoteexecution.proto.DebugInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.facebook.buck.remoteexecution.proto.DebugInfo other) { if (other == com.facebook.buck.remoteexecution.proto.DebugInfo.getDefaultInstance()) return this; if (other.getPauseBeforeCleanTimeout() != 0) { setPauseBeforeCleanTimeout(other.getPauseBeforeCleanTimeout()); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.facebook.buck.remoteexecution.proto.DebugInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.facebook.buck.remoteexecution.proto.DebugInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int pauseBeforeCleanTimeout_ ; /** * <code>uint32 pause_before_clean_timeout = 1;</code> */ public int getPauseBeforeCleanTimeout() { return pauseBeforeCleanTimeout_; } /** * <code>uint32 pause_before_clean_timeout = 1;</code> */ public Builder setPauseBeforeCleanTimeout(int value) { pauseBeforeCleanTimeout_ = value; onChanged(); return this; } /** * <code>uint32 pause_before_clean_timeout = 1;</code> */ public Builder clearPauseBeforeCleanTimeout() { pauseBeforeCleanTimeout_ = 0; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:facebook.remote_execution.DebugInfo) } // @@protoc_insertion_point(class_scope:facebook.remote_execution.DebugInfo) private static final com.facebook.buck.remoteexecution.proto.DebugInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.facebook.buck.remoteexecution.proto.DebugInfo(); } public static com.facebook.buck.remoteexecution.proto.DebugInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<DebugInfo> PARSER = new com.google.protobuf.AbstractParser<DebugInfo>() { @java.lang.Override public DebugInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new DebugInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser<DebugInfo> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<DebugInfo> getParserForType() { return PARSER; } @java.lang.Override public com.facebook.buck.remoteexecution.proto.DebugInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
facebook/buck
src-gen/com/facebook/buck/remoteexecution/proto/DebugInfo.java
Java
apache-2.0
16,887
<!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <title>JQuery JSONView</title> <link rel="stylesheet" href="jquery.jsonview.css" /> <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script> <script type="text/javascript" src="jquery.jsonview.js"></script> <script type="text/javascript"> var json = { "hey": "guy", "anumber": 243, "anobject": { "whoa": "nuts", "anarray": [1, 2, "thr<h1>ee"], "more":"stuff" }, "awesome": true, "bogus": false, "meaning": null, "japanese":"明日がある。", "link": "http://jsonview.com", "notLink": "http://jsonview.com is great", "multiline": ['Much like me, you make your way forward,', 'Walking with downturned eyes.', 'Well, I too kept mine lowered.', 'Passer-by, stop here, please.'].join("\n") }; $(function() { $("#json").JSONView(json); $("#json-collapsed").JSONView(json, {collapsed: true, nl2br: true}); $('#collapse-btn').on('click', function() { $('#json').JSONView('collapse'); }); $('#expand-btn').on('click', function() { $('#json').JSONView('expand'); }); $('#toggle-btn').on('click', function() { $('#json').JSONView('toggle'); }); $('#toggle-level1-btn').on('click', function() { $('#json').JSONView('toggle', 1); }); $('#toggle-level2-btn').on('click', function() { $('#json').JSONView('toggle', 2); }); }); </script> </head> <body> <h2>Data</h2> <button id="collapse-btn">Collapse</button> <button id="expand-btn">Expand</button> <button id="toggle-btn">Toggle</button> <button id="toggle-level1-btn">Toggle level1</button> <button id="toggle-level2-btn">Toggle level2</button> <div id="json"></div> <h2>Data Collapsed</h2> <div id="json-collapsed"></div> </body> </html>
joshkh/joshkh.github.io
node_modules/jsonview/src/index.html
HTML
apache-2.0
1,950
# Migrating to Kite This guide details the changes necessary to migrate existing projects to Kite. ## From CDK-0.9.0 As of version 0.10.0, CDK has been renamed to Kite. The main goal of Kite is to increase the accessibility of Apache Hadoop as a platform. This isn't specific to Cloudera, so we updated the name to correctly represent the project as an open, community-driven set of tools. Version 0.10.0 is purely a rename. There are **no feature changes**, so after migration from 0.9.0 to 0.10.0, datasets and morphlines will produce exactly the same results. Migration to is done primarily by updating project dependencies and imports, with some additional configuration changes. ### Dependencies Kite artifacts are now prefixed with `kite-` instead of `cdk-`, and the group id is now `org.kitesdk` instead of `com.cloudera.cdk`. All references must be updated. For projects using maven, running these commands in a project's root folder will find and update POM entries: ``` # Update group ids from com.cloudera.cdk to org.kitesdk find . -name pom.xml -exec sed -i '' -e 's/com\.cloudera\.cdk/org.kitesdk/g' '{}' \; # Update artifact names from cdk-* to kite-* find . -name pom.xml -exec sed -i '' 's/cdk-/kite-/g' '{}' \; ``` In addition, the version in POM files must be updated to `0.10.0`. This command will find the potential references: ``` find . -name pom.xml -exec grep 0.9.0 '{}' \; ``` Other build configurations should be updated similarly. The **required changes** are: * `com.cloudera.cdk` group id changes to `org.kitesdk` * `cdk-...` artifact names change to `kite-...` * `0.9.0` artifact versions change to `0.10.0` ### Imports Next, references to CDK / Kite packages must be updated. Only the package names have changed, so only import statements and similar package references must be changed. This command finds and updates import statements, avro schema namespaces, and log4j configurations: ``` find . \( -name *.avsc -o -name *.avdl -o -name *.java -o -name log4j.properties \) \ -exec sed -i '' -e 's/com\.cloudera\.cdk/org.kitesdk/g' '{}' \; ``` Other references to CDK should be updated also. For example, using a different slf4j binding would require updating the logging configuration for Kite / CDK classes in that logger's configuration instead of `log4j.properties`. **Required changes**: * `com.cloudera.cdk...` package names change to `org.kitesdk...` ### Dataset configuration changes Some internal dataset properties have been changed from using the prefix `cdk.` to `kite.`. Most updates are backwards-compatible, except for partitioned datasets that are written by flume. Flume agent configurations must be updated when migrating to the `kite-data-flume` `Log4jAppender`. This command updates `flume.properties` files. Flume agent configurations must also be updated, and the agents restarted. ``` # Update Flume configuration files - note that Flume agents will need to be updated too find . -name flume.properties -exec sed -i '' 's/cdk\.partition/kite.partition/g' '{}' \; ``` This command renames the partition properties that are set by the `Log4jAppender`. The two components, clients logging events with the appender and flume agents, must use the same property naming scheme and should be updated and restarted at the same time. ### Morphlines configuration changes Morphlines configuration files must be updated to import morphlines commands from `org.kitesdk`. The following command finds and updates `.conf` files: ``` # Update Morphlines config file imports from com.cloudera.cdk to org.kitesdk find . -name *.conf -exec sed -i '' 's/com\.cloudera\.cdk/org.kitesdk/g' '{}' \; find . -name *.conf -exec sed -i '' 's/com\.cloudera\.\*\*/org.kitesdk.**/g' '{}' \; ``` The above change fixes startup errors that look like like this: ``` org.kitesdk.morphline.api.MorphlineCompilationException: No command builder registered for name: readLine near: { # target/test-classes/test-morphlines/readLine.conf: 22 "readLine" : { # target/test-classes/test-morphlines/readLine.conf: 24 "commentPrefix" : "#", # target/test-classes/test-morphlines/readLine.conf: 23 "ignoreFirstLine" : true, # target/test-classes/test-morphlines/readLine.conf: 25 "charset" : "UTF-8" } } at org.kitesdk.morphline.base.AbstractCommand.buildCommand(AbstractCommand.java:271) at org.kitesdk.morphline.base.AbstractCommand.buildCommandChain(AbstractCommand.java:242) at org.kitesdk.morphline.stdlib.Pipe.<init>(Pipe.java:45) at org.kitesdk.morphline.stdlib.PipeBuilder.build(PipeBuilder.java:39) ``` ### Morphlines command implmentation changes Morphline users that maintain custom Java morphline commands need to change these commands to implement Java interface `org.kitesdk.morphline.api.Command` instead of `com.cloudera.cdk.morphline.api.Command` or subclass `org.kitesdk.morphline.base.AbstractCommand` instead of `com.cloudera.cdk.morphline.base.AbstractCommand`.
dlanza1/kite
src/site/markdown/migrating.md
Markdown
apache-2.0
4,992
/* * Copyright 2000-2011 JetBrains s.r.o. * * 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.intellij.util.ui; /** * @author Konstantin Bulenkov * @since 11.0 */ public interface EditableModel { void addRow(); void removeRow(int index); void exchangeRows(int oldIndex, int newIndex); boolean canExchangeRows(int oldIndex, int newIndex); }
android-ia/platform_tools_idea
platform/util/src/com/intellij/util/ui/EditableModel.java
Java
apache-2.0
874
<div class="container-fluid form-horizontal"> <div class="form-group"> <div class="col-md-12"> <table class="table table-condensed packed"> <thead> <tr> <th>Name</th> <th>Certificate</th> <th>CA Cert</th> <th>Private Key</th> <th>Passphrase</th> </tr> </thead> <tbody> <tr ng-repeat="cert in ctrl.certificates"> <td ng-if="!cert.isNew">{{cert.certificateName}}</td> <td ng-if="cert.isNew"> <input class="form-control input-sm" ng-model="cert.certificateName" required ng-focus="prevCertNames[$index] = cert.name" ng-blur="ctrl.certNameChanged($index)" /> </td> <td> <textarea ng-if="cert.isNew" ng-model="cert.publicCertificate" required class="form-control input-sm" ></textarea> </td> <td> <textarea ng-if="cert.isNew" ng-model="cert.caCertificate" class="form-control input-sm"></textarea> </td> <td> <textarea ng-if="cert.isNew" ng-model="cert.privateKey" required class="form-control input-sm"></textarea> </td> <td> <textarea ng-if="cert.isNew" ng-model="cert.passphrase" class="form-control input-sm"></textarea> </td> <td> <a href class="sm-label" ng-if="ctrl.isCertRemovable($index)" ng-click="ctrl.removeCert($index)" ><span class="glyphicon glyphicon-trash"></span> </a> </td> </tr> </tbody> <tfoot> <tr> <td colspan="5"> <button class="add-new col-md-12" ng-click="ctrl.addCert()"> <span class="glyphicon glyphicon-plus-sign"></span> Add Certificate </button> </td> </tr> </tfoot> </table> </div> </div> </div>
spinnaker/deck
packages/oracle/src/loadBalancer/configure/certificates.html
HTML
apache-2.0
2,141
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.34014 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace PdfiumViewer.Demo.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
pvginkel/PdfiumViewer
PdfiumViewer.Demo/Properties/Settings.Designer.cs
C#
apache-2.0
1,100
/* * © Copyright IBM Corp. 2010 * * 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.ibm.xsp.extlib.renderkit.dojo.layout; import java.io.IOException; import java.util.Map; import javax.faces.context.FacesContext; import com.ibm.xsp.dojo.FacesDojoComponent; import com.ibm.xsp.extlib.component.dojo.layout.UIDojoBorderContainer; import com.ibm.xsp.extlib.renderkit.dojo.DojoRendererUtil; import com.ibm.xsp.extlib.resources.ExtLibResources; import com.ibm.xsp.resource.DojoModuleResource; public class DojoBorderContainerRenderer extends DojoLayoutRenderer { @Override protected String getDefaultDojoType(FacesContext context, FacesDojoComponent component) { return "dijit.layout.BorderContainer"; // $NON-NLS-1$ } @Override protected DojoModuleResource getDefaultDojoModule(FacesContext context, FacesDojoComponent component) { return ExtLibResources.dijitLayoutBorderContainer; } @Override protected void initDojoAttributes(FacesContext context, FacesDojoComponent dojoComponent, Map<String,String> attrs) throws IOException { super.initDojoAttributes(context, dojoComponent, attrs); if(dojoComponent instanceof UIDojoBorderContainer) { UIDojoBorderContainer c = (UIDojoBorderContainer)dojoComponent; DojoRendererUtil.addDojoHtmlAttributes(attrs,"design",c.getDesign()); // $NON-NLS-1$ DojoRendererUtil.addDojoHtmlAttributes(attrs,"gutters",c.isGutters(), true); // $NON-NLS-1$ DojoRendererUtil.addDojoHtmlAttributes(attrs,"liveSplitters",c.isLiveSplitters(), true); // $NON-NLS-1$ DojoRendererUtil.addDojoHtmlAttributes(attrs,"persist",c.isPersist()); // $NON-NLS-1$ } } }
iharkhukhrakou/XPagesExtensionLibrary
extlib/lwp/product/runtime/eclipse/plugins/com.ibm.xsp.extlib.controls/src/com/ibm/xsp/extlib/renderkit/dojo/layout/DojoBorderContainerRenderer.java
Java
apache-2.0
2,262
/* * Copyright 2000-2015 JetBrains s.r.o. * * 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.intellij.openapi.fileTypes.impl; import com.intellij.openapi.fileTypes.ExactFileNameMatcher; import com.intellij.openapi.fileTypes.ExtensionFileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcher; import com.intellij.openapi.fileTypes.FileNameMatcherEx; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.io.FileUtilRt; import com.intellij.util.ArrayUtil; import com.intellij.util.text.CharSequenceHashingStrategy; import gnu.trove.THashMap; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; /** * @author max */ public class FileTypeAssocTable<T> { private final Map<CharSequence, T> myExtensionMappings; private final Map<CharSequence, T> myExactFileNameMappings; private final Map<CharSequence, T> myExactFileNameAnyCaseMappings; private boolean myHasAnyCaseExactMappings; private final List<Pair<FileNameMatcher, T>> myMatchingMappings; private FileTypeAssocTable(Map<CharSequence, T> extensionMappings, Map<CharSequence, T> exactFileNameMappings, Map<CharSequence, T> exactFileNameAnyCaseMappings, List<Pair<FileNameMatcher, T>> matchingMappings) { myExtensionMappings = new THashMap<CharSequence, T>(extensionMappings, CharSequenceHashingStrategy.CASE_INSENSITIVE); myExactFileNameMappings = new THashMap<CharSequence, T>(exactFileNameMappings, CharSequenceHashingStrategy.CASE_SENSITIVE); myExactFileNameAnyCaseMappings = new THashMap<CharSequence, T>(exactFileNameAnyCaseMappings, CharSequenceHashingStrategy.CASE_INSENSITIVE) { @Override public T remove(Object key) { T removed = super.remove(key); myHasAnyCaseExactMappings = size() > 0; return removed; } @Override public T put(CharSequence key, T value) { T result = super.put(key, value); myHasAnyCaseExactMappings = true; return result; } }; myMatchingMappings = new ArrayList<Pair<FileNameMatcher, T>>(matchingMappings); } public FileTypeAssocTable() { this(Collections.<CharSequence, T>emptyMap(), Collections.<CharSequence, T>emptyMap(), Collections.<CharSequence, T>emptyMap(), Collections.<Pair<FileNameMatcher, T>>emptyList()); } public boolean isAssociatedWith(T type, FileNameMatcher matcher) { if (matcher instanceof ExtensionFileNameMatcher || matcher instanceof ExactFileNameMatcher) { return findAssociatedFileType(matcher) == type; } for (Pair<FileNameMatcher, T> mapping : myMatchingMappings) { if (matcher.equals(mapping.getFirst()) && type == mapping.getSecond()) return true; } return false; } public void addAssociation(FileNameMatcher matcher, T type) { if (matcher instanceof ExtensionFileNameMatcher) { myExtensionMappings.put(((ExtensionFileNameMatcher)matcher).getExtension(), type); } else if (matcher instanceof ExactFileNameMatcher) { final ExactFileNameMatcher exactFileNameMatcher = (ExactFileNameMatcher)matcher; if (exactFileNameMatcher.isIgnoreCase()) { myExactFileNameAnyCaseMappings.put(exactFileNameMatcher.getFileName(), type); } else { myExactFileNameMappings.put(exactFileNameMatcher.getFileName(), type); } } else { myMatchingMappings.add(Pair.create(matcher, type)); } } public boolean removeAssociation(FileNameMatcher matcher, T type) { if (matcher instanceof ExtensionFileNameMatcher) { String extension = ((ExtensionFileNameMatcher)matcher).getExtension(); if (myExtensionMappings.get(extension) == type) { myExtensionMappings.remove(extension); return true; } return false; } if (matcher instanceof ExactFileNameMatcher) { final ExactFileNameMatcher exactFileNameMatcher = (ExactFileNameMatcher)matcher; final Map<CharSequence, T> mapToUse; String fileName = exactFileNameMatcher.getFileName(); if (exactFileNameMatcher.isIgnoreCase()) { mapToUse = myExactFileNameAnyCaseMappings; } else { mapToUse = myExactFileNameMappings; } if(mapToUse.get(fileName) == type) { mapToUse.remove(fileName); return true; } return false; } List<Pair<FileNameMatcher, T>> copy = new ArrayList<Pair<FileNameMatcher, T>>(myMatchingMappings); for (Pair<FileNameMatcher, T> assoc : copy) { if (matcher.equals(assoc.getFirst())) { myMatchingMappings.remove(assoc); return true; } } return false; } public boolean removeAllAssociations(T type) { boolean changed = removeAssociationsFromMap(myExtensionMappings, type, false); changed = removeAssociationsFromMap(myExactFileNameAnyCaseMappings, type, changed); changed = removeAssociationsFromMap(myExactFileNameMappings, type, changed); List<Pair<FileNameMatcher, T>> copy = new ArrayList<Pair<FileNameMatcher, T>>(myMatchingMappings); for (Pair<FileNameMatcher, T> assoc : copy) { if (assoc.getSecond() == type) { myMatchingMappings.remove(assoc); changed = true; } } return changed; } private boolean removeAssociationsFromMap(Map<CharSequence, T> extensionMappings, T type, boolean changed) { Set<CharSequence> exts = extensionMappings.keySet(); CharSequence[] extsStrings = exts.toArray(new CharSequence[exts.size()]); for (CharSequence s : extsStrings) { if (extensionMappings.get(s) == type) { extensionMappings.remove(s); changed = true; } } return changed; } @Nullable public T findAssociatedFileType(@NotNull @NonNls CharSequence fileName) { T t = myExactFileNameMappings.get(fileName); if (t != null) return t; if (myHasAnyCaseExactMappings) { // even hash lookup with case insensitive hasher is costly for isIgnored checks during compile t = myExactFileNameAnyCaseMappings.get(fileName); if (t != null) return t; } //noinspection ForLoopReplaceableByForEach for (int i = 0, n = myMatchingMappings.size(); i < n; i++) { final Pair<FileNameMatcher, T> mapping = myMatchingMappings.get(i); if (FileNameMatcherEx.acceptsCharSequence(mapping.getFirst(), fileName)) return mapping.getSecond(); } return myExtensionMappings.get(FileUtilRt.getExtension(fileName)); } @Nullable public T findAssociatedFileType(final FileNameMatcher matcher) { if (matcher instanceof ExtensionFileNameMatcher) { return myExtensionMappings.get(((ExtensionFileNameMatcher)matcher).getExtension()); } if (matcher instanceof ExactFileNameMatcher) { final ExactFileNameMatcher exactFileNameMatcher = (ExactFileNameMatcher)matcher; if (exactFileNameMatcher.isIgnoreCase()) { return myExactFileNameAnyCaseMappings.get(exactFileNameMatcher.getFileName()); } else { return myExactFileNameMappings.get(exactFileNameMatcher.getFileName()); } } for (Pair<FileNameMatcher, T> mapping : myMatchingMappings) { if (matcher.equals(mapping.getFirst())) return mapping.getSecond(); } return null; } @Deprecated @NotNull public String[] getAssociatedExtensions(T type) { Map<CharSequence, T> extMap = myExtensionMappings; List<String> exts = new ArrayList<String>(); for (CharSequence ext : extMap.keySet()) { if (extMap.get(ext) == type) { exts.add(ext.toString()); } } return ArrayUtil.toStringArray(exts); } @NotNull public FileTypeAssocTable<T> copy() { return new FileTypeAssocTable<T>(myExtensionMappings, myExactFileNameMappings, myExactFileNameAnyCaseMappings, myMatchingMappings); } @NotNull public List<FileNameMatcher> getAssociations(@NotNull T type) { List<FileNameMatcher> result = new ArrayList<FileNameMatcher>(); for (Pair<FileNameMatcher, T> mapping : myMatchingMappings) { if (mapping.getSecond() == type) { result.add(mapping.getFirst()); } } for (Map.Entry<CharSequence, T> entries : myExactFileNameMappings.entrySet()) { if (entries.getValue() == type) { result.add(new ExactFileNameMatcher(entries.getKey().toString())); } } for (Map.Entry<CharSequence, T> entries : myExactFileNameAnyCaseMappings.entrySet()) { if (entries.getValue() == type) { result.add(new ExactFileNameMatcher(entries.getKey().toString(), true)); } } for (Map.Entry<CharSequence, T> entries : myExtensionMappings.entrySet()) { if (entries.getValue() == type) { result.add(new ExtensionFileNameMatcher(entries.getKey().toString())); } } return result; } public boolean hasAssociationsFor(@NotNull T fileType) { if (myExtensionMappings.values().contains(fileType) || myExactFileNameMappings.values().contains(fileType) || myExactFileNameAnyCaseMappings.values().contains(fileType)) { return true; } for (Pair<FileNameMatcher, T> mapping : myMatchingMappings) { if (mapping.getSecond() == fileType) { return true; } } return false; } public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } FileTypeAssocTable<?> that = (FileTypeAssocTable)o; return myExtensionMappings.equals(that.myExtensionMappings) && myMatchingMappings.equals(that.myMatchingMappings) && myExactFileNameMappings.equals(that.myExactFileNameMappings) && myExactFileNameAnyCaseMappings.equals(that.myExactFileNameAnyCaseMappings); } public int hashCode() { int result; result = myExtensionMappings.hashCode(); result = 31 * result + myMatchingMappings.hashCode(); result = 31 * result + myExactFileNameMappings.hashCode(); result = 31 * result + myExactFileNameAnyCaseMappings.hashCode(); return result; } }
diorcety/intellij-community
jps/model-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeAssocTable.java
Java
apache-2.0
10,578
/* * Copyright 2004-2009 the original author or authors. * * 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 org.compass.core.test.analyzer; import org.compass.core.CompassHits; import org.compass.core.CompassSession; import org.compass.core.CompassTransaction; import org.compass.core.config.CompassEnvironment; import org.compass.core.config.CompassSettings; import org.compass.core.engine.SearchEngineException; /** * @author kimchy */ public class OsemNoUnmarshallAnalyzerTests extends AbstractAnalyzerTests { protected String[] getMappings() { return new String[]{"analyzer/osem.cpm.xml"}; } @Override protected void addSettings(CompassSettings settings) { super.addSettings(settings); settings.setBooleanSetting(CompassEnvironment.Osem.SUPPORT_UNMARSHALL, false); } public void testClassNoAnalyzer() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); session.save("a1", a); CompassHits hits = session.find("a1.value:the"); assertEquals(0, hits.getLength()); // test for the all property as well hits = session.find("the"); assertEquals(0, hits.getLength()); tr.commit(); } public void testClassAnalyzerSetForResource() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); session.save("a2", a); CompassHits hits = session.find("a2.value:the"); assertEquals(1, hits.getLength()); // test for the all property as well hits = session.find("the"); assertEquals(1, hits.getLength()); tr.commit(); } public void testClassAnalyzerSetForProperty() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); a.setValue2(TEXT); session.save("a3", a); CompassHits hits = session.find("a3.value:the"); assertEquals(1, hits.getLength()); hits = session.find("a3.value2:the"); assertEquals(0, hits.getLength()); // test for the all property as well hits = session.find("the"); assertEquals(1, hits.getLength()); tr.commit(); } public void testClassAnalyzerSetForResourceAndProperty() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); a.setValue2(TEXT); session.save("a4", a); CompassHits hits = session.find("a4.value:the"); assertEquals(0, hits.getLength()); hits = session.find("a4.value2:the"); assertEquals(1, hits.getLength()); tr.commit(); } public void testClassAnalyzerController() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); a.setValue2(TEXT); a.setAnalyzer("simple"); session.save("a6", a); CompassHits hits = session.find("value:the"); assertEquals(1, hits.getLength()); a = new A(); a.setId((long) 2); a.setValue(TEXT); a.setValue2(TEXT); a.setAnalyzer(null); try { session.save("a6", a); tr.commit(); fail(); } catch (SearchEngineException e) { tr.rollback(); } session.close(); } public void testClassAnalyzerControllerWithNullAnalyzer() { CompassSession session = openSession(); CompassTransaction tr = session.beginTransaction(); Long id = (long) 1; A a = new A(); a.setId(id); a.setValue(TEXT); a.setValue2(TEXT); a.setAnalyzer("simple"); session.save("a7", a); CompassHits hits = session.find("value:the"); assertEquals(1, hits.getLength()); a = new A(); a.setId((long) 2); a.setValue(TEXT); a.setValue2(TEXT); a.setAnalyzer(null); session.save("a7", a); hits = session.find("value:the"); assertEquals(2, hits.getLength()); tr.commit(); } }
baboune/compass
src/main/test/org/compass/core/test/analyzer/OsemNoUnmarshallAnalyzerTests.java
Java
apache-2.0
5,146
package com.fincatto.nfe310.classes; public enum NFTipoEmissao { EMISSAO_NORMAL("1", "Normal"), CONTINGENCIA_FS_IA("2", "Conting\u00eancia FS"), CONTINGENCIA_SCAN("3", "Conting\u00eancia SCAN"), CONTINGENCIA_DPEC("4", "Conting\u00eancia DPEC"), CONTINGENCIA_FSDA("5", "Conting\u00eancia FSDA"), CONTINGENCIA_SVCAN("6", "Conting\u00eancia SVCAN"), CONTINGENCIA_SVCRS("7", "Conting\u00eancia SVCRS"), CONTIGENCIA_OFFLINE("9", "Contig\u00eancia offline NFC-e"); private final String codigo; private final String descricao; NFTipoEmissao(final String codigo, final String descricao) { this.codigo = codigo; this.descricao = descricao; } public String getCodigo() { return this.codigo; } public String getDescricao() { return this.descricao; } public static NFTipoEmissao valueOfCodigo(final String codigo) { for (final NFTipoEmissao tipo : NFTipoEmissao.values()) { if (tipo.getCodigo().equals(codigo)) { return tipo; } } return null; } @Override public String toString() { return codigo + " - " + descricao; } }
danieldhp/nfe
src/main/java/com/fincatto/nfe310/classes/NFTipoEmissao.java
Java
apache-2.0
1,204
' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Imports Microsoft.CodeAnalysis.CodeRefactorings Imports Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.CodeRefactorings Imports Microsoft.CodeAnalysis.VisualBasic.SplitOrMergeIfStatements Namespace Microsoft.CodeAnalysis.Editor.VisualBasic.UnitTests.SplitOrMergeIfStatements <Trait(Traits.Feature, Traits.Features.CodeActionsSplitIntoNestedIfStatements)> Public NotInheritable Class SplitIntoNestedIfStatementsTests Inherits AbstractVisualBasicCodeActionTest Protected Overrides Function CreateCodeRefactoringProvider(workspace As Workspace, parameters As TestParameters) As CodeRefactoringProvider Return New VisualBasicSplitIntoNestedIfStatementsCodeRefactoringProvider() End Function <Theory> <InlineData("a [||]andalso b")> <InlineData("a an[||]dalso b")> <InlineData("a andalso[||] b")> <InlineData("a [|andalso|] b")> Public Async Function SplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then end if end if end sub end class") End Function <Theory> <InlineData("a [|and|]also b")> <InlineData("a[| andalso|] b")> <InlineData("a[||] andalso b")> Public Async Function NotSplitOnAndAlsoOperatorSpans(condition As String) As Task Await TestMissingInRegularAndScriptAsync( $"class C sub M(a as boolean, b as boolean) if {condition} then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnIfKeyword() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) [||]if a andalso b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnOrElseOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]orelse b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnBitwiseAndOperator() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]and b then end if end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorOutsideIfStatement() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) dim v = a [||]andalso b end sub end class") End Function <Fact> Public Async Function NotSplitOnAndAlsoOperatorInIfStatementBody() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a andalso b then a [||]andalso b end if end sub end class") End Function <Fact> Public Async Function NotSplitOnSingleLineIf() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso b andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if b andalso c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b [||]andalso c andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b then if c andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithChainedAndAlsoExpression3() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso c then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a [||]andalso b) andalso c andalso d then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso b andalso (c [||]andalso d) then end if end sub end class") End Function <Fact> Public Async Function NotSplitInsideParentheses3() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if (a andalso b [||]andalso c andalso d) then end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a [||]andalso (b andalso c) andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a then if (b andalso c) andalso d then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithOtherExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) [||]andalso d then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean, d as boolean) if a andalso (b andalso c) then if d then end if end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression1() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b orelse c then end if end sub end class") End Function <Fact> Public Async Function NotSplitWithMixedOrElseExpression2() As Task Await TestMissingInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a orelse b [||]andalso c then end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso (b orelse c) then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if (b orelse c) then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedOrElseExpressionInsideParentheses2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if (a orelse b) then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression1() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a [||]andalso b = c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a then if b = c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithMixedEqualsExpression2() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean, c as boolean) if a = b [||]andalso c then end if end sub end class", "class C sub M(a as boolean, b as boolean, c as boolean) if a = b then if c then end if end if end sub end class") End Function <Fact> Public Async Function SplitWithStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine(a andalso b) end if end if end sub end class") End Function <Fact> Public Async Function SplitWithNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then if true end if end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else System.Console.WriteLine(a andalso b) end if else System.Console.WriteLine(a andalso b) end if end sub end class") End Function <Fact> Public Async Function SplitWithElseNestedIfStatement() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() else if true end if end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() else if true end if end if else if true end if end if end sub end class") End Function <Fact> Public Async Function SplitWithElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if a [||]andalso b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if a then if b then System.Console.WriteLine() elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if elseif a then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElse() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) else System.Console.WriteLine(b) end if else System.Console.WriteLine(b) end if end sub end class") End Function <Fact> Public Async Function SplitAsPartOfElseIfElseIf() As Task Await TestInRegularAndScriptAsync( "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a [||]andalso b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if end sub end class", "class C sub M(a as boolean, b as boolean) if true then System.Console.WriteLine() elseif a then if b then System.Console.WriteLine(a) elseif a orelse b System.Console.WriteLine(b) end if elseif a orelse b System.Console.WriteLine(b) end if end sub end class") End Function End Class End Namespace
VSadov/roslyn
src/EditorFeatures/VisualBasicTest/SplitOrMergeIfStatements/SplitIntoNestedIfStatementsTests.vb
Visual Basic
apache-2.0
14,561
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.psi.impl; import com.intellij.lang.ASTFactory; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.TokenType; import com.jetbrains.python.PythonDialectsTokenSetProvider; import com.jetbrains.python.psi.PyElementGenerator; import com.jetbrains.python.psi.PyElementVisitor; import com.jetbrains.python.psi.PyStatement; import com.jetbrains.python.psi.PyStatementList; import org.jetbrains.annotations.NotNull; /** * @author yole */ public class PyStatementListImpl extends PyElementImpl implements PyStatementList { public PyStatementListImpl(ASTNode astNode) { super(astNode); } @Override protected void acceptPyVisitor(PyElementVisitor pyVisitor) { pyVisitor.visitPyStatementList(this); } @Override public PyStatement[] getStatements() { return childrenToPsi(PythonDialectsTokenSetProvider.INSTANCE.getStatementTokens(), PyStatement.EMPTY_ARRAY); } @Override public ASTNode addInternal(ASTNode first, ASTNode last, ASTNode anchor, Boolean before) { if (first.getPsi() instanceof PyStatement && getStatements().length == 1) { ASTNode treePrev = getNode().getTreePrev(); if (treePrev != null && treePrev.getElementType() == TokenType.WHITE_SPACE && !treePrev.textContains('\n')) { ASTNode lineBreak = ASTFactory.whitespace("\n"); treePrev.getTreeParent().replaceChild(treePrev, lineBreak); } } return super.addInternal(first, last, anchor, before); } @Override public void deleteChildInternal(@NotNull ASTNode child) { final PsiElement childElement = child.getPsi(); if (childElement instanceof PyStatement && getStatements().length == 1) { childElement.replace(PyElementGenerator.getInstance(getProject()).createPassStatement()); return; } super.deleteChildInternal(child); } }
paplorinc/intellij-community
python/src/com/jetbrains/python/psi/impl/PyStatementListImpl.java
Java
apache-2.0
2,011
/** * FreeRDP: A Remote Desktop Protocol Implementation * Graphical Objects * * Copyright 2011 Marc-Andre Moreau <[email protected]> * * 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. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <winpr/crt.h> #include <freerdp/graphics.h> /* Bitmap Class */ rdpBitmap* Bitmap_Alloc(rdpContext* context) { rdpBitmap* bitmap; rdpGraphics* graphics; graphics = context->graphics; bitmap = (rdpBitmap*) malloc(graphics->Bitmap_Prototype->size); if (bitmap != NULL) { memcpy(bitmap, context->graphics->Bitmap_Prototype, sizeof(rdpBitmap)); bitmap->data = NULL; } return bitmap; } void Bitmap_New(rdpContext* context, rdpBitmap* bitmap) { } void Bitmap_Free(rdpContext* context, rdpBitmap* bitmap) { if (bitmap != NULL) { bitmap->Free(context, bitmap); if (bitmap->data != NULL) free(bitmap->data); free(bitmap); } } void Bitmap_SetRectangle(rdpContext* context, rdpBitmap* bitmap, UINT16 left, UINT16 top, UINT16 right, UINT16 bottom) { bitmap->left = left; bitmap->top = top; bitmap->right = right; bitmap->bottom = bottom; } void Bitmap_SetDimensions(rdpContext* context, rdpBitmap* bitmap, UINT16 width, UINT16 height) { bitmap->width = width; bitmap->height = height; } /* static method */ void Bitmap_SetSurface(rdpContext* context, rdpBitmap* bitmap, BOOL primary) { context->graphics->Bitmap_Prototype->SetSurface(context, bitmap, primary); } void graphics_register_bitmap(rdpGraphics* graphics, rdpBitmap* bitmap) { memcpy(graphics->Bitmap_Prototype, bitmap, sizeof(rdpBitmap)); } /* Pointer Class */ rdpPointer* Pointer_Alloc(rdpContext* context) { rdpPointer* pointer; rdpGraphics* graphics; graphics = context->graphics; pointer = (rdpPointer*) malloc(graphics->Pointer_Prototype->size); if (pointer != NULL) { memcpy(pointer, context->graphics->Pointer_Prototype, sizeof(rdpPointer)); } return pointer; } void Pointer_New(rdpContext* context, rdpPointer* pointer) { } void Pointer_Free(rdpContext* context, rdpPointer* pointer) { if (pointer != NULL) { pointer->Free(context, pointer); if (pointer->xorMaskData) { free(pointer->xorMaskData); pointer->xorMaskData = NULL; } if (pointer->andMaskData) { free(pointer->andMaskData); pointer->andMaskData = NULL; } free(pointer); } } /* static method */ void Pointer_Set(rdpContext* context, rdpPointer* pointer) { context->graphics->Pointer_Prototype->Set(context, pointer); } void Pointer_SetNull(rdpContext* context) { context->graphics->Pointer_Prototype->SetNull(context); } void Pointer_SetDefault(rdpContext* context) { context->graphics->Pointer_Prototype->SetDefault(context); } void graphics_register_pointer(rdpGraphics* graphics, rdpPointer* pointer) { memcpy(graphics->Pointer_Prototype, pointer, sizeof(rdpPointer)); } /* Glyph Class */ rdpGlyph* Glyph_Alloc(rdpContext* context) { rdpGlyph* glyph; rdpGraphics* graphics; graphics = context->graphics; glyph = (rdpGlyph*) malloc(graphics->Glyph_Prototype->size); if (glyph != NULL) { memcpy(glyph, context->graphics->Glyph_Prototype, sizeof(rdpGlyph)); } return glyph; } void Glyph_New(rdpContext* context, rdpGlyph* glyph) { context->graphics->Glyph_Prototype->New(context, glyph); } void Glyph_Free(rdpContext* context, rdpGlyph* glyph) { context->graphics->Glyph_Prototype->Free(context, glyph); } void Glyph_Draw(rdpContext* context, rdpGlyph* glyph, int x, int y) { context->graphics->Glyph_Prototype->Draw(context, glyph, x, y); } void Glyph_BeginDraw(rdpContext* context, int x, int y, int width, int height, UINT32 bgcolor, UINT32 fgcolor) { context->graphics->Glyph_Prototype->BeginDraw(context, x, y, width, height, bgcolor, fgcolor); } void Glyph_EndDraw(rdpContext* context, int x, int y, int width, int height, UINT32 bgcolor, UINT32 fgcolor) { context->graphics->Glyph_Prototype->EndDraw(context, x, y, width, height, bgcolor, fgcolor); } void graphics_register_glyph(rdpGraphics* graphics, rdpGlyph* glyph) { memcpy(graphics->Glyph_Prototype, glyph, sizeof(rdpGlyph)); } /* Graphics Module */ rdpGraphics* graphics_new(rdpContext* context) { rdpGraphics* graphics; graphics = (rdpGraphics*) malloc(sizeof(rdpGraphics)); if (graphics != NULL) { ZeroMemory(graphics, sizeof(rdpGraphics)); graphics->context = context; graphics->Bitmap_Prototype = (rdpBitmap*) malloc(sizeof(rdpBitmap)); ZeroMemory(graphics->Bitmap_Prototype, sizeof(rdpBitmap)); graphics->Bitmap_Prototype->size = sizeof(rdpBitmap); graphics->Bitmap_Prototype->New = Bitmap_New; graphics->Bitmap_Prototype->Free = Bitmap_Free; graphics->Pointer_Prototype = (rdpPointer*) malloc(sizeof(rdpPointer)); ZeroMemory(graphics->Pointer_Prototype, sizeof(rdpPointer)); graphics->Pointer_Prototype->size = sizeof(rdpPointer); graphics->Pointer_Prototype->New = Pointer_New; graphics->Pointer_Prototype->Free = Pointer_Free; graphics->Glyph_Prototype = (rdpGlyph*) malloc(sizeof(rdpGlyph)); ZeroMemory(graphics->Glyph_Prototype, sizeof(rdpGlyph)); graphics->Glyph_Prototype->size = sizeof(rdpGlyph); graphics->Glyph_Prototype->New = Glyph_New; graphics->Glyph_Prototype->Free = Glyph_Free; } return graphics; } void graphics_free(rdpGraphics* graphics) { if (graphics != NULL) { free(graphics->Bitmap_Prototype); free(graphics->Pointer_Prototype); free(graphics->Glyph_Prototype); free(graphics); } }
VeeamSoftware/FreeRDP
libfreerdp/core/graphics.c
C
apache-2.0
5,953
[![Build Status](https://api.travis-ci.com/norcams/himlar.svg)](https://travis-ci.com/norcams/himlar) himlar ====== himlar m. plural indefinite of himmel
TorLdre/himlar
README.md
Markdown
apache-2.0
157
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>FreeType-2.4.4 API Reference</title> <style type="text/css"> body { font-family: Verdana, Geneva, Arial, Helvetica, serif; color: #000000; background: #FFFFFF; } p { text-align: justify; } h1 { text-align: center; } li { text-align: justify; } td { padding: 0 0.5em 0 0.5em; } td.left { padding: 0 0.5em 0 0.5em; text-align: left; } a:link { color: #0000EF; } a:visited { color: #51188E; } a:hover { color: #FF0000; } span.keyword { font-family: monospace; text-align: left; white-space: pre; color: darkblue; } pre.colored { color: blue; } ul.empty { list-style-type: none; } </style> </head> <body> <table align=center><tr><td><font size=-1>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-1>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <center><h1>FreeType-2.4.4 API Reference</h1></center> <center><h1> TrueType Tables </h1></center> <h2>Synopsis</h2> <table align=center cellspacing=5 cellpadding=0 border=0> <tr><td></td><td><a href="#TT_PLATFORM_XXX">TT_PLATFORM_XXX</a></td><td></td><td><a href="#TT_Postscript">TT_Postscript</a></td></tr> <tr><td></td><td><a href="#TT_APPLE_ID_XXX">TT_APPLE_ID_XXX</a></td><td></td><td><a href="#TT_PCLT">TT_PCLT</a></td></tr> <tr><td></td><td><a href="#TT_MAC_ID_XXX">TT_MAC_ID_XXX</a></td><td></td><td><a href="#TT_MaxProfile">TT_MaxProfile</a></td></tr> <tr><td></td><td><a href="#TT_ISO_ID_XXX">TT_ISO_ID_XXX</a></td><td></td><td><a href="#FT_Sfnt_Tag">FT_Sfnt_Tag</a></td></tr> <tr><td></td><td><a href="#TT_MS_ID_XXX">TT_MS_ID_XXX</a></td><td></td><td><a href="#FT_Get_Sfnt_Table">FT_Get_Sfnt_Table</a></td></tr> <tr><td></td><td><a href="#TT_ADOBE_ID_XXX">TT_ADOBE_ID_XXX</a></td><td></td><td><a href="#FT_Load_Sfnt_Table">FT_Load_Sfnt_Table</a></td></tr> <tr><td></td><td><a href="#TT_Header">TT_Header</a></td><td></td><td><a href="#FT_Sfnt_Table_Info">FT_Sfnt_Table_Info</a></td></tr> <tr><td></td><td><a href="#TT_HoriHeader">TT_HoriHeader</a></td><td></td><td><a href="#FT_Get_CMap_Language_ID">FT_Get_CMap_Language_ID</a></td></tr> <tr><td></td><td><a href="#TT_VertHeader">TT_VertHeader</a></td><td></td><td><a href="#FT_Get_CMap_Format">FT_Get_CMap_Format</a></td></tr> <tr><td></td><td><a href="#TT_OS2">TT_OS2</a></td><td></td><td><a href="#FT_PARAM_TAG_UNPATENTED_HINTING">FT_PARAM_TAG_UNPATENTED_HINTING</a></td></tr> </table><br><br> <table align=center width="87%"><tr><td> <p>This section contains the definition of TrueType-specific tables as well as some routines used to access and process them.</p> </td></tr></table><br> <table align=center width="75%"><tr><td> <h4><a name="TT_PLATFORM_XXX">TT_PLATFORM_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_APPLE_UNICODE</a> 0 #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_MACINTOSH</a> 1 #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_ISO</a> 2 /* deprecated */ #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_MICROSOFT</a> 3 #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_CUSTOM</a> 4 #define <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_ADOBE</a> 7 /* artificial */ </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;platform_id&rsquo; identifier code in <a href="ft2-base_interface.html#FT_CharMapRec">FT_CharMapRec</a> and <a href="ft2-sfnt_names.html#FT_SfntName">FT_SfntName</a> structures.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td colspan=0><b>TT_PLATFORM_APPLE_UNICODE</b></td></tr> <tr valign=top><td></td><td> <p>Used by Apple to indicate a Unicode character map and/or name entry. See <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_XXX</a> for corresponding &lsquo;encoding_id&rsquo; values. Note that name entries in this format are coded as big-endian UCS-2 character codes <i>only</i>.</p> </td></tr> <tr valign=top><td><b>TT_PLATFORM_MACINTOSH</b></td><td> <p>Used by Apple to indicate a MacOS-specific charmap and/or name entry. See <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_XXX</a> for corresponding &lsquo;encoding_id&rsquo; values. Note that most TrueType fonts contain an Apple roman charmap to be usable on MacOS systems (even if they contain a Microsoft charmap as well).</p> </td></tr> <tr valign=top><td><b>TT_PLATFORM_ISO</b></td><td> <p>This value was used to specify ISO/IEC 10646 charmaps. It is however now deprecated. See <a href="ft2-truetype_tables.html#TT_ISO_ID_XXX">TT_ISO_ID_XXX</a> for a list of corresponding &lsquo;encoding_id&rsquo; values.</p> </td></tr> <tr valign=top><td><b>TT_PLATFORM_MICROSOFT</b></td><td> <p>Used by Microsoft to indicate Windows-specific charmaps. See <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_XXX</a> for a list of corresponding &lsquo;encoding_id&rsquo; values. Note that most fonts contain a Unicode charmap using (TT_PLATFORM_MICROSOFT, <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_UNICODE_CS</a>).</p> </td></tr> <tr valign=top><td><b>TT_PLATFORM_CUSTOM</b></td><td> <p>Used to indicate application-specific charmaps.</p> </td></tr> <tr valign=top><td><b>TT_PLATFORM_ADOBE</b></td><td> <p>This value isn't part of any font format specification, but is used by FreeType to report Adobe-specific charmaps in an <a href="ft2-base_interface.html#FT_CharMapRec">FT_CharMapRec</a> structure. See <a href="ft2-truetype_tables.html#TT_ADOBE_ID_XXX">TT_ADOBE_ID_XXX</a>.</p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_APPLE_ID_XXX">TT_APPLE_ID_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_DEFAULT</a> 0 /* Unicode 1.0 */ #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_UNICODE_1_1</a> 1 /* specify Hangul at U+34xx */ #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_ISO_10646</a> 2 /* deprecated */ #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_UNICODE_2_0</a> 3 /* or later */ #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_UNICODE_32</a> 4 /* 2.0 or later, full repertoire */ #define <a href="ft2-truetype_tables.html#TT_APPLE_ID_XXX">TT_APPLE_ID_VARIANT_SELECTOR</a> 5 /* variation selector data */ </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;encoding_id&rsquo; for <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_APPLE_UNICODE</a> charmaps and name entries.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>TT_APPLE_ID_DEFAULT</b></td><td> <p>Unicode version 1.0.</p> </td></tr> <tr valign=top><td colspan=0><b>TT_APPLE_ID_UNICODE_1_1</b></td></tr> <tr valign=top><td></td><td> <p>Unicode 1.1; specifies Hangul characters starting at U+34xx.</p> </td></tr> <tr valign=top><td><b>TT_APPLE_ID_ISO_10646</b></td><td> <p>Deprecated (identical to preceding).</p> </td></tr> <tr valign=top><td colspan=0><b>TT_APPLE_ID_UNICODE_2_0</b></td></tr> <tr valign=top><td></td><td> <p>Unicode 2.0 and beyond (UTF-16 BMP only).</p> </td></tr> <tr valign=top><td><b>TT_APPLE_ID_UNICODE_32</b></td><td> <p>Unicode 3.1 and beyond, using UTF-32.</p> </td></tr> <tr valign=top><td colspan=0><b>TT_APPLE_ID_VARIANT_SELECTOR</b></td></tr> <tr valign=top><td></td><td> <p>From Adobe, not Apple. Not a normal cmap. Specifies variations on a real cmap.</p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_MAC_ID_XXX">TT_MAC_ID_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_ROMAN</a> 0 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_JAPANESE</a> 1 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_TRADITIONAL_CHINESE</a> 2 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_KOREAN</a> 3 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_ARABIC</a> 4 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_HEBREW</a> 5 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_GREEK</a> 6 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_RUSSIAN</a> 7 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_RSYMBOL</a> 8 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_DEVANAGARI</a> 9 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_GURMUKHI</a> 10 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_GUJARATI</a> 11 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_ORIYA</a> 12 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_BENGALI</a> 13 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_TAMIL</a> 14 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_TELUGU</a> 15 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_KANNADA</a> 16 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_MALAYALAM</a> 17 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_SINHALESE</a> 18 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_BURMESE</a> 19 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_KHMER</a> 20 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_THAI</a> 21 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_LAOTIAN</a> 22 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_GEORGIAN</a> 23 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_ARMENIAN</a> 24 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_MALDIVIAN</a> 25 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_SIMPLIFIED_CHINESE</a> 25 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_TIBETAN</a> 26 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_MONGOLIAN</a> 27 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_GEEZ</a> 28 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_SLAVIC</a> 29 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_VIETNAMESE</a> 30 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_SINDHI</a> 31 #define <a href="ft2-truetype_tables.html#TT_MAC_ID_XXX">TT_MAC_ID_UNINTERP</a> 32 </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;encoding_id&rsquo; for <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_MACINTOSH</a> charmaps and name entries.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>TT_MAC_ID_ROMAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_JAPANESE</b></td><td> <p></p> </td></tr> <tr valign=top><td colspan=0><b>TT_MAC_ID_TRADITIONAL_CHINESE</b></td></tr> <tr valign=top><td></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_KOREAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_ARABIC</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_HEBREW</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_GREEK</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_RUSSIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_RSYMBOL</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_DEVANAGARI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_GURMUKHI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_GUJARATI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_ORIYA</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_BENGALI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_TAMIL</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_TELUGU</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_KANNADA</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_MALAYALAM</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_SINHALESE</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_BURMESE</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_KHMER</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_THAI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_LAOTIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_GEORGIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_ARMENIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_MALDIVIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td colspan=0><b>TT_MAC_ID_SIMPLIFIED_CHINESE</b></td></tr> <tr valign=top><td></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_TIBETAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_MONGOLIAN</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_GEEZ</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_SLAVIC</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_VIETNAMESE</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_SINDHI</b></td><td> <p></p> </td></tr> <tr valign=top><td><b>TT_MAC_ID_UNINTERP</b></td><td> <p></p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_ISO_ID_XXX">TT_ISO_ID_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_ISO_ID_XXX">TT_ISO_ID_7BIT_ASCII</a> 0 #define <a href="ft2-truetype_tables.html#TT_ISO_ID_XXX">TT_ISO_ID_10646</a> 1 #define <a href="ft2-truetype_tables.html#TT_ISO_ID_XXX">TT_ISO_ID_8859_1</a> 2 </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;encoding_id&rsquo; for <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_ISO</a> charmaps and name entries.</p> <p>Their use is now deprecated.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>TT_ISO_ID_7BIT_ASCII</b></td><td> <p>ASCII.</p> </td></tr> <tr valign=top><td><b>TT_ISO_ID_10646</b></td><td> <p>ISO/10646.</p> </td></tr> <tr valign=top><td><b>TT_ISO_ID_8859_1</b></td><td> <p>Also known as Latin-1.</p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_MS_ID_XXX">TT_MS_ID_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_SYMBOL_CS</a> 0 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_UNICODE_CS</a> 1 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_SJIS</a> 2 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_GB2312</a> 3 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_BIG_5</a> 4 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_WANSUNG</a> 5 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_JOHAB</a> 6 #define <a href="ft2-truetype_tables.html#TT_MS_ID_XXX">TT_MS_ID_UCS_4</a> 10 </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;encoding_id&rsquo; for <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_MICROSOFT</a> charmaps and name entries.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>TT_MS_ID_SYMBOL_CS</b></td><td> <p>Corresponds to Microsoft symbol encoding. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_MS_SYMBOL</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_UNICODE_CS</b></td><td> <p>Corresponds to a Microsoft WGL4 charmap, matching Unicode. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_UNICODE</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_SJIS</b></td><td> <p>Corresponds to SJIS Japanese encoding. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_SJIS</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_GB2312</b></td><td> <p>Corresponds to Simplified Chinese as used in Mainland China. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_GB2312</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_BIG_5</b></td><td> <p>Corresponds to Traditional Chinese as used in Taiwan and Hong Kong. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_BIG5</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_WANSUNG</b></td><td> <p>Corresponds to Korean Wansung encoding. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_WANSUNG</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_JOHAB</b></td><td> <p>Corresponds to Johab encoding. See <a href="ft2-base_interface.html#FT_Encoding">FT_ENCODING_JOHAB</a>.</p> </td></tr> <tr valign=top><td><b>TT_MS_ID_UCS_4</b></td><td> <p>Corresponds to UCS-4 or UTF-32 charmaps. This has been added to the OpenType specification version 1.4 (mid-2001.)</p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_ADOBE_ID_XXX">TT_ADOBE_ID_XXX</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_IDS_H (freetype/ttnameid.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <a href="ft2-truetype_tables.html#TT_ADOBE_ID_XXX">TT_ADOBE_ID_STANDARD</a> 0 #define <a href="ft2-truetype_tables.html#TT_ADOBE_ID_XXX">TT_ADOBE_ID_EXPERT</a> 1 #define <a href="ft2-truetype_tables.html#TT_ADOBE_ID_XXX">TT_ADOBE_ID_CUSTOM</a> 2 #define <a href="ft2-truetype_tables.html#TT_ADOBE_ID_XXX">TT_ADOBE_ID_LATIN_1</a> 3 </pre></table><br> <table align=center width="87%"><tr><td> <p>A list of valid values for the &lsquo;encoding_id&rsquo; for <a href="ft2-truetype_tables.html#TT_PLATFORM_XXX">TT_PLATFORM_ADOBE</a> charmaps. This is a FreeType-specific extension!</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>values</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>TT_ADOBE_ID_STANDARD</b></td><td> <p>Adobe standard encoding.</p> </td></tr> <tr valign=top><td><b>TT_ADOBE_ID_EXPERT</b></td><td> <p>Adobe expert encoding.</p> </td></tr> <tr valign=top><td><b>TT_ADOBE_ID_CUSTOM</b></td><td> <p>Adobe custom encoding.</p> </td></tr> <tr valign=top><td><b>TT_ADOBE_ID_LATIN_1</b></td><td> <p>Adobe Latin&nbsp;1 encoding.</p> </td></tr> </table> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_Header">TT_Header</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_Header_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> Table_Version; <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> Font_Revision; <a href="ft2-basic_types.html#FT_Long">FT_Long</a> CheckSum_Adjust; <a href="ft2-basic_types.html#FT_Long">FT_Long</a> Magic_Number; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Flags; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Units_Per_EM; <a href="ft2-basic_types.html#FT_Long">FT_Long</a> Created [2]; <a href="ft2-basic_types.html#FT_Long">FT_Long</a> Modified[2]; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> xMin; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> yMin; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> xMax; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> yMax; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Mac_Style; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Lowest_Rec_PPEM; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Font_Direction; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Index_To_Loc_Format; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Glyph_Data_Format; } <b>TT_Header</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType font header table. All fields follow the TrueType specification.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_HoriHeader">TT_HoriHeader</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_HoriHeader_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> Version; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Ascender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Descender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Line_Gap; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> advance_Width_Max; /* advance width maximum */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> min_Left_Side_Bearing; /* minimum left-sb */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> min_Right_Side_Bearing; /* minimum right-sb */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> xMax_Extent; /* xmax extents */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Slope_Rise; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Slope_Run; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Offset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Reserved[4]; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> metric_Data_Format; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> number_Of_HMetrics; /* The following fields are not defined by the TrueType specification */ /* but they are used to connect the metrics header to the relevant */ /* `HMTX' table. */ <span class="keyword">void</span>* long_metrics; <span class="keyword">void</span>* short_metrics; } <b>TT_HoriHeader</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType horizontal header, the &lsquo;hhea&rsquo; table, as well as the corresponding horizontal metrics table, i.e., the &lsquo;hmtx&rsquo; table.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>fields</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>Version</b></td><td> <p>The table version.</p> </td></tr> <tr valign=top><td><b>Ascender</b></td><td> <p>The font's ascender, i.e., the distance from the baseline to the top-most of all glyph points found in the font.</p> <p>This value is invalid in many fonts, as it is usually set by the font designer, and often reflects only a portion of the glyphs found in the font (maybe ASCII).</p> <p>You should use the &lsquo;sTypoAscender&rsquo; field of the OS/2 table instead if you want the correct one.</p> </td></tr> <tr valign=top><td><b>Descender</b></td><td> <p>The font's descender, i.e., the distance from the baseline to the bottom-most of all glyph points found in the font. It is negative.</p> <p>This value is invalid in many fonts, as it is usually set by the font designer, and often reflects only a portion of the glyphs found in the font (maybe ASCII).</p> <p>You should use the &lsquo;sTypoDescender&rsquo; field of the OS/2 table instead if you want the correct one.</p> </td></tr> <tr valign=top><td><b>Line_Gap</b></td><td> <p>The font's line gap, i.e., the distance to add to the ascender and descender to get the BTB, i.e., the baseline-to-baseline distance for the font.</p> </td></tr> <tr valign=top><td><b>advance_Width_Max</b></td><td> <p>This field is the maximum of all advance widths found in the font. It can be used to compute the maximum width of an arbitrary string of text.</p> </td></tr> <tr valign=top><td><b>min_Left_Side_Bearing</b></td><td> <p>The minimum left side bearing of all glyphs within the font.</p> </td></tr> <tr valign=top><td><b>min_Right_Side_Bearing</b></td><td> <p>The minimum right side bearing of all glyphs within the font.</p> </td></tr> <tr valign=top><td><b>xMax_Extent</b></td><td> <p>The maximum horizontal extent (i.e., the &lsquo;width&rsquo; of a glyph's bounding box) for all glyphs in the font.</p> </td></tr> <tr valign=top><td><b>caret_Slope_Rise</b></td><td> <p>The rise coefficient of the cursor's slope of the cursor (slope=rise/run).</p> </td></tr> <tr valign=top><td><b>caret_Slope_Run</b></td><td> <p>The run coefficient of the cursor's slope.</p> </td></tr> <tr valign=top><td><b>Reserved</b></td><td> <p>8&nbsp;reserved bytes.</p> </td></tr> <tr valign=top><td><b>metric_Data_Format</b></td><td> <p>Always&nbsp;0.</p> </td></tr> <tr valign=top><td><b>number_Of_HMetrics</b></td><td> <p>Number of HMetrics entries in the &lsquo;hmtx&rsquo; table -- this value can be smaller than the total number of glyphs in the font.</p> </td></tr> <tr valign=top><td><b>long_metrics</b></td><td> <p>A pointer into the &lsquo;hmtx&rsquo; table.</p> </td></tr> <tr valign=top><td><b>short_metrics</b></td><td> <p>A pointer into the &lsquo;hmtx&rsquo; table.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should be identical except for the names of their fields which are different.</p> <p>This ensures that a single function in the &lsquo;ttload&rsquo; module is able to read both the horizontal and vertical headers.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_VertHeader">TT_VertHeader</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_VertHeader_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> Version; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Ascender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Descender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Line_Gap; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> advance_Height_Max; /* advance height maximum */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> min_Top_Side_Bearing; /* minimum left-sb or top-sb */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> min_Bottom_Side_Bearing; /* minimum right-sb or bottom-sb */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> yMax_Extent; /* xmax or ymax extents */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Slope_Rise; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Slope_Run; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> caret_Offset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> Reserved[4]; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> metric_Data_Format; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> number_Of_VMetrics; /* The following fields are not defined by the TrueType specification */ /* but they're used to connect the metrics header to the relevant */ /* `HMTX' or `VMTX' table. */ <span class="keyword">void</span>* long_metrics; <span class="keyword">void</span>* short_metrics; } <b>TT_VertHeader</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType vertical header, the &lsquo;vhea&rsquo; table, as well as the corresponding vertical metrics table, i.e., the &lsquo;vmtx&rsquo; table.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>fields</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>Version</b></td><td> <p>The table version.</p> </td></tr> <tr valign=top><td><b>Ascender</b></td><td> <p>The font's ascender, i.e., the distance from the baseline to the top-most of all glyph points found in the font.</p> <p>This value is invalid in many fonts, as it is usually set by the font designer, and often reflects only a portion of the glyphs found in the font (maybe ASCII).</p> <p>You should use the &lsquo;sTypoAscender&rsquo; field of the OS/2 table instead if you want the correct one.</p> </td></tr> <tr valign=top><td><b>Descender</b></td><td> <p>The font's descender, i.e., the distance from the baseline to the bottom-most of all glyph points found in the font. It is negative.</p> <p>This value is invalid in many fonts, as it is usually set by the font designer, and often reflects only a portion of the glyphs found in the font (maybe ASCII).</p> <p>You should use the &lsquo;sTypoDescender&rsquo; field of the OS/2 table instead if you want the correct one.</p> </td></tr> <tr valign=top><td><b>Line_Gap</b></td><td> <p>The font's line gap, i.e., the distance to add to the ascender and descender to get the BTB, i.e., the baseline-to-baseline distance for the font.</p> </td></tr> <tr valign=top><td><b>advance_Height_Max</b></td><td> <p>This field is the maximum of all advance heights found in the font. It can be used to compute the maximum height of an arbitrary string of text.</p> </td></tr> <tr valign=top><td><b>min_Top_Side_Bearing</b></td><td> <p>The minimum top side bearing of all glyphs within the font.</p> </td></tr> <tr valign=top><td colspan=0><b>min_Bottom_Side_Bearing</b></td></tr> <tr valign=top><td></td><td> <p>The minimum bottom side bearing of all glyphs within the font.</p> </td></tr> <tr valign=top><td><b>yMax_Extent</b></td><td> <p>The maximum vertical extent (i.e., the &lsquo;height&rsquo; of a glyph's bounding box) for all glyphs in the font.</p> </td></tr> <tr valign=top><td><b>caret_Slope_Rise</b></td><td> <p>The rise coefficient of the cursor's slope of the cursor (slope=rise/run).</p> </td></tr> <tr valign=top><td><b>caret_Slope_Run</b></td><td> <p>The run coefficient of the cursor's slope.</p> </td></tr> <tr valign=top><td><b>caret_Offset</b></td><td> <p>The cursor's offset for slanted fonts. This value is &lsquo;reserved&rsquo; in vmtx version 1.0.</p> </td></tr> <tr valign=top><td><b>Reserved</b></td><td> <p>8&nbsp;reserved bytes.</p> </td></tr> <tr valign=top><td><b>metric_Data_Format</b></td><td> <p>Always&nbsp;0.</p> </td></tr> <tr valign=top><td><b>number_Of_HMetrics</b></td><td> <p>Number of VMetrics entries in the &lsquo;vmtx&rsquo; table -- this value can be smaller than the total number of glyphs in the font.</p> </td></tr> <tr valign=top><td><b>long_metrics</b></td><td> <p>A pointer into the &lsquo;vmtx&rsquo; table.</p> </td></tr> <tr valign=top><td><b>short_metrics</b></td><td> <p>A pointer into the &lsquo;vmtx&rsquo; table.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>IMPORTANT: The TT_HoriHeader and TT_VertHeader structures should be identical except for the names of their fields which are different.</p> <p>This ensures that a single function in the &lsquo;ttload&rsquo; module is able to read both the horizontal and vertical headers.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_OS2">TT_OS2</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_OS2_ { <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> version; /* 0x0001 - more or 0xFFFF */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> xAvgCharWidth; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usWeightClass; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usWidthClass; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> fsType; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySubscriptXSize; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySubscriptYSize; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySubscriptXOffset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySubscriptYOffset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySuperscriptXSize; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySuperscriptYSize; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySuperscriptXOffset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> ySuperscriptYOffset; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> yStrikeoutSize; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> yStrikeoutPosition; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sFamilyClass; <a href="ft2-basic_types.html#FT_Byte">FT_Byte</a> panose[10]; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulUnicodeRange1; /* Bits 0-31 */ <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulUnicodeRange2; /* Bits 32-63 */ <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulUnicodeRange3; /* Bits 64-95 */ <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulUnicodeRange4; /* Bits 96-127 */ <a href="ft2-basic_types.html#FT_Char">FT_Char</a> achVendID[4]; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> fsSelection; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usFirstCharIndex; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usLastCharIndex; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sTypoAscender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sTypoDescender; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sTypoLineGap; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usWinAscent; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usWinDescent; /* only version 1 tables: */ <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulCodePageRange1; /* Bits 0-31 */ <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ulCodePageRange2; /* Bits 32-63 */ /* only version 2 tables: */ <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sxHeight; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> sCapHeight; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usDefaultChar; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usBreakChar; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> usMaxContext; } <b>TT_OS2</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType OS/2 table. This is the long table version. All fields comply to the TrueType specification.</p> <p>Note that we now support old Mac fonts which do not include an OS/2 table. In this case, the &lsquo;version&rsquo; field is always set to 0xFFFF.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_Postscript">TT_Postscript</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_Postscript_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> FormatType; <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> italicAngle; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> underlinePosition; <a href="ft2-basic_types.html#FT_Short">FT_Short</a> underlineThickness; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> isFixedPitch; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> minMemType42; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> maxMemType42; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> minMemType1; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> maxMemType1; /* Glyph names follow in the file, but we don't */ /* load them by default. See the ttpost.c file. */ } <b>TT_Postscript</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType PostScript table. All fields comply to the TrueType specification. This structure does not reference the PostScript glyph names, which can be nevertheless accessed with the &lsquo;ttpost&rsquo; module.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_PCLT">TT_PCLT</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_PCLT_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> Version; <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> FontNumber; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Pitch; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> xHeight; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> Style; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> TypeFamily; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> CapHeight; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> SymbolSet; <a href="ft2-basic_types.html#FT_Char">FT_Char</a> TypeFace[16]; <a href="ft2-basic_types.html#FT_Char">FT_Char</a> CharacterComplement[8]; <a href="ft2-basic_types.html#FT_Char">FT_Char</a> FileName[6]; <a href="ft2-basic_types.html#FT_Char">FT_Char</a> StrokeWeight; <a href="ft2-basic_types.html#FT_Char">FT_Char</a> WidthType; <a href="ft2-basic_types.html#FT_Byte">FT_Byte</a> SerifStyle; <a href="ft2-basic_types.html#FT_Byte">FT_Byte</a> Reserved; } <b>TT_PCLT</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>A structure used to model a TrueType PCLT table. All fields comply to the TrueType specification.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="TT_MaxProfile">TT_MaxProfile</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">struct</span> TT_MaxProfile_ { <a href="ft2-basic_types.html#FT_Fixed">FT_Fixed</a> version; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> numGlyphs; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxPoints; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxContours; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxCompositePoints; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxCompositeContours; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxZones; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxTwilightPoints; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxStorage; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxFunctionDefs; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxInstructionDefs; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxStackElements; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxSizeOfInstructions; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxComponentElements; <a href="ft2-basic_types.html#FT_UShort">FT_UShort</a> maxComponentDepth; } <b>TT_MaxProfile</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>The maximum profile is a table containing many max values which can be used to pre-allocate arrays. This ensures that no memory allocation occurs during a glyph load.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>fields</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>version</b></td><td> <p>The version number.</p> </td></tr> <tr valign=top><td><b>numGlyphs</b></td><td> <p>The number of glyphs in this TrueType font.</p> </td></tr> <tr valign=top><td><b>maxPoints</b></td><td> <p>The maximum number of points in a non-composite TrueType glyph. See also the structure element &lsquo;maxCompositePoints&rsquo;.</p> </td></tr> <tr valign=top><td><b>maxContours</b></td><td> <p>The maximum number of contours in a non-composite TrueType glyph. See also the structure element &lsquo;maxCompositeContours&rsquo;.</p> </td></tr> <tr valign=top><td><b>maxCompositePoints</b></td><td> <p>The maximum number of points in a composite TrueType glyph. See also the structure element &lsquo;maxPoints&rsquo;.</p> </td></tr> <tr valign=top><td><b>maxCompositeContours</b></td><td> <p>The maximum number of contours in a composite TrueType glyph. See also the structure element &lsquo;maxContours&rsquo;.</p> </td></tr> <tr valign=top><td><b>maxZones</b></td><td> <p>The maximum number of zones used for glyph hinting.</p> </td></tr> <tr valign=top><td><b>maxTwilightPoints</b></td><td> <p>The maximum number of points in the twilight zone used for glyph hinting.</p> </td></tr> <tr valign=top><td><b>maxStorage</b></td><td> <p>The maximum number of elements in the storage area used for glyph hinting.</p> </td></tr> <tr valign=top><td><b>maxFunctionDefs</b></td><td> <p>The maximum number of function definitions in the TrueType bytecode for this font.</p> </td></tr> <tr valign=top><td><b>maxInstructionDefs</b></td><td> <p>The maximum number of instruction definitions in the TrueType bytecode for this font.</p> </td></tr> <tr valign=top><td><b>maxStackElements</b></td><td> <p>The maximum number of stack elements used during bytecode interpretation.</p> </td></tr> <tr valign=top><td><b>maxSizeOfInstructions</b></td><td> <p>The maximum number of TrueType opcodes used for glyph hinting.</p> </td></tr> <tr valign=top><td><b>maxComponentElements</b></td><td> <p>The maximum number of simple (i.e., non- composite) glyphs in a composite glyph.</p> </td></tr> <tr valign=top><td><b>maxComponentDepth</b></td><td> <p>The maximum nesting depth of composite glyphs.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>This structure is only used during font loading.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Sfnt_Tag">FT_Sfnt_Tag</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> <span class="keyword">typedef</span> <span class="keyword">enum</span> FT_Sfnt_Tag_ { ft_sfnt_head = 0, /* <a href="ft2-truetype_tables.html#TT_Header">TT_Header</a> */ ft_sfnt_maxp = 1, /* <a href="ft2-truetype_tables.html#TT_MaxProfile">TT_MaxProfile</a> */ ft_sfnt_os2 = 2, /* <a href="ft2-truetype_tables.html#TT_OS2">TT_OS2</a> */ ft_sfnt_hhea = 3, /* <a href="ft2-truetype_tables.html#TT_HoriHeader">TT_HoriHeader</a> */ ft_sfnt_vhea = 4, /* <a href="ft2-truetype_tables.html#TT_VertHeader">TT_VertHeader</a> */ ft_sfnt_post = 5, /* <a href="ft2-truetype_tables.html#TT_Postscript">TT_Postscript</a> */ ft_sfnt_pclt = 6, /* <a href="ft2-truetype_tables.html#TT_PCLT">TT_PCLT</a> */ sfnt_max /* internal end mark */ } <b>FT_Sfnt_Tag</b>; </pre></table><br> <table align=center width="87%"><tr><td> <p>An enumeration used to specify the index of an SFNT table. Used in the <a href="ft2-truetype_tables.html#FT_Get_Sfnt_Table">FT_Get_Sfnt_Table</a> API function.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Get_Sfnt_Table">FT_Get_Sfnt_Table</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <span class="keyword">void</span>* ) <b>FT_Get_Sfnt_Table</b>( <a href="ft2-base_interface.html#FT_Face">FT_Face</a> face, <a href="ft2-truetype_tables.html#FT_Sfnt_Tag">FT_Sfnt_Tag</a> tag ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Return a pointer to a given SFNT table within a face.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>face</b></td><td> <p>A handle to the source.</p> </td></tr> <tr valign=top><td><b>tag</b></td><td> <p>The index of the SFNT table.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>A type-less pointer to the table. This will be&nbsp;0 in case of error, or if the corresponding table was not found <b>OR</b> loaded from the file.</p> <p>Use a typecast according to &lsquo;tag&rsquo; to access the structure elements.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>The table is owned by the face object and disappears with it.</p> <p>This function is only useful to access SFNT tables that are loaded by the sfnt, truetype, and opentype drivers. See <a href="ft2-truetype_tables.html#FT_Sfnt_Tag">FT_Sfnt_Tag</a> for a list.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Load_Sfnt_Table">FT_Load_Sfnt_Table</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_Error">FT_Error</a> ) <b>FT_Load_Sfnt_Table</b>( <a href="ft2-base_interface.html#FT_Face">FT_Face</a> face, <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> tag, <a href="ft2-basic_types.html#FT_Long">FT_Long</a> offset, <a href="ft2-basic_types.html#FT_Byte">FT_Byte</a>* buffer, <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a>* length ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Load any font table into client memory.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>face</b></td><td> <p>A handle to the source face.</p> </td></tr> <tr valign=top><td><b>tag</b></td><td> <p>The four-byte tag of the table to load. Use the value&nbsp;0 if you want to access the whole font file. Otherwise, you can use one of the definitions found in the <a href="ft2-header_file_macros.html#FT_TRUETYPE_TAGS_H">FT_TRUETYPE_TAGS_H</a> file, or forge a new one with <a href="ft2-basic_types.html#FT_MAKE_TAG">FT_MAKE_TAG</a>.</p> </td></tr> <tr valign=top><td><b>offset</b></td><td> <p>The starting offset in the table (or file if tag == 0).</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>output</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>buffer</b></td><td> <p>The target buffer address. The client must ensure that the memory array is big enough to hold the data.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>inout</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>length</b></td><td> <p>If the &lsquo;length&rsquo; parameter is NULL, then try to load the whole table. Return an error code if it fails.</p> <p>Else, if &lsquo;*length&rsquo; is&nbsp;0, exit immediately while returning the table's (or file) full size in it.</p> <p>Else the number of bytes to read from the table or file, from the starting offset.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>FreeType error code. 0&nbsp;means success.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>If you need to determine the table's length you should first call this function with &lsquo;*length&rsquo; set to&nbsp;0, as in the following example:</p> <pre class="colored"> FT_ULong length = 0; error = FT_Load_Sfnt_Table( face, tag, 0, NULL, &amp;length ); if ( error ) { ... table does not exist ... } buffer = malloc( length ); if ( buffer == NULL ) { ... not enough memory ... } error = FT_Load_Sfnt_Table( face, tag, 0, buffer, &amp;length ); if ( error ) { ... could not load table ... } </pre> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Sfnt_Table_Info">FT_Sfnt_Table_Info</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_Error">FT_Error</a> ) <b>FT_Sfnt_Table_Info</b>( <a href="ft2-base_interface.html#FT_Face">FT_Face</a> face, <a href="ft2-basic_types.html#FT_UInt">FT_UInt</a> table_index, <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> *tag, <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> *length ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Return information on an SFNT table.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>face</b></td><td> <p>A handle to the source face.</p> </td></tr> <tr valign=top><td><b>table_index</b></td><td> <p>The index of an SFNT table. The function returns FT_Err_Table_Missing for an invalid value.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>output</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>tag</b></td><td> <p>The name tag of the SFNT table.</p> </td></tr> <tr valign=top><td><b>length</b></td><td> <p>The length of the SFNT table.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>FreeType error code. 0&nbsp;means success.</p> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>note</b></em></td></tr><tr><td> <p>SFNT tables with length zero are treated as missing.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Get_CMap_Language_ID">FT_Get_CMap_Language_ID</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_ULong">FT_ULong</a> ) <b>FT_Get_CMap_Language_ID</b>( <a href="ft2-base_interface.html#FT_CharMap">FT_CharMap</a> charmap ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Return TrueType/sfnt specific cmap language ID. Definitions of language ID values are in &lsquo;freetype/ttnameid.h&rsquo;.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>charmap</b></td><td> <p>The target charmap.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>The language ID of &lsquo;charmap&rsquo;. If &lsquo;charmap&rsquo; doesn't belong to a TrueType/sfnt face, just return&nbsp;0 as the default value.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_Get_CMap_Format">FT_Get_CMap_Format</a></h4> <table align=center width="87%"><tr><td> Defined in FT_TRUETYPE_TABLES_H (freetype/tttables.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> FT_EXPORT( <a href="ft2-basic_types.html#FT_Long">FT_Long</a> ) <b>FT_Get_CMap_Format</b>( <a href="ft2-base_interface.html#FT_CharMap">FT_CharMap</a> charmap ); </pre></table><br> <table align=center width="87%"><tr><td> <p>Return TrueType/sfnt specific cmap format.</p> </td></tr></table><br> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>input</b></em></td></tr><tr><td> <p></p> <table cellpadding=3 border=0> <tr valign=top><td><b>charmap</b></td><td> <p>The target charmap.</p> </td></tr> </table> </td></tr></table> <table align=center width="87%" cellpadding=5><tr bgcolor="#EEEEFF"><td><em><b>return</b></em></td></tr><tr><td> <p>The format of &lsquo;charmap&rsquo;. If &lsquo;charmap&rsquo; doesn't belong to a TrueType/sfnt face, return -1.</p> </td></tr></table> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> <table align=center width="75%"><tr><td> <h4><a name="FT_PARAM_TAG_UNPATENTED_HINTING">FT_PARAM_TAG_UNPATENTED_HINTING</a></h4> <table align=center width="87%"><tr><td> Defined in FT_UNPATENTED_HINTING_H (freetype/ttunpat.h). </td></tr></table><br> <table align=center width="87%"><tr bgcolor="#D6E8FF"><td><pre> #define <b>FT_PARAM_TAG_UNPATENTED_HINTING</b> <a href="ft2-basic_types.html#FT_MAKE_TAG">FT_MAKE_TAG</a>( 'u', 'n', 'p', 'a' ) </pre></table><br> <table align=center width="87%"><tr><td> <p>A constant used as the tag of an <a href="ft2-base_interface.html#FT_Parameter">FT_Parameter</a> structure to indicate that unpatented methods only should be used by the TrueType bytecode interpreter for a typeface opened by <a href="ft2-base_interface.html#FT_Open_Face">FT_Open_Face</a>.</p> </td></tr></table><br> </td></tr></table> <hr width="75%"> <table align=center width="75%"><tr><td><font size=-2>[<a href="ft2-index.html">Index</a>]</font></td> <td width="100%"></td> <td><font size=-2>[<a href="ft2-toc.html">TOC</a>]</font></td></tr></table> </body> </html>
VizLibrary/Visualization-Library
src/3rdparty/freetype/docs/reference/ft2-truetype_tables.html
HTML
bsd-2-clause
61,497
goog.provide('ol.layer.VectorTile'); goog.require('ol.layer.Vector'); goog.require('ol.object'); /** * @enum {string} */ ol.layer.VectorTileProperty = { PRELOAD: 'preload', USE_INTERIM_TILES_ON_ERROR: 'useInterimTilesOnError' }; /** * @classdesc * Layer for vector tile data that is rendered client-side. * Note that any property set in the options is set as a {@link ol.Object} * property on the layer object; for example, setting `title: 'My Title'` in the * options means that `title` is observable, and has get/set accessors. * * @constructor * @extends {ol.layer.Vector} * @param {olx.layer.VectorTileOptions=} opt_options Options. * @api */ ol.layer.VectorTile = function(opt_options) { var options = opt_options ? opt_options : {}; var baseOptions = ol.object.assign({}, options); delete baseOptions.preload; delete baseOptions.useInterimTilesOnError; goog.base(this, /** @type {olx.layer.VectorOptions} */ (baseOptions)); this.setPreload(options.preload ? options.preload : 0); this.setUseInterimTilesOnError(options.useInterimTilesOnError ? options.useInterimTilesOnError : true); }; goog.inherits(ol.layer.VectorTile, ol.layer.Vector); /** * Return the level as number to which we will preload tiles up to. * @return {number} The level to preload tiles up to. * @observable * @api */ ol.layer.VectorTile.prototype.getPreload = function() { return /** @type {number} */ (this.get(ol.layer.VectorTileProperty.PRELOAD)); }; /** * Whether we use interim tiles on error. * @return {boolean} Use interim tiles on error. * @observable * @api */ ol.layer.VectorTile.prototype.getUseInterimTilesOnError = function() { return /** @type {boolean} */ ( this.get(ol.layer.VectorTileProperty.USE_INTERIM_TILES_ON_ERROR)); }; /** * Set the level as number to which we will preload tiles up to. * @param {number} preload The level to preload tiles up to. * @observable * @api */ ol.layer.VectorTile.prototype.setPreload = function(preload) { this.set(ol.layer.TileProperty.PRELOAD, preload); }; /** * Set whether we use interim tiles on error. * @param {boolean} useInterimTilesOnError Use interim tiles on error. * @observable * @api */ ol.layer.VectorTile.prototype.setUseInterimTilesOnError = function(useInterimTilesOnError) { this.set( ol.layer.TileProperty.USE_INTERIM_TILES_ON_ERROR, useInterimTilesOnError); };
NOAA-ORR-ERD/ol3
src/ol/layer/vectortilelayer.js
JavaScript
bsd-2-clause
2,408
class Yemuzip < Cask url 'http://www.yellowmug.com/download/YemuZip.dmg' homepage 'http://www.yellowmug.com/yemuzip' version 'latest' sha256 :no_check link 'YemuZip.app' end
okonomi/homebrew-cask
Casks/yemuzip.rb
Ruby
bsd-2-clause
184
--TEST-- IF doesn't change scope --FILE-- <?php include('common.inc'); ini_set('blitz.remove_spaces_around_context_tags', 1); $T = new Blitz(); $tmp = " {{BEGIN item}} {{id}} = 1 {{BEGIN children}} {{id}} = 2 {{ if \$_parent.id == 1 }} Success Parent id: {{_parent.id}} is 1 {{END}} {{END}} {{END}} "; $T->load($tmp); $T->block('/item', array("id"=>1)); $T->block('/item/children', array("id"=>2)); echo $T->parse(); ?> --EXPECTF-- 1 = 1 2 = 2 Success Parent id: 1 is 1
poison/blitz
tests/scope_if.phpt
PHP
bsd-2-clause
502
package org.jcodec.containers.mxf.model; import java.nio.ByteBuffer; import java.util.Date; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import org.jcodec.common.logging.Logger; /** * This class is part of JCodec ( www.jcodec.org ) This software is distributed * under FreeBSD License * * @author The JCodec project * */ public class Preface extends MXFInterchangeObject { private Date lastModifiedDate; private int objectModelVersion; private UL op; private UL[] essenceContainers; private UL[] dmSchemes; public Preface(UL ul) { super(ul); } @Override protected void read(Map<Integer, ByteBuffer> tags) { for (Iterator<Entry<Integer, ByteBuffer>> it = tags.entrySet().iterator(); it.hasNext();) { Entry<Integer, ByteBuffer> entry = it.next(); ByteBuffer _bb = entry.getValue(); switch (entry.getKey()) { case 0x3b02: lastModifiedDate = readDate(_bb); break; case 0x3b07: objectModelVersion = _bb.getInt(); break; case 0x3b09: op = UL.read(_bb); break; case 0x3b0a: essenceContainers = readULBatch(_bb); break; case 0x3b0b: dmSchemes = readULBatch(_bb); break; default: Logger.warn(String.format("Unknown tag [ " + ul + "]: %04x", entry.getKey())); continue; } it.remove(); } } public Date getLastModifiedDate() { return lastModifiedDate; } public int getObjectModelVersion() { return objectModelVersion; } public UL getOp() { return op; } public UL[] getEssenceContainers() { return essenceContainers; } public UL[] getDmSchemes() { return dmSchemes; } }
minseonahn/jcodec
src/main/java/org/jcodec/containers/mxf/model/Preface.java
Java
bsd-2-clause
1,976
package gs import "testing" var configTests = []struct { s string cfg Config }{ {"gs:bucketname:/", Config{ Bucket: "bucketname", Prefix: "", Connections: 5, }}, {"gs:bucketname:/prefix/directory", Config{ Bucket: "bucketname", Prefix: "prefix/directory", Connections: 5, }}, {"gs:bucketname:/prefix/directory/", Config{ Bucket: "bucketname", Prefix: "prefix/directory", Connections: 5, }}, } func TestParseConfig(t *testing.T) { for i, test := range configTests { cfg, err := ParseConfig(test.s) if err != nil { t.Errorf("test %d:%s failed: %v", i, test.s, err) continue } if cfg != test.cfg { t.Errorf("test %d:\ninput:\n %s\n wrong config, want:\n %v\ngot:\n %v", i, test.s, test.cfg, cfg) continue } } }
restic/restic
internal/backend/gs/config_test.go
GO
bsd-2-clause
801
// Traditional Chinese BIG-5; Twapweb Site translated; twapweb_AT_gmail_DOT_com // ÁcÅ餤¤å BIG-5 ¡F¼Æ¦ìÀ³¥Î§{»s§@¡F twapweb_AT_gmail_DOT_com tinyMCE.addToLang('',{ directionality_ltr_desc : '¥Ñ¥ª©¹¥k¤è¦V', directionality_rtl_desc : '¥Ñ¥k©¹¥ª¤è¦V' });
dalinhuang/suduforum
templates/default/editors/tiny_mce/plugins/directionality/langs/zh_tw.js
JavaScript
bsd-3-clause
260
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <!-- Hand-written HTML --> <html> <head> <title>SWIG and MzScheme/Racket</title> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body bgcolor="#ffffff"> <H1><a name="Mzscheme"></a>28 SWIG and MzScheme/Racket</H1> <!-- INDEX --> <div class="sectiontoc"> <ul> <li><a href="#MzScheme_nn2">Creating native structures</a> <li><a href="#MzScheme_simple">Simple example</a> <li><a href="#MzScheme_external_docs">External documentation</a> </ul> </div> <!-- INDEX --> <p> This section contains information on SWIG's support of Racket, formally known as MzScheme. <H2><a name="MzScheme_nn2"></a>28.1 Creating native structures</H2> <p> Example interface file: </p> <div class="code"> <pre> /* define a macro for the struct creation */ %define handle_ptr(TYPE,NAME) %typemap(argout) TYPE *NAME{ Scheme_Object *o = SWIG_NewStructFromPtr($1, $*1_mangle); SWIG_APPEND_VALUE(o); } %typemap(in,numinputs=0) TYPE *NAME (TYPE temp) { $1 = &amp;temp; } %enddef /* setup the typemaps for the pointer to an output parameter cntrs */ handle_ptr(struct diag_cntrs, cntrs); </pre> </div> <p> Then in scheme, you can use regular struct access procedures like </p> <div class="code"> <pre> ; suppose a function created a struct foo as ; (define foo (make-diag-cntrs (#x1 #x2 #x3) (make-inspector)) ; Then you can do (format "0x~x" (diag-cntrs-field1 foo)) (format "0x~x" (diag-cntrs-field2 foo)) ;etc... </pre> </div> <H2><a name="MzScheme_simple"></a>28.2 Simple example</H2> <p> A few examples are available in the Examples/mzscheme directory. The code and log of a session using SWIG below should help getting started. </p> <p> C header file: </p> <div class="code"> <pre> // example.h int fact(int n); </pre> </div> <p> C source code: </p> <div class="code"> <pre> // File: example.c #include "example.h" int fact(int n) { if (n &lt; 0) { /* This should probably return an error, but this is simpler */ return 0; } if (n == 0) { return 1; } else { /* testing for overflow would be a good idea here */ return n * fact(n-1); } } </pre> </div> <p> SWIG interface file: </p> <div class="code"> <pre> /* File: example.i */ %module example %{ #include "example.h" %} int fact(int n); </pre> </div> <p> The session below using the above files is on an OS X machine, but the points to be made are more general. On OS X, libtool is the tool which creates libraries, which are named .dylib, rather than .so on other unixes, or .dll on Windows. </p> <div class="shell"> <pre> % swig -mzscheme -declaremodule example.i % gcc -c -m32 -o example.o example.c # force 32-bit object file (mzscheme is 32-bit only) % libtool -dynamic -o libexample.dylib example.o # make it into a library % ls # what've we got so far? example.c example.o example.h example_wrap.c example.i libexample.dylib* % mzc --cgc --cc example_wrap.c # compile the wrapping code % LDFLAGS="-L. -lexample" mzc --ld example_wrap.dylib example_wrap.o # ...and link it % mzscheme -e '(path-&gt;string (build-path "compiled" "native" (system-library-subpath)))' "compiled/native/i386-macosx/3m" % mkdir -p compiled/native/i386-macosx/3m # move the extension library to a magic place % mv example_wrap.dylib compiled/native/i386-macosx/3m/example_ss.dylib % mzscheme Welcome to MzScheme v4.2.4 [3m], Copyright (c) 2004-2010 PLT Scheme Inc. &gt; (require "example.ss") &gt; (fact 5) 120 &gt; ^D % echo 'It works!' </pre> </div> <p> Some points of interest: </p> <ul> <li> This is on a 64-bit machine, so we have to include the -m32 option when building the object file <li> If you want to declare a scheme module (and you probably do), it's important that you include the -declaremodule option to swig (if you miss this out, it'll appear to work, but fail later). <li> Use mzc to compile and then link the wrapped code. You'll probably need to adjust the link flags to refer to the library you're wrapping (you can either do this with an LDFLAGS declaration, as here, or with multiple ++ldf options to mzc). <li> Create the directory with path (build-path "compiled" "native" (system-library-subpath)) and move the freshly-generated .dylib to there, changing its name to module-name_ss.dylib. After that, you can REQUIRE the new module with (require "module-name.ss"). <li> The above requests mzc to create an extension using the CGC garbage-collector. The alternative -- the 3m collector -- has generally better performance, but work is still required for SWIG to emit code which is compatible with it. </ul> <H2><a name="MzScheme_external_docs"></a>28.3 External documentation</H2> <p> See the <a href="http://docs.racket-lang.org/inside/index.html">C API</a> for more description of using the mechanism for adding extensions. The main documentation is <a href="http://docs.racket-lang.org/">here</a>. </p> <p> Tip: mzc's --vv option is very useful for debugging the inevitable library problems you'll encounter. </p> </body> </html>
d909b/GADEL-Snake
Tools/swigwin-2.0.6/Doc/Manual/Mzscheme.html
HTML
bsd-3-clause
5,036
<?php /** * Remove all the elements in the sorted set at key with a score between min and max (including elements with score equal to min or max). * * @param string $name Key name * @param numeric $min Min value * @param numeric $max Max value * @return integer * * @author Ivan Shumkov * @package Rediska * @version @package_version@ * @link http://rediska.geometria-lab.net * @license http://www.opensource.org/licenses/bsd-license.php */ class Rediska_Command_DeleteFromSortedSetByRankTest extends Rediska_TestCase { public function testDeleteFromNotExistsSetReturnFalse() { $reply = $this->rediska->deleteFromSortedSetByRank('test', 0, 1); $this->assertEquals(0, $reply); } public function testDelete() { $this->rediska->addToSortedSet('test', 'aaa', 1); $this->rediska->addToSortedSet('test', 'bbb', 2); $this->rediska->addToSortedSet('test', 'ccc', 3); $this->rediska->addToSortedSet('test', 'ddd', 4); $reply = $this->rediska->deleteFromSortedSetByRank('test', 1, 2); $this->assertEquals(2, $reply); $values = $this->rediska->getSortedSet('test'); $this->assertContains('aaa', $values); $this->assertNotContains('bbb', $values); $this->assertNotContains('ccc', $values); $this->assertContains('ddd', $values); } }
AlphaStaxLLC/Rediska
tests/library/Rediska/Command/DeleteFromSortedSetByRankTest.php
PHP
bsd-3-clause
1,377
/** * (C) 1999-2003 Lars Knoll ([email protected]) * Copyright (C) 2004, 2005, 2006 Apple Computer, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "core/css/CSSProperty.h" #include "core/StylePropertyShorthand.h" #include "core/css/CSSValueList.h" #include "core/rendering/style/RenderStyleConstants.h" namespace blink { struct SameSizeAsCSSProperty { uint32_t bitfields; void* value; }; static_assert(sizeof(CSSProperty) == sizeof(SameSizeAsCSSProperty), "CSSProperty should stay small"); CSSPropertyID StylePropertyMetadata::shorthandID() const { if (!m_isSetFromShorthand) return CSSPropertyInvalid; Vector<StylePropertyShorthand, 4> shorthands; getMatchingShorthandsForLonghand(static_cast<CSSPropertyID>(m_propertyID), &shorthands); ASSERT(shorthands.size() && m_indexInShorthandsVector >= 0 && m_indexInShorthandsVector < shorthands.size()); return shorthands.at(m_indexInShorthandsVector).id(); } void CSSProperty::wrapValueInCommaSeparatedList() { RefPtrWillBeRawPtr<CSSValue> value = m_value.release(); m_value = CSSValueList::createCommaSeparated(); toCSSValueList(m_value.get())->append(value.release()); } enum LogicalBoxSide { BeforeSide, EndSide, AfterSide, StartSide }; enum PhysicalBoxSide { TopSide, RightSide, BottomSide, LeftSide }; static CSSPropertyID resolveToPhysicalProperty(TextDirection direction, WritingMode writingMode, LogicalBoxSide logicalSide, const StylePropertyShorthand& shorthand) { if (direction == LTR) { if (writingMode == TopToBottomWritingMode) { // The common case. The logical and physical box sides match. // Left = Start, Right = End, Before = Top, After = Bottom return shorthand.properties()[logicalSide]; } if (writingMode == BottomToTopWritingMode) { // Start = Left, End = Right, Before = Bottom, After = Top. switch (logicalSide) { case StartSide: return shorthand.properties()[LeftSide]; case EndSide: return shorthand.properties()[RightSide]; case BeforeSide: return shorthand.properties()[BottomSide]; default: return shorthand.properties()[TopSide]; } } if (writingMode == LeftToRightWritingMode) { // Start = Top, End = Bottom, Before = Left, After = Right. switch (logicalSide) { case StartSide: return shorthand.properties()[TopSide]; case EndSide: return shorthand.properties()[BottomSide]; case BeforeSide: return shorthand.properties()[LeftSide]; default: return shorthand.properties()[RightSide]; } } // Start = Top, End = Bottom, Before = Right, After = Left switch (logicalSide) { case StartSide: return shorthand.properties()[TopSide]; case EndSide: return shorthand.properties()[BottomSide]; case BeforeSide: return shorthand.properties()[RightSide]; default: return shorthand.properties()[LeftSide]; } } if (writingMode == TopToBottomWritingMode) { // Start = Right, End = Left, Before = Top, After = Bottom switch (logicalSide) { case StartSide: return shorthand.properties()[RightSide]; case EndSide: return shorthand.properties()[LeftSide]; case BeforeSide: return shorthand.properties()[TopSide]; default: return shorthand.properties()[BottomSide]; } } if (writingMode == BottomToTopWritingMode) { // Start = Right, End = Left, Before = Bottom, After = Top switch (logicalSide) { case StartSide: return shorthand.properties()[RightSide]; case EndSide: return shorthand.properties()[LeftSide]; case BeforeSide: return shorthand.properties()[BottomSide]; default: return shorthand.properties()[TopSide]; } } if (writingMode == LeftToRightWritingMode) { // Start = Bottom, End = Top, Before = Left, After = Right switch (logicalSide) { case StartSide: return shorthand.properties()[BottomSide]; case EndSide: return shorthand.properties()[TopSide]; case BeforeSide: return shorthand.properties()[LeftSide]; default: return shorthand.properties()[RightSide]; } } // Start = Bottom, End = Top, Before = Right, After = Left switch (logicalSide) { case StartSide: return shorthand.properties()[BottomSide]; case EndSide: return shorthand.properties()[TopSide]; case BeforeSide: return shorthand.properties()[RightSide]; default: return shorthand.properties()[LeftSide]; } } enum LogicalExtent { LogicalWidth, LogicalHeight }; static CSSPropertyID resolveToPhysicalProperty(WritingMode writingMode, LogicalExtent logicalSide, const CSSPropertyID* properties) { if (writingMode == TopToBottomWritingMode || writingMode == BottomToTopWritingMode) return properties[logicalSide]; return logicalSide == LogicalWidth ? properties[1] : properties[0]; } static const StylePropertyShorthand& borderDirections() { static const CSSPropertyID properties[4] = { CSSPropertyBorderTop, CSSPropertyBorderRight, CSSPropertyBorderBottom, CSSPropertyBorderLeft }; DEFINE_STATIC_LOCAL(StylePropertyShorthand, borderDirections, (CSSPropertyBorder, properties, WTF_ARRAY_LENGTH(properties))); return borderDirections; } CSSPropertyID CSSProperty::resolveDirectionAwareProperty(CSSPropertyID propertyID, TextDirection direction, WritingMode writingMode) { switch (propertyID) { case CSSPropertyWebkitMarginEnd: return resolveToPhysicalProperty(direction, writingMode, EndSide, marginShorthand()); case CSSPropertyWebkitMarginStart: return resolveToPhysicalProperty(direction, writingMode, StartSide, marginShorthand()); case CSSPropertyWebkitMarginBefore: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, marginShorthand()); case CSSPropertyWebkitMarginAfter: return resolveToPhysicalProperty(direction, writingMode, AfterSide, marginShorthand()); case CSSPropertyWebkitPaddingEnd: return resolveToPhysicalProperty(direction, writingMode, EndSide, paddingShorthand()); case CSSPropertyWebkitPaddingStart: return resolveToPhysicalProperty(direction, writingMode, StartSide, paddingShorthand()); case CSSPropertyWebkitPaddingBefore: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, paddingShorthand()); case CSSPropertyWebkitPaddingAfter: return resolveToPhysicalProperty(direction, writingMode, AfterSide, paddingShorthand()); case CSSPropertyWebkitBorderEnd: return resolveToPhysicalProperty(direction, writingMode, EndSide, borderDirections()); case CSSPropertyWebkitBorderStart: return resolveToPhysicalProperty(direction, writingMode, StartSide, borderDirections()); case CSSPropertyWebkitBorderBefore: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, borderDirections()); case CSSPropertyWebkitBorderAfter: return resolveToPhysicalProperty(direction, writingMode, AfterSide, borderDirections()); case CSSPropertyWebkitBorderEndColor: return resolveToPhysicalProperty(direction, writingMode, EndSide, borderColorShorthand()); case CSSPropertyWebkitBorderStartColor: return resolveToPhysicalProperty(direction, writingMode, StartSide, borderColorShorthand()); case CSSPropertyWebkitBorderBeforeColor: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, borderColorShorthand()); case CSSPropertyWebkitBorderAfterColor: return resolveToPhysicalProperty(direction, writingMode, AfterSide, borderColorShorthand()); case CSSPropertyWebkitBorderEndStyle: return resolveToPhysicalProperty(direction, writingMode, EndSide, borderStyleShorthand()); case CSSPropertyWebkitBorderStartStyle: return resolveToPhysicalProperty(direction, writingMode, StartSide, borderStyleShorthand()); case CSSPropertyWebkitBorderBeforeStyle: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, borderStyleShorthand()); case CSSPropertyWebkitBorderAfterStyle: return resolveToPhysicalProperty(direction, writingMode, AfterSide, borderStyleShorthand()); case CSSPropertyWebkitBorderEndWidth: return resolveToPhysicalProperty(direction, writingMode, EndSide, borderWidthShorthand()); case CSSPropertyWebkitBorderStartWidth: return resolveToPhysicalProperty(direction, writingMode, StartSide, borderWidthShorthand()); case CSSPropertyWebkitBorderBeforeWidth: return resolveToPhysicalProperty(direction, writingMode, BeforeSide, borderWidthShorthand()); case CSSPropertyWebkitBorderAfterWidth: return resolveToPhysicalProperty(direction, writingMode, AfterSide, borderWidthShorthand()); case CSSPropertyWebkitLogicalWidth: { const CSSPropertyID properties[2] = { CSSPropertyWidth, CSSPropertyHeight }; return resolveToPhysicalProperty(writingMode, LogicalWidth, properties); } case CSSPropertyWebkitLogicalHeight: { const CSSPropertyID properties[2] = { CSSPropertyWidth, CSSPropertyHeight }; return resolveToPhysicalProperty(writingMode, LogicalHeight, properties); } case CSSPropertyWebkitMinLogicalWidth: { const CSSPropertyID properties[2] = { CSSPropertyMinWidth, CSSPropertyMinHeight }; return resolveToPhysicalProperty(writingMode, LogicalWidth, properties); } case CSSPropertyWebkitMinLogicalHeight: { const CSSPropertyID properties[2] = { CSSPropertyMinWidth, CSSPropertyMinHeight }; return resolveToPhysicalProperty(writingMode, LogicalHeight, properties); } case CSSPropertyWebkitMaxLogicalWidth: { const CSSPropertyID properties[2] = { CSSPropertyMaxWidth, CSSPropertyMaxHeight }; return resolveToPhysicalProperty(writingMode, LogicalWidth, properties); } case CSSPropertyWebkitMaxLogicalHeight: { const CSSPropertyID properties[2] = { CSSPropertyMaxWidth, CSSPropertyMaxHeight }; return resolveToPhysicalProperty(writingMode, LogicalHeight, properties); } default: return propertyID; } } bool CSSProperty::isAffectedByAllProperty(CSSPropertyID propertyID) { if (propertyID == CSSPropertyAll) return false; // all shorthand spec says: // The all property is a shorthand that resets all CSS properties except // direction and unicode-bidi. It only accepts the CSS-wide keywords. // c.f. http://dev.w3.org/csswg/css-cascade/#all-shorthand // So CSSPropertyUnicodeBidi and CSSPropertyDirection are not // affected by all property. return propertyID != CSSPropertyUnicodeBidi && propertyID != CSSPropertyDirection; } } // namespace blink
mxOBS/deb-pkg_trusty_chromium-browser
third_party/WebKit/Source/core/css/CSSProperty.cpp
C++
bsd-3-clause
11,995
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef WEBKIT_FILEAPI_ISOLATED_FILE_UTIL_H_ #define WEBKIT_FILEAPI_ISOLATED_FILE_UTIL_H_ #include "base/file_path.h" #include "base/file_util_proxy.h" #include "base/platform_file.h" #include "webkit/fileapi/file_system_file_util.h" namespace base { class Time; } namespace fileapi { class FileSystemOperationContext; class IsolatedContext; class IsolatedFileUtil : public FileSystemFileUtil { public: explicit IsolatedFileUtil(FileSystemFileUtil* underlying_file_util); virtual ~IsolatedFileUtil() {} // FileSystemFileUtil overrides. virtual base::PlatformFileError CreateOrOpen( FileSystemOperationContext* context, const FileSystemPath& path, int file_flags, base::PlatformFile* file_handle, bool* created) OVERRIDE; virtual base::PlatformFileError Close( FileSystemOperationContext* context, base::PlatformFile) OVERRIDE; virtual base::PlatformFileError EnsureFileExists( FileSystemOperationContext* context, const FileSystemPath& path, bool* created) OVERRIDE; virtual base::PlatformFileError CreateDirectory( FileSystemOperationContext* context, const FileSystemPath& path, bool exclusive, bool recursive) OVERRIDE; virtual base::PlatformFileError GetFileInfo( FileSystemOperationContext* context, const FileSystemPath& path, base::PlatformFileInfo* file_info, FilePath* platform_path) OVERRIDE; virtual AbstractFileEnumerator* CreateFileEnumerator( FileSystemOperationContext* context, const FileSystemPath& root_path, bool recursive) OVERRIDE; virtual base::PlatformFileError Touch( FileSystemOperationContext* context, const FileSystemPath& path, const base::Time& last_access_time, const base::Time& last_modified_time) OVERRIDE; virtual base::PlatformFileError Truncate( FileSystemOperationContext* context, const FileSystemPath& path, int64 length) OVERRIDE; virtual bool PathExists( FileSystemOperationContext* context, const FileSystemPath& path) OVERRIDE; virtual bool DirectoryExists( FileSystemOperationContext* context, const FileSystemPath& path) OVERRIDE; virtual bool IsDirectoryEmpty( FileSystemOperationContext* context, const FileSystemPath& path) OVERRIDE; virtual base::PlatformFileError CopyOrMoveFile( FileSystemOperationContext* context, const FileSystemPath& src_path, const FileSystemPath& dest_path, bool copy) OVERRIDE; virtual base::PlatformFileError CopyInForeignFile( FileSystemOperationContext* context, const FileSystemPath& underlying_src_path, const FileSystemPath& dest_path) OVERRIDE; virtual base::PlatformFileError DeleteFile( FileSystemOperationContext* context, const FileSystemPath& path) OVERRIDE; virtual base::PlatformFileError DeleteSingleDirectory( FileSystemOperationContext* context, const FileSystemPath& path) OVERRIDE; private: // Returns false if the given |virtual_path| is not a valid path. bool GetPlatformPath(const FileSystemPath& virtual_path, FilePath* platform_path) const; DISALLOW_COPY_AND_ASSIGN(IsolatedFileUtil); }; } // namespace fileapi #endif // WEBKIT_FILEAPI_ISOLATED_FILE_UTIL_H_
ropik/chromium
webkit/fileapi/isolated_file_util.h
C
bsd-3-clause
3,477
from __future__ import print_function import numpy as np from theano.compat.six.moves import cStringIO, xrange import theano.tensor as T from theano.tests import disturb_mem from theano.tests.record import Record, RecordMode from pylearn2.compat import first_key from pylearn2.costs.cost import Cost, SumOfCosts, DefaultDataSpecsMixin from pylearn2.datasets.dense_design_matrix import DenseDesignMatrix from pylearn2.models.model import Model from pylearn2.monitor import Monitor, push_monitor from pylearn2.space import CompositeSpace, Conv2DSpace, VectorSpace from pylearn2.termination_criteria import EpochCounter from pylearn2.testing.cost import CallbackCost, SumOfParams from pylearn2.testing.datasets import ArangeDataset from pylearn2.train import Train from pylearn2.training_algorithms.sgd import (ExponentialDecay, PolyakAveraging, LinearDecay, LinearDecayOverEpoch, MonitorBasedLRAdjuster, SGD, AnnealedLearningRate, EpochMonitor) from pylearn2.training_algorithms.learning_rule import (Momentum, MomentumAdjustor) from pylearn2.utils.iteration import _iteration_schemes from pylearn2.utils import safe_izip, safe_union, sharedX from pylearn2.utils.exc import reraise_as class SupervisedDummyCost(DefaultDataSpecsMixin, Cost): supervised = True def expr(self, model, data): space, sources = self.get_data_specs(model) space.validate(data) (X, Y) = data return T.square(model(X) - Y).mean() class DummyCost(DefaultDataSpecsMixin, Cost): def expr(self, model, data): space, sources = self.get_data_specs(model) space.validate(data) X = data return T.square(model(X) - X).mean() class DummyModel(Model): def __init__(self, shapes, lr_scalers=None): super(DummyModel, self).__init__() self._params = [sharedX(np.random.random(shape)) for shape in shapes] self.input_space = VectorSpace(1) self.lr_scalers = lr_scalers def __call__(self, X): # Implemented only so that DummyCost would work return X def get_lr_scalers(self): if self.lr_scalers: return dict(zip(self._params, self.lr_scalers)) else: return dict() class SoftmaxModel(Model): """A dummy model used for testing. Important properties: has a parameter (P) for SGD to act on has a get_output_space method, so it can tell the algorithm what kind of space the targets for supervised learning live in has a get_input_space method, so it can tell the algorithm what kind of space the features live in """ def __init__(self, dim): super(SoftmaxModel, self).__init__() self.dim = dim rng = np.random.RandomState([2012, 9, 25]) self.P = sharedX(rng.uniform(-1., 1., (dim, ))) def get_params(self): return [self.P] def get_input_space(self): return VectorSpace(self.dim) def get_output_space(self): return VectorSpace(self.dim) def __call__(self, X): # Make the test fail if algorithm does not # respect get_input_space assert X.ndim == 2 # Multiplying by P ensures the shape as well # as ndim is correct return T.nnet.softmax(X*self.P) class TopoSoftmaxModel(Model): """A dummy model used for testing. Like SoftmaxModel but its features have 2 topological dimensions. This tests that the training algorithm will provide topological data correctly. """ def __init__(self, rows, cols, channels): super(TopoSoftmaxModel, self).__init__() dim = rows * cols * channels self.input_space = Conv2DSpace((rows, cols), channels) self.dim = dim rng = np.random.RandomState([2012, 9, 25]) self.P = sharedX(rng.uniform(-1., 1., (dim, ))) def get_params(self): return [self.P] def get_output_space(self): return VectorSpace(self.dim) def __call__(self, X): # Make the test fail if algorithm does not # respect get_input_space assert X.ndim == 4 # Multiplying by P ensures the shape as well # as ndim is correct return T.nnet.softmax(X.reshape((X.shape[0], self.dim)) * self.P) def test_sgd_unspec_num_mon_batch(): # tests that if you don't specify a number of # monitoring batches, SGD configures the monitor # to run on all the data m = 25 visited = [False] * m rng = np.random.RandomState([25, 9, 2012]) X = np.zeros((m, 1)) X[:, 0] = np.arange(m) dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(1) learning_rate = 1e-3 batch_size = 5 cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=None, monitoring_dataset=dataset, termination_criterion=None, update_callbacks=None, set_batch_size=False) algorithm.setup(dataset=dataset, model=model) monitor = Monitor.get_monitor(model) X = T.matrix() def tracker(*data): X, = data assert X.shape[1] == 1 for i in xrange(X.shape[0]): visited[int(X[i, 0])] = True monitor.add_channel(name='tracker', ipt=X, val=0., prereqs=[tracker], data_specs=(model.get_input_space(), model.get_input_source())) monitor() if False in visited: print(visited) assert False def test_sgd_sup(): # tests that we can run the sgd algorithm # on a supervised cost. # does not test for correctness at all, just # that the algorithm runs without dying dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) idx = rng.randint(0, dim, (m, )) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 dataset = DenseDesignMatrix(X=X, y=Y) m = 15 X = rng.randn(m, dim) idx = rng.randint(0, dim, (m,)) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 # Including a monitoring dataset lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X, y=Y) model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 cost = SupervisedDummyCost() # We need to include this so the test actually stops running at some point termination_criterion = EpochCounter(5) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def test_sgd_unsup(): # tests that we can run the sgd algorithm # on an supervised cost. # does not test for correctness at all, just # that the algorithm runs without dying dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # Including a monitoring dataset lets us test that # the monitor works with unsupervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 cost = DummyCost() # We need to include this so the test actually stops running at some point termination_criterion = EpochCounter(5) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def get_topological_dataset(rng, rows, cols, channels, m): X = rng.randn(m, rows, cols, channels) dim = rows * cols * channels idx = rng.randint(0, dim, (m,)) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 return DenseDesignMatrix(topo_view=X, y=Y) def test_linear_decay(): # tests that the class LinearDecay in sgd.py # gets the learning rate properly over the training batches # it runs a small softmax and at the end checks the learning values. # the learning rates are expected to start changing at batch 'start' # by an amount of 'step' specified below. # the decrease of the learning rate should continue linearly until # we reach batch 'saturate' at which the learning rate equals # 'learning_rate * decay_factor' class LearningRateTracker(object): def __init__(self): self.lr_rates = [] def __call__(self, algorithm): self.lr_rates.append(algorithm.learning_rate.get_value()) dim = 3 dataset_size = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(dataset_size, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 15 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() start = 5 saturate = 10 decay_factor = 0.1 linear_decay = LinearDecay(start=start, saturate=saturate, decay_factor=decay_factor) # including this extension for saving learning rate value after each batch lr_tracker = LearningRateTracker() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=[linear_decay, lr_tracker], set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() step = (learning_rate - learning_rate*decay_factor)/(saturate - start + 1) num_batches = np.ceil(dataset_size / float(batch_size)).astype(int) for i in xrange(epoch_num * num_batches): actual = lr_tracker.lr_rates[i] batches_seen = i + 1 if batches_seen < start: expected = learning_rate elif batches_seen >= saturate: expected = learning_rate*decay_factor elif (start <= batches_seen) and (batches_seen < saturate): expected = (decay_factor * learning_rate + (saturate - batches_seen) * step) if not np.allclose(actual, expected): raise AssertionError("After %d batches, expected learning rate to " "be %f, but it is %f." % (batches_seen, expected, actual)) def test_annealed_learning_rate(): # tests that the class AnnealedLearingRate in sgd.py # gets the learning rate properly over the training batches # it runs a small softmax and at the end checks the learning values. # the learning rates are expected to start changing at batch 'anneal_start' # After batch anneal_start, the learning rate should be # learning_rate * anneal_start/number of batches seen class LearningRateTracker(object): def __init__(self): self.lr_rates = [] def __call__(self, algorithm): self.lr_rates.append(algorithm.learning_rate.get_value()) dim = 3 dataset_size = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(dataset_size, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 15 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() anneal_start = 5 annealed_rate = AnnealedLearningRate(anneal_start=anneal_start) # including this extension for saving learning rate value after each batch lr_tracker = LearningRateTracker() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=[annealed_rate, lr_tracker], set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() num_batches = np.ceil(dataset_size / float(batch_size)).astype(int) for i in xrange(epoch_num * num_batches): actual = lr_tracker.lr_rates[i] batches_seen = i + 1 expected = learning_rate*min(1, float(anneal_start)/batches_seen) if not np.allclose(actual, expected): raise AssertionError("After %d batches, expected learning rate to " "be %f, but it is %f." % (batches_seen, expected, actual)) def test_linear_decay_over_epoch(): # tests that the class LinearDecayOverEpoch in sgd.py # gets the learning rate properly over the training epochs # it runs a small softmax and at the end checks the learning values. # the learning rates are expected to start changing at epoch 'start' by an # amount of 'step' specified below. # the decrease of the learning rate should continue linearly until we # reach epoch 'saturate' at which the learning rate equals # 'learning_rate * decay_factor' dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 15 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) start = 5 saturate = 10 decay_factor = 0.1 linear_decay = LinearDecayOverEpoch(start=start, saturate=saturate, decay_factor=decay_factor) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[linear_decay]) train.main_loop() lr = model.monitor.channels['learning_rate'] step = (learning_rate - learning_rate*decay_factor)/(saturate - start + 1) for i in xrange(epoch_num + 1): actual = lr.val_record[i] if i < start: expected = learning_rate elif i >= saturate: expected = learning_rate*decay_factor elif (start <= i) and (i < saturate): expected = decay_factor * learning_rate + (saturate - i) * step if not np.allclose(actual, expected): raise AssertionError("After %d epochs, expected learning rate to " "be %f, but it is %f." % (i, expected, actual)) def test_linear_decay_epoch_xfer(): # tests that the class LinearDecayOverEpoch in sgd.py # gets the epochs xfered over properly dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 6 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) start = 5 saturate = 10 decay_factor = 0.1 linear_decay = LinearDecayOverEpoch(start=start, saturate=saturate, decay_factor=decay_factor) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[linear_decay]) train.main_loop() lr = model.monitor.channels['learning_rate'] final_learning_rate = lr.val_record[-1] algorithm2 = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=EpochCounter(epoch_num+1, new_epochs=False), update_callbacks=None, set_batch_size=False) model_xfer = push_monitor(name="old_monitor", transfer_experience=True, model=model) linear_decay2 = LinearDecayOverEpoch(start=start, saturate=saturate, decay_factor=decay_factor) train2 = Train(dataset, model_xfer, algorithm2, save_path=None, save_freq=0, extensions=[linear_decay2]) train2.main_loop() lr_resume = model_xfer.monitor.channels['learning_rate'] resume_learning_rate = lr_resume.val_record[0] assert np.allclose(resume_learning_rate, final_learning_rate) def test_momentum_epoch_xfer(): # tests that the class MomentumAdjustor in learning_rate.py # gets the epochs xfered over properly dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 6 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False, learning_rule=Momentum(.4)) start = 1 saturate = 11 final_momentum = 0.9 momentum_adjustor = MomentumAdjustor(final_momentum=final_momentum, start=start, saturate=saturate) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[momentum_adjustor]) train.main_loop() mm = model.monitor.channels['momentum'] final_momentum_init = mm.val_record[-1] algorithm2 = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=EpochCounter(epoch_num+1, new_epochs=False), update_callbacks=None, set_batch_size=False, learning_rule=Momentum(.4)) model_xfer = push_monitor(name="old_monitor", transfer_experience=True, model=model) momentum_adjustor2 = MomentumAdjustor(final_momentum=final_momentum, start=start, saturate=saturate) train2 = Train(dataset, model_xfer, algorithm2, save_path=None, save_freq=0, extensions=[momentum_adjustor2]) train2.main_loop() assert np.allclose(model.monitor.channels['momentum'].val_record[0], final_momentum_init) def test_val_records_xfer(): # tests that the class push_motnior in learning_rate.py # gets the epochs xfered over properly dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 6 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0) train.main_loop() assert len(model.monitor.channels['objective'].val_record) ==\ model.monitor._epochs_seen + 1 final_obj = model.monitor.channels['objective'].val_record[-1] algorithm2 = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=EpochCounter(epoch_num+1, new_epochs=False), update_callbacks=None, set_batch_size=False) model_xfer = push_monitor(name="old_monitor", transfer_experience=True, model=model) train2 = Train(dataset, model_xfer, algorithm2, save_path=None, save_freq=0) train2.main_loop() assert np.allclose(model.monitor.channels['objective'].val_record[0], final_obj) assert len(model.monitor.channels['objective'].val_record) == 2 def test_save_records(): # tests that the flag save_records in class # push_monitor in learning_rate.py # gets the val_records xfered over properly dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(dim) learning_rate = 1e-1 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 6 termination_criterion = EpochCounter(epoch_num) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0) train.main_loop() old_monitor_len =\ len(model.monitor.channels['objective'].val_record) assert old_monitor_len == model.monitor._epochs_seen + 1 init_obj = model.monitor.channels['objective'].val_record[0] final_obj = model.monitor.channels['objective'].val_record[-1] index_final_obj =\ len(model.monitor.channels['objective'].val_record) - 1 algorithm2 = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=EpochCounter(epoch_num+1, new_epochs=False), update_callbacks=None, set_batch_size=False) model_xfer = push_monitor(name="old_monitor", transfer_experience=True, model=model, save_records=True) train2 = Train(dataset, model_xfer, algorithm2, save_path=None, save_freq=0) train2.main_loop() assert len(model.old_monitor.channels['objective'].val_record) ==\ old_monitor_len assert np.allclose(model.monitor.channels['objective'].val_record[0], init_obj) assert len(model.monitor.channels['objective'].val_record) ==\ model.monitor._epochs_seen + 1 assert len(model.monitor.channels['objective'].val_record) ==\ epoch_num + 2 assert model.monitor.channels['objective'].val_record[index_final_obj] ==\ final_obj def test_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py # gets the learning rate properly over the training epochs # it runs a small softmax and at the end checks the learning values. It # runs 2 loops. Each loop evaluates one of the if clauses when checking # the observation channels. Otherwise, longer training epochs are needed # to observe both if and elif cases. high_trigger = 1.0 shrink_amt = 0.99 low_trigger = 0.99 grow_amt = 1.01 min_lr = 1e-7 max_lr = 1. dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) dataset = DenseDesignMatrix(X=X) m = 15 X = rng.randn(m, dim) learning_rate = 1e-2 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 5 # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) cost = DummyCost() for i in xrange(2): if i == 1: high_trigger = 0.99 model = SoftmaxModel(dim) termination_criterion = EpochCounter(epoch_num) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) monitor_lr = MonitorBasedLRAdjuster(high_trigger=high_trigger, shrink_amt=shrink_amt, low_trigger=low_trigger, grow_amt=grow_amt, min_lr=min_lr, max_lr=max_lr) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[monitor_lr]) train.main_loop() v = model.monitor.channels['objective'].val_record lr = model.monitor.channels['learning_rate'].val_record lr_monitor = learning_rate for i in xrange(2, epoch_num + 1): if v[i-1] > high_trigger * v[i-2]: lr_monitor *= shrink_amt elif v[i-1] > low_trigger * v[i-2]: lr_monitor *= grow_amt lr_monitor = max(min_lr, lr_monitor) lr_monitor = min(max_lr, lr_monitor) assert np.allclose(lr_monitor, lr[i]) def test_bad_monitoring_input_in_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py avoids wrong # settings of channel_name or dataset_name in the constructor. dim = 3 m = 10 rng = np.random.RandomState([6, 2, 2014]) X = rng.randn(m, dim) learning_rate = 1e-2 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 2 dataset = DenseDesignMatrix(X=X) # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_dataset = DenseDesignMatrix(X=X) cost = DummyCost() model = SoftmaxModel(dim) termination_criterion = EpochCounter(epoch_num) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=2, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) # testing for bad dataset_name input dummy = 'void' monitor_lr = MonitorBasedLRAdjuster(dataset_name=dummy) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[monitor_lr]) try: train.main_loop() except ValueError as e: pass except Exception: reraise_as(AssertionError("MonitorBasedLRAdjuster takes dataset_name " "that is invalid ")) # testing for bad channel_name input monitor_lr2 = MonitorBasedLRAdjuster(channel_name=dummy) model2 = SoftmaxModel(dim) train2 = Train(dataset, model2, algorithm, save_path=None, save_freq=0, extensions=[monitor_lr2]) try: train2.main_loop() except ValueError as e: pass except Exception: reraise_as(AssertionError("MonitorBasedLRAdjuster takes channel_name " "that is invalid ")) return def testing_multiple_datasets_in_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py does not take # multiple datasets in which multiple channels ending in '_objective' # exist. # This case happens when the user has not specified either channel_name or # dataset_name in the constructor dim = 3 m = 10 rng = np.random.RandomState([6, 2, 2014]) X = rng.randn(m, dim) Y = rng.randn(m, dim) learning_rate = 1e-2 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 1 # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_train = DenseDesignMatrix(X=X) monitoring_test = DenseDesignMatrix(X=Y) cost = DummyCost() model = SoftmaxModel(dim) dataset = DenseDesignMatrix(X=X) termination_criterion = EpochCounter(epoch_num) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=2, monitoring_dataset={'train': monitoring_train, 'test': monitoring_test}, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) monitor_lr = MonitorBasedLRAdjuster() train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[monitor_lr]) try: train.main_loop() except ValueError: return raise AssertionError("MonitorBasedLRAdjuster takes multiple dataset names " "in which more than one \"objective\" channel exist " "and the user has not specified either channel_name " "or database_name in the constructor to " "disambiguate.") def testing_multiple_datasets_with_specified_dataset_in_monitor_based_lr(): # tests that the class MonitorBasedLRAdjuster in sgd.py can properly use # the spcified dataset_name in the constructor when multiple datasets # exist. dim = 3 m = 10 rng = np.random.RandomState([6, 2, 2014]) X = rng.randn(m, dim) Y = rng.randn(m, dim) learning_rate = 1e-2 batch_size = 5 # We need to include this so the test actually stops running at some point epoch_num = 1 # including a monitoring datasets lets us test that # the monitor works with supervised data monitoring_train = DenseDesignMatrix(X=X) monitoring_test = DenseDesignMatrix(X=Y) cost = DummyCost() model = SoftmaxModel(dim) dataset = DenseDesignMatrix(X=X) termination_criterion = EpochCounter(epoch_num) monitoring_dataset = {'train': monitoring_train, 'test': monitoring_test} algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=2, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) dataset_name = first_key(monitoring_dataset) monitor_lr = MonitorBasedLRAdjuster(dataset_name=dataset_name) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=[monitor_lr]) train.main_loop() def test_sgd_topo(): # tests that we can run the sgd algorithm # on data with topology # does not test for correctness at all, just # that the algorithm runs without dying rows = 3 cols = 4 channels = 2 dim = rows * cols * channels m = 10 rng = np.random.RandomState([25, 9, 2012]) dataset = get_topological_dataset(rng, rows, cols, channels, m) # including a monitoring datasets lets us test that # the monitor works with supervised data m = 15 monitoring_dataset = get_topological_dataset(rng, rows, cols, channels, m) model = TopoSoftmaxModel(rows, cols, channels) learning_rate = 1e-3 batch_size = 5 cost = SupervisedDummyCost() # We need to include this so the test actually stops running at some point termination_criterion = EpochCounter(5) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=monitoring_dataset, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def test_sgd_no_mon(): # tests that we can run the sgd algorithm # wihout a monitoring dataset # does not test for correctness at all, just # that the algorithm runs without dying dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) idx = rng.randint(0, dim, (m,)) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 dataset = DenseDesignMatrix(X=X, y=Y) m = 15 X = rng.randn(m, dim) idx = rng.randint(0, dim, (m,)) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 cost = SupervisedDummyCost() # We need to include this so the test actually stops running at some point termination_criterion = EpochCounter(5) algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_dataset=None, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def test_reject_mon_batch_without_mon(): # tests that setting up the sgd algorithm # without a monitoring dataset # but with monitoring_batches specified is an error dim = 3 m = 10 rng = np.random.RandomState([25, 9, 2012]) X = rng.randn(m, dim) idx = rng.randint(0, dim, (m,)) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 dataset = DenseDesignMatrix(X=X, y=Y) m = 15 X = rng.randn(m, dim) idx = rng.randint(0, dim, (m, )) Y = np.zeros((m, dim)) for i in xrange(m): Y[i, idx[i]] = 1 model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 cost = SupervisedDummyCost() try: algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_batches=3, monitoring_dataset=None, update_callbacks=None, set_batch_size=False) except ValueError: return assert False def test_sgd_sequential(): # tests that requesting train_iteration_mode = 'sequential' # works dim = 1 batch_size = 3 m = 5 * batch_size dataset = ArangeDataset(m) model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 visited = [False] * m def visit(X): assert X.shape[1] == 1 assert np.all(X[1:] == X[0:-1]+1) start = int(X[0, 0]) if start > 0: assert visited[start - 1] for i in xrange(batch_size): assert not visited[start+i] visited[start+i] = 1 data_specs = (model.get_input_space(), model.get_input_source()) cost = CallbackCost(visit, data_specs) # We need to include this so the test actually stops running at some point termination_criterion = EpochCounter(5) algorithm = SGD(learning_rate, cost, batch_size=batch_size, train_iteration_mode='sequential', monitoring_dataset=None, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) algorithm.setup(dataset=dataset, model=model) algorithm.train(dataset) assert all(visited) def test_determinism(): # Verifies that running SGD twice results in the same examples getting # visited in the same order for mode in _iteration_schemes: dim = 1 batch_size = 3 num_batches = 5 m = num_batches * batch_size dataset = ArangeDataset(m) model = SoftmaxModel(dim) learning_rate = 1e-3 batch_size = 5 visited = [[-1] * m] def visit(X): mx = max(visited[0]) counter = mx + 1 for i in X[:, 0]: i = int(i) assert visited[0][i] == -1 visited[0][i] = counter counter += 1 data_specs = (model.get_input_space(), model.get_input_source()) cost = CallbackCost(visit, data_specs) # We need to include this so the test actually stops running at some # point termination_criterion = EpochCounter(5) def run_algorithm(): unsupported_modes = ['random_slice', 'random_uniform'] algorithm = SGD(learning_rate, cost, batch_size=batch_size, train_iteration_mode=mode, monitoring_dataset=None, termination_criterion=termination_criterion, update_callbacks=None, set_batch_size=False) algorithm.setup(dataset=dataset, model=model) raised = False try: algorithm.train(dataset) except ValueError: print(mode) assert mode in unsupported_modes raised = True if mode in unsupported_modes: assert raised return True return False if run_algorithm(): continue visited.insert(0, [-1] * m) del model.monitor run_algorithm() for v in visited: assert len(v) == m for elem in range(m): assert elem in v assert len(visited) == 2 print(visited[0]) print(visited[1]) assert np.all(np.asarray(visited[0]) == np.asarray(visited[1])) def test_determinism_2(): """ A more aggressive determinism test. Tests that apply nodes are all passed inputs with the same md5sums, apply nodes are run in same order, etc. Uses disturb_mem to try to cause dictionaries to iterate in different orders, etc. """ def run_sgd(mode): # Must be seeded the same both times run_sgd is called disturb_mem.disturb_mem() rng = np.random.RandomState([2012, 11, 27]) batch_size = 5 train_batches = 3 valid_batches = 4 num_features = 2 # Synthesize dataset with a linear decision boundary w = rng.randn(num_features) def make_dataset(num_batches): disturb_mem.disturb_mem() m = num_batches*batch_size X = rng.randn(m, num_features) y = np.zeros((m, 1)) y[:, 0] = np.dot(X, w) > 0. rval = DenseDesignMatrix(X=X, y=y) rval.yaml_src = "" # suppress no yaml_src warning X = rval.get_batch_design(batch_size) assert X.shape == (batch_size, num_features) return rval train = make_dataset(train_batches) valid = make_dataset(valid_batches) num_chunks = 10 chunk_width = 2 class ManyParamsModel(Model): """ Make a model with lots of parameters, so that there are many opportunities for their updates to get accidentally re-ordered non-deterministically. This makes non-determinism bugs manifest more frequently. """ def __init__(self): super(ManyParamsModel, self).__init__() self.W1 = [sharedX(rng.randn(num_features, chunk_width)) for i in xrange(num_chunks)] disturb_mem.disturb_mem() self.W2 = [sharedX(rng.randn(chunk_width)) for i in xrange(num_chunks)] self._params = safe_union(self.W1, self.W2) self.input_space = VectorSpace(num_features) self.output_space = VectorSpace(1) disturb_mem.disturb_mem() model = ManyParamsModel() disturb_mem.disturb_mem() class LotsOfSummingCost(Cost): """ Make a cost whose gradient on the parameters involves summing many terms together, so that T.grad is more likely to sum things in a random order. """ supervised = True def expr(self, model, data, **kwargs): self.get_data_specs(model)[0].validate(data) X, Y = data disturb_mem.disturb_mem() def mlp_pred(non_linearity): Z = [T.dot(X, W) for W in model.W1] H = [non_linearity(z) for z in Z] Z = [T.dot(h, W) for h, W in safe_izip(H, model.W2)] pred = sum(Z) return pred nonlinearity_predictions = map(mlp_pred, [T.nnet.sigmoid, T.nnet.softplus, T.sqr, T.sin]) pred = sum(nonlinearity_predictions) disturb_mem.disturb_mem() return abs(pred-Y[:, 0]).sum() def get_data_specs(self, model): data = CompositeSpace((model.get_input_space(), model.get_output_space())) source = (model.get_input_source(), model.get_target_source()) return (data, source) cost = LotsOfSummingCost() disturb_mem.disturb_mem() algorithm = SGD(cost=cost, batch_size=batch_size, learning_rule=Momentum(.5), learning_rate=1e-3, monitoring_dataset={'train': train, 'valid': valid}, update_callbacks=[ExponentialDecay(decay_factor=2., min_lr=.0001)], termination_criterion=EpochCounter(max_epochs=5)) disturb_mem.disturb_mem() train_object = Train(dataset=train, model=model, algorithm=algorithm, extensions=[PolyakAveraging(start=0), MomentumAdjustor(final_momentum=.9, start=1, saturate=5), ], save_freq=0) disturb_mem.disturb_mem() train_object.main_loop() output = cStringIO() record = Record(file_object=output, replay=False) record_mode = RecordMode(record) run_sgd(record_mode) output = cStringIO(output.getvalue()) playback = Record(file_object=output, replay=True) playback_mode = RecordMode(playback) run_sgd(playback_mode) def test_lr_scalers(): """ Tests that SGD respects Model.get_lr_scalers """ # We include a cost other than SumOfParams so that data is actually # queried from the training set, and the expected number of updates # are applied. cost = SumOfCosts([SumOfParams(), (0., DummyCost())]) scales = [.01, .02, .05, 1., 5.] shapes = [(1,), (9,), (8, 7), (6, 5, 4), (3, 2, 2, 2)] learning_rate = .001 class ModelWithScalers(Model): def __init__(self): super(ModelWithScalers, self).__init__() self._params = [sharedX(np.zeros(shape)) for shape in shapes] self.input_space = VectorSpace(1) def __call__(self, X): # Implemented only so that DummyCost would work return X def get_lr_scalers(self): return dict(zip(self._params, scales)) model = ModelWithScalers() dataset = ArangeDataset(1) sgd = SGD(cost=cost, learning_rate=learning_rate, learning_rule=Momentum(.0), batch_size=1) sgd.setup(model=model, dataset=dataset) manual = [param.get_value() for param in model.get_params()] manual = [param - learning_rate * scale for param, scale in zip(manual, scales)] sgd.train(dataset=dataset) assert all(np.allclose(manual_param, sgd_param.get_value()) for manual_param, sgd_param in zip(manual, model.get_params())) manual = [param - learning_rate * scale for param, scale in zip(manual, scales)] sgd.train(dataset=dataset) assert all(np.allclose(manual_param, sgd_param.get_value()) for manual_param, sgd_param in zip(manual, model.get_params())) def test_lr_scalers_momentum(): """ Tests that SGD respects Model.get_lr_scalers when using momentum. """ # We include a cost other than SumOfParams so that data is actually # queried from the training set, and the expected number of updates # are applied. cost = SumOfCosts([SumOfParams(), (0., DummyCost())]) scales = [.01, .02, .05, 1., 5.] shapes = [(1,), (9,), (8, 7), (6, 5, 4), (3, 2, 2, 2)] model = DummyModel(shapes, lr_scalers=scales) dataset = ArangeDataset(1) learning_rate = .001 momentum = 0.5 sgd = SGD(cost=cost, learning_rate=learning_rate, learning_rule=Momentum(momentum), batch_size=1) sgd.setup(model=model, dataset=dataset) manual = [param.get_value() for param in model.get_params()] inc = [-learning_rate * scale for param, scale in zip(manual, scales)] manual = [param + i for param, i in zip(manual, inc)] sgd.train(dataset=dataset) assert all(np.allclose(manual_param, sgd_param.get_value()) for manual_param, sgd_param in zip(manual, model.get_params())) manual = [param - learning_rate * scale + i * momentum for param, scale, i in zip(manual, scales, inc)] sgd.train(dataset=dataset) assert all(np.allclose(manual_param, sgd_param.get_value()) for manual_param, sgd_param in zip(manual, model.get_params())) def test_batch_size_specialization(): # Tests that using a batch size of 1 for training and a batch size # other than 1 for monitoring does not result in a crash. # This catches a bug reported in the [email protected] # e-mail "[pylearn-dev] monitor assertion error: channel_X.type != X.type" # The training data was specialized to a row matrix (theano tensor with # first dim broadcastable) and the monitor ended up with expressions # mixing the specialized and non-specialized version of the expression. m = 2 rng = np.random.RandomState([25, 9, 2012]) X = np.zeros((m, 1)) dataset = DenseDesignMatrix(X=X) model = SoftmaxModel(1) learning_rate = 1e-3 cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=1, monitoring_batches=1, monitoring_dataset=dataset, termination_criterion=EpochCounter(max_epochs=1), update_callbacks=None, set_batch_size=False) train = Train(dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def test_empty_monitoring_datasets(): """ Test that handling of monitoring datasets dictionnary does not fail when it is empty. """ learning_rate = 1e-3 batch_size = 5 dim = 3 rng = np.random.RandomState([25, 9, 2012]) train_dataset = DenseDesignMatrix(X=rng.randn(10, dim)) model = SoftmaxModel(dim) cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, monitoring_dataset={}, termination_criterion=EpochCounter(2)) train = Train(train_dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() def test_uneven_batch_size(): """ Testing extensively sgd parametrisations for datasets with a number of examples not divisible by batch size The tested settings are: - Model with force_batch_size = True or False - Training dataset with number of examples divisible or not by batch size - Monitoring dataset with number of examples divisible or not by batch size - Even or uneven iterators 2 tests out of 10 should raise ValueError """ learning_rate = 1e-3 batch_size = 5 dim = 3 m1, m2, m3 = 10, 15, 22 rng = np.random.RandomState([25, 9, 2012]) dataset1 = DenseDesignMatrix(X=rng.randn(m1, dim)) dataset2 = DenseDesignMatrix(X=rng.randn(m2, dim)) dataset3 = DenseDesignMatrix(X=rng.randn(m3, dim)) def train_with_monitoring_datasets(train_dataset, monitoring_datasets, model_force_batch_size, train_iteration_mode, monitor_iteration_mode): model = SoftmaxModel(dim) if model_force_batch_size: model.force_batch_size = model_force_batch_size cost = DummyCost() algorithm = SGD(learning_rate, cost, batch_size=batch_size, train_iteration_mode=train_iteration_mode, monitor_iteration_mode=monitor_iteration_mode, monitoring_dataset=monitoring_datasets, termination_criterion=EpochCounter(2)) train = Train(train_dataset, model, algorithm, save_path=None, save_freq=0, extensions=None) train.main_loop() no_monitoring_datasets = None even_monitoring_datasets = {'valid': dataset2} uneven_monitoring_datasets = {'valid': dataset2, 'test': dataset3} # without monitoring datasets train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=no_monitoring_datasets, model_force_batch_size=False, train_iteration_mode='sequential', monitor_iteration_mode='sequential') train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=no_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='sequential', monitor_iteration_mode='sequential') # with uneven training datasets train_with_monitoring_datasets( train_dataset=dataset3, monitoring_datasets=no_monitoring_datasets, model_force_batch_size=False, train_iteration_mode='sequential', monitor_iteration_mode='sequential') try: train_with_monitoring_datasets( train_dataset=dataset3, monitoring_datasets=no_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='sequential', monitor_iteration_mode='sequential') assert False except ValueError: pass train_with_monitoring_datasets( train_dataset=dataset3, monitoring_datasets=no_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='even_sequential', monitor_iteration_mode='sequential') # with even monitoring datasets train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=even_monitoring_datasets, model_force_batch_size=False, train_iteration_mode='sequential', monitor_iteration_mode='sequential') train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=even_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='sequential', monitor_iteration_mode='sequential') # with uneven monitoring datasets train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=uneven_monitoring_datasets, model_force_batch_size=False, train_iteration_mode='sequential', monitor_iteration_mode='sequential') try: train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=uneven_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='sequential', monitor_iteration_mode='sequential') assert False except ValueError: pass train_with_monitoring_datasets( train_dataset=dataset1, monitoring_datasets=uneven_monitoring_datasets, model_force_batch_size=batch_size, train_iteration_mode='sequential', monitor_iteration_mode='even_sequential') def test_epoch_monitor(): """ Checks that monitored channels contain expected number of values when using EpochMonitor for updates within epochs. """ dim = 1 batch_size = 3 n_batches = 10 m = n_batches * batch_size dataset = ArangeDataset(m) model = SoftmaxModel(dim) monitor = Monitor.get_monitor(model) learning_rate = 1e-3 data_specs = (model.get_input_space(), model.get_input_source()) cost = DummyCost() termination_criterion = EpochCounter(1) monitor_rate = 3 em = EpochMonitor(model=model, tick_rate=None, monitor_rate=monitor_rate) algorithm = SGD(learning_rate, cost, batch_size=batch_size, train_iteration_mode='sequential', monitoring_dataset=dataset, termination_criterion=termination_criterion, update_callbacks=[em], set_batch_size=False) algorithm.setup(dataset=dataset, model=model) algorithm.train(dataset) for key, val in monitor.channels.items(): assert len(val.val_record) == n_batches//monitor_rate if __name__ == '__main__': test_monitor_based_lr()
bartvm/pylearn2
pylearn2/training_algorithms/tests/test_sgd.py
Python
bsd-3-clause
60,639
<?php /** * BMFlagValueRelevantToScore: Code specific to forcing a die to display its value * * @author: james */ /** * This class allows dice to be flagged as always needing to show their values. * This was added specifically to support value dice. */ class BMFlagValueRelevantToScore extends BMFlag { }
dwvanstone/buttonmen
src/engine/BMFlagValueRelevantToScore.php
PHP
bsd-3-clause
314
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "printing/printing_context_no_system_dialog.h" #include <stdint.h> #include <unicode/ulocdata.h> #include "base/logging.h" #include "base/memory/ptr_util.h" #include "base/values.h" #include "printing/metafile.h" #include "printing/print_job_constants.h" #include "printing/units.h" namespace printing { // static std::unique_ptr<PrintingContext> PrintingContext::Create(Delegate* delegate) { return base::WrapUnique(new PrintingContextNoSystemDialog(delegate)); } PrintingContextNoSystemDialog::PrintingContextNoSystemDialog(Delegate* delegate) : PrintingContext(delegate) { } PrintingContextNoSystemDialog::~PrintingContextNoSystemDialog() { ReleaseContext(); } void PrintingContextNoSystemDialog::AskUserForSettings( int max_pages, bool has_selection, bool is_scripted, const PrintSettingsCallback& callback) { // We don't want to bring up a dialog here. Ever. Just signal the callback. callback.Run(OK); } PrintingContext::Result PrintingContextNoSystemDialog::UseDefaultSettings() { DCHECK(!in_print_job_); ResetSettings(); settings_.set_dpi(kDefaultPdfDpi); gfx::Size physical_size = GetPdfPaperSizeDeviceUnits(); // Assume full page is printable for now. gfx::Rect printable_area(0, 0, physical_size.width(), physical_size.height()); DCHECK_EQ(settings_.device_units_per_inch(), kDefaultPdfDpi); settings_.SetPrinterPrintableArea(physical_size, printable_area, true); return OK; } gfx::Size PrintingContextNoSystemDialog::GetPdfPaperSizeDeviceUnits() { int32_t width = 0; int32_t height = 0; UErrorCode error = U_ZERO_ERROR; ulocdata_getPaperSize( delegate_->GetAppLocale().c_str(), &height, &width, &error); if (error > U_ZERO_ERROR) { // If the call failed, assume a paper size of 8.5 x 11 inches. LOG(WARNING) << "ulocdata_getPaperSize failed, using 8.5 x 11, error: " << error; width = static_cast<int>( kLetterWidthInch * settings_.device_units_per_inch()); height = static_cast<int>( kLetterHeightInch * settings_.device_units_per_inch()); } else { // ulocdata_getPaperSize returns the width and height in mm. // Convert this to pixels based on the dpi. float multiplier = 100 * settings_.device_units_per_inch(); multiplier /= kHundrethsMMPerInch; width *= multiplier; height *= multiplier; } return gfx::Size(width, height); } PrintingContext::Result PrintingContextNoSystemDialog::UpdatePrinterSettings( bool external_preview, bool show_system_dialog, int page_count) { DCHECK(!show_system_dialog); if (settings_.dpi() == 0) UseDefaultSettings(); return OK; } PrintingContext::Result PrintingContextNoSystemDialog::InitWithSettings( const PrintSettings& settings) { DCHECK(!in_print_job_); settings_ = settings; return OK; } PrintingContext::Result PrintingContextNoSystemDialog::NewDocument( const base::string16& document_name) { DCHECK(!in_print_job_); in_print_job_ = true; return OK; } PrintingContext::Result PrintingContextNoSystemDialog::NewPage() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); // Intentional No-op. return OK; } PrintingContext::Result PrintingContextNoSystemDialog::PageDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); // Intentional No-op. return OK; } PrintingContext::Result PrintingContextNoSystemDialog::DocumentDone() { if (abort_printing_) return CANCEL; DCHECK(in_print_job_); ResetSettings(); return OK; } void PrintingContextNoSystemDialog::Cancel() { abort_printing_ = true; in_print_job_ = false; } void PrintingContextNoSystemDialog::ReleaseContext() { // Intentional No-op. } gfx::NativeDrawingContext PrintingContextNoSystemDialog::context() const { // Intentional No-op. return NULL; } } // namespace printing
axinging/chromium-crosswalk
printing/printing_context_no_system_dialog.cc
C++
bsd-3-clause
4,045
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/payments/content/android/payment_app_service_bridge.h" #include <string> #include <vector> #include "base/android/jni_array.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "base/bind.h" #include "base/check_op.h" #include "base/memory/singleton.h" #include "base/notreached.h" #include "components/payments/content/android/byte_buffer_helper.h" #include "components/payments/content/android/jni_headers/PaymentAppServiceBridge_jni.h" #include "components/payments/content/android/jni_payment_app.h" #include "components/payments/content/android/payment_request_spec.h" #include "components/payments/content/payment_app_service.h" #include "components/payments/content/payment_app_service_factory.h" #include "components/payments/content/payment_manifest_web_data_service.h" #include "components/payments/content/payment_request_spec.h" #include "components/url_formatter/elide_url.h" #include "components/webauthn/android/internal_authenticator_android.h" #include "components/webdata_services/web_data_service_wrapper_factory.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/web_contents.h" #include "third_party/blink/public/mojom/payments/payment_app.mojom.h" #include "third_party/blink/public/mojom/payments/payment_request.mojom.h" #include "ui/gfx/android/java_bitmap.h" #include "url/android/gurl_android.h" #include "url/origin.h" namespace { using ::base::android::AttachCurrentThread; using ::base::android::ConvertJavaStringToUTF8; using ::base::android::ConvertUTF8ToJavaString; using ::base::android::JavaParamRef; using ::base::android::JavaRef; using ::base::android::ScopedJavaGlobalRef; using ::payments::mojom::PaymentMethodDataPtr; void OnCanMakePaymentCalculated(const JavaRef<jobject>& jcallback, bool can_make_payment) { Java_PaymentAppServiceCallback_onCanMakePaymentCalculated( AttachCurrentThread(), jcallback, can_make_payment); } void OnPaymentAppCreated(const JavaRef<jobject>& jcallback, std::unique_ptr<payments::PaymentApp> payment_app) { JNIEnv* env = AttachCurrentThread(); Java_PaymentAppServiceCallback_onPaymentAppCreated( env, jcallback, payments::JniPaymentApp::Create(env, std::move(payment_app))); } void OnPaymentAppCreationError( const JavaRef<jobject>& jcallback, const std::string& error_message, payments::AppCreationFailureReason error_reason) { JNIEnv* env = AttachCurrentThread(); Java_PaymentAppServiceCallback_onPaymentAppCreationError( env, jcallback, ConvertUTF8ToJavaString(env, error_message), static_cast<jint>(error_reason)); } void OnDoneCreatingPaymentApps(const JavaRef<jobject>& jcallback) { JNIEnv* env = AttachCurrentThread(); Java_PaymentAppServiceCallback_onDoneCreatingPaymentApps(env, jcallback); } void SetCanMakePaymentEvenWithoutApps(const JavaRef<jobject>& jcallback) { JNIEnv* env = AttachCurrentThread(); if (!env) return; Java_PaymentAppServiceCallback_setCanMakePaymentEvenWithoutApps(env, jcallback); } } // namespace /* static */ void JNI_PaymentAppServiceBridge_Create( JNIEnv* env, const JavaParamRef<jobject>& jrender_frame_host, const JavaParamRef<jstring>& jtop_origin, const JavaParamRef<jobject>& jpayment_request_spec, const JavaParamRef<jstring>& jtwa_package_name, jboolean jmay_crawl_for_installable_payment_apps, jboolean jis_off_the_record, const JavaParamRef<jobject>& jcallback) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); auto* render_frame_host = content::RenderFrameHost::FromJavaRenderFrameHost(jrender_frame_host); if (!render_frame_host) // The frame is being unloaded. return; std::string top_origin = ConvertJavaStringToUTF8(jtop_origin); scoped_refptr<payments::PaymentManifestWebDataService> web_data_service = webdata_services::WebDataServiceWrapperFactory:: GetPaymentManifestWebDataServiceForBrowserContext( render_frame_host->GetBrowserContext(), ServiceAccessType::EXPLICIT_ACCESS); payments::PaymentAppService* service = payments::PaymentAppServiceFactory::GetForContext( render_frame_host->GetBrowserContext()); auto* bridge = payments::PaymentAppServiceBridge::Create( service->GetNumberOfFactories(), render_frame_host, GURL(top_origin), payments::android::PaymentRequestSpec::FromJavaPaymentRequestSpec( env, jpayment_request_spec), jtwa_package_name ? ConvertJavaStringToUTF8(env, jtwa_package_name) : "", web_data_service, jmay_crawl_for_installable_payment_apps, jis_off_the_record, base::BindOnce(&OnCanMakePaymentCalculated, ScopedJavaGlobalRef<jobject>(env, jcallback)), base::BindRepeating(&OnPaymentAppCreated, ScopedJavaGlobalRef<jobject>(env, jcallback)), base::BindRepeating(&OnPaymentAppCreationError, ScopedJavaGlobalRef<jobject>(env, jcallback)), base::BindOnce(&OnDoneCreatingPaymentApps, ScopedJavaGlobalRef<jobject>(env, jcallback)), base::BindRepeating(&SetCanMakePaymentEvenWithoutApps, ScopedJavaGlobalRef<jobject>(env, jcallback))); service->Create(bridge->GetWeakPtr()); } namespace payments { namespace { // A singleton class to maintain ownership of PaymentAppServiceBridge objects // until Remove() is called. class PaymentAppServiceBridgeStorage { public: static PaymentAppServiceBridgeStorage* GetInstance() { return base::Singleton<PaymentAppServiceBridgeStorage>::get(); } PaymentAppServiceBridge* Add(std::unique_ptr<PaymentAppServiceBridge> owned) { DCHECK(owned); PaymentAppServiceBridge* key = owned.get(); owner_[key] = std::move(owned); return key; } void Remove(PaymentAppServiceBridge* owned) { size_t number_of_deleted_objects = owner_.erase(owned); DCHECK_EQ(1U, number_of_deleted_objects); } private: friend struct base::DefaultSingletonTraits<PaymentAppServiceBridgeStorage>; PaymentAppServiceBridgeStorage() = default; ~PaymentAppServiceBridgeStorage() = default; std::map<PaymentAppServiceBridge*, std::unique_ptr<PaymentAppServiceBridge>> owner_; }; } // namespace /* static */ PaymentAppServiceBridge* PaymentAppServiceBridge::Create( size_t number_of_factories, content::RenderFrameHost* render_frame_host, const GURL& top_origin, base::WeakPtr<PaymentRequestSpec> spec, const std::string& twa_package_name, scoped_refptr<PaymentManifestWebDataService> web_data_service, bool may_crawl_for_installable_payment_apps, bool is_off_the_record, CanMakePaymentCalculatedCallback can_make_payment_calculated_callback, PaymentAppCreatedCallback payment_app_created_callback, PaymentAppCreationErrorCallback payment_app_creation_error_callback, base::OnceClosure done_creating_payment_apps_callback, base::RepeatingClosure set_can_make_payment_even_without_apps_callback) { DCHECK(render_frame_host); // Not using std::make_unique, because that requires a public constructor. std::unique_ptr<PaymentAppServiceBridge> bridge(new PaymentAppServiceBridge( number_of_factories, render_frame_host, top_origin, spec, twa_package_name, std::move(web_data_service), may_crawl_for_installable_payment_apps, is_off_the_record, std::move(can_make_payment_calculated_callback), std::move(payment_app_created_callback), std::move(payment_app_creation_error_callback), std::move(done_creating_payment_apps_callback), std::move(set_can_make_payment_even_without_apps_callback))); return PaymentAppServiceBridgeStorage::GetInstance()->Add(std::move(bridge)); } PaymentAppServiceBridge::PaymentAppServiceBridge( size_t number_of_factories, content::RenderFrameHost* render_frame_host, const GURL& top_origin, base::WeakPtr<PaymentRequestSpec> spec, const std::string& twa_package_name, scoped_refptr<PaymentManifestWebDataService> web_data_service, bool may_crawl_for_installable_payment_apps, bool is_off_the_record, CanMakePaymentCalculatedCallback can_make_payment_calculated_callback, PaymentAppCreatedCallback payment_app_created_callback, PaymentAppCreationErrorCallback payment_app_creation_error_callback, base::OnceClosure done_creating_payment_apps_callback, base::RepeatingClosure set_can_make_payment_even_without_apps_callback) : number_of_pending_factories_(number_of_factories), frame_routing_id_(render_frame_host->GetGlobalId()), top_origin_(top_origin), frame_origin_(url_formatter::FormatUrlForSecurityDisplay( render_frame_host->GetLastCommittedURL())), frame_security_origin_(render_frame_host->GetLastCommittedOrigin()), spec_(spec), twa_package_name_(twa_package_name), payment_manifest_web_data_service_(web_data_service), may_crawl_for_installable_payment_apps_( may_crawl_for_installable_payment_apps), is_off_the_record_(is_off_the_record), can_make_payment_calculated_callback_( std::move(can_make_payment_calculated_callback)), payment_app_created_callback_(std::move(payment_app_created_callback)), payment_app_creation_error_callback_( std::move(payment_app_creation_error_callback)), done_creating_payment_apps_callback_( std::move(done_creating_payment_apps_callback)), set_can_make_payment_even_without_apps_callback_( std::move(set_can_make_payment_even_without_apps_callback)) {} PaymentAppServiceBridge::~PaymentAppServiceBridge() = default; base::WeakPtr<PaymentAppServiceBridge> PaymentAppServiceBridge::GetWeakPtr() { return weak_ptr_factory_.GetWeakPtr(); } content::WebContents* PaymentAppServiceBridge::GetWebContents() { auto* rfh = content::RenderFrameHost::FromID(frame_routing_id_); return rfh && rfh->IsActive() ? content::WebContents::FromRenderFrameHost(rfh) : nullptr; } const GURL& PaymentAppServiceBridge::GetTopOrigin() { return top_origin_; } const GURL& PaymentAppServiceBridge::GetFrameOrigin() { return frame_origin_; } const url::Origin& PaymentAppServiceBridge::GetFrameSecurityOrigin() { return frame_security_origin_; } content::RenderFrameHost* PaymentAppServiceBridge::GetInitiatorRenderFrameHost() const { return content::RenderFrameHost::FromID(frame_routing_id_); } content::GlobalRenderFrameHostId PaymentAppServiceBridge::GetInitiatorRenderFrameHostId() const { return frame_routing_id_; } const std::vector<PaymentMethodDataPtr>& PaymentAppServiceBridge::GetMethodData() const { DCHECK(spec_); return spec_->method_data(); } std::unique_ptr<webauthn::InternalAuthenticator> PaymentAppServiceBridge::CreateInternalAuthenticator() const { // This authenticator can be used in a cross-origin iframe only if the // top-level frame allowed it with Permissions Policy, e.g., with // allow="payment" iframe attribute. The secure payment confirmation dialog // displays the top-level origin in its UI before the user can click on the // [Verify] button to invoke this authenticator. auto* rfh = content::RenderFrameHost::FromID(frame_routing_id_); // Lifetime of the created authenticator is externally managed by the // authenticator factory, but is generally tied to the RenderFrame by // listening for `RenderFrameDeleted()`. Check `IsRenderFrameLive()` as a // safety precaution to ensure that `RenderFrameDeleted()` will be called at // some point. return rfh && rfh->IsActive() && rfh->IsRenderFrameLive() ? std::make_unique<InternalAuthenticatorAndroid>(rfh) : nullptr; } scoped_refptr<PaymentManifestWebDataService> PaymentAppServiceBridge::GetPaymentManifestWebDataService() const { return payment_manifest_web_data_service_; } bool PaymentAppServiceBridge::MayCrawlForInstallablePaymentApps() { return may_crawl_for_installable_payment_apps_; } bool PaymentAppServiceBridge::IsOffTheRecord() const { return is_off_the_record_; } const std::vector<autofill::AutofillProfile*>& PaymentAppServiceBridge::GetBillingProfiles() { // PaymentAppService flow should have short-circuited before this point. NOTREACHED(); return dummy_profiles_; } bool PaymentAppServiceBridge::IsRequestedAutofillDataAvailable() { // PaymentAppService flow should have short-circuited before this point. NOTREACHED(); return false; } base::WeakPtr<ContentPaymentRequestDelegate> PaymentAppServiceBridge::GetPaymentRequestDelegate() const { // PaymentAppService flow should have short-circuited before this point. NOTREACHED(); return nullptr; } void PaymentAppServiceBridge::ShowProcessingSpinner() { // Java UI determines when the show a spinner itself. } base::WeakPtr<PaymentRequestSpec> PaymentAppServiceBridge::GetSpec() const { return spec_; } std::string PaymentAppServiceBridge::GetTwaPackageName() const { return twa_package_name_; } void PaymentAppServiceBridge::OnPaymentAppCreated( std::unique_ptr<PaymentApp> app) { if (can_make_payment_calculated_callback_) std::move(can_make_payment_calculated_callback_).Run(true); payment_app_created_callback_.Run(std::move(app)); } bool PaymentAppServiceBridge::SkipCreatingNativePaymentApps() const { return true; } void PaymentAppServiceBridge::OnPaymentAppCreationError( const std::string& error_message, AppCreationFailureReason error_reason) { payment_app_creation_error_callback_.Run(error_message, error_reason); } void PaymentAppServiceBridge::OnDoneCreatingPaymentApps() { if (number_of_pending_factories_ > 1U) { number_of_pending_factories_--; return; } DCHECK_EQ(1U, number_of_pending_factories_); if (can_make_payment_calculated_callback_) std::move(can_make_payment_calculated_callback_).Run(false); std::move(done_creating_payment_apps_callback_).Run(); PaymentAppServiceBridgeStorage::GetInstance()->Remove(this); } void PaymentAppServiceBridge::SetCanMakePaymentEvenWithoutApps() { set_can_make_payment_even_without_apps_callback_.Run(); } } // namespace payments
chromium/chromium
components/payments/content/android/payment_app_service_bridge.cc
C++
bsd-3-clause
14,652
package main import ( "encoding/json" "fmt" "io" "log" "net/http" "regexp" "strconv" "strings" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/go-sql" "github.com/flynn/flynn/Godeps/_workspace/src/github.com/flynn/que-go" "github.com/flynn/flynn/Godeps/_workspace/src/golang.org/x/net/context" "github.com/flynn/flynn/controller/name" "github.com/flynn/flynn/controller/schema" ct "github.com/flynn/flynn/controller/types" "github.com/flynn/flynn/controller/utils" logaggc "github.com/flynn/flynn/logaggregator/client" "github.com/flynn/flynn/pkg/ctxhelper" "github.com/flynn/flynn/pkg/httphelper" "github.com/flynn/flynn/pkg/postgres" "github.com/flynn/flynn/pkg/random" "github.com/flynn/flynn/pkg/sse" routerc "github.com/flynn/flynn/router/client" "github.com/flynn/flynn/router/types" ) type AppRepo struct { router routerc.Client defaultDomain string db *postgres.DB } type appUpdate map[string]interface{} func NewAppRepo(db *postgres.DB, defaultDomain string, router routerc.Client) *AppRepo { return &AppRepo{db: db, defaultDomain: defaultDomain, router: router} } func (r *AppRepo) Add(data interface{}) error { app := data.(*ct.App) tx, err := r.db.Begin() if err != nil { return err } if app.Name == "" { var nameID uint32 if err := tx.QueryRow("SELECT nextval('name_ids')").Scan(&nameID); err != nil { tx.Rollback() return err } app.Name = name.Get(nameID) } if len(app.Name) > 100 || !utils.AppNamePattern.MatchString(app.Name) { return ct.ValidationError{Field: "name", Message: "is invalid"} } if app.ID == "" { app.ID = random.UUID() } if app.Strategy == "" { app.Strategy = "all-at-once" } meta, err := json.Marshal(app.Meta) if err != nil { return err } if err := tx.QueryRow("INSERT INTO apps (app_id, name, meta, strategy) VALUES ($1, $2, $3, $4) RETURNING created_at, updated_at", app.ID, app.Name, meta, app.Strategy).Scan(&app.CreatedAt, &app.UpdatedAt); err != nil { tx.Rollback() if postgres.IsUniquenessError(err, "apps_name_idx") { return httphelper.ObjectExistsErr(fmt.Sprintf("application %q already exists", app.Name)) } return err } if err := createEvent(tx.Exec, &ct.Event{ AppID: app.ID, ObjectID: app.ID, ObjectType: ct.EventTypeApp, }, app); err != nil { tx.Rollback() return err } if err := tx.Commit(); err != nil { return err } if !app.System() && r.defaultDomain != "" { route := (&router.HTTPRoute{ Domain: fmt.Sprintf("%s.%s", app.Name, r.defaultDomain), Service: app.Name + "-web", }).ToRoute() if err := createRoute(r.db, r.router, app.ID, route); err != nil { log.Printf("Error creating default route for %s: %s", app.Name, err) } } return nil } func scanApp(s postgres.Scanner) (*ct.App, error) { app := &ct.App{} var meta []byte var releaseID *string err := s.Scan(&app.ID, &app.Name, &meta, &app.Strategy, &releaseID, &app.CreatedAt, &app.UpdatedAt) if err == sql.ErrNoRows { return nil, ErrNotFound } else if err != nil { return nil, err } if releaseID != nil { app.ReleaseID = *releaseID } if len(meta) > 0 { err = json.Unmarshal(meta, &app.Meta) } return app, err } var idPattern = regexp.MustCompile(`^[a-f0-9]{8}-?([a-f0-9]{4}-?){3}[a-f0-9]{12}$`) type rowQueryer interface { QueryRow(query string, args ...interface{}) postgres.Scanner } func selectApp(db rowQueryer, id string, update bool) (*ct.App, error) { query := "SELECT app_id, name, meta, strategy, release_id, created_at, updated_at FROM apps WHERE deleted_at IS NULL AND " var suffix string if update { suffix = " FOR UPDATE" } var row postgres.Scanner if idPattern.MatchString(id) { row = db.QueryRow(query+"(app_id = $1 OR name = $2) LIMIT 1"+suffix, id, id) } else { row = db.QueryRow(query+"name = $1"+suffix, id) } return scanApp(row) } func (r *AppRepo) Get(id string) (interface{}, error) { return selectApp(r.db, id, false) } func (r *AppRepo) Update(id string, data map[string]interface{}) (interface{}, error) { tx, err := r.db.Begin() if err != nil { return nil, err } app, err := selectApp(tx, id, true) if err != nil { tx.Rollback() return nil, err } for k, v := range data { switch k { case "strategy": strategy, ok := v.(string) if !ok { tx.Rollback() return nil, fmt.Errorf("controller: expected string, got %T", v) } app.Strategy = strategy if _, err := tx.Exec("UPDATE apps SET strategy = $2, updated_at = now() WHERE app_id = $1", app.ID, app.Strategy); err != nil { tx.Rollback() return nil, err } case "meta": data, ok := v.(map[string]interface{}) if !ok { tx.Rollback() return nil, fmt.Errorf("controller: expected map[string]interface{}, got %T", v) } app.Meta = make(map[string]string, len(data)) for k, v := range data { s, ok := v.(string) if !ok { tx.Rollback() return nil, fmt.Errorf("controller: expected string, got %T", v) } app.Meta[k] = s } meta, err := json.Marshal(app.Meta) if err != nil { tx.Rollback() return nil, err } if _, err := tx.Exec("UPDATE apps SET meta = $2, updated_at = now() WHERE app_id = $1", app.ID, meta); err != nil { tx.Rollback() return nil, err } } } if err := createEvent(tx.Exec, &ct.Event{ AppID: app.ID, ObjectID: app.ID, ObjectType: ct.EventTypeApp, }, app); err != nil { tx.Rollback() return nil, err } return app, tx.Commit() } func (r *AppRepo) List() (interface{}, error) { rows, err := r.db.Query("SELECT app_id, name, meta, strategy, release_id, created_at, updated_at FROM apps WHERE deleted_at IS NULL ORDER BY created_at DESC") if err != nil { return nil, err } apps := []*ct.App{} for rows.Next() { app, err := scanApp(rows) if err != nil { rows.Close() return nil, err } apps = append(apps, app) } return apps, rows.Err() } func (r *AppRepo) SetRelease(app *ct.App, releaseID string) error { tx, err := r.db.Begin() if err != nil { return err } var release *ct.Release row := tx.QueryRow("SELECT release_id, artifact_id, data, created_at FROM releases WHERE release_id = $1 AND deleted_at IS NULL", releaseID) if release, err = scanRelease(row); err != nil { return err } app.ReleaseID = releaseID if _, err := tx.Exec("UPDATE apps SET release_id = $2, updated_at = now() WHERE app_id = $1", app.ID, app.ReleaseID); err != nil { tx.Rollback() return err } if err := createEvent(tx.Exec, &ct.Event{ AppID: app.ID, ObjectID: release.ID, ObjectType: ct.EventTypeAppRelease, }, release); err != nil { tx.Rollback() return err } return tx.Commit() } func (r *AppRepo) GetRelease(id string) (*ct.Release, error) { row := r.db.QueryRow("SELECT r.release_id, r.artifact_id, r.data, r.created_at FROM apps a JOIN releases r USING (release_id) WHERE a.app_id = $1", id) return scanRelease(row) } func (c *controllerAPI) UpdateApp(ctx context.Context, rw http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) var data appUpdate if err := httphelper.DecodeJSON(req, &data); err != nil { respondWithError(rw, err) return } if err := schema.Validate(data); err != nil { respondWithError(rw, err) return } app, err := c.appRepo.Update(params.ByName("apps_id"), data) if err != nil { respondWithError(rw, err) return } httphelper.JSON(rw, 200, app) } func (c *controllerAPI) UpdateAppMeta(ctx context.Context, rw http.ResponseWriter, req *http.Request) { params, _ := ctxhelper.ParamsFromContext(ctx) var data appUpdate if err := httphelper.DecodeJSON(req, &data); err != nil { respondWithError(rw, err) return } if err := schema.Validate(data); err != nil { respondWithError(rw, err) return } if data["meta"] == nil { data["meta"] = make(map[string]interface{}) } app, err := c.appRepo.Update(params.ByName("apps_id"), data) if err != nil { respondWithError(rw, err) return } httphelper.JSON(rw, 200, app) } func (c *controllerAPI) DeleteApp(ctx context.Context, w http.ResponseWriter, req *http.Request) { args, err := json.Marshal(c.getApp(ctx)) if err != nil { respondWithError(w, err) return } if err := c.que.Enqueue(&que.Job{ Type: "app_deletion", Args: args, }); err != nil { respondWithError(w, err) return } } func (c *controllerAPI) AppLog(ctx context.Context, w http.ResponseWriter, req *http.Request) { ctx, cancel := context.WithCancel(ctx) opts := logaggc.LogOpts{ Follow: req.FormValue("follow") == "true", JobID: req.FormValue("job_id"), } if vals, ok := req.Form["process_type"]; ok && len(vals) > 0 { opts.ProcessType = &vals[len(vals)-1] } if strLines := req.FormValue("lines"); strLines != "" { lines, err := strconv.Atoi(req.FormValue("lines")) if err != nil { respondWithError(w, err) return } opts.Lines = &lines } rc, err := c.logaggc.GetLog(c.getApp(ctx).ID, &opts) if err != nil { respondWithError(w, err) return } if cn, ok := w.(http.CloseNotifier); ok { go func() { select { case <-cn.CloseNotify(): rc.Close() case <-ctx.Done(): } }() } defer cancel() defer rc.Close() if !strings.Contains(req.Header.Get("Accept"), "text/event-stream") { w.Header().Set("Content-Type", "text/plain") w.WriteHeader(200) // Send headers right away if following if wf, ok := w.(http.Flusher); ok && opts.Follow { wf.Flush() } fw := httphelper.FlushWriter{Writer: w, Enabled: opts.Follow} io.Copy(fw, rc) return } ch := make(chan *sseLogChunk) l, _ := ctxhelper.LoggerFromContext(ctx) s := sse.NewStream(w, ch, l) defer s.Close() s.Serve() msgc := make(chan *json.RawMessage) go func() { defer close(msgc) dec := json.NewDecoder(rc) for { var m json.RawMessage if err := dec.Decode(&m); err != nil { if err != io.EOF { l.Error("decoding logagg stream", err) } return } msgc <- &m } }() for { select { case m := <-msgc: if m == nil { ch <- &sseLogChunk{Event: "eof"} return } // write to sse select { case ch <- &sseLogChunk{Event: "message", Data: *m}: case <-s.Done: return case <-ctx.Done(): return } case <-s.Done: return case <-ctx.Done(): return } } }
schatt/flynn
controller/app.go
GO
bsd-3-clause
10,272
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef REMOTING_HOST_OAUTH_TOKEN_GETTER_H_ #define REMOTING_HOST_OAUTH_TOKEN_GETTER_H_ #include <queue> #include "base/basictypes.h" #include "base/callback.h" #include "base/threading/non_thread_safe.h" #include "base/time/time.h" #include "base/timer/timer.h" #include "google_apis/gaia/gaia_oauth_client.h" namespace net { class URLRequestContextGetter; } // namespace net namespace remoting { // OAuthTokenGetter caches OAuth access tokens and refreshes them as needed. class OAuthTokenGetter : public base::NonThreadSafe, public gaia::GaiaOAuthClient::Delegate { public: // Status of the refresh token attempt. enum Status { // Success, credentials in user_email/access_token. SUCCESS, // Network failure (caller may retry). NETWORK_ERROR, // Authentication failure (permanent). AUTH_ERROR, }; typedef base::Callback<void(Status status, const std::string& user_email, const std::string& access_token)> TokenCallback; // This structure contains information required to perform // authentication to OAuth2. struct OAuthCredentials { // |is_service_account| should be True if the OAuth refresh token is for a // service account, False for a user account, to allow the correct client-ID // to be used. OAuthCredentials(const std::string& login, const std::string& refresh_token, bool is_service_account); // The user's account name (i.e. their email address). std::string login; // Token delegating authority to us to act as the user. std::string refresh_token; // Whether these credentials belong to a service account. bool is_service_account; }; OAuthTokenGetter(scoped_ptr<OAuthCredentials> oauth_credentials, const scoped_refptr<net::URLRequestContextGetter>& url_request_context_getter, bool auto_refresh); ~OAuthTokenGetter() override; // Call |on_access_token| with an access token, or the failure status. void CallWithToken(const OAuthTokenGetter::TokenCallback& on_access_token); // gaia::GaiaOAuthClient::Delegate interface. void OnGetTokensResponse(const std::string& user_email, const std::string& access_token, int expires_seconds) override; void OnRefreshTokenResponse(const std::string& access_token, int expires_in_seconds) override; void OnGetUserEmailResponse(const std::string& user_email) override; void OnOAuthError() override; void OnNetworkError(int response_code) override; private: void NotifyCallbacks(Status status, const std::string& user_email, const std::string& access_token); void RefreshOAuthToken(); scoped_ptr<OAuthCredentials> oauth_credentials_; scoped_ptr<gaia::GaiaOAuthClient> gaia_oauth_client_; scoped_refptr<net::URLRequestContextGetter> url_request_context_getter_; bool refreshing_oauth_token_; std::string oauth_access_token_; std::string verified_email_; base::Time auth_token_expiry_time_; std::queue<OAuthTokenGetter::TokenCallback> pending_callbacks_; scoped_ptr<base::OneShotTimer<OAuthTokenGetter> > refresh_timer_; DISALLOW_COPY_AND_ASSIGN(OAuthTokenGetter); }; } // namespace remoting #endif // REMOTING_HOST_OAUTH_TOKEN_GETTER_H_
CTSRD-SOAAP/chromium-42.0.2311.135
remoting/host/oauth_token_getter.h
C
bsd-3-clause
3,606
/* * Copyright (c) 2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include "NumpyArrayAllocator.h" #define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION #include <numpy/arrayobject.h> #include <thpp/Storage.h> namespace fblualib { namespace python { void* NumpyArrayAllocator::malloc(long size) { return (*THDefaultAllocator.malloc)(nullptr, size); } void* NumpyArrayAllocator::realloc(void* ptr, long size) { if (array_ && ptr == PyArray_DATA(array())) { void* newPtr = this->malloc(size); memcpy(newPtr, ptr, std::min(size, PyArray_NBYTES(array()))); // Whee! We're done! release(); return newPtr; } return (*THDefaultAllocator.realloc)(nullptr, ptr, size); } void NumpyArrayAllocator::free(void* ptr) { // We're relying on the slightly unsafe (and undocumented) behavior that // THStorage will only call the "free" method of the allocator once at the // end of its lifetime. if (array() && ptr == PyArray_DATA(array())) { release(); return; } (*THDefaultAllocator.free)(nullptr, ptr); delete this; } void NumpyArrayAllocator::release() { if (!array_) { return; } debugDeletePythonRef(array_.get()); // We may or may not have a Python context, let's be safe. PythonGuard g; array_.reset(); } int initNumpyArrayAllocator(lua_State* L) { initNumpy(L); return 0; } }} // namespaces
soumith/fblualib
fblualib/python/NumpyArrayAllocator.cpp
C++
bsd-3-clause
1,600
/* * MPEG2 transport stream (aka DVB) demuxer * Copyright (c) 2002-2003 Fabrice Bellard * * This file is part of FFmpeg. * * FFmpeg is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * FFmpeg is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with FFmpeg; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "libavutil/buffer.h" #include "libavutil/crc.h" #include "libavutil/intreadwrite.h" #include "libavutil/log.h" #include "libavutil/dict.h" #include "libavutil/mathematics.h" #include "libavutil/opt.h" #include "libavutil/avassert.h" #include "libavcodec/bytestream.h" #include "libavcodec/get_bits.h" #include "libavcodec/opus.h" #include "avformat.h" #include "mpegts.h" #include "internal.h" #include "avio_internal.h" #include "seek.h" #include "mpeg.h" #include "isom.h" /* maximum size in which we look for synchronisation if * synchronisation is lost */ #define MAX_RESYNC_SIZE 65536 #define MAX_PES_PAYLOAD 200 * 1024 #define MAX_MP4_DESCR_COUNT 16 #define MOD_UNLIKELY(modulus, dividend, divisor, prev_dividend) \ do { \ if ((prev_dividend) == 0 || (dividend) - (prev_dividend) != (divisor)) \ (modulus) = (dividend) % (divisor); \ (prev_dividend) = (dividend); \ } while (0) enum MpegTSFilterType { MPEGTS_PES, MPEGTS_SECTION, MPEGTS_PCR, }; typedef struct MpegTSFilter MpegTSFilter; typedef int PESCallback (MpegTSFilter *f, const uint8_t *buf, int len, int is_start, int64_t pos); typedef struct MpegTSPESFilter { PESCallback *pes_cb; void *opaque; } MpegTSPESFilter; typedef void SectionCallback (MpegTSFilter *f, const uint8_t *buf, int len); typedef void SetServiceCallback (void *opaque, int ret); typedef struct MpegTSSectionFilter { int section_index; int section_h_size; uint8_t *section_buf; unsigned int check_crc : 1; unsigned int end_of_section_reached : 1; SectionCallback *section_cb; void *opaque; } MpegTSSectionFilter; struct MpegTSFilter { int pid; int es_id; int last_cc; /* last cc code (-1 if first packet) */ int64_t last_pcr; enum MpegTSFilterType type; union { MpegTSPESFilter pes_filter; MpegTSSectionFilter section_filter; } u; }; #define MAX_PIDS_PER_PROGRAM 64 struct Program { unsigned int id; // program id/service id unsigned int nb_pids; unsigned int pids[MAX_PIDS_PER_PROGRAM]; /** have we found pmt for this program */ int pmt_found; }; struct MpegTSContext { const AVClass *class; /* user data */ AVFormatContext *stream; /** raw packet size, including FEC if present */ int raw_packet_size; int size_stat[3]; int size_stat_count; #define SIZE_STAT_THRESHOLD 10 int64_t pos47_full; /** if true, all pids are analyzed to find streams */ int auto_guess; /** compute exact PCR for each transport stream packet */ int mpeg2ts_compute_pcr; /** fix dvb teletext pts */ int fix_teletext_pts; int64_t cur_pcr; /**< used to estimate the exact PCR */ int pcr_incr; /**< used to estimate the exact PCR */ /* data needed to handle file based ts */ /** stop parsing loop */ int stop_parse; /** packet containing Audio/Video data */ AVPacket *pkt; /** to detect seek */ int64_t last_pos; int skip_changes; int skip_clear; int scan_all_pmts; int resync_size; /******************************************/ /* private mpegts data */ /* scan context */ /** structure to keep track of Program->pids mapping */ unsigned int nb_prg; struct Program *prg; int8_t crc_validity[NB_PID_MAX]; /** filters for various streams specified by PMT + for the PAT and PMT */ MpegTSFilter *pids[NB_PID_MAX]; int current_pid; }; #define MPEGTS_OPTIONS \ { "resync_size", "Size limit for looking up a new synchronization.", offsetof(MpegTSContext, resync_size), AV_OPT_TYPE_INT, { .i64 = MAX_RESYNC_SIZE}, 0, INT_MAX, AV_OPT_FLAG_DECODING_PARAM } static const AVOption options[] = { MPEGTS_OPTIONS, {"fix_teletext_pts", "Try to fix pts values of dvb teletext streams.", offsetof(MpegTSContext, fix_teletext_pts), AV_OPT_TYPE_INT, {.i64 = 1}, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, {"ts_packetsize", "Output option carrying the raw packet size.", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }, {"scan_all_pmts", "Scan and combine all PMTs", offsetof(MpegTSContext, scan_all_pmts), AV_OPT_TYPE_INT, { .i64 = -1}, -1, 1, AV_OPT_FLAG_DECODING_PARAM }, {"skip_changes", "Skip changing / adding streams / programs.", offsetof(MpegTSContext, skip_changes), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0 }, {"skip_clear", "Skip clearing programs.", offsetof(MpegTSContext, skip_clear), AV_OPT_TYPE_INT, {.i64 = 0}, 0, 1, 0 }, { NULL }, }; static const AVClass mpegts_class = { .class_name = "mpegts demuxer", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; static const AVOption raw_options[] = { MPEGTS_OPTIONS, { "compute_pcr", "Compute exact PCR for each transport stream packet.", offsetof(MpegTSContext, mpeg2ts_compute_pcr), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 1, AV_OPT_FLAG_DECODING_PARAM }, { "ts_packetsize", "Output option carrying the raw packet size.", offsetof(MpegTSContext, raw_packet_size), AV_OPT_TYPE_INT, { .i64 = 0 }, 0, 0, AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_EXPORT | AV_OPT_FLAG_READONLY }, { NULL }, }; static const AVClass mpegtsraw_class = { .class_name = "mpegtsraw demuxer", .item_name = av_default_item_name, .option = raw_options, .version = LIBAVUTIL_VERSION_INT, }; /* TS stream handling */ enum MpegTSState { MPEGTS_HEADER = 0, MPEGTS_PESHEADER, MPEGTS_PESHEADER_FILL, MPEGTS_PAYLOAD, MPEGTS_SKIP, }; /* enough for PES header + length */ #define PES_START_SIZE 6 #define PES_HEADER_SIZE 9 #define MAX_PES_HEADER_SIZE (9 + 255) typedef struct PESContext { int pid; int pcr_pid; /**< if -1 then all packets containing PCR are considered */ int stream_type; MpegTSContext *ts; AVFormatContext *stream; AVStream *st; AVStream *sub_st; /**< stream for the embedded AC3 stream in HDMV TrueHD */ enum MpegTSState state; /* used to get the format */ int data_index; int flags; /**< copied to the AVPacket flags */ int total_size; int pes_header_size; int extended_stream_id; int64_t pts, dts; int64_t ts_packet_pos; /**< position of first TS packet of this PES packet */ uint8_t header[MAX_PES_HEADER_SIZE]; AVBufferRef *buffer; SLConfigDescr sl; } PESContext; extern AVInputFormat ff_mpegts_demuxer; static struct Program * get_program(MpegTSContext *ts, unsigned int programid) { int i; for (i = 0; i < ts->nb_prg; i++) { if (ts->prg[i].id == programid) { return &ts->prg[i]; } } return NULL; } static void clear_avprogram(MpegTSContext *ts, unsigned int programid) { AVProgram *prg = NULL; int i; for (i = 0; i < ts->stream->nb_programs; i++) if (ts->stream->programs[i]->id == programid) { prg = ts->stream->programs[i]; break; } if (!prg) return; prg->nb_stream_indexes = 0; } static void clear_program(MpegTSContext *ts, unsigned int programid) { int i; clear_avprogram(ts, programid); for (i = 0; i < ts->nb_prg; i++) if (ts->prg[i].id == programid) { ts->prg[i].nb_pids = 0; ts->prg[i].pmt_found = 0; } } static void clear_programs(MpegTSContext *ts) { av_freep(&ts->prg); ts->nb_prg = 0; } static void add_pat_entry(MpegTSContext *ts, unsigned int programid) { struct Program *p; if (av_reallocp_array(&ts->prg, ts->nb_prg + 1, sizeof(*ts->prg)) < 0) { ts->nb_prg = 0; return; } p = &ts->prg[ts->nb_prg]; p->id = programid; p->nb_pids = 0; p->pmt_found = 0; ts->nb_prg++; } static void add_pid_to_pmt(MpegTSContext *ts, unsigned int programid, unsigned int pid) { struct Program *p = get_program(ts, programid); int i; if (!p) return; if (p->nb_pids >= MAX_PIDS_PER_PROGRAM) return; for (i = 0; i < p->nb_pids; i++) if (p->pids[i] == pid) return; p->pids[p->nb_pids++] = pid; } static void set_pmt_found(MpegTSContext *ts, unsigned int programid) { struct Program *p = get_program(ts, programid); if (!p) return; p->pmt_found = 1; } static void set_pcr_pid(AVFormatContext *s, unsigned int programid, unsigned int pid) { int i; for (i = 0; i < s->nb_programs; i++) { if (s->programs[i]->id == programid) { s->programs[i]->pcr_pid = pid; break; } } } /** * @brief discard_pid() decides if the pid is to be discarded according * to caller's programs selection * @param ts : - TS context * @param pid : - pid * @return 1 if the pid is only comprised in programs that have .discard=AVDISCARD_ALL * 0 otherwise */ static int discard_pid(MpegTSContext *ts, unsigned int pid) { int i, j, k; int used = 0, discarded = 0; struct Program *p; /* If none of the programs have .discard=AVDISCARD_ALL then there's * no way we have to discard this packet */ for (k = 0; k < ts->stream->nb_programs; k++) if (ts->stream->programs[k]->discard == AVDISCARD_ALL) break; if (k == ts->stream->nb_programs) return 0; for (i = 0; i < ts->nb_prg; i++) { p = &ts->prg[i]; for (j = 0; j < p->nb_pids; j++) { if (p->pids[j] != pid) continue; // is program with id p->id set to be discarded? for (k = 0; k < ts->stream->nb_programs; k++) { if (ts->stream->programs[k]->id == p->id) { if (ts->stream->programs[k]->discard == AVDISCARD_ALL) discarded++; else used++; } } } } return !used && discarded; } /** * Assemble PES packets out of TS packets, and then call the "section_cb" * function when they are complete. */ static void write_section_data(MpegTSContext *ts, MpegTSFilter *tss1, const uint8_t *buf, int buf_size, int is_start) { MpegTSSectionFilter *tss = &tss1->u.section_filter; int len; if (is_start) { memcpy(tss->section_buf, buf, buf_size); tss->section_index = buf_size; tss->section_h_size = -1; tss->end_of_section_reached = 0; } else { if (tss->end_of_section_reached) return; len = 4096 - tss->section_index; if (buf_size < len) len = buf_size; memcpy(tss->section_buf + tss->section_index, buf, len); tss->section_index += len; } /* compute section length if possible */ if (tss->section_h_size == -1 && tss->section_index >= 3) { len = (AV_RB16(tss->section_buf + 1) & 0xfff) + 3; if (len > 4096) return; tss->section_h_size = len; } if (tss->section_h_size != -1 && tss->section_index >= tss->section_h_size) { int crc_valid = 1; tss->end_of_section_reached = 1; if (tss->check_crc) { crc_valid = !av_crc(av_crc_get_table(AV_CRC_32_IEEE), -1, tss->section_buf, tss->section_h_size); if (crc_valid) { ts->crc_validity[ tss1->pid ] = 100; }else if (ts->crc_validity[ tss1->pid ] > -10) { ts->crc_validity[ tss1->pid ]--; }else crc_valid = 2; } if (crc_valid) tss->section_cb(tss1, tss->section_buf, tss->section_h_size); } } static MpegTSFilter *mpegts_open_filter(MpegTSContext *ts, unsigned int pid, enum MpegTSFilterType type) { MpegTSFilter *filter; av_dlog(ts->stream, "Filter: pid=0x%x\n", pid); if (pid >= NB_PID_MAX || ts->pids[pid]) return NULL; filter = av_mallocz(sizeof(MpegTSFilter)); if (!filter) return NULL; ts->pids[pid] = filter; filter->type = type; filter->pid = pid; filter->es_id = -1; filter->last_cc = -1; filter->last_pcr= -1; return filter; } static MpegTSFilter *mpegts_open_section_filter(MpegTSContext *ts, unsigned int pid, SectionCallback *section_cb, void *opaque, int check_crc) { MpegTSFilter *filter; MpegTSSectionFilter *sec; if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_SECTION))) return NULL; sec = &filter->u.section_filter; sec->section_cb = section_cb; sec->opaque = opaque; sec->section_buf = av_malloc(MAX_SECTION_SIZE); sec->check_crc = check_crc; if (!sec->section_buf) { av_free(filter); return NULL; } return filter; } static MpegTSFilter *mpegts_open_pes_filter(MpegTSContext *ts, unsigned int pid, PESCallback *pes_cb, void *opaque) { MpegTSFilter *filter; MpegTSPESFilter *pes; if (!(filter = mpegts_open_filter(ts, pid, MPEGTS_PES))) return NULL; pes = &filter->u.pes_filter; pes->pes_cb = pes_cb; pes->opaque = opaque; return filter; } static MpegTSFilter *mpegts_open_pcr_filter(MpegTSContext *ts, unsigned int pid) { return mpegts_open_filter(ts, pid, MPEGTS_PCR); } static void mpegts_close_filter(MpegTSContext *ts, MpegTSFilter *filter) { int pid; pid = filter->pid; if (filter->type == MPEGTS_SECTION) av_freep(&filter->u.section_filter.section_buf); else if (filter->type == MPEGTS_PES) { PESContext *pes = filter->u.pes_filter.opaque; av_buffer_unref(&pes->buffer); /* referenced private data will be freed later in * avformat_close_input */ if (!((PESContext *)filter->u.pes_filter.opaque)->st) { av_freep(&filter->u.pes_filter.opaque); } } av_free(filter); ts->pids[pid] = NULL; } static int analyze(const uint8_t *buf, int size, int packet_size, int *index) { int stat[TS_MAX_PACKET_SIZE]; int stat_all = 0; int i; int best_score = 0; memset(stat, 0, packet_size * sizeof(*stat)); for (i = 0; i < size - 3; i++) { if (buf[i] == 0x47 && !(buf[i + 1] & 0x80) && buf[i + 3] != 0x47) { int x = i % packet_size; stat[x]++; stat_all++; if (stat[x] > best_score) { best_score = stat[x]; if (index) *index = x; } } } return best_score - FFMAX(stat_all - 10*best_score, 0)/10; } /* autodetect fec presence. Must have at least 1024 bytes */ static int get_packet_size(const uint8_t *buf, int size) { int score, fec_score, dvhs_score; if (size < (TS_FEC_PACKET_SIZE * 5 + 1)) return AVERROR_INVALIDDATA; score = analyze(buf, size, TS_PACKET_SIZE, NULL); dvhs_score = analyze(buf, size, TS_DVHS_PACKET_SIZE, NULL); fec_score = analyze(buf, size, TS_FEC_PACKET_SIZE, NULL); av_dlog(NULL, "score: %d, dvhs_score: %d, fec_score: %d \n", score, dvhs_score, fec_score); if (score > fec_score && score > dvhs_score) return TS_PACKET_SIZE; else if (dvhs_score > score && dvhs_score > fec_score) return TS_DVHS_PACKET_SIZE; else if (score < fec_score && dvhs_score < fec_score) return TS_FEC_PACKET_SIZE; else return AVERROR_INVALIDDATA; } typedef struct SectionHeader { uint8_t tid; uint16_t id; uint8_t version; uint8_t sec_num; uint8_t last_sec_num; } SectionHeader; static inline int get8(const uint8_t **pp, const uint8_t *p_end) { const uint8_t *p; int c; p = *pp; if (p >= p_end) return AVERROR_INVALIDDATA; c = *p++; *pp = p; return c; } static inline int get16(const uint8_t **pp, const uint8_t *p_end) { const uint8_t *p; int c; p = *pp; if ((p + 1) >= p_end) return AVERROR_INVALIDDATA; c = AV_RB16(p); p += 2; *pp = p; return c; } /* read and allocate a DVB string preceded by its length */ static char *getstr8(const uint8_t **pp, const uint8_t *p_end) { int len; const uint8_t *p; char *str; p = *pp; len = get8(&p, p_end); if (len < 0) return NULL; if ((p + len) > p_end) return NULL; str = av_malloc(len + 1); if (!str) return NULL; memcpy(str, p, len); str[len] = '\0'; p += len; *pp = p; return str; } static int parse_section_header(SectionHeader *h, const uint8_t **pp, const uint8_t *p_end) { int val; val = get8(pp, p_end); if (val < 0) return val; h->tid = val; *pp += 2; val = get16(pp, p_end); if (val < 0) return val; h->id = val; val = get8(pp, p_end); if (val < 0) return val; h->version = (val >> 1) & 0x1f; val = get8(pp, p_end); if (val < 0) return val; h->sec_num = val; val = get8(pp, p_end); if (val < 0) return val; h->last_sec_num = val; return 0; } typedef struct { uint32_t stream_type; enum AVMediaType codec_type; enum AVCodecID codec_id; } StreamType; static const StreamType ISO_types[] = { { 0x01, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO }, { 0x02, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG2VIDEO }, { 0x03, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 }, { 0x04, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_MP3 }, { 0x0f, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC }, { 0x10, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_MPEG4 }, /* Makito encoder sets stream type 0x11 for AAC, * so auto-detect LOAS/LATM instead of hardcoding it. */ #if !CONFIG_LOAS_DEMUXER { 0x11, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AAC_LATM }, /* LATM syntax */ #endif { 0x1b, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_H264 }, { 0x24, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC }, { 0x42, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_CAVS }, { 0xd1, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC }, { 0xea, AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 }, { 0 }, }; static const StreamType HDMV_types[] = { { 0x80, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_PCM_BLURAY }, { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, { 0x82, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { 0x83, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_TRUEHD }, { 0x84, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, { 0x85, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD */ { 0x86, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS HD MASTER*/ { 0xa1, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC3 Secondary Audio */ { 0xa2, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, /* DTS Express Secondary Audio */ { 0x90, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_HDMV_PGS_SUBTITLE }, { 0 }, }; /* ATSC ? */ static const StreamType MISC_types[] = { { 0x81, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, { 0x8a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { 0 }, }; static const StreamType REGD_types[] = { { MKTAG('d', 'r', 'a', 'c'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_DIRAC }, { MKTAG('A', 'C', '-', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, { MKTAG('B', 'S', 'S', 'D'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_S302M }, { MKTAG('D', 'T', 'S', '1'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { MKTAG('D', 'T', 'S', '2'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { MKTAG('D', 'T', 'S', '3'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { MKTAG('H', 'E', 'V', 'C'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_HEVC }, { MKTAG('K', 'L', 'V', 'A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV }, { MKTAG('V', 'C', '-', '1'), AVMEDIA_TYPE_VIDEO, AV_CODEC_ID_VC1 }, { MKTAG('O', 'p', 'u', 's'), AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_OPUS }, { 0 }, }; static const StreamType METADATA_types[] = { { MKTAG('K','L','V','A'), AVMEDIA_TYPE_DATA, AV_CODEC_ID_SMPTE_KLV }, { MKTAG('I','D','3',' '), AVMEDIA_TYPE_DATA, AV_CODEC_ID_TIMED_ID3 }, { 0 }, }; /* descriptor present */ static const StreamType DESC_types[] = { { 0x6a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_AC3 }, /* AC-3 descriptor */ { 0x7a, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_EAC3 }, /* E-AC-3 descriptor */ { 0x7b, AVMEDIA_TYPE_AUDIO, AV_CODEC_ID_DTS }, { 0x56, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_TELETEXT }, { 0x59, AVMEDIA_TYPE_SUBTITLE, AV_CODEC_ID_DVB_SUBTITLE }, /* subtitling descriptor */ { 0 }, }; static void mpegts_find_stream_type(AVStream *st, uint32_t stream_type, const StreamType *types) { if (avcodec_is_open(st->codec)) { av_log(NULL, AV_LOG_DEBUG, "cannot set stream info, codec is open\n"); return; } for (; types->stream_type; types++) if (stream_type == types->stream_type) { st->codec->codec_type = types->codec_type; st->codec->codec_id = types->codec_id; st->request_probe = 0; return; } } static int mpegts_set_stream_info(AVStream *st, PESContext *pes, uint32_t stream_type, uint32_t prog_reg_desc) { int old_codec_type = st->codec->codec_type; int old_codec_id = st->codec->codec_id; if (avcodec_is_open(st->codec)) { av_log(pes->stream, AV_LOG_DEBUG, "cannot set stream info, codec is open\n"); return 0; } avpriv_set_pts_info(st, 33, 1, 90000); st->priv_data = pes; st->codec->codec_type = AVMEDIA_TYPE_DATA; st->codec->codec_id = AV_CODEC_ID_NONE; st->need_parsing = AVSTREAM_PARSE_FULL; pes->st = st; pes->stream_type = stream_type; av_log(pes->stream, AV_LOG_DEBUG, "stream=%d stream_type=%x pid=%x prog_reg_desc=%.4s\n", st->index, pes->stream_type, pes->pid, (char *)&prog_reg_desc); st->codec->codec_tag = pes->stream_type; mpegts_find_stream_type(st, pes->stream_type, ISO_types); if ((prog_reg_desc == AV_RL32("HDMV") || prog_reg_desc == AV_RL32("HDPR")) && st->codec->codec_id == AV_CODEC_ID_NONE) { mpegts_find_stream_type(st, pes->stream_type, HDMV_types); if (pes->stream_type == 0x83) { // HDMV TrueHD streams also contain an AC3 coded version of the // audio track - add a second stream for this AVStream *sub_st; // priv_data cannot be shared between streams PESContext *sub_pes = av_malloc(sizeof(*sub_pes)); if (!sub_pes) return AVERROR(ENOMEM); memcpy(sub_pes, pes, sizeof(*sub_pes)); sub_st = avformat_new_stream(pes->stream, NULL); if (!sub_st) { av_free(sub_pes); return AVERROR(ENOMEM); } sub_st->id = pes->pid; avpriv_set_pts_info(sub_st, 33, 1, 90000); sub_st->priv_data = sub_pes; sub_st->codec->codec_type = AVMEDIA_TYPE_AUDIO; sub_st->codec->codec_id = AV_CODEC_ID_AC3; sub_st->need_parsing = AVSTREAM_PARSE_FULL; sub_pes->sub_st = pes->sub_st = sub_st; } } if (st->codec->codec_id == AV_CODEC_ID_NONE) mpegts_find_stream_type(st, pes->stream_type, MISC_types); if (st->codec->codec_id == AV_CODEC_ID_NONE) { st->codec->codec_id = old_codec_id; st->codec->codec_type = old_codec_type; } return 0; } static void reset_pes_packet_state(PESContext *pes) { pes->pts = AV_NOPTS_VALUE; pes->dts = AV_NOPTS_VALUE; pes->data_index = 0; pes->flags = 0; av_buffer_unref(&pes->buffer); } static void new_pes_packet(PESContext *pes, AVPacket *pkt) { av_init_packet(pkt); pkt->buf = pes->buffer; pkt->data = pes->buffer->data; pkt->size = pes->data_index; if (pes->total_size != MAX_PES_PAYLOAD && pes->pes_header_size + pes->data_index != pes->total_size + PES_START_SIZE) { av_log(pes->stream, AV_LOG_WARNING, "PES packet size mismatch\n"); pes->flags |= AV_PKT_FLAG_CORRUPT; } memset(pkt->data + pkt->size, 0, FF_INPUT_BUFFER_PADDING_SIZE); // Separate out the AC3 substream from an HDMV combined TrueHD/AC3 PID if (pes->sub_st && pes->stream_type == 0x83 && pes->extended_stream_id == 0x76) pkt->stream_index = pes->sub_st->index; else pkt->stream_index = pes->st->index; pkt->pts = pes->pts; pkt->dts = pes->dts; /* store position of first TS packet of this PES packet */ pkt->pos = pes->ts_packet_pos; pkt->flags = pes->flags; pes->buffer = NULL; reset_pes_packet_state(pes); } static uint64_t get_ts64(GetBitContext *gb, int bits) { if (get_bits_left(gb) < bits) return AV_NOPTS_VALUE; return get_bits64(gb, bits); } static int read_sl_header(PESContext *pes, SLConfigDescr *sl, const uint8_t *buf, int buf_size) { GetBitContext gb; int au_start_flag = 0, au_end_flag = 0, ocr_flag = 0, idle_flag = 0; int padding_flag = 0, padding_bits = 0, inst_bitrate_flag = 0; int dts_flag = -1, cts_flag = -1; int64_t dts = AV_NOPTS_VALUE, cts = AV_NOPTS_VALUE; uint8_t buf_padded[128 + FF_INPUT_BUFFER_PADDING_SIZE]; int buf_padded_size = FFMIN(buf_size, sizeof(buf_padded) - FF_INPUT_BUFFER_PADDING_SIZE); memcpy(buf_padded, buf, buf_padded_size); init_get_bits(&gb, buf_padded, buf_padded_size * 8); if (sl->use_au_start) au_start_flag = get_bits1(&gb); if (sl->use_au_end) au_end_flag = get_bits1(&gb); if (!sl->use_au_start && !sl->use_au_end) au_start_flag = au_end_flag = 1; if (sl->ocr_len > 0) ocr_flag = get_bits1(&gb); if (sl->use_idle) idle_flag = get_bits1(&gb); if (sl->use_padding) padding_flag = get_bits1(&gb); if (padding_flag) padding_bits = get_bits(&gb, 3); if (!idle_flag && (!padding_flag || padding_bits != 0)) { if (sl->packet_seq_num_len) skip_bits_long(&gb, sl->packet_seq_num_len); if (sl->degr_prior_len) if (get_bits1(&gb)) skip_bits(&gb, sl->degr_prior_len); if (ocr_flag) skip_bits_long(&gb, sl->ocr_len); if (au_start_flag) { if (sl->use_rand_acc_pt) get_bits1(&gb); if (sl->au_seq_num_len > 0) skip_bits_long(&gb, sl->au_seq_num_len); if (sl->use_timestamps) { dts_flag = get_bits1(&gb); cts_flag = get_bits1(&gb); } } if (sl->inst_bitrate_len) inst_bitrate_flag = get_bits1(&gb); if (dts_flag == 1) dts = get_ts64(&gb, sl->timestamp_len); if (cts_flag == 1) cts = get_ts64(&gb, sl->timestamp_len); if (sl->au_len > 0) skip_bits_long(&gb, sl->au_len); if (inst_bitrate_flag) skip_bits_long(&gb, sl->inst_bitrate_len); } if (dts != AV_NOPTS_VALUE) pes->dts = dts; if (cts != AV_NOPTS_VALUE) pes->pts = cts; if (sl->timestamp_len && sl->timestamp_res) avpriv_set_pts_info(pes->st, sl->timestamp_len, 1, sl->timestamp_res); return (get_bits_count(&gb) + 7) >> 3; } /* return non zero if a packet could be constructed */ static int mpegts_push_data(MpegTSFilter *filter, const uint8_t *buf, int buf_size, int is_start, int64_t pos) { PESContext *pes = filter->u.pes_filter.opaque; MpegTSContext *ts = pes->ts; const uint8_t *p; int len, code; if (!ts->pkt) return 0; if (is_start) { if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) { new_pes_packet(pes, ts->pkt); ts->stop_parse = 1; } else { reset_pes_packet_state(pes); } pes->state = MPEGTS_HEADER; pes->ts_packet_pos = pos; } p = buf; while (buf_size > 0) { switch (pes->state) { case MPEGTS_HEADER: len = PES_START_SIZE - pes->data_index; if (len > buf_size) len = buf_size; memcpy(pes->header + pes->data_index, p, len); pes->data_index += len; p += len; buf_size -= len; if (pes->data_index == PES_START_SIZE) { /* we got all the PES or section header. We can now * decide */ if (pes->header[0] == 0x00 && pes->header[1] == 0x00 && pes->header[2] == 0x01) { /* it must be an mpeg2 PES stream */ code = pes->header[3] | 0x100; av_dlog(pes->stream, "pid=%x pes_code=%#x\n", pes->pid, code); if ((pes->st && pes->st->discard == AVDISCARD_ALL && (!pes->sub_st || pes->sub_st->discard == AVDISCARD_ALL)) || code == 0x1be) /* padding_stream */ goto skip; /* stream not present in PMT */ if (!pes->st) { if (ts->skip_changes) goto skip; pes->st = avformat_new_stream(ts->stream, NULL); if (!pes->st) return AVERROR(ENOMEM); pes->st->id = pes->pid; mpegts_set_stream_info(pes->st, pes, 0, 0); } pes->total_size = AV_RB16(pes->header + 4); /* NOTE: a zero total size means the PES size is * unbounded */ if (!pes->total_size) pes->total_size = MAX_PES_PAYLOAD; /* allocate pes buffer */ pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE); if (!pes->buffer) return AVERROR(ENOMEM); if (code != 0x1bc && code != 0x1bf && /* program_stream_map, private_stream_2 */ code != 0x1f0 && code != 0x1f1 && /* ECM, EMM */ code != 0x1ff && code != 0x1f2 && /* program_stream_directory, DSMCC_stream */ code != 0x1f8) { /* ITU-T Rec. H.222.1 type E stream */ pes->state = MPEGTS_PESHEADER; if (pes->st->codec->codec_id == AV_CODEC_ID_NONE && !pes->st->request_probe) { av_dlog(pes->stream, "pid=%x stream_type=%x probing\n", pes->pid, pes->stream_type); pes->st->request_probe = 1; } } else { pes->state = MPEGTS_PAYLOAD; pes->data_index = 0; } } else { /* otherwise, it should be a table */ /* skip packet */ skip: pes->state = MPEGTS_SKIP; continue; } } break; /**********************************************/ /* PES packing parsing */ case MPEGTS_PESHEADER: len = PES_HEADER_SIZE - pes->data_index; if (len < 0) return AVERROR_INVALIDDATA; if (len > buf_size) len = buf_size; memcpy(pes->header + pes->data_index, p, len); pes->data_index += len; p += len; buf_size -= len; if (pes->data_index == PES_HEADER_SIZE) { pes->pes_header_size = pes->header[8] + 9; pes->state = MPEGTS_PESHEADER_FILL; } break; case MPEGTS_PESHEADER_FILL: len = pes->pes_header_size - pes->data_index; if (len < 0) return AVERROR_INVALIDDATA; if (len > buf_size) len = buf_size; memcpy(pes->header + pes->data_index, p, len); pes->data_index += len; p += len; buf_size -= len; if (pes->data_index == pes->pes_header_size) { const uint8_t *r; unsigned int flags, pes_ext, skip; flags = pes->header[7]; r = pes->header + 9; pes->pts = AV_NOPTS_VALUE; pes->dts = AV_NOPTS_VALUE; if ((flags & 0xc0) == 0x80) { pes->dts = pes->pts = ff_parse_pes_pts(r); r += 5; } else if ((flags & 0xc0) == 0xc0) { pes->pts = ff_parse_pes_pts(r); r += 5; pes->dts = ff_parse_pes_pts(r); r += 5; } pes->extended_stream_id = -1; if (flags & 0x01) { /* PES extension */ pes_ext = *r++; /* Skip PES private data, program packet sequence counter and P-STD buffer */ skip = (pes_ext >> 4) & 0xb; skip += skip & 0x9; r += skip; if ((pes_ext & 0x41) == 0x01 && (r + 2) <= (pes->header + pes->pes_header_size)) { /* PES extension 2 */ if ((r[0] & 0x7f) > 0 && (r[1] & 0x80) == 0) pes->extended_stream_id = r[1]; } } /* we got the full header. We parse it and get the payload */ pes->state = MPEGTS_PAYLOAD; pes->data_index = 0; if (pes->stream_type == 0x12 && buf_size > 0) { int sl_header_bytes = read_sl_header(pes, &pes->sl, p, buf_size); pes->pes_header_size += sl_header_bytes; p += sl_header_bytes; buf_size -= sl_header_bytes; } if (pes->stream_type == 0x15 && buf_size >= 5) { /* skip metadata access unit header */ pes->pes_header_size += 5; p += 5; buf_size -= 5; } if (pes->ts->fix_teletext_pts && pes->st->codec->codec_id == AV_CODEC_ID_DVB_TELETEXT) { AVProgram *p = NULL; while ((p = av_find_program_from_stream(pes->stream, p, pes->st->index))) { if (p->pcr_pid != -1 && p->discard != AVDISCARD_ALL) { MpegTSFilter *f = pes->ts->pids[p->pcr_pid]; if (f) { AVStream *st = NULL; if (f->type == MPEGTS_PES) { PESContext *pcrpes = f->u.pes_filter.opaque; if (pcrpes) st = pcrpes->st; } else if (f->type == MPEGTS_PCR) { int i; for (i = 0; i < p->nb_stream_indexes; i++) { AVStream *pst = pes->stream->streams[p->stream_index[i]]; if (pst->codec->codec_type == AVMEDIA_TYPE_VIDEO) st = pst; } } if (f->last_pcr != -1 && st && st->discard != AVDISCARD_ALL) { // teletext packets do not always have correct timestamps, // the standard says they should be handled after 40.6 ms at most, // and the pcr error to this packet should be no more than 100 ms. // TODO: we should interpolate the PCR, not just use the last one int64_t pcr = f->last_pcr / 300; pes->st->pts_wrap_reference = st->pts_wrap_reference; pes->st->pts_wrap_behavior = st->pts_wrap_behavior; if (pes->dts == AV_NOPTS_VALUE || pes->dts < pcr) { pes->pts = pes->dts = pcr; } else if (pes->dts > pcr + 3654 + 9000) { pes->pts = pes->dts = pcr + 3654 + 9000; } break; } } } } } } break; case MPEGTS_PAYLOAD: if (pes->buffer) { if (pes->data_index > 0 && pes->data_index + buf_size > pes->total_size) { new_pes_packet(pes, ts->pkt); pes->total_size = MAX_PES_PAYLOAD; pes->buffer = av_buffer_alloc(pes->total_size + FF_INPUT_BUFFER_PADDING_SIZE); if (!pes->buffer) return AVERROR(ENOMEM); ts->stop_parse = 1; } else if (pes->data_index == 0 && buf_size > pes->total_size) { // pes packet size is < ts size packet and pes data is padded with 0xff // not sure if this is legal in ts but see issue #2392 buf_size = pes->total_size; } memcpy(pes->buffer->data + pes->data_index, p, buf_size); pes->data_index += buf_size; /* emit complete packets with known packet size * decreases demuxer delay for infrequent packets like subtitles from * a couple of seconds to milliseconds for properly muxed files. * total_size is the number of bytes following pes_packet_length * in the pes header, i.e. not counting the first PES_START_SIZE bytes */ if (!ts->stop_parse && pes->total_size < MAX_PES_PAYLOAD && pes->pes_header_size + pes->data_index == pes->total_size + PES_START_SIZE) { ts->stop_parse = 1; new_pes_packet(pes, ts->pkt); } } buf_size = 0; break; case MPEGTS_SKIP: buf_size = 0; break; } } return 0; } static PESContext *add_pes_stream(MpegTSContext *ts, int pid, int pcr_pid) { MpegTSFilter *tss; PESContext *pes; /* if no pid found, then add a pid context */ pes = av_mallocz(sizeof(PESContext)); if (!pes) return 0; pes->ts = ts; pes->stream = ts->stream; pes->pid = pid; pes->pcr_pid = pcr_pid; pes->state = MPEGTS_SKIP; pes->pts = AV_NOPTS_VALUE; pes->dts = AV_NOPTS_VALUE; tss = mpegts_open_pes_filter(ts, pid, mpegts_push_data, pes); if (!tss) { av_free(pes); return 0; } return pes; } #define MAX_LEVEL 4 typedef struct { AVFormatContext *s; AVIOContext pb; Mp4Descr *descr; Mp4Descr *active_descr; int descr_count; int max_descr_count; int level; int predefined_SLConfigDescriptor_seen; } MP4DescrParseContext; static int init_MP4DescrParseContext(MP4DescrParseContext *d, AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int max_descr_count) { int ret; if (size > (1 << 30)) return AVERROR_INVALIDDATA; if ((ret = ffio_init_context(&d->pb, (unsigned char *)buf, size, 0, NULL, NULL, NULL, NULL)) < 0) return ret; d->s = s; d->level = 0; d->descr_count = 0; d->descr = descr; d->active_descr = NULL; d->max_descr_count = max_descr_count; return 0; } static void update_offsets(AVIOContext *pb, int64_t *off, int *len) { int64_t new_off = avio_tell(pb); (*len) -= new_off - *off; *off = new_off; } static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len, int target_tag); static int parse_mp4_descr_arr(MP4DescrParseContext *d, int64_t off, int len) { while (len > 0) { int ret = parse_mp4_descr(d, off, len, 0); if (ret < 0) return ret; update_offsets(&d->pb, &off, &len); } return 0; } static int parse_MP4IODescrTag(MP4DescrParseContext *d, int64_t off, int len) { avio_rb16(&d->pb); // ID avio_r8(&d->pb); avio_r8(&d->pb); avio_r8(&d->pb); avio_r8(&d->pb); avio_r8(&d->pb); update_offsets(&d->pb, &off, &len); return parse_mp4_descr_arr(d, off, len); } static int parse_MP4ODescrTag(MP4DescrParseContext *d, int64_t off, int len) { int id_flags; if (len < 2) return 0; id_flags = avio_rb16(&d->pb); if (!(id_flags & 0x0020)) { // URL_Flag update_offsets(&d->pb, &off, &len); return parse_mp4_descr_arr(d, off, len); // ES_Descriptor[] } else { return 0; } } static int parse_MP4ESDescrTag(MP4DescrParseContext *d, int64_t off, int len) { int es_id = 0; if (d->descr_count >= d->max_descr_count) return AVERROR_INVALIDDATA; ff_mp4_parse_es_descr(&d->pb, &es_id); d->active_descr = d->descr + (d->descr_count++); d->active_descr->es_id = es_id; update_offsets(&d->pb, &off, &len); parse_mp4_descr(d, off, len, MP4DecConfigDescrTag); update_offsets(&d->pb, &off, &len); if (len > 0) parse_mp4_descr(d, off, len, MP4SLDescrTag); d->active_descr = NULL; return 0; } static int parse_MP4DecConfigDescrTag(MP4DescrParseContext *d, int64_t off, int len) { Mp4Descr *descr = d->active_descr; if (!descr) return AVERROR_INVALIDDATA; d->active_descr->dec_config_descr = av_malloc(len); if (!descr->dec_config_descr) return AVERROR(ENOMEM); descr->dec_config_descr_len = len; avio_read(&d->pb, descr->dec_config_descr, len); return 0; } static int parse_MP4SLDescrTag(MP4DescrParseContext *d, int64_t off, int len) { Mp4Descr *descr = d->active_descr; int predefined; if (!descr) return AVERROR_INVALIDDATA; predefined = avio_r8(&d->pb); if (!predefined) { int lengths; int flags = avio_r8(&d->pb); descr->sl.use_au_start = !!(flags & 0x80); descr->sl.use_au_end = !!(flags & 0x40); descr->sl.use_rand_acc_pt = !!(flags & 0x20); descr->sl.use_padding = !!(flags & 0x08); descr->sl.use_timestamps = !!(flags & 0x04); descr->sl.use_idle = !!(flags & 0x02); descr->sl.timestamp_res = avio_rb32(&d->pb); avio_rb32(&d->pb); descr->sl.timestamp_len = avio_r8(&d->pb); if (descr->sl.timestamp_len > 64) { avpriv_request_sample(NULL, "timestamp_len > 64"); descr->sl.timestamp_len = 64; return AVERROR_PATCHWELCOME; } descr->sl.ocr_len = avio_r8(&d->pb); descr->sl.au_len = avio_r8(&d->pb); descr->sl.inst_bitrate_len = avio_r8(&d->pb); lengths = avio_rb16(&d->pb); descr->sl.degr_prior_len = lengths >> 12; descr->sl.au_seq_num_len = (lengths >> 7) & 0x1f; descr->sl.packet_seq_num_len = (lengths >> 2) & 0x1f; } else if (!d->predefined_SLConfigDescriptor_seen){ avpriv_report_missing_feature(d->s, "Predefined SLConfigDescriptor"); d->predefined_SLConfigDescriptor_seen = 1; } return 0; } static int parse_mp4_descr(MP4DescrParseContext *d, int64_t off, int len, int target_tag) { int tag; int len1 = ff_mp4_read_descr(d->s, &d->pb, &tag); update_offsets(&d->pb, &off, &len); if (len < 0 || len1 > len || len1 <= 0) { av_log(d->s, AV_LOG_ERROR, "Tag %x length violation new length %d bytes remaining %d\n", tag, len1, len); return AVERROR_INVALIDDATA; } if (d->level++ >= MAX_LEVEL) { av_log(d->s, AV_LOG_ERROR, "Maximum MP4 descriptor level exceeded\n"); goto done; } if (target_tag && tag != target_tag) { av_log(d->s, AV_LOG_ERROR, "Found tag %x expected %x\n", tag, target_tag); goto done; } switch (tag) { case MP4IODescrTag: parse_MP4IODescrTag(d, off, len1); break; case MP4ODescrTag: parse_MP4ODescrTag(d, off, len1); break; case MP4ESDescrTag: parse_MP4ESDescrTag(d, off, len1); break; case MP4DecConfigDescrTag: parse_MP4DecConfigDescrTag(d, off, len1); break; case MP4SLDescrTag: parse_MP4SLDescrTag(d, off, len1); break; } done: d->level--; avio_seek(&d->pb, off + len1, SEEK_SET); return 0; } static int mp4_read_iods(AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int *descr_count, int max_descr_count) { MP4DescrParseContext d; int ret; ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count); if (ret < 0) return ret; ret = parse_mp4_descr(&d, avio_tell(&d.pb), size, MP4IODescrTag); *descr_count = d.descr_count; return ret; } static int mp4_read_od(AVFormatContext *s, const uint8_t *buf, unsigned size, Mp4Descr *descr, int *descr_count, int max_descr_count) { MP4DescrParseContext d; int ret; ret = init_MP4DescrParseContext(&d, s, buf, size, descr, max_descr_count); if (ret < 0) return ret; ret = parse_mp4_descr_arr(&d, avio_tell(&d.pb), size); *descr_count = d.descr_count; return ret; } static void m4sl_cb(MpegTSFilter *filter, const uint8_t *section, int section_len) { MpegTSContext *ts = filter->u.section_filter.opaque; SectionHeader h; const uint8_t *p, *p_end; AVIOContext pb; int mp4_descr_count = 0; Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } }; int i, pid; AVFormatContext *s = ts->stream; p_end = section + section_len - 4; p = section; if (parse_section_header(&h, &p, p_end) < 0) return; if (h.tid != M4OD_TID) return; mp4_read_od(s, p, (unsigned) (p_end - p), mp4_descr, &mp4_descr_count, MAX_MP4_DESCR_COUNT); for (pid = 0; pid < NB_PID_MAX; pid++) { if (!ts->pids[pid]) continue; for (i = 0; i < mp4_descr_count; i++) { PESContext *pes; AVStream *st; if (ts->pids[pid]->es_id != mp4_descr[i].es_id) continue; if (ts->pids[pid]->type != MPEGTS_PES) { av_log(s, AV_LOG_ERROR, "pid %x is not PES\n", pid); continue; } pes = ts->pids[pid]->u.pes_filter.opaque; st = pes->st; if (!st) continue; pes->sl = mp4_descr[i].sl; ffio_init_context(&pb, mp4_descr[i].dec_config_descr, mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL); ff_mp4_read_dec_config_descr(s, st, &pb); if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size > 0) st->need_parsing = 0; if (st->codec->codec_id == AV_CODEC_ID_H264 && st->codec->extradata_size > 0) st->need_parsing = 0; if (st->codec->codec_id <= AV_CODEC_ID_NONE) { // do nothing } else if (st->codec->codec_id < AV_CODEC_ID_FIRST_AUDIO) st->codec->codec_type = AVMEDIA_TYPE_VIDEO; else if (st->codec->codec_id < AV_CODEC_ID_FIRST_SUBTITLE) st->codec->codec_type = AVMEDIA_TYPE_AUDIO; else if (st->codec->codec_id < AV_CODEC_ID_FIRST_UNKNOWN) st->codec->codec_type = AVMEDIA_TYPE_SUBTITLE; } } for (i = 0; i < mp4_descr_count; i++) av_free(mp4_descr[i].dec_config_descr); } static const uint8_t opus_coupled_stream_cnt[9] = { 1, 0, 1, 1, 2, 2, 2, 3, 3 }; static const uint8_t opus_channel_map[8][8] = { { 0 }, { 0,1 }, { 0,2,1 }, { 0,1,2,3 }, { 0,4,1,2,3 }, { 0,4,1,2,3,5 }, { 0,4,1,2,3,5,6 }, { 0,6,1,2,3,4,5,7 }, }; int ff_parse_mpeg2_descriptor(AVFormatContext *fc, AVStream *st, int stream_type, const uint8_t **pp, const uint8_t *desc_list_end, Mp4Descr *mp4_descr, int mp4_descr_count, int pid, MpegTSContext *ts) { const uint8_t *desc_end; int desc_len, desc_tag, desc_es_id, ext_desc_tag, channels, channel_config_code; char language[252]; int i; desc_tag = get8(pp, desc_list_end); if (desc_tag < 0) return AVERROR_INVALIDDATA; desc_len = get8(pp, desc_list_end); if (desc_len < 0) return AVERROR_INVALIDDATA; desc_end = *pp + desc_len; if (desc_end > desc_list_end) return AVERROR_INVALIDDATA; av_dlog(fc, "tag: 0x%02x len=%d\n", desc_tag, desc_len); if ((st->codec->codec_id == AV_CODEC_ID_NONE || st->request_probe > 0) && stream_type == STREAM_TYPE_PRIVATE_DATA) mpegts_find_stream_type(st, desc_tag, DESC_types); switch (desc_tag) { case 0x1E: /* SL descriptor */ desc_es_id = get16(pp, desc_end); if (ts && ts->pids[pid]) ts->pids[pid]->es_id = desc_es_id; for (i = 0; i < mp4_descr_count; i++) if (mp4_descr[i].dec_config_descr_len && mp4_descr[i].es_id == desc_es_id) { AVIOContext pb; ffio_init_context(&pb, mp4_descr[i].dec_config_descr, mp4_descr[i].dec_config_descr_len, 0, NULL, NULL, NULL, NULL); ff_mp4_read_dec_config_descr(fc, st, &pb); if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size > 0) st->need_parsing = 0; if (st->codec->codec_id == AV_CODEC_ID_MPEG4SYSTEMS) mpegts_open_section_filter(ts, pid, m4sl_cb, ts, 1); } break; case 0x1F: /* FMC descriptor */ get16(pp, desc_end); if (mp4_descr_count > 0 && (st->codec->codec_id == AV_CODEC_ID_AAC_LATM || st->request_probe > 0) && mp4_descr->dec_config_descr_len && mp4_descr->es_id == pid) { AVIOContext pb; ffio_init_context(&pb, mp4_descr->dec_config_descr, mp4_descr->dec_config_descr_len, 0, NULL, NULL, NULL, NULL); ff_mp4_read_dec_config_descr(fc, st, &pb); if (st->codec->codec_id == AV_CODEC_ID_AAC && st->codec->extradata_size > 0) { st->request_probe = st->need_parsing = 0; st->codec->codec_type = AVMEDIA_TYPE_AUDIO; } } break; case 0x56: /* DVB teletext descriptor */ { uint8_t *extradata = NULL; int language_count = desc_len / 5; if (desc_len > 0 && desc_len % 5 != 0) return AVERROR_INVALIDDATA; if (language_count > 0) { /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */ if (language_count > sizeof(language) / 4) { language_count = sizeof(language) / 4; } if (st->codec->extradata == NULL) { if (ff_alloc_extradata(st->codec, language_count * 2)) { return AVERROR(ENOMEM); } } if (st->codec->extradata_size < language_count * 2) return AVERROR_INVALIDDATA; extradata = st->codec->extradata; for (i = 0; i < language_count; i++) { language[i * 4 + 0] = get8(pp, desc_end); language[i * 4 + 1] = get8(pp, desc_end); language[i * 4 + 2] = get8(pp, desc_end); language[i * 4 + 3] = ','; memcpy(extradata, *pp, 2); extradata += 2; *pp += 2; } language[i * 4 - 1] = 0; av_dict_set(&st->metadata, "language", language, 0); } } break; case 0x59: /* subtitling descriptor */ { /* 8 bytes per DVB subtitle substream data: * ISO_639_language_code (3 bytes), * subtitling_type (1 byte), * composition_page_id (2 bytes), * ancillary_page_id (2 bytes) */ int language_count = desc_len / 8; if (desc_len > 0 && desc_len % 8 != 0) return AVERROR_INVALIDDATA; if (language_count > 1) { avpriv_request_sample(fc, "DVB subtitles with multiple languages"); } if (language_count > 0) { uint8_t *extradata; /* 4 bytes per language code (3 bytes) with comma or NUL byte should fit language buffer */ if (language_count > sizeof(language) / 4) { language_count = sizeof(language) / 4; } if (st->codec->extradata == NULL) { if (ff_alloc_extradata(st->codec, language_count * 5)) { return AVERROR(ENOMEM); } } if (st->codec->extradata_size < language_count * 5) return AVERROR_INVALIDDATA; extradata = st->codec->extradata; for (i = 0; i < language_count; i++) { language[i * 4 + 0] = get8(pp, desc_end); language[i * 4 + 1] = get8(pp, desc_end); language[i * 4 + 2] = get8(pp, desc_end); language[i * 4 + 3] = ','; /* hearing impaired subtitles detection using subtitling_type */ switch (*pp[0]) { case 0x20: /* DVB subtitles (for the hard of hearing) with no monitor aspect ratio criticality */ case 0x21: /* DVB subtitles (for the hard of hearing) for display on 4:3 aspect ratio monitor */ case 0x22: /* DVB subtitles (for the hard of hearing) for display on 16:9 aspect ratio monitor */ case 0x23: /* DVB subtitles (for the hard of hearing) for display on 2.21:1 aspect ratio monitor */ case 0x24: /* DVB subtitles (for the hard of hearing) for display on a high definition monitor */ case 0x25: /* DVB subtitles (for the hard of hearing) with plano-stereoscopic disparity for display on a high definition monitor */ st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break; } extradata[4] = get8(pp, desc_end); /* subtitling_type */ memcpy(extradata, *pp, 4); /* composition_page_id and ancillary_page_id */ extradata += 5; *pp += 4; } language[i * 4 - 1] = 0; av_dict_set(&st->metadata, "language", language, 0); } } break; case 0x0a: /* ISO 639 language descriptor */ for (i = 0; i + 4 <= desc_len; i += 4) { language[i + 0] = get8(pp, desc_end); language[i + 1] = get8(pp, desc_end); language[i + 2] = get8(pp, desc_end); language[i + 3] = ','; switch (get8(pp, desc_end)) { case 0x01: st->disposition |= AV_DISPOSITION_CLEAN_EFFECTS; break; case 0x02: st->disposition |= AV_DISPOSITION_HEARING_IMPAIRED; break; case 0x03: st->disposition |= AV_DISPOSITION_VISUAL_IMPAIRED; break; } } if (i && language[0]) { language[i - 1] = 0; av_dict_set(&st->metadata, "language", language, 0); } break; case 0x05: /* registration descriptor */ st->codec->codec_tag = bytestream_get_le32(pp); av_dlog(fc, "reg_desc=%.4s\n", (char *)&st->codec->codec_tag); if (st->codec->codec_id == AV_CODEC_ID_NONE) mpegts_find_stream_type(st, st->codec->codec_tag, REGD_types); break; case 0x52: /* stream identifier descriptor */ st->stream_identifier = 1 + get8(pp, desc_end); break; case 0x26: /* metadata descriptor */ if (get16(pp, desc_end) == 0xFFFF) *pp += 4; if (get8(pp, desc_end) == 0xFF) { st->codec->codec_tag = bytestream_get_le32(pp); if (st->codec->codec_id == AV_CODEC_ID_NONE) mpegts_find_stream_type(st, st->codec->codec_tag, METADATA_types); } break; case 0x7f: /* DVB extension descriptor */ ext_desc_tag = get8(pp, desc_end); if (ext_desc_tag < 0) return AVERROR_INVALIDDATA; if (st->codec->codec_id == AV_CODEC_ID_OPUS && ext_desc_tag == 0x80) { /* User defined (provisional Opus) */ if (!st->codec->extradata) { st->codec->extradata = av_mallocz(sizeof(opus_default_extradata) + FF_INPUT_BUFFER_PADDING_SIZE); if (!st->codec->extradata) return AVERROR(ENOMEM); st->codec->extradata_size = sizeof(opus_default_extradata); memcpy(st->codec->extradata, opus_default_extradata, sizeof(opus_default_extradata)); channel_config_code = get8(pp, desc_end); if (channel_config_code < 0) return AVERROR_INVALIDDATA; if (channel_config_code <= 0x8) { st->codec->extradata[9] = channels = channel_config_code ? channel_config_code : 2; st->codec->extradata[18] = channels > 2; st->codec->extradata[19] = channel_config_code; if (channel_config_code == 0) { /* Dual Mono */ st->codec->extradata[18] = 255; /* Mapping */ st->codec->extradata[19] = 2; /* Stream Count */ } st->codec->extradata[20] = opus_coupled_stream_cnt[channel_config_code]; memcpy(&st->codec->extradata[21], opus_channel_map[channels - 1], channels); } else { avpriv_request_sample(fc, "Opus in MPEG-TS - channel_config_code > 0x8"); } st->need_parsing = AVSTREAM_PARSE_FULL; } } break; default: break; } *pp = desc_end; return 0; } static void pmt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len) { MpegTSContext *ts = filter->u.section_filter.opaque; SectionHeader h1, *h = &h1; PESContext *pes; AVStream *st; const uint8_t *p, *p_end, *desc_list_end; int program_info_length, pcr_pid, pid, stream_type; int desc_list_len; uint32_t prog_reg_desc = 0; /* registration descriptor */ int mp4_descr_count = 0; Mp4Descr mp4_descr[MAX_MP4_DESCR_COUNT] = { { 0 } }; int i; av_dlog(ts->stream, "PMT: len %i\n", section_len); hex_dump_debug(ts->stream, section, section_len); p_end = section + section_len - 4; p = section; if (parse_section_header(h, &p, p_end) < 0) return; av_dlog(ts->stream, "sid=0x%x sec_num=%d/%d version=%d\n", h->id, h->sec_num, h->last_sec_num, h->version); if (h->tid != PMT_TID) return; if (!ts->scan_all_pmts && ts->skip_changes) return; if (!ts->skip_clear) clear_program(ts, h->id); pcr_pid = get16(&p, p_end); if (pcr_pid < 0) return; pcr_pid &= 0x1fff; add_pid_to_pmt(ts, h->id, pcr_pid); set_pcr_pid(ts->stream, h->id, pcr_pid); av_dlog(ts->stream, "pcr_pid=0x%x\n", pcr_pid); program_info_length = get16(&p, p_end); if (program_info_length < 0) return; program_info_length &= 0xfff; while (program_info_length >= 2) { uint8_t tag, len; tag = get8(&p, p_end); len = get8(&p, p_end); av_dlog(ts->stream, "program tag: 0x%02x len=%d\n", tag, len); if (len > program_info_length - 2) // something else is broken, exit the program_descriptors_loop break; program_info_length -= len + 2; if (tag == 0x1d) { // IOD descriptor get8(&p, p_end); // scope get8(&p, p_end); // label len -= 2; mp4_read_iods(ts->stream, p, len, mp4_descr + mp4_descr_count, &mp4_descr_count, MAX_MP4_DESCR_COUNT); } else if (tag == 0x05 && len >= 4) { // registration descriptor prog_reg_desc = bytestream_get_le32(&p); len -= 4; } p += len; } p += program_info_length; if (p >= p_end) goto out; // stop parsing after pmt, we found header if (!ts->stream->nb_streams) ts->stop_parse = 2; set_pmt_found(ts, h->id); for (;;) { st = 0; pes = NULL; stream_type = get8(&p, p_end); if (stream_type < 0) break; pid = get16(&p, p_end); if (pid < 0) goto out; pid &= 0x1fff; if (pid == ts->current_pid) goto out; /* now create stream */ if (ts->pids[pid] && ts->pids[pid]->type == MPEGTS_PES) { pes = ts->pids[pid]->u.pes_filter.opaque; if (!pes->st) { pes->st = avformat_new_stream(pes->stream, NULL); if (!pes->st) goto out; pes->st->id = pes->pid; } st = pes->st; } else if (stream_type != 0x13) { if (ts->pids[pid]) mpegts_close_filter(ts, ts->pids[pid]); // wrongly added sdt filter probably pes = add_pes_stream(ts, pid, pcr_pid); if (pes) { st = avformat_new_stream(pes->stream, NULL); if (!st) goto out; st->id = pes->pid; } } else { int idx = ff_find_stream_index(ts->stream, pid); if (idx >= 0) { st = ts->stream->streams[idx]; } else { st = avformat_new_stream(ts->stream, NULL); if (!st) goto out; st->id = pid; st->codec->codec_type = AVMEDIA_TYPE_DATA; } } if (!st) goto out; if (pes && !pes->stream_type) mpegts_set_stream_info(st, pes, stream_type, prog_reg_desc); add_pid_to_pmt(ts, h->id, pid); ff_program_add_stream_index(ts->stream, h->id, st->index); desc_list_len = get16(&p, p_end); if (desc_list_len < 0) goto out; desc_list_len &= 0xfff; desc_list_end = p + desc_list_len; if (desc_list_end > p_end) goto out; for (;;) { if (ff_parse_mpeg2_descriptor(ts->stream, st, stream_type, &p, desc_list_end, mp4_descr, mp4_descr_count, pid, ts) < 0) break; if (pes && prog_reg_desc == AV_RL32("HDMV") && stream_type == 0x83 && pes->sub_st) { ff_program_add_stream_index(ts->stream, h->id, pes->sub_st->index); pes->sub_st->codec->codec_tag = st->codec->codec_tag; } } p = desc_list_end; } if (!ts->pids[pcr_pid]) mpegts_open_pcr_filter(ts, pcr_pid); out: for (i = 0; i < mp4_descr_count; i++) av_free(mp4_descr[i].dec_config_descr); } static void pat_cb(MpegTSFilter *filter, const uint8_t *section, int section_len) { MpegTSContext *ts = filter->u.section_filter.opaque; SectionHeader h1, *h = &h1; const uint8_t *p, *p_end; int sid, pmt_pid; AVProgram *program; av_dlog(ts->stream, "PAT:\n"); hex_dump_debug(ts->stream, section, section_len); p_end = section + section_len - 4; p = section; if (parse_section_header(h, &p, p_end) < 0) return; if (h->tid != PAT_TID) return; if (ts->skip_changes) return; ts->stream->ts_id = h->id; clear_programs(ts); for (;;) { sid = get16(&p, p_end); if (sid < 0) break; pmt_pid = get16(&p, p_end); if (pmt_pid < 0) break; pmt_pid &= 0x1fff; if (pmt_pid == ts->current_pid) break; av_dlog(ts->stream, "sid=0x%x pid=0x%x\n", sid, pmt_pid); if (sid == 0x0000) { /* NIT info */ } else { MpegTSFilter *fil = ts->pids[pmt_pid]; program = av_new_program(ts->stream, sid); if (program) { program->program_num = sid; program->pmt_pid = pmt_pid; } if (fil) if ( fil->type != MPEGTS_SECTION || fil->pid != pmt_pid || fil->u.section_filter.section_cb != pmt_cb) mpegts_close_filter(ts, ts->pids[pmt_pid]); if (!ts->pids[pmt_pid]) mpegts_open_section_filter(ts, pmt_pid, pmt_cb, ts, 1); add_pat_entry(ts, sid); add_pid_to_pmt(ts, sid, 0); // add pat pid to program add_pid_to_pmt(ts, sid, pmt_pid); } } if (sid < 0) { int i,j; for (j=0; j<ts->stream->nb_programs; j++) { for (i = 0; i < ts->nb_prg; i++) if (ts->prg[i].id == ts->stream->programs[j]->id) break; if (i==ts->nb_prg && !ts->skip_clear) clear_avprogram(ts, ts->stream->programs[j]->id); } } } static void sdt_cb(MpegTSFilter *filter, const uint8_t *section, int section_len) { MpegTSContext *ts = filter->u.section_filter.opaque; SectionHeader h1, *h = &h1; const uint8_t *p, *p_end, *desc_list_end, *desc_end; int onid, val, sid, desc_list_len, desc_tag, desc_len, service_type; char *name, *provider_name; av_dlog(ts->stream, "SDT:\n"); hex_dump_debug(ts->stream, section, section_len); p_end = section + section_len - 4; p = section; if (parse_section_header(h, &p, p_end) < 0) return; if (h->tid != SDT_TID) return; if (ts->skip_changes) return; onid = get16(&p, p_end); if (onid < 0) return; val = get8(&p, p_end); if (val < 0) return; for (;;) { sid = get16(&p, p_end); if (sid < 0) break; val = get8(&p, p_end); if (val < 0) break; desc_list_len = get16(&p, p_end); if (desc_list_len < 0) break; desc_list_len &= 0xfff; desc_list_end = p + desc_list_len; if (desc_list_end > p_end) break; for (;;) { desc_tag = get8(&p, desc_list_end); if (desc_tag < 0) break; desc_len = get8(&p, desc_list_end); desc_end = p + desc_len; if (desc_len < 0 || desc_end > desc_list_end) break; av_dlog(ts->stream, "tag: 0x%02x len=%d\n", desc_tag, desc_len); switch (desc_tag) { case 0x48: service_type = get8(&p, p_end); if (service_type < 0) break; provider_name = getstr8(&p, p_end); if (!provider_name) break; name = getstr8(&p, p_end); if (name) { AVProgram *program = av_new_program(ts->stream, sid); if (program) { av_dict_set(&program->metadata, "service_name", name, 0); av_dict_set(&program->metadata, "service_provider", provider_name, 0); } } av_free(name); av_free(provider_name); break; default: break; } p = desc_end; } p = desc_list_end; } } static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet); /* handle one TS packet */ static int handle_packet(MpegTSContext *ts, const uint8_t *packet) { MpegTSFilter *tss; int len, pid, cc, expected_cc, cc_ok, afc, is_start, is_discontinuity, has_adaptation, has_payload; const uint8_t *p, *p_end; int64_t pos; pid = AV_RB16(packet + 1) & 0x1fff; if (pid && discard_pid(ts, pid)) return 0; is_start = packet[1] & 0x40; tss = ts->pids[pid]; if (ts->auto_guess && !tss && is_start) { add_pes_stream(ts, pid, -1); tss = ts->pids[pid]; } if (!tss) return 0; ts->current_pid = pid; afc = (packet[3] >> 4) & 3; if (afc == 0) /* reserved value */ return 0; has_adaptation = afc & 2; has_payload = afc & 1; is_discontinuity = has_adaptation && packet[4] != 0 && /* with length > 0 */ (packet[5] & 0x80); /* and discontinuity indicated */ /* continuity check (currently not used) */ cc = (packet[3] & 0xf); expected_cc = has_payload ? (tss->last_cc + 1) & 0x0f : tss->last_cc; cc_ok = pid == 0x1FFF || // null packet PID is_discontinuity || tss->last_cc < 0 || expected_cc == cc; tss->last_cc = cc; if (!cc_ok) { av_log(ts->stream, AV_LOG_DEBUG, "Continuity check failed for pid %d expected %d got %d\n", pid, expected_cc, cc); if (tss->type == MPEGTS_PES) { PESContext *pc = tss->u.pes_filter.opaque; pc->flags |= AV_PKT_FLAG_CORRUPT; } } p = packet + 4; if (has_adaptation) { int64_t pcr_h; int pcr_l; if (parse_pcr(&pcr_h, &pcr_l, packet) == 0) tss->last_pcr = pcr_h * 300 + pcr_l; /* skip adaptation field */ p += p[0] + 1; } /* if past the end of packet, ignore */ p_end = packet + TS_PACKET_SIZE; if (p >= p_end || !has_payload) return 0; pos = avio_tell(ts->stream->pb); if (pos >= 0) { av_assert0(pos >= TS_PACKET_SIZE); ts->pos47_full = pos - TS_PACKET_SIZE; } if (tss->type == MPEGTS_SECTION) { if (is_start) { /* pointer field present */ len = *p++; if (p + len > p_end) return 0; if (len && cc_ok) { /* write remaining section bytes */ write_section_data(ts, tss, p, len, 0); /* check whether filter has been closed */ if (!ts->pids[pid]) return 0; } p += len; if (p < p_end) { write_section_data(ts, tss, p, p_end - p, 1); } } else { if (cc_ok) { write_section_data(ts, tss, p, p_end - p, 0); } } // stop find_stream_info from waiting for more streams // when all programs have received a PMT if (ts->stream->ctx_flags & AVFMTCTX_NOHEADER && ts->scan_all_pmts <= 0) { int i; for (i = 0; i < ts->nb_prg; i++) { if (!ts->prg[i].pmt_found) break; } if (i == ts->nb_prg && ts->nb_prg > 0) { int types = 0; for (i = 0; i < ts->stream->nb_streams; i++) { AVStream *st = ts->stream->streams[i]; types |= 1<<st->codec->codec_type; } if ((types & (1<<AVMEDIA_TYPE_AUDIO) && types & (1<<AVMEDIA_TYPE_VIDEO)) || pos > 100000) { av_log(ts->stream, AV_LOG_DEBUG, "All programs have pmt, headers found\n"); ts->stream->ctx_flags &= ~AVFMTCTX_NOHEADER; } } } } else { int ret; // Note: The position here points actually behind the current packet. if (tss->type == MPEGTS_PES) { if ((ret = tss->u.pes_filter.pes_cb(tss, p, p_end - p, is_start, pos - ts->raw_packet_size)) < 0) return ret; } } return 0; } static void reanalyze(MpegTSContext *ts) { AVIOContext *pb = ts->stream->pb; int64_t pos = avio_tell(pb); if (pos < 0) return; pos -= ts->pos47_full; if (pos == TS_PACKET_SIZE) { ts->size_stat[0] ++; } else if (pos == TS_DVHS_PACKET_SIZE) { ts->size_stat[1] ++; } else if (pos == TS_FEC_PACKET_SIZE) { ts->size_stat[2] ++; } ts->size_stat_count ++; if (ts->size_stat_count > SIZE_STAT_THRESHOLD) { int newsize = 0; if (ts->size_stat[0] > SIZE_STAT_THRESHOLD) { newsize = TS_PACKET_SIZE; } else if (ts->size_stat[1] > SIZE_STAT_THRESHOLD) { newsize = TS_DVHS_PACKET_SIZE; } else if (ts->size_stat[2] > SIZE_STAT_THRESHOLD) { newsize = TS_FEC_PACKET_SIZE; } if (newsize && newsize != ts->raw_packet_size) { av_log(ts->stream, AV_LOG_WARNING, "changing packet size to %d\n", newsize); ts->raw_packet_size = newsize; } ts->size_stat_count = 0; memset(ts->size_stat, 0, sizeof(ts->size_stat)); } } /* XXX: try to find a better synchro over several packets (use * get_packet_size() ?) */ static int mpegts_resync(AVFormatContext *s) { MpegTSContext *ts = s->priv_data; AVIOContext *pb = s->pb; int c, i; for (i = 0; i < ts->resync_size; i++) { c = avio_r8(pb); if (avio_feof(pb)) return AVERROR_EOF; if (c == 0x47) { avio_seek(pb, -1, SEEK_CUR); reanalyze(s->priv_data); return 0; } } av_log(s, AV_LOG_ERROR, "max resync size reached, could not find sync byte\n"); /* no sync found */ return AVERROR_INVALIDDATA; } /* return AVERROR_something if error or EOF. Return 0 if OK. */ static int read_packet(AVFormatContext *s, uint8_t *buf, int raw_packet_size, const uint8_t **data) { AVIOContext *pb = s->pb; int len; for (;;) { len = ffio_read_indirect(pb, buf, TS_PACKET_SIZE, data); if (len != TS_PACKET_SIZE) return len < 0 ? len : AVERROR_EOF; /* check packet sync byte */ if ((*data)[0] != 0x47) { /* find a new packet start */ uint64_t pos = avio_tell(pb); avio_seek(pb, -FFMIN(raw_packet_size, pos), SEEK_CUR); if (mpegts_resync(s) < 0) return AVERROR(EAGAIN); else continue; } else { break; } } return 0; } static void finished_reading_packet(AVFormatContext *s, int raw_packet_size) { AVIOContext *pb = s->pb; int skip = raw_packet_size - TS_PACKET_SIZE; if (skip > 0) avio_skip(pb, skip); } static int handle_packets(MpegTSContext *ts, int64_t nb_packets) { AVFormatContext *s = ts->stream; uint8_t packet[TS_PACKET_SIZE + FF_INPUT_BUFFER_PADDING_SIZE]; const uint8_t *data; int64_t packet_num; int ret = 0; if (avio_tell(s->pb) != ts->last_pos) { int i; av_dlog(ts->stream, "Skipping after seek\n"); /* seek detected, flush pes buffer */ for (i = 0; i < NB_PID_MAX; i++) { if (ts->pids[i]) { if (ts->pids[i]->type == MPEGTS_PES) { PESContext *pes = ts->pids[i]->u.pes_filter.opaque; av_buffer_unref(&pes->buffer); pes->data_index = 0; pes->state = MPEGTS_SKIP; /* skip until pes header */ } ts->pids[i]->last_cc = -1; ts->pids[i]->last_pcr = -1; } } } ts->stop_parse = 0; packet_num = 0; memset(packet + TS_PACKET_SIZE, 0, FF_INPUT_BUFFER_PADDING_SIZE); for (;;) { packet_num++; if (nb_packets != 0 && packet_num >= nb_packets || ts->stop_parse > 1) { ret = AVERROR(EAGAIN); break; } if (ts->stop_parse > 0) break; ret = read_packet(s, packet, ts->raw_packet_size, &data); if (ret != 0) break; ret = handle_packet(ts, data); finished_reading_packet(s, ts->raw_packet_size); if (ret != 0) break; } ts->last_pos = avio_tell(s->pb); return ret; } static int mpegts_probe(AVProbeData *p) { const int size = p->buf_size; int maxscore = 0; int sumscore = 0; int i; int check_count = size / TS_FEC_PACKET_SIZE; #define CHECK_COUNT 10 #define CHECK_BLOCK 100 if (check_count < CHECK_COUNT) return AVERROR_INVALIDDATA; for (i = 0; i<check_count; i+=CHECK_BLOCK) { int left = FFMIN(check_count - i, CHECK_BLOCK); int score = analyze(p->buf + TS_PACKET_SIZE *i, TS_PACKET_SIZE *left, TS_PACKET_SIZE , NULL); int dvhs_score = analyze(p->buf + TS_DVHS_PACKET_SIZE*i, TS_DVHS_PACKET_SIZE*left, TS_DVHS_PACKET_SIZE, NULL); int fec_score = analyze(p->buf + TS_FEC_PACKET_SIZE *i, TS_FEC_PACKET_SIZE *left, TS_FEC_PACKET_SIZE , NULL); score = FFMAX3(score, dvhs_score, fec_score); sumscore += score; maxscore = FFMAX(maxscore, score); } sumscore = sumscore * CHECK_COUNT / check_count; maxscore = maxscore * CHECK_COUNT / CHECK_BLOCK; av_dlog(0, "TS score: %d %d\n", sumscore, maxscore); if (sumscore > 6) return AVPROBE_SCORE_MAX + sumscore - CHECK_COUNT; else if (maxscore > 6) return AVPROBE_SCORE_MAX/2 + sumscore - CHECK_COUNT; else return AVERROR_INVALIDDATA; } /* return the 90kHz PCR and the extension for the 27MHz PCR. return * (-1) if not available */ static int parse_pcr(int64_t *ppcr_high, int *ppcr_low, const uint8_t *packet) { int afc, len, flags; const uint8_t *p; unsigned int v; afc = (packet[3] >> 4) & 3; if (afc <= 1) return AVERROR_INVALIDDATA; p = packet + 4; len = p[0]; p++; if (len == 0) return AVERROR_INVALIDDATA; flags = *p++; len--; if (!(flags & 0x10)) return AVERROR_INVALIDDATA; if (len < 6) return AVERROR_INVALIDDATA; v = AV_RB32(p); *ppcr_high = ((int64_t) v << 1) | (p[4] >> 7); *ppcr_low = ((p[4] & 1) << 8) | p[5]; return 0; } static void seek_back(AVFormatContext *s, AVIOContext *pb, int64_t pos) { /* NOTE: We attempt to seek on non-seekable files as well, as the * probe buffer usually is big enough. Only warn if the seek failed * on files where the seek should work. */ if (avio_seek(pb, pos, SEEK_SET) < 0) av_log(s, pb->seekable ? AV_LOG_ERROR : AV_LOG_INFO, "Unable to seek back to the start\n"); } static int mpegts_read_header(AVFormatContext *s) { MpegTSContext *ts = s->priv_data; AVIOContext *pb = s->pb; uint8_t buf[8 * 1024] = {0}; int len; int64_t pos, probesize = s->probesize ? s->probesize : s->probesize2; ffio_ensure_seekback(pb, probesize); /* read the first 8192 bytes to get packet size */ pos = avio_tell(pb); len = avio_read(pb, buf, sizeof(buf)); ts->raw_packet_size = get_packet_size(buf, len); if (ts->raw_packet_size <= 0) { av_log(s, AV_LOG_WARNING, "Could not detect TS packet size, defaulting to non-FEC/DVHS\n"); ts->raw_packet_size = TS_PACKET_SIZE; } ts->stream = s; ts->auto_guess = 0; if (s->iformat == &ff_mpegts_demuxer) { /* normal demux */ /* first do a scan to get all the services */ seek_back(s, pb, pos); mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1); mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1); handle_packets(ts, probesize / ts->raw_packet_size); /* if could not find service, enable auto_guess */ ts->auto_guess = 1; av_dlog(ts->stream, "tuning done\n"); s->ctx_flags |= AVFMTCTX_NOHEADER; } else { AVStream *st; int pcr_pid, pid, nb_packets, nb_pcrs, ret, pcr_l; int64_t pcrs[2], pcr_h; int packet_count[2]; uint8_t packet[TS_PACKET_SIZE]; const uint8_t *data; /* only read packets */ st = avformat_new_stream(s, NULL); if (!st) return AVERROR(ENOMEM); avpriv_set_pts_info(st, 60, 1, 27000000); st->codec->codec_type = AVMEDIA_TYPE_DATA; st->codec->codec_id = AV_CODEC_ID_MPEG2TS; /* we iterate until we find two PCRs to estimate the bitrate */ pcr_pid = -1; nb_pcrs = 0; nb_packets = 0; for (;;) { ret = read_packet(s, packet, ts->raw_packet_size, &data); if (ret < 0) return ret; pid = AV_RB16(data + 1) & 0x1fff; if ((pcr_pid == -1 || pcr_pid == pid) && parse_pcr(&pcr_h, &pcr_l, data) == 0) { finished_reading_packet(s, ts->raw_packet_size); pcr_pid = pid; packet_count[nb_pcrs] = nb_packets; pcrs[nb_pcrs] = pcr_h * 300 + pcr_l; nb_pcrs++; if (nb_pcrs >= 2) break; } else { finished_reading_packet(s, ts->raw_packet_size); } nb_packets++; } /* NOTE1: the bitrate is computed without the FEC */ /* NOTE2: it is only the bitrate of the start of the stream */ ts->pcr_incr = (pcrs[1] - pcrs[0]) / (packet_count[1] - packet_count[0]); ts->cur_pcr = pcrs[0] - ts->pcr_incr * packet_count[0]; s->bit_rate = TS_PACKET_SIZE * 8 * 27e6 / ts->pcr_incr; st->codec->bit_rate = s->bit_rate; st->start_time = ts->cur_pcr; av_dlog(ts->stream, "start=%0.3f pcr=%0.3f incr=%d\n", st->start_time / 1000000.0, pcrs[0] / 27e6, ts->pcr_incr); } seek_back(s, pb, pos); return 0; } #define MAX_PACKET_READAHEAD ((128 * 1024) / 188) static int mpegts_raw_read_packet(AVFormatContext *s, AVPacket *pkt) { MpegTSContext *ts = s->priv_data; int ret, i; int64_t pcr_h, next_pcr_h, pos; int pcr_l, next_pcr_l; uint8_t pcr_buf[12]; const uint8_t *data; if (av_new_packet(pkt, TS_PACKET_SIZE) < 0) return AVERROR(ENOMEM); ret = read_packet(s, pkt->data, ts->raw_packet_size, &data); pkt->pos = avio_tell(s->pb); if (ret < 0) { av_free_packet(pkt); return ret; } if (data != pkt->data) memcpy(pkt->data, data, ts->raw_packet_size); finished_reading_packet(s, ts->raw_packet_size); if (ts->mpeg2ts_compute_pcr) { /* compute exact PCR for each packet */ if (parse_pcr(&pcr_h, &pcr_l, pkt->data) == 0) { /* we read the next PCR (XXX: optimize it by using a bigger buffer */ pos = avio_tell(s->pb); for (i = 0; i < MAX_PACKET_READAHEAD; i++) { avio_seek(s->pb, pos + i * ts->raw_packet_size, SEEK_SET); avio_read(s->pb, pcr_buf, 12); if (parse_pcr(&next_pcr_h, &next_pcr_l, pcr_buf) == 0) { /* XXX: not precise enough */ ts->pcr_incr = ((next_pcr_h - pcr_h) * 300 + (next_pcr_l - pcr_l)) / (i + 1); break; } } avio_seek(s->pb, pos, SEEK_SET); /* no next PCR found: we use previous increment */ ts->cur_pcr = pcr_h * 300 + pcr_l; } pkt->pts = ts->cur_pcr; pkt->duration = ts->pcr_incr; ts->cur_pcr += ts->pcr_incr; } pkt->stream_index = 0; return 0; } static int mpegts_read_packet(AVFormatContext *s, AVPacket *pkt) { MpegTSContext *ts = s->priv_data; int ret, i; pkt->size = -1; ts->pkt = pkt; ret = handle_packets(ts, 0); if (ret < 0) { av_free_packet(ts->pkt); /* flush pes data left */ for (i = 0; i < NB_PID_MAX; i++) if (ts->pids[i] && ts->pids[i]->type == MPEGTS_PES) { PESContext *pes = ts->pids[i]->u.pes_filter.opaque; if (pes->state == MPEGTS_PAYLOAD && pes->data_index > 0) { new_pes_packet(pes, pkt); pes->state = MPEGTS_SKIP; ret = 0; break; } } } if (!ret && pkt->size < 0) ret = AVERROR(EINTR); return ret; } static void mpegts_free(MpegTSContext *ts) { int i; clear_programs(ts); for (i = 0; i < NB_PID_MAX; i++) if (ts->pids[i]) mpegts_close_filter(ts, ts->pids[i]); } static int mpegts_read_close(AVFormatContext *s) { MpegTSContext *ts = s->priv_data; mpegts_free(ts); return 0; } static av_unused int64_t mpegts_get_pcr(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { MpegTSContext *ts = s->priv_data; int64_t pos, timestamp; uint8_t buf[TS_PACKET_SIZE]; int pcr_l, pcr_pid = ((PESContext *)s->streams[stream_index]->priv_data)->pcr_pid; int pos47 = ts->pos47_full % ts->raw_packet_size; pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47; while(pos < pos_limit) { if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; if (avio_read(s->pb, buf, TS_PACKET_SIZE) != TS_PACKET_SIZE) return AV_NOPTS_VALUE; if (buf[0] != 0x47) { avio_seek(s->pb, -TS_PACKET_SIZE, SEEK_CUR); if (mpegts_resync(s) < 0) return AV_NOPTS_VALUE; pos = avio_tell(s->pb); continue; } if ((pcr_pid < 0 || (AV_RB16(buf + 1) & 0x1fff) == pcr_pid) && parse_pcr(&timestamp, &pcr_l, buf) == 0) { *ppos = pos; return timestamp; } pos += ts->raw_packet_size; } return AV_NOPTS_VALUE; } static int64_t mpegts_get_dts(AVFormatContext *s, int stream_index, int64_t *ppos, int64_t pos_limit) { MpegTSContext *ts = s->priv_data; int64_t pos; int pos47 = ts->pos47_full % ts->raw_packet_size; pos = ((*ppos + ts->raw_packet_size - 1 - pos47) / ts->raw_packet_size) * ts->raw_packet_size + pos47; ff_read_frame_flush(s); if (avio_seek(s->pb, pos, SEEK_SET) < 0) return AV_NOPTS_VALUE; while(pos < pos_limit) { int ret; AVPacket pkt; av_init_packet(&pkt); ret = av_read_frame(s, &pkt); if (ret < 0) return AV_NOPTS_VALUE; av_free_packet(&pkt); if (pkt.dts != AV_NOPTS_VALUE && pkt.pos >= 0) { ff_reduce_index(s, pkt.stream_index); av_add_index_entry(s->streams[pkt.stream_index], pkt.pos, pkt.dts, 0, 0, AVINDEX_KEYFRAME /* FIXME keyframe? */); if (pkt.stream_index == stream_index && pkt.pos >= *ppos) { *ppos = pkt.pos; return pkt.dts; } } pos = pkt.pos; } return AV_NOPTS_VALUE; } /**************************************************************/ /* parsing functions - called from other demuxers such as RTP */ MpegTSContext *avpriv_mpegts_parse_open(AVFormatContext *s) { MpegTSContext *ts; ts = av_mallocz(sizeof(MpegTSContext)); if (!ts) return NULL; /* no stream case, currently used by RTP */ ts->raw_packet_size = TS_PACKET_SIZE; ts->stream = s; ts->auto_guess = 1; mpegts_open_section_filter(ts, SDT_PID, sdt_cb, ts, 1); mpegts_open_section_filter(ts, PAT_PID, pat_cb, ts, 1); return ts; } /* return the consumed length if a packet was output, or -1 if no * packet is output */ int avpriv_mpegts_parse_packet(MpegTSContext *ts, AVPacket *pkt, const uint8_t *buf, int len) { int len1; len1 = len; ts->pkt = pkt; for (;;) { ts->stop_parse = 0; if (len < TS_PACKET_SIZE) return AVERROR_INVALIDDATA; if (buf[0] != 0x47) { buf++; len--; } else { handle_packet(ts, buf); buf += TS_PACKET_SIZE; len -= TS_PACKET_SIZE; if (ts->stop_parse == 1) break; } } return len1 - len; } void avpriv_mpegts_parse_close(MpegTSContext *ts) { mpegts_free(ts); av_free(ts); } AVInputFormat ff_mpegts_demuxer = { .name = "mpegts", .long_name = NULL_IF_CONFIG_SMALL("MPEG-TS (MPEG-2 Transport Stream)"), .priv_data_size = sizeof(MpegTSContext), .read_probe = mpegts_probe, .read_header = mpegts_read_header, .read_packet = mpegts_read_packet, .read_close = mpegts_read_close, .read_timestamp = mpegts_get_dts, .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT, .priv_class = &mpegts_class, }; AVInputFormat ff_mpegtsraw_demuxer = { .name = "mpegtsraw", .long_name = NULL_IF_CONFIG_SMALL("raw MPEG-TS (MPEG-2 Transport Stream)"), .priv_data_size = sizeof(MpegTSContext), .read_header = mpegts_read_header, .read_packet = mpegts_raw_read_packet, .read_close = mpegts_read_close, .read_timestamp = mpegts_get_dts, .flags = AVFMT_SHOW_IDS | AVFMT_TS_DISCONT, .priv_class = &mpegtsraw_class, };
mxOBS/deb-pkg_trusty_chromium-browser
third_party/ffmpeg/libavformat/mpegts.c
C
bsd-3-clause
93,323
<?php class Post extends Rediska_Key { public function __construct($id = null) { return parent::__construct(self::_getKey($id)); } public static function fetchNextId() { $key = new Rediska_Key('posts:nextId'); return $key->increment(); } protected function _getKey($id) { return 'posts:' . $id; } }
lmaxim/sfRediska
lib/rediska/examples/retwitter/application/models/Post.php
PHP
bsd-3-clause
379
/***************************************************************************** * cpu.h: h264 encoder library ***************************************************************************** * Copyright (C) 2004-2008 Loren Merritt <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02111, USA. *****************************************************************************/ #ifndef X264_CPU_H #define X264_CPU_H uint32_t x264_cpu_detect( void ); int x264_cpu_num_processors( void ); void x264_emms( void ); void x264_cpu_mask_misalign_sse( void ); /* kluge: * gcc can't give variables any greater alignment than the stack frame has. * We need 16 byte alignment for SSE2, so here we make sure that the stack is * aligned to 16 bytes. * gcc 4.2 introduced __attribute__((force_align_arg_pointer)) to fix this * problem, but I don't want to require such a new version. * This applies only to x86_32, since other architectures that need alignment * either have ABIs that ensure aligned stack, or don't support it at all. */ #if defined(ARCH_X86) && defined(HAVE_MMX) int x264_stack_align( void (*func)(), ... ); #define x264_stack_align(func,...) x264_stack_align((void (*)())func, __VA_ARGS__) #else #define x264_stack_align(func,...) func(__VA_ARGS__) #endif typedef struct { const char name[16]; int flags; } x264_cpu_name_t; extern const x264_cpu_name_t x264_cpu_names[]; #endif
mdsalman729/flexpret_project
emulator/concurrit-poplsyntax/concurrit-poplsyntax/bench/x264/src/x264/common/cpu.h
C
bsd-3-clause
2,091
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/app_restore/full_restore_read_handler.h" #include <cstdint> #include <memory> #include <utility> #include "ash/constants/app_types.h" #include "base/bind.h" #include "base/no_destructor.h" #include "base/task/post_task.h" #include "base/threading/thread_task_runner_handle.h" #include "components/app_constants/constants.h" #include "components/app_restore/app_launch_info.h" #include "components/app_restore/app_restore_utils.h" #include "components/app_restore/desk_template_read_handler.h" #include "components/app_restore/features.h" #include "components/app_restore/full_restore_file_handler.h" #include "components/app_restore/full_restore_info.h" #include "components/app_restore/full_restore_save_handler.h" #include "components/app_restore/lacros_read_handler.h" #include "components/app_restore/restore_data.h" #include "components/app_restore/window_info.h" #include "components/app_restore/window_properties.h" #include "components/sessions/core/session_id.h" #include "ui/aura/client/aura_constants.h" namespace full_restore { namespace { // These are temporary estimate of how long it takes full restore to launch // apps. constexpr base::TimeDelta kFullRestoreEstimateDuration = base::Seconds(5); constexpr base::TimeDelta kFullRestoreARCEstimateDuration = base::Minutes(3); constexpr base::TimeDelta kFullRestoreLacrosEstimateDuration = base::Minutes(1); } // namespace FullRestoreReadHandler* FullRestoreReadHandler::GetInstance() { static base::NoDestructor<FullRestoreReadHandler> full_restore_read_handler; return full_restore_read_handler.get(); } FullRestoreReadHandler::FullRestoreReadHandler() { if (aura::Env::HasInstance()) env_observer_.Observe(aura::Env::GetInstance()); arc_info_observer_.Observe(app_restore::AppRestoreArcInfo::GetInstance()); } FullRestoreReadHandler::~FullRestoreReadHandler() = default; void FullRestoreReadHandler::OnWindowInitialized(aura::Window* window) { int32_t window_id = window->GetProperty(app_restore::kRestoreWindowIdKey); if (app_restore::IsArcWindow(window)) { // If there isn't restore data for ARC apps, we don't need to handle ARC app // windows restoration. if (!arc_read_handler_) return; if (window_id == app_restore::kParentToHiddenContainer || arc_read_handler_->HasRestoreData(window_id)) { observed_windows_.AddObservation(window); arc_read_handler_->AddArcWindowCandidate(window); FullRestoreInfo::GetInstance()->OnWindowInitialized(window); } return; } if (app_restore::IsLacrosWindow(window)) { // If the Lacros `window` is added to the hidden container, observe `window` // to restore and remove it from the hidden container in // OnWindowAddedToRootWindow callback. if (lacros_read_handler_ && window_id == app_restore::kParentToHiddenContainer) { observed_windows_.AddObservation(window); } return; } if (!SessionID::IsValidValue(window_id)) { return; } observed_windows_.AddObservation(window); FullRestoreInfo::GetInstance()->OnWindowInitialized(window); } void FullRestoreReadHandler::OnWindowAddedToRootWindow(aura::Window* window) { // If the Lacros `window` is added to the hidden container, call // OnWindowAddedToRootWindow to restore and remove it from the hidden // container. if (app_restore::IsLacrosWindow(window) && lacros_read_handler_ && window->GetProperty(app_restore::kParentToHiddenContainerKey)) { lacros_read_handler_->OnWindowAddedToRootWindow(window); } } void FullRestoreReadHandler::OnWindowDestroyed(aura::Window* window) { DCHECK(observed_windows_.IsObservingSource(window)); observed_windows_.RemoveObservation(window); if (app_restore::IsArcWindow(window)) { if (arc_read_handler_) arc_read_handler_->OnWindowDestroyed(window); return; } if (app_restore::IsLacrosWindow(window) && lacros_read_handler_) lacros_read_handler_->OnWindowDestroyed(window); int32_t restore_window_id = window->GetProperty(app_restore::kRestoreWindowIdKey); DCHECK(SessionID::IsValidValue(restore_window_id)); RemoveAppRestoreData(restore_window_id); } std::unique_ptr<app_restore::AppLaunchInfo> FullRestoreReadHandler::GetAppLaunchInfo(const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return nullptr; return restore_data->GetAppLaunchInfo(app_id, restore_window_id); } std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo( const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return nullptr; return restore_data->GetWindowInfo(app_id, restore_window_id); } void FullRestoreReadHandler::RemoveAppRestoreData( const base::FilePath& profile_path, const std::string& app_id, int32_t restore_window_id) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return; restore_data->RemoveAppRestoreData(app_id, restore_window_id); } void FullRestoreReadHandler::OnTaskCreated(const std::string& app_id, int32_t task_id, int32_t session_id) { if (arc_read_handler_) arc_read_handler_->OnTaskCreated(app_id, task_id, session_id); } void FullRestoreReadHandler::OnTaskDestroyed(int32_t task_id) { if (arc_read_handler_) arc_read_handler_->OnTaskDestroyed(task_id); } void FullRestoreReadHandler::OnLacrosBrowserWindowAdded( aura::Window* const window, uint32_t restored_browser_session_id) { if (lacros_read_handler_) { lacros_read_handler_->OnLacrosBrowserWindowAdded( window, restored_browser_session_id); } } void FullRestoreReadHandler::OnLacrosChromeAppWindowAdded( const std::string& app_id, const std::string& window_id) { if (lacros_read_handler_) lacros_read_handler_->OnAppWindowAdded(app_id, window_id); } void FullRestoreReadHandler::OnLacrosChromeAppWindowRemoved( const std::string& app_id, const std::string& window_id) { if (lacros_read_handler_) lacros_read_handler_->OnAppWindowRemoved(app_id, window_id); } void FullRestoreReadHandler::SetPrimaryProfilePath( const base::FilePath& profile_path) { primary_profile_path_ = profile_path; if (::full_restore::features::IsFullRestoreForLacrosEnabled()) { lacros_read_handler_ = std::make_unique<app_restore::LacrosReadHandler>(profile_path); } } void FullRestoreReadHandler::SetActiveProfilePath( const base::FilePath& profile_path) { active_profile_path_ = profile_path; } void FullRestoreReadHandler::SetCheckRestoreData( const base::FilePath& profile_path) { should_check_restore_data_.insert(profile_path); } void FullRestoreReadHandler::ReadFromFile(const base::FilePath& profile_path, Callback callback) { auto it = profile_path_to_restore_data_.find(profile_path); if (it != profile_path_to_restore_data_.end()) { // If the restore data has been read from the file, just use it, and don't // need to read it again. // // We must use post task here, because FullRestoreAppLaunchHandler calls // ReadFromFile in FullRestoreService construct function, and the callback // in FullRestoreAppLaunchHandler calls the init function of // FullRestoreService. If we don't use post task, and call the callback // function directly, it could cause deadloop. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(std::move(callback), (it->second ? it->second->Clone() : nullptr))); return; } auto file_handler = base::MakeRefCounted<FullRestoreFileHandler>(profile_path); file_handler->owning_task_runner()->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&FullRestoreFileHandler::ReadFromFile, file_handler.get()), base::BindOnce(&FullRestoreReadHandler::OnGetRestoreData, weak_factory_.GetWeakPtr(), profile_path, std::move(callback))); } void FullRestoreReadHandler::SetNextRestoreWindowIdForChromeApp( const base::FilePath& profile_path, const std::string& app_id) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return; restore_data->SetNextRestoreWindowIdForChromeApp(app_id); } void FullRestoreReadHandler::RemoveApp(const base::FilePath& profile_path, const std::string& app_id) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return; restore_data->RemoveApp(app_id); } bool FullRestoreReadHandler::HasAppTypeBrowser( const base::FilePath& profile_path) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return false; return restore_data->HasAppTypeBrowser(); } bool FullRestoreReadHandler::HasBrowser(const base::FilePath& profile_path) { auto* restore_data = GetRestoreData(profile_path); if (!restore_data) return false; return restore_data->HasBrowser(); } bool FullRestoreReadHandler::HasWindowInfo(int32_t restore_window_id) { if (!SessionID::IsValidValue(restore_window_id) || !base::Contains(should_check_restore_data_, active_profile_path_)) { return false; } auto it = window_id_to_app_restore_info_.find(restore_window_id); if (it == window_id_to_app_restore_info_.end()) return false; return true; } std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo( aura::Window* window) { if (!window) return nullptr; const int32_t restore_window_id = window->GetProperty(app_restore::kRestoreWindowIdKey); if (app_restore::IsArcWindow(window)) { return arc_read_handler_ ? arc_read_handler_->GetWindowInfo(restore_window_id) : nullptr; } return GetWindowInfo(restore_window_id); } std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfoForActiveProfile( int32_t restore_window_id) { if (!base::Contains(should_check_restore_data_, active_profile_path_)) return nullptr; return GetWindowInfo(restore_window_id); } std::unique_ptr<app_restore::AppLaunchInfo> FullRestoreReadHandler::GetArcAppLaunchInfo(const std::string& app_id, int32_t session_id) { return arc_read_handler_ ? arc_read_handler_->GetArcAppLaunchInfo(app_id, session_id) : nullptr; } int32_t FullRestoreReadHandler::FetchRestoreWindowId( const std::string& app_id) { auto* restore_data = GetRestoreData(active_profile_path_); if (!restore_data) return 0; return restore_data->FetchRestoreWindowId(app_id); } int32_t FullRestoreReadHandler::GetArcRestoreWindowIdForTaskId( int32_t task_id) { if (!arc_read_handler_) return 0; return arc_read_handler_->GetArcRestoreWindowIdForTaskId(task_id); } int32_t FullRestoreReadHandler::GetArcRestoreWindowIdForSessionId( int32_t session_id) { if (!arc_read_handler_) return 0; return arc_read_handler_->GetArcRestoreWindowIdForSessionId(session_id); } int32_t FullRestoreReadHandler::GetLacrosRestoreWindowId( const std::string& lacros_window_id) const { return IsLacrosRestoreRunning() ? lacros_read_handler_->GetLacrosRestoreWindowId(lacros_window_id) : 0; } void FullRestoreReadHandler::SetArcSessionIdForWindowId(int32_t arc_session_id, int32_t window_id) { if (arc_read_handler_) arc_read_handler_->SetArcSessionIdForWindowId(arc_session_id, window_id); } void FullRestoreReadHandler::SetStartTimeForProfile( const base::FilePath& profile_path) { profile_path_to_start_time_data_[profile_path] = base::TimeTicks::Now(); } bool FullRestoreReadHandler::IsFullRestoreRunning() const { auto it = profile_path_to_start_time_data_.find(active_profile_path_); if (it == profile_path_to_start_time_data_.end()) return false; if (IsArcRestoreRunning() || IsLacrosRestoreRunning()) return true; // We estimate that full restore is still running if it has been less than // five seconds since it started. return base::TimeTicks::Now() - it->second < kFullRestoreEstimateDuration; } void FullRestoreReadHandler::AddChromeBrowserLaunchInfoForTesting( const base::FilePath& profile_path) { auto session_id = SessionID::NewUnique(); auto app_launch_info = std::make_unique<app_restore::AppLaunchInfo>( app_constants::kChromeAppId, session_id.id()); app_launch_info->app_type_browser = true; if (profile_path_to_restore_data_.find(profile_path) == profile_path_to_restore_data_.end()) { profile_path_to_restore_data_[profile_path] = std::make_unique<app_restore::RestoreData>(); } profile_path_to_restore_data_[profile_path]->AddAppLaunchInfo( std::move(app_launch_info)); window_id_to_app_restore_info_[session_id.id()] = std::make_pair(profile_path, app_constants::kChromeAppId); } std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo( int32_t restore_window_id) { if (!SessionID::IsValidValue(restore_window_id)) return nullptr; auto it = window_id_to_app_restore_info_.find(restore_window_id); if (it == window_id_to_app_restore_info_.end()) return nullptr; const base::FilePath& profile_path = it->second.first; const std::string& app_id = it->second.second; return GetWindowInfo(profile_path, app_id, restore_window_id); } bool FullRestoreReadHandler::IsArcRestoreRunning() const { if (!arc_read_handler_ || active_profile_path_ != primary_profile_path_) return false; auto it = profile_path_to_start_time_data_.find(primary_profile_path_); if (it == profile_path_to_start_time_data_.end()) return false; // We estimate that full restore is still running for ARC windows if it has // been less than five minutes since it started, when there is at least one // ARC app, since it might take long time to boot ARC. return base::TimeTicks::Now() - it->second < kFullRestoreARCEstimateDuration; } bool FullRestoreReadHandler::IsLacrosRestoreRunning() const { if (!lacros_read_handler_ || active_profile_path_ != primary_profile_path_) return false; auto it = profile_path_to_start_time_data_.find(primary_profile_path_); if (it == profile_path_to_start_time_data_.end()) return false; // We estimate that full restore is still running if it has been less than // one minute since it started, when Lacros is available. return base::TimeTicks::Now() - it->second < kFullRestoreLacrosEstimateDuration; } void FullRestoreReadHandler::OnGetRestoreData( const base::FilePath& profile_path, Callback callback, std::unique_ptr<app_restore::RestoreData> restore_data) { if (restore_data) { profile_path_to_restore_data_[profile_path] = restore_data->Clone(); for (auto it = restore_data->app_id_to_launch_list().begin(); it != restore_data->app_id_to_launch_list().end(); it++) { const std::string& app_id = it->first; for (auto data_it = it->second.begin(); data_it != it->second.end(); data_it++) { int32_t window_id = data_it->first; // Only ARC app launch parameters have event_flag. if (data_it->second->event_flag.has_value()) { if (!arc_read_handler_) { arc_read_handler_ = std::make_unique<app_restore::ArcReadHandler>( profile_path, this); } arc_read_handler_->AddRestoreData(app_id, window_id); } else { window_id_to_app_restore_info_[window_id] = std::make_pair(profile_path, app_id); // TODO(crbug.com/1239984): Remove restore data from // `lacros_read_handler_` for ash browser apps. if (lacros_read_handler_ && app_id != app_constants::kChromeAppId && primary_profile_path_ == profile_path) { lacros_read_handler_->AddRestoreData(app_id, window_id); } } } } } else { profile_path_to_restore_data_[profile_path] = nullptr; } std::move(callback).Run(std::move(restore_data)); // Call FullRestoreSaveHandler to start a timer to clear the restore data // after reading the restore data. Otherwise, if the user doesn't select // restore, and never launch a new app, the restore data is not cleared. So // when the system is reboot, the restore process could restore the previous // record before the last reboot. FullRestoreSaveHandler::GetInstance()->ClearRestoreData(profile_path); } void FullRestoreReadHandler::RemoveAppRestoreData(int32_t window_id) { auto it = window_id_to_app_restore_info_.find(window_id); if (it == window_id_to_app_restore_info_.end()) return; const base::FilePath& profile_path = it->second.first; const std::string& app_id = it->second.second; RemoveAppRestoreData(profile_path, app_id, window_id); window_id_to_app_restore_info_.erase(it); } app_restore::RestoreData* FullRestoreReadHandler::GetRestoreData( const base::FilePath& profile_path) { auto it = profile_path_to_restore_data_.find(profile_path); if (it == profile_path_to_restore_data_.end() || !it->second) { return nullptr; } return it->second.get(); } } // namespace full_restore
chromium/chromium
components/app_restore/full_restore_read_handler.cc
C++
bsd-3-clause
17,782
/** * Show or hide tiles loader * * Usage: * * var tiles_loader = new cdb.geo.ui.TilesLoader(); * mapWrapper.$el.append(tiles_loader.render().$el); * */ cdb.geo.ui.TilesLoader = cdb.core.View.extend({ className: "cartodb-tiles-loader", default_options: { animationSpeed: 500 }, initialize: function() { _.defaults(this.options, this.default_options); this.isVisible = 0; this.template = this.options.template ? this.options.template : cdb.templates.getTemplate('geo/tiles_loader'); }, render: function() { this.$el.html($(this.template(this.options))); return this; }, show: function(ev) { if(this.isVisible) return; if (!$.browser.msie || ($.browser.msie && $.browser.version.indexOf("9.") != 0)) { this.$el.fadeTo(this.options.animationSpeed, 1) } else { this.$el.show(); } this.isVisible++; }, hide: function(ev) { this.isVisible--; if(this.isVisible > 0) return; this.isVisible = 0; if (!$.browser.msie || ($.browser.msie && $.browser.version.indexOf("9.") == 0)) { this.$el.stop(true).fadeTo(this.options.animationSpeed, 0) } else { this.$el.hide(); } }, visible: function() { return this.isVisible > 0; } });
limasol/cartodb.js
src/geo/ui/tiles_loader.js
JavaScript
bsd-3-clause
1,255
// +build ignore // Copyright 2014 The Go Authors. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. package main import ( "fmt" "log" "github.com/vanackere/ldap" ) var ( LdapServer string = "localhost" LdapPort uint16 = 389 BaseDN string = "dc=enterprise,dc=org" Filter string = "(cn=kirkj)" Attributes []string = []string{"mail"} ) func main() { l, err := ldap.DialTLS("tcp", fmt.Sprintf("%s:%d", LdapServer, LdapPort), nil) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) } defer l.Close() // l.Debug = true search := ldap.NewSearchRequest( BaseDN, ldap.ScopeWholeSubtree, ldap.NeverDerefAliases, 0, 0, false, Filter, Attributes, nil) sr, err := l.Search(search) if err != nil { log.Fatalf("ERROR: %s\n", err.Error()) return } log.Printf("Search: %s -> num of entries = %d\n", search.Filter, len(sr.Entries)) sr.PrettyPrint(0) }
sendgrid-ops/go-ldap
examples/searchTLS.go
GO
bsd-3-clause
976
/* * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). * Copyright (C) 2011 Igalia S.L. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef GtkPopupMenu_h #define GtkPopupMenu_h #include "GRefPtrGtk.h" #include "IntPoint.h" #include "IntSize.h" #include <wtf/FastMalloc.h> #include <wtf/Noncopyable.h> #include <wtf/PassOwnPtr.h> #include <wtf/text/WTFString.h> typedef struct _GdkEventKey GdkEventKey; namespace WebCore { class GtkPopupMenu { WTF_MAKE_NONCOPYABLE(GtkPopupMenu); WTF_MAKE_FAST_ALLOCATED; public: static PassOwnPtr<GtkPopupMenu> create() { return adoptPtr(new GtkPopupMenu()); } ~GtkPopupMenu(); GtkWidget* platformMenu() const { return m_popup.get(); } void clear(); void appendSeparator(); void appendItem(GtkAction*); void popUp(const IntSize&, const IntPoint&, int itemsCount, int selectedItem, const GdkEvent*); void popDown(); private: GtkPopupMenu(); void resetTypeAheadFindState(); bool typeAheadFind(GdkEventKey*); static void menuItemActivated(GtkMenuItem*, GtkPopupMenu*); static void menuPositionFunction(GtkMenu*, gint*, gint*, gboolean*, GtkPopupMenu*); static void menuRemoveItem(GtkWidget*, GtkPopupMenu*); static void selectItemCallback(GtkMenuItem*, GtkPopupMenu*); static gboolean keyPressEventCallback(GtkWidget*, GdkEventKey*, GtkPopupMenu*); GRefPtr<GtkWidget> m_popup; IntPoint m_menuPosition; String m_currentSearchString; uint32_t m_previousKeyEventTimestamp; unsigned int m_previousKeyEventCharacter; GtkWidget* m_currentlySelectedMenuItem; unsigned int m_keyPressHandlerID; }; } #endif // GtkPopupMenu_h
klim-iv/phantomjs-qt5
src/webkit/Source/WebCore/platform/gtk/GtkPopupMenu.h
C
bsd-3-clause
2,430
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "mandoline/tab/frame.h" #include <algorithm> #include "base/stl_util.h" #include "components/view_manager/public/cpp/view.h" #include "components/view_manager/public/cpp/view_property.h" #include "mandoline/tab/frame_tree.h" #include "mandoline/tab/frame_tree_delegate.h" #include "mandoline/tab/frame_user_data.h" using mojo::View; DECLARE_VIEW_PROPERTY_TYPE(mandoline::Frame*); namespace mandoline { // Used to find the Frame associated with a View. DEFINE_LOCAL_VIEW_PROPERTY_KEY(Frame*, kFrame, nullptr); namespace { const uint32_t kNoParentId = 0u; FrameDataPtr FrameToFrameData(const Frame* frame) { FrameDataPtr frame_data(FrameData::New()); frame_data->frame_id = frame->view()->id(); frame_data->parent_id = frame->parent() ? frame->parent()->view()->id() : kNoParentId; return frame_data.Pass(); } } // namespace Frame::Frame(FrameTree* tree, View* view, ViewOwnership view_ownership, FrameTreeClient* frame_tree_client, scoped_ptr<FrameUserData> user_data) : tree_(tree), view_(view), parent_(nullptr), view_ownership_(view_ownership), user_data_(user_data.Pass()), frame_tree_client_(frame_tree_client), frame_tree_server_binding_(this) { view_->SetLocalProperty(kFrame, this); view_->AddObserver(this); } Frame::~Frame() { if (view_) view_->RemoveObserver(this); while (!children_.empty()) delete children_[0]; if (parent_) parent_->Remove(this); if (view_) view_->ClearLocalProperty(kFrame); if (view_ownership_ == ViewOwnership::OWNS_VIEW) view_->Destroy(); } void Frame::Init(Frame* parent) { if (parent) parent->Add(this); std::vector<const Frame*> frames; tree_->root()->BuildFrameTree(&frames); mojo::Array<FrameDataPtr> array(frames.size()); for (size_t i = 0; i < frames.size(); ++i) array[i] = FrameToFrameData(frames[i]).Pass(); // TODO(sky): error handling. FrameTreeServerPtr frame_tree_server_ptr; frame_tree_server_binding_.Bind(GetProxy(&frame_tree_server_ptr).Pass()); frame_tree_client_->OnConnect(frame_tree_server_ptr.Pass(), array.Pass()); } // static Frame* Frame::FindFirstFrameAncestor(View* view) { while (view && !view->GetLocalProperty(kFrame)) view = view->parent(); return view ? view->GetLocalProperty(kFrame) : nullptr; } const Frame* Frame::FindFrame(uint32_t id) const { if (id == view_->id()) return this; for (const Frame* child : children_) { const Frame* match = child->FindFrame(id); if (match) return match; } return nullptr; } bool Frame::HasAncestor(const Frame* frame) const { const Frame* current = this; while (current && current != frame) current = current->parent_; return current == frame; } void Frame::BuildFrameTree(std::vector<const Frame*>* frames) const { frames->push_back(this); for (const Frame* frame : children_) frame->BuildFrameTree(frames); } void Frame::Add(Frame* node) { DCHECK(!node->parent_); node->parent_ = this; children_.push_back(node); tree_->root()->NotifyAdded(this, node); } void Frame::Remove(Frame* node) { DCHECK_EQ(node->parent_, this); auto iter = std::find(children_.begin(), children_.end(), node); DCHECK(iter != children_.end()); node->parent_ = nullptr; children_.erase(iter); tree_->root()->NotifyRemoved(this, node); } void Frame::NotifyAdded(const Frame* source, const Frame* added_node) { if (added_node == this) return; if (source != this) frame_tree_client_->OnFrameAdded(FrameToFrameData(added_node)); for (Frame* child : children_) child->NotifyAdded(source, added_node); } void Frame::NotifyRemoved(const Frame* source, const Frame* removed_node) { if (removed_node == this) return; if (source != this) frame_tree_client_->OnFrameRemoved(removed_node->view_->id()); for (Frame* child : children_) child->NotifyRemoved(source, removed_node); } void Frame::OnViewDestroying(mojo::View* view) { if (parent_) parent_->Remove(this); // Reset |view_ownership_| so we don't attempt to delete |view_| in the // destructor. view_ownership_ = ViewOwnership::DOESNT_OWN_VIEW; // Assume the view associated with the root is never deleted out from under // us. // TODO(sky): Change browser to create a child for each FrameTree. if (tree_->root() == this) { view_->RemoveObserver(this); view_ = nullptr; return; } delete this; } void Frame::PostMessageEventToFrame(uint32_t frame_id, MessageEventPtr event) { Frame* target = tree_->root()->FindFrame(frame_id); if (!target || !tree_->delegate_->CanPostMessageEventToFrame(this, target, event.get())) return; NOTIMPLEMENTED(); } void Frame::NavigateFrame(uint32_t frame_id) { NOTIMPLEMENTED(); } void Frame::ReloadFrame(uint32_t frame_id) { NOTIMPLEMENTED(); } } // namespace mandoline
SaschaMester/delicium
mandoline/tab/frame.cc
C++
bsd-3-clause
5,075
/* * Copyright 2006 The Android Open Source Project * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/core/SkColorPriv.h" #include "include/core/SkString.h" #include "include/effects/SkBlurMaskFilter.h" #include "include/private/SkTPin.h" #include "src/core/SkBlurMask.h" #include "src/core/SkReadBuffer.h" #include "src/core/SkWriteBuffer.h" #include "src/effects/SkEmbossMask.h" #include "src/effects/SkEmbossMaskFilter.h" static void normalize3(SkScalar dst[3], const SkScalar src[3]) { SkScalar mag = SkScalarSquare(src[0]) + SkScalarSquare(src[1]) + SkScalarSquare(src[2]); SkScalar scale = SkScalarInvert(SkScalarSqrt(mag)); for (int i = 0; i < 3; i++) { dst[i] = src[i] * scale; } } sk_sp<SkMaskFilter> SkEmbossMaskFilter::Make(SkScalar blurSigma, const Light& light) { if (!SkScalarIsFinite(blurSigma) || blurSigma <= 0) { return nullptr; } Light newLight = light; normalize3(newLight.fDirection, light.fDirection); if (!SkScalarsAreFinite(newLight.fDirection, 3)) { return nullptr; } return sk_sp<SkMaskFilter>(new SkEmbossMaskFilter(blurSigma, newLight)); } #ifdef SK_SUPPORT_LEGACY_EMBOSSMASKFILTER sk_sp<SkMaskFilter> SkBlurMaskFilter::MakeEmboss(SkScalar blurSigma, const SkScalar direction[3], SkScalar ambient, SkScalar specular) { if (direction == nullptr) { return nullptr; } SkEmbossMaskFilter::Light light; memcpy(light.fDirection, direction, sizeof(light.fDirection)); // ambient should be 0...1 as a scalar light.fAmbient = SkUnitScalarClampToByte(ambient); // specular should be 0..15.99 as a scalar static const SkScalar kSpecularMultiplier = SkIntToScalar(255) / 16; light.fSpecular = static_cast<U8CPU>(SkTPin(specular, 0.0f, 16.0f) * kSpecularMultiplier + 0.5); return SkEmbossMaskFilter::Make(blurSigma, light); } #endif /////////////////////////////////////////////////////////////////////////////// SkEmbossMaskFilter::SkEmbossMaskFilter(SkScalar blurSigma, const Light& light) : fLight(light), fBlurSigma(blurSigma) { SkASSERT(fBlurSigma > 0); SkASSERT(SkScalarsAreFinite(fLight.fDirection, 3)); } SkMask::Format SkEmbossMaskFilter::getFormat() const { return SkMask::k3D_Format; } bool SkEmbossMaskFilter::filterMask(SkMask* dst, const SkMask& src, const SkMatrix& matrix, SkIPoint* margin) const { if (src.fFormat != SkMask::kA8_Format) { return false; } SkScalar sigma = matrix.mapRadius(fBlurSigma); if (!SkBlurMask::BoxBlur(dst, src, sigma, kInner_SkBlurStyle)) { return false; } dst->fFormat = SkMask::k3D_Format; if (margin) { margin->set(SkScalarCeilToInt(3*sigma), SkScalarCeilToInt(3*sigma)); } if (src.fImage == nullptr) { return true; } // create a larger buffer for the other two channels (should force fBlur to do this for us) { uint8_t* alphaPlane = dst->fImage; size_t planeSize = dst->computeImageSize(); if (0 == planeSize) { return false; // too big to allocate, abort } dst->fImage = SkMask::AllocImage(planeSize * 3); memcpy(dst->fImage, alphaPlane, planeSize); SkMask::FreeImage(alphaPlane); } // run the light direction through the matrix... Light light = fLight; matrix.mapVectors((SkVector*)(void*)light.fDirection, (SkVector*)(void*)fLight.fDirection, 1); // now restore the length of the XY component // cast to SkVector so we can call setLength (this double cast silences alias warnings) SkVector* vec = (SkVector*)(void*)light.fDirection; vec->setLength(light.fDirection[0], light.fDirection[1], SkPoint::Length(fLight.fDirection[0], fLight.fDirection[1])); SkEmbossMask::Emboss(dst, light); // restore original alpha memcpy(dst->fImage, src.fImage, src.computeImageSize()); return true; } sk_sp<SkFlattenable> SkEmbossMaskFilter::CreateProc(SkReadBuffer& buffer) { Light light; if (buffer.readByteArray(&light, sizeof(Light))) { light.fPad = 0; // for the font-cache lookup to be clean const SkScalar sigma = buffer.readScalar(); return Make(sigma, light); } return nullptr; } void SkEmbossMaskFilter::flatten(SkWriteBuffer& buffer) const { Light tmpLight = fLight; tmpLight.fPad = 0; // for the font-cache lookup to be clean buffer.writeByteArray(&tmpLight, sizeof(tmpLight)); buffer.writeScalar(fBlurSigma); }
youtube/cobalt
third_party/skia_next/third_party/skia/src/effects/SkEmbossMaskFilter.cpp
C++
bsd-3-clause
4,719
/* liblouis Braille Translation and Back-Translation Library Based on the Linux screenreader BRLTTY, copyright (C) 1999-2006 by The BRLTTY Team Copyright (C) 2004, 2005, 2006, 2009 ViewPlus Technologies, Inc. www.viewplus.com and JJB Software, Inc. www.jjb-software.com This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <config.h> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <stdint.h> #include "liblouis.h" #include "internal.h" #include <getopt.h> #include "progname.h" #include "unistr.h" #include "version-etc.h" static const struct option longopts[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, 'v' }, { NULL, 0, NULL, 0 }, }; const char version_etc_copyright[] = "Copyright %s %d ViewPlus Technologies, Inc. and JJB Software, Inc."; #define AUTHORS "John J. Boyer" static void print_help(void) { printf("\ Usage: %s [OPTIONS]\n", program_name); fputs("\ This program tests every capability of the liblouis library. It is\n\ completely interactive. \n\n", stdout); fputs("\ -h, --help display this help and exit\n\ -v, --version display version information and exit\n", stdout); printf("\n"); printf("Report bugs to %s.\n", PACKAGE_BUGREPORT); #ifdef PACKAGE_PACKAGER_BUG_REPORTS printf("Report %s bugs to: %s\n", PACKAGE_PACKAGER, PACKAGE_PACKAGER_BUG_REPORTS); #endif #ifdef PACKAGE_URL printf("%s home page: <%s>\n", PACKAGE_NAME, PACKAGE_URL); #endif } #define BUFSIZE 256 static char inputBuffer[BUFSIZE]; static const void *validTable = NULL; static int forwardOnly = 0; static int backOnly = 0; static int showPositions = 0; static int minimalist = 0; static int outputSize = BUFSIZE; static int showSizes = 0; static int enteredCursorPos = -1; static unsigned int mode; static char table[BUFSIZE]; static formtype emphasis[BUFSIZE]; static char spacing[BUFSIZE]; static char enteredEmphasis[BUFSIZE]; static char enteredSpacing[BUFSIZE]; static int getInput(void) { int inputLength; inputBuffer[0] = 0; if (!fgets(inputBuffer, sizeof(inputBuffer), stdin)) exit(EXIT_FAILURE); inputLength = strlen(inputBuffer) - 1; if (inputLength < 0) /* EOF on script */ { lou_free(); exit(EXIT_SUCCESS); } inputBuffer[inputLength] = 0; return inputLength; } static int getYN(void) { printf("? y/n: "); getInput(); if (inputBuffer[0] == 'y') return 1; return 0; } static void paramLetters(void) { printf("Press one of the letters in parentheses, then enter.\n"); printf("(t)able, (r)un, (m)ode, (c)ursor, (e)mphasis, (s)pacing, (h)elp,\n"); printf("(q)uit, (f)orward-only, (b)ack-only, show-(p)ositions m(i)nimal.\n"); printf("test-(l)engths.\n"); } static int getCommands(void) { paramLetters(); do { printf("Command: "); getInput(); switch (inputBuffer[0]) { case 0: break; case 't': do { printf("Enter the name of a table: "); getInput(); strcpy(table, inputBuffer); } while ((validTable = lou_getTable(table)) == NULL); break; case 'r': if (validTable == NULL) { printf("You must enter a valid table name.\n"); inputBuffer[0] = 0; } break; case 'm': printf("Reset mode"); if (getYN()) mode = 0; printf("No contractions"); mode |= noContractions * getYN(); printf("Computer Braille at cursor"); mode |= compbrlAtCursor * getYN(); printf("Dots input and output"); mode |= dotsIO * getYN(); printf("Computer Braille left of cursor"); mode |= compbrlLeftCursor * getYN(); printf("Unicode Braille"); mode |= ucBrl * getYN(); printf("No undefined dots"); mode |= noUndefined * getYN(); printf("Partial back-translation"); mode |= partialTrans * getYN(); break; case 'l': printf("Do you want to test input and output lengths"); showSizes = getYN(); if (!showSizes) { outputSize = BUFSIZE; break; } printf("Enter a maximum output size: "); getInput(); outputSize = atoi(inputBuffer); if (outputSize < 0 || outputSize > BUFSIZE) { printf("Output size must be from 0 tu %d.\n", BUFSIZE); outputSize = BUFSIZE; showSizes = 0; } break; case 'c': printf("Enter a cursor position: "); getInput(); enteredCursorPos = atoi(inputBuffer); if (enteredCursorPos < -1 || enteredCursorPos > outputSize) { printf("Cursor position must be from -1 to %d.\n", outputSize); enteredCursorPos = -1; } break; case 'e': printf("(Enter an x to cancel emphasis.)\n"); printf("Enter an emphasis string: "); getInput(); strcpy(enteredEmphasis, inputBuffer); break; case 's': printf("(Enter an x to cancel spacing.)\n"); printf("Enter a spacing string: "); getInput(); strcpy(enteredSpacing, inputBuffer); break; case 'h': printf("Commands: action\n"); printf("(t)able: Enter a table name\n"); printf("(r)un: run the translation/back-translation loop\n"); printf("(m)ode: Enter a mode parameter\n"); printf("(c)ursor: Enter a cursor position\n"); printf("(e)mphasis: Enter an emphasis string\n"); printf("(s)pacing: Enter a spacing string\n"); printf("(h)elp: print this page\n"); printf("(q)uit: leave the program\n"); printf("(f)orward-only: do only forward translation\n"); printf("(b)ack-only: do only back-translation\n"); printf("show-(p)ositions: show input and output positions\n"); printf("m(i)nimal: test translator and back-translator with minimal " "parameters\n"); printf("test-(l)engths: test accuracy of returned lengths\n"); printf("\n"); paramLetters(); break; case 'q': lou_free(); exit(EXIT_SUCCESS); case 'f': printf("Do only forward translation"); forwardOnly = getYN(); break; case 'b': printf("Do only backward translation"); backOnly = getYN(); break; case 'p': printf("Show input and output positions"); showPositions = getYN(); break; case 'i': printf("Test translation/back-translation loop with minimal parameters"); minimalist = getYN(); break; default: printf("Bad choice.\n"); break; } if (forwardOnly && backOnly) printf("You cannot specify both forward-only and backward-only " "translation.\n"); } while (inputBuffer[0] != 'r'); return 1; } int main(int argc, char **argv) { uint8_t *charbuf; size_t charlen; widechar inbuf[BUFSIZE]; widechar transbuf[BUFSIZE]; widechar outbuf[BUFSIZE]; int outputPos[BUFSIZE]; int inputPos[BUFSIZE]; int inlen; int translen; int outlen; int cursorPos = -1; int realInlen = 0; int optc; set_program_name(argv[0]); while ((optc = getopt_long(argc, argv, "hv", longopts, NULL)) != -1) { switch (optc) { /* --help and --version exit immediately, per GNU coding standards. */ case 'v': version_etc( stdout, program_name, PACKAGE_NAME, VERSION, AUTHORS, (char *)NULL); exit(EXIT_SUCCESS); break; case 'h': print_help(); exit(EXIT_SUCCESS); break; default: fprintf(stderr, "Try `%s --help' for more information.\n", program_name); exit(EXIT_FAILURE); break; } } if (optind < argc) { /* Print error message and exit. */ fprintf(stderr, "%s: extra operand: %s\n", program_name, argv[optind]); fprintf(stderr, "Try `%s --help' for more information.\n", program_name); exit(EXIT_FAILURE); } validTable = NULL; enteredCursorPos = -1; mode = 0; while (1) { getCommands(); printf("Type something, press enter, and view the results.\n"); printf("A blank line returns to command entry.\n"); if (minimalist) while (1) { translen = outputSize; outlen = outputSize; inlen = getInput(); if (inlen == 0) break; if (!(realInlen = _lou_extParseChars(inputBuffer, inbuf))) break; inlen = realInlen; if (!lou_translateString( table, inbuf, &inlen, transbuf, &translen, NULL, NULL, 0)) break; transbuf[translen] = 0; printf("Translation:\n"); #ifdef WIDECHARS_ARE_UCS4 charbuf = u32_to_u8(transbuf, translen, NULL, &charlen); #else charbuf = u16_to_u8(transbuf, translen, NULL, &charlen); #endif printf("%.*s\n", (int)charlen, charbuf); free(charbuf); if (showSizes) printf("input length = %d; output length = %d\n", inlen, translen); lou_backTranslateString( table, transbuf, &translen, outbuf, &outlen, NULL, NULL, 0); printf("Back-translation:\n"); #ifdef WIDECHARS_ARE_UCS4 charbuf = u32_to_u8(outbuf, outlen, NULL, &charlen); #else charbuf = u16_to_u8(outbuf, outlen, NULL, &charlen); #endif printf("%.*s\n", (int)charlen, charbuf); free(charbuf); if (showSizes) printf("input length = %d; output length = %d.\n", translen, outlen); if (outlen == realInlen) { int k; for (k = 0; k < realInlen; k++) if (inbuf[k] != outbuf[k]) break; if (k == realInlen) printf("Perfect roundtrip!\n"); } } else while (1) { memset(emphasis, 0, sizeof(formtype) * BUFSIZE); { size_t k = 0; for (k = 0; k < strlen(enteredEmphasis); k++) emphasis[k] = (formtype)enteredEmphasis[k] - '0'; emphasis[k] = 0; } strcpy(spacing, enteredSpacing); cursorPos = enteredCursorPos; inlen = getInput(); if (inlen == 0) break; outlen = outputSize; if (backOnly) { if (!(translen = _lou_extParseChars(inputBuffer, transbuf))) break; inlen = realInlen; } else { translen = outputSize; if (!(realInlen = _lou_extParseChars(inputBuffer, inbuf))) break; inlen = realInlen; if (!lou_translate(table, inbuf, &inlen, transbuf, &translen, emphasis, spacing, &outputPos[0], &inputPos[0], &cursorPos, mode)) break; transbuf[translen] = 0; if (mode & dotsIO) { printf("Translation dot patterns:\n"); printf("%s\n", _lou_showDots(transbuf, translen)); } else { printf("Translation:\n"); #ifdef WIDECHARS_ARE_UCS4 charbuf = u32_to_u8(transbuf, translen, NULL, &charlen); #else charbuf = u16_to_u8(transbuf, translen, NULL, &charlen); #endif printf("%.*s\n", (int)charlen, charbuf); free(charbuf); if (showSizes) printf("input length = %d; output length = %d\n", inlen, translen); } } if (cursorPos != -1) printf("Cursor position: %d\n", cursorPos); if (enteredSpacing[0]) printf("Returned spacing: %s\n", spacing); if (showPositions) { printf("Output positions:\n"); for (int k = 0; k < inlen; k++) printf("%d ", outputPos[k]); printf("\n"); printf("Input positions:\n"); for (int k = 0; k < translen; k++) printf("%d ", inputPos[k]); printf("\n"); } if (!forwardOnly) { if (!lou_backTranslate(table, transbuf, &translen, outbuf, &outlen, emphasis, spacing, &outputPos[0], &inputPos[0], &cursorPos, mode)) break; printf("Back-translation:\n"); #ifdef WIDECHARS_ARE_UCS4 charbuf = u32_to_u8(outbuf, outlen, NULL, &charlen); #else charbuf = u16_to_u8(outbuf, outlen, NULL, &charlen); #endif printf("%.*s\n", (int)charlen, charbuf); free(charbuf); if (showSizes) printf("input length = %d; output length = %d\n", translen, outlen); if (cursorPos != -1) printf("Cursor position: %d\n", cursorPos); if (enteredSpacing[0]) printf("Returned spacing: %s\n", spacing); if (showPositions) { printf("Output positions:\n"); for (int k = 0; k < translen; k++) printf("%d ", outputPos[k]); printf("\n"); printf("Input positions:\n"); for (int k = 0; k < outlen; k++) printf("%d ", inputPos[k]); printf("\n"); } } if (!(forwardOnly || backOnly)) { if (outlen == realInlen) { int k; for (k = 0; k < realInlen; k++) if (inbuf[k] != outbuf[k]) break; if (k == realInlen) printf("Perfect roundtrip!\n"); } } } } lou_free(); exit(EXIT_SUCCESS); }
endlessm/chromium-browser
third_party/liblouis/src/tools/lou_allround.c
C
bsd-3-clause
12,469
#! /usr/bin/env python3 import sys # See #17264. # # Generates a module of Luc Maranget's V series size = int(sys.argv[1]) if len(sys.argv) > 1 else 3 a = 'A' b = 'B' wc = '_' def horiz_join(M, N): return [ row_M + row_N for (row_M, row_N) in zip(M, N) ] def vert_join(M, N): return M + N def b_m(n): if n == 1: return [ [ b ] ] b_sub = b_m(n-1) top_row = [ [ b ] + [ wc ]*len(b_sub) ] left_col = [ [ wc ] ] * len(b_sub) return vert_join(top_row, horiz_join(left_col, b_sub)) def n_cols(M): return len(M[0]) def v(n): if n == 1: return [ [ a ], [ b ] ] b_sub = b_m(n) v_sub = v(n-1) top_row = [ [ a ]*n + [ wc ]*n_cols(v_sub) ] return vert_join(top_row, horiz_join(b_sub, v_sub)) def debug_print(M): for row in M: print("".join(row)) def format_hs(M): hdr = """module V where data T = A | B """ fun = "v :: " + "T -> "*n_cols(M) + "()\n" for row in M: fun += "v " + " ".join(row) + "= ()\n" return hdr + fun open("V.hs", "w").write(format_hs(v(size)))
sdiehl/ghc
testsuite/tests/pmcheck/should_compile/genV.py
Python
bsd-3-clause
1,063
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #ifndef SkImageShader_DEFINED #define SkImageShader_DEFINED #include "include/core/SkImage.h" #include "src/shaders/SkBitmapProcShader.h" #include "src/shaders/SkShaderBase.h" // private subclass of SkStageUpdater class SkImageStageUpdater; class SkImageShader : public SkShaderBase { public: static sk_sp<SkShader> Make(sk_sp<SkImage>, SkTileMode tmx, SkTileMode tmy, const SkMatrix* localMatrix, bool clampAsIfUnpremul = false); bool isOpaque() const override; #if SK_SUPPORT_GPU std::unique_ptr<GrFragmentProcessor> asFragmentProcessor(const GrFPArgs&) const override; #endif private: SK_FLATTENABLE_HOOKS(SkImageShader) SkImageShader(sk_sp<SkImage>, SkTileMode tmx, SkTileMode tmy, const SkMatrix* localMatrix, bool clampAsIfUnpremul); void flatten(SkWriteBuffer&) const override; #ifdef SK_ENABLE_LEGACY_SHADERCONTEXT Context* onMakeContext(const ContextRec&, SkArenaAlloc* storage) const override; #endif SkImage* onIsAImage(SkMatrix*, SkTileMode*) const override; bool onAppendStages(const SkStageRec&) const override; SkStageUpdater* onAppendUpdatableStages(const SkStageRec&) const override; bool doStages(const SkStageRec&, SkImageStageUpdater* = nullptr) const; sk_sp<SkImage> fImage; const SkTileMode fTileModeX; const SkTileMode fTileModeY; const bool fClampAsIfUnpremul; friend class SkShaderBase; typedef SkShaderBase INHERITED; }; #endif
youtube/cobalt
third_party/skia/src/shaders/SkImageShader.h
C
bsd-3-clause
1,788
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the KiWi Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Contributor(s): * * */ package kiwi.widgets.explanation; import java.util.ArrayList; import java.util.List; import javax.persistence.EntityManager; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import kiwi.api.explanation.ExplanationService; import kiwi.model.kbase.KiWiTriple; import kiwi.service.reasoning.reasonmaintenance.Justification; import org.jboss.resteasy.annotations.providers.jaxb.Wrapped; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Scope; import org.jboss.seam.log.Log; /** Explanation web service provides access to justification data maintained by reason maintenance. * * It uses the explanation service to get "explanation subtrees" for triples and returns them as JSON. * * @author Jakub Kotowski * */ @Name("kiwi.widgets.explanationWidget") @Scope(ScopeType.STATELESS) @Path("/widgets/explanation") public class ExplanationWidgetWebService { @Logger private Log log; @In("explanationService") ExplanationService explanationService; @In EntityManager entityManager; /** * Return a JSON object representing a graph of nodes which explain the triple with the * id passed as argument. The web service is called using * /KiWi/seam/resource/services/widgets/explanation/explain?id=<KIWI_TRIPLE_ID> * * @param id KiWiTriple id of the triple to explain * @return */ @GET @Path("/explain") @Produces("application/json") @Wrapped(element="nodes") public List<NodeJSON> getSubtree(@QueryParam("id") Long id, @QueryParam("rootid") String rootid) { log.info("getNodes(#0)", id); List<Justification> justifications = explanationService.explainTriple(id); log.info("Explanation returned #0", justifications); return toNodes(justifications, rootid); } private String describeTriple(Long tripleId) { KiWiTriple triple = entityManager.find(KiWiTriple.class, tripleId); return explanationService.describeTriple(triple, false); } private String describeTriple(KiWiTriple triple) { return explanationService.describeTriple(triple, false); } private List<NodeJSON> toNodes(List<Justification> justifications, String rootid) { List<NodeJSON> nodes = new ArrayList<NodeJSON>(); //TODO size for (Justification j : justifications) { NodeJSON node; List<String> neighbours; List<PairJSON> data; //first add all nodes to avoid the JIT adjacency bug /*for (String id : getAllNodeIds(j)) { node = new NodeJSON(id, id, new ArrayList<String>()); nodes.add(node); }*/ // NODE FOR THE JUSTIFIED TRIPLE neighbours = new ArrayList<String>(1); neighbours.add(rootid+j.toString()); data = new ArrayList<PairJSON>(2); data.add(new PairJSON("kiwiid", j.getFactId().toString())); data.add(new PairJSON("type", "triple")); data.add(new PairJSON("kiwiidj", j.getNeoId().toString())); //id of the justif this node belongs to data.add(new PairJSON("id",rootid));//connect the subtree we are constructing to the right node (the node for which this tree is loaded) data.add(new PairJSON("tooltip",describeTriple(j.getFact()))); node = new NodeJSON(toJITid(rootid), toJITid(j.getFactId()), neighbours, data); nodes.add(node); //log.info("Adding node #0", node.toString()); neighbours = getNeighbours(j, rootid); // NODE FOR THE JUSTIFICATION data = new ArrayList<PairJSON>(2); data.add(new PairJSON("id", rootid + j.toString())); data.add(new PairJSON("type", "justification")); data.add(new PairJSON("kiwiid", j.getNeoId().toString())); data.add(new PairJSON("tooltip","the node above is derived using the rule and triples below")); node = new NodeJSON(rootid + j.toString(),"support", neighbours, data); nodes.add(node); //log.info("Adding node #0", node.toString()); // NODES FOR THE IN TRIPLES for (Long id : j.getInTripleIds()) { data = new ArrayList<PairJSON>(2); data.add(new PairJSON("kiwiid", id.toString())); data.add(new PairJSON("type", "triple")); data.add(new PairJSON("kiwiidj", j.getNeoId().toString())); //id of the justif this node belongs to data.add(new PairJSON("id",rootid+j.toString()+id.toString()));//create a unique id for each justification so that nodes are never shared --> we're creating a tree, never a more general graph data.add(new PairJSON("leaf","true")); data.add(new PairJSON("tooltip",describeTriple(id))); node = new NodeJSON(toJITid(rootid+j.toString()+id.toString()), toJITid(id), new ArrayList<String>(), data); nodes.add(node); //log.info("Adding node #0", node.toString()); } data = new ArrayList<PairJSON>(2); data.add(new PairJSON("kiwiid", j.getRuleId())); data.add(new PairJSON("type", "rule")); data.add(new PairJSON("id", rootid+j.toString()+j.getRuleId()));//we don't wan't rules have only one node in the graph data.add(new PairJSON("tooltip","Rule "+j.getRuleId())); node = new NodeJSON(toJITid(rootid+j.toString()+j.getRuleId()), j.getRuleId(), new ArrayList<String>(), data); nodes.add(node); //log.info("Adding node #0", node.toString()); } return nodes; } private List<String> getNeighbours(Justification j, String rootid) { List<String> ns = new ArrayList<String>(); //ns.add(toJITid(j.getFactId())); for (Long id : j.getInTripleIds()) ns.add(toJITid(rootid+j.toString()+id)); ns.add(toJITid(rootid+j.toString()+j.getRuleId())); return ns; } private List<String> getAllNodeIds(Justification j) { List<String> ns = new ArrayList<String>(); ns.add(toJITid(j.getFactId())); for (Long id : j.getInTripleIds()) ns.add(toJITid(id)); ns.add(toJITid(j.getRuleId())); ns.add(j.toString()); return ns; } /** * JIT requires ids to be strings. * @param id * @return */ private String toJITid(Long id) { return "id"+id; } /** * JIT requires ids to be strings. * @param id * @return */ private String toJITid(String id) { return "id"+id; } }
fregaham/KiWi
src/action/kiwi/widgets/explanation/ExplanationWidgetWebService.java
Java
bsd-3-clause
7,806
/** * Copyright (C) 2016 Turi * All rights reserved. * * This software may be modified and distributed under the terms * of the BSD license. See the LICENSE file for details. */ #ifndef GRAPHLAB_MINIPSUTIL_H #define GRAPHLAB_MINIPSUTIL_H #include <stdint.h> extern "C" { /** * Returns the number of (Logical) CPUs. * Returns 0 on failure */ int32_t num_cpus(); /** * Returns the total amount of physical memory on the system. * Returns 0 on failure. */ uint64_t total_mem(); /** * Returns 1 if the pid is running, 0 otherwise. */ int32_t pid_is_running(int32_t pid); /** * Kill a process. Returns 1 on success, 0 on failure. */ int32_t kill_process(int32_t pid); } #endif
TobyRoseman/SFrame
oss_src/minipsutil/minipsutil.h
C
bsd-3-clause
692
UPDATE button SET flavor_text='This button gets a different random recipe in each game, with a vanilla random formula: 5 dice, no swing dice, no skills' WHERE name='RandomBMVanilla'; UPDATE button SET flavor_text='This button gets a different random recipe in each game, with a fixed random formula: 5 dice, no swing dice, two of them having a single skill chosen from c, f, and d (the same skill on both)' WHERE name='RandomBMFixed'; UPDATE button SET flavor_text='This button gets a different random recipe in each game, with a fixed random formula: 5 dice, no swing dice, three skills chosen from all existing skills, with each skill dealt out twice randomly and independently over all dice)' WHERE name='RandomBMMixed';
dwvanstone/buttonmen
deploy/database/updates/00779_03_fixed_redefine.sql
SQL
bsd-3-clause
726
<?php /** * Zend Framework (http://framework.zend.com/) * * @link http://github.com/zendframework/zf2 for the canonical source repository * @copyright Copyright (c) 2005-2015 Zend Technologies USA Inc. (http://www.zend.com) * @license http://framework.zend.com/license/new-bsd New BSD License */ namespace Zend\Db\TableGateway; use Zend\Db\Adapter\AdapterInterface; use Zend\Db\ResultSet\ResultSet; use Zend\Db\ResultSet\ResultSetInterface; use Zend\Db\Sql\Delete; use Zend\Db\Sql\Insert; use Zend\Db\Sql\Select; use Zend\Db\Sql\Sql; use Zend\Db\Sql\TableIdentifier; use Zend\Db\Sql\Update; use Zend\Db\Sql\Where; use Zend\Db\TableGateway\Feature\EventFeature; /** * * @property AdapterInterface $adapter * @property int $lastInsertValue * @property string $table */ abstract class AbstractTableGateway implements TableGatewayInterface { /** * @var bool */ protected $isInitialized = false; /** * @var AdapterInterface */ protected $adapter = null; /** * @var string|array|TableIdentifier */ protected $table = null; /** * @var array */ protected $columns = []; /** * @var Feature\FeatureSet */ protected $featureSet = null; /** * @var ResultSetInterface */ protected $resultSetPrototype = null; /** * @var Sql */ protected $sql = null; /** * * @var int */ protected $lastInsertValue = null; /** * @return bool */ public function isInitialized() { return $this->isInitialized; } /** * Initialize * * @throws Exception\RuntimeException * @return null */ public function initialize() { if ($this->isInitialized) { return; } if (!$this->featureSet instanceof Feature\FeatureSet) { $this->featureSet = new Feature\FeatureSet; } $this->featureSet->setTableGateway($this); $this->featureSet->apply(EventFeature::EVENT_PRE_INITIALIZE, []); if (!$this->adapter instanceof AdapterInterface) { throw new Exception\RuntimeException('This table does not have an Adapter setup'); } if (!is_string($this->table) && !$this->table instanceof TableIdentifier && !is_array($this->table)) { throw new Exception\RuntimeException('This table object does not have a valid table set.'); } if (!$this->resultSetPrototype instanceof ResultSetInterface) { $this->resultSetPrototype = new ResultSet; } if (!$this->sql instanceof Sql) { $this->sql = new Sql($this->adapter, $this->table); } $this->featureSet->apply(EventFeature::EVENT_POST_INITIALIZE, []); $this->isInitialized = true; } /** * Get table name * * @return string */ public function getTable() { return $this->table; } /** * Get adapter * * @return AdapterInterface */ public function getAdapter() { return $this->adapter; } /** * @return array */ public function getColumns() { return $this->columns; } /** * @return Feature\FeatureSet */ public function getFeatureSet() { return $this->featureSet; } /** * Get select result prototype * * @return ResultSet */ public function getResultSetPrototype() { return $this->resultSetPrototype; } /** * @return Sql */ public function getSql() { return $this->sql; } /** * Select * * @param Where|\Closure|string|array $where * @return ResultSet */ public function select($where = null) { if (!$this->isInitialized) { $this->initialize(); } $select = $this->sql->select(); if ($where instanceof \Closure) { $where($select); } elseif ($where !== null) { $select->where($where); } return $this->selectWith($select); } /** * @param Select $select * @return null|ResultSetInterface * @throws \RuntimeException */ public function selectWith(Select $select) { if (!$this->isInitialized) { $this->initialize(); } return $this->executeSelect($select); } /** * @param Select $select * @return ResultSet * @throws Exception\RuntimeException */ protected function executeSelect(Select $select) { $selectState = $select->getRawState(); if ($selectState['table'] != $this->table && (is_array($selectState['table']) && end($selectState['table']) != $this->table) ) { throw new Exception\RuntimeException( 'The table name of the provided select object must match that of the table' ); } if ($selectState['columns'] == [Select::SQL_STAR] && $this->columns !== []) { $select->columns($this->columns); } // apply preSelect features $this->featureSet->apply(EventFeature::EVENT_PRE_SELECT, [$select]); // prepare and execute $statement = $this->sql->prepareStatementForSqlObject($select); $result = $statement->execute(); // build result set $resultSet = clone $this->resultSetPrototype; $resultSet->initialize($result); // apply postSelect features $this->featureSet->apply(EventFeature::EVENT_POST_SELECT, [$statement, $result, $resultSet]); return $resultSet; } /** * Insert * * @param array $set * @return int */ public function insert($set) { if (!$this->isInitialized) { $this->initialize(); } $insert = $this->sql->insert(); $insert->values($set); return $this->executeInsert($insert); } /** * @param Insert $insert * @return mixed */ public function insertWith(Insert $insert) { if (!$this->isInitialized) { $this->initialize(); } return $this->executeInsert($insert); } /** * @todo add $columns support * * @param Insert $insert * @return mixed * @throws Exception\RuntimeException */ protected function executeInsert(Insert $insert) { $insertState = $insert->getRawState(); if ($insertState['table'] != $this->table) { throw new Exception\RuntimeException( 'The table name of the provided Insert object must match that of the table' ); } // apply preInsert features $this->featureSet->apply(EventFeature::EVENT_PRE_INSERT, [$insert]); // Most RDBMS solutions do not allow using table aliases in INSERTs // See https://github.com/zendframework/zf2/issues/7311 $unaliasedTable = false; if (is_array($insertState['table'])) { $tableData = array_values($insertState['table']); $unaliasedTable = array_shift($tableData); $insert->into($unaliasedTable); } $statement = $this->sql->prepareStatementForSqlObject($insert); $result = $statement->execute(); $this->lastInsertValue = $this->adapter->getDriver()->getConnection()->getLastGeneratedValue(); // apply postInsert features $this->featureSet->apply(EventFeature::EVENT_POST_INSERT, [$statement, $result]); // Reset original table information in Insert instance, if necessary if ($unaliasedTable) { $insert->into($insertState['table']); } $return = $result->getAffectedRows(); return $return; } /** * Update * * @param array $set * @param string|array|\Closure $where * @return int */ public function update($set, $where = null) { if (!$this->isInitialized) { $this->initialize(); } $sql = $this->sql; $update = $sql->update(); $update->set($set); if ($where !== null) { $update->where($where); } return $this->executeUpdate($update); } /** * @param \Zend\Db\Sql\Update $update * @return mixed */ public function updateWith(Update $update) { if (!$this->isInitialized) { $this->initialize(); } return $this->executeUpdate($update); } /** * @todo add $columns support * * @param Update $update * @return mixed * @throws Exception\RuntimeException */ protected function executeUpdate(Update $update) { $updateState = $update->getRawState(); if ($updateState['table'] != $this->table) { throw new Exception\RuntimeException( 'The table name of the provided Update object must match that of the table' ); } // apply preUpdate features $this->featureSet->apply(EventFeature::EVENT_PRE_UPDATE, [$update]); $statement = $this->sql->prepareStatementForSqlObject($update); $result = $statement->execute(); // apply postUpdate features $this->featureSet->apply(EventFeature::EVENT_POST_UPDATE, [$statement, $result]); return $result->getAffectedRows(); } /** * Delete * * @param Where|\Closure|string|array $where * @return int */ public function delete($where) { if (!$this->isInitialized) { $this->initialize(); } $delete = $this->sql->delete(); if ($where instanceof \Closure) { $where($delete); } else { $delete->where($where); } return $this->executeDelete($delete); } /** * @param Delete $delete * @return mixed */ public function deleteWith(Delete $delete) { $this->initialize(); return $this->executeDelete($delete); } /** * @todo add $columns support * * @param Delete $delete * @return mixed * @throws Exception\RuntimeException */ protected function executeDelete(Delete $delete) { $deleteState = $delete->getRawState(); if ($deleteState['table'] != $this->table) { throw new Exception\RuntimeException( 'The table name of the provided Update object must match that of the table' ); } // pre delete update $this->featureSet->apply(EventFeature::EVENT_PRE_DELETE, [$delete]); $statement = $this->sql->prepareStatementForSqlObject($delete); $result = $statement->execute(); // apply postDelete features $this->featureSet->apply(EventFeature::EVENT_POST_DELETE, [$statement, $result]); return $result->getAffectedRows(); } /** * Get last insert value * * @return int */ public function getLastInsertValue() { return $this->lastInsertValue; } /** * __get * * @param string $property * @throws Exception\InvalidArgumentException * @return mixed */ public function __get($property) { switch (strtolower($property)) { case 'lastinsertvalue': return $this->lastInsertValue; case 'adapter': return $this->adapter; case 'table': return $this->table; } if ($this->featureSet->canCallMagicGet($property)) { return $this->featureSet->callMagicGet($property); } throw new Exception\InvalidArgumentException('Invalid magic property access in ' . __CLASS__ . '::__get()'); } /** * @param string $property * @param mixed $value * @return mixed * @throws Exception\InvalidArgumentException */ public function __set($property, $value) { if ($this->featureSet->canCallMagicSet($property)) { return $this->featureSet->callMagicSet($property, $value); } throw new Exception\InvalidArgumentException('Invalid magic property access in ' . __CLASS__ . '::__set()'); } /** * @param $method * @param $arguments * @return mixed * @throws Exception\InvalidArgumentException */ public function __call($method, $arguments) { if ($this->featureSet->canCallMagicCall($method)) { return $this->featureSet->callMagicCall($method, $arguments); } throw new Exception\InvalidArgumentException(sprintf( 'Invalid method (%s) called, caught by %s::__call()', $method, __CLASS__ )); } /** * __clone */ public function __clone() { $this->resultSetPrototype = (isset($this->resultSetPrototype)) ? clone $this->resultSetPrototype : null; $this->sql = clone $this->sql; if (is_object($this->table)) { $this->table = clone $this->table; } elseif ( is_array($this->table) && count($this->table) == 1 && is_object(reset($this->table)) ) { foreach ($this->table as $alias => &$tableObject) { $tableObject = clone $tableObject; } } } }
srayner/zend-db
src/TableGateway/AbstractTableGateway.php
PHP
bsd-3-clause
13,476
/******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #if defined (WITH_GRAPHICS) #include <Array.hpp> #include <graphics_common.hpp> namespace cpu { template<typename T> void copy_surface(const Array<T> &P, fg::Surface* surface); } #endif
ghisvail/arrayfire
src/backend/cpu/surface.hpp
C++
bsd-3-clause
531
#ifndef __EIRODS_MS_HOME_H__ #define __EIRODS_MS_HOME_H__ #include <string> namespace eirods { const std::string EIRODS_MS_HOME( "EIRODSMSVCPATH" ); }; // namespace eirods #endif // __EIRODS_MS_HOME_H__
iPlantCollaborativeOpenSource/irods-3.3.1-iplant
server/re/include/eirods_ms_home.h
C
bsd-3-clause
210
#!/usr/bin/env php <?php require dirname(__DIR__) . '/_bootstrap.php'; defined('STDIN') or define('STDIN', fopen('php://stdin', 'r')); defined('STDOUT') or define('STDOUT', fopen('php://stdout', 'w')); $config = require(__DIR__ . '/config/console.php'); Yii::setAlias('@baseApp', dirname(__FILE__)); $exitCode = (new yii\console\Application($config))->run(); exit($exitCode);
jarrus90/yii2-website-comments
tests/_app/yii.php
PHP
bsd-3-clause
389
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @format * @flow strict-local */ 'use strict'; const Platform = require('../../Utilities/Platform'); import SliderNativeComponent from './SliderNativeComponent'; const React = require('react'); const StyleSheet = require('../../StyleSheet/StyleSheet'); import type {ImageSource} from '../../Image/ImageSource'; import type {ViewStyleProp} from '../../StyleSheet/StyleSheet'; import type {ColorValue} from '../../StyleSheet/StyleSheet'; import type {ViewProps} from '../View/ViewPropTypes'; import type {SyntheticEvent} from '../../Types/CoreEventTypes'; type Event = SyntheticEvent< $ReadOnly<{| value: number, /** * Android Only. */ fromUser?: boolean, |}>, >; type IOSProps = $ReadOnly<{| /** * Assigns a single image for the track. Only static images are supported. * The center pixel of the image will be stretched to fill the track. */ trackImage?: ?ImageSource, /** * Assigns a minimum track image. Only static images are supported. The * rightmost pixel of the image will be stretched to fill the track. */ minimumTrackImage?: ?ImageSource, /** * Assigns a maximum track image. Only static images are supported. The * leftmost pixel of the image will be stretched to fill the track. */ maximumTrackImage?: ?ImageSource, /** * Sets an image for the thumb. Only static images are supported. */ thumbImage?: ?ImageSource, |}>; type Props = $ReadOnly<{| ...ViewProps, ...IOSProps, /** * Used to style and layout the `Slider`. See `StyleSheet.js` and * `DeprecatedViewStylePropTypes.js` for more info. */ style?: ?ViewStyleProp, /** * Initial value of the slider. The value should be between minimumValue * and maximumValue, which default to 0 and 1 respectively. * Default value is 0. * * *This is not a controlled component*, you don't need to update the * value during dragging. */ value?: ?number, /** * Step value of the slider. The value should be * between 0 and (maximumValue - minimumValue). * Default value is 0. */ step?: ?number, /** * Initial minimum value of the slider. Default value is 0. */ minimumValue?: ?number, /** * Initial maximum value of the slider. Default value is 1. */ maximumValue?: ?number, /** * The color used for the track to the left of the button. * Overrides the default blue gradient image on iOS. */ minimumTrackTintColor?: ?ColorValue, /** * The color used for the track to the right of the button. * Overrides the default blue gradient image on iOS. */ maximumTrackTintColor?: ?ColorValue, /** * The color used to tint the default thumb images on iOS, or the * color of the foreground switch grip on Android. */ thumbTintColor?: ?ColorValue, /** * If true the user won't be able to move the slider. * Default value is false. */ disabled?: ?boolean, /** * Callback continuously called while the user is dragging the slider. */ onValueChange?: ?(value: number) => void, /** * Callback that is called when the user releases the slider, * regardless if the value has changed. The current value is passed * as an argument to the callback handler. */ onSlidingComplete?: ?(value: number) => void, /** * Used to locate this view in UI automation tests. */ testID?: ?string, |}>; /** * A component used to select a single value from a range of values. * * ### Usage * * The example below shows how to use `Slider` to change * a value used by `Text`. The value is stored using * the state of the root component (`App`). The same component * subscribes to the `onValueChange` of `Slider` and changes * the value using `setState`. * *``` * import React from 'react'; * import { StyleSheet, Text, View, Slider } from 'react-native'; * * export default class App extends React.Component { * constructor(props) { * super(props); * this.state = { * value: 50 * } * } * * change(value) { * this.setState(() => { * return { * value: parseFloat(value) * }; * }); * } * * render() { * const {value} = this.state; * return ( * <View style={styles.container}> * <Text style={styles.text}>{String(value)}</Text> * <Slider * step={1} * maximumValue={100} * onValueChange={this.change.bind(this)} * value={value} /> * </View> * ); * } * } * * const styles = StyleSheet.create({ * container: { * flex: 1, * flexDirection: 'column', * justifyContent: 'center' * }, * text: { * fontSize: 50, * textAlign: 'center' * } * }); *``` * */ const Slider = ( props: Props, forwardedRef?: ?React.Ref<typeof SliderNativeComponent>, ) => { const style = StyleSheet.compose(styles.slider, props.style); const { disabled = false, value = 0.5, minimumValue = 0, maximumValue = 1, step = 0, onValueChange, onSlidingComplete, ...localProps } = props; const onValueChangeEvent = onValueChange ? (event: Event) => { let userEvent = true; if (Platform.OS === 'android') { // On Android there's a special flag telling us the user is // dragging the slider. userEvent = event.nativeEvent.fromUser != null && event.nativeEvent.fromUser; } userEvent && onValueChange(event.nativeEvent.value); } : null; const onChangeEvent = onValueChangeEvent; const onSlidingCompleteEvent = onSlidingComplete ? (event: Event) => { onSlidingComplete(event.nativeEvent.value); } : null; return ( <SliderNativeComponent {...localProps} // TODO: Reconcile these across the two platforms. enabled={!disabled} disabled={disabled} maximumValue={maximumValue} minimumValue={minimumValue} onChange={onChangeEvent} onResponderTerminationRequest={() => false} onSlidingComplete={onSlidingCompleteEvent} onStartShouldSetResponder={() => true} onValueChange={onValueChangeEvent} ref={forwardedRef} step={step} style={style} value={value} /> ); }; const SliderWithRef: React.AbstractComponent< Props, React.ElementRef<typeof SliderNativeComponent>, > = React.forwardRef(Slider); let styles; if (Platform.OS === 'ios') { styles = StyleSheet.create({ slider: { height: 40, }, }); } else { styles = StyleSheet.create({ slider: {}, }); } module.exports = SliderWithRef;
hoangpham95/react-native
Libraries/Components/Slider/Slider.js
JavaScript
bsd-3-clause
6,808
/* * Copyright © 2007,2008,2009,2010 Red Hat, Inc. * Copyright © 2010,2012 Google, Inc. * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. * * Red Hat Author(s): Behdad Esfahbod * Google Author(s): Behdad Esfahbod */ #ifndef HB_OT_LAYOUT_GPOS_TABLE_HH #define HB_OT_LAYOUT_GPOS_TABLE_HH #include "hb-ot-layout-gsubgpos-private.hh" namespace OT { /* buffer **position** var allocations */ #define attach_lookback() var.u16[0] /* number of glyphs to go back to attach this glyph to its base */ #define cursive_chain() var.i16[1] /* character to which this connects, may be positive or negative */ /* Shared Tables: ValueRecord, Anchor Table, and MarkArray */ typedef USHORT Value; typedef Value ValueRecord[VAR]; struct ValueFormat : USHORT { enum Flags { xPlacement = 0x0001, /* Includes horizontal adjustment for placement */ yPlacement = 0x0002, /* Includes vertical adjustment for placement */ xAdvance = 0x0004, /* Includes horizontal adjustment for advance */ yAdvance = 0x0008, /* Includes vertical adjustment for advance */ xPlaDevice = 0x0010, /* Includes horizontal Device table for placement */ yPlaDevice = 0x0020, /* Includes vertical Device table for placement */ xAdvDevice = 0x0040, /* Includes horizontal Device table for advance */ yAdvDevice = 0x0080, /* Includes vertical Device table for advance */ ignored = 0x0F00, /* Was used in TrueType Open for MM fonts */ reserved = 0xF000, /* For future use */ devices = 0x00F0 /* Mask for having any Device table */ }; /* All fields are options. Only those available advance the value pointer. */ #if 0 SHORT xPlacement; /* Horizontal adjustment for * placement--in design units */ SHORT yPlacement; /* Vertical adjustment for * placement--in design units */ SHORT xAdvance; /* Horizontal adjustment for * advance--in design units (only used * for horizontal writing) */ SHORT yAdvance; /* Vertical adjustment for advance--in * design units (only used for vertical * writing) */ Offset xPlaDevice; /* Offset to Device table for * horizontal placement--measured from * beginning of PosTable (may be NULL) */ Offset yPlaDevice; /* Offset to Device table for vertical * placement--measured from beginning * of PosTable (may be NULL) */ Offset xAdvDevice; /* Offset to Device table for * horizontal advance--measured from * beginning of PosTable (may be NULL) */ Offset yAdvDevice; /* Offset to Device table for vertical * advance--measured from beginning of * PosTable (may be NULL) */ #endif inline unsigned int get_len (void) const { return _hb_popcount32 ((unsigned int) *this); } inline unsigned int get_size (void) const { return get_len () * Value::static_size; } void apply_value (hb_font_t *font, hb_direction_t direction, const void *base, const Value *values, hb_glyph_position_t &glyph_pos) const { unsigned int x_ppem, y_ppem; unsigned int format = *this; hb_bool_t horizontal = HB_DIRECTION_IS_HORIZONTAL (direction); if (!format) return; if (format & xPlacement) glyph_pos.x_offset += font->em_scale_x (get_short (values++)); if (format & yPlacement) glyph_pos.y_offset += font->em_scale_y (get_short (values++)); if (format & xAdvance) { if (likely (horizontal)) glyph_pos.x_advance += font->em_scale_x (get_short (values++)); else values++; } /* y_advance values grow downward but font-space grows upward, hence negation */ if (format & yAdvance) { if (unlikely (!horizontal)) glyph_pos.y_advance -= font->em_scale_y (get_short (values++)); else values++; } if (!has_device ()) return; x_ppem = font->x_ppem; y_ppem = font->y_ppem; if (!x_ppem && !y_ppem) return; /* pixel -> fractional pixel */ if (format & xPlaDevice) { if (x_ppem) glyph_pos.x_offset += (base + get_device (values++)).get_x_delta (font); else values++; } if (format & yPlaDevice) { if (y_ppem) glyph_pos.y_offset += (base + get_device (values++)).get_y_delta (font); else values++; } if (format & xAdvDevice) { if (horizontal && x_ppem) glyph_pos.x_advance += (base + get_device (values++)).get_x_delta (font); else values++; } if (format & yAdvDevice) { /* y_advance values grow downward but font-space grows upward, hence negation */ if (!horizontal && y_ppem) glyph_pos.y_advance -= (base + get_device (values++)).get_y_delta (font); else values++; } } private: inline bool sanitize_value_devices (hb_sanitize_context_t *c, void *base, Value *values) { unsigned int format = *this; if (format & xPlacement) values++; if (format & yPlacement) values++; if (format & xAdvance) values++; if (format & yAdvance) values++; if ((format & xPlaDevice) && !get_device (values++).sanitize (c, base)) return false; if ((format & yPlaDevice) && !get_device (values++).sanitize (c, base)) return false; if ((format & xAdvDevice) && !get_device (values++).sanitize (c, base)) return false; if ((format & yAdvDevice) && !get_device (values++).sanitize (c, base)) return false; return true; } static inline OffsetTo<Device>& get_device (Value* value) { return *CastP<OffsetTo<Device> > (value); } static inline const OffsetTo<Device>& get_device (const Value* value) { return *CastP<OffsetTo<Device> > (value); } static inline const SHORT& get_short (const Value* value) { return *CastP<SHORT> (value); } public: inline bool has_device (void) const { unsigned int format = *this; return (format & devices) != 0; } inline bool sanitize_value (hb_sanitize_context_t *c, void *base, Value *values) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_range (values, get_size ()) && (!has_device () || sanitize_value_devices (c, base, values))); } inline bool sanitize_values (hb_sanitize_context_t *c, void *base, Value *values, unsigned int count) { TRACE_SANITIZE (); unsigned int len = get_len (); if (!c->check_array (values, get_size (), count)) return TRACE_RETURN (false); if (!has_device ()) return TRACE_RETURN (true); for (unsigned int i = 0; i < count; i++) { if (!sanitize_value_devices (c, base, values)) return TRACE_RETURN (false); values += len; } return TRACE_RETURN (true); } /* Just sanitize referenced Device tables. Doesn't check the values themselves. */ inline bool sanitize_values_stride_unsafe (hb_sanitize_context_t *c, void *base, Value *values, unsigned int count, unsigned int stride) { TRACE_SANITIZE (); if (!has_device ()) return TRACE_RETURN (true); for (unsigned int i = 0; i < count; i++) { if (!sanitize_value_devices (c, base, values)) return TRACE_RETURN (false); values += stride; } return TRACE_RETURN (true); } }; struct AnchorFormat1 { friend struct Anchor; private: inline void get_anchor (hb_font_t *font, hb_codepoint_t glyph_id HB_UNUSED, hb_position_t *x, hb_position_t *y) const { *x = font->em_scale_x (xCoordinate); *y = font->em_scale_y (yCoordinate); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this)); } protected: USHORT format; /* Format identifier--format = 1 */ SHORT xCoordinate; /* Horizontal value--in design units */ SHORT yCoordinate; /* Vertical value--in design units */ public: DEFINE_SIZE_STATIC (6); }; struct AnchorFormat2 { friend struct Anchor; private: inline void get_anchor (hb_font_t *font, hb_codepoint_t glyph_id, hb_position_t *x, hb_position_t *y) const { unsigned int x_ppem = font->x_ppem; unsigned int y_ppem = font->y_ppem; hb_position_t cx, cy; hb_bool_t ret = false; if (x_ppem || y_ppem) ret = font->get_glyph_contour_point_for_origin (glyph_id, anchorPoint, HB_DIRECTION_LTR, &cx, &cy); *x = x_ppem && ret ? cx : font->em_scale_x (xCoordinate); *y = y_ppem && ret ? cy : font->em_scale_y (yCoordinate); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this)); } protected: USHORT format; /* Format identifier--format = 2 */ SHORT xCoordinate; /* Horizontal value--in design units */ SHORT yCoordinate; /* Vertical value--in design units */ USHORT anchorPoint; /* Index to glyph contour point */ public: DEFINE_SIZE_STATIC (8); }; struct AnchorFormat3 { friend struct Anchor; private: inline void get_anchor (hb_font_t *font, hb_codepoint_t glyph_id HB_UNUSED, hb_position_t *x, hb_position_t *y) const { *x = font->em_scale_x (xCoordinate); *y = font->em_scale_y (yCoordinate); if (font->x_ppem) *x += (this+xDeviceTable).get_x_delta (font); if (font->y_ppem) *y += (this+yDeviceTable).get_x_delta (font); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && xDeviceTable.sanitize (c, this) && yDeviceTable.sanitize (c, this)); } protected: USHORT format; /* Format identifier--format = 3 */ SHORT xCoordinate; /* Horizontal value--in design units */ SHORT yCoordinate; /* Vertical value--in design units */ OffsetTo<Device> xDeviceTable; /* Offset to Device table for X * coordinate-- from beginning of * Anchor table (may be NULL) */ OffsetTo<Device> yDeviceTable; /* Offset to Device table for Y * coordinate-- from beginning of * Anchor table (may be NULL) */ public: DEFINE_SIZE_STATIC (10); }; struct Anchor { inline void get_anchor (hb_font_t *font, hb_codepoint_t glyph_id, hb_position_t *x, hb_position_t *y) const { *x = *y = 0; switch (u.format) { case 1: u.format1.get_anchor (font, glyph_id, x, y); return; case 2: u.format2.get_anchor (font, glyph_id, x, y); return; case 3: u.format3.get_anchor (font, glyph_id, x, y); return; default: return; } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); case 2: return TRACE_RETURN (u.format2.sanitize (c)); case 3: return TRACE_RETURN (u.format3.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ AnchorFormat1 format1; AnchorFormat2 format2; AnchorFormat3 format3; } u; public: DEFINE_SIZE_UNION (2, format); }; struct AnchorMatrix { inline const Anchor& get_anchor (unsigned int row, unsigned int col, unsigned int cols) const { if (unlikely (row >= rows || col >= cols)) return Null(Anchor); return this+matrix[row * cols + col]; } inline bool sanitize (hb_sanitize_context_t *c, unsigned int cols) { TRACE_SANITIZE (); if (!c->check_struct (this)) return TRACE_RETURN (false); if (unlikely (rows > 0 && cols >= ((unsigned int) -1) / rows)) return TRACE_RETURN (false); unsigned int count = rows * cols; if (!c->check_array (matrix, matrix[0].static_size, count)) return TRACE_RETURN (false); for (unsigned int i = 0; i < count; i++) if (!matrix[i].sanitize (c, this)) return TRACE_RETURN (false); return TRACE_RETURN (true); } USHORT rows; /* Number of rows */ protected: OffsetTo<Anchor> matrix[VAR]; /* Matrix of offsets to Anchor tables-- * from beginning of AnchorMatrix table */ public: DEFINE_SIZE_ARRAY (2, matrix); }; struct MarkRecord { friend struct MarkArray; inline bool sanitize (hb_sanitize_context_t *c, void *base) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && markAnchor.sanitize (c, base)); } protected: USHORT klass; /* Class defined for this mark */ OffsetTo<Anchor> markAnchor; /* Offset to Anchor table--from * beginning of MarkArray table */ public: DEFINE_SIZE_STATIC (4); }; struct MarkArray : ArrayOf<MarkRecord> /* Array of MarkRecords--in Coverage order */ { inline bool apply (hb_apply_context_t *c, unsigned int mark_index, unsigned int glyph_index, const AnchorMatrix &anchors, unsigned int class_count, unsigned int glyph_pos) const { TRACE_APPLY (); const MarkRecord &record = ArrayOf<MarkRecord>::operator[](mark_index); unsigned int mark_class = record.klass; const Anchor& mark_anchor = this + record.markAnchor; const Anchor& glyph_anchor = anchors.get_anchor (glyph_index, mark_class, class_count); hb_position_t mark_x, mark_y, base_x, base_y; mark_anchor.get_anchor (c->font, c->buffer->cur().codepoint, &mark_x, &mark_y); glyph_anchor.get_anchor (c->font, c->buffer->info[glyph_pos].codepoint, &base_x, &base_y); hb_glyph_position_t &o = c->buffer->cur_pos(); o.x_offset = base_x - mark_x; o.y_offset = base_y - mark_y; o.attach_lookback() = c->buffer->idx - glyph_pos; c->buffer->idx++; return TRACE_RETURN (true); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (ArrayOf<MarkRecord>::sanitize (c, this)); } }; /* Lookups */ struct SinglePosFormat1 { friend struct SinglePos; private: inline const Coverage &get_coverage (void) const { return this+coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); unsigned int index = (this+coverage) (c->buffer->cur().codepoint); if (likely (index == NOT_COVERED)) return TRACE_RETURN (false); valueFormat.apply_value (c->font, c->direction, this, values, c->buffer->cur_pos()); c->buffer->idx++; return TRACE_RETURN (true); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && coverage.sanitize (c, this) && valueFormat.sanitize_value (c, this, values)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of subtable */ ValueFormat valueFormat; /* Defines the types of data in the * ValueRecord */ ValueRecord values; /* Defines positioning * value(s)--applied to all glyphs in * the Coverage table */ public: DEFINE_SIZE_ARRAY (6, values); }; struct SinglePosFormat2 { friend struct SinglePos; private: inline const Coverage &get_coverage (void) const { return this+coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); unsigned int index = (this+coverage) (c->buffer->cur().codepoint); if (likely (index == NOT_COVERED)) return TRACE_RETURN (false); if (likely (index >= valueCount)) return TRACE_RETURN (false); valueFormat.apply_value (c->font, c->direction, this, &values[index * valueFormat.get_len ()], c->buffer->cur_pos()); c->buffer->idx++; return TRACE_RETURN (true); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && coverage.sanitize (c, this) && valueFormat.sanitize_values (c, this, values, valueCount)); } protected: USHORT format; /* Format identifier--format = 2 */ OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of subtable */ ValueFormat valueFormat; /* Defines the types of data in the * ValueRecord */ USHORT valueCount; /* Number of ValueRecords */ ValueRecord values; /* Array of ValueRecords--positioning * values applied to glyphs */ public: DEFINE_SIZE_ARRAY (8, values); }; struct SinglePos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); case 2: return u.format2.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); case 2: return TRACE_RETURN (u.format2.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); case 2: return TRACE_RETURN (u.format2.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ SinglePosFormat1 format1; SinglePosFormat2 format2; } u; }; struct PairValueRecord { friend struct PairSet; protected: GlyphID secondGlyph; /* GlyphID of second glyph in the * pair--first glyph is listed in the * Coverage table */ ValueRecord values; /* Positioning data for the first glyph * followed by for second glyph */ public: DEFINE_SIZE_ARRAY (2, values); }; struct PairSet { friend struct PairPosFormat1; inline bool apply (hb_apply_context_t *c, const ValueFormat *valueFormats, unsigned int pos) const { TRACE_APPLY (); unsigned int len1 = valueFormats[0].get_len (); unsigned int len2 = valueFormats[1].get_len (); unsigned int record_size = USHORT::static_size * (1 + len1 + len2); unsigned int count = len; const PairValueRecord *record = CastP<PairValueRecord> (array); for (unsigned int i = 0; i < count; i++) { if (c->buffer->info[pos].codepoint == record->secondGlyph) { valueFormats[0].apply_value (c->font, c->direction, this, &record->values[0], c->buffer->cur_pos()); valueFormats[1].apply_value (c->font, c->direction, this, &record->values[len1], c->buffer->pos[pos]); if (len2) pos++; c->buffer->idx = pos; return TRACE_RETURN (true); } record = &StructAtOffset<PairValueRecord> (record, record_size); } return TRACE_RETURN (false); } struct sanitize_closure_t { void *base; ValueFormat *valueFormats; unsigned int len1; /* valueFormats[0].get_len() */ unsigned int stride; /* 1 + len1 + len2 */ }; inline bool sanitize (hb_sanitize_context_t *c, const sanitize_closure_t *closure) { TRACE_SANITIZE (); if (!(c->check_struct (this) && c->check_array (array, USHORT::static_size * closure->stride, len))) return TRACE_RETURN (false); unsigned int count = len; PairValueRecord *record = CastP<PairValueRecord> (array); return TRACE_RETURN (closure->valueFormats[0].sanitize_values_stride_unsafe (c, closure->base, &record->values[0], count, closure->stride) && closure->valueFormats[1].sanitize_values_stride_unsafe (c, closure->base, &record->values[closure->len1], count, closure->stride)); } protected: USHORT len; /* Number of PairValueRecords */ USHORT array[VAR]; /* Array of PairValueRecords--ordered * by GlyphID of the second glyph */ public: DEFINE_SIZE_ARRAY (2, array); }; struct PairPosFormat1 { friend struct PairPos; private: inline const Coverage &get_coverage (void) const { return this+coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); hb_apply_context_t::mark_skipping_forward_iterator_t skippy_iter (c, c->buffer->idx, 1); if (skippy_iter.has_no_chance ()) return TRACE_RETURN (false); unsigned int index = (this+coverage) (c->buffer->cur().codepoint); if (likely (index == NOT_COVERED)) return TRACE_RETURN (false); if (!skippy_iter.next ()) return TRACE_RETURN (false); return TRACE_RETURN ((this+pairSet[index]).apply (c, &valueFormat1, skippy_iter.idx)); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); unsigned int len1 = valueFormat1.get_len (); unsigned int len2 = valueFormat2.get_len (); PairSet::sanitize_closure_t closure = { this, &valueFormat1, len1, 1 + len1 + len2 }; return TRACE_RETURN (c->check_struct (this) && coverage.sanitize (c, this) && pairSet.sanitize (c, this, &closure)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of subtable */ ValueFormat valueFormat1; /* Defines the types of data in * ValueRecord1--for the first glyph * in the pair--may be zero (0) */ ValueFormat valueFormat2; /* Defines the types of data in * ValueRecord2--for the second glyph * in the pair--may be zero (0) */ OffsetArrayOf<PairSet> pairSet; /* Array of PairSet tables * ordered by Coverage Index */ public: DEFINE_SIZE_ARRAY (10, pairSet); }; struct PairPosFormat2 { friend struct PairPos; private: inline const Coverage &get_coverage (void) const { return this+coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); hb_apply_context_t::mark_skipping_forward_iterator_t skippy_iter (c, c->buffer->idx, 1); if (skippy_iter.has_no_chance ()) return TRACE_RETURN (false); unsigned int index = (this+coverage) (c->buffer->cur().codepoint); if (likely (index == NOT_COVERED)) return TRACE_RETURN (false); if (!skippy_iter.next ()) return TRACE_RETURN (false); unsigned int len1 = valueFormat1.get_len (); unsigned int len2 = valueFormat2.get_len (); unsigned int record_len = len1 + len2; unsigned int klass1 = (this+classDef1) (c->buffer->cur().codepoint); unsigned int klass2 = (this+classDef2) (c->buffer->info[skippy_iter.idx].codepoint); if (unlikely (klass1 >= class1Count || klass2 >= class2Count)) return TRACE_RETURN (false); const Value *v = &values[record_len * (klass1 * class2Count + klass2)]; valueFormat1.apply_value (c->font, c->direction, this, v, c->buffer->cur_pos()); valueFormat2.apply_value (c->font, c->direction, this, v + len1, c->buffer->pos[skippy_iter.idx]); c->buffer->idx = skippy_iter.idx; if (len2) c->buffer->idx++; return TRACE_RETURN (true); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!(c->check_struct (this) && coverage.sanitize (c, this) && classDef1.sanitize (c, this) && classDef2.sanitize (c, this))) return TRACE_RETURN (false); unsigned int len1 = valueFormat1.get_len (); unsigned int len2 = valueFormat2.get_len (); unsigned int stride = len1 + len2; unsigned int record_size = valueFormat1.get_size () + valueFormat2.get_size (); unsigned int count = (unsigned int) class1Count * (unsigned int) class2Count; return TRACE_RETURN (c->check_array (values, record_size, count) && valueFormat1.sanitize_values_stride_unsafe (c, this, &values[0], count, stride) && valueFormat2.sanitize_values_stride_unsafe (c, this, &values[len1], count, stride)); } protected: USHORT format; /* Format identifier--format = 2 */ OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of subtable */ ValueFormat valueFormat1; /* ValueRecord definition--for the * first glyph of the pair--may be zero * (0) */ ValueFormat valueFormat2; /* ValueRecord definition--for the * second glyph of the pair--may be * zero (0) */ OffsetTo<ClassDef> classDef1; /* Offset to ClassDef table--from * beginning of PairPos subtable--for * the first glyph of the pair */ OffsetTo<ClassDef> classDef2; /* Offset to ClassDef table--from * beginning of PairPos subtable--for * the second glyph of the pair */ USHORT class1Count; /* Number of classes in ClassDef1 * table--includes Class0 */ USHORT class2Count; /* Number of classes in ClassDef2 * table--includes Class0 */ ValueRecord values; /* Matrix of value pairs: * class1-major, class2-minor, * Each entry has value1 and value2 */ public: DEFINE_SIZE_ARRAY (16, values); }; struct PairPos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); case 2: return u.format2.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); case 2: return TRACE_RETURN (u.format2.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); case 2: return TRACE_RETURN (u.format2.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ PairPosFormat1 format1; PairPosFormat2 format2; } u; }; struct EntryExitRecord { friend struct CursivePosFormat1; inline bool sanitize (hb_sanitize_context_t *c, void *base) { TRACE_SANITIZE (); return TRACE_RETURN (entryAnchor.sanitize (c, base) && exitAnchor.sanitize (c, base)); } protected: OffsetTo<Anchor> entryAnchor; /* Offset to EntryAnchor table--from * beginning of CursivePos * subtable--may be NULL */ OffsetTo<Anchor> exitAnchor; /* Offset to ExitAnchor table--from * beginning of CursivePos * subtable--may be NULL */ public: DEFINE_SIZE_STATIC (4); }; struct CursivePosFormat1 { friend struct CursivePos; private: inline const Coverage &get_coverage (void) const { return this+coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); /* We don't handle mark glyphs here. */ if (c->property & HB_OT_LAYOUT_GLYPH_CLASS_MARK) return TRACE_RETURN (false); hb_apply_context_t::mark_skipping_forward_iterator_t skippy_iter (c, c->buffer->idx, 1); if (skippy_iter.has_no_chance ()) return TRACE_RETURN (false); const EntryExitRecord &this_record = entryExitRecord[(this+coverage) (c->buffer->cur().codepoint)]; if (!this_record.exitAnchor) return TRACE_RETURN (false); if (!skippy_iter.next ()) return TRACE_RETURN (false); const EntryExitRecord &next_record = entryExitRecord[(this+coverage) (c->buffer->info[skippy_iter.idx].codepoint)]; if (!next_record.entryAnchor) return TRACE_RETURN (false); unsigned int i = c->buffer->idx; unsigned int j = skippy_iter.idx; hb_position_t entry_x, entry_y, exit_x, exit_y; (this+this_record.exitAnchor).get_anchor (c->font, c->buffer->info[i].codepoint, &exit_x, &exit_y); (this+next_record.entryAnchor).get_anchor (c->font, c->buffer->info[j].codepoint, &entry_x, &entry_y); hb_glyph_position_t *pos = c->buffer->pos; hb_position_t d; /* Main-direction adjustment */ switch (c->direction) { case HB_DIRECTION_LTR: pos[i].x_advance = exit_x + pos[i].x_offset; d = entry_x + pos[j].x_offset; pos[j].x_advance -= d; pos[j].x_offset -= d; break; case HB_DIRECTION_RTL: d = exit_x + pos[i].x_offset; pos[i].x_advance -= d; pos[i].x_offset -= d; pos[j].x_advance = entry_x + pos[j].x_offset; break; case HB_DIRECTION_TTB: pos[i].y_advance = exit_y + pos[i].y_offset; d = entry_y + pos[j].y_offset; pos[j].y_advance -= d; pos[j].y_offset -= d; break; case HB_DIRECTION_BTT: d = exit_y + pos[i].y_offset; pos[i].y_advance -= d; pos[i].y_offset -= d; pos[j].y_advance = entry_y; break; case HB_DIRECTION_INVALID: default: break; } /* Cross-direction adjustment */ if (c->lookup_props & LookupFlag::RightToLeft) { pos[i].cursive_chain() = j - i; if (likely (HB_DIRECTION_IS_HORIZONTAL (c->direction))) pos[i].y_offset = entry_y - exit_y; else pos[i].x_offset = entry_x - exit_x; } else { pos[j].cursive_chain() = i - j; if (likely (HB_DIRECTION_IS_HORIZONTAL (c->direction))) pos[j].y_offset = exit_y - entry_y; else pos[j].x_offset = exit_x - entry_x; } c->buffer->idx = j; return TRACE_RETURN (true); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (coverage.sanitize (c, this) && entryExitRecord.sanitize (c, this)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> coverage; /* Offset to Coverage table--from * beginning of subtable */ ArrayOf<EntryExitRecord> entryExitRecord; /* Array of EntryExit records--in * Coverage Index order */ public: DEFINE_SIZE_ARRAY (6, entryExitRecord); }; struct CursivePos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ CursivePosFormat1 format1; } u; }; typedef AnchorMatrix BaseArray; /* base-major-- * in order of BaseCoverage Index--, * mark-minor-- * ordered by class--zero-based. */ struct MarkBasePosFormat1 { friend struct MarkBasePos; private: inline const Coverage &get_coverage (void) const { return this+markCoverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); unsigned int mark_index = (this+markCoverage) (c->buffer->cur().codepoint); if (likely (mark_index == NOT_COVERED)) return TRACE_RETURN (false); /* now we search backwards for a non-mark glyph */ unsigned int property; hb_apply_context_t::mark_skipping_backward_iterator_t skippy_iter (c, c->buffer->idx, 1); do { if (!skippy_iter.prev (&property, LookupFlag::IgnoreMarks)) return TRACE_RETURN (false); /* We only want to attach to the first of a MultipleSubst sequence. Reject others. */ if (0 == get_lig_comp (c->buffer->info[skippy_iter.idx])) break; skippy_iter.reject (); } while (1); /* The following assertion is too strong, so we've disabled it. */ if (!(property & HB_OT_LAYOUT_GLYPH_CLASS_BASE_GLYPH)) {/*return TRACE_RETURN (false);*/} unsigned int base_index = (this+baseCoverage) (c->buffer->info[skippy_iter.idx].codepoint); if (base_index == NOT_COVERED) return TRACE_RETURN (false); return TRACE_RETURN ((this+markArray).apply (c, mark_index, base_index, this+baseArray, classCount, skippy_iter.idx)); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && markCoverage.sanitize (c, this) && baseCoverage.sanitize (c, this) && markArray.sanitize (c, this) && baseArray.sanitize (c, this, (unsigned int) classCount)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> markCoverage; /* Offset to MarkCoverage table--from * beginning of MarkBasePos subtable */ OffsetTo<Coverage> baseCoverage; /* Offset to BaseCoverage table--from * beginning of MarkBasePos subtable */ USHORT classCount; /* Number of classes defined for marks */ OffsetTo<MarkArray> markArray; /* Offset to MarkArray table--from * beginning of MarkBasePos subtable */ OffsetTo<BaseArray> baseArray; /* Offset to BaseArray table--from * beginning of MarkBasePos subtable */ public: DEFINE_SIZE_STATIC (12); }; struct MarkBasePos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ MarkBasePosFormat1 format1; } u; }; typedef AnchorMatrix LigatureAttach; /* component-major-- * in order of writing direction--, * mark-minor-- * ordered by class--zero-based. */ typedef OffsetListOf<LigatureAttach> LigatureArray; /* Array of LigatureAttach * tables ordered by * LigatureCoverage Index */ struct MarkLigPosFormat1 { friend struct MarkLigPos; private: inline const Coverage &get_coverage (void) const { return this+markCoverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); unsigned int mark_index = (this+markCoverage) (c->buffer->cur().codepoint); if (likely (mark_index == NOT_COVERED)) return TRACE_RETURN (false); /* now we search backwards for a non-mark glyph */ unsigned int property; hb_apply_context_t::mark_skipping_backward_iterator_t skippy_iter (c, c->buffer->idx, 1); if (!skippy_iter.prev (&property, LookupFlag::IgnoreMarks)) return TRACE_RETURN (false); /* The following assertion is too strong, so we've disabled it. */ if (!(property & HB_OT_LAYOUT_GLYPH_CLASS_LIGATURE)) {/*return TRACE_RETURN (false);*/} unsigned int j = skippy_iter.idx; unsigned int lig_index = (this+ligatureCoverage) (c->buffer->info[j].codepoint); if (lig_index == NOT_COVERED) return TRACE_RETURN (false); const LigatureArray& lig_array = this+ligatureArray; const LigatureAttach& lig_attach = lig_array[lig_index]; /* Find component to attach to */ unsigned int comp_count = lig_attach.rows; if (unlikely (!comp_count)) return TRACE_RETURN (false); /* We must now check whether the ligature ID of the current mark glyph * is identical to the ligature ID of the found ligature. If yes, we * can directly use the component index. If not, we attach the mark * glyph to the last component of the ligature. */ unsigned int comp_index; unsigned int lig_id = get_lig_id (c->buffer->info[j]); unsigned int mark_id = get_lig_id (c->buffer->cur()); unsigned int mark_comp = get_lig_comp (c->buffer->cur()); if (lig_id && lig_id == mark_id && mark_comp > 0) comp_index = MIN (comp_count, get_lig_comp (c->buffer->cur())) - 1; else comp_index = comp_count - 1; return TRACE_RETURN ((this+markArray).apply (c, mark_index, comp_index, lig_attach, classCount, j)); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && markCoverage.sanitize (c, this) && ligatureCoverage.sanitize (c, this) && markArray.sanitize (c, this) && ligatureArray.sanitize (c, this, (unsigned int) classCount)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> markCoverage; /* Offset to Mark Coverage table--from * beginning of MarkLigPos subtable */ OffsetTo<Coverage> ligatureCoverage; /* Offset to Ligature Coverage * table--from beginning of MarkLigPos * subtable */ USHORT classCount; /* Number of defined mark classes */ OffsetTo<MarkArray> markArray; /* Offset to MarkArray table--from * beginning of MarkLigPos subtable */ OffsetTo<LigatureArray> ligatureArray; /* Offset to LigatureArray table--from * beginning of MarkLigPos subtable */ public: DEFINE_SIZE_STATIC (12); }; struct MarkLigPos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ MarkLigPosFormat1 format1; } u; }; typedef AnchorMatrix Mark2Array; /* mark2-major-- * in order of Mark2Coverage Index--, * mark1-minor-- * ordered by class--zero-based. */ struct MarkMarkPosFormat1 { friend struct MarkMarkPos; private: inline const Coverage &get_coverage (void) const { return this+mark1Coverage; } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); unsigned int mark1_index = (this+mark1Coverage) (c->buffer->cur().codepoint); if (likely (mark1_index == NOT_COVERED)) return TRACE_RETURN (false); /* now we search backwards for a suitable mark glyph until a non-mark glyph */ unsigned int property; hb_apply_context_t::mark_skipping_backward_iterator_t skippy_iter (c, c->buffer->idx, 1); if (!skippy_iter.prev (&property)) return TRACE_RETURN (false); if (!(property & HB_OT_LAYOUT_GLYPH_CLASS_MARK)) return TRACE_RETURN (false); unsigned int j = skippy_iter.idx; unsigned int id1 = get_lig_id (c->buffer->cur()); unsigned int id2 = get_lig_id (c->buffer->info[j]); unsigned int comp1 = get_lig_comp (c->buffer->cur()); unsigned int comp2 = get_lig_comp (c->buffer->info[j]); if (likely (id1 == id2)) { if (id1 == 0) /* Marks belonging to the same base. */ goto good; else if (comp1 == comp2) /* Marks belonging to the same ligature component. */ goto good; } else { /* If ligature ids don't match, it may be the case that one of the marks * itself is a ligature. In which case match. */ if ((id1 > 0 && !comp1) || (id2 > 0 && !comp2)) goto good; } /* Didn't match. */ return TRACE_RETURN (false); good: unsigned int mark2_index = (this+mark2Coverage) (c->buffer->info[j].codepoint); if (mark2_index == NOT_COVERED) return TRACE_RETURN (false); return TRACE_RETURN ((this+mark1Array).apply (c, mark1_index, mark2_index, this+mark2Array, classCount, j)); } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); return TRACE_RETURN (c->check_struct (this) && mark1Coverage.sanitize (c, this) && mark2Coverage.sanitize (c, this) && mark1Array.sanitize (c, this) && mark2Array.sanitize (c, this, (unsigned int) classCount)); } protected: USHORT format; /* Format identifier--format = 1 */ OffsetTo<Coverage> mark1Coverage; /* Offset to Combining Mark1 Coverage * table--from beginning of MarkMarkPos * subtable */ OffsetTo<Coverage> mark2Coverage; /* Offset to Combining Mark2 Coverage * table--from beginning of MarkMarkPos * subtable */ USHORT classCount; /* Number of defined mark classes */ OffsetTo<MarkArray> mark1Array; /* Offset to Mark1Array table--from * beginning of MarkMarkPos subtable */ OffsetTo<Mark2Array> mark2Array; /* Offset to Mark2Array table--from * beginning of MarkMarkPos subtable */ public: DEFINE_SIZE_STATIC (12); }; struct MarkMarkPos { friend struct PosLookupSubTable; private: inline const Coverage &get_coverage (void) const { switch (u.format) { case 1: return u.format1.get_coverage (); default:return Null(Coverage); } } inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); switch (u.format) { case 1: return TRACE_RETURN (u.format1.apply (c)); default:return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (!u.format.sanitize (c)) return TRACE_RETURN (false); switch (u.format) { case 1: return TRACE_RETURN (u.format1.sanitize (c)); default:return TRACE_RETURN (true); } } protected: union { USHORT format; /* Format identifier */ MarkMarkPosFormat1 format1; } u; }; static inline bool position_lookup (hb_apply_context_t *c, unsigned int lookup_index); struct ContextPos : Context { friend struct PosLookupSubTable; private: inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); return TRACE_RETURN (Context::apply (c, position_lookup)); } }; struct ChainContextPos : ChainContext { friend struct PosLookupSubTable; private: inline bool apply (hb_apply_context_t *c) const { TRACE_APPLY (); return TRACE_RETURN (ChainContext::apply (c, position_lookup)); } }; struct ExtensionPos : Extension { friend struct PosLookupSubTable; private: inline const struct PosLookupSubTable& get_subtable (void) const { unsigned int offset = get_offset (); if (unlikely (!offset)) return Null(PosLookupSubTable); return StructAtOffset<PosLookupSubTable> (this, offset); } inline const Coverage &get_coverage (void) const; inline bool apply (hb_apply_context_t *c) const; inline bool sanitize (hb_sanitize_context_t *c); }; /* * PosLookup */ struct PosLookupSubTable { friend struct PosLookup; enum Type { Single = 1, Pair = 2, Cursive = 3, MarkBase = 4, MarkLig = 5, MarkMark = 6, Context = 7, ChainContext = 8, Extension = 9 }; inline const Coverage &get_coverage (unsigned int lookup_type) const { switch (lookup_type) { case Single: return u.single.get_coverage (); case Pair: return u.pair.get_coverage (); case Cursive: return u.cursive.get_coverage (); case MarkBase: return u.markBase.get_coverage (); case MarkLig: return u.markLig.get_coverage (); case MarkMark: return u.markMark.get_coverage (); case Context: return u.context.get_coverage (); case ChainContext: return u.chainContext.get_coverage (); case Extension: return u.extension.get_coverage (); default: return Null(Coverage); } } inline bool apply (hb_apply_context_t *c, unsigned int lookup_type) const { TRACE_APPLY (); switch (lookup_type) { case Single: return TRACE_RETURN (u.single.apply (c)); case Pair: return TRACE_RETURN (u.pair.apply (c)); case Cursive: return TRACE_RETURN (u.cursive.apply (c)); case MarkBase: return TRACE_RETURN (u.markBase.apply (c)); case MarkLig: return TRACE_RETURN (u.markLig.apply (c)); case MarkMark: return TRACE_RETURN (u.markMark.apply (c)); case Context: return TRACE_RETURN (u.context.apply (c)); case ChainContext: return TRACE_RETURN (u.chainContext.apply (c)); case Extension: return TRACE_RETURN (u.extension.apply (c)); default: return TRACE_RETURN (false); } } inline bool sanitize (hb_sanitize_context_t *c, unsigned int lookup_type) { TRACE_SANITIZE (); if (!u.header.sub_format.sanitize (c)) return TRACE_RETURN (false); switch (lookup_type) { case Single: return TRACE_RETURN (u.single.sanitize (c)); case Pair: return TRACE_RETURN (u.pair.sanitize (c)); case Cursive: return TRACE_RETURN (u.cursive.sanitize (c)); case MarkBase: return TRACE_RETURN (u.markBase.sanitize (c)); case MarkLig: return TRACE_RETURN (u.markLig.sanitize (c)); case MarkMark: return TRACE_RETURN (u.markMark.sanitize (c)); case Context: return TRACE_RETURN (u.context.sanitize (c)); case ChainContext: return TRACE_RETURN (u.chainContext.sanitize (c)); case Extension: return TRACE_RETURN (u.extension.sanitize (c)); default: return TRACE_RETURN (true); } } protected: union { struct { USHORT sub_format; } header; SinglePos single; PairPos pair; CursivePos cursive; MarkBasePos markBase; MarkLigPos markLig; MarkMarkPos markMark; ContextPos context; ChainContextPos chainContext; ExtensionPos extension; } u; public: DEFINE_SIZE_UNION (2, header.sub_format); }; struct PosLookup : Lookup { inline const PosLookupSubTable& get_subtable (unsigned int i) const { return this+CastR<OffsetArrayOf<PosLookupSubTable> > (subTable)[i]; } template <typename set_t> inline void add_coverage (set_t *glyphs) const { const Coverage *last = NULL; unsigned int count = get_subtable_count (); for (unsigned int i = 0; i < count; i++) { const Coverage *c = &get_subtable (i).get_coverage (get_type ()); if (c != last) { c->add_coverage (glyphs); last = c; } } } inline bool apply_once (hb_apply_context_t *c) const { unsigned int lookup_type = get_type (); if (!c->check_glyph_property (&c->buffer->cur(), c->lookup_props, &c->property)) return false; unsigned int count = get_subtable_count (); for (unsigned int i = 0; i < count; i++) if (get_subtable (i).apply (c, lookup_type)) return true; return false; } inline bool apply_string (hb_apply_context_t *c, const hb_set_digest_t *digest) const { bool ret = false; if (unlikely (!c->buffer->len || !c->lookup_mask)) return false; c->set_lookup (*this); c->buffer->idx = 0; while (c->buffer->idx < c->buffer->len) { if ((c->buffer->cur().mask & c->lookup_mask) && digest->may_have (c->buffer->cur().codepoint) && apply_once (c)) ret = true; else c->buffer->idx++; } return ret; } inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (unlikely (!Lookup::sanitize (c))) return TRACE_RETURN (false); OffsetArrayOf<PosLookupSubTable> &list = CastR<OffsetArrayOf<PosLookupSubTable> > (subTable); return TRACE_RETURN (list.sanitize (c, this, get_type ())); } }; typedef OffsetListOf<PosLookup> PosLookupList; /* * GPOS -- The Glyph Positioning Table */ struct GPOS : GSUBGPOS { static const hb_tag_t Tag = HB_OT_TAG_GPOS; inline const PosLookup& get_lookup (unsigned int i) const { return CastR<PosLookup> (GSUBGPOS::get_lookup (i)); } template <typename set_t> inline void add_coverage (set_t *glyphs, unsigned int lookup_index) const { get_lookup (lookup_index).add_coverage (glyphs); } static inline void position_start (hb_font_t *font, hb_buffer_t *buffer); static inline void position_finish (hb_font_t *font, hb_buffer_t *buffer, hb_bool_t zero_width_attahced_marks); inline bool sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (unlikely (!GSUBGPOS::sanitize (c))) return TRACE_RETURN (false); OffsetTo<PosLookupList> &list = CastR<OffsetTo<PosLookupList> > (lookupList); return TRACE_RETURN (list.sanitize (c, this)); } public: DEFINE_SIZE_STATIC (10); }; static void fix_cursive_minor_offset (hb_glyph_position_t *pos, unsigned int i, hb_direction_t direction) { unsigned int j = pos[i].cursive_chain(); if (likely (!j)) return; j += i; pos[i].cursive_chain() = 0; fix_cursive_minor_offset (pos, j, direction); if (HB_DIRECTION_IS_HORIZONTAL (direction)) pos[i].y_offset += pos[j].y_offset; else pos[i].x_offset += pos[j].x_offset; } static void fix_mark_attachment (hb_glyph_position_t *pos, unsigned int i, hb_direction_t direction, hb_bool_t zero_width_attached_marks) { if (likely (!(pos[i].attach_lookback()))) return; unsigned int j = i - pos[i].attach_lookback(); if (zero_width_attached_marks) { pos[i].x_advance = 0; pos[i].y_advance = 0; } pos[i].x_offset += pos[j].x_offset; pos[i].y_offset += pos[j].y_offset; if (HB_DIRECTION_IS_FORWARD (direction)) for (unsigned int k = j; k < i; k++) { pos[i].x_offset -= pos[k].x_advance; pos[i].y_offset -= pos[k].y_advance; } else for (unsigned int k = j + 1; k < i + 1; k++) { pos[i].x_offset += pos[k].x_advance; pos[i].y_offset += pos[k].y_advance; } } void GPOS::position_start (hb_font_t *font HB_UNUSED, hb_buffer_t *buffer) { buffer->clear_positions (); unsigned int count = buffer->len; for (unsigned int i = 0; i < count; i++) buffer->pos[i].attach_lookback() = buffer->pos[i].cursive_chain() = 0; } void GPOS::position_finish (hb_font_t *font HB_UNUSED, hb_buffer_t *buffer, hb_bool_t zero_width_attached_marks) { unsigned int len; hb_glyph_position_t *pos = hb_buffer_get_glyph_positions (buffer, &len); hb_direction_t direction = buffer->props.direction; /* Handle cursive connections */ for (unsigned int i = 0; i < len; i++) fix_cursive_minor_offset (pos, i, direction); /* Handle attachments */ for (unsigned int i = 0; i < len; i++) fix_mark_attachment (pos, i, direction, zero_width_attached_marks); HB_BUFFER_DEALLOCATE_VAR (buffer, syllable); HB_BUFFER_DEALLOCATE_VAR (buffer, lig_props); HB_BUFFER_DEALLOCATE_VAR (buffer, glyph_props); } /* Out-of-class implementation for methods recursing */ inline const Coverage & ExtensionPos::get_coverage (void) const { return get_subtable ().get_coverage (get_type ()); } inline bool ExtensionPos::apply (hb_apply_context_t *c) const { TRACE_APPLY (); return TRACE_RETURN (get_subtable ().apply (c, get_type ())); } inline bool ExtensionPos::sanitize (hb_sanitize_context_t *c) { TRACE_SANITIZE (); if (unlikely (!Extension::sanitize (c))) return TRACE_RETURN (false); unsigned int offset = get_offset (); if (unlikely (!offset)) return TRACE_RETURN (true); return TRACE_RETURN (StructAtOffset<PosLookupSubTable> (this, offset).sanitize (c, get_type ())); } static inline bool position_lookup (hb_apply_context_t *c, unsigned int lookup_index) { const GPOS &gpos = *(hb_ot_layout_from_face (c->face)->gpos); const PosLookup &l = gpos.get_lookup (lookup_index); if (unlikely (c->nesting_level_left == 0)) return false; hb_apply_context_t new_c (*c); new_c.nesting_level_left--; new_c.set_lookup (l); return l.apply_once (&new_c); } #undef attach_lookback #undef cursive_chain } // namespace OT #endif /* HB_OT_LAYOUT_GPOS_TABLE_HH */
leighpauls/k2cro4
third_party/harfbuzz-ng/src/hb-ot-layout-gpos-table.hh
C++
bsd-3-clause
51,795
/* * This file provided by Facebook is for non-commercial testing and evaluation * purposes only. Facebook reserves all rights not expressly granted. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.facebook.samples.comparison.configs.picasso; import android.content.Context; import com.squareup.picasso.LruCache; import com.jakewharton.picasso.OkHttp3Downloader; import com.squareup.picasso.Picasso; import com.facebook.samples.comparison.configs.ConfigConstants; /** * Provides instance of Picasso with common configuration for the sample app */ public class SamplePicassoFactory { private static Picasso sPicasso; public static Picasso getPicasso(Context context) { if (sPicasso == null) { sPicasso = new Picasso.Builder(context) .downloader(new OkHttp3Downloader(context, ConfigConstants.MAX_DISK_CACHE_SIZE)) .memoryCache(new LruCache(ConfigConstants.MAX_MEMORY_CACHE_SIZE)) .build(); } return sPicasso; } }
pandavickey/fresco
samples/comparison/src/main/java/com/facebook/samples/comparison/configs/picasso/SamplePicassoFactory.java
Java
bsd-3-clause
1,412
<style include="settings-shared iron-flex"> h2 { padding-inline-start: var(--cr-section-padding); } cr-policy-pref-indicator { margin-inline-end: var(--settings-controlled-by-spacing); } cr-policy-pref-indicator + cr-icon-button { margin-inline-start: 0; } .bottom-margin { margin-bottom: var(--cr-section-vertical-margin); } .explain-selected { color: var(--cros-text-color-positive); font-weight: initial; margin-top: 4px; } .icon-external { margin-inline-end: 0; } .name-with-error[disabled] { pointer-events: none; } /* Paddings when showing download error */ .name-with-error { padding: 14px 0; } .name-with-error div { color: var(--cros-text-color-alert); margin-top: 8px; } iron-icon[icon='cr:error'] { --iron-icon-fill-color: var(--cros-icon-color-alert); height: var(--cr-icon-size); margin-inline-end: 4px; width: var(--cr-icon-size); } iron-icon[icon='cr20:domain'] { margin-inline-end: 10px; } iron-icon[icon='cr:add'] { margin-inline-end: 8px; } /* Used to maintain vertical alignment for the error icon. */ iron-icon + span { vertical-align: middle; } /* The default implementation of the actionable list item makes the * entire list item row a button such that clicking anywhere will * activate the action of the list item. The input method list behaves * differently in that clicking the list item sets that item as the input * method, and the selected list item should not react to selection after * being selected. Sets the cursor to auto to override the default * implementation which would otherwise make the entire row appear * clickable when it is not. */ .selected[actionable] { cursor: auto; } .subsection { padding-inline-end: var(--cr-section-padding); padding-inline-start: var(--cr-section-indent-padding); } .subsection .list-frame { padding-inline-end: 0; padding-inline-start: 40px; } .subsection > settings-toggle-button, .subsection > cr-link-row, #spellCheckLanguagesListV2 > .cr-row { padding-inline-end: 0; padding-inline-start: 0; } .internal-wrapper, .external-wrapper { display: flex; } #addInputMethod, #addSpellcheckLanguages { --iron-icon-fill-color: var(--cr-link-color); margin-top: 16px; } cr-button[disabled] iron-icon { --iron-icon-fill-color: var(--cros-button-icon-color-primary-disabled); } </style> <div route-path="default"> <template is="dom-if" if="[[shouldShowLanguagePacksNotice_]]"> <localized-link id="languagePacksNotice" class="cr-row first bottom-margin cr-secondary-text" localized-string="$i18n{languagePacksNotice}" on-link-clicked="onLanguagePackNoticeLinkClick_"> </localized-link> </template> <settings-toggle-button class="first" id="showImeMenu" pref="{{prefs.settings.language.ime_menu_activated}}" label="$i18n{showImeMenu}" on-settings-boolean-control-change="onShowImeMenuChange_" deep-link-focus-id$="[[Setting.kShowInputOptionsInShelf]]"> </settings-toggle-button> <div class="hr bottom-margin"> <template is="dom-if" if="[[shouldShowShortcutReminder_( languageSettingsV2Update2Enabled_, shortcutReminderBody_.length)]]"> <keyboard-shortcut-banner header="$i18n{imeShortcutReminderTitle}" body="[[shortcutReminderBody_]]" on-dismiss="onShortcutReminderDismiss_"> </keyboard-shortcut-banner> </template> <h2>$i18n{inputMethodListTitle}</h2> <template is="dom-if" if="[[inputMethodsLimitedByPolicy_( prefs.settings.language.allowed_input_methods.*)]]"> <div class="cr-row continuation" id="inputMethodsManagedbyPolicy"> <iron-icon icon="cr20:domain"></iron-icon> <div class="secondary">$i18n{inputMethodsManagedbyPolicy}</div> </div> </template> <div class="list-frame vertical-list" id="inputMethodsList"> <template is="dom-repeat" items="[[languages.inputMethods.enabled]]"> <div class$="list-item [[getInputMethodItemClass_( item.id, languages.inputMethods.currentId)]]" actionable on-click="onInputMethodClick_" on-keypress="onInputMethodKeyPress_" tabindex$="[[getInputMethodTabIndex_( item.id, languages.inputMethods.currentId)]]" aria-labelledby$="language-[[index]]" role="button"> <div class="start" id="language-[[index]]" aria-hidden="true"> <div class="display-name">[[item.displayName]]</div> <div class="explain-selected" hidden="[[!isCurrentInputMethod_( item.id, languages.inputMethods.currentId)]]"> $i18n{inputMethodEnabled} </div> </div> <template is="dom-if" if="[[hasOptionsPageInSettings_(item.id)]]"> <div class="internal-wrapper" hidden="[[!item.hasOptionsPage]]"> <cr-icon-button class="subpage-arrow" aria-label$="[[getOpenOptionsPageLabel_( item.displayName)]]" on-click="navigateToOptionsPageInSettings_"> </cr-icon-button> </div> </template> <template is="dom-if" if="[[!hasOptionsPageInSettings_(item.id)]]"> <div class="external-wrapper" hidden="[[!item.hasOptionsPage]]"> <cr-icon-button class="icon-external" aria-label$="[[getOpenOptionsPageLabel_( item.displayName)]]" on-click="openExtensionOptionsPage_"> </cr-icon-button> </div> </template> <div class="separator"></div> <cr-icon-button class="icon-clear" disabled$="[[disableRemoveInputMethod_(item, languages.inputMethods.enabled.*)]]" on-click="onRemoveInputMethodClick_" title="[[getRemoveInputMethodTooltip_(item)]]"> </cr-icon-button> </div> </template> <div class="list-item"> <cr-button id="addInputMethod" on-click="onAddInputMethodClick_" deep-link-focus-id$="[[Setting.kAddInputMethod]]"> <iron-icon icon="cr:add"></iron-icon> $i18n{addInputMethodLabel} </cr-button> </div> </div> </div> <template is="dom-if" if="[[onDeviceGrammarCheckEnabled_]]"> <settings-toggle-button id="enableSpellcheckingToggle" class="hr" label="$i18n{spellAndGrammarCheckTitle}" sub-label="$i18n{spellAndGrammarCheckDescription}" pref="{{prefs.browser.enable_spellchecking}}" no-set-pref disabled="[[isEnableSpellcheckingDisabled_( languageSettingsV2Update2Enabled_, spellCheckLanguages_.length)]]" on-settings-boolean-control-change="onSpellcheckToggleChange_" deep-link-focus-id$="[[Setting.kSpellCheck]]" aria-describedby="spellAndGrammarCheckDescription"> </settings-toggle-button> </template> <template is="dom-if" if="[[!onDeviceGrammarCheckEnabled_]]"> <settings-toggle-button id="enableSpellcheckingToggle" class="hr" label="$i18n{spellCheckTitle}" pref="{{prefs.browser.enable_spellchecking}}" no-set-pref disabled="[[isEnableSpellcheckingDisabled_( languageSettingsV2Update2Enabled_, spellCheckLanguages_.length)]]" on-settings-boolean-control-change="onSpellcheckToggleChange_" deep-link-focus-id$="[[Setting.kSpellCheck]]"> </settings-toggle-button> </template> <iron-collapse class="subsection" opened="[[isCollapseOpened_( languageSettingsV2Update2Enabled_, prefs.browser.enable_spellchecking.value)]]"> <template is="dom-if" if="[[!languageSettingsV2Update2Enabled_]]"> <div id="spellCheckLanguagesList"> <div class="single-column"> <div aria-describedby="spellChecklanguagesListDescription"> $i18n{spellCheckLanguagesListTitle} </div> <div class="secondary" id="spellChecklanguagesListDescription" aria-hidden="true"> $i18n{spellCheckLanguagesListDescription} </div> </div> <div class="list-frame vertical-list" role="list"> <template is="dom-repeat" items="[[spellCheckLanguages_]]" mutable-data> <div class="list-item"> <div class="flex name-with-error" aria-hidden="true" on-click="onSpellCheckNameClick_" actionable disabled$="[[isSpellCheckNameClickDisabled_(item, item.*, prefs.browser.enable_spellchecking.*)]]"> [[item.language.displayName]] <div hidden="[[!item.downloadDictionaryFailureCount]]" aria-hidden="true"> <iron-icon icon="cr:error"></iron-icon> <span>$i18n{languagesDictionaryDownloadError}</span> </div> </div> <cr-button on-click="onRetryDictionaryDownloadClick_" hidden="[[!item.downloadDictionaryFailureCount]]" disabled="[[!prefs.browser.enable_spellchecking.value]]" aria-label$="[[getDictionaryDownloadRetryAriaLabel_( item)]]"> $i18n{languagesDictionaryDownloadRetryLabel} </cr-button> <template is="dom-if" if="[[! item.downloadDictionaryFailureCount]]"> <template is="dom-if" if="[[!item.isManaged]]"> <cr-toggle on-change="onSpellCheckLanguageChange_" disabled="[[ !prefs.browser.enable_spellchecking.value]]" checked="[[item.spellCheckEnabled]]" aria-label="[[item.language.displayName]]"> </cr-toggle> </template> <template is="dom-if" if="[[item.isManaged]]"> <cr-policy-pref-indicator pref="[[getIndicatorPrefForManagedSpellcheckLanguage_( item.spellCheckEnabled)]]"> </cr-policy-pref-indicator> <cr-toggle disabled="true" class="managed-toggle" checked="[[item.spellCheckEnabled]]" aria-label="[[item.language.displayName]]"> </cr-toggle> </template> </template> </div> </template> </div> </div> </template> <template is="dom-if" if="[[!onDeviceGrammarCheckEnabled_]]"> <settings-toggle-button id="enhancedSpellCheckToggle" class="[[getEnhancedSpellCheckClass_( languageSettingsV2Update2Enabled_)]]" label="$i18n{spellCheckEnhancedLabel}" pref="{{prefs.spellcheck.use_spelling_service}}" disabled="[[!prefs.browser.enable_spellchecking.value]]"> </settings-toggle-button> </template> <cr-link-row class="hr" label="$i18n{editDictionaryLabel}" on-click="onEditDictionaryClick_" id="editDictionarySubpageTrigger" disabled="[[!prefs.browser.enable_spellchecking.value]]" role-description="$i18n{subpageArrowRoleDescription}"> </cr-link-row> <template is="dom-if" if="[[languageSettingsV2Update2Enabled_]]"> <div id="spellCheckLanguagesListV2"> <div class="cr-row hr"> <div> $i18n{spellCheckLanguagesListTitle} </div> </div> <div class="list-frame vertical-list" role="list"> <template is="dom-repeat" items="[[spellCheckLanguages_]]" mutable-data> <div class="list-item"> <div class="flex name-with-error" aria-hidden="true" disabled$="[[isSpellCheckNameClickDisabled_(item, item.*, prefs.browser.enable_spellchecking.*)]]"> [[item.language.displayName]] <div hidden="[[!item.downloadDictionaryFailureCount]]" aria-hidden="true"> <iron-icon icon="cr:error"></iron-icon> <span>$i18n{languagesDictionaryDownloadError}</span> </div> </div> <cr-button on-click="onRetryDictionaryDownloadClick_" hidden="[[!item.downloadDictionaryFailureCount]]" disabled="[[!prefs.browser.enable_spellchecking.value]]" aria-label$="[[getDictionaryDownloadRetryAriaLabel_( item)]]"> $i18n{languagesDictionaryDownloadRetryLabel} </cr-button> <template is="dom-if" if="[[!item.isManaged]]"> <cr-icon-button class="icon-clear" disabled="[[!prefs.browser.enable_spellchecking.value]]" on-click="onRemoveSpellcheckLanguageClick_" title="[[getRemoveSpellcheckLanguageTooltip_(item)]]"> </cr-icon-button> </template> <template is="dom-if" if="[[item.isManaged]]"> <cr-policy-pref-indicator pref="[[getIndicatorPrefForManagedSpellcheckLanguage_( item.spellCheckEnabled)]]"> </cr-policy-pref-indicator> <cr-icon-button class="icon-clear managed-button" disabled="true" title="[[getRemoveSpellcheckLanguageTooltip_(item)]]"> </cr-icon-button> </template> </div> </template> <div class="list-item"> <cr-button id="addSpellcheckLanguages" on-click="onAddSpellcheckLanguagesClick_" disabled="[[!prefs.browser.enable_spellchecking.value]]"> <iron-icon icon="cr:add"></iron-icon> $i18n{addLanguages} </cr-button> </div> </div> </div> </template> </iron-collapse> </div> <template is="dom-if" if="[[showAddInputMethodsDialog_]]" restamp> <os-settings-add-input-methods-dialog languages="[[languages]]" language-helper="[[languageHelper]]" on-close="onAddInputMethodsDialogClose_"> </os-settings-add-input-methods-dialog> </template> <template is="dom-if" if="[[showAddSpellcheckLanguagesDialog_]]" restamp> <os-settings-add-spellcheck-languages-dialog languages="[[languages]]" language-helper="[[languageHelper]]" prefs="{{prefs}}" on-close="onAddSpellcheckLanguagesDialogClose_"> </os-settings-add-spellcheck-languages-dialog> </template>
chromium/chromium
chrome/browser/resources/settings/chromeos/os_languages_page/input_page.html
HTML
bsd-3-clause
14,808
/* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_ #define WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_ #include <map> #include "webrtc/base/deprecation.h" #include "webrtc/modules/rtp_rtcp/include/receive_statistics.h" #include "webrtc/modules/rtp_rtcp/include/rtp_rtcp_defines.h" #include "webrtc/modules/rtp_rtcp/source/rtp_header_extension.h" #include "webrtc/modules/rtp_rtcp/source/rtp_rtcp_config.h" #include "webrtc/typedefs.h" namespace webrtc { const uint8_t kRtpMarkerBitMask = 0x80; RtpData* NullObjectRtpData(); RtpFeedback* NullObjectRtpFeedback(); ReceiveStatistics* NullObjectReceiveStatistics(); namespace RtpUtility { struct Payload { char name[RTP_PAYLOAD_NAME_SIZE]; bool audio; PayloadUnion typeSpecific; }; bool StringCompare(const char* str1, const char* str2, const uint32_t length); // Round up to the nearest size that is a multiple of 4. size_t Word32Align(size_t size); class RtpHeaderParser { public: RtpHeaderParser(const uint8_t* rtpData, size_t rtpDataLength); ~RtpHeaderParser(); bool RTCP() const; bool ParseRtcp(RTPHeader* header) const; bool Parse(RTPHeader* parsedPacket, RtpHeaderExtensionMap* ptrExtensionMap = nullptr) const; private: void ParseOneByteExtensionHeader(RTPHeader* parsedPacket, const RtpHeaderExtensionMap* ptrExtensionMap, const uint8_t* ptrRTPDataExtensionEnd, const uint8_t* ptr) const; const uint8_t* const _ptrRTPDataBegin; const uint8_t* const _ptrRTPDataEnd; }; } // namespace RtpUtility } // namespace webrtc #endif // WEBRTC_MODULES_RTP_RTCP_SOURCE_RTP_UTILITY_H_
Alkalyne/webrtctrunk
modules/rtp_rtcp/source/rtp_utility.h
C
bsd-3-clause
2,105
// Copyright 2014 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Message definition file, included multiple times, hence no include guard. #include <stdint.h> #include <string> #include "content/common/service_worker/embedded_worker_settings.h" #include "content/public/common/console_message_level.h" #include "content/public/common/web_preferences.h" #include "ipc/ipc_message.h" #include "ipc/ipc_message_macros.h" #include "ipc/ipc_param_traits.h" #include "url/gurl.h" #undef IPC_MESSAGE_EXPORT #define IPC_MESSAGE_EXPORT CONTENT_EXPORT #define IPC_MESSAGE_START EmbeddedWorkerMsgStart IPC_STRUCT_TRAITS_BEGIN(content::EmbeddedWorkerSettings) IPC_STRUCT_TRAITS_MEMBER(v8_cache_options) IPC_STRUCT_TRAITS_MEMBER(data_saver_enabled) IPC_STRUCT_TRAITS_END() // Parameters structure for EmbeddedWorkerMsg_StartWorker. IPC_STRUCT_BEGIN(EmbeddedWorkerMsg_StartWorker_Params) IPC_STRUCT_MEMBER(int, embedded_worker_id) IPC_STRUCT_MEMBER(int64_t, service_worker_version_id) IPC_STRUCT_MEMBER(GURL, scope) IPC_STRUCT_MEMBER(GURL, script_url) IPC_STRUCT_MEMBER(int, worker_devtools_agent_route_id) IPC_STRUCT_MEMBER(bool, pause_after_download) IPC_STRUCT_MEMBER(bool, wait_for_debugger) IPC_STRUCT_MEMBER(bool, is_installed) IPC_STRUCT_MEMBER(content::EmbeddedWorkerSettings, settings) IPC_STRUCT_END() // Parameters structure for EmbeddedWorkerHostMsg_ReportConsoleMessage. // The data members directly correspond to parameters of // WorkerMessagingProxy::reportConsoleMessage() IPC_STRUCT_BEGIN(EmbeddedWorkerHostMsg_ReportConsoleMessage_Params) IPC_STRUCT_MEMBER(int, source_identifier) IPC_STRUCT_MEMBER(int, message_level) IPC_STRUCT_MEMBER(base::string16, message) IPC_STRUCT_MEMBER(int, line_number) IPC_STRUCT_MEMBER(GURL, source_url) IPC_STRUCT_END() // Browser -> Renderer message to create a new embedded worker context. IPC_MESSAGE_CONTROL1(EmbeddedWorkerMsg_StartWorker, EmbeddedWorkerMsg_StartWorker_Params /* params */) // Browser -> Renderer message to resume a worker that has been started // with the pause_after_download option. IPC_MESSAGE_CONTROL1(EmbeddedWorkerMsg_ResumeAfterDownload, int /* embedded_worker_id */) // Browser -> Renderer message to stop (terminate) the embedded worker. IPC_MESSAGE_CONTROL1(EmbeddedWorkerMsg_StopWorker, int /* embedded_worker_id */) // Browser -> Renderer message to add message to the devtools console. IPC_MESSAGE_CONTROL3(EmbeddedWorkerMsg_AddMessageToConsole, int /* embedded_worker_id */, content::ConsoleMessageLevel /* level */, std::string /* message */) // Renderer -> Browser message to indicate that the worker is ready for // inspection. IPC_MESSAGE_CONTROL1(EmbeddedWorkerHostMsg_WorkerReadyForInspection, int /* embedded_worker_id */) // Renderer -> Browser message to indicate that the worker has loaded the // script. IPC_MESSAGE_CONTROL1(EmbeddedWorkerHostMsg_WorkerScriptLoaded, int /* embedded_worker_id */) // Renderer -> Browser message to indicate that the worker thread is started. IPC_MESSAGE_CONTROL3(EmbeddedWorkerHostMsg_WorkerThreadStarted, int /* embedded_worker_id */, int /* thread_id */, int /* provider_id */) // Renderer -> Browser message to indicate that the worker has failed to load // the script. IPC_MESSAGE_CONTROL1(EmbeddedWorkerHostMsg_WorkerScriptLoadFailed, int /* embedded_worker_id */) // Renderer -> Browser message to indicate that the worker has evaluated the // script. IPC_MESSAGE_CONTROL2(EmbeddedWorkerHostMsg_WorkerScriptEvaluated, int /* embedded_worker_id */, bool /* success */) // Renderer -> Browser message to indicate that the worker is started. IPC_MESSAGE_CONTROL1(EmbeddedWorkerHostMsg_WorkerStarted, int /* embedded_worker_id */) // Renderer -> Browser message to indicate that the worker is stopped. IPC_MESSAGE_CONTROL1(EmbeddedWorkerHostMsg_WorkerStopped, int /* embedded_worker_id */) // Renderer -> Browser message to report an exception. IPC_MESSAGE_CONTROL5(EmbeddedWorkerHostMsg_ReportException, int /* embedded_worker_id */, base::string16 /* error_message */, int /* line_number */, int /* column_number */, GURL /* source_url */) // Renderer -> Browser message to report console message. IPC_MESSAGE_CONTROL2( EmbeddedWorkerHostMsg_ReportConsoleMessage, int /* embedded_worker_id */, EmbeddedWorkerHostMsg_ReportConsoleMessage_Params /* params */) // --------------------------------------------------------------------------- // For EmbeddedWorkerContext related messages, which are directly sent from // browser to the worker thread in the child process. We use a new message class // for this for easier cross-thread message dispatching. #undef IPC_MESSAGE_START #define IPC_MESSAGE_START EmbeddedWorkerContextMsgStart // Browser -> Renderer message to send message. IPC_MESSAGE_CONTROL3(EmbeddedWorkerContextMsg_MessageToWorker, int /* thread_id */, int /* embedded_worker_id */, IPC::Message /* message */)
danakj/chromium
content/common/service_worker/embedded_worker_messages.h
C
bsd-3-clause
5,518
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "gpu/config/gpu_info_collector.h" #include <string> #include <vector> #include "base/logging.h" #include "base/memory/scoped_ptr.h" #include "base/strings/string_number_conversions.h" #include "base/strings/string_piece.h" #include "base/strings/string_split.h" #include "base/trace_event/trace_event.h" #include "ui/gl/gl_bindings.h" #include "ui/gl/gl_context.h" #include "ui/gl/gl_implementation.h" #include "ui/gl/gl_surface.h" namespace { scoped_refptr<gfx::GLSurface> InitializeGLSurface() { scoped_refptr<gfx::GLSurface> surface( gfx::GLSurface::CreateOffscreenGLSurface(gfx::Size())); if (!surface.get()) { LOG(ERROR) << "gfx::GLContext::CreateOffscreenGLSurface failed"; return NULL; } return surface; } scoped_refptr<gfx::GLContext> InitializeGLContext(gfx::GLSurface* surface) { scoped_refptr<gfx::GLContext> context( gfx::GLContext::CreateGLContext(NULL, surface, gfx::PreferIntegratedGpu)); if (!context.get()) { LOG(ERROR) << "gfx::GLContext::CreateGLContext failed"; return NULL; } if (!context->MakeCurrent(surface)) { LOG(ERROR) << "gfx::GLContext::MakeCurrent() failed"; return NULL; } return context; } std::string GetGLString(unsigned int pname) { const char* gl_string = reinterpret_cast<const char*>(glGetString(pname)); if (gl_string) return std::string(gl_string); return std::string(); } // Return a version string in the format of "major.minor". std::string GetVersionFromString(const std::string& version_string) { size_t begin = version_string.find_first_of("0123456789"); if (begin != std::string::npos) { size_t end = version_string.find_first_not_of("01234567890.", begin); std::string sub_string; if (end != std::string::npos) sub_string = version_string.substr(begin, end - begin); else sub_string = version_string.substr(begin); std::vector<std::string> pieces; base::SplitString(sub_string, '.', &pieces); if (pieces.size() >= 2) return pieces[0] + "." + pieces[1]; } return std::string(); } } // namespace anonymous namespace gpu { CollectInfoResult CollectGraphicsInfoGL(GPUInfo* gpu_info) { TRACE_EVENT0("startup", "gpu_info_collector::CollectGraphicsInfoGL"); DCHECK_NE(gfx::GetGLImplementation(), gfx::kGLImplementationNone); scoped_refptr<gfx::GLSurface> surface(InitializeGLSurface()); if (!surface.get()) { LOG(ERROR) << "Could not create surface for info collection."; return kCollectInfoFatalFailure; } scoped_refptr<gfx::GLContext> context(InitializeGLContext(surface.get())); if (!context.get()) { LOG(ERROR) << "Could not create context for info collection."; return kCollectInfoFatalFailure; } gpu_info->gl_renderer = GetGLString(GL_RENDERER); gpu_info->gl_vendor = GetGLString(GL_VENDOR); gpu_info->gl_extensions = GetGLString(GL_EXTENSIONS); gpu_info->gl_version = GetGLString(GL_VERSION); std::string glsl_version_string = GetGLString(GL_SHADING_LANGUAGE_VERSION); GLint max_samples = 0; glGetIntegerv(GL_MAX_SAMPLES, &max_samples); gpu_info->max_msaa_samples = base::IntToString(max_samples); gfx::GLWindowSystemBindingInfo window_system_binding_info; if (GetGLWindowSystemBindingInfo(&window_system_binding_info)) { gpu_info->gl_ws_vendor = window_system_binding_info.vendor; gpu_info->gl_ws_version = window_system_binding_info.version; gpu_info->gl_ws_extensions = window_system_binding_info.extensions; gpu_info->direct_rendering = window_system_binding_info.direct_rendering; } bool supports_robustness = gpu_info->gl_extensions.find("GL_EXT_robustness") != std::string::npos || gpu_info->gl_extensions.find("GL_KHR_robustness") != std::string::npos || gpu_info->gl_extensions.find("GL_ARB_robustness") != std::string::npos; if (supports_robustness) { glGetIntegerv(GL_RESET_NOTIFICATION_STRATEGY_ARB, reinterpret_cast<GLint*>(&gpu_info->gl_reset_notification_strategy)); } // TODO(kbr): remove once the destruction of a current context automatically // clears the current context. context->ReleaseCurrent(surface.get()); std::string glsl_version = GetVersionFromString(glsl_version_string); gpu_info->pixel_shader_version = glsl_version; gpu_info->vertex_shader_version = glsl_version; return CollectDriverInfoGL(gpu_info); } void MergeGPUInfoGL(GPUInfo* basic_gpu_info, const GPUInfo& context_gpu_info) { DCHECK(basic_gpu_info); basic_gpu_info->gl_renderer = context_gpu_info.gl_renderer; basic_gpu_info->gl_vendor = context_gpu_info.gl_vendor; basic_gpu_info->gl_version = context_gpu_info.gl_version; basic_gpu_info->gl_extensions = context_gpu_info.gl_extensions; basic_gpu_info->pixel_shader_version = context_gpu_info.pixel_shader_version; basic_gpu_info->vertex_shader_version = context_gpu_info.vertex_shader_version; basic_gpu_info->max_msaa_samples = context_gpu_info.max_msaa_samples; basic_gpu_info->gl_ws_vendor = context_gpu_info.gl_ws_vendor; basic_gpu_info->gl_ws_version = context_gpu_info.gl_ws_version; basic_gpu_info->gl_ws_extensions = context_gpu_info.gl_ws_extensions; basic_gpu_info->gl_reset_notification_strategy = context_gpu_info.gl_reset_notification_strategy; if (!context_gpu_info.driver_vendor.empty()) basic_gpu_info->driver_vendor = context_gpu_info.driver_vendor; if (!context_gpu_info.driver_version.empty()) basic_gpu_info->driver_version = context_gpu_info.driver_version; basic_gpu_info->can_lose_context = context_gpu_info.can_lose_context; basic_gpu_info->sandboxed = context_gpu_info.sandboxed; basic_gpu_info->direct_rendering = context_gpu_info.direct_rendering; basic_gpu_info->context_info_state = context_gpu_info.context_info_state; basic_gpu_info->initialization_time = context_gpu_info.initialization_time; basic_gpu_info->video_decode_accelerator_supported_profiles = context_gpu_info.video_decode_accelerator_supported_profiles; basic_gpu_info->video_encode_accelerator_supported_profiles = context_gpu_info.video_encode_accelerator_supported_profiles; } } // namespace gpu
SaschaMester/delicium
gpu/config/gpu_info_collector.cc
C++
bsd-3-clause
6,421
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. /** * @packageDocumentation * @module extensionmanager-extension */ import { ILabShell, ILayoutRestorer, JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { Dialog, ICommandPalette, showDialog } from '@jupyterlab/apputils'; import { ExtensionView } from '@jupyterlab/extensionmanager'; import { ISettingRegistry } from '@jupyterlab/settingregistry'; import { ITranslator, TranslationBundle } from '@jupyterlab/translation'; import { extensionIcon } from '@jupyterlab/ui-components'; const PLUGIN_ID = '@jupyterlab/extensionmanager-extension:plugin'; /** * IDs of the commands added by this extension. */ namespace CommandIDs { export const showPanel = 'extensionmanager:show-panel'; export const toggle = 'extensionmanager:toggle'; } /** * The extension manager plugin. */ const plugin: JupyterFrontEndPlugin<void> = { id: PLUGIN_ID, autoStart: true, requires: [ISettingRegistry, ITranslator], optional: [ILabShell, ILayoutRestorer, ICommandPalette], activate: async ( app: JupyterFrontEnd, registry: ISettingRegistry, translator: ITranslator, labShell: ILabShell | null, restorer: ILayoutRestorer | null, palette: ICommandPalette | null ) => { const trans = translator.load('jupyterlab'); const settings = await registry.load(plugin.id); let enabled = settings.composite['enabled'] === true; const { commands, serviceManager } = app; let view: ExtensionView | undefined; const createView = () => { const v = new ExtensionView(app, serviceManager, settings, translator); v.id = 'extensionmanager.main-view'; v.title.icon = extensionIcon; v.title.caption = trans.__('Extension Manager'); if (restorer) { restorer.add(v, v.id); } return v; }; if (enabled && labShell) { view = createView(); view.node.setAttribute('role', 'region'); view.node.setAttribute( 'aria-label', trans.__('Extension Manager section') ); labShell.add(view, 'left', { rank: 1000 }); } // If the extension is enabled or disabled, // add or remove it from the left area. Promise.all([app.restored, registry.load(PLUGIN_ID)]) .then(([, settings]) => { settings.changed.connect(async () => { enabled = settings.composite['enabled'] === true; if (enabled && !view?.isAttached) { const accepted = await Private.showWarning(trans); if (!accepted) { void settings.set('enabled', false); return; } view = view || createView(); view.node.setAttribute('role', 'region'); view.node.setAttribute( 'aria-label', trans.__('Extension Manager section') ); if (labShell) { labShell.add(view, 'left', { rank: 1000 }); } } else if (!enabled && view?.isAttached) { app.commands.notifyCommandChanged(CommandIDs.toggle); view.close(); } }); }) .catch(reason => { console.error( `Something went wrong when reading the settings.\n${reason}` ); }); commands.addCommand(CommandIDs.showPanel, { label: trans.__('Extension Manager'), execute: () => { if (view) { labShell?.activateById(view.id); } }, isVisible: () => enabled && labShell !== null }); commands.addCommand(CommandIDs.toggle, { label: trans.__('Enable Extension Manager'), execute: () => { if (registry) { void registry.set(plugin.id, 'enabled', !enabled); } }, isToggled: () => enabled, isEnabled: () => serviceManager.builder.isAvailable }); const category = trans.__('Extension Manager'); const command = CommandIDs.toggle; if (palette) { palette.addItem({ command, category }); } } }; /** * Export the plugin as the default. */ export default plugin; /** * A namespace for module-private functions. */ namespace Private { /** * Show a warning dialog about extension security. * * @returns whether the user accepted the dialog. */ export async function showWarning( trans: TranslationBundle ): Promise<boolean> { return showDialog({ title: trans.__('Enable Extension Manager?'), body: trans.__(`Thanks for trying out JupyterLab's extension manager. The JupyterLab development team is excited to have a robust third-party extension community. However, we cannot vouch for every extension, and some may introduce security risks. Do you want to continue?`), buttons: [ Dialog.cancelButton({ label: trans.__('Disable') }), Dialog.warnButton({ label: trans.__('Enable') }) ] }).then(result => { return result.button.accept; }); } }
jupyter/jupyterlab
packages/extensionmanager-extension/src/index.ts
TypeScript
bsd-3-clause
5,021
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "net/dns/mock_host_resolver.h" #include <string> #include <vector> #include "base/bind.h" #include "base/memory/ref_counted.h" #include "base/message_loop/message_loop.h" #include "base/stl_util.h" #include "base/strings/string_split.h" #include "base/strings/string_util.h" #include "base/threading/platform_thread.h" #include "net/base/ip_endpoint.h" #include "net/base/net_errors.h" #include "net/base/net_util.h" #include "net/base/test_completion_callback.h" #include "net/dns/host_cache.h" #if defined(OS_WIN) #include "net/base/winsock_init.h" #endif namespace net { namespace { // Cache size for the MockCachingHostResolver. const unsigned kMaxCacheEntries = 100; // TTL for the successful resolutions. Failures are not cached. const unsigned kCacheEntryTTLSeconds = 60; } // namespace int ParseAddressList(const std::string& host_list, const std::string& canonical_name, AddressList* addrlist) { *addrlist = AddressList(); std::vector<std::string> addresses; base::SplitString(host_list, ',', &addresses); addrlist->set_canonical_name(canonical_name); for (size_t index = 0; index < addresses.size(); ++index) { IPAddressNumber ip_number; if (!ParseIPLiteralToNumber(addresses[index], &ip_number)) { LOG(WARNING) << "Not a supported IP literal: " << addresses[index]; return ERR_UNEXPECTED; } addrlist->push_back(IPEndPoint(ip_number, 0)); } return OK; } struct MockHostResolverBase::Request { Request(const RequestInfo& req_info, AddressList* addr, const CompletionCallback& cb) : info(req_info), addresses(addr), callback(cb) {} RequestInfo info; AddressList* addresses; CompletionCallback callback; }; MockHostResolverBase::~MockHostResolverBase() { STLDeleteValues(&requests_); } int MockHostResolverBase::Resolve(const RequestInfo& info, RequestPriority priority, AddressList* addresses, const CompletionCallback& callback, RequestHandle* handle, const BoundNetLog& net_log) { DCHECK(CalledOnValidThread()); last_request_priority_ = priority; num_resolve_++; size_t id = next_request_id_++; int rv = ResolveFromIPLiteralOrCache(info, addresses); if (rv != ERR_DNS_CACHE_MISS) { return rv; } if (synchronous_mode_) { return ResolveProc(id, info, addresses); } // Store the request for asynchronous resolution Request* req = new Request(info, addresses, callback); requests_[id] = req; if (handle) *handle = reinterpret_cast<RequestHandle>(id); if (!ondemand_mode_) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&MockHostResolverBase::ResolveNow, AsWeakPtr(), id)); } return ERR_IO_PENDING; } int MockHostResolverBase::ResolveFromCache(const RequestInfo& info, AddressList* addresses, const BoundNetLog& net_log) { num_resolve_from_cache_++; DCHECK(CalledOnValidThread()); next_request_id_++; int rv = ResolveFromIPLiteralOrCache(info, addresses); return rv; } void MockHostResolverBase::CancelRequest(RequestHandle handle) { DCHECK(CalledOnValidThread()); size_t id = reinterpret_cast<size_t>(handle); RequestMap::iterator it = requests_.find(id); if (it != requests_.end()) { scoped_ptr<Request> req(it->second); requests_.erase(it); } else { NOTREACHED() << "CancelRequest must NOT be called after request is " "complete or canceled."; } } HostCache* MockHostResolverBase::GetHostCache() { return cache_.get(); } void MockHostResolverBase::ResolveAllPending() { DCHECK(CalledOnValidThread()); DCHECK(ondemand_mode_); for (RequestMap::iterator i = requests_.begin(); i != requests_.end(); ++i) { base::MessageLoop::current()->PostTask( FROM_HERE, base::Bind(&MockHostResolverBase::ResolveNow, AsWeakPtr(), i->first)); } } // start id from 1 to distinguish from NULL RequestHandle MockHostResolverBase::MockHostResolverBase(bool use_caching) : last_request_priority_(DEFAULT_PRIORITY), synchronous_mode_(false), ondemand_mode_(false), next_request_id_(1), num_resolve_(0), num_resolve_from_cache_(0) { rules_ = CreateCatchAllHostResolverProc(); if (use_caching) { cache_.reset(new HostCache(kMaxCacheEntries)); } } int MockHostResolverBase::ResolveFromIPLiteralOrCache(const RequestInfo& info, AddressList* addresses) { IPAddressNumber ip; if (ParseIPLiteralToNumber(info.hostname(), &ip)) { // This matches the behavior HostResolverImpl. if (info.address_family() != ADDRESS_FAMILY_UNSPECIFIED && info.address_family() != GetAddressFamily(ip)) { return ERR_NAME_NOT_RESOLVED; } *addresses = AddressList::CreateFromIPAddress(ip, info.port()); if (info.host_resolver_flags() & HOST_RESOLVER_CANONNAME) addresses->SetDefaultCanonicalName(); return OK; } int rv = ERR_DNS_CACHE_MISS; if (cache_.get() && info.allow_cached_response()) { HostCache::Key key(info.hostname(), info.address_family(), info.host_resolver_flags()); const HostCache::Entry* entry = cache_->Lookup(key, base::TimeTicks::Now()); if (entry) { rv = entry->error; if (rv == OK) *addresses = AddressList::CopyWithPort(entry->addrlist, info.port()); } } return rv; } int MockHostResolverBase::ResolveProc(size_t id, const RequestInfo& info, AddressList* addresses) { AddressList addr; int rv = rules_->Resolve(info.hostname(), info.address_family(), info.host_resolver_flags(), &addr, NULL); if (cache_.get()) { HostCache::Key key(info.hostname(), info.address_family(), info.host_resolver_flags()); // Storing a failure with TTL 0 so that it overwrites previous value. base::TimeDelta ttl; if (rv == OK) ttl = base::TimeDelta::FromSeconds(kCacheEntryTTLSeconds); cache_->Set(key, HostCache::Entry(rv, addr), base::TimeTicks::Now(), ttl); } if (rv == OK) *addresses = AddressList::CopyWithPort(addr, info.port()); return rv; } void MockHostResolverBase::ResolveNow(size_t id) { RequestMap::iterator it = requests_.find(id); if (it == requests_.end()) return; // was canceled scoped_ptr<Request> req(it->second); requests_.erase(it); int rv = ResolveProc(id, req->info, req->addresses); if (!req->callback.is_null()) req->callback.Run(rv); } //----------------------------------------------------------------------------- struct RuleBasedHostResolverProc::Rule { enum ResolverType { kResolverTypeFail, kResolverTypeSystem, kResolverTypeIPLiteral, }; ResolverType resolver_type; std::string host_pattern; AddressFamily address_family; HostResolverFlags host_resolver_flags; std::string replacement; std::string canonical_name; int latency_ms; // In milliseconds. Rule(ResolverType resolver_type, const std::string& host_pattern, AddressFamily address_family, HostResolverFlags host_resolver_flags, const std::string& replacement, const std::string& canonical_name, int latency_ms) : resolver_type(resolver_type), host_pattern(host_pattern), address_family(address_family), host_resolver_flags(host_resolver_flags), replacement(replacement), canonical_name(canonical_name), latency_ms(latency_ms) {} }; RuleBasedHostResolverProc::RuleBasedHostResolverProc(HostResolverProc* previous) : HostResolverProc(previous) { } void RuleBasedHostResolverProc::AddRule(const std::string& host_pattern, const std::string& replacement) { AddRuleForAddressFamily(host_pattern, ADDRESS_FAMILY_UNSPECIFIED, replacement); } void RuleBasedHostResolverProc::AddRuleForAddressFamily( const std::string& host_pattern, AddressFamily address_family, const std::string& replacement) { DCHECK(!replacement.empty()); HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; Rule rule(Rule::kResolverTypeSystem, host_pattern, address_family, flags, replacement, std::string(), 0); rules_.push_back(rule); } void RuleBasedHostResolverProc::AddIPLiteralRule( const std::string& host_pattern, const std::string& ip_literal, const std::string& canonical_name) { // Literals are always resolved to themselves by HostResolverImpl, // consequently we do not support remapping them. IPAddressNumber ip_number; DCHECK(!ParseIPLiteralToNumber(host_pattern, &ip_number)); HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; if (!canonical_name.empty()) flags |= HOST_RESOLVER_CANONNAME; Rule rule(Rule::kResolverTypeIPLiteral, host_pattern, ADDRESS_FAMILY_UNSPECIFIED, flags, ip_literal, canonical_name, 0); rules_.push_back(rule); } void RuleBasedHostResolverProc::AddRuleWithLatency( const std::string& host_pattern, const std::string& replacement, int latency_ms) { DCHECK(!replacement.empty()); HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; Rule rule(Rule::kResolverTypeSystem, host_pattern, ADDRESS_FAMILY_UNSPECIFIED, flags, replacement, std::string(), latency_ms); rules_.push_back(rule); } void RuleBasedHostResolverProc::AllowDirectLookup( const std::string& host_pattern) { HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; Rule rule(Rule::kResolverTypeSystem, host_pattern, ADDRESS_FAMILY_UNSPECIFIED, flags, std::string(), std::string(), 0); rules_.push_back(rule); } void RuleBasedHostResolverProc::AddSimulatedFailure( const std::string& host_pattern) { HostResolverFlags flags = HOST_RESOLVER_LOOPBACK_ONLY | HOST_RESOLVER_DEFAULT_FAMILY_SET_DUE_TO_NO_IPV6; Rule rule(Rule::kResolverTypeFail, host_pattern, ADDRESS_FAMILY_UNSPECIFIED, flags, std::string(), std::string(), 0); rules_.push_back(rule); } void RuleBasedHostResolverProc::ClearRules() { rules_.clear(); } int RuleBasedHostResolverProc::Resolve(const std::string& host, AddressFamily address_family, HostResolverFlags host_resolver_flags, AddressList* addrlist, int* os_error) { RuleList::iterator r; for (r = rules_.begin(); r != rules_.end(); ++r) { bool matches_address_family = r->address_family == ADDRESS_FAMILY_UNSPECIFIED || r->address_family == address_family; // Ignore HOST_RESOLVER_SYSTEM_ONLY, since it should have no impact on // whether a rule matches. HostResolverFlags flags = host_resolver_flags & ~HOST_RESOLVER_SYSTEM_ONLY; // Flags match if all of the bitflags in host_resolver_flags are enabled // in the rule's host_resolver_flags. However, the rule may have additional // flags specified, in which case the flags should still be considered a // match. bool matches_flags = (r->host_resolver_flags & flags) == flags; if (matches_flags && matches_address_family && MatchPattern(host, r->host_pattern)) { if (r->latency_ms != 0) { base::PlatformThread::Sleep( base::TimeDelta::FromMilliseconds(r->latency_ms)); } // Remap to a new host. const std::string& effective_host = r->replacement.empty() ? host : r->replacement; // Apply the resolving function to the remapped hostname. switch (r->resolver_type) { case Rule::kResolverTypeFail: return ERR_NAME_NOT_RESOLVED; case Rule::kResolverTypeSystem: #if defined(OS_WIN) EnsureWinsockInit(); #endif return SystemHostResolverCall(effective_host, address_family, host_resolver_flags, addrlist, os_error); case Rule::kResolverTypeIPLiteral: return ParseAddressList(effective_host, r->canonical_name, addrlist); default: NOTREACHED(); return ERR_UNEXPECTED; } } } return ResolveUsingPrevious(host, address_family, host_resolver_flags, addrlist, os_error); } RuleBasedHostResolverProc::~RuleBasedHostResolverProc() { } RuleBasedHostResolverProc* CreateCatchAllHostResolverProc() { RuleBasedHostResolverProc* catchall = new RuleBasedHostResolverProc(NULL); catchall->AddIPLiteralRule("*", "127.0.0.1", "localhost"); // Next add a rules-based layer the use controls. return new RuleBasedHostResolverProc(catchall); } //----------------------------------------------------------------------------- int HangingHostResolver::Resolve(const RequestInfo& info, RequestPriority priority, AddressList* addresses, const CompletionCallback& callback, RequestHandle* out_req, const BoundNetLog& net_log) { return ERR_IO_PENDING; } int HangingHostResolver::ResolveFromCache(const RequestInfo& info, AddressList* addresses, const BoundNetLog& net_log) { return ERR_DNS_CACHE_MISS; } //----------------------------------------------------------------------------- ScopedDefaultHostResolverProc::ScopedDefaultHostResolverProc() {} ScopedDefaultHostResolverProc::ScopedDefaultHostResolverProc( HostResolverProc* proc) { Init(proc); } ScopedDefaultHostResolverProc::~ScopedDefaultHostResolverProc() { HostResolverProc* old_proc = HostResolverProc::SetDefault(previous_proc_.get()); // The lifetimes of multiple instances must be nested. CHECK_EQ(old_proc, current_proc_.get()); } void ScopedDefaultHostResolverProc::Init(HostResolverProc* proc) { current_proc_ = proc; previous_proc_ = HostResolverProc::SetDefault(current_proc_.get()); current_proc_->SetLastProc(previous_proc_.get()); } } // namespace net
guorendong/iridium-browser-ubuntu
net/dns/mock_host_resolver.cc
C++
bsd-3-clause
15,308
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.5.0_22) on Sun Oct 21 11:03:15 GMT+01:00 2012 --> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <TITLE> Uses of Class org.apache.http.client.fluent.Form (HttpComponents Client 4.2.2 API) </TITLE> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { parent.document.title="Uses of Class org.apache.http.client.fluent.Form (HttpComponents Client 4.2.2 API)"; } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/http/client/fluent/class-use/Form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.http.client.fluent.Form</B></H2> </CENTER> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Packages that use <A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent">Form</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD><A HREF="#org.apache.http.client.fluent"><B>org.apache.http.client.fluent</B></A></TD> <TD>&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <A NAME="org.apache.http.client.fluent"><!-- --></A> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor"> <TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2"> Uses of <A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent">Form</A> in <A HREF="../../../../../../org/apache/http/client/fluent/package-summary.html">org.apache.http.client.fluent</A></FONT></TH> </TR> </TABLE> &nbsp; <P> <TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY=""> <TR BGCOLOR="#CCCCFF" CLASS="TableSubHeadingColor"> <TH ALIGN="left" COLSPAN="2">Methods in <A HREF="../../../../../../org/apache/http/client/fluent/package-summary.html">org.apache.http.client.fluent</A> that return <A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent">Form</A></FONT></TH> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>&nbsp;<A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent">Form</A></CODE></FONT></TD> <TD><CODE><B>Form.</B><B><A HREF="../../../../../../org/apache/http/client/fluent/Form.html#add(java.lang.String, java.lang.String)">add</A></B>(<A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A>&nbsp;name, <A HREF="http://download.oracle.com/javase/1.5.0/docs/api/java/lang/String.html" title="class or interface in java.lang">String</A>&nbsp;value)</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> <TR BGCOLOR="white" CLASS="TableRowColor"> <TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1"> <CODE>static&nbsp;<A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent">Form</A></CODE></FONT></TD> <TD><CODE><B>Form.</B><B><A HREF="../../../../../../org/apache/http/client/fluent/Form.html#form()">form</A></B>()</CODE> <BR> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</TD> </TR> </TABLE> &nbsp; <P> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/http/client/fluent/Form.html" title="class in org.apache.http.client.fluent"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html?org/apache/http/client/fluent/class-use/Form.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="Form.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> Copyright &#169; 1999-2012 <a href="http://www.apache.org/">The Apache Software Foundation</a>. All Rights Reserved. </BODY> </HTML>
espadrine/opera
chromium/src/third_party/httpcomponents-client/binary-distribution/javadoc/org/apache/http/client/fluent/class-use/Form.html
HTML
bsd-3-clause
8,738
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/autofill/core/browser/payments/autofill_offer_manager.h" #include "base/bind.h" #include "base/containers/contains.h" #include "base/ranges/ranges.h" #include "components/autofill/core/browser/autofill_client.h" #include "components/autofill/core/browser/data_model/autofill_offer_data.h" #include "components/autofill/core/browser/data_model/credit_card.h" #include "components/autofill/core/browser/payments/payments_client.h" #include "components/autofill/core/browser/personal_data_manager.h" #include "components/autofill/core/common/autofill_payments_features.h" #include "components/strings/grit/components_strings.h" #include "ui/base/l10n/l10n_util.h" namespace autofill { AutofillOfferManager::AutofillOfferManager( PersonalDataManager* personal_data, CouponServiceDelegate* coupon_service_delegate) : personal_data_(personal_data), coupon_service_delegate_(coupon_service_delegate) { personal_data_->AddObserver(this); UpdateEligibleMerchantDomains(); } AutofillOfferManager::~AutofillOfferManager() { personal_data_->RemoveObserver(this); } void AutofillOfferManager::OnPersonalDataChanged() { UpdateEligibleMerchantDomains(); } void AutofillOfferManager::OnDidNavigateFrame(AutofillClient* client) { notification_handler_.UpdateOfferNotificationVisibility(client); } void AutofillOfferManager::UpdateSuggestionsWithOffers( const GURL& last_committed_url, std::vector<Suggestion>& suggestions) { GURL last_committed_url_origin = last_committed_url.DeprecatedGetOriginAsURL(); if (eligible_merchant_domains_.count(last_committed_url_origin) == 0) { return; } AutofillOfferManager::OffersMap eligible_offers_map = CreateCardLinkedOffersMap(last_committed_url_origin); // Update |offer_label| for each suggestion. for (auto& suggestion : suggestions) { std::string id = suggestion.backend_id; if (eligible_offers_map.count(id)) { suggestion.offer_label = l10n_util::GetStringUTF16(IDS_AUTOFILL_OFFERS_CASHBACK); } } // Sort the suggestions such that suggestions with offers are shown at the // top. if (base::FeatureList::IsEnabled( features::kAutofillSortSuggestionsBasedOnOfferPresence)) { std::sort(suggestions.begin(), suggestions.end(), [](const Suggestion& a, const Suggestion& b) { if (!a.offer_label.empty() && b.offer_label.empty()) { return true; } return false; }); } } bool AutofillOfferManager::IsUrlEligible(const GURL& last_committed_url) { if (coupon_service_delegate_ && coupon_service_delegate_->IsUrlEligible(last_committed_url)) { return true; } return base::Contains(eligible_merchant_domains_, last_committed_url.DeprecatedGetOriginAsURL()); } AutofillOfferData* AutofillOfferManager::GetOfferForUrl( const GURL& last_committed_url) { if (coupon_service_delegate_) { for (AutofillOfferData* offer : coupon_service_delegate_->GetFreeListingCouponsForUrl( last_committed_url)) { if (offer->IsActiveAndEligibleForOrigin( last_committed_url.DeprecatedGetOriginAsURL())) { return offer; } } } for (AutofillOfferData* offer : personal_data_->GetAutofillOffers()) { if (offer->IsActiveAndEligibleForOrigin( last_committed_url.DeprecatedGetOriginAsURL())) { return offer; } } return nullptr; } void AutofillOfferManager::UpdateEligibleMerchantDomains() { eligible_merchant_domains_.clear(); std::vector<AutofillOfferData*> offers = personal_data_->GetAutofillOffers(); for (auto* offer : offers) { eligible_merchant_domains_.insert(offer->merchant_origins.begin(), offer->merchant_origins.end()); } } AutofillOfferManager::OffersMap AutofillOfferManager::CreateCardLinkedOffersMap( const GURL& last_committed_url_origin) const { AutofillOfferManager::OffersMap offers_map; std::vector<AutofillOfferData*> offers = personal_data_->GetAutofillOffers(); std::vector<CreditCard*> cards = personal_data_->GetCreditCards(); for (auto* offer : offers) { // Ensure the offer is valid. if (!offer->IsActiveAndEligibleForOrigin(last_committed_url_origin)) { continue; } // Ensure the offer is a card-linked offer. if (!offer->IsCardLinkedOffer()) { continue; } // Find card with corresponding instrument ID and add its guid to the map. for (const auto* card : cards) { // If card has an offer, add the backend ID to the map. There is currently // a one-to-one mapping between cards and offer data, however, this may // change in the future. if (std::count(offer->eligible_instrument_id.begin(), offer->eligible_instrument_id.end(), card->instrument_id())) { offers_map[card->guid()] = offer; } } } return offers_map; } } // namespace autofill
chromium/chromium
components/autofill/core/browser/payments/autofill_offer_manager.cc
C++
bsd-3-clause
5,212
/* * Copyright 2014 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "include/private/SkOnce.h" #include "include/utils/SkEventTracer.h" #include <atomic> #include <stdlib.h> class SkDefaultEventTracer : public SkEventTracer { SkEventTracer::Handle addTraceEvent(char phase, const uint8_t* categoryEnabledFlag, const char* name, uint64_t id, int numArgs, const char** argNames, const uint8_t* argTypes, const uint64_t* argValues, uint8_t flags) override { return 0; } void updateTraceEventDuration(const uint8_t* categoryEnabledFlag, const char* name, SkEventTracer::Handle handle) override {} const uint8_t* getCategoryGroupEnabled(const char* name) override { static uint8_t no = 0; return &no; } const char* getCategoryGroupName( const uint8_t* categoryEnabledFlag) override { static const char* stub = "stub"; return stub; } }; // We prefer gUserTracer if it's been set, otherwise we fall back on a default tracer; static std::atomic<SkEventTracer*> gUserTracer{nullptr}; bool SkEventTracer::SetInstance(SkEventTracer* tracer) { SkEventTracer* expected = nullptr; if (!gUserTracer.compare_exchange_strong(expected, tracer)) { delete tracer; return false; } atexit([]() { delete gUserTracer.load(); }); return true; } SkEventTracer* SkEventTracer::GetInstance() { if (auto tracer = gUserTracer.load(std::memory_order_acquire)) { return tracer; } static SkOnce once; static SkDefaultEventTracer* defaultTracer; once([] { defaultTracer = new SkDefaultEventTracer; }); return defaultTracer; }
youtube/cobalt
third_party/skia_next/third_party/skia/src/utils/SkEventTracer.cpp
C++
bsd-3-clause
1,973
// Copyright 2022 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/attribution_reporting/attribution_cookie_checker_impl.h" #include <memory> #include "base/bind.h" #include "base/run_loop.h" #include "base/test/bind.h" #include "base/test/scoped_feature_list.h" #include "base/unguessable_token.h" #include "content/browser/storage_partition_impl.h" #include "content/public/browser/storage_partition.h" #include "content/public/test/browser_task_environment.h" #include "content/public/test/test_browser_context.h" #include "net/base/features.h" #include "net/cookies/canonical_cookie.h" #include "net/cookies/cookie_options.h" #include "net/cookies/cookie_util.h" #include "services/network/public/mojom/cookie_manager.mojom.h" #include "testing/gtest/include/gtest/gtest.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "url/gurl.h" #include "url/origin.h" namespace content { namespace { // It is not possible to create a `SameSite: None` cookie insecurely, so // we can't explicitly test what happens when `secure = false` but the other // parameters are correct. struct AttributionCookieParams { const char* name; const char* domain; bool httponly; net::CookieSameSite same_site; absl::optional<net::CookiePartitionKey> partition_key; }; class AttributionCookieCheckerImplTest : public testing::Test { public: void SetCookie(const AttributionCookieParams& params) { auto cookie = net::CanonicalCookie::CreateUnsafeCookieForTesting( /*name=*/params.name, /*value=*/"1", /*domain=*/params.domain, /*path=*/"/", /*creation=*/base::Time(), /*expiration=*/base::Time(), /*last_access=*/base::Time(), /*secure=*/true, /*httponly=*/params.httponly, /*same_site=*/params.same_site, /*priority=*/net::COOKIE_PRIORITY_DEFAULT, /*same_party=*/false, /*partition_key=*/params.partition_key); CHECK(cookie); net::CookieInclusionStatus result; base::RunLoop loop; browser_context_.GetDefaultStoragePartition() ->GetCookieManagerForBrowserProcess() ->SetCanonicalCookie( *cookie, net::cookie_util::SimulatedCookieSource(*cookie, "https"), net::CookieOptions::MakeAllInclusive(), base::BindLambdaForTesting([&](net::CookieAccessResult r) { result = r.status; loop.Quit(); })); loop.Run(); ASSERT_TRUE(result.IsInclude()) << result.GetDebugString(); } bool IsDebugCookieSet() { bool result; base::RunLoop loop; cookie_checker_.IsDebugCookieSet( url::Origin::Create(GURL("https://r.test")), base::BindLambdaForTesting([&](bool r) { result = r; loop.Quit(); })); loop.Run(); return result; } private: base::test::ScopedFeatureList scoped_feature_list_{ net::features::kPartitionedCookies}; BrowserTaskEnvironment task_environment_; TestBrowserContext browser_context_; AttributionCookieCheckerImpl cookie_checker_{ static_cast<StoragePartitionImpl*>( browser_context_.GetDefaultStoragePartition())}; }; TEST_F(AttributionCookieCheckerImplTest, NoCookie_NotSet) { EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, ValidCookie_Set) { SetCookie({ .name = "ar_debug", .domain = "r.test", .httponly = true, .same_site = net::CookieSameSite::NO_RESTRICTION, }); EXPECT_TRUE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, WrongCookieName_NotSet) { SetCookie({ .name = "AR_DEBUG", .domain = "r.test", .httponly = true, .same_site = net::CookieSameSite::NO_RESTRICTION, }); EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, WrongDomain_NotSet) { SetCookie({ .name = "ar_debug", .domain = "r2.test", .httponly = true, .same_site = net::CookieSameSite::NO_RESTRICTION, }); EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, NotHttpOnly_NotSet) { SetCookie({ .name = "ar_debug", .domain = "r.test", .httponly = false, .same_site = net::CookieSameSite::NO_RESTRICTION, }); EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, SameSiteLaxMode_NotSet) { SetCookie({ .name = "ar_debug", .domain = "r.test", .httponly = false, .same_site = net::CookieSameSite::LAX_MODE, }); EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, SameSiteStrictMode_NotSet) { SetCookie({ .name = "ar_debug", .domain = "r.test", .httponly = false, .same_site = net::CookieSameSite::STRICT_MODE, }); EXPECT_FALSE(IsDebugCookieSet()); } TEST_F(AttributionCookieCheckerImplTest, Partitioned_NotSet) { SetCookie({ .name = "ar_debug", .domain = "r.test", .httponly = false, .same_site = net::CookieSameSite::NO_RESTRICTION, // Mojo deserialization crashes without the unguessable token here. .partition_key = net::CookiePartitionKey::FromURLForTesting( GURL("https://r2.test"), base::UnguessableToken::Create()), }); EXPECT_FALSE(IsDebugCookieSet()); } } // namespace } // namespace content
chromium/chromium
content/browser/attribution_reporting/attribution_cookie_checker_impl_unittest.cc
C++
bsd-3-clause
5,429
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/views/animation/slide_out_controller.h" #include <algorithm> #include "base/bind.h" #include "base/threading/thread_task_runner_handle.h" #include "ui/compositor/layer.h" #include "ui/compositor/scoped_layer_animation_settings.h" #include "ui/gfx/geometry/transform.h" #include "ui/views/animation/animation_builder.h" #include "ui/views/animation/slide_out_controller_delegate.h" namespace views { namespace { constexpr base::TimeDelta kSwipeRestoreDuration = base::Milliseconds(150); constexpr int kSwipeOutTotalDurationMs = 150; gfx::Tween::Type kSwipeTweenType = gfx::Tween::EASE_IN; // When we have a swipe control, we will close the target if it is slid more // than this amount plus the width of the swipe control. constexpr int kSwipeCloseMargin = 64; } // anonymous namespace SlideOutController::SlideOutController(ui::EventTarget* target, SlideOutControllerDelegate* delegate) : target_handling_(target, this), delegate_(delegate) {} SlideOutController::~SlideOutController() = default; void SlideOutController::CaptureControlOpenState() { if (!has_swipe_control_) return; if ((mode_ == SlideMode::kFull || mode_ == SlideMode::kPartial) && fabs(gesture_amount_) >= swipe_control_width_) { control_open_state_ = gesture_amount_ < 0 ? SwipeControlOpenState::kOpenOnRight : SwipeControlOpenState::kOpenOnLeft; } else { control_open_state_ = SwipeControlOpenState::kClosed; } } void SlideOutController::OnGestureEvent(ui::GestureEvent* event) { ui::Layer* layer = delegate_->GetSlideOutLayer(); int width = layer->bounds().width(); float scroll_amount_for_closing_notification = has_swipe_control_ ? swipe_control_width_ + kSwipeCloseMargin : width * 0.5; if (event->type() == ui::ET_SCROLL_FLING_START) { // The threshold for the fling velocity is computed empirically. // The unit is in pixels/second. const float kFlingThresholdForClose = 800.f; if (mode_ == SlideMode::kFull && fabsf(event->details().velocity_x()) > kFlingThresholdForClose) { SlideOutAndClose(event->details().velocity_x()); event->StopPropagation(); return; } CaptureControlOpenState(); RestoreVisualState(); return; } if (!event->IsScrollGestureEvent()) return; if (event->type() == ui::ET_GESTURE_SCROLL_BEGIN) { switch (control_open_state_) { case SwipeControlOpenState::kClosed: gesture_amount_ = 0.f; break; case SwipeControlOpenState::kOpenOnRight: gesture_amount_ = -swipe_control_width_; break; case SwipeControlOpenState::kOpenOnLeft: gesture_amount_ = swipe_control_width_; break; default: NOTREACHED(); } delegate_->OnSlideStarted(); } else if (event->type() == ui::ET_GESTURE_SCROLL_UPDATE) { // The scroll-update events include the incremental scroll amount. gesture_amount_ += event->details().scroll_x(); float scroll_amount; float opacity; switch (mode_) { case SlideMode::kFull: scroll_amount = gesture_amount_; opacity = 1.f - std::min(fabsf(scroll_amount) / width, 1.f); break; case SlideMode::kNone: scroll_amount = 0.f; opacity = 1.f; break; case SlideMode::kPartial: if (gesture_amount_ >= 0) { scroll_amount = std::min(0.5f * gesture_amount_, scroll_amount_for_closing_notification); } else { scroll_amount = std::max(0.5f * gesture_amount_, -1.f * scroll_amount_for_closing_notification); } opacity = 1.f; break; } SetOpacityIfNecessary(opacity); gfx::Transform transform; transform.Translate(scroll_amount, 0.0); layer->SetTransform(transform); delegate_->OnSlideChanged(true); } else if (event->type() == ui::ET_GESTURE_SCROLL_END) { float scrolled_ratio = fabsf(gesture_amount_) / width; if (mode_ == SlideMode::kFull && scrolled_ratio >= scroll_amount_for_closing_notification / width) { SlideOutAndClose(gesture_amount_); event->StopPropagation(); return; } CaptureControlOpenState(); RestoreVisualState(); } event->SetHandled(); } void SlideOutController::RestoreVisualState() { // Restore the layer state. gfx::Transform transform; switch (control_open_state_) { case SwipeControlOpenState::kClosed: gesture_amount_ = 0.f; break; case SwipeControlOpenState::kOpenOnRight: gesture_amount_ = -swipe_control_width_; transform.Translate(-swipe_control_width_, 0); break; case SwipeControlOpenState::kOpenOnLeft: gesture_amount_ = swipe_control_width_; transform.Translate(swipe_control_width_, 0); break; } SetOpacityIfNecessary(1.f); SetTransformWithAnimationIfNecessary(transform, kSwipeRestoreDuration); } void SlideOutController::SlideOutAndClose(int direction) { ui::Layer* layer = delegate_->GetSlideOutLayer(); gfx::Transform transform; int width = layer->bounds().width(); transform.Translate(direction < 0 ? -width : width, 0.0); int swipe_out_duration = kSwipeOutTotalDurationMs * opacity_; SetOpacityIfNecessary(0.f); SetTransformWithAnimationIfNecessary(transform, base::Milliseconds(swipe_out_duration)); } void SlideOutController::SetOpacityIfNecessary(float opacity) { if (update_opacity_) delegate_->GetSlideOutLayer()->SetOpacity(opacity); opacity_ = opacity; } void SlideOutController::SetTransformWithAnimationIfNecessary( const gfx::Transform& transform, base::TimeDelta animation_duration) { ui::Layer* layer = delegate_->GetSlideOutLayer(); if (layer->transform() != transform) { // Notify slide changed with inprogress=true, since the element will slide // with animation. OnSlideChanged(false) will be called after animation. delegate_->OnSlideChanged(true); // An animation starts. OnAnimationsCompleted will be called just // after the animation finishes. AnimationBuilder() .OnEnded(base::BindOnce(&SlideOutController::OnAnimationsCompleted, weak_ptr_factory_.GetWeakPtr())) .Once() .SetDuration(animation_duration) .SetTransform(layer, transform, kSwipeTweenType); } else { // Notify slide changed after the animation finishes. // The argument in_progress is true if the target view is back at the // origin or has been gone. False if the target is visible but not at // the origin. False if the target is visible but not at // the origin. const bool in_progress = !layer->transform().IsIdentity(); delegate_->OnSlideChanged(in_progress); } } void SlideOutController::OnAnimationsCompleted() { // Here the situation is either of: // 1) Notification is slided out and is about to be removed // => |in_progress| is false, calling OnSlideOut // 2) Notification is at the origin => |in_progress| is false // 3) Notification is snapped to the swipe control => |in_progress| is true const bool is_completely_slid_out = (opacity_ == 0); const bool in_progress = !delegate_->GetSlideOutLayer()->transform().IsIdentity() && !is_completely_slid_out; delegate_->OnSlideChanged(in_progress); if (!is_completely_slid_out) return; // Call SlideOutControllerDelegate::OnSlideOut() if this animation came from // SlideOutAndClose(). // OnImplicitAnimationsCompleted is called from BeginMainFrame, so we should // delay operation that might result in deletion of LayerTreeHost. // https://crbug.com/895883 base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&SlideOutController::OnSlideOut, weak_ptr_factory_.GetWeakPtr())); } void SlideOutController::OnSlideOut() { delegate_->OnSlideOut(); } void SlideOutController::SetSwipeControlWidth(int swipe_control_width) { swipe_control_width_ = swipe_control_width; has_swipe_control_ = (swipe_control_width != 0); } void SlideOutController::CloseSwipeControl() { if (!has_swipe_control_) return; gesture_amount_ = 0; CaptureControlOpenState(); RestoreVisualState(); } } // namespace views
chromium/chromium
ui/views/animation/slide_out_controller.cc
C++
bsd-3-clause
8,586
// Copyright 2019 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "ui/ozone/platform/wayland/test/mock_surface.h" #include "base/notreached.h" #include "ui/ozone/platform/wayland/test/test_augmented_subsurface.h" namespace wl { namespace { void SetPosition(wl_client* client, wl_resource* resource, int32_t x, int32_t y) { GetUserDataAs<TestSubSurface>(resource)->SetPosition(x, y); } void PlaceAbove(wl_client* client, wl_resource* resource, wl_resource* reference_resource) { NOTIMPLEMENTED_LOG_ONCE(); } void PlaceBelow(wl_client* client, wl_resource* resource, wl_resource* sibling_resource) { NOTIMPLEMENTED_LOG_ONCE(); } void SetSync(wl_client* client, wl_resource* resource) { GetUserDataAs<TestSubSurface>(resource)->set_sync(true); } void SetDesync(wl_client* client, wl_resource* resource) { GetUserDataAs<TestSubSurface>(resource)->set_sync(false); } } // namespace const struct wl_subsurface_interface kTestSubSurfaceImpl = { DestroyResource, SetPosition, PlaceAbove, PlaceBelow, SetSync, SetDesync, }; TestSubSurface::TestSubSurface(wl_resource* resource, wl_resource* surface, wl_resource* parent_resource) : ServerObject(resource), surface_(surface), parent_resource_(parent_resource) { DCHECK(surface_); } TestSubSurface::~TestSubSurface() { auto* mock_surface = GetUserDataAs<MockSurface>(surface_); if (mock_surface) mock_surface->set_sub_surface(nullptr); if (augmented_subsurface_ && augmented_subsurface_->resource()) wl_resource_destroy(augmented_subsurface_->resource()); } void TestSubSurface::SetPosition(float x, float y) { position_ = gfx::PointF(x, y); } } // namespace wl
chromium/chromium
ui/ozone/platform/wayland/test/test_subsurface.cc
C++
bsd-3-clause
1,951
#!/usr/bin/env python3 """ cythonize Cythonize pyx files into C files as needed. Usage: cythonize [root_dir] Default [root_dir] is 'numpy'. Checks pyx files to see if they have been changed relative to their corresponding C files. If they have, then runs cython on these files to recreate the C files. The script thinks that the pyx files have changed relative to the C files by comparing hashes stored in a database file. Simple script to invoke Cython (and Tempita) on all .pyx (.pyx.in) files; while waiting for a proper build system. Uses file hashes to figure out if rebuild is needed. For now, this script should be run by developers when changing Cython files only, and the resulting C files checked in, so that end-users (and Python-only developers) do not get the Cython/Tempita dependencies. Originally written by Dag Sverre Seljebotn, and copied here from: https://raw.github.com/dagss/private-scipy-refactor/cythonize/cythonize.py Note: this script does not check any of the dependent C libraries; it only operates on the Cython .pyx files. """ import os import re import sys import hashlib import subprocess HASH_FILE = 'cythonize.dat' DEFAULT_ROOT = 'numpy' VENDOR = 'NumPy' # # Rules # def process_pyx(fromfile, tofile): flags = ['-3', '--fast-fail'] if tofile.endswith('.cxx'): flags.append('--cplus') try: # try the cython in the installed python first (somewhat related to scipy/scipy#2397) import Cython from Cython.Compiler.Version import version as cython_version except ImportError as e: # The `cython` command need not point to the version installed in the # Python running this script, so raise an error to avoid the chance of # using the wrong version of Cython. msg = 'Cython needs to be installed in Python as a module' raise OSError(msg) from e else: # check the version, and invoke through python from distutils.version import LooseVersion # Cython 0.29.21 is required for Python 3.9 and there are # other fixes in the 0.29 series that are needed even for earlier # Python versions. # Note: keep in sync with that in pyproject.toml # Update for Python 3.10 required_version = LooseVersion('0.29.24') if LooseVersion(cython_version) < required_version: cython_path = Cython.__file__ raise RuntimeError(f'Building {VENDOR} requires Cython >= {required_version}' f', found {cython_version} at {cython_path}') subprocess.check_call( [sys.executable, '-m', 'cython'] + flags + ["-o", tofile, fromfile]) def process_tempita_pyx(fromfile, tofile): import npy_tempita as tempita assert fromfile.endswith('.pyx.in') with open(fromfile, "r") as f: tmpl = f.read() pyxcontent = tempita.sub(tmpl) pyxfile = fromfile[:-len('.pyx.in')] + '.pyx' with open(pyxfile, "w") as f: f.write(pyxcontent) process_pyx(pyxfile, tofile) def process_tempita_pyd(fromfile, tofile): import npy_tempita as tempita assert fromfile.endswith('.pxd.in') assert tofile.endswith('.pxd') with open(fromfile, "r") as f: tmpl = f.read() pyxcontent = tempita.sub(tmpl) with open(tofile, "w") as f: f.write(pyxcontent) def process_tempita_pxi(fromfile, tofile): import npy_tempita as tempita assert fromfile.endswith('.pxi.in') assert tofile.endswith('.pxi') with open(fromfile, "r") as f: tmpl = f.read() pyxcontent = tempita.sub(tmpl) with open(tofile, "w") as f: f.write(pyxcontent) def process_tempita_pxd(fromfile, tofile): import npy_tempita as tempita assert fromfile.endswith('.pxd.in') assert tofile.endswith('.pxd') with open(fromfile, "r") as f: tmpl = f.read() pyxcontent = tempita.sub(tmpl) with open(tofile, "w") as f: f.write(pyxcontent) rules = { # fromext : function, toext '.pyx' : (process_pyx, '.c'), '.pyx.in' : (process_tempita_pyx, '.c'), '.pxi.in' : (process_tempita_pxi, '.pxi'), '.pxd.in' : (process_tempita_pxd, '.pxd'), '.pyd.in' : (process_tempita_pyd, '.pyd'), } # # Hash db # def load_hashes(filename): # Return { filename : (sha256 of input, sha256 of output) } if os.path.isfile(filename): hashes = {} with open(filename, 'r') as f: for line in f: filename, inhash, outhash = line.split() hashes[filename] = (inhash, outhash) else: hashes = {} return hashes def save_hashes(hash_db, filename): with open(filename, 'w') as f: for key, value in sorted(hash_db.items()): f.write("%s %s %s\n" % (key, value[0], value[1])) def sha256_of_file(filename): h = hashlib.sha256() with open(filename, "rb") as f: h.update(f.read()) return h.hexdigest() # # Main program # def normpath(path): path = path.replace(os.sep, '/') if path.startswith('./'): path = path[2:] return path def get_hash(frompath, topath): from_hash = sha256_of_file(frompath) to_hash = sha256_of_file(topath) if os.path.exists(topath) else None return (from_hash, to_hash) def process(path, fromfile, tofile, processor_function, hash_db): fullfrompath = os.path.join(path, fromfile) fulltopath = os.path.join(path, tofile) current_hash = get_hash(fullfrompath, fulltopath) if current_hash == hash_db.get(normpath(fullfrompath), None): print(f'{fullfrompath} has not changed') return orig_cwd = os.getcwd() try: os.chdir(path) print(f'Processing {fullfrompath}') processor_function(fromfile, tofile) finally: os.chdir(orig_cwd) # changed target file, recompute hash current_hash = get_hash(fullfrompath, fulltopath) # store hash in db hash_db[normpath(fullfrompath)] = current_hash def find_process_files(root_dir): hash_db = load_hashes(HASH_FILE) files = [x for x in os.listdir(root_dir) if not os.path.isdir(x)] # .pxi or .pxi.in files are most likely dependencies for # .pyx files, so we need to process them first files.sort(key=lambda name: (name.endswith('.pxi') or name.endswith('.pxi.in') or name.endswith('.pxd.in')), reverse=True) for filename in files: in_file = os.path.join(root_dir, filename + ".in") for fromext, value in rules.items(): if filename.endswith(fromext): if not value: break function, toext = value if toext == '.c': with open(os.path.join(root_dir, filename), 'rb') as f: data = f.read() m = re.search(br"^\s*#\s*distutils:\s*language\s*=\s*c\+\+\s*$", data, re.I|re.M) if m: toext = ".cxx" fromfile = filename tofile = filename[:-len(fromext)] + toext process(root_dir, fromfile, tofile, function, hash_db) save_hashes(hash_db, HASH_FILE) break def main(): try: root_dir = sys.argv[1] except IndexError: root_dir = DEFAULT_ROOT find_process_files(root_dir) if __name__ == '__main__': main()
charris/numpy
tools/cythonize.py
Python
bsd-3-clause
7,459
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/security_interstitials/content/utils.h" #include <string> #include "base/command_line.h" #include "base/files/file_util.h" #include "base/notreached.h" #include "base/process/launch.h" #include "build/build_config.h" #include "build/chromeos_buildflags.h" #if BUILDFLAG(IS_ANDROID) #include "base/android/jni_android.h" #include "base/android/jni_string.h" #include "base/android/scoped_java_ref.h" #include "components/security_interstitials/content/android/jni_headers/DateAndTimeSettingsHelper_jni.h" #endif #if BUILDFLAG(IS_WIN) #include "base/base_paths_win.h" #include "base/path_service.h" #endif namespace security_interstitials { #if !BUILDFLAG(IS_CHROMEOS_ASH) void LaunchDateAndTimeSettings() { // The code for each OS is completely separate, in order to avoid bugs like // https://crbug.com/430877 . #if BUILDFLAG(IS_ANDROID) JNIEnv* env = base::android::AttachCurrentThread(); Java_DateAndTimeSettingsHelper_openDateAndTimeSettings(env); #elif BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS) struct ClockCommand { const char* const pathname; const char* const argument; }; static const ClockCommand kClockCommands[] = { // Unity {"/usr/bin/unity-control-center", "datetime"}, // GNOME // // NOTE: On old Ubuntu, naming control panels doesn't work, so it // opens the overview. This will have to be good enough. {"/usr/bin/gnome-control-center", "datetime"}, {"/usr/local/bin/gnome-control-center", "datetime"}, {"/opt/bin/gnome-control-center", "datetime"}, // KDE {"/usr/bin/kcmshell4", "clock"}, {"/usr/local/bin/kcmshell4", "clock"}, {"/opt/bin/kcmshell4", "clock"}, }; base::CommandLine command(base::FilePath("")); for (const ClockCommand& cmd : kClockCommands) { base::FilePath pathname(cmd.pathname); if (base::PathExists(pathname)) { command.SetProgram(pathname); command.AppendArg(cmd.argument); break; } } if (command.GetProgram().empty()) { // Alas, there is nothing we can do. return; } base::LaunchOptions options; options.wait = false; options.allow_new_privs = true; base::LaunchProcess(command, options); #elif BUILDFLAG(IS_APPLE) base::CommandLine command(base::FilePath("/usr/bin/open")); command.AppendArg("/System/Library/PreferencePanes/DateAndTime.prefPane"); base::LaunchOptions options; options.wait = false; base::LaunchProcess(command, options); #elif BUILDFLAG(IS_WIN) base::FilePath path; base::PathService::Get(base::DIR_SYSTEM, &path); static const wchar_t kControlPanelExe[] = L"control.exe"; path = path.Append(std::wstring(kControlPanelExe)); base::CommandLine command(path); command.AppendArg(std::string("/name")); command.AppendArg(std::string("Microsoft.DateAndTime")); base::LaunchOptions options; options.wait = false; base::LaunchProcess(command, options); #elif BUILDFLAG(IS_FUCHSIA) // TODO(crbug.com/1233494): Send to the platform settings. NOTIMPLEMENTED_LOG_ONCE(); #else #error Unsupported target architecture. #endif // Don't add code here! (See the comment at the beginning of the function.) } #endif } // namespace security_interstitials
chromium/chromium
components/security_interstitials/content/utils.cc
C++
bsd-3-clause
3,390
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/ash/login/existing_user_controller.h" #include <memory> #include <tuple> #include <utility> #include <vector> #include "ash/components/arc/arc_util.h" #include "ash/components/arc/enterprise/arc_data_snapshotd_manager.h" #include "ash/components/cryptohome/cryptohome_parameters.h" #include "ash/components/cryptohome/cryptohome_util.h" #include "ash/components/login/auth/key.h" #include "ash/components/login/session/session_termination_manager.h" #include "ash/components/settings/cros_settings_names.h" #include "ash/constants/ash_features.h" #include "ash/constants/ash_pref_names.h" #include "ash/constants/ash_switches.h" #include "ash/public/cpp/login_screen.h" #include "ash/public/cpp/notification_utils.h" #include "base/barrier_closure.h" #include "base/bind.h" #include "base/callback.h" #include "base/callback_helpers.h" #include "base/command_line.h" #include "base/compiler_specific.h" #include "base/logging.h" #include "base/metrics/histogram_functions.h" #include "base/scoped_observation.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/timer/elapsed_timer.h" #include "base/values.h" #include "base/version.h" #include "chrome/app/vector_icons/vector_icons.h" #include "chrome/browser/ash/app_mode/kiosk_app_launch_error.h" #include "chrome/browser/ash/app_mode/kiosk_app_types.h" #include "chrome/browser/ash/arc/arc_util.h" #include "chrome/browser/ash/authpolicy/authpolicy_helper.h" #include "chrome/browser/ash/boot_times_recorder.h" #include "chrome/browser/ash/crosapi/browser_data_migrator.h" #include "chrome/browser/ash/customization/customization_document.h" #include "chrome/browser/ash/login/auth/chrome_login_performer.h" #include "chrome/browser/ash/login/easy_unlock/easy_unlock_service.h" #include "chrome/browser/ash/login/enterprise_user_session_metrics.h" #include "chrome/browser/ash/login/helper.h" #include "chrome/browser/ash/login/quick_unlock/pin_storage_cryptohome.h" #include "chrome/browser/ash/login/reauth_stats.h" #include "chrome/browser/ash/login/screens/encryption_migration_mode.h" #include "chrome/browser/ash/login/session/user_session_manager.h" #include "chrome/browser/ash/login/signin/oauth2_token_initializer.h" #include "chrome/browser/ash/login/signin_specifics.h" #include "chrome/browser/ash/login/startup_utils.h" #include "chrome/browser/ash/login/ui/login_display_host.h" #include "chrome/browser/ash/login/ui/signin_ui.h" #include "chrome/browser/ash/login/ui/user_adding_screen.h" #include "chrome/browser/ash/login/user_flow.h" #include "chrome/browser/ash/login/users/chrome_user_manager.h" #include "chrome/browser/ash/login/wizard_controller.h" #include "chrome/browser/ash/policy/core/browser_policy_connector_ash.h" #include "chrome/browser/ash/policy/core/device_local_account.h" #include "chrome/browser/ash/policy/core/device_local_account_policy_service.h" #include "chrome/browser/ash/policy/handlers/minimum_version_policy_handler.h" #include "chrome/browser/ash/policy/handlers/powerwash_requirements_checker.h" #include "chrome/browser/ash/profiles/profile_helper.h" #include "chrome/browser/ash/settings/cros_settings.h" #include "chrome/browser/ash/system/device_disabling_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_platform_part.h" #include "chrome/browser/chrome_notification_types.h" #include "chrome/browser/lifetime/application_lifetime.h" #include "chrome/browser/lifetime/browser_shutdown.h" #include "chrome/browser/net/system_network_context_manager.h" #include "chrome/browser/notifications/system_notification_helper.h" #include "chrome/browser/policy/profile_policy_connector.h" #include "chrome/browser/profiles/profile.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/signin/chrome_device_id_helper.h" #include "chrome/browser/ui/ash/system_tray_client_impl.h" #include "chrome/browser/ui/aura/accessibility/automation_manager_aura.h" #include "chrome/browser/ui/managed_ui.h" #include "chrome/browser/ui/webui/chromeos/login/encryption_migration_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_autolaunch_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/kiosk_enable_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/l10n_util.h" #include "chrome/browser/ui/webui/chromeos/login/tpm_error_screen_handler.h" #include "chrome/browser/ui/webui/chromeos/login/update_required_screen_handler.h" #include "chrome/common/channel_info.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/pref_names.h" #include "chrome/common/url_constants.h" #include "chrome/grit/generated_resources.h" #include "chromeos/components/hibernate/buildflags.h" #include "chromeos/dbus/power/power_manager_client.h" #include "chromeos/dbus/session_manager/session_manager_client.h" #include "chromeos/dbus/userdataauth/userdataauth_client.h" #include "chromeos/strings/grit/chromeos_strings.h" #include "components/account_id/account_id.h" #include "components/google/core/common/google_util.h" #include "components/policy/core/common/cloud/cloud_policy_core.h" #include "components/policy/core/common/cloud/cloud_policy_store.h" #include "components/policy/core/common/cloud/device_management_service.h" #include "components/policy/core/common/policy_map.h" #include "components/policy/core/common/policy_service.h" #include "components/policy/core/common/policy_types.h" #include "components/policy/policy_constants.h" #include "components/policy/proto/cloud_policy.pb.h" #include "components/prefs/pref_service.h" #include "components/session_manager/core/session_manager.h" #include "components/user_manager/known_user.h" #include "components/user_manager/user_names.h" #include "components/user_manager/user_type.h" #include "components/vector_icons/vector_icons.h" #include "components/version_info/version_info.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/notification_service.h" #include "content/public/browser/notification_types.h" #include "content/public/browser/storage_partition.h" #include "google_apis/gaia/gaia_auth_util.h" #include "google_apis/gaia/google_service_auth_error.h" #include "services/network/public/mojom/network_context.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/l10n/l10n_util.h" #include "ui/message_center/public/cpp/notification.h" #include "ui/message_center/public/cpp/notification_delegate.h" #include "ui/views/widget/widget.h" #if BUILDFLAG(ENABLE_HIBERNATE) #include "chromeos/dbus/hiberman/hiberman_client.h" // nogncheck #endif namespace ash { namespace { using RebootOnSignOutPolicy = ::enterprise_management::DeviceRebootOnUserSignoutProto; const char kAutoLaunchNotificationId[] = "chrome://managed_guest_session/auto_launch"; const char kAutoLaunchNotifierId[] = "ash.managed_guest_session-auto_launch"; // Delay for transferring the auth cache to the system profile. const long int kAuthCacheTransferDelayMs = 2000; // Delay for restarting the ui if safe-mode login has failed. const long int kSafeModeRestartUiDelayMs = 30000; // Makes a call to the policy subsystem to reload the policy when we detect // authentication change. void RefreshPoliciesOnUIThread() { if (g_browser_process->policy_service()) g_browser_process->policy_service()->RefreshPolicies(base::OnceClosure()); } void OnTranferredHttpAuthCaches() { VLOG(1) << "Main request context populated with authentication data."; // Last but not least tell the policy subsystem to refresh now as it might // have been stuck until now too. content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&RefreshPoliciesOnUIThread)); } void TransferHttpAuthCacheToSystemNetworkContext( base::RepeatingClosure completion_callback, const base::UnguessableToken& cache_key) { network::mojom::NetworkContext* system_network_context = g_browser_process->system_network_context_manager()->GetContext(); system_network_context->LoadHttpAuthCacheProxyEntries(cache_key, completion_callback); } // Copies any authentication details that were entered in the login profile to // the main profile to make sure all subsystems of Chrome can access the network // with the provided authentication which are possibly for a proxy server. void TransferHttpAuthCaches() { content::StoragePartition* webview_storage_partition = login::GetSigninPartition(); base::RepeatingClosure completion_callback = base::BarrierClosure(webview_storage_partition ? 2 : 1, base::BindOnce(&OnTranferredHttpAuthCaches)); if (webview_storage_partition) { webview_storage_partition->GetNetworkContext() ->SaveHttpAuthCacheProxyEntries(base::BindOnce( &TransferHttpAuthCacheToSystemNetworkContext, completion_callback)); } network::mojom::NetworkContext* default_network_context = ProfileHelper::GetSigninProfile() ->GetDefaultStoragePartition() ->GetNetworkContext(); default_network_context->SaveHttpAuthCacheProxyEntries(base::BindOnce( &TransferHttpAuthCacheToSystemNetworkContext, completion_callback)); } // Record UMA for password login of regular user when Signin with Smart Lock is // enabled. Excludes signins in the multi-signin context; only records for the // signin screen context. void RecordPasswordLoginEvent(const UserContext& user_context) { // If a user is already logged in, this is a multi-signin attempt. Disregard. if (session_manager::SessionManager::Get()->IsInSecondaryLoginScreen()) return; EasyUnlockService* easy_unlock_service = EasyUnlockService::Get(ProfileHelper::GetSigninProfile()); if (user_context.GetUserType() == user_manager::USER_TYPE_REGULAR && user_context.GetAuthFlow() == UserContext::AUTH_FLOW_OFFLINE && easy_unlock_service) { easy_unlock_service->RecordPasswordLoginEvent(user_context.GetAccountId()); } } bool IsUpdateRequiredDeadlineReached() { policy::MinimumVersionPolicyHandler* policy_handler = g_browser_process->platform_part() ->browser_policy_connector_ash() ->GetMinimumVersionPolicyHandler(); return policy_handler && policy_handler->DeadlineReached(); } bool IsTestingMigrationUI() { return base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kTestEncryptionMigrationUI); } bool ShouldForceDircrypto(const AccountId& account_id) { if (IsTestingMigrationUI()) return true; // If the device is not officially supported to run ARC, we don't need to // force Ext4 dircrypto. if (!arc::IsArcAvailable()) return false; // When a user is signing in as a secondary user, we don't need to force Ext4 // dircrypto since the user can not run ARC. if (UserAddingScreen::Get()->IsRunning()) return false; return true; } // Returns true if the device is enrolled to an Active Directory domain // according to InstallAttributes (proxied through BrowserPolicyConnector). bool IsActiveDirectoryManaged() { return g_browser_process->platform_part() ->browser_policy_connector_ash() ->IsActiveDirectoryManaged(); } LoginDisplayHost* GetLoginDisplayHost() { return LoginDisplayHost::default_host(); } LoginDisplay* GetLoginDisplay() { return GetLoginDisplayHost()->GetLoginDisplay(); } void SetLoginExtensionApiCanLockManagedGuestSessionPref( const AccountId& account_id, bool can_lock_managed_guest_session) { const user_manager::User* user = user_manager::UserManager::Get()->FindUser(account_id); DCHECK(user); Profile* profile = ProfileHelper::Get()->GetProfileByUser(user); DCHECK(profile); PrefService* prefs = profile->GetPrefs(); prefs->SetBoolean(::prefs::kLoginExtensionApiCanLockManagedGuestSession, can_lock_managed_guest_session); prefs->CommitPendingWrite(); } absl::optional<EncryptionMigrationMode> GetEncryptionMigrationMode( const UserContext& user_context, bool has_incomplete_migration) { if (has_incomplete_migration) { // If migration was incomplete, continue migration automatically. return EncryptionMigrationMode::RESUME_MIGRATION; } if (user_context.GetUserType() == user_manager::USER_TYPE_CHILD) { // Force-migrate child users. return EncryptionMigrationMode::START_MIGRATION; } user_manager::KnownUser known_user(g_browser_process->local_state()); const bool profile_has_policy = known_user.GetProfileRequiresPolicy(user_context.GetAccountId()) == user_manager::ProfileRequiresPolicy::kPolicyRequired || base::CommandLine::ForCurrentProcess()->HasSwitch( switches::kProfileRequiresPolicy); // Force-migrate all home directories if the user is known to have enterprise // policy, otherwise ask the user. return profile_has_policy ? EncryptionMigrationMode::START_MIGRATION : EncryptionMigrationMode::ASK_USER; } // Returns account ID of a public session account if it is unique, otherwise // returns invalid account ID. AccountId GetArcDataSnapshotAutoLoginAccountId( const std::vector<policy::DeviceLocalAccount>& device_local_accounts) { AccountId auto_login_account_id = EmptyAccountId(); for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->type == policy::DeviceLocalAccount::TYPE_PUBLIC_SESSION) { // Do not perform ARC data snapshot auto-login if more than one public // session account is configured. if (auto_login_account_id.is_valid()) return EmptyAccountId(); auto_login_account_id = AccountId::FromUserEmail(it->user_id); VLOG(2) << "PublicSession autologin found: " << it->user_id; } } return auto_login_account_id; } // Returns account ID if a corresponding to `auto_login_account_id` device local // account exists, otherwise returns invalid account ID. AccountId GetPublicSessionAutoLoginAccountId( const std::vector<policy::DeviceLocalAccount>& device_local_accounts, const std::string& auto_login_account_id) { for (std::vector<policy::DeviceLocalAccount>::const_iterator it = device_local_accounts.begin(); it != device_local_accounts.end(); ++it) { if (it->account_id == auto_login_account_id) { VLOG(2) << "PublicSession autologin found: " << it->user_id; return AccountId::FromUserEmail(it->user_id); } } return EmptyAccountId(); } } // namespace // Utility class used to wait for a Public Session policy store load if public // session login is requested before the associated policy store is loaded. // When the store gets loaded, it will run the callback passed to the // constructor. class ExistingUserController::PolicyStoreLoadWaiter : public policy::CloudPolicyStore::Observer { public: PolicyStoreLoadWaiter(policy::CloudPolicyStore* store, base::OnceClosure callback) : callback_(std::move(callback)) { DCHECK(!store->is_initialized()); scoped_observation_.Observe(store); } ~PolicyStoreLoadWaiter() override = default; PolicyStoreLoadWaiter(const PolicyStoreLoadWaiter& other) = delete; PolicyStoreLoadWaiter& operator=(const PolicyStoreLoadWaiter& other) = delete; // policy::CloudPolicyStore::Observer: void OnStoreLoaded(policy::CloudPolicyStore* store) override { scoped_observation_.Reset(); std::move(callback_).Run(); } void OnStoreError(policy::CloudPolicyStore* store) override { // If store load fails, run the callback to unblock public session login // attempt, which will likely fail. scoped_observation_.Reset(); std::move(callback_).Run(); } private: base::OnceClosure callback_; base::ScopedObservation<policy::CloudPolicyStore, policy::CloudPolicyStore::Observer> scoped_observation_{this}; }; // static ExistingUserController* ExistingUserController::current_controller() { auto* host = LoginDisplayHost::default_host(); return host ? host->GetExistingUserController() : nullptr; } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, public: ExistingUserController::ExistingUserController() : cros_settings_(CrosSettings::Get()), network_state_helper_(new login::NetworkStateHelper) { registrar_.Add(this, chrome::NOTIFICATION_AUTH_SUPPLIED, content::NotificationService::AllSources()); show_user_names_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefShowUserNamesOnSignIn, base::BindRepeating(&ExistingUserController::DeviceSettingsChanged, base::Unretained(this))); allow_guest_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefAllowGuest, base::BindRepeating(&ExistingUserController::DeviceSettingsChanged, base::Unretained(this))); users_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefUsers, base::BindRepeating(&ExistingUserController::DeviceSettingsChanged, base::Unretained(this))); local_account_auto_login_id_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefDeviceLocalAccountAutoLoginId, base::BindRepeating(&ExistingUserController::ConfigureAutoLogin, base::Unretained(this))); local_account_auto_login_delay_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefDeviceLocalAccountAutoLoginDelay, base::BindRepeating(&ExistingUserController::ConfigureAutoLogin, base::Unretained(this))); family_link_allowed_subscription_ = cros_settings_->AddSettingsObserver( kAccountsPrefFamilyLinkAccountsAllowed, base::BindRepeating(&ExistingUserController::DeviceSettingsChanged, base::Unretained(this))); observed_user_manager_.Observe(user_manager::UserManager::Get()); } void ExistingUserController::Init(const user_manager::UserList& users) { timer_init_ = std::make_unique<base::ElapsedTimer>(); UpdateLoginDisplay(users); ConfigureAutoLogin(); } void ExistingUserController::UpdateLoginDisplay( const user_manager::UserList& users) { int reboot_on_signout_policy = -1; cros_settings_->GetInteger(kDeviceRebootOnUserSignout, &reboot_on_signout_policy); if (reboot_on_signout_policy != -1 && reboot_on_signout_policy != RebootOnSignOutPolicy::REBOOT_ON_SIGNOUT_MODE_UNSPECIFIED && reboot_on_signout_policy != RebootOnSignOutPolicy::NEVER) { SessionTerminationManager::Get()->RebootIfNecessary(); // Initialize PowerwashRequirementsChecker so its instances will be able to // use stored cryptohome powerwash state later policy::PowerwashRequirementsChecker::Initialize(); } bool show_users_on_signin; user_manager::UserList saml_users_for_password_sync; cros_settings_->GetBoolean(kAccountsPrefShowUserNamesOnSignIn, &show_users_on_signin); user_manager::UserManager* const user_manager = user_manager::UserManager::Get(); // By default disable offline login from the error screen. ErrorScreen::AllowOfflineLogin(false /* allowed */); // Counts regular device users that can log in. int regular_users_counter = 0; for (auto* user : users) { // Skip kiosk apps for login screen user list. Kiosk apps as pods (aka new // kiosk UI) is currently disabled and it gets the apps directly from // KioskAppManager, ArcKioskAppManager and WebKioskAppManager. if (user->IsKioskType()) continue; // Allow offline login from the error screen if user of one of these types // has already logged in. if (user->GetType() == user_manager::USER_TYPE_REGULAR || user->GetType() == user_manager::USER_TYPE_CHILD || user->GetType() == user_manager::USER_TYPE_ACTIVE_DIRECTORY) { ErrorScreen::AllowOfflineLogin(true /* allowed */); regular_users_counter++; } const bool meets_allowlist_requirements = !user->HasGaiaAccount() || user_manager::UserManager::Get()->IsGaiaUserAllowed(*user); if (meets_allowlist_requirements && user->using_saml()) saml_users_for_password_sync.push_back(user); } // Records total number of users on the login screen. base::UmaHistogramCounts100("Login.NumberOfUsersOnLoginScreen", regular_users_counter); auto login_users = ExtractLoginUsers(users); // ExistingUserController owns PasswordSyncTokenLoginCheckers only if user // pods are hidden. if (!show_users_on_signin && !saml_users_for_password_sync.empty()) { sync_token_checkers_ = std::make_unique<PasswordSyncTokenCheckersCollection>(); sync_token_checkers_->StartPasswordSyncCheckers( saml_users_for_password_sync, /*observer*/ nullptr); } else { sync_token_checkers_.reset(); } bool show_guest = user_manager->IsGuestSessionAllowed(); GetLoginDisplay()->Init(login_users, show_guest); } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, content::NotificationObserver implementation: // void ExistingUserController::Observe( int type, const content::NotificationSource& source, const content::NotificationDetails& details) { DCHECK_EQ(type, chrome::NOTIFICATION_AUTH_SUPPLIED); // Don't transfer http auth cache on NOTIFICATION_AUTH_SUPPLIED after user // session starts. if (session_manager::SessionManager::Get()->IsSessionStarted()) return; // Possibly the user has authenticated against a proxy server and we might // need the credentials for enrollment and other system requests from the // main `g_browser_process` request context (see bug // http://crosbug.com/24861). So we transfer any credentials to the global // request context here. // The issue we have here is that the NOTIFICATION_AUTH_SUPPLIED is sent // just after the UI is closed but before the new credentials were stored // in the profile. Therefore we have to give it some time to make sure it // has been updated before we copy it. // TODO(pmarko): Find a better way to do this, see https://crbug.com/796512. VLOG(1) << "Authentication was entered manually, possibly for proxyauth."; base::SequencedTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, base::BindOnce(&TransferHttpAuthCaches), base::Milliseconds(kAuthCacheTransferDelayMs)); } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, private: ExistingUserController::~ExistingUserController() { if (browser_shutdown::IsTryingToQuit() || chrome::IsAttemptingShutdown()) return; CHECK(UserSessionManager::GetInstance()); UserSessionManager::GetInstance()->DelegateDeleted(this); } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, LoginDisplay::Delegate implementation: // void ExistingUserController::CompleteLogin(const UserContext& user_context) { if (!GetLoginDisplayHost()) { // Complete login event was generated already from UI. Ignore notification. return; } if (is_login_in_progress_) return; is_login_in_progress_ = true; ContinueLoginIfDeviceNotDisabled( base::BindOnce(&ExistingUserController::DoCompleteLogin, weak_factory_.GetWeakPtr(), user_context)); } std::u16string ExistingUserController::GetConnectedNetworkName() const { return network_state_helper_->GetCurrentNetworkName(); } bool ExistingUserController::IsSigninInProgress() const { return is_login_in_progress_; } void ExistingUserController::Login(const UserContext& user_context, const SigninSpecifics& specifics) { if (is_login_in_progress_) { // If there is another login in progress, bail out. Do not re-enable // clicking on other windows and the status area. Do not start the // auto-login timer. return; } is_login_in_progress_ = true; if (user_context.GetUserType() != user_manager::USER_TYPE_REGULAR && user_manager::UserManager::Get()->IsUserLoggedIn()) { // Multi-login is only allowed for regular users. If we are attempting to // do multi-login as another type of user somehow, bail out. Do not // re-enable clicking on other windows and the status area. Do not start the // auto-login timer. return; } ContinueLoginIfDeviceNotDisabled( base::BindOnce(&ExistingUserController::DoLogin, weak_factory_.GetWeakPtr(), user_context, specifics)); } void ExistingUserController::PerformLogin( const UserContext& user_context, LoginPerformer::AuthorizationMode auth_mode) { VLOG(1) << "Setting flow from PerformLogin"; BootTimesRecorder::Get()->RecordLoginAttempted(); // Use the same LoginPerformer for subsequent login as it has state // such as Authenticator instance. if (!login_performer_.get() || num_login_attempts_ <= 1) { // Only one instance of LoginPerformer should exist at a time. login_performer_.reset(nullptr); login_performer_ = std::make_unique<ChromeLoginPerformer>(this); } if (IsActiveDirectoryManaged() && user_context.GetUserType() != user_manager::USER_TYPE_ACTIVE_DIRECTORY) { PerformLoginFinishedActions(false /* don't start auto login timer */); ShowError(SigninError::kGoogleAccountNotAllowed, "Google accounts are not allowed on this device"); return; } if (user_context.GetAccountId().GetAccountType() == AccountType::ACTIVE_DIRECTORY && user_context.GetAuthFlow() == UserContext::AUTH_FLOW_OFFLINE && user_context.GetKey()->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN) { // Try to get kerberos TGT while we have user's password typed on the pod // screen. Failure to get TGT here is OK - that could mean e.g. Active // Directory server is not reachable. We don't want to have user wait for // the Active Directory Authentication on the pod screen. // AuthPolicyCredentialsManager will be created inside the user session // which would get status about last authentication and handle possible // failures. AuthPolicyHelper::TryAuthenticateUser( user_context.GetAccountId().GetUserEmail(), user_context.GetAccountId().GetObjGuid(), user_context.GetKey()->GetSecret()); } // If plain text password is available, computes its salt, hash, and length, // and saves them in `user_context`. They will be saved to prefs when user // profile is ready. UserContext new_user_context = user_context; if (user_context.GetKey()->GetKeyType() == Key::KEY_TYPE_PASSWORD_PLAIN) { std::u16string password( base::UTF8ToUTF16(new_user_context.GetKey()->GetSecret())); new_user_context.SetSyncPasswordData(password_manager::PasswordHashData( user_context.GetAccountId().GetUserEmail(), password, auth_mode == LoginPerformer::AuthorizationMode::kExternal)); } if (new_user_context.IsUsingPin()) { absl::optional<Key> key = quick_unlock::PinStorageCryptohome::TransformKey( new_user_context.GetAccountId(), *new_user_context.GetKey()); if (key) { new_user_context.SetKey(*key); } else { new_user_context.SetIsUsingPin(false); } } // If a regular user log in to a device which supports ARC, we should make // sure that the user's cryptohome is encrypted in ext4 dircrypto to run the // latest Android runtime. new_user_context.SetIsForcingDircrypto( ShouldForceDircrypto(new_user_context.GetAccountId())); login_performer_->PerformLogin(new_user_context, auth_mode); RecordPasswordLoginEvent(new_user_context); SendAccessibilityAlert( l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNING_IN)); if (timer_init_) { base::UmaHistogramMediumTimes("Login.PromptToLoginTime", timer_init_->Elapsed()); timer_init_.reset(); } } void ExistingUserController::ContinuePerformLogin( LoginPerformer::AuthorizationMode auth_mode, const UserContext& user_context) { login_performer_->PerformLogin(user_context, auth_mode); } void ExistingUserController::ContinuePerformLoginWithoutMigration( LoginPerformer::AuthorizationMode auth_mode, const UserContext& user_context) { UserContext user_context_ecryptfs = user_context; user_context_ecryptfs.SetIsForcingDircrypto(false); ContinuePerformLogin(auth_mode, user_context_ecryptfs); } void ExistingUserController::OnGaiaScreenReady() { StartAutoLoginTimer(); } void ExistingUserController::OnStartEnterpriseEnrollment() { if (KioskAppManager::Get()->IsConsumerKioskDeviceWithAutoLaunch()) { LOG(WARNING) << "Enterprise enrollment is not available after kiosk auto " "launch is set."; return; } DeviceSettingsService::Get()->GetOwnershipStatusAsync(base::BindOnce( &ExistingUserController::OnEnrollmentOwnershipCheckCompleted, weak_factory_.GetWeakPtr())); } void ExistingUserController::OnStartKioskEnableScreen() { KioskAppManager::Get()->GetConsumerKioskAutoLaunchStatus(base::BindOnce( &ExistingUserController::OnConsumerKioskAutoLaunchCheckCompleted, weak_factory_.GetWeakPtr())); } void ExistingUserController::OnStartKioskAutolaunchScreen() { ShowKioskAutolaunchScreen(); } void ExistingUserController::SetDisplayEmail(const std::string& email) { display_email_ = email; } void ExistingUserController::SetDisplayAndGivenName( const std::string& display_name, const std::string& given_name) { display_name_ = base::UTF8ToUTF16(display_name); given_name_ = base::UTF8ToUTF16(given_name); } bool ExistingUserController::IsUserAllowlisted( const AccountId& account_id, const absl::optional<user_manager::UserType>& user_type) { bool wildcard_match = false; if (login_performer_.get()) { return login_performer_->IsUserAllowlisted(account_id, &wildcard_match, user_type); } return cros_settings_->IsUserAllowlisted(account_id.GetUserEmail(), &wildcard_match, user_type); } void ExistingUserController::LocalStateChanged( user_manager::UserManager* user_manager) { DeviceSettingsChanged(); } void ExistingUserController::OnConsumerKioskAutoLaunchCheckCompleted( KioskAppManager::ConsumerKioskAutoLaunchStatus status) { if (status == KioskAppManager::ConsumerKioskAutoLaunchStatus::kConfigurable) ShowKioskEnableScreen(); } void ExistingUserController::OnEnrollmentOwnershipCheckCompleted( DeviceSettingsService::OwnershipStatus status) { VLOG(1) << "OnEnrollmentOwnershipCheckCompleted status=" << status; if (status == DeviceSettingsService::OWNERSHIP_NONE) { ShowEnrollmentScreen(); } else if (status == DeviceSettingsService::OWNERSHIP_TAKEN) { // On a device that is already owned we might want to allow users to // re-enroll if the policy information is invalid. CrosSettingsProvider::TrustedStatus trusted_status = CrosSettings::Get()->PrepareTrustedValues(base::BindOnce( &ExistingUserController::OnEnrollmentOwnershipCheckCompleted, weak_factory_.GetWeakPtr(), status)); if (trusted_status == CrosSettingsProvider::PERMANENTLY_UNTRUSTED) { VLOG(1) << "Showing enrollment because device is PERMANENTLY_UNTRUSTED"; ShowEnrollmentScreen(); } } else { // OwnershipService::GetStatusAsync is supposed to return either // OWNERSHIP_NONE or OWNERSHIP_TAKEN. NOTREACHED(); } } void ExistingUserController::ShowEnrollmentScreen() { GetLoginDisplayHost()->StartWizard(EnrollmentScreenView::kScreenId); } void ExistingUserController::ShowKioskEnableScreen() { GetLoginDisplayHost()->StartWizard(KioskEnableScreenView::kScreenId); } void ExistingUserController::ShowKioskAutolaunchScreen() { GetLoginDisplayHost()->StartWizard(KioskAutolaunchScreenView::kScreenId); } void ExistingUserController::ShowEncryptionMigrationScreen( const UserContext& user_context, EncryptionMigrationMode migration_mode) { GetLoginDisplayHost()->GetSigninUI()->StartEncryptionMigration( user_context, migration_mode, base::BindOnce(&ExistingUserController::ContinuePerformLogin, weak_factory_.GetWeakPtr(), login_performer_->auth_mode())); } void ExistingUserController::ShowTPMError() { GetLoginDisplay()->SetUIEnabled(false); GetLoginDisplayHost()->StartWizard(TpmErrorView::kScreenId); } void ExistingUserController::ShowPasswordChangedDialog( const UserContext& user_context) { VLOG(1) << "Show password changed dialog" << ", count=" << login_performer_->password_changed_callback_count(); // True if user has already made an attempt to enter old password and failed. bool show_invalid_old_password_error = login_performer_->password_changed_callback_count() > 1; GetLoginDisplayHost()->GetSigninUI()->ShowPasswordChangedDialog( user_context.GetAccountId(), show_invalid_old_password_error); } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, LoginPerformer::Delegate implementation: // void ExistingUserController::OnAuthFailure(const AuthFailure& failure) { guest_mode_url_ = GURL::EmptyGURL(); std::string error = failure.GetErrorString(); PerformLoginFinishedActions(false /* don't start auto login timer */); if (ChromeUserManager::Get() ->GetUserFlow(last_login_attempt_account_id_) ->HandleLoginFailure(failure)) { return; } const bool is_known_user = user_manager::UserManager::Get()->IsKnownUser( last_login_attempt_account_id_); if (failure.reason() == AuthFailure::OWNER_REQUIRED) { ShowError(SigninError::kOwnerRequired, error); // Using Untretained here is safe because SessionTerminationManager is // destroyed after the task runner, in // ChromeBrowserMainParts::PostDestroyThreads(). content::GetUIThreadTaskRunner({})->PostDelayedTask( FROM_HERE, base::BindOnce(&SessionTerminationManager::StopSession, base::Unretained(SessionTerminationManager::Get()), login_manager::SessionStopReason::OWNER_REQUIRED), base::Milliseconds(kSafeModeRestartUiDelayMs)); } else if (failure.reason() == AuthFailure::TPM_ERROR) { ShowTPMError(); } else if (failure.reason() == AuthFailure::TPM_UPDATE_REQUIRED) { ShowError(SigninError::kTpmUpdateRequired, error); } else if (last_login_attempt_account_id_ == user_manager::GuestAccountId()) { StartAutoLoginTimer(); } else if (is_known_user && failure.reason() == AuthFailure::MISSING_CRYPTOHOME) { ForceOnlineLoginForAccountId(last_login_attempt_account_id_); RecordReauthReason(last_login_attempt_account_id_, ReauthReason::MISSING_CRYPTOHOME); } else if (is_known_user && failure.reason() == AuthFailure::UNRECOVERABLE_CRYPTOHOME) { // TODO(chromium:1140868, dlunev): for now we route unrecoverable the same // way as missing because it is removed under the hood in cryptohomed when // the condition met. We should surface that up and deal with it on the // chromium level, including making the decision user-driven. ForceOnlineLoginForAccountId(last_login_attempt_account_id_); RecordReauthReason(last_login_attempt_account_id_, ReauthReason::UNRECOVERABLE_CRYPTOHOME); } else { // Check networking after trying to login in case user is // cached locally or the local admin account. if (!network_state_helper_->IsConnected()) { if (is_known_user) ShowError(SigninError::kKnownUserFailedNetworkNotConnected, error); else ShowError(SigninError::kNewUserFailedNetworkNotConnected, error); } else { if (is_known_user) ShowError(SigninError::kKnownUserFailedNetworkConnected, error); else ShowError(SigninError::kNewUserFailedNetworkConnected, error); } StartAutoLoginTimer(); } // Reset user flow to default, so that special flow will not affect next // attempt. ChromeUserManager::Get()->ResetUserFlow(last_login_attempt_account_id_); for (auto& auth_status_consumer : auth_status_consumers_) auth_status_consumer.OnAuthFailure(failure); ClearActiveDirectoryState(); ClearRecordedNames(); } void ExistingUserController::OnAuthSuccess(const UserContext& user_context) { is_login_in_progress_ = false; GetLoginDisplay()->set_signin_completed(true); // Login performer will be gone so cache this value to use // once profile is loaded. password_changed_ = login_performer_->password_changed(); auth_mode_ = login_performer_->auth_mode(); ChromeUserManager::Get() ->GetUserFlow(user_context.GetAccountId()) ->HandleLoginSuccess(user_context); StopAutoLoginTimer(); if (user_context.GetAuthFlow() == UserContext::AUTH_FLOW_OFFLINE) { base::UmaHistogramCounts100("Login.OfflineSuccess.Attempts", num_login_attempts_); } // If the hibernate service is supported, call it to initiate resume. #if BUILDFLAG(ENABLE_HIBERNATE) if (features::IsHibernateEnabled()) { HibermanClient::Get()->WaitForServiceToBeAvailable( base::BindOnce(&ExistingUserController::OnHibernateServiceAvailable, weak_factory_.GetWeakPtr(), user_context)); return; } #endif // The hibernate service is not supported, just continue directly. ContinueAuthSuccessAfterResumeAttempt(user_context, true); return; } #if BUILDFLAG(ENABLE_HIBERNATE) void ExistingUserController::OnHibernateServiceAvailable( const UserContext& user_context, bool service_is_available) { if (!service_is_available) { LOG(ERROR) << "Hibernate service is unavailable"; ContinueAuthSuccessAfterResumeAttempt(user_context, false); } else { // In a successful resume case, this function never returns, as execution // continues in the resumed hibernation image. HibermanClient::Get()->ResumeFromHibernate( user_context.GetAccountId().GetUserEmail(), base::BindOnce(&ExistingUserController::ContinueAuthSuccessAfterResumeAttempt, weak_factory_.GetWeakPtr(), user_context)); } } #endif void ExistingUserController::ContinueAuthSuccessAfterResumeAttempt( const UserContext& user_context, bool resume_call_success) { // There are three cases that may have led to execution here, and one that // won't: // 1) The ENABLE_HIBERNATE buildflag is not enabled, so this function was // simply called directly by OnAuthSuccess. Pretend the call out was a // success by passing true for resume_call_success. // 2) There was a hibernation image primed for resume, and we resumed to it. // In that case execution never gets here, as the resumed image will have // replaced this world. // 3) There was no hibernation image primed for resume, the resume was // cancelled, or the resume was aborted. In that case this will be running // with resume_call_success == true, indicating the hibernate daemon was // called, but opted to return control. // 4) Chrome failed to make contact with the hiberman daemon at all, in which // case resume_call_success is false. Print an error here, as it represents // a broken link in the chain. if (!resume_call_success) { LOG(ERROR) << "Failed to call ResumeFromHibernate, continuing with login"; } // Truth table of `has_auth_cookies`: // Regular SAML // /ServiceLogin T T // /ChromeOsEmbeddedSetup F T const bool has_auth_cookies = login_performer_->auth_mode() == LoginPerformer::AuthorizationMode::kExternal && (user_context.GetAccessToken().empty() || user_context.GetAuthFlow() == UserContext::AUTH_FLOW_GAIA_WITH_SAML); // LoginPerformer instance will delete itself in case of successful auth. login_performer_->set_delegate(nullptr); std::ignore = login_performer_.release(); const bool is_enterprise_managed = g_browser_process->platform_part() ->browser_policy_connector_ash() ->IsDeviceEnterpriseManaged(); // Mark device will be consumer owned if the device is not managed and this is // the first user on the device. if (!is_enterprise_managed && user_manager::UserManager::Get()->GetUsers().empty()) { DeviceSettingsService::Get()->MarkWillEstablishConsumerOwnership(); } if (user_context.CanLockManagedGuestSession()) { CHECK(user_context.GetUserType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT); user_manager::User* user = user_manager::UserManager::Get()->FindUserAndModify( user_context.GetAccountId()); DCHECK(user); user->AddProfileCreatedObserver( base::BindOnce(&SetLoginExtensionApiCanLockManagedGuestSessionPref, user_context.GetAccountId(), true)); } if (BrowserDataMigratorImpl::MaybeForceResumeMoveMigration( g_browser_process->local_state(), user_context.GetAccountId(), user_context.GetUserIDHash())) { // TODO(crbug.com/1261730): Add an UMA. LOG(WARNING) << "Restarting Chrome to resume move migration."; return; } UserSessionManager::StartSessionType start_session_type = UserAddingScreen::Get()->IsRunning() ? UserSessionManager::StartSessionType::kSecondary : UserSessionManager::StartSessionType::kPrimary; UserSessionManager::GetInstance()->StartSession( user_context, start_session_type, has_auth_cookies, false, // Start session for user. this); // Update user's displayed email. if (!display_email_.empty()) { user_manager::UserManager::Get()->SaveUserDisplayEmail( user_context.GetAccountId(), display_email_); } if (!display_name_.empty() || !given_name_.empty()) { user_manager::UserManager::Get()->UpdateUserAccountData( user_context.GetAccountId(), user_manager::UserManager::UserAccountData(display_name_, given_name_, std::string() /* locale */)); } ClearRecordedNames(); if (public_session_auto_login_account_id_.is_valid() && public_session_auto_login_account_id_ == user_context.GetAccountId() && last_login_attempt_was_auto_login_) { const std::string& user_id = user_context.GetAccountId().GetUserEmail(); policy::DeviceLocalAccountPolicyBroker* broker = g_browser_process->platform_part() ->browser_policy_connector_ash() ->GetDeviceLocalAccountPolicyService() ->GetBrokerForUser(user_id); bool privacy_warnings_enabled = g_browser_process->local_state()->GetBoolean( prefs::kManagedGuestSessionPrivacyWarningsEnabled); if (ChromeUserManager::Get()->IsFullManagementDisclosureNeeded(broker) && privacy_warnings_enabled) { ShowAutoLaunchManagedGuestSessionNotification(); } } if (is_enterprise_managed) { enterprise_user_session_metrics::RecordSignInEvent( user_context, last_login_attempt_was_auto_login_); } } void ExistingUserController::ShowAutoLaunchManagedGuestSessionNotification() { policy::BrowserPolicyConnectorAsh* connector = g_browser_process->platform_part()->browser_policy_connector_ash(); DCHECK(connector->IsDeviceEnterpriseManaged()); message_center::RichNotificationData data; data.buttons.push_back(message_center::ButtonInfo( l10n_util::GetStringUTF16(IDS_AUTO_LAUNCH_NOTIFICATION_BUTTON))); const std::u16string title = l10n_util::GetStringUTF16(IDS_AUTO_LAUNCH_NOTIFICATION_TITLE); const std::u16string message = l10n_util::GetStringFUTF16( IDS_ASH_LOGIN_MANAGED_SESSION_MONITORING_FULL_WARNING, base::UTF8ToUTF16(connector->GetEnterpriseDomainManager())); auto delegate = base::MakeRefCounted<message_center::HandleNotificationClickDelegate>( base::BindRepeating([](absl::optional<int> button_index) { DCHECK(button_index); SystemTrayClientImpl::Get()->ShowEnterpriseInfo(); })); std::unique_ptr<message_center::Notification> notification = CreateSystemNotification( message_center::NOTIFICATION_TYPE_SIMPLE, kAutoLaunchNotificationId, title, message, std::u16string(), GURL(), message_center::NotifierId( message_center::NotifierType::SYSTEM_COMPONENT, kAutoLaunchNotifierId), data, std::move(delegate), vector_icons::kBusinessIcon, message_center::SystemNotificationWarningLevel::NORMAL); notification->SetSystemPriority(); notification->set_pinned(true); SystemNotificationHelper::GetInstance()->Display(*notification); } void ExistingUserController::OnProfilePrepared(Profile* profile, bool browser_launched) { // Reenable clicking on other windows and status area. GetLoginDisplay()->SetUIEnabled(true); profile_prepared_ = true; UserContext user_context = UserContext(*ProfileHelper::Get()->GetUserByProfile(profile)); auto* profile_connector = profile->GetProfilePolicyConnector(); bool is_enterprise_managed = profile_connector->IsManaged() && user_context.GetUserType() != user_manager::USER_TYPE_CHILD; user_manager::KnownUser known_user(g_browser_process->local_state()); known_user.SetIsEnterpriseManaged(user_context.GetAccountId(), is_enterprise_managed); if (is_enterprise_managed) { absl::optional<std::string> manager = chrome::GetAccountManagerIdentity(profile); if (manager) { known_user.SetAccountManager(user_context.GetAccountId(), *manager); } } // Inform `auth_status_consumers_` about successful login. // TODO(nkostylev): Pass UserContext back crbug.com/424550 for (auto& auth_status_consumer : auth_status_consumers_) auth_status_consumer.OnAuthSuccess(user_context); } void ExistingUserController::OnOffTheRecordAuthSuccess() { // Do not reset is_login_in_progress_ flag: // CompleteGuestSessionLogin() below should result in browser restart // that would actually complete the login process. // Mark the device as registered., i.e. the second part of OOBE as completed. if (!StartupUtils::IsDeviceRegistered()) StartupUtils::MarkDeviceRegistered(base::OnceClosure()); UserSessionManager::GetInstance()->CompleteGuestSessionLogin(guest_mode_url_); for (auto& auth_status_consumer : auth_status_consumers_) auth_status_consumer.OnOffTheRecordAuthSuccess(); } void ExistingUserController::OnPasswordChangeDetected( const UserContext& user_context) { is_login_in_progress_ = false; // Must not proceed without signature verification. if (CrosSettingsProvider::TRUSTED != cros_settings_->PrepareTrustedValues( base::BindOnce(&ExistingUserController::OnPasswordChangeDetected, weak_factory_.GetWeakPtr(), user_context))) { // Value of owner email is still not verified. // Another attempt will be invoked after verification completion. return; } for (auto& auth_status_consumer : auth_status_consumers_) auth_status_consumer.OnPasswordChangeDetected(user_context); ShowPasswordChangedDialog(user_context); } void ExistingUserController::OnOldEncryptionDetected( const UserContext& user_context, bool has_incomplete_migration) { absl::optional<EncryptionMigrationMode> encryption_migration_mode = GetEncryptionMigrationMode(user_context, has_incomplete_migration); if (!encryption_migration_mode.has_value()) { ContinuePerformLoginWithoutMigration(login_performer_->auth_mode(), user_context); return; } ShowEncryptionMigrationScreen(user_context, encryption_migration_mode.value()); } void ExistingUserController::ForceOnlineLoginForAccountId( const AccountId& account_id) { // Save the necessity to sign-in online into UserManager in case the user // aborts the online flow. user_manager::UserManager::Get()->SaveForceOnlineSignin(account_id, true); // Start online sign-in UI for the user. is_login_in_progress_ = false; login_performer_.reset(); if (session_manager::SessionManager::Get()->IsInSecondaryLoginScreen()) { // Gaia dialog is not supported on the secondary login screen. return; } GetLoginDisplayHost()->ShowGaiaDialog(account_id); } void ExistingUserController::AllowlistCheckFailed(const std::string& email) { PerformLoginFinishedActions(true /* start auto login timer */); GetLoginDisplayHost()->ShowAllowlistCheckFailedError(); for (auto& auth_status_consumer : auth_status_consumers_) { auth_status_consumer.OnAuthFailure( AuthFailure(AuthFailure::ALLOWLIST_CHECK_FAILED)); } ClearActiveDirectoryState(); ClearRecordedNames(); } void ExistingUserController::PolicyLoadFailed() { ShowError(SigninError::kOwnerKeyLost, std::string()); PerformLoginFinishedActions(false /* don't start auto login timer */); ClearActiveDirectoryState(); ClearRecordedNames(); } //////////////////////////////////////////////////////////////////////////////// // ExistingUserController, private: void ExistingUserController::DeviceSettingsChanged() { // If login was already completed, we should avoid any signin screen // transitions, see http://crbug.com/461604 for example. if (!profile_prepared_ && GetLoginDisplay() && !GetLoginDisplay()->is_signin_completed()) { // Signed settings or user list changed. Notify views and update them. const user_manager::UserList& users = UserAddingScreen::Get()->IsRunning() ? user_manager::UserManager::Get()->GetUsersAllowedForMultiProfile() : user_manager::UserManager::Get()->GetUsers(); UpdateLoginDisplay(users); ConfigureAutoLogin(); } } void ExistingUserController::AddLoginStatusConsumer( AuthStatusConsumer* consumer) { auth_status_consumers_.AddObserver(consumer); } void ExistingUserController::RemoveLoginStatusConsumer( const AuthStatusConsumer* consumer) { auth_status_consumers_.RemoveObserver(consumer); } LoginPerformer::AuthorizationMode ExistingUserController::auth_mode() const { if (login_performer_) return login_performer_->auth_mode(); return auth_mode_; } bool ExistingUserController::password_changed() const { if (login_performer_) return login_performer_->password_changed(); return password_changed_; } // static user_manager::UserList ExistingUserController::ExtractLoginUsers( const user_manager::UserList& users) { bool show_users_on_signin; CrosSettings::Get()->GetBoolean(kAccountsPrefShowUserNamesOnSignIn, &show_users_on_signin); user_manager::UserList filtered_users; for (auto* user : users) { // Skip kiosk apps for login screen user list. Kiosk apps as pods (aka new // kiosk UI) is currently disabled and it gets the apps directly from // KioskAppManager, ArcKioskAppManager and WebKioskAppManager. if (user->IsKioskType()) continue; const bool meets_allowlist_requirements = !user->HasGaiaAccount() || user_manager::UserManager::Get()->IsGaiaUserAllowed(*user); // Public session accounts are always shown on login screen. const bool meets_show_users_requirements = show_users_on_signin || user->GetType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT; if (meets_allowlist_requirements && meets_show_users_requirements) filtered_users.push_back(user); } return filtered_users; } void ExistingUserController::LoginAsGuest() { PerformPreLoginActions(UserContext(user_manager::USER_TYPE_GUEST, user_manager::GuestAccountId())); bool allow_guest = user_manager::UserManager::Get()->IsGuestSessionAllowed(); if (!allow_guest) { // Disallowed. The UI should normally not show the guest session button. LOG(ERROR) << "Guest login attempt when guest mode is disallowed."; PerformLoginFinishedActions(true /* start auto login timer */); ClearRecordedNames(); return; } // Only one instance of LoginPerformer should exist at a time. login_performer_.reset(nullptr); login_performer_ = std::make_unique<ChromeLoginPerformer>(this); login_performer_->LoginOffTheRecord(); SendAccessibilityAlert( l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNIN_OFFRECORD)); } void ExistingUserController::LoginAsPublicSession( const UserContext& user_context) { VLOG(2) << "LoginAsPublicSession"; PerformPreLoginActions(user_context); // If there is no public account with the given user ID, logging in is not // possible. const user_manager::User* user = user_manager::UserManager::Get()->FindUser(user_context.GetAccountId()); if (!user || user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) { VLOG(2) << "Public session user not found"; PerformLoginFinishedActions(true /* start auto login timer */); return; } // Public session login will fail if attempted if the associated policy store // is not initialized - wait for the policy store load before starting the // auto-login timer. policy::CloudPolicyStore* policy_store = g_browser_process->platform_part() ->browser_policy_connector_ash() ->GetDeviceLocalAccountPolicyService() ->GetBrokerForUser(user->GetAccountId().GetUserEmail()) ->core() ->store(); if (!policy_store->is_initialized()) { VLOG(2) << "Public session policy store not yet initialized"; policy_store_waiter_ = std::make_unique<PolicyStoreLoadWaiter>( policy_store, base::BindOnce( &ExistingUserController::LoginAsPublicSessionWithPolicyStoreReady, base::Unretained(this), user_context)); return; } LoginAsPublicSessionWithPolicyStoreReady(user_context); } void ExistingUserController::LoginAsPublicSessionWithPolicyStoreReady( const UserContext& user_context) { VLOG(2) << "LoginAsPublicSessionWithPolicyStoreReady"; policy_store_waiter_.reset(); UserContext new_user_context = user_context; std::string locale = user_context.GetPublicSessionLocale(); if (locale.empty()) { // When performing auto-login, no locale is chosen by the user. Check // whether a list of recommended locales was set by policy. If so, use its // first entry. Otherwise, `locale` will remain blank, indicating that the // public session should use the current UI locale. const policy::PolicyMap::Entry* entry = g_browser_process->platform_part() ->browser_policy_connector_ash() ->GetDeviceLocalAccountPolicyService() ->GetBrokerForUser(user_context.GetAccountId().GetUserEmail()) ->core() ->store() ->policy_map() .Get(policy::key::kSessionLocales); if (entry && entry->level == policy::POLICY_LEVEL_RECOMMENDED && entry->value() && entry->value()->is_list()) { base::Value::ConstListView list = entry->value()->GetListDeprecated(); if (!list.empty() && list[0].is_string()) { locale = list[0].GetString(); new_user_context.SetPublicSessionLocale(locale); } } } if (!locale.empty() && new_user_context.GetPublicSessionInputMethod().empty()) { // When `locale` is set, a suitable keyboard layout should be chosen. In // most cases, this will already be the case because the UI shows a list of // keyboard layouts suitable for the `locale` and ensures that one of them // us selected. However, it is still possible that `locale` is set but no // keyboard layout was chosen: // * The list of keyboard layouts is updated asynchronously. If the user // enters the public session before the list of keyboard layouts for the // `locale` has been retrieved, the UI will indicate that no keyboard // layout was chosen. // * During auto-login, the `locale` is set in this method and a suitable // keyboard layout must be chosen next. // // The list of suitable keyboard layouts is constructed asynchronously. Once // it has been retrieved, `SetPublicSessionKeyboardLayoutAndLogin` will // select the first layout from the list and continue login. VLOG(2) << "Requesting keyboard layouts for public session"; GetKeyboardLayoutsForLocale( base::BindOnce( &ExistingUserController::SetPublicSessionKeyboardLayoutAndLogin, weak_factory_.GetWeakPtr(), new_user_context), locale, input_method::InputMethodManager::Get()); return; } // The user chose a locale and a suitable keyboard layout or left both unset. // Login can continue immediately. LoginAsPublicSessionInternal(new_user_context); } void ExistingUserController::LoginAsKioskApp(KioskAppId kiosk_app_id) { GetLoginDisplayHost()->StartKiosk(kiosk_app_id, /*auto_launch*/ false); } void ExistingUserController::ConfigureAutoLogin() { std::string auto_login_account_id; cros_settings_->GetString(kAccountsPrefDeviceLocalAccountAutoLoginId, &auto_login_account_id); VLOG(2) << "Autologin account in prefs: " << auto_login_account_id; const std::vector<policy::DeviceLocalAccount> device_local_accounts = policy::GetDeviceLocalAccounts(cros_settings_); const bool show_update_required_screen = IsUpdateRequiredDeadlineReached(); auto* data_snapshotd_manager = arc::data_snapshotd::ArcDataSnapshotdManager::Get(); bool is_arc_data_snapshot_autologin = (data_snapshotd_manager && data_snapshotd_manager->IsAutoLoginConfigured()); if (is_arc_data_snapshot_autologin) { public_session_auto_login_account_id_ = GetArcDataSnapshotAutoLoginAccountId(device_local_accounts); } else { public_session_auto_login_account_id_ = GetPublicSessionAutoLoginAccountId( device_local_accounts, auto_login_account_id); } const user_manager::User* public_session_user = user_manager::UserManager::Get()->FindUser( public_session_auto_login_account_id_); if (!public_session_user || public_session_user->GetType() != user_manager::USER_TYPE_PUBLIC_ACCOUNT) { VLOG(2) << "PublicSession autologin user not found"; public_session_auto_login_account_id_ = EmptyAccountId(); } if (is_arc_data_snapshot_autologin || !cros_settings_->GetInteger(kAccountsPrefDeviceLocalAccountAutoLoginDelay, &auto_login_delay_)) { auto_login_delay_ = 0; } // TODO(crbug.com/1105387): Part of initial screen logic. if (show_update_required_screen) { // Update required screen overrides public session auto login. StopAutoLoginTimer(); GetLoginDisplayHost()->StartWizard(UpdateRequiredView::kScreenId); } else if (public_session_auto_login_account_id_.is_valid()) { StartAutoLoginTimer(); } else { StopAutoLoginTimer(); } } void ExistingUserController::ResetAutoLoginTimer() { // Only restart the auto-login timer if it's already running. if (auto_login_timer_ && auto_login_timer_->IsRunning()) { StopAutoLoginTimer(); StartAutoLoginTimer(); } } void ExistingUserController::OnPublicSessionAutoLoginTimerFire() { CHECK(public_session_auto_login_account_id_.is_valid()); VLOG(2) << "Public session autologin fired"; SigninSpecifics signin_specifics; signin_specifics.is_auto_login = true; Login(UserContext(user_manager::USER_TYPE_PUBLIC_ACCOUNT, public_session_auto_login_account_id_), signin_specifics); } void ExistingUserController::StopAutoLoginTimer() { VLOG(2) << "Stopping autologin timer that is " << (auto_login_timer_ ? "" : "not ") << "running"; if (auto_login_timer_) auto_login_timer_->Stop(); } void ExistingUserController::CancelPasswordChangedFlow() { login_performer_.reset(nullptr); ClearActiveDirectoryState(); PerformLoginFinishedActions(true /* start auto login timer */); } void ExistingUserController::MigrateUserData(const std::string& old_password) { // LoginPerformer instance has state of the user so it should exist. if (login_performer_.get()) { VLOG(1) << "Migrate the existing cryptohome to new password."; login_performer_->RecoverEncryptedData(old_password); } } void ExistingUserController::ResyncUserData() { // LoginPerformer instance has state of the user so it should exist. if (login_performer_.get()) { VLOG(1) << "Create a new cryptohome and resync user data."; login_performer_->ResyncEncryptedData(); } } void ExistingUserController::StartAutoLoginTimer() { if (is_login_in_progress_ || !public_session_auto_login_account_id_.is_valid()) { VLOG(2) << "Not starting autologin timer, because:"; VLOG_IF(2, is_login_in_progress_) << "* Login is in process;"; VLOG_IF(2, !public_session_auto_login_account_id_.is_valid()) << "* No valid autologin account;"; return; } VLOG(2) << "Starting autologin timer with delay: " << auto_login_delay_; if (auto_login_timer_ && auto_login_timer_->IsRunning()) { StopAutoLoginTimer(); } // Block auto-login flow until ArcDataSnapshotdManager is ready to enter an // auto-login session. // ArcDataSnapshotdManager stores a reset auto-login callback to fire it once // it is ready. auto* data_snapshotd_manager = arc::data_snapshotd::ArcDataSnapshotdManager::Get(); if (data_snapshotd_manager && !data_snapshotd_manager->IsAutoLoginAllowed() && data_snapshotd_manager->IsAutoLoginConfigured()) { data_snapshotd_manager->set_reset_autologin_callback( base::BindOnce(&ExistingUserController::StartAutoLoginTimer, weak_factory_.GetWeakPtr())); return; } // Start the auto-login timer. if (!auto_login_timer_) auto_login_timer_ = std::make_unique<base::OneShotTimer>(); VLOG(2) << "Public session autologin will be fired in " << auto_login_delay_ << "ms"; auto_login_timer_->Start( FROM_HERE, base::Milliseconds(auto_login_delay_), base::BindOnce(&ExistingUserController::OnPublicSessionAutoLoginTimerFire, weak_factory_.GetWeakPtr())); } void ExistingUserController::ShowError(SigninError error, const std::string& details) { VLOG(1) << details; auto* signin_ui = GetLoginDisplayHost()->GetSigninUI(); if (!signin_ui) { DCHECK(session_manager::SessionManager::Get()->IsInSecondaryLoginScreen()); // Silently ignore the error on the secondary login screen. The screen is // being deprecated anyway. return; } signin_ui->ShowSigninError(error, details); } void ExistingUserController::SendAccessibilityAlert( const std::string& alert_text) { AutomationManagerAura::GetInstance()->HandleAlert(alert_text); } void ExistingUserController::SetPublicSessionKeyboardLayoutAndLogin( const UserContext& user_context, std::unique_ptr<base::ListValue> keyboard_layouts) { UserContext new_user_context = user_context; std::string keyboard_layout; for (size_t i = 0; i < keyboard_layouts->GetListDeprecated().size(); ++i) { base::Value& entry = keyboard_layouts->GetListDeprecated()[i]; if (entry.FindBoolKey("selected").value_or(false)) { const std::string* keyboard_layout_ptr = entry.FindStringKey("value"); if (keyboard_layout_ptr) keyboard_layout = *keyboard_layout_ptr; break; } } DCHECK(!keyboard_layout.empty()); new_user_context.SetPublicSessionInputMethod(keyboard_layout); LoginAsPublicSessionInternal(new_user_context); } void ExistingUserController::LoginAsPublicSessionInternal( const UserContext& user_context) { // Only one instance of LoginPerformer should exist at a time. VLOG(2) << "LoginAsPublicSessionInternal for user: " << user_context.GetAccountId(); login_performer_.reset(nullptr); login_performer_ = std::make_unique<ChromeLoginPerformer>(this); login_performer_->LoginAsPublicSession(user_context); SendAccessibilityAlert( l10n_util::GetStringUTF8(IDS_CHROMEOS_ACC_LOGIN_SIGNIN_PUBLIC_ACCOUNT)); } void ExistingUserController::PerformPreLoginActions( const UserContext& user_context) { // Disable clicking on other windows and status tray. GetLoginDisplay()->SetUIEnabled(false); if (last_login_attempt_account_id_ != user_context.GetAccountId()) { last_login_attempt_account_id_ = user_context.GetAccountId(); num_login_attempts_ = 0; } num_login_attempts_++; // Stop the auto-login timer when attempting login. StopAutoLoginTimer(); } void ExistingUserController::PerformLoginFinishedActions( bool start_auto_login_timer) { is_login_in_progress_ = false; // Reenable clicking on other windows and status area. GetLoginDisplay()->SetUIEnabled(true); if (start_auto_login_timer) StartAutoLoginTimer(); } void ExistingUserController::ContinueLoginWhenCryptohomeAvailable( base::OnceClosure continuation, bool service_is_available) { if (!service_is_available) { LOG(ERROR) << "Cryptohome service is not available"; OnAuthFailure(AuthFailure(AuthFailure::COULD_NOT_MOUNT_CRYPTOHOME)); return; } std::move(continuation).Run(); } void ExistingUserController::ContinueLoginIfDeviceNotDisabled( base::OnceClosure continuation) { // Disable clicking on other windows and status tray. GetLoginDisplay()->SetUIEnabled(false); // Stop the auto-login timer. StopAutoLoginTimer(); auto split_continuation = base::SplitOnceCallback(std::move(continuation)); // Wait for the `cros_settings_` to become either trusted or permanently // untrusted. const CrosSettingsProvider::TrustedStatus status = cros_settings_->PrepareTrustedValues(base::BindOnce( &ExistingUserController::ContinueLoginIfDeviceNotDisabled, weak_factory_.GetWeakPtr(), std::move(split_continuation.first))); if (status == CrosSettingsProvider::TEMPORARILY_UNTRUSTED) return; if (status == CrosSettingsProvider::PERMANENTLY_UNTRUSTED) { // If the `cros_settings_` are permanently untrusted, show an error message // and refuse to log in. ++num_login_attempts_; ShowError(SigninError::kOwnerKeyLost, /*details=*/std::string()); // Re-enable clicking on other windows and the status area. Do not start the // auto-login timer though. Without trusted `cros_settings_`, no auto-login // can succeed. GetLoginDisplay()->SetUIEnabled(true); return; } if (system::DeviceDisablingManager::IsDeviceDisabledDuringNormalOperation()) { // If the device is disabled, bail out. A device disabled screen will be // shown by the DeviceDisablingManager. // Re-enable clicking on other windows and the status area. Do not start the // auto-login timer though. On a disabled device, no auto-login can succeed. GetLoginDisplay()->SetUIEnabled(true); return; } UserDataAuthClient::Get()->WaitForServiceToBeAvailable(base::BindOnce( &ExistingUserController::ContinueLoginWhenCryptohomeAvailable, weak_factory_.GetWeakPtr(), std::move(split_continuation.second))); } void ExistingUserController::DoCompleteLogin( const UserContext& user_context_wo_device_id) { UserContext user_context = user_context_wo_device_id; user_manager::KnownUser known_user(g_browser_process->local_state()); std::string device_id = known_user.GetDeviceId(user_context.GetAccountId()); if (device_id.empty()) { bool is_ephemeral = ChromeUserManager::Get()->AreEphemeralUsersEnabled() && user_context.GetAccountId() != ChromeUserManager::Get()->GetOwnerAccountId(); device_id = GenerateSigninScopedDeviceId(is_ephemeral); } user_context.SetDeviceId(device_id); const std::string& gaps_cookie = user_context.GetGAPSCookie(); if (!gaps_cookie.empty()) { known_user.SetGAPSCookie(user_context.GetAccountId(), gaps_cookie); } PerformPreLoginActions(user_context); if (timer_init_) { base::UmaHistogramMediumTimes("Login.PromptToCompleteLoginTime", timer_init_->Elapsed()); timer_init_.reset(); } // Fetch OAuth2 tokens if we have an auth code. if (!user_context.GetAuthCode().empty()) { oauth2_token_initializer_ = std::make_unique<OAuth2TokenInitializer>(); oauth2_token_initializer_->Start( user_context, base::BindOnce(&ExistingUserController::OnOAuth2TokensFetched, weak_factory_.GetWeakPtr())); return; } PerformLogin(user_context, LoginPerformer::AuthorizationMode::kExternal); } void ExistingUserController::DoLogin(const UserContext& user_context, const SigninSpecifics& specifics) { last_login_attempt_was_auto_login_ = specifics.is_auto_login; VLOG(2) << "DoLogin with a user type: " << user_context.GetUserType(); if (user_context.GetUserType() == user_manager::USER_TYPE_GUEST) { if (!specifics.guest_mode_url.empty()) { guest_mode_url_ = GURL(specifics.guest_mode_url); if (specifics.guest_mode_url_append_locale) guest_mode_url_ = google_util::AppendGoogleLocaleParam( guest_mode_url_, g_browser_process->GetApplicationLocale()); } LoginAsGuest(); return; } if (user_context.GetUserType() == user_manager::USER_TYPE_PUBLIC_ACCOUNT) { LoginAsPublicSession(user_context); return; } if (user_context.GetUserType() == user_manager::USER_TYPE_KIOSK_APP) { LoginAsKioskApp( KioskAppId::ForChromeApp(user_context.GetAccountId().GetUserEmail())); return; } if (user_context.GetUserType() == user_manager::USER_TYPE_ARC_KIOSK_APP) { LoginAsKioskApp(KioskAppId::ForArcApp(user_context.GetAccountId())); return; } if (user_context.GetUserType() == user_manager::USER_TYPE_WEB_KIOSK_APP) { LoginAsKioskApp(KioskAppId::ForWebApp(user_context.GetAccountId())); return; } // Regular user or supervised user login. if (!user_context.HasCredentials()) { // If credentials are missing, refuse to log in. // Ensure WebUI is loaded to allow security token dialog to pop up. GetLoginDisplayHost()->GetWizardController(); // Reenable clicking on other windows and status area. GetLoginDisplay()->SetUIEnabled(true); // Restart the auto-login timer. StartAutoLoginTimer(); } PerformPreLoginActions(user_context); PerformLogin(user_context, LoginPerformer::AuthorizationMode::kInternal); } void ExistingUserController::OnOAuth2TokensFetched( bool success, const UserContext& user_context) { if (!success) { LOG(ERROR) << "OAuth2 token fetch failed."; OnAuthFailure(AuthFailure(AuthFailure::FAILED_TO_INITIALIZE_TOKEN)); return; } PerformLogin(user_context, LoginPerformer::AuthorizationMode::kExternal); } void ExistingUserController::ClearRecordedNames() { display_email_.clear(); display_name_.clear(); given_name_.clear(); } void ExistingUserController::ClearActiveDirectoryState() { if (last_login_attempt_account_id_.GetAccountType() != AccountType::ACTIVE_DIRECTORY) { return; } // Clear authpolicyd state so nothing could leak from one user to another. AuthPolicyHelper::Restart(); } AccountId ExistingUserController::GetLastLoginAttemptAccountId() const { return last_login_attempt_account_id_; } } // namespace ash
chromium/chromium
chrome/browser/ash/login/existing_user_controller.cc
C++
bsd-3-clause
72,509
import STOCK_ITEM from './stock_item' export default { stock_items: [STOCK_ITEM], count: 25, current_page: 1, pages: 5 }
ayb/spree
guides/src/data/stock_items.js
JavaScript
bsd-3-clause
130
--- id: bad87fee1348bd9aec908854 title: Label Bootstrap Wells challengeType: 0 videoUrl: '' localeTitle: 标签Bootstrap Wells --- ## Description <section id="description">为了清楚起见,我们用它们的ID标记我们的两个井。在左侧井的上方,在其<code>col-xs-6</code> <code>div</code>元素内,添加一个带有文本<code>#left-well</code>的<code>h4</code>元素。在右侧井上方,在其<code>col-xs-6</code> <code>div</code>元素内,添加一个带有文本<code>#right-well</code>的<code>h4</code>元素。 </section> ## Instructions <section id="instructions"> </section> ## Tests <section id='tests'> ```yml tests: - text: 在每个<code>&lt;div class=&quot;col-xs-6&quot;&gt;</code>元素中添加一个<code>h4</code>元素。 testString: 'assert($(".col-xs-6").children("h4") && $(".col-xs-6").children("h4").length > 1, "Add an <code>h4</code> element to each of your <code>&#60;div class="col-xs-6"&#62;</code> elements.");' - text: '一个<code>h4</code>元素应该有<code>#left-well</code>文本。' testString: 'assert(new RegExp("#left-well","gi").test($("h4").text()), "One <code>h4</code> element should have the text <code>#left-well</code>.");' - text: '一个<code>h4</code>元素应该有<code>#right-well</code>文本。' testString: 'assert(new RegExp("#right-well","gi").test($("h4").text()), "One <code>h4</code> element should have the text <code>#right-well</code>.");' - text: 确保所有<code>h4</code>元素都有结束标记。 testString: 'assert(code.match(/<\/h4>/g) && code.match(/<h4/g) && code.match(/<\/h4>/g).length === code.match(/<h4/g).length, "Make sure all your <code>h4</code> elements have closing tags.");' ``` </section> ## Challenge Seed <section id='challengeSeed'> <div id='html-seed'> ```html <div class="container-fluid"> <h3 class="text-primary text-center">jQuery Playground</h3> <div class="row"> <div class="col-xs-6"> <div class="well" id="left-well"> <button class="btn btn-default target"></button> <button class="btn btn-default target"></button> <button class="btn btn-default target"></button> </div> </div> <div class="col-xs-6"> <div class="well" id="right-well"> <button class="btn btn-default target"></button> <button class="btn btn-default target"></button> <button class="btn btn-default target"></button> </div> </div> </div> </div> ``` </div> </section> ## Solution <section id='solution'> ```js // solution required ``` </section>
otavioarc/freeCodeCamp
curriculum/challenges/chinese/03-front-end-libraries/bootstrap/label-bootstrap-wells.chinese.md
Markdown
bsd-3-clause
2,579
from __future__ import absolute_import import six from django.core.urlresolvers import reverse from sentry.models import SavedSearch, SavedSearchUserDefault from sentry.testutils import APITestCase class ProjectSearchListTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = self.create_team() project1 = self.create_project(team=team, name='foo') project2 = self.create_project(team=team, name='bar') SavedSearch.objects.filter(project=project1).delete() SavedSearch.objects.filter(project=project2).delete() search1 = SavedSearch.objects.create( project=project1, name='bar', query='', ) search2 = SavedSearch.objects.create( project=project1, name='foo', query='', ) SavedSearch.objects.create( project=project2, name='foo', query='', ) url = reverse('sentry-api-0-project-searches', kwargs={ 'organization_slug': project1.organization.slug, 'project_slug': project1.slug, }) response = self.client.get(url, format='json') assert response.status_code == 200, response.content assert len(response.data) == 2 assert response.data[0]['id'] == six.text_type(search1.id) assert response.data[1]['id'] == six.text_type(search2.id) class ProjectSearchCreateTest(APITestCase): def test_simple(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo') url = reverse('sentry-api-0-project-searches', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, }) response = self.client.post(url, data={ 'name': 'ignored', 'query': 'is:ignored' }) assert response.status_code == 201, response.content assert response.data['id'] search = SavedSearch.objects.get( project=project, id=response.data['id'], ) assert not search.is_default def test_duplicate(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo') SavedSearch.objects.create(name='ignored', project=project, query='') url = reverse('sentry-api-0-project-searches', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, }) response = self.client.post(url, data={ 'name': 'ignored', 'query': 'is:ignored' }) assert response.status_code == 400, response.content def test_default(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo') url = reverse('sentry-api-0-project-searches', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, }) response = self.client.post(url, data={ 'name': 'ignored', 'query': 'is:ignored', 'isDefault': True, }) assert response.status_code == 201, response.content assert response.data['id'] search = SavedSearch.objects.get( project=project, id=response.data['id'], ) assert search.is_default assert not SavedSearchUserDefault.objects.filter( project=project, user=self.user, savedsearch=search, ).exists() def test_user_default(self): self.login_as(user=self.user) team = self.create_team() project = self.create_project(team=team, name='foo') url = reverse('sentry-api-0-project-searches', kwargs={ 'organization_slug': project.organization.slug, 'project_slug': project.slug, }) response = self.client.post(url, data={ 'name': 'ignored', 'query': 'is:ignored', 'isUserDefault': True, }) assert response.status_code == 201, response.content assert response.data['id'] search = SavedSearch.objects.get( project=project, id=response.data['id'], ) assert not search.is_default userdefault = SavedSearchUserDefault.objects.get( project=project, user=self.user, ) assert userdefault.savedsearch == search
JackDanger/sentry
tests/sentry/api/endpoints/test_project_searches.py
Python
bsd-3-clause
4,665
define("ace/snippets/textile",["require","exports","module"], function(require, exports, module) { "use strict"; exports.snippetText = "# Jekyll post header\n\ snippet header\n\ ---\n\ title: ${1:title}\n\ layout: post\n\ date: ${2:date} ${3:hour:minute:second} -05:00\n\ ---\n\ \n\ # Image\n\ snippet img\n\ !${1:url}(${2:title}):${3:link}!\n\ \n\ # Table\n\ snippet |\n\ |${1}|${2}\n\ \n\ # Link\n\ snippet link\n\ \"${1:link text}\":${2:url}\n\ \n\ # Acronym\n\ snippet (\n\ (${1:Expand acronym})${2}\n\ \n\ # Footnote\n\ snippet fn\n\ [${1:ref number}] ${3}\n\ \n\ fn$1. ${2:footnote}\n\ \n\ "; exports.scope = "textile"; });
nikste/visualizationDemo
zeppelin-web/bower_components/ace-builds/src/snippets/textile.js
JavaScript
apache-2.0
644
using System; using System.Collections.Generic; using Palaso.Data; using NUnit.Framework; namespace Palaso.Tests.Data { [TestFixture] public class DictionaryEqualityComparerTests { private DictionaryEqualityComparer<string, string> _comparer; private Dictionary<string, string> _x; private Dictionary<string, string> _y; [SetUp] public void SetUp() { _comparer = new DictionaryEqualityComparer<string, string>(); _x = new Dictionary<string, string>(); _y = new Dictionary<string, string>(); } [Test] public void Equals_xNullyNotNull_false() { _x = null; _y.Add("0", "Zero"); Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xNotNullyNull_false() { _x.Add("0", "Zero"); _y = null; Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xMoreEntriesThany_false() { _x.Add("0", "Zero"); Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xFewerEntriesThany_false() { _y.Add("0", "Zero"); Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xKeyIsDifferentThany_false() { _x.Add("0", "Zero"); _y.Add("1", "Zero"); Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xValueIsDifferentThany_false() { _x.Add("0", "Zero"); _y.Add("0", "One"); Assert.IsFalse(_comparer.Equals(_x, _y)); } [Test] public void Equals_xHasSameLengthKeysAndValuesAsy_true() { _x.Add("0", "Zero"); _y.Add("0", "Zero"); Assert.IsTrue(_comparer.Equals(_x, _y)); } [Test] public void Equals_xAndyAreBothEmpty_true() { Assert.IsTrue(_comparer.Equals(_x, _y)); } [Test] public void Equals_xIsNullyIsNull_true() { _x = null; _y = null; Assert.IsTrue(_comparer.Equals(_x, _y)); } [Test] public void GetHashCode_Null_Throws() { var comparer = new DictionaryEqualityComparer<string, string>(); Assert.Throws<ArgumentNullException>( () => comparer.GetHashCode(null)); } [Test] public void GetHashCode_TwoDictionariesAreEqual_ReturnSameHashCodes() { var reference = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}; var other = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}; var comparer = new DictionaryEqualityComparer<string, string>(); Assert.AreEqual(comparer.GetHashCode(reference), comparer.GetHashCode(other)); } [Test] public void GetHashCode_TwoDictionariesHaveDifferentLength_ReturnDifferentHashCodes() { var reference = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}; var other = new Dictionary<string, string> {{"key1", "value1"}}; var comparer = new DictionaryEqualityComparer<string, string>(); Assert.AreNotEqual(comparer.GetHashCode(reference), comparer.GetHashCode(other)); } [Test] public void GetHashCode_TwoDictionariesHaveDifferentKey_ReturnDifferentHashCodes() { var reference = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}; var other = new Dictionary<string, string> {{"key1", "value1"}, {"key3", "value2"}}; var comparer = new DictionaryEqualityComparer<string, string>(); Assert.AreNotEqual(comparer.GetHashCode(reference), comparer.GetHashCode(other)); } [Test] public void GetHashCode_TwoDictionariesHaveDifferentValue_ReturnDifferentHashCodes() { var reference = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value2"}}; var other = new Dictionary<string, string> {{"key1", "value1"}, {"key2", "value3"}}; var comparer = new DictionaryEqualityComparer<string, string>(); Assert.AreNotEqual(comparer.GetHashCode(reference), comparer.GetHashCode(other)); } } }
darcywong00/libpalaso
Palaso.Tests/Data/DictionaryEqualityComparerTests.cs
C#
mit
3,736
<?xml version="1.0" ?><!DOCTYPE TS><TS language="lt" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About Potcoin</source> <translation>Apie Potcoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;Potcoin&lt;/b&gt; version</source> <translation>&lt;b&gt;Potcoin&lt;/b&gt; versija</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young ([email protected]) and UPnP software written by Thomas Bernard.</source> <translation>Tai eksperimentinė programa. Platinama pagal MIT/X11 licenciją, kurią rasite faile COPYING arba http://www.opensource.org/licenses/mit-license.php. Šiame produkte yra OpenSSL projekto kuriamas OpenSSL Toolkit (http://www.openssl.org/), Eric Young parašyta kriptografinė programinė įranga bei Thomas Bernard sukurta UPnP programinė įranga.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The Potcoin developers</source> <translation type="unfinished"/> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Adresų knygelė</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Spragtelėkite, kad pakeistumėte adresą arba žymę</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Sukurti naują adresą</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Kopijuoti esamą adresą į mainų atmintį</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Naujas adresas</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your Potcoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Tai yra jūsų Potcoin adresai mokėjimų gavimui. Galite duoti skirtingus adresus atskiriems siuntėjams, kad galėtumėte sekti, kas jums moka.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Kopijuoti adresą</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Rodyti &amp;QR kodą</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a Potcoin address</source> <translation>Pasirašykite žinutę, kad įrodytume, jog esate Potcoin adreso savininkas</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Registruoti praneši&amp;mą</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified Potcoin address</source> <translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas Potcoin adresas</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Tikrinti žinutę</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>&amp;Trinti</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your Potcoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Kopijuoti ž&amp;ymę</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Keisti</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation type="unfinished"/> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Eksportuoti adresų knygelės duomenis</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais išskirtas failas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Nepavyko įrašyti į failą %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(nėra žymės)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Slaptafrazės dialogas</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Įvesti slaptafrazę</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nauja slaptafrazė</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Pakartokite naują slaptafrazę</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Įveskite naują piniginės slaptafrazę.&lt;br/&gt;Prašome naudoti slaptafrazę iš &lt;b&gt; 10 ar daugiau atsitiktinių simbolių&lt;/b&gt; arba &lt;b&gt;aštuonių ar daugiau žodžių&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Užšifruoti piniginę</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai atrakinti.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Atrakinti piniginę</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>Ši operacija reikalauja jūsų piniginės slaptafrazės jai iššifruoti.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Iššifruoti piniginę</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Pakeisti slaptafrazę</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Įveskite seną ir naują piniginės slaptafrazes.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Patvirtinkite piniginės užšifravimą</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR POTCOINS&lt;/b&gt;!</source> <translation>Dėmesio: jei užšifruosite savo piniginę ir pamesite slaptafrazę, jūs&lt;b&gt;PRARASITE VISUS SAVO LITECOINUS&lt;/b&gt;! </translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Ar tikrai norite šifruoti savo piniginę?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation type="unfinished"/> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Įspėjimas: įjungtas Caps Lock klavišas!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Piniginė užšifruota</translation> </message> <message> <location line="-56"/> <source>Potcoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your potcoins from being stolen by malware infecting your computer.</source> <translation>Potcoin dabar užsidarys šifravimo proceso pabaigai. Atminkite, kad piniginės šifravimas negali pilnai apsaugoti potcoinų vagysčių kai tinkle esančios kenkėjiškos programos patenka į jūsų kompiuterį.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>Nepavyko užšifruoti piniginę</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>Dėl vidinės klaidos nepavyko užšifruoti piniginę.Piniginė neužšifruota.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>Įvestos slaptafrazės nesutampa.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>Nepavyko atrakinti piniginę</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>Neteisingai įvestas slaptažodis piniginės iššifravimui.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>Nepavyko iššifruoti piniginės</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>Piniginės slaptažodis sėkmingai pakeistas.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Pasirašyti ži&amp;nutę...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sinchronizavimas su tinklu ...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>&amp;Apžvalga</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Rodyti piniginės bendrą apžvalgą</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Sandoriai</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Apžvelgti sandorių istoriją</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Redaguoti išsaugotus adresus bei žymes</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Parodyti adresų sąraša mokėjimams gauti</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>&amp;Išeiti</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Išjungti programą</translation> </message> <message> <location line="+4"/> <source>Show information about Potcoin</source> <translation>Rodyti informaciją apie Potcoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Apie &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Rodyti informaciją apie Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Parinktys...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>&amp;Užšifruoti piniginę...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Backup piniginę...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>&amp;Keisti slaptafrazę...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation type="unfinished"/> </message> <message> <location line="-347"/> <source>Send coins to a Potcoin address</source> <translation>Siųsti monetas Potcoin adresui</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for Potcoin</source> <translation>Keisti potcoin konfigūracijos galimybes</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Daryti piniginės atsarginę kopiją</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Pakeisti slaptafrazę naudojamą piniginės užšifravimui</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>&amp;Derinimo langas</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Atverti derinimo ir diagnostikos konsolę</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Tikrinti žinutę...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>Potcoin</source> <translation>Potcoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>&amp;About Potcoin</source> <translation>&amp;Apie Potcoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>&amp;Rodyti / Slėpti</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Sign messages with your Potcoin addresses to prove you own them</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified Potcoin addresses</source> <translation type="unfinished"/> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Failas</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>&amp;Nustatymai</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>&amp;Pagalba</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Kortelių įrankinė</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> <message> <location line="+47"/> <source>Potcoin client</source> <translation>Potcoin klientas</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to Potcoin network</source> <translation><numerusform>%n Potcoin tinklo aktyvus ryšys</numerusform><numerusform>%n Potcoin tinklo aktyvūs ryšiai</numerusform><numerusform>%n Potcoin tinklo aktyvūs ryšiai</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation type="unfinished"/> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation type="unfinished"/> </message> <message> <location line="+22"/> <source>Error</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation type="unfinished"/> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atnaujinta</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Vejamasi...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Patvirtinti sandorio mokestį</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Sandoris nusiųstas</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Ateinantis sandoris</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Suma: %2 Tipas: %3 Adresas: %4</translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>URI apdorojimas</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid Potcoin address or malformed URI parameters.</source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;atrakinta&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>Piniginė &lt;b&gt;užšifruota&lt;/b&gt; ir šiuo metu &lt;b&gt;užrakinta&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. Potcoin can no longer continue safely and will quit.</source> <translation type="unfinished"/> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Tinklo įspėjimas</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Keisti adresą</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>Ž&amp;ymė</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>Žymė yra susieta su šios adresų knygelęs turiniu</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>&amp;Adresas</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>Adresas yra susietas su šios adresų knygelęs turiniu. Tai gali būti keičiama tik siuntimo adresams.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Naujas gavimo adresas</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Naujas siuntimo adresas</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Keisti gavimo adresą</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Keisti siuntimo adresą</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>Įvestas adresas „%1“ jau yra adresų knygelėje.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid Potcoin address.</source> <translation>Įvestas adresas „%1“ nėra galiojantis Potcoin adresas.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Nepavyko atrakinti piniginės.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Naujo rakto generavimas nepavyko.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>Potcoin-Qt</source> <translation>Potcoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versija</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>komandinės eilutės parametrai</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Naudotoji sąsajos parametrai</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Nustatyti kalbą, pavyzdžiui &quot;lt_LT&quot; (numatyta: sistemos kalba)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Paleisti sumažintą</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation type="unfinished"/> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Parinktys</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Pagrindinės</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation type="unfinished"/> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>&amp;Mokėti sandorio mokestį</translation> </message> <message> <location line="+31"/> <source>Automatically start Potcoin after logging in to the system.</source> <translation>Automatiškai paleisti Bitkoin programą įjungus sistemą.</translation> </message> <message> <location line="+3"/> <source>&amp;Start Potcoin on system login</source> <translation>&amp;Paleisti Potcoin programą su window sistemos paleidimu</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Tinklas</translation> </message> <message> <location line="+6"/> <source>Automatically open the Potcoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Automatiškai atidaryti Potcoin kliento prievadą maršrutizatoriuje. Tai veikia tik tada, kai jūsų maršrutizatorius palaiko UPnP ir ji įjungta.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Persiųsti prievadą naudojant &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the Potcoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Jungtis į Bitkoin tinklą per socks proxy (pvz. jungiantis per Tor)</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>&amp;Jungtis per SOCKS tarpinį serverį:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>Tarpinio serverio &amp;IP:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Tarpinio serverio IP adresas (pvz. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Prievadas:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Tarpinio serverio preivadas (pvz, 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>SOCKS &amp;versija:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Tarpinio serverio SOCKS versija (pvz., 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Langas</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Po programos lango sumažinimo rodyti tik programos ikoną.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;M sumažinti langą bet ne užduočių juostą</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Uždarant langą neuždaryti programos. Kai ši parinktis įjungta, programa bus uždaryta tik pasirinkus meniu komandą Baigti.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>&amp;Sumažinti uždarant</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>&amp;Rodymas</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>Naudotojo sąsajos &amp;kalba:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting Potcoin.</source> <translation>Čia gali būti nustatyta naudotojo sąsajos kalba. Šis nustatymas įsigalios iš naujo paleidus Potcoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Vienetai, kuriais rodyti sumas:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Rodomų ir siunčiamų monetų kiekio matavimo vienetai</translation> </message> <message> <location line="+9"/> <source>Whether to show Potcoin addresses in the transaction list or not.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>&amp;Rodyti adresus sandorių sąraše</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;Gerai</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Atšaukti</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Pritaikyti</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>numatyta</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation type="unfinished"/> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Įspėjimas</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting Potcoin.</source> <translation type="unfinished"/> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>Nurodytas tarpinio serverio adresas negalioja.</translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the Potcoin network after a connection is established, but this process has not completed yet.</source> <translation type="unfinished"/> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Nepatvirtinti:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Piniginė</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Nepribrendę:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation type="unfinished"/> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Naujausi sandoriai&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>Jūsų einamasis balansas</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Iš viso sandorių, įskaitant tuos kurie dar turi būti patvirtinti, ir jie dar nėra įskaičiuotii į einamosios sąskaitos balansą</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation type="unfinished"/> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start potcoin: click-to-pay handler</source> <translation type="unfinished"/> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>QR kodo dialogas</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Prašau išmokėti</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Suma:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Žymė:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Žinutė:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>Į&amp;rašyti kaip...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Klaida, koduojant URI į QR kodą.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>Įvesta suma neteisinga, prašom patikrinti.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation type="unfinished"/> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Įrašyti QR kodą</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>PNG paveikslėliai (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Kliento pavadinimas</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>nėra</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Kliento versija</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informacija</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Naudojama OpenSSL versija</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Paleidimo laikas</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Tinklas</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Prisijungimų kiekis</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Testnete</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Blokų grandinė</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Dabartinis blokų skaičius</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Paskutinio bloko laikas</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Atverti</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Komandinės eilutės parametrai</translation> </message> <message> <location line="+7"/> <source>Show the Potcoin-Qt help message to get a list with possible Potcoin command-line options.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>&amp;Rodyti</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Konsolė</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Kompiliavimo data</translation> </message> <message> <location line="-104"/> <source>Potcoin - Debug window</source> <translation>Potcoin - Derinimo langas</translation> </message> <message> <location line="+25"/> <source>Potcoin Core</source> <translation>Potcoin branduolys</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Derinimo žurnalo failas</translation> </message> <message> <location line="+7"/> <source>Open the Potcoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation type="unfinished"/> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Išvalyti konsolę</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the Potcoin RPC console.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation type="unfinished"/> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Siųsti keliems gavėjams vienu metu</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>&amp;A Pridėti gavėją</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Pašalinti visus sandorio laukus</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Balansas:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Patvirtinti siuntimo veiksmą</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Siųsti</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Patvirtinti monetų siuntimą</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Ar tikrai norite siųsti %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> ir </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>Negaliojantis gavėjo adresas. Patikrinkite.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>Apmokėjimo suma turi būti didesnė nei 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>Suma viršija jūsų balansą.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>Jei pridedame sandorio mokestį %1 bendra suma viršija jūsų balansą.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Rastas adreso dublikatas.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Klaida: sandoris buvo atmestas.Tai gali įvykti, jei kai kurios monetos iš jūsų piniginėje jau buvo panaudotos, pvz. jei naudojote wallet.dat kopiją ir monetos buvo išleistos kopijoje, bet nepažymėtos kaip skirtos išleisti čia.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Forma</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Su&amp;ma:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>Mokėti &amp;gavėjui:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation type="unfinished"/> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Įveskite žymę šiam adresui kad galėtumėte įtraukti ją į adresų knygelę</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Ž&amp;ymė:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Pašalinti šį gavėją</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a Potcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation type="unfinished"/> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>&amp;Pasirašyti žinutę</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation type="unfinished"/> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Pasirinkite adresą iš adresų knygelės</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Įvesti adresą iš mainų atminties</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Įveskite pranešimą, kurį norite pasirašyti čia</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this Potcoin address</source> <translation>Registruotis žinute įrodymuii, kad turite šį adresą</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Išvalyti &amp;viską</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Patikrinti žinutę</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation type="unfinished"/> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified Potcoin address</source> <translation>Patikrinkite žinutę, jog įsitikintumėte, kad ją pasirašė nurodytas Potcoin adresas</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation type="unfinished"/> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a Potcoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Įveskite bitkoinų adresą (pvz. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Spragtelėkite &quot;Registruotis žinutę&quot; tam, kad gauti parašą</translation> </message> <message> <location line="+3"/> <source>Enter Potcoin signature</source> <translation>Įveskite Potcoin parašą</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>Įvestas adresas negalioja.</translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Prašom patikrinti adresą ir bandyti iš naujo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation type="unfinished"/> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>Piniginės atrakinimas atšauktas.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation type="unfinished"/> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Žinutės pasirašymas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Žinutė pasirašyta.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>Nepavyko iškoduoti parašo.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Prašom patikrinti parašą ir bandyti iš naujo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>Parašas neatitinka žinutės.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Žinutės tikrinimas nepavyko.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Žinutė patikrinta.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The Potcoin developers</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[testavimotinklas]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/neprisijungęs</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/nepatvirtintas</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 patvirtinimų</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Būsena</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Šaltinis</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Sugeneruotas</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>Nuo</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Kam</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>savo adresas</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>žymė</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Kreditas</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>nepriimta</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Debitas</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Sandorio mokestis</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Neto suma</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Žinutė</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Komentaras</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>Sandorio ID</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Išgautos monetos turi sulaukti 120 blokų, kol jos gali būti naudojamos. Kai sukūrėte šį bloką, jis buvo transliuojamas tinkle ir turėjo būti įtrauktas į blokų grandinę. Jei nepavyksta patekti į grandinę, bus pakeista į &quot;nepriėmė&quot;, o ne &quot;vartojamas&quot;. Tai kartais gali atsitikti, jei kitas mazgas per keletą sekundžių sukuria bloką po jūsų bloko.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Derinimo informacija</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Sandoris</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation type="unfinished"/> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>tiesa</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>netiesa</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, transliavimas dar nebuvo sėkmingas</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>nežinomas</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Sandorio detelės</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Šis langas sandorio detalų aprašymą</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Suma</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Atidaryta iki %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Atjungta (%1 patvirtinimai)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Nepatvirtintos (%1 iš %2 patvirtinimų)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Patvirtinta (%1 patvirtinimai)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation type="unfinished"><numerusform></numerusform><numerusform></numerusform><numerusform></numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Šis blokas negautas nė vienu iš mazgų ir matomai nepriimtas</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Išgauta bet nepriimta</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Gauta iš</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Siųsta </translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Mokėjimas sau</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>nepasiekiama</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Sandorio būklė. Užvedus pelės žymeklį ant šios srities matysite patvirtinimų skaičių.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Sandorio gavimo data ir laikas</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Sandorio tipas.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Sandorio paskirties adresas</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Suma pridėta ar išskaičiuota iš balanso</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Visi</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Šiandien</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Šią savaitę</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Šį mėnesį</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Paskutinį mėnesį</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Šiais metais</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Intervalas...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Gauta su</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Išsiųsta</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Skirta sau</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Išgauta</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Kita</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Įveskite adresą ar žymę į paiešką</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Minimali suma</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Kopijuoti adresą</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Kopijuoti žymę</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Kopijuoti sumą</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Taisyti žymę</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Rodyti sandėrio detales</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Sandorio duomenų eksportavimas</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Kableliais atskirtų duomenų failas (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Patvirtintas</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipas</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Žymė</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Adresas</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Suma</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Eksportavimo klaida</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Neįmanoma įrašyti į failą %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Grupė:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>skirta</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Siųsti monetas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation type="unfinished"/> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation type="unfinished"/> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation type="unfinished"/> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>Potcoin version</source> <translation>Potcoin versija</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Naudojimas:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or potcoind</source> <translation>Siųsti komandą serveriui arba potcoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Komandų sąrašas</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Suteikti pagalba komandai</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Parinktys:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: potcoin.conf)</source> <translation>Nurodyti konfigūracijos failą (pagal nutylėjimąt: potcoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: potcoind.pid)</source> <translation>Nurodyti pid failą (pagal nutylėjimą: potcoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Nustatyti duomenų aplanką</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation type="unfinished"/> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 4200 or testnet: 14200)</source> <translation>Sujungimo klausymas prijungčiai &lt;port&gt; (pagal nutylėjimą: 4200 arba testnet: 14200)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Palaikyti ne daugiau &lt;n&gt; jungčių kolegoms (pagal nutylėjimą: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation type="unfinished"/> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Atjungimo dėl netinkamo kolegų elgesio riba (pagal nutylėjimą: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Sekundžių kiekis eikiamas palaikyti ryšį dėl lygiarangių nestabilumo (pagal nutylėjimą: 86.400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 42000 or testnet: 42001)</source> <translation>Klausymas JSON-RPC sujungimui prijungčiai &lt;port&gt; (pagal nutylėjimą: 42000 or testnet: 42001)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Priimti komandinę eilutę ir JSON-RPC komandas</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Dirbti fone kaip šešėlyje ir priimti komandas</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Naudoti testavimo tinklą</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation type="unfinished"/> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=potcoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;Potcoin Alert&quot; [email protected] </source> <translation type="unfinished"/> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. Potcoin is probably already running.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation type="unfinished"/> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation type="unfinished"/> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Įspėjimas: -paytxfee yra nustatytas per didelis. Tai sandorio mokestis, kurį turėsite mokėti, jei siųsite sandorį.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong Potcoin will not work properly.</source> <translation>Įspėjimas: Patikrinkite, kad kompiuterio data ir laikas yra teisingi.Jei Jūsų laikrodis neteisingai nustatytas Potcoin, veiks netinkamai.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation type="unfinished"/> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation type="unfinished"/> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Prisijungti tik prie nurodyto mazgo</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation type="unfinished"/> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation type="unfinished"/> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation type="unfinished"/> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation type="unfinished"/> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation type="unfinished"/> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+77"/> <source>Information</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Neteisingas tor adresas: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Maksimalus buferis priėmimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Maksimalus buferis siuntimo sujungimui &lt;n&gt;*1000 bitų (pagal nutylėjimą: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Išvesti papildomą derinimo informaciją. Numanomi visi kiti -debug* parametrai</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Išvesti papildomą tinklo derinimo informaciją</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Prideėti laiko žymę derinimo rezultatams</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the Potcoin Wiki for SSL setup instructions)</source> <translation>SSL opcijos (žr.e Potcoin Wiki for SSL setup instructions)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Siųsti atsekimo/derinimo info į konsolę vietoj debug.log failo</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Siųsti sekimo/derinimo info derintojui</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Nustatyti sujungimo trukmę milisekundėmis (pagal nutylėjimą: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation type="unfinished"/> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation type="unfinished"/> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Bandymas naudoti UPnP struktūra klausymosi prievadui (default: 1 when listening)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation type="unfinished"/> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Vartotojo vardas JSON-RPC jungimuisi</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation type="unfinished"/> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Slaptažodis JSON-RPC sujungimams</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Leisti JSON-RPC tik iš nurodytų IP adresų</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Siųsti komandą mazgui dirbančiam &lt;ip&gt; (pagal nutylėjimą: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation type="unfinished"/> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atnaujinti piniginę į naujausią formatą</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Nustatyti rakto apimties dydį &lt;n&gt; (pagal nutylėjimą: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Ieškoti prarastų piniginės sandorių blokų grandinėje</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Naudoti OpenSSL (https) jungimuisi JSON-RPC </translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Serverio sertifikato failas (pagal nutylėjimą: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Serverio privatus raktas (pagal nutylėjimą: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Priimtini šifrai (pagal nutylėjimą: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Pagelbos žinutė</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Nepavyko susieti šiame kompiuteryje prievado %s (bind returned error %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Jungtis per socks tarpinį serverį</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Leisti DNS paiešką sujungimui ir mazgo pridėjimui</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Užkraunami adresai...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation> wallet.dat pakrovimo klaida, wallet.dat sugadintas</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of Potcoin</source> <translation> wallet.dat pakrovimo klaida, wallet.dat reikalauja naujasnės Potcoin versijos</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart Potcoin to complete</source> <translation>Piniginė turi būti prrašyta: įvykdymui perkraukite Potcoin</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation> wallet.dat pakrovimo klaida</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Neteisingas proxy adresas: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation type="unfinished"/> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation type="unfinished"/> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Neteisinga suma -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Neteisinga suma</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Nepakanka lėšų</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Įkeliamas blokų indeksas...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Pridėti mazgą prie sujungti su and attempt to keep the connection open</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. Potcoin is probably already running.</source> <translation>Nepavyko susieti šiame kompiuteryje prievado %s. Potcoin tikriausiai jau veikia.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Įtraukti mokestį už kB siunčiamiems sandoriams</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Užkraunama piniginė...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation type="unfinished"/> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation type="unfinished"/> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Peržiūra</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Įkėlimas baigtas</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation type="unfinished"/> </message> <message> <location line="-74"/> <source>Error</source> <translation>Klaida</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation type="unfinished"/> </message> </context> </TS>
mkminer/potcoin
src/qt/locale/bitcoin_lt.ts
TypeScript
mit
108,293
// WARNING // // This file has been generated automatically by Xamarin Studio from the outlets and // actions declared in your storyboard file. // Manual changes to this file will not be maintained. // using Foundation; using UIKit; using System; using System.CodeDom.Compiler; namespace KitchenSyncIos { [Register ("HomeScreenController")] partial class HomeScreenController { [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UITableView tableView { get; set; } [Outlet] [GeneratedCode ("iOS Designer", "1.0")] UITextField textField { get; set; } void ReleaseDesignerOutlets () { if (tableView != null) { tableView.Dispose (); tableView = null; } if (textField != null) { textField.Dispose (); textField = null; } } } }
dhartwich1991/mini-hacks
kitchen-sync/xamarin/project/src/workshop_start/KitchenSynciOS/HomeScreenController.designer.cs
C#
mit
774
// THIS FILE IS AUTOMATICALLY GENERATED. DO NOT EDIT. package route53domains import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/internal/protocol/jsonrpc" "github.com/aws/aws-sdk-go/internal/signer/v4" ) // Route53Domains is a client for Amazon Route 53 Domains. type Route53Domains struct { *aws.Service } // Used for custom service initialization logic var initService func(*aws.Service) // Used for custom request initialization logic var initRequest func(*aws.Request) // New returns a new Route53Domains client. func New(config *aws.Config) *Route53Domains { service := &aws.Service{ Config: aws.DefaultConfig.Merge(config), ServiceName: "route53domains", APIVersion: "2014-05-15", JSONVersion: "1.1", TargetPrefix: "Route53Domains_v20140515", } service.Initialize() // Handlers service.Handlers.Sign.PushBack(v4.Sign) service.Handlers.Build.PushBack(jsonrpc.Build) service.Handlers.Unmarshal.PushBack(jsonrpc.Unmarshal) service.Handlers.UnmarshalMeta.PushBack(jsonrpc.UnmarshalMeta) service.Handlers.UnmarshalError.PushBack(jsonrpc.UnmarshalError) // Run custom service initialization if present if initService != nil { initService(service) } return &Route53Domains{service} } // newRequest creates a new request for a Route53Domains operation and runs any // custom request initialization. func (c *Route53Domains) newRequest(op *aws.Operation, params, data interface{}) *aws.Request { req := aws.NewRequest(c.Service, op, params, data) // Run custom request initialization if present if initRequest != nil { initRequest(req) } return req }
michaeldwan/static
vendor/github.com/aws/aws-sdk-go/service/route53domains/service.go
GO
mit
1,623
<?php /* * This file is part of the php-phantomjs. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace JonnyW\PhantomJs\Procedure; use JonnyW\PhantomJs\Cache\CacheInterface; use JonnyW\PhantomJs\Template\TemplateRendererInterface; /** * PHP PhantomJs * * @author Jon Wenmoth <[email protected]> */ class ProcedureCompiler implements ProcedureCompilerInterface { /** * Procedure loader * * @var \JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface * @access protected */ protected $procedureLoader; /** * Procedure validator * * @var \JonnyW\PhantomJs\Procedure\ProcedureValidatorInterface * @access protected */ protected $procedureValidator; /** * Cache handler * * @var \JonnyW\PhantomJs\Cache\CacheInterface * @access protected */ protected $cacheHandler; /** * Renderer * * @var \JonnyW\PhantomJs\Template\TemplateRendererInterface * @access protected */ protected $renderer; /** * Cache enabled * * @var boolean * @access protected */ protected $cacheEnabled; /** * Internal constructor * * @access public * @param \JonnyW\PhantomJs\Procedure\ProcedureLoaderInterface $procedureLoader * @param \JonnyW\PhantomJs\Procedure\ProcedureValidatorInterface $procedureValidator * @param \JonnyW\PhantomJs\Cache\CacheInterface $cacheHandler * @param \JonnyW\PhantomJs\Template\TemplateRendererInterface $renderer */ public function __construct(ProcedureLoaderInterface $procedureLoader, ProcedureValidatorInterface $procedureValidator, CacheInterface $cacheHandler, TemplateRendererInterface $renderer) { $this->procedureLoader = $procedureLoader; $this->procedureValidator = $procedureValidator; $this->cacheHandler = $cacheHandler; $this->renderer = $renderer; $this->cacheEnabled = true; } /** * Compile partials into procedure. * * @access public * @param \JonnyW\PhantomJs\Procedure\ProcedureInterface $procedure * @param \JonnyW\PhantomJs\Procedure\InputInterface $input * @return void */ public function compile(ProcedureInterface $procedure, InputInterface $input) { $cacheKey = sprintf('phantomjs_%s_%s', $input->getType(), md5($procedure->getTemplate())); if ($this->cacheEnabled && $this->cacheHandler->exists($cacheKey)) { $template = $this->cacheHandler->fetch($cacheKey); } if (empty($template)) { $template = $this->renderer ->render($procedure->getTemplate(), array('engine' => $this, 'procedure_type' => $input->getType())); $test = clone $procedure; $test->setTemplate($template); $compiled = $test->compile($input); $this->procedureValidator->validate($compiled); if ($this->cacheEnabled) { $this->cacheHandler->save($cacheKey, $template); } } $procedure->setTemplate($template); } /** * Load partial template. * * @access public * @param string $name * @return string */ public function load($name) { return $this->procedureLoader->loadTemplate($name, 'partial'); } /** * Enable cache. * * @access public * @return void */ public function enableCache() { $this->cacheEnabled = true; } /** * Disable cache. * * @access public * @return void */ public function disableCache() { $this->cacheEnabled = false; } /** * Clear cache. * * @access public * @return void */ public function clearCache() { $this->cacheHandler->delete('phantomjs_*'); } }
nekulin/php-phantomjs
src/JonnyW/PhantomJs/Procedure/ProcedureCompiler.php
PHP
mit
4,030
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; internal class bug1 { public struct VT { public int a3; } public class CL { public float a2 = 4.0F; public long a5 = 2L; } public static VT vtstatic = new VT(); public static int Main() { CL cl = new CL(); float[] arr1d = new float[11]; double a4 = 3; arr1d[0] = 4F; long a1 = 6L; vtstatic.a3 = 13; Console.WriteLine("The correct result is 1"); Console.Write("The actual result is "); int retval = Convert.ToInt32(Convert.ToInt32((long)(Convert.ToInt32(vtstatic.a3) + (long)(18L / cl.a5 / 3)) / (cl.a5 * a1 / a4) + (cl.a2 / arr1d[0] - cl.a2))); Console.WriteLine(retval); return retval + 99; } }
bitcrazed/coreclr
tests/src/JIT/Regression/CLR-x86-JIT/V1-M12-Beta2/b76511/b76511.cs
C#
mit
916
/** * Vue is a modern JavaScript library for building interactive web interfaces * using reactive data binding and reusable components. Vue's API is clean * and simple, leaving you to focus on building your next great project. */ window.Vue = require('vue'); require('vue-resource'); /** * We'll register a HTTP interceptor to attach the "CSRF" header to each of * the outgoing requests issued by this application. The CSRF middleware * included w/ Laravel will automatically verify the header's value. */ Vue.http.interceptors.push((request, next) => { request.headers.set('X-CSRF-TOKEN', Laravel.csrfToken); next(); }); /** * Moment is a javascript library that we can use to format dates * It's similar to Carbon in PHP so we mostly use it to format * dates that are returned from our Laravel Eloquent models */ window.moment = require('moment');
iamleet/project-lb-ssl
vendor/talvbansal/media-manager/resources/assets/js/base.js
JavaScript
mit
874
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Setup\Test\Unit\Module\Di\Compiler\Config\Chain; use \Magento\Setup\Module\Di\Compiler\Config\Chain\BackslashTrim; class BackslashTrimTest extends \PHPUnit_Framework_TestCase { public function testModifyArgumentsDoNotExist() { $inputConfig = [ 'data' => [] ]; $modifier = new BackslashTrim(); $this->assertSame($inputConfig, $modifier->modify($inputConfig)); } public function testModifyArguments() { $modifier = new BackslashTrim(); $this->assertEquals($this->getOutputConfig(), $modifier->modify($this->getInputConfig())); } /** * Input config * * @return array */ private function getInputConfig() { return [ 'arguments' => [ '\\Class' => [ 'argument_type' => ['_i_' => '\\Class\\Dependency'], 'argument_not_shared' => ['_ins_' => '\\Class\\Dependency'], 'array' => [ 'argument_type' => ['_i_' => '\\Class\\Dependency'], 'argument_not_shared' => ['_ins_' => '\\Class\\Dependency'], 'array' => [ 'argument_type' => ['_i_' => '\\Class\\Dependency'], 'argument_not_shared' => ['_ins_' => '\\Class\\Dependency'], ] ] ] ] ]; } /** * Output config * * @return array */ private function getOutputConfig() { return [ 'arguments' => [ 'Class' => [ 'argument_type' => ['_i_' => 'Class\\Dependency'], 'argument_not_shared' => ['_ins_' => 'Class\\Dependency'], 'array' => [ 'argument_type' => ['_i_' => 'Class\\Dependency'], 'argument_not_shared' => ['_ins_' => 'Class\\Dependency'], 'array' => [ 'argument_type' => ['_i_' => 'Class\\Dependency'], 'argument_not_shared' => ['_ins_' => 'Class\\Dependency'], ] ] ] ] ]; } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/setup/src/Magento/Setup/Test/Unit/Module/Di/Compiler/Config/Chain/BackslashTrimTest.php
PHP
mit
2,416
<?php namespace Zotlabs\Module; require_once('include/attach.php'); require_once('include/channel.php'); require_once('include/photos.php'); class File_upload extends \Zotlabs\Web\Controller { function post() { logger('file upload: ' . print_r($_REQUEST,true)); logger('file upload: ' . print_r($_FILES,true)); $channel = (($_REQUEST['channick']) ? channelx_by_nick($_REQUEST['channick']) : null); if(! $channel) { logger('channel not found'); killme(); } $_REQUEST['source'] = 'file_upload'; if($channel['channel_id'] != local_channel()) { $_REQUEST['contact_allow'] = expand_acl($channel['channel_allow_cid']); $_REQUEST['group_allow'] = expand_acl($channel['channel_allow_gid']); $_REQUEST['contact_deny'] = expand_acl($channel['channel_deny_cid']); $_REQUEST['group_deny'] = expand_acl($channel['channel_deny_gid']); } $_REQUEST['allow_cid'] = perms2str($_REQUEST['contact_allow']); $_REQUEST['allow_gid'] = perms2str($_REQUEST['group_allow']); $_REQUEST['deny_cid'] = perms2str($_REQUEST['contact_deny']); $_REQUEST['deny_gid'] = perms2str($_REQUEST['group_deny']); if($_REQUEST['filename']) { $r = attach_mkdir($channel, get_observer_hash(), $_REQUEST); if($r['success']) { $hash = $r['data']['hash']; $sync = attach_export_data($channel,$hash); if($sync) { build_sync_packet($channel['channel_id'],array('file' => array($sync))); } goaway(z_root() . '/cloud/' . $channel['channel_address'] . '/' . $r['data']['display_path']); } } else { $matches = []; $partial = false; if(array_key_exists('HTTP_CONTENT_RANGE',$_SERVER)) { $pm = preg_match('/bytes (\d*)\-(\d*)\/(\d*)/',$_SERVER['HTTP_CONTENT_RANGE'],$matches); if($pm) { logger('Content-Range: ' . print_r($matches,true)); $partial = true; } } if($partial) { $x = save_chunk($channel,$matches[1],$matches[2],$matches[3]); if($x['partial']) { header('Range: bytes=0-' . (($x['length']) ? $x['length'] - 1 : 0)); json_return_and_die($result); } else { header('Range: bytes=0-' . (($x['size']) ? $x['size'] - 1 : 0)); $_FILES['userfile'] = [ 'name' => $x['name'], 'type' => $x['type'], 'tmp_name' => $x['tmp_name'], 'error' => $x['error'], 'size' => $x['size'] ]; } } else { if(! array_key_exists('userfile',$_FILES)) { $_FILES['userfile'] = [ 'name' => $_FILES['files']['name'], 'type' => $_FILES['files']['type'], 'tmp_name' => $_FILES['files']['tmp_name'], 'error' => $_FILES['files']['error'], 'size' => $_FILES['files']['size'] ]; } } $r = attach_store($channel, get_observer_hash(), '', $_REQUEST); if($r['success']) { $sync = attach_export_data($channel,$r['data']['hash']); if($sync) build_sync_packet($channel['channel_id'],array('file' => array($sync))); } } goaway(z_root() . '/' . $_REQUEST['return_url']); } }
redmatrix/hubzilla
Zotlabs/Module/File_upload.php
PHP
mit
3,027
/***************************************************************************** * * Author: Kerri Shotts <[email protected]> * http://www.photokandy.com/books/mastering-phonegap * * MIT LICENSED * * Copyright (c) 2016 Packt Publishing * Portions Copyright (c) 2016 Kerri Shotts (photoKandy Studios LLC) * Portions Copyright various third parties where noted. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to the following * conditions: * The above copyright notice and this permission notice shall be included in all copies * or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT * OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * *****************************************************************************/ "use strict"; var config = require("../config"), paths = require("../utils/paths"), run = require("browserify-test").default, glob = require("glob"), gutil = require("gulp-util"); function testPhantom() { let files = []; files.push(...glob.sync(paths.makeFullPath(config.test.code))); run({ watch: gutil.env.watch === "yes", transform: [['babelify', { stage: 0 }]], files }); } module.exports = { task: testPhantom, desc: "Runs code-level tests using PhantomJS", help: ["Executes code-level tests in ./test using Mocha and PhantomJS", "Run with --watch yes to watch and run in other browsers."] };
kerrishotts/Mastering-PhoneGap-Code-Package
logology/gulp/tasks/test-phantom.js
JavaScript
mit
2,218
<?php namespace Dingo\Api\Provider; use ReflectionClass; use Dingo\Api\Http\Middleware\Auth; use Illuminate\Contracts\Http\Kernel; use Dingo\Api\Event\RequestWasMatched; use Dingo\Api\Http\Middleware\Request; use Dingo\Api\Http\Middleware\RateLimit; use Illuminate\Routing\ControllerDispatcher; use Dingo\Api\Http\Middleware\PrepareController; use Dingo\Api\Routing\Adapter\Laravel as LaravelAdapter; class LaravelServiceProvider extends DingoServiceProvider { /** * Boot the service provider. * * @return void */ public function boot() { parent::boot(); $this->publishes([realpath(__DIR__.'/../../config/api.php') => config_path('api.php')]); $kernel = $this->app->make(Kernel::class); $this->app[Request::class]->mergeMiddlewares( $this->gatherAppMiddleware($kernel) ); $this->addRequestMiddlewareToBeginning($kernel); $this->app['events']->listen(RequestWasMatched::class, function (RequestWasMatched $event) { $this->replaceRouteDispatcher(); $this->updateRouterBindings(); }); $this->addMiddlewareAlias('api.auth', Auth::class); $this->addMiddlewareAlias('api.throttle', RateLimit::class); $this->addMiddlewareAlias('api.controllers', PrepareController::class); } /** * Replace the route dispatcher. * * @return void */ protected function replaceRouteDispatcher() { $this->app->singleton('illuminate.route.dispatcher', function ($app) { return new ControllerDispatcher($app['api.router.adapter']->getRouter(), $app); }); } /** * Grab the bindings from the Laravel router and set them on the adapters * router. * * @return void */ protected function updateRouterBindings() { foreach ($this->getRouterBindings() as $key => $binding) { $this->app['api.router.adapter']->getRouter()->bind($key, $binding); } } /** * Get the Laravel routers bindings. * * @return array */ protected function getRouterBindings() { $property = (new ReflectionClass($this->app['router']))->getProperty('binders'); $property->setAccessible(true); return $property->getValue($this->app['router']); } /** * Register the service provider. * * @return void */ public function register() { parent::register(); $this->registerRouterAdapter(); } /** * Register the router adapter. * * @return void */ protected function registerRouterAdapter() { $this->app->singleton('api.router.adapter', function ($app) { return new LaravelAdapter($app['router']); }); } /** * Add the request middleware to the beginning of the kernel. * * @param \Illuminate\Contracts\Http\Kernel $kernel * * @return void */ protected function addRequestMiddlewareToBeginning(Kernel $kernel) { $kernel->prependMiddleware(Request::class); } /** * Register a short-hand name for a middleware. For Compatability * with Laravel < 5.4 check if aliasMiddleware exists since this * method has been renamed. * * @param string $name * @param string $class * * @return void */ protected function addMiddlewareAlias($name, $class) { $router = $this->app['router']; if (method_exists($router, 'aliasMiddleware')) { return $router->aliasMiddleware($name, $class); } return $router->middleware($name, $class); } /** * Gather the application middleware besides this one so that we can send * our request through them, exactly how the developer wanted. * * @param \Illuminate\Contracts\Http\Kernel $kernel * * @return array */ protected function gatherAppMiddleware(Kernel $kernel) { $property = (new ReflectionClass($kernel))->getProperty('middleware'); $property->setAccessible(true); return $property->getValue($kernel); } }
fannan1991/pyrocms
vendor/dingo/api/src/Provider/LaravelServiceProvider.php
PHP
mit
4,180
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Example - example-example115-debug</title> <script src="../../../angular.js"></script> <script src="../../../angular-touch.js"></script> <script src="script.js"></script> </head> <body ng-app="ngSwipeLeftExample"> <div ng-show="!showActions" ng-swipe-left="showActions = true"> Some list content, like an email in the inbox </div> <div ng-show="showActions" ng-swipe-right="showActions = false"> <button ng-click="reply()">Reply</button> <button ng-click="delete()">Delete</button> </div> </body> </html>
viral810/ngSimpleCMS
web/bundles/sunraangular/js/angular/angular-1.3.3/docs/examples/example-example115/index-debug.html
HTML
mit
617
<?php /** * Filter for analyze controller's access rules and determine public actions and scopes * for private actions. If action is private than check oauth access token and if it has needed * scopes to this action * * @author Ihor Karas <[email protected]> */ namespace api\components\filters; use Yii; use yii\base\Action; use yii\filters\auth\HttpBearerAuth; use yii\filters\auth\QueryParamAuth; use yii\web\ForbiddenHttpException; class OAuth2AccessFilter extends \yii\base\ActionFilter { /** * @param Action $action * @return bool * @throws ForbiddenHttpException * @throws \yii\base\InvalidConfigException */ public function beforeAction($action) { $action_name = $action->id; list($public_actions, $actions_scopes) = $this->analyzeAccessRules($action_name); if (in_array($action_name, $public_actions)) { //action is public return true; } // else, if not public, add additional auth filters if (Yii::$app->hasModule('oauth2')) { /** @var \filsh\yii2\oauth2server\Module $oauth_module */ $oauth_module = Yii::$app->getModule('oauth2'); $query_param_auth = ['class' => QueryParamAuth::className()]; if (!empty($oauth_module->options['token_param_name'])) { $query_param_auth['tokenParam'] = $oauth_module->options['token_param_name']; } $auth_behavior = $this->owner->getBehavior('authenticator'); $auth_behavior->authMethods = [ $query_param_auth, ['class' => HttpBearerAuth::className()], ]; $scopes = isset($actions_scopes[$action_name]) ? $actions_scopes[$action_name] : ''; if (is_array($scopes)) { $scopes = implode(' ', $scopes); } $oauthServer = $oauth_module->getServer(); $oauthRequest = $oauth_module->getRequest(); $oauthResponse = $oauth_module->getResponse(); if (!$oauthServer->verifyResourceRequest($oauthRequest, $oauthResponse, $scopes)) { throw new ForbiddenHttpException(Yii::t('yii', 'You are not allowed to perform this action.')); } } return parent::beforeAction($action); } protected function analyzeAccessRules($current_action) { /** @var \api\components\Controller $this->owner */ $access_rules = $this->owner->accessRules(); $public_actions = []; $actions_scopes = []; $is_met_curr_action = false; foreach ($access_rules as $rule) { if (empty($rule['controllers']) || in_array($this->owner->uniqueId, $rule['controllers'], true)) { if (empty($rule['actions'])) { $rule['actions'] = [$current_action]; } if (!empty($rule['actions']) && is_array($rule['actions']) && in_array($current_action, $rule['actions'], true)){ $is_met_curr_action = true; $actions = $rule['actions']; $is_public = null; if (isset($rule['allow'])) { if ($rule['allow'] && (empty($rule['roles']) || in_array('?', $rule['roles']))) { $public_actions = array_merge($public_actions, $rule['actions']); $is_public = true; } elseif ( (!$rule['allow'] && (empty($rule['roles']) || in_array('?', $rule['roles']))) || ($rule['allow'] && !empty($rule['roles']) && in_array('@', $rule['roles'])) ) { $public_actions = array_diff($public_actions, $rule['actions']); $is_public = false; } } if ($is_public === false && !empty($rule['scopes'])) { $rule_scopes = $rule['scopes']; $scopes = is_array($rule_scopes) ? $rule_scopes : explode(' ', trim($rule_scopes)); foreach ($actions as $a) { if (!isset($actions_scopes[$a])) { $actions_scopes[$a] = $scopes; } else { $actions_scopes[$a] = array_merge($actions_scopes[$a], $scopes); } } } } } } if (!$is_met_curr_action) { $public_actions[] = $current_action; } return [$public_actions, $actions_scopes]; } }
tejrajs/yii2-oauth2-rest-template
application/api/components/filters/OAuth2AccessFilter.php
PHP
mit
3,780
<?php /** * aSlideshowSlot form base class. * * @method aSlideshowSlot getObject() Returns the current form's model object * * @package asandbox * @subpackage form * @author Your name here * @version SVN: $Id: sfDoctrineFormGeneratedInheritanceTemplate.php 24171 2009-11-19 16:37:50Z Kris.Wallsmith $ */ abstract class BaseaSlideshowSlotForm extends aSlotForm { protected function setupInheritance() { parent::setupInheritance(); $this->widgetSchema->setNameFormat('a_slideshow_slot[%s]'); } public function getModelName() { return 'aSlideshowSlot'; } }
jpasosa/agroapex
lib/form/doctrine/apostrophePlugin/base/BaseaSlideshowSlotForm.class.php
PHP
mit
601
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.Azure.AcceptanceTestsLro.Models { using System.Linq; /// <summary> /// Defines headers for deleteNoHeaderInRetry operation. /// </summary> public partial class LROsDeleteNoHeaderInRetryHeaders { /// <summary> /// Initializes a new instance of the LROsDeleteNoHeaderInRetryHeaders /// class. /// </summary> public LROsDeleteNoHeaderInRetryHeaders() { } /// <summary> /// Initializes a new instance of the LROsDeleteNoHeaderInRetryHeaders /// class. /// </summary> /// <param name="location">Location to poll for result status: will be /// set to /lro/put/noheader/202/204/operationresults</param> public LROsDeleteNoHeaderInRetryHeaders(string location = default(string)) { Location = location; } /// <summary> /// Gets or sets location to poll for result status: will be set to /// /lro/put/noheader/202/204/operationresults /// </summary> [Newtonsoft.Json.JsonProperty(PropertyName = "Location")] public string Location { get; set; } } }
yaqiyang/autorest
src/generator/AutoRest.CSharp.Azure.Tests/Expected/AcceptanceTests/Lro/Models/LROsDeleteNoHeaderInRetryHeaders.cs
C#
mit
1,475
# This technical data was produced for the U. S. Government under Contract No. W15P7T-13-C-F600, and # is subject to the Rights in Technical Data-Noncommercial Items clause at DFARS 252.227-7013 (FEB 2012) from django.contrib.gis.db import models #ShapeFile has: ['STATEFP', 'COUNTYFP', 'COUNTYNS', 'AFFGEOID', 'GEOID', 'NAME', 'LSAD', 'ALAND', 'AWATER'] # Import Steps: # # from django.contrib.gis.utils import LayerMapping # from geoq.locations.models import * # mapping = {'name': 'NAME', 'state': 'STATEFP', 'poly': 'MULTIPOLYGON',} # lm = LayerMapping(Counties, 'static/world_cells/counties/cb_2013_us_county_20m.shp', mapping, encoding='cp1252') # lm.save(verbose=True) class Counties(models.Model): name = models.CharField(max_length=80) state = models.IntegerField(blank=True, null=True) poly = models.MultiPolygonField(srid=4326) objects = models.GeoManager() def __str__(self): # __unicode__ on Python 2 return 'County: %s' % self.name class Meta: verbose_name = 'US Counties' verbose_name_plural = 'Counties'
stephenrjones/geoq
geoq/locations/models.py
Python
mit
1,087
<?php /** * Copyright © 2013-2017 Magento, Inc. All rights reserved. * See COPYING.txt for license details. */ namespace Magento\Tax\Block\Adminhtml\Rate; use Magento\Tax\Controller\RegistryConstants; use Magento\Tax\Model\Calculation\Rate; class TitleTest extends \PHPUnit_Framework_TestCase { /** * @var \Magento\Tax\Block\Adminhtml\Rate\Title */ protected $_block; /** * @var \Magento\TestFramework\ObjectManager */ protected $_objectManager; protected function setUp() { /** @var $objectManager \Magento\TestFramework\ObjectManager */ $this->_objectManager = \Magento\TestFramework\Helper\Bootstrap::getObjectManager(); } /** * @magentoDataFixture Magento/Store/_files/store.php * @magentoDataFixture Magento/Tax/_files/tax_classes.php */ public function testGetTitles() { /** @var \Magento\Tax\Model\Calculation\Rate $rate */ $rate = $this->_objectManager->create('Magento\Tax\Model\Calculation\Rate'); $rate->load(1); /** @var \Magento\Store\Model\Store $store */ $store = $this->_objectManager->get('Magento\Store\Model\Store'); $store->load('test', 'code'); $title = 'title'; $rate->saveTitles([$store->getId() => $title]); $coreRegistry = $this->_objectManager->create('Magento\Framework\Registry'); $coreRegistry->register(RegistryConstants::CURRENT_TAX_RATE_ID, 1); /** @var \Magento\Tax\Block\Adminhtml\Rate\Title $block */ $block = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create( 'Magento\Tax\Block\Adminhtml\Rate\Title', [ 'coreRegistry' => $coreRegistry, ] ); $titles = $block->getTitles(); $this->assertArrayHasKey($store->getId(), $titles, 'Store was not created'); $this->assertEquals($title, $titles[$store->getId()], 'Invalid Tax Title'); } }
j-froehlich/magento2_wk
vendor/magento/magento2-base/dev/tests/integration/testsuite/Magento/Tax/Block/Adminhtml/Rate/TitleTest.php
PHP
mit
1,970
describe('$mdThemingProvider', function() { var themingProvider; var defaultTheme; var testTheme; var testPalette; var startAngular = inject; beforeEach(function() { module('material.core', function($provide) { /** * material-mocks.js clears the $MD_THEME_CSS for Karma testing performance * performance optimizations. Here inject some length into our theme_css so that * palettes are parsed/generated */ $provide.constant('$MD_THEME_CSS', '/**/'); }); }); function setup() { module('material.core', function($mdThemingProvider) { themingProvider = $mdThemingProvider; testPalette = themingProvider._PALETTES.testPalette = themingProvider._PALETTES.otherTestPalette = { '50': 'ffebee', '100': 'ffcdd2', '200': 'ef9a9a', '300': 'e57373', '400': 'ef5350', '500': 'f44336', '600': 'e53935', '700': 'd32f2f', '800': 'c62828', '900': 'b71c1c', 'A100': 'ff8a80', 'A200': 'ff5252', 'A400': 'ff1744', 'A700': 'd50000', 'contrastDefaultColor': 'light', 'contrastDarkColors': ['50', '100', '200', '300', '400', 'A100'], 'contrastStrongLightColors': ['900'] }; defaultTheme = themingProvider.theme('default') .primaryPalette('testPalette') .warnPalette('testPalette') .accentPalette('otherTestPalette') .backgroundPalette('testPalette'); testTheme = themingProvider.theme('test'); }); startAngular(); } describe('creating themes', function() { beforeEach(setup); it('allows registering of a theme', function() { expect(testTheme.name).toBe('test'); expect(testTheme.dark).toBeOfType('function'); expect(testTheme.colors).toBeOfType('object'); }); it('defaults to light theme', function() { expect(testTheme.foregroundPalette.name).toBe('dark'); expect(testTheme.foregroundShadow).toBeFalsy(); }); describe('registering a dark theme', function() { it('changes the foreground color & shadow', function() { testTheme.dark(); expect(testTheme.foregroundPalette.name).toBe('light'); expect(testTheme.foregroundShadow).toBeTruthy(); }); it('changes the existing hues to match the dark or light defaults, if the hues are still default', function() { var darkBackground = themingProvider._DARK_DEFAULT_HUES.background; var lightBackground = themingProvider._LIGHT_DEFAULT_HUES.background; testTheme.dark(); expect(testTheme.colors.background.hues['hue-3']).toBe(darkBackground['hue-3']); testTheme.dark(false); expect(testTheme.colors.background.hues['hue-3']).toBe(lightBackground['hue-3']); testTheme.dark(); expect(testTheme.colors.background.hues['hue-3']).toBe(darkBackground['hue-3']); testTheme.backgroundPalette('testPalette', { 'hue-3': '50' }); testTheme.dark(false); expect(testTheme.colors.background.hues['hue-3']).toBe('50'); }); }); describe('theme extension', function() { var parentTheme; beforeEach(function() { themingProvider.definePalette('parentPalette', angular.extend({}, testPalette)); parentTheme = themingProvider.theme('parent').primaryPalette('parentPalette'); }); it('allows extension by string', function() { var childTheme = themingProvider.theme('child', 'parent'); expect(childTheme.colors.primary.name).toBe('parentPalette'); }); it('allows extension by reference', function() { var childTheme = themingProvider.theme('child', parentTheme); expect(childTheme.colors.primary.name).toBe('parentPalette'); }); it('extends the default theme automatically', function() { var childTheme = themingProvider.theme('child'); expect(childTheme.colors.primary.name).toEqual(defaultTheme.colors.primary.name); }); }); describe('providing hue map for a color', function() { it('extends default hue map automatically', function() { expect(testTheme.colors.primary.hues).toEqual(defaultTheme.colors.primary.hues); }); it('allows specifying a custom hue map', function() { expect(testTheme.colors.primary.hues['hue-1']).not.toBe('50'); testTheme.primaryPalette('testPalette', { 'hue-1': '50' }); expect(testTheme.colors.primary.hues['hue-1']).toBe('50'); }); it('errors on invalid key in hue map', function() { expect(function() { testTheme.primaryPalette('testPalette', { 'invalid-key': '100' }); }).toThrow(); }); it('errors on invalid value in hue map', function() { expect(function() { testTheme.primaryPalette('testPalette', { 'hue-1': 'invalid-value' }); }).toThrow(); }); }); }); describe('registering palettes', function() { beforeEach(setup); it('requires all hues specified', function() { var colors = { '50': ' ', '100': ' ', '200': ' ', '300': ' ', '400': ' ', '500': ' ', '600': ' ', '700': ' ', '800': ' ', '900': ' ', 'A100': ' ', 'A200': ' ', 'A400': ' ', 'A700': ' ' }; themingProvider.definePalette('newPalette', colors); delete colors['50']; expect(function() { themingProvider.definePalette('newPaletteTwo', colors); }).toThrow(); }); it('allows to extend an existing palette', function() { themingProvider.definePalette('extended', themingProvider.extendPalette('testPalette', { '50': 'newValue' })); expect(themingProvider._PALETTES.extended['100']).toEqual(testPalette['100']); expect(themingProvider._PALETTES.extended['50']).toEqual('newValue'); }); }); describe('css template parsing', function() { beforeEach(setup); function parse(str) { return themingProvider._parseRules(testTheme, 'primary', str) .join('') .split(/\}(?!(\}|'|"|;))/) .filter(function(val) { return !!val; }) .map(function(rule) { rule += '}'; return { content: (rule.match(/\{\s*(.*?)\s*\}/) || [])[1] || null, hue: (rule.match(/md-(hue-\d)/) || [])[1] || null, type: (rule.match(/(primary)/) || [])[1] || null }; }); } it('errors if given a theme with invalid palettes', function() { testTheme.primaryPalette('invalidPalette'); expect(function() { themingProvider._parseRules(testTheme, 'primary', '').join(''); }).toThrow(); }); it('drops the default theme name from the selectors', function() { expect(themingProvider._parseRules( defaultTheme, 'primary', '.md-THEME_NAME-theme.md-button { }' ).join('')).toContain('.md-button { }'); }); it('replaces THEME_NAME', function() { expect(themingProvider._parseRules( testTheme, 'primary', '.md-THEME_NAME-theme {}' ).join('')).toContain('.md-test-theme {}'); }); describe('parses foreground text and shadow', function() { it('for a light theme', function() { testTheme.dark(false); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-1}}"; }')[0].content) .toEqual('color: rgba(0,0,0,0.87);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-2}}"; }')[0].content) .toEqual('color: rgba(0,0,0,0.54);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-3}}"; }')[0].content) .toEqual('color: rgba(0,0,0,0.38);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-4}}"; }')[0].content) .toEqual('color: rgba(0,0,0,0.12);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-shadow}}"; }')[0].content) .toEqual('color: ;'); }); it('for a dark theme', function() { testTheme.dark(); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-1}}"; }')[0].content) .toEqual('color: rgba(255,255,255,1.0);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-2}}"; }')[0].content) .toEqual('color: rgba(255,255,255,0.7);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-3}}"; }')[0].content) .toEqual('color: rgba(255,255,255,0.5);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-4}}"; }')[0].content) .toEqual('color: rgba(255,255,255,0.12);'); expect(parse('.md-THEME_NAME-theme { color: "{{foreground-shadow}}"; }')[0].content) .toEqual('color: 1px 1px 0px rgba(0,0,0,0.4), -1px -1px 0px rgba(0,0,0,0.4);'); }); }); it('parses contrast colors', function() { testTheme.primaryPalette('testPalette', { 'default': '50' }); expect(parse('.md-THEME_NAME-theme { color: "{{primary-contrast}}"; } ')[0].content) .toEqual('color: rgba(0,0,0,0.87);'); testTheme.primaryPalette('testPalette', { 'default': '800' }); expect(parse('{ color: "{{primary-contrast}}"; }')[0].content) .toEqual('color: rgba(255,255,255,0.87);'); testTheme.primaryPalette('testPalette', { 'default': '900' }); expect(parse('{ color: "{{primary-contrast}}"; }')[0].content) .toEqual('color: rgb(255,255,255);'); }); it('generates base, non-colorType-specific, rules', function() { var accent100 = themingProvider._rgba(themingProvider._PALETTES.testPalette['100'].value); var result = parse('.md-THEME_NAME-theme { color: "{{accent-100}}"; }'); expect(result[0].content).toEqual('color: ' + accent100 + ';'); expect(result[0].hue).toBeFalsy(); expect(result[1].content).toEqual('color: ' + accent100 + ';'); expect(result[1].hue).toBe('hue-1'); expect(result[2].content).toEqual('color: ' + accent100 + ';'); expect(result[2].hue).toBe('hue-2'); expect(result[3].content).toEqual('color: ' + accent100 + ';'); expect(result[3].hue).toBe('hue-3'); expect(result.length).toBe(4); }); it('generates colorType-specific rules for each hue', function() { var primary = themingProvider._rgba(themingProvider._PALETTES.testPalette['500'].value); var hue1 = themingProvider._rgba(themingProvider._PALETTES.testPalette['300'].value); var hue2 = themingProvider._rgba(themingProvider._PALETTES.testPalette['800'].value); var hue3 = themingProvider._rgba(themingProvider._PALETTES.testPalette.A100.value); var result = parse('.md-THEME_NAME-theme.md-primary { color: "{{primary-color}}"; }'); expect(result[0]).toEqual({content: 'color: ' + primary + ';', hue: null, type: 'primary'}); expect(result[1]).toEqual({content: 'color: ' + hue1 + ';', hue: 'hue-1', type: 'primary'}); expect(result[2]).toEqual({content: 'color: ' + hue2 + ';', hue: 'hue-2', type: 'primary'}); expect(result[3]).toEqual({content: 'color: ' + hue3 + ';', hue: 'hue-3', type: 'primary'}); expect(result.length).toEqual(4); }); it('generates colorType-specific rules for each hue with opacity', function() { var primary = themingProvider._rgba(themingProvider._PALETTES.testPalette['500'].value, '0.3'); var hue1 = themingProvider._rgba(themingProvider._PALETTES.testPalette['300'].value, '0.3'); var hue2 = themingProvider._rgba(themingProvider._PALETTES.testPalette['800'].value, '0.3'); var hue3 = themingProvider._rgba(themingProvider._PALETTES.testPalette.A100.value, '0.3'); var result = parse('.md-THEME_NAME-theme.md-primary { color: "{{primary-color-0.3}}"; }'); expect(result[0]).toEqual({content: 'color: ' + primary + ';', hue: null, type: 'primary'}); expect(result[1]).toEqual({content: 'color: ' + hue1 + ';', hue: 'hue-1', type: 'primary'}); expect(result[2]).toEqual({content: 'color: ' + hue2 + ';', hue: 'hue-2', type: 'primary'}); expect(result[3]).toEqual({content: 'color: ' + hue3 + ';', hue: 'hue-3', type: 'primary'}); expect(result.length).toEqual(4); }); describe('allows selecting a colorType', function() { it('hue value', function() { var A400 = themingProvider._rgba(themingProvider._PALETTES.testPalette.A400.value); var result = parse('.md-THEME_NAME-theme.md-primary { color: {{primary-A400}}; }'); expect(result[0]).toEqual({content: 'color: ' + A400 + ';', hue: null, type: 'primary'}); expect(result[1]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-1', type: 'primary'}); expect(result[2]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-2', type: 'primary'}); expect(result[3]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-3', type: 'primary'}); expect(result.length).toEqual(4); }); it('hue value with opacity', function() { var A400 = themingProvider._rgba(themingProvider._PALETTES.testPalette.A400.value, '0.25'); var result = parse('.md-THEME_NAME-theme.md-primary { color: {{primary-A400-0.25}}; }'); expect(result[0]).toEqual({content: 'color: ' + A400 + ';', hue: null, type: 'primary'}); expect(result[1]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-1', type: 'primary'}); expect(result[2]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-2', type: 'primary'}); expect(result[3]).toEqual({content: 'color: ' + A400 + ';', hue: 'hue-3', type: 'primary'}); expect(result.length).toEqual(4); }); }); }); }); describe('$mdThemeProvider with on-demand generation', function() { var $mdTheming; function getThemeStyleElements() { return document.head.querySelectorAll('style[md-theme-style]'); } function cleanThemeStyleElements() { angular.forEach(getThemeStyleElements(), function(style) { document.head.removeChild(style); }); } beforeEach(module('material.core', function($provide, $mdThemingProvider) { // Theming requires that there is at least one element present in the document head. cleanThemeStyleElements(); // Use a single simple style rule for which we can check presence / absense. $provide.constant('$MD_THEME_CSS', "sparkle.md-THEME_NAME-theme { color: '{{primary-color}}' }"); $mdThemingProvider.theme('sweden') .primaryPalette('light-blue') .accentPalette('yellow'); $mdThemingProvider.theme('belarus') .primaryPalette('red') .accentPalette('green'); $mdThemingProvider.generateThemesOnDemand(true); })); beforeEach(inject(function(_$mdTheming_) { $mdTheming = _$mdTheming_; })); it('should not add any theme styles automatically', function() { var styles = getThemeStyleElements(); expect(styles.length).toBe(0); }); it('should add themes on-demand', function() { $mdTheming.generateTheme('sweden'); var styles = getThemeStyleElements(); // One style tag for each default hue (default, hue-1, hue-2, hue-3). expect(styles.length).toBe(4); expect(document.head.innerHTML).toMatch(/md-sweden-theme/); expect(document.head.innerHTML).not.toMatch(/md-belarus-theme/); $mdTheming.generateTheme('belarus'); styles = getThemeStyleElements(); expect(styles.length).toBe(8); expect(document.head.innerHTML).toMatch(/md-sweden-theme/); expect(document.head.innerHTML).toMatch(/md-belarus-theme/); }); }); describe('$mdThemeProvider with nonce', function() { beforeEach(function() { module('material.core', function($provide) { /** * material-mocks.js clears the $MD_THEME_CSS for Karma testing performance * performance optimizations. Here inject some length into our theme_css so that * palettes are parsed/generated */ $provide.constant('$MD_THEME_CSS', '/**/'); }); }); describe('and auto-generated themes', function() { beforeEach(function() { module('material.core', function($mdThemingProvider) { $mdThemingProvider.generateThemesOnDemand(false); $mdThemingProvider.theme('auto-nonce') .primaryPalette('light-blue') .accentPalette('yellow'); $mdThemingProvider.setNonce('1'); }); inject(); }); it('should add a nonce', function() { var styles = document.head.querySelectorAll('style[nonce="1"]'); expect(styles.length).toBe(4); }); }); describe('and on-demand generated themes', function() { var $mdTheming; beforeEach(function() { module('material.core', function($mdThemingProvider) { $mdThemingProvider.generateThemesOnDemand(true); $mdThemingProvider.theme('nonce') .primaryPalette('light-blue') .accentPalette('yellow'); $mdThemingProvider.setNonce('2'); }); inject(function(_$mdTheming_) { $mdTheming = _$mdTheming_; }); }); it('should add a nonce', function() { var styles = document.head.querySelectorAll('style[nonce="2"]'); expect(styles.length).toBe(0); $mdTheming.generateTheme('nonce'); styles = document.head.querySelectorAll('style[nonce="2"]'); expect(styles.length).toBe(4); }); }); }); describe('$mdTheming service', function() { var $mdThemingProvider; beforeEach(module('material.core', function(_$mdThemingProvider_) { $mdThemingProvider = _$mdThemingProvider_; })); var el, testHtml, compileAndLink; beforeEach(inject(function($rootScope, $compile) { compileAndLink = function(html) { return $compile(html)($rootScope.$new()); }; })); beforeEach(function() { testHtml = '<h1>Test</h1>'; el = compileAndLink(testHtml); }); it('supports setting a different default theme', function() { $mdThemingProvider.setDefaultTheme('other'); inject(function($rootScope, $compile, $mdTheming) { el = $compile('<h1>Test</h1>')($rootScope); $mdTheming(el); expect(el.hasClass('md-other-theme')).toBe(true); expect(el.hasClass('md-default-theme')).toBe(false); }); }); it('inherits the theme from parent elements', inject(function($mdTheming) { el = compileAndLink([ '<div md-theme="awesome">', testHtml, '</div>' ].join('')).children(0); $mdTheming(el); expect(el.hasClass('md-default-theme')).toBe(false); expect(el.hasClass('md-awesome-theme')).toBe(true); })); it('provides the md-themable directive', function() { $mdThemingProvider.setDefaultTheme('some'); el = compileAndLink('<h1 md-themable></h1>'); expect(el.hasClass('md-some-theme')).toBe(true); }); it('can inherit from explicit parents', inject(function($rootScope, $mdTheming) { var child = compileAndLink('<h1 md-theme="dark"></h1>'); var container = compileAndLink('<div md-theme="space"><h1></h1></div>'); var inherited = container.children(); $mdTheming(child); expect(child.hasClass('md-dark-theme')).toBe(true); $mdTheming.inherit(child, inherited); expect(child.hasClass('md-dark-theme')).toBe(false); expect(child.hasClass('md-space-theme')).toBe(true); })); it('exposes a getter for the default theme', inject(function($mdTheming) { expect($mdTheming.defaultTheme()).toBe('default'); })); }); describe('md-theme directive', function() { beforeEach(module('material.core')); it('should observe and set mdTheme controller', inject(function($compile, $rootScope) { $rootScope.themey = 'red'; var el = $compile('<div md-theme="{{themey}}">')($rootScope); $rootScope.$apply(); var ctrl = el.data('$mdThemeController'); expect(ctrl.$mdTheme).toBe('red'); $rootScope.$apply('themey = "blue"'); expect(ctrl.$mdTheme).toBe('blue'); })); it('warns when an unregistered theme is used', function() { inject(function($log, $compile, $rootScope) { spyOn($log, 'warn'); $compile('<div md-theme="unregistered"></div>')($rootScope); $rootScope.$apply(); expect($log.warn).toHaveBeenCalled(); }); }); it('does not warn when a registered theme is used', function() { inject(function($log, $compile, $rootScope) { spyOn($log, 'warn'); $compile('<div md-theme="default"></div>')($rootScope); $rootScope.$apply(); expect($log.warn.calls.count()).toBe(0); }); }); }); describe('md-themable directive', function() { var $mdThemingProvider; beforeEach(module('material.core', function(_$mdThemingProvider_) { $mdThemingProvider = _$mdThemingProvider_; })); it('should inherit parent theme', inject(function($compile, $rootScope) { var el = $compile('<div md-theme="a"><span md-themable></span></div>')($rootScope); $rootScope.$apply(); expect(el.children().hasClass('md-a-theme')).toBe(true); })); it('should watch parent theme with md-theme-watch', inject(function($compile, $rootScope) { $rootScope.themey = 'red'; var el = $compile('<div md-theme="{{themey}}"><span md-themable md-theme-watch></span></div>')($rootScope); $rootScope.$apply(); expect(el.children().hasClass('md-red-theme')).toBe(true); $rootScope.$apply('themey = "blue"'); expect(el.children().hasClass('md-blue-theme')).toBe(true); expect(el.children().hasClass('md-red-theme')).toBe(false); })); it('should not watch parent theme by default', inject(function($compile, $rootScope) { $rootScope.themey = 'red'; var el = $compile('<div md-theme="{{themey}}"><span md-themable></span></div>')($rootScope); $rootScope.$apply(); expect(el.children().hasClass('md-red-theme')).toBe(true); $rootScope.$apply('themey = "blue"'); expect(el.children().hasClass('md-blue-theme')).toBe(false); expect(el.children().hasClass('md-red-theme')).toBe(true); })); it('should support watching parent theme by default', function() { $mdThemingProvider.alwaysWatchTheme(true); inject(function($rootScope, $compile) { $rootScope.themey = 'red'; var el = $compile('<div md-theme="{{themey}}"><span md-themable></span></div>')($rootScope); $rootScope.$apply(); expect(el.children().hasClass('md-red-theme')).toBe(true); $rootScope.$apply('themey = "blue"'); expect(el.children().hasClass('md-blue-theme')).toBe(false); expect(el.children().hasClass('md-red-theme')).toBe(true); }); }); it('should not apply a class for an unnested default theme', inject(function($rootScope, $compile) { var el = $compile('<div md-themable></div>')($rootScope); expect(el.hasClass('md-default-theme')).toBe(false); })); it('should apply a class for a nested default theme', inject(function($rootScope, $compile) { var el = $compile('<div md-theme="default" md-themable></div>')($rootScope); expect(el.hasClass('md-default-theme')).toBe(true); })); });
robertmesserle/material
src/core/services/theming/theming.spec.js
JavaScript
mit
23,029