text
stringlengths
2
99.9k
meta
dict
/** ****************************************************************************** * @file usbd_msc_core.h * @author MCD Application Team * @version V1.0.0 * @date 22-July-2011 * @brief header for the usbd_msc_core.c file ****************************************************************************** * @attention * * THE PRESENT FIRMWARE WHICH IS FOR GUIDANCE ONLY AIMS AT PROVIDING CUSTOMERS * WITH CODING INFORMATION REGARDING THEIR PRODUCTS IN ORDER FOR THEM TO SAVE * TIME. AS A RESULT, STMICROELECTRONICS SHALL NOT BE HELD LIABLE FOR ANY * DIRECT, INDIRECT OR CONSEQUENTIAL DAMAGES WITH RESPECT TO ANY CLAIMS ARISING * FROM THE CONTENT OF SUCH FIRMWARE AND/OR THE USE MADE BY CUSTOMERS OF THE * CODING INFORMATION CONTAINED HEREIN IN CONNECTION WITH THEIR PRODUCTS. * * <h2><center>&copy; COPYRIGHT 2011 STMicroelectronics</center></h2> ****************************************************************************** */ /* Define to prevent recursive inclusion -------------------------------------*/ #ifndef _USB_MSC_CORE_H_ #define _USB_MSC_CORE_H_ #include "usbd_ioreq.h" /** @addtogroup USBD_MSC_BOT * @{ */ /** @defgroup USBD_MSC * @brief This file is the Header file for USBD_msc.c * @{ */ /** @defgroup USBD_BOT_Exported_Defines * @{ */ #define BOT_GET_MAX_LUN 0xFE #define BOT_RESET 0xFF #define USB_MSC_CONFIG_DESC_SIZ 32 #define MSC_EPIN_SIZE *(uint16_t *)(((USB_OTG_CORE_HANDLE *)pdev)->dev.pConfig_descriptor + 22) #define MSC_EPOUT_SIZE *(uint16_t *)(((USB_OTG_CORE_HANDLE *)pdev)->dev.pConfig_descriptor + 29) /** * @} */ /** @defgroup USB_CORE_Exported_Types * @{ */ extern USBD_Class_cb_TypeDef USBD_MSC_cb; /** * @} */ /** * @} */ #endif // _USB_MSC_CORE_H_ /** * @} */ /******************* (C) COPYRIGHT 2011 STMicroelectronics *****END OF FILE****/
{ "pile_set_name": "Github" }
require 'sass/script' require 'sass/script/css_lexer' module Sass module Script # This is a subclass of {Parser} for use in parsing plain CSS properties. # # @see Sass::SCSS::CssParser class CssParser < Parser private # @private def lexer_class; CssLexer; end # We need a production that only does /, # since * and % aren't allowed in plain CSS production :div, :unary_plus, :div def string tok = try_tok(:string) return number unless tok unless @lexer.peek && @lexer.peek.type == :begin_interpolation return literal_node(tok.value, tok.source_range) end end # Short-circuit all the SassScript-only productions alias_method :interpolation, :space alias_method :or_expr, :div alias_method :unary_div, :ident alias_method :paren, :string end end end
{ "pile_set_name": "Github" }
@if "%DEBUG%" == "" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS= set DIRNAME=%~dp0 if "%DIRNAME%" == "" set DIRNAME=. set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if "%ERRORLEVEL%" == "0" goto init echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto init echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :init @rem Get command-line arguments, handling Windowz variants if not "%OS%" == "Windows_NT" goto win9xME_args if "%@eval[2+2]" == "4" goto 4NT_args :win9xME_args @rem Slurp the command line arguments. set CMD_LINE_ARGS= set _SKIP=2 :win9xME_args_slurp if "x%~1" == "x" goto execute set CMD_LINE_ARGS=%* goto execute :4NT_args @rem Get arguments from the 4NT Shell from JP Software set CMD_LINE_ARGS=%$ :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% :end @rem End local scope for the variables with windows NT shell if "%ERRORLEVEL%"=="0" goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 exit /b 1 :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
{ "pile_set_name": "Github" }
{%- import '_macros.j2' as macros with context -%} {%- set config_name_default = 'www' -%} {%- set config_default = { 'listen': '/run/php/php7.1-fpm.sock', 'pm.max_children': 20 } -%} {%- set config_extra = { } -%} {% include manala_php_version|string ~ '/_base.j2' %}
{ "pile_set_name": "Github" }
/* Copyright 2016 The Kubernetes 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 workqueue import ( "container/heap" "sync" "time" "k8s.io/apimachinery/pkg/util/clock" utilruntime "k8s.io/apimachinery/pkg/util/runtime" ) // DelayingInterface is an Interface that can Add an item at a later time. This makes it easier to // requeue items after failures without ending up in a hot-loop. type DelayingInterface interface { Interface // AddAfter adds an item to the workqueue after the indicated duration has passed AddAfter(item interface{}, duration time.Duration) } // NewDelayingQueue constructs a new workqueue with delayed queuing ability func NewDelayingQueue() DelayingInterface { return NewDelayingQueueWithCustomClock(clock.RealClock{}, "") } // NewNamedDelayingQueue constructs a new named workqueue with delayed queuing ability func NewNamedDelayingQueue(name string) DelayingInterface { return NewDelayingQueueWithCustomClock(clock.RealClock{}, name) } // NewDelayingQueueWithCustomClock constructs a new named workqueue // with ability to inject real or fake clock for testing purposes func NewDelayingQueueWithCustomClock(clock clock.Clock, name string) DelayingInterface { ret := &delayingType{ Interface: NewNamed(name), clock: clock, heartbeat: clock.NewTicker(maxWait), stopCh: make(chan struct{}), waitingForAddCh: make(chan *waitFor, 1000), metrics: newRetryMetrics(name), } go ret.waitingLoop() return ret } // delayingType wraps an Interface and provides delayed re-enquing type delayingType struct { Interface // clock tracks time for delayed firing clock clock.Clock // stopCh lets us signal a shutdown to the waiting loop stopCh chan struct{} // stopOnce guarantees we only signal shutdown a single time stopOnce sync.Once // heartbeat ensures we wait no more than maxWait before firing heartbeat clock.Ticker // waitingForAddCh is a buffered channel that feeds waitingForAdd waitingForAddCh chan *waitFor // metrics counts the number of retries metrics retryMetrics } // waitFor holds the data to add and the time it should be added type waitFor struct { data t readyAt time.Time // index in the priority queue (heap) index int } // waitForPriorityQueue implements a priority queue for waitFor items. // // waitForPriorityQueue implements heap.Interface. The item occurring next in // time (i.e., the item with the smallest readyAt) is at the root (index 0). // Peek returns this minimum item at index 0. Pop returns the minimum item after // it has been removed from the queue and placed at index Len()-1 by // container/heap. Push adds an item at index Len(), and container/heap // percolates it into the correct location. type waitForPriorityQueue []*waitFor func (pq waitForPriorityQueue) Len() int { return len(pq) } func (pq waitForPriorityQueue) Less(i, j int) bool { return pq[i].readyAt.Before(pq[j].readyAt) } func (pq waitForPriorityQueue) Swap(i, j int) { pq[i], pq[j] = pq[j], pq[i] pq[i].index = i pq[j].index = j } // Push adds an item to the queue. Push should not be called directly; instead, // use `heap.Push`. func (pq *waitForPriorityQueue) Push(x interface{}) { n := len(*pq) item := x.(*waitFor) item.index = n *pq = append(*pq, item) } // Pop removes an item from the queue. Pop should not be called directly; // instead, use `heap.Pop`. func (pq *waitForPriorityQueue) Pop() interface{} { n := len(*pq) item := (*pq)[n-1] item.index = -1 *pq = (*pq)[0:(n - 1)] return item } // Peek returns the item at the beginning of the queue, without removing the // item or otherwise mutating the queue. It is safe to call directly. func (pq waitForPriorityQueue) Peek() interface{} { return pq[0] } // ShutDown stops the queue. After the queue drains, the returned shutdown bool // on Get() will be true. This method may be invoked more than once. func (q *delayingType) ShutDown() { q.stopOnce.Do(func() { q.Interface.ShutDown() close(q.stopCh) q.heartbeat.Stop() }) } // AddAfter adds the given item to the work queue after the given delay func (q *delayingType) AddAfter(item interface{}, duration time.Duration) { // don't add if we're already shutting down if q.ShuttingDown() { return } q.metrics.retry() // immediately add things with no delay if duration <= 0 { q.Add(item) return } select { case <-q.stopCh: // unblock if ShutDown() is called case q.waitingForAddCh <- &waitFor{data: item, readyAt: q.clock.Now().Add(duration)}: } } // maxWait keeps a max bound on the wait time. It's just insurance against weird things happening. // Checking the queue every 10 seconds isn't expensive and we know that we'll never end up with an // expired item sitting for more than 10 seconds. const maxWait = 10 * time.Second // waitingLoop runs until the workqueue is shutdown and keeps a check on the list of items to be added. func (q *delayingType) waitingLoop() { defer utilruntime.HandleCrash() // Make a placeholder channel to use when there are no items in our list never := make(<-chan time.Time) // Make a timer that expires when the item at the head of the waiting queue is ready var nextReadyAtTimer clock.Timer waitingForQueue := &waitForPriorityQueue{} heap.Init(waitingForQueue) waitingEntryByData := map[t]*waitFor{} for { if q.Interface.ShuttingDown() { return } now := q.clock.Now() // Add ready entries for waitingForQueue.Len() > 0 { entry := waitingForQueue.Peek().(*waitFor) if entry.readyAt.After(now) { break } entry = heap.Pop(waitingForQueue).(*waitFor) q.Add(entry.data) delete(waitingEntryByData, entry.data) } // Set up a wait for the first item's readyAt (if one exists) nextReadyAt := never if waitingForQueue.Len() > 0 { if nextReadyAtTimer != nil { nextReadyAtTimer.Stop() } entry := waitingForQueue.Peek().(*waitFor) nextReadyAtTimer = q.clock.NewTimer(entry.readyAt.Sub(now)) nextReadyAt = nextReadyAtTimer.C() } select { case <-q.stopCh: return case <-q.heartbeat.C(): // continue the loop, which will add ready items case <-nextReadyAt: // continue the loop, which will add ready items case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { insert(waitingForQueue, waitingEntryByData, waitEntry) } else { q.Add(waitEntry.data) } drained := false for !drained { select { case waitEntry := <-q.waitingForAddCh: if waitEntry.readyAt.After(q.clock.Now()) { insert(waitingForQueue, waitingEntryByData, waitEntry) } else { q.Add(waitEntry.data) } default: drained = true } } } } } // insert adds the entry to the priority queue, or updates the readyAt if it already exists in the queue func insert(q *waitForPriorityQueue, knownEntries map[t]*waitFor, entry *waitFor) { // if the entry already exists, update the time only if it would cause the item to be queued sooner existing, exists := knownEntries[entry.data] if exists { if existing.readyAt.After(entry.readyAt) { existing.readyAt = entry.readyAt heap.Fix(q, existing.index) } return } heap.Push(q, entry) knownEntries[entry.data] = entry }
{ "pile_set_name": "Github" }
// Copyright 2012 Citrix Systems, Inc. Licensed under the // Apache License, Version 2.0 (the "License"); you may not use this // file except in compliance with the License. Citrix Systems, Inc. // reserves all rights not expressly granted by 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. // // Automatically generated by addcopyright.py at 04/03/2012 package com.cloud.test.stress; import java.util.Arrays; import java.util.Iterator; import java.util.List; import org.apache.log4j.Logger; import com.trilead.ssh2.Connection; import com.trilead.ssh2.Session; public class SshTest { public static final Logger s_logger = Logger.getLogger(SshTest.class.getName()); public static String host = ""; public static String password = "password"; public static String url = "http://google.com"; public static void main (String[] args) { // Parameters List<String> argsList = Arrays.asList(args); Iterator<String> iter = argsList.iterator(); while (iter.hasNext()) { String arg = iter.next(); if (arg.equals("-h")) { host = iter.next(); } if (arg.equals("-p")) { password = iter.next(); } if (arg.equals("-u")) { url = iter.next(); } } if (host == null || host.equals("")) { s_logger.info("Did not receive a host back from test, ignoring ssh test"); System.exit(2); } if (password == null){ s_logger.info("Did not receive a password back from test, ignoring ssh test"); System.exit(2); } try { s_logger.info("Attempting to SSH into host " + host); Connection conn = new Connection(host); conn.connect(null, 60000, 60000); s_logger.info("User + ssHed successfully into host " + host); boolean isAuthenticated = conn.authenticateWithPassword("root", password); if (isAuthenticated == false) { s_logger.info("Authentication failed for root with password" + password); System.exit(2); } String linuxCommand = "wget " + url; Session sess = conn.openSession(); sess.execCommand(linuxCommand); sess.close(); conn.close(); } catch (Exception e) { s_logger.error("SSH test fail with error", e); System.exit(2); } } }
{ "pile_set_name": "Github" }
{ "acno": "D40572", "acquisitionYear": 1856, "additionalImages": [ { "copyright": null, "creativeCommons": null, "filenameBase": "D40572", "sizes": [ { "caption": "Enhanced image", "cleared": true, "file": "enhanced_images/D405/D40572_E.jpg", "height": 337, "resolution": 512, "size": "large", "width": 512 } ] } ], "all_artists": "Joseph Mallord William Turner", "catTextResId": 1129878, "catalogueGroup": { "accessionRanges": "D05491-D05617; D40568-D40574; D41505", "completeStatus": "COMPLETE", "finbergNumber": "XC", "groupType": "Turner Sketchbook", "id": 65737, "shortTitle": "Studies for Pictures: Isleworth Sketchbook" }, "classification": "on paper, unique", "contributorCount": 1, "contributors": [ { "birthYear": 1775, "date": "1775\u20131851", "displayOrder": 1, "fc": "Joseph Mallord William Turner", "gender": "Male", "id": 558, "mda": "Turner, Joseph Mallord William", "role": "artist", "startLetter": "T" } ], "creditLine": "Accepted by the nation as part of the Turner Bequest 1856", "dateRange": { "endYear": 1805, "startYear": 1805, "text": "1805" }, "dateText": "1805", "depth": "", "dimensions": "support: 150 x 258 mm", "finberg": null, "foreignTitle": null, "groupTitle": "Studies for Pictures: Isleworth Sketchbook", "height": "258", "id": 64321, "inscription": null, "medium": "Pen and ink on paper", "movementCount": 0, "pageNumber": 98, "subjectCount": 1, "subjects": { "children": [ { "children": [ { "children": [ { "id": 1827, "name": "tree" } ], "id": 1809, "name": "trees" } ], "id": 60, "name": "nature" } ], "id": 1, "name": "subject" }, "thumbnailCopyright": null, "thumbnailUrl": "http://www.tate.org.uk/art/images/work/D/D40/D40572_8.jpg", "title": "A View on the Thames", "units": "mm", "url": "http://www.tate.org.uk/art/artworks/turner-a-view-on-the-thames-d40572", "width": "150" }
{ "pile_set_name": "Github" }
// // Created by Dusan Klinec on 28.12.17. // #include <gtest/gtest.h> #include "../WBAES.h" #include "../WBAESGenerator.h" #include "../EncTools.h" #include "Commons.h" using namespace std; TEST(WBAES, GenerateKey) { initDefaultModulus(); shared_ptr<WBAES> wbaes(new WBAES()); WBAESGenerator generator; ExtEncoding coding; generator.generateExtEncoding(&coding, 0); generator.generateTables(const_cast<BYTE *>(test_key), KEY_SIZE_16, wbaes.get(), &coding, true); generator.generateTables(const_cast<BYTE *>(test_key), KEY_SIZE_16, wbaes.get(), &coding, false); W128b plain{}, cipher{}, state{}; arr_to_W128b(const_cast<BYTE *>(test_plaintext), 0, plain); arr_to_W128b(const_cast<BYTE *>(test_plaintext), 0, state); arr_to_W128b(const_cast<BYTE *>(test_ciphertext), 0, cipher); generator.applyExternalEnc(state, &coding, true); wbaes->encrypt(state); generator.applyExternalEnc(state, &coding, false); EXPECT_TRUE(compare_W128b(state, cipher)); generator.applyExternalEnc(state, &coding, true); wbaes->decrypt(state); generator.applyExternalEnc(state, &coding, false); EXPECT_TRUE(compare_W128b(state, plain)); std::stringstream inout; generator.save(inout, wbaes.get(), &coding); } TEST(WBAES, EncDec) { initDefaultModulus(); std::stringstream inout; // Generating part // Different scope to prevent unwanted access after generation. { shared_ptr<WBAES> wbaes(new WBAES()); WBAESGenerator generator; ExtEncoding coding; generator.generateExtEncoding(&coding, 0); generator.generateTables(const_cast<BYTE *>(test_key), KEY_SIZE_16, wbaes.get(), &coding, true); generator.generateTables(const_cast<BYTE *>(test_key), KEY_SIZE_16, wbaes.get(), &coding, false); generator.save(inout, wbaes.get(), &coding); } // Load phase shared_ptr<WBAES> wbaes2(new WBAES()); WBAESGenerator generator2; ExtEncoding coding2; generator2.load(inout, wbaes2.get(), &coding2); W128b plain{}, cipher{}, state{}; arr_to_W128b(const_cast<BYTE *>(test_plaintext), 0, plain); arr_to_W128b(const_cast<BYTE *>(test_plaintext), 0, state); arr_to_W128b(const_cast<BYTE *>(test_ciphertext), 0, cipher); generator2.applyExternalEnc(state, &coding2, true); wbaes2->encrypt(state); generator2.applyExternalEnc(state, &coding2, false); EXPECT_TRUE(compare_W128b(state, cipher)); generator2.applyExternalEnc(state, &coding2, true); wbaes2->decrypt(state); generator2.applyExternalEnc(state, &coding2, false); EXPECT_TRUE(compare_W128b(state, plain)); } TEST(WBAES, TestVectors) { initDefaultModulus(); WBAESGenerator generator; shared_ptr<WBAES> wbaes(new WBAES()); // Test WB AES with test vectors. // This test also demonstrates usage of external encodings by wrapping AES int errors = generator.testWithVectors(false, wbaes.get()); EXPECT_EQ(errors, 0); // Test WB AES with test vectors - no external encoding. errors = generator.testWithVectors(false, wbaes.get(), WBAESGEN_EXTGEN_ID); EXPECT_EQ(errors, 0); }
{ "pile_set_name": "Github" }
The direct utility estimation method in Section <a class="sectionRef" title="" href="#">passive-rl-section</a> uses distinguished terminal states to indicate the end of a trial. How could it be modified for environments with discounted rewards and no terminal states?
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: 012c135e7de4d094baea093d738625b2 folderAsset: yes DefaultImporter: userData: assetBundleName:
{ "pile_set_name": "Github" }
/** * Buttons * -------------------------------------------------- */ .button { // set the color defaults @include button-style($button-default-bg, $button-default-border, $button-default-active-bg, $button-default-active-border, $button-default-text); position: relative; display: inline-block; margin: 0; padding: 0 $button-padding; min-width: ($button-padding * 3) + $button-font-size; min-height: $button-height + 5px; border-width: $button-border-width; border-style: solid; border-radius: $button-border-radius; vertical-align: top; text-align: center; text-overflow: ellipsis; font-size: $button-font-size; line-height: $button-height - $button-border-width + 1px; cursor: pointer; &:after { // used to create a larger button "hit" area position: absolute; top: -6px; right: -6px; bottom: -6px; left: -6px; content: ' '; } .icon { vertical-align: top; pointer-events: none; } .icon:before, &.icon:before, &.icon-left:before, &.icon-right:before { display: inline-block; padding: 0 0 $button-border-width 0; vertical-align: inherit; font-size: $button-icon-size; line-height: $button-height - $button-border-width; pointer-events: none; } &.icon-left:before { float: left; padding-right: .2em; padding-left: 0; } &.icon-right:before { float: right; padding-right: 0; padding-left: .2em; } &.button-block, &.button-full { margin-top: $button-block-margin; margin-bottom: $button-block-margin; } &.button-light { @include button-style($button-light-bg, $button-default-border, $button-light-active-bg, $button-default-active-border, $button-light-text); @include button-clear($button-light-border); @include button-outline($button-light-border); } &.button-stable { @include button-style($button-stable-bg, $button-default-border, $button-stable-active-bg, $button-default-active-border, $button-stable-text); @include button-clear($button-stable-border); @include button-outline($button-stable-border); } &.button-positive { @include button-style($button-positive-bg, $button-default-border, $button-positive-active-bg, $button-default-active-border, $button-positive-text); @include button-clear($button-positive-bg); @include button-outline($button-positive-bg); } &.button-calm { @include button-style($button-calm-bg, $button-default-border, $button-calm-active-bg, $button-default-active-border, $button-calm-text); @include button-clear($button-calm-bg); @include button-outline($button-calm-bg); } &.button-assertive { @include button-style($button-assertive-bg, $button-default-border, $button-assertive-active-bg, $button-default-active-border, $button-assertive-text); @include button-clear($button-assertive-bg); @include button-outline($button-assertive-bg); } &.button-balanced { @include button-style($button-balanced-bg, $button-default-border, $button-balanced-active-bg, $button-default-active-border, $button-balanced-text); @include button-clear($button-balanced-bg); @include button-outline($button-balanced-bg); } &.button-energized { @include button-style($button-energized-bg, $button-default-border, $button-energized-active-bg, $button-default-active-border, $button-energized-text); @include button-clear($button-energized-bg); @include button-outline($button-energized-bg); } &.button-royal { @include button-style($button-royal-bg, $button-default-border, $button-royal-active-bg, $button-default-active-border, $button-royal-text); @include button-clear($button-royal-bg); @include button-outline($button-royal-bg); } &.button-dark { @include button-style($button-dark-bg, $button-default-border, $button-dark-active-bg, $button-default-active-border, $button-dark-text); @include button-clear($button-dark-bg); @include button-outline($button-dark-bg); } } .button-small { padding: 2px $button-small-padding 1px; min-width: $button-small-height; min-height: $button-small-height + 2; font-size: $button-small-font-size; line-height: $button-small-height - $button-border-width - 1; .icon:before, &.icon:before, &.icon-left:before, &.icon-right:before { font-size: $button-small-icon-size; line-height: $button-small-icon-size + 3; margin-top: 3px; } } .button-large { padding: 0 $button-large-padding; min-width: ($button-large-padding * 3) + $button-large-font-size; min-height: $button-large-height + 5; font-size: $button-large-font-size; line-height: $button-large-height - $button-border-width; .icon:before, &.icon:before, &.icon-left:before, &.icon-right:before { padding-bottom: ($button-border-width * 2); font-size: $button-large-icon-size; line-height: $button-large-height - ($button-border-width * 2) - 1; } } .button-icon { @include transition(opacity .1s); padding: 0 6px; min-width: initial; border-color: transparent; background: none; &.button.active, &.button.activated { border-color: transparent; background: none; box-shadow: none; opacity: 0.3; } .icon:before, &.icon:before { font-size: $button-large-icon-size; } } .button-clear { @include button-clear($button-default-border); @include transition(opacity .1s); padding: 0 $button-clear-padding; max-height: $button-height; border-color: transparent; background: none; box-shadow: none; &.active, &.activated { opacity: 0.3; } } .button-outline { @include button-outline($button-default-border); @include transition(opacity .1s); background: none; box-shadow: none; } .padding > .button.button-block:first-child { margin-top: 0; } .button-block { display: block; clear: both; &:after { clear: both; } } .button-full, .button-full > .button { display: block; margin-right: 0; margin-left: 0; border-right-width: 0; border-left-width: 0; border-radius: 0; } button.button-block, button.button-full, .button-full > button.button, input.button.button-block { width: 100%; } a.button { text-decoration: none; .icon:before, &.icon:before, &.icon-left:before, &.icon-right:before { margin-top: 2px; } } .button.disabled, .button[disabled] { opacity: .4; cursor: default !important; pointer-events: none; }
{ "pile_set_name": "Github" }
'use strict'; module.exports = function(Chart) { var helpers = Chart.helpers; Chart.scaleService = { // Scale registration object. Extensions can register new scale types (such as log or DB scales) and then // use the new chart options to grab the correct scale constructors: {}, // Use a registration function so that we can move to an ES6 map when we no longer need to support // old browsers // Scale config defaults defaults: {}, registerScaleType: function(type, scaleConstructor, defaults) { this.constructors[type] = scaleConstructor; this.defaults[type] = helpers.clone(defaults); }, getScaleConstructor: function(type) { return this.constructors.hasOwnProperty(type) ? this.constructors[type] : undefined; }, getScaleDefaults: function(type) { // Return the scale defaults merged with the global settings so that we always use the latest ones return this.defaults.hasOwnProperty(type) ? helpers.scaleMerge(Chart.defaults.scale, this.defaults[type]) : {}; }, updateScaleDefaults: function(type, additions) { var defaults = this.defaults; if (defaults.hasOwnProperty(type)) { defaults[type] = helpers.extend(defaults[type], additions); } }, addScalesToLayout: function(chart) { // Adds each scale to the chart.boxes array to be sized accordingly helpers.each(chart.scales, function(scale) { // Set ILayoutItem parameters for backwards compatibility scale.fullWidth = scale.options.fullWidth; scale.position = scale.options.position; scale.weight = scale.options.weight; Chart.layoutService.addBox(chart, scale); }); } }; };
{ "pile_set_name": "Github" }
describe Wordmove::Doctor::Mysql do let(:movefile_name) { 'multi_environments' } let(:movefile_dir) { "spec/fixtures/movefiles" } let(:doctor) { described_class.new(movefile_name, movefile_dir) } context ".new" do it "implements #check! method" do expect_any_instance_of(described_class).to receive(:check!) silence_stream(STDOUT) { doctor.check! } end it "calls mysql client check" do expect(doctor).to receive(:mysql_client_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysqldump check" do expect(doctor).to receive(:mysqldump_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysql server check" do expect(doctor).to receive(:mysql_server_doctor) silence_stream(STDOUT) { doctor.check! } end it "calls mysql database check" do # expect(doctor).to receive(:mysql_database_doctor) silence_stream(STDOUT) { doctor.check! } end end end
{ "pile_set_name": "Github" }
b9be2701e164b0f70a8abd4916bf98b34f4f7233
{ "pile_set_name": "Github" }
package mirror.android.os; import android.os.Parcel; import mirror.RefClass; import mirror.RefObject; public class BundleICS { public static Class<?> TYPE = RefClass.load(BundleICS.class, "android.os.Bundle"); public static RefObject<Parcel> mParcelledData; }
{ "pile_set_name": "Github" }
/* * Copyright 2011 David Jurgens * * This file is part of the S-Space package and is covered under the terms and * conditions therein. * * The S-Space package is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation and distributed hereunder to you. * * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES, * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER * RIGHTS. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package edu.ucla.sspace.graph; import java.util.*; import edu.ucla.sspace.util.OpenIntSet; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; /** * */ public class DirectedMultigraphTests { @Test public void testConstructor() { Set<Integer> vertices = new HashSet<Integer>(); DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertEquals(0, g.order()); assertEquals(0, g.size()); } @Test(expected=NullPointerException.class) public void testConstructor2NullArg() { Graph<Edge> g = new SparseUndirectedGraph((Graph<DirectedTypedEdge<String>>)null); } @Test public void testAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(0)); assertEquals(1, g.order()); assertTrue(g.contains(0)); // second add should have no effect assertFalse(g.add(0)); assertEquals(1, g.order()); assertTrue(g.contains(0)); assertTrue(g.add(1)); assertEquals(2, g.order()); assertTrue(g.contains(1)); } @Test public void testEquals() { DirectedMultigraph<String> g1 = new DirectedMultigraph<String>(); DirectedMultigraph<String> g2 = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } } assertEquals(g1, g2); g1 = new DirectedMultigraph<String>(); g2 = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",j, i)); } } assertFalse(g1.equals(g2)); assertFalse(g2.equals(g1)); } @Test public void testEqualGeneric() { DirectedMultigraph<String> g1 = new DirectedMultigraph<String>(); Graph<DirectedTypedEdge<String>> g2 = new GenericGraph<DirectedTypedEdge<String>>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { g1.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g2.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } } assertEquals(g1, g2); } @Test public void testContainsEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 100; ++i) for (int j = i + 1; j < 100; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); for (int i = 0; i < 100; ++i) { for (int j = i + 1; j < 100; ++j) { g.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g.contains(new SimpleDirectedTypedEdge<String>("type-1",j, i)); g.contains(i, j); g.contains(j, i); } } } @Test public void testAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(2, g.order()); assertEquals(1, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2)); assertEquals(3, g.order()); assertEquals(2, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 2))); g.add(new SimpleDirectedTypedEdge<String>("type-1",3, 4)); assertEquals(5, g.order()); assertEquals(3, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",3, 4))); } @Test public void testRemoveLesserVertexWithEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 1; i < 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); } assertTrue(g.contains(0)); assertTrue(g.remove(0)); assertEquals(99, g.order()); assertEquals(0, g.size()); } @Test public void testRemoveHigherVertexWithEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 99; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",100, i); g.add(e); } assertTrue(g.contains(100)); assertTrue(g.remove(100)); assertEquals(99, g.order()); assertEquals(0, g.size()); } @Test public void testRemoveVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 100; ++i) { g.add(i); } for (int i = 99; i >= 0; --i) { assertTrue(g.remove(i)); assertEquals(i, g.order()); assertFalse(g.contains(i)); assertFalse(g.remove(i)); } } @Test public void testRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 1; i < 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); } for (int i = 99; i > 0; --i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); assertTrue(g.remove(e)); assertEquals(i-1, g.size()); assertFalse(g.contains(e)); assertFalse(g.remove(e)); } } @Test public void testVertexIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } assertEquals(control.size(), g.order()); for (Integer i : g.vertices()) assertTrue(control.contains(i)); } @Test public void testEdgeIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { assertTrue(control.remove(e)); returned++; } assertEquals(g.size(), returned); assertEquals(0, control.size()); } @Test public void testEdgeIteratorSmall() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 5; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); assertTrue(g.add(e)); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { System.out.println(e); assertTrue(control.contains(e)); returned++; } assertEquals(control.size(), returned); } @Test public void testEdgeIteratorSmallReverse() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 5; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, 0); g.add(e); control.add(e); } assertEquals(control.size(), g.size()); assertEquals(control.size(), g.edges().size()); int returned = 0; for (Edge e : g.edges()) { System.out.println(e); assertTrue(control.contains(e)); returned++; } assertEquals(control.size(), returned); } @Test public void testAdjacentEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); } @Test public void testAdjacencyListSize() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<DirectedTypedEdge<String>> adjList = g.getAdjacencyList(0); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(1); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(2); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(3); assertEquals(9, adjList.size()); adjList = g.getAdjacencyList(5); assertEquals(9, adjList.size()); } @Test public void testAdjacentEdgesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); Edge removed = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertTrue(test.remove(removed)); assertTrue(control.remove(removed)); assertEquals(control, test); assertEquals(99, g.size()); } @Test public void testAdjacentEdgesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 1; i <= 100; ++i) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, i); g.add(e); control.add(e); } Set<DirectedTypedEdge<String>> test = g.getAdjacencyList(0); assertEquals(control, test); DirectedTypedEdge<String> added = new SimpleDirectedTypedEdge<String>("type-1",0, 101); assertTrue(test.add(added)); assertTrue(control.add(added)); assertEquals(control, test); assertEquals(101, g.size()); assertTrue(g.contains(added)); assertTrue(g.contains(101)); assertEquals(102, g.order()); } @Test public void testClear() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); g.clear(); assertEquals(0, g.size()); assertEquals(0, g.order()); assertEquals(0, g.vertices().size()); assertEquals(0, g.edges().size()); // Error checking case for double-clear g.clear(); } @Test public void testClearEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); g.clearEdges(); assertEquals(0, g.size()); assertEquals(10, g.order()); assertEquals(10, g.vertices().size()); assertEquals(0, g.edges().size()); // Error checking case for double-clear g.clearEdges(); } @Test public void testToString() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); g.toString(); // only vertices g.clearEdges(); g.toString(); // empty graph g.clear(); g.toString(); } /****************************************************************** * * * VertexSet tests * * ******************************************************************/ @Test(expected=UnsupportedOperationException.class) public void testVertexSetAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(vertices.add(100)); assertTrue(g.contains(100)); assertEquals(101, vertices.size()); assertEquals(101, g.order()); // dupe assertFalse(vertices.add(100)); assertEquals(101, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetAddFromGraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.add(100)); assertTrue(g.contains(100)); assertTrue(vertices.contains(100)); assertEquals(101, vertices.size()); assertEquals(101, g.order()); // dupe assertFalse(vertices.add(100)); assertEquals(101, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.contains(99)); assertTrue(vertices.remove(99)); assertFalse(g.contains(99)); assertEquals(99, vertices.size()); assertEquals(99, g.order()); // dupe assertFalse(vertices.remove(99)); assertEquals(99, vertices.size()); } @Test public void testVertexSetRemoveFromGraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); assertTrue(g.remove(99)); assertFalse(g.contains(99)); assertFalse(vertices.contains(99)); assertEquals(99, vertices.size()); assertEquals(99, g.order()); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); assertEquals(control.size(), vertices.size()); Iterator<Integer> iter = vertices.iterator(); assertTrue(iter.hasNext()); Integer toRemove = iter.next(); assertTrue(g.contains(toRemove)); assertTrue(vertices.contains(toRemove)); iter.remove(); assertFalse(g.contains(toRemove)); assertFalse(vertices.contains(toRemove)); assertEquals(g.order(), vertices.size()); } @Test(expected=NoSuchElementException.class) public void testVertexSetIteratorTooFar() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); int i = 0; while (iter.hasNext()) { i++; iter.next(); } assertEquals(vertices.size(), i); iter.next(); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveTwice() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); assertTrue(iter.hasNext()); Integer toRemove = iter.next(); assertTrue(g.contains(toRemove)); assertTrue(vertices.contains(toRemove)); iter.remove(); iter.remove(); } @Test(expected=UnsupportedOperationException.class) public void testVertexSetIteratorRemoveEarly() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<Integer> control = new HashSet<Integer>(); for (int i = 0; i < 100; ++i) { g.add(i); control.add(i); } Set<Integer> vertices = g.vertices(); Iterator<Integer> iter = vertices.iterator(); iter.remove(); } /****************************************************************** * * * EdgeView tests * * ******************************************************************/ @Test public void testEdgeViewAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); assertEquals(g.size(), edges.size()); edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); assertEquals(2, g.order()); assertEquals(1, g.size()); assertEquals(1, edges.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } @Test public void testEdgeViewRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); assertEquals(g.size(), edges.size()); edges.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); edges.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); assertEquals(2, g.order()); assertEquals(0, g.size()); assertEquals(0, edges.size()); assertFalse(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } @Test public void testEdgeViewIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 0; i < 100; i += 2) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1); g.add(e); // all disconnected control.add(e); } assertEquals(100, g.order()); assertEquals(50, g.size()); assertEquals(50, edges.size()); Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); for (DirectedTypedEdge<String> e : edges) test.add(e); assertEquals(control.size(), test.size()); for (Edge e : test) assertTrue(control.contains(e)); } @Test public void testEdgeViewIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> edges = g.edges(); Set<DirectedTypedEdge<String>> control = new HashSet<DirectedTypedEdge<String>>(); for (int i = 0; i < 10; i += 2) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, i+1); g.add(e); // all disconnected control.add(e); } assertEquals(10, g.order()); assertEquals(5, g.size()); assertEquals(5, edges.size()); Iterator<DirectedTypedEdge<String>> iter = edges.iterator(); while (iter.hasNext()) { iter.next(); iter.remove(); } assertEquals(0, g.size()); assertFalse(g.edges().iterator().hasNext()); assertEquals(0, edges.size()); assertEquals(10, g.order()); } /****************************************************************** * * * AdjacencyListView tests * * ******************************************************************/ @Test public void testAdjacencyList() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); for (int i = 0; i < 10; ++i) { Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(i); assertEquals(9, adjacencyList.size()); for (int j = 0; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); if (i >= j) assertFalse(adjacencyList.contains(e)); else assertTrue(adjacencyList.contains(e)); } } } @Test public void testAdjacencyListRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); Edge e = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertTrue(adjacencyList.contains(e)); assertTrue(adjacencyList.remove(e)); assertEquals(8, adjacencyList.size()); assertEquals( (10 * 9) / 2 - 1, g.size()); } public void testAdjacencyListAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) for (int j = i + 2; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); assertEquals( (10 * 9) / 2 - 9, g.size()); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",0, 1); assertFalse(adjacencyList.contains(e)); assertFalse(g.contains(e)); assertTrue(adjacencyList.add(e)); assertTrue(g.contains(e)); assertEquals(9, adjacencyList.size()); assertEquals( (10 * 9) / 2 - 8, g.size()); } @Test public void testAdjacencyListIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); int i = 0; while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); } @Test public void testAdjacencyListNoVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(0, adjacencyList.size()); } @Test(expected=NoSuchElementException.class) public void testAdjacencyListIteratorNextOffEnd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); int i = 0; while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); it.next(); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); assertTrue(it.hasNext()); Edge e = it.next(); it.remove(); assertFalse(adjacencyList.contains(e)); assertEquals(8, adjacencyList.size()); assertFalse(g.contains(e)); assertEquals( (10 * 9) / 2 - 1, g.size()); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemoveFirst() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); it.remove(); } @Test(expected=UnsupportedOperationException.class) public void testAdjacencyListIteratorRemoveTwice() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<DirectedTypedEdge<String>> test = new HashSet<DirectedTypedEdge<String>>(); Set<DirectedTypedEdge<String>> adjacencyList = g.getAdjacencyList(0); assertEquals(9, adjacencyList.size()); Iterator<DirectedTypedEdge<String>> it = adjacencyList.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); it.remove(); } /****************************************************************** * * * AdjacentVerticesView tests * * ******************************************************************/ @Test public void testAdjacentVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); assertEquals(9, adjacent.size()); for (int i = 1; i < 10; ++i) assertTrue(adjacent.contains(i)); assertFalse(adjacent.contains(0)); assertFalse(adjacent.contains(10)); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); adjacent.add(1); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); adjacent.remove(1); } @Test public void testAdjacentVerticesIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); Iterator<Integer> it = adjacent.iterator(); while (it.hasNext()) assertTrue(test.add(it.next())); assertEquals(9, test.size()); } @Test(expected=UnsupportedOperationException.class) public void testAdjacentVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); for (int i = 0; i < 10; ++i) { for (int j = i + 1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); g.add(e); } } Set<Integer> test = new HashSet<Integer>(); Set<Integer> adjacent = g.getNeighbors(0); Iterator<Integer> it = adjacent.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); } /****************************************************************** * * * Subgraph tests * * ******************************************************************/ @Test public void testSubgraph() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); } @Test public void testSubgraphContainsVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); for (int i = 0; i < 5; ++i) assertTrue(subgraph.contains(i)); for (int i = 5; i < 10; ++i) { assertTrue(g.contains(i)); assertFalse(subgraph.contains(i)); } } @Test public void testSubgraphContainsEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); for (int i = 0; i < 5; ++i) { for (int j = i+1; j < 5; ++j) { assertTrue(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",i, j))); } } for (int i = 5; i < 10; ++i) { for (int j = i+1; j < 10; ++j) { DirectedTypedEdge<String> e = new SimpleDirectedTypedEdge<String>("type-1",i, j); assertTrue(g.contains(e)); assertFalse(subgraph.contains(e)); } } } @Test public void testSubgraphAddEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < i+2 && j < 10; ++j) assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j))); } assertEquals(9, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals(4, subgraph.size()); // Add an edge to a new vertex assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0))); assertEquals(5, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAddEdgeNewVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); // Add an edge to a new vertex assertTrue(subgraph.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5))); assertEquals( (5 * 4) / 2 + 1, subgraph.size()); assertEquals(6, subgraph.order()); assertEquals(11, g.order()); assertEquals( (9*10)/2 + 1, g.size()); } @Test public void testSubgraphRemoveEdge() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); // Remove an existing edge assertTrue(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals( (5 * 4) / 2 - 1, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.order()); assertEquals( (9*10)/2 - 1, g.size()); // Remove a non-existent edge, which should have no effect even though // the edge is present in the backing graph assertFalse(subgraph.remove(new SimpleDirectedTypedEdge<String>("type-1",0, 6))); assertEquals( (5 * 4) / 2 - 1, subgraph.size()); assertEquals(5, subgraph.order()); assertEquals(10, g.order()); assertEquals( (9*10)/2 - 1, g.size()); } /****************************************************************** * * * SubgraphVertexView tests * * ******************************************************************/ @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); // Add a vertex assertTrue(test.add(5)); assertEquals(6, test.size()); assertEquals(6, subgraph.order()); assertEquals(11, g.order()); assertEquals( (5*4)/2, subgraph.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); // Add a vertex assertTrue(test.remove(0)); assertEquals(4, test.size()); assertEquals(4, subgraph.order()); assertEquals(9, g.order()); assertEquals( (4*3)/2, subgraph.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); assertEquals(5, subgraph.order()); assertEquals( (5 * 4) / 2, subgraph.size()); Set<Integer> test = subgraph.vertices(); assertEquals(5, test.size()); Iterator<Integer> it = test.iterator(); assertTrue(it.hasNext()); // Remove the first vertex returned it.next(); it.remove(); assertEquals(4, test.size()); assertEquals(4, subgraph.order()); assertEquals(9, g.order()); assertEquals( (4*3)/2, subgraph.size()); } /****************************************************************** * * * SubgraphEdgeView tests * * ******************************************************************/ @Test public void testSubgraphEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { g.add(i); } g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1)); g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 2)); g.add(new SimpleDirectedTypedEdge<String>("type-1",1, 2)); assertEquals(3, g.size()); Set<Integer> verts = new HashSet<Integer>(); for (int i = 0; i < 3; ++i) verts.add(i); DirectedMultigraph<String> sub = g.subgraph(verts); assertEquals(3, sub.order()); assertEquals(3, sub.size()); Set<DirectedTypedEdge<String>> edges = sub.edges(); assertEquals(3, edges.size()); int j = 0; Iterator<DirectedTypedEdge<String>> iter = edges.iterator(); while (iter.hasNext()) { iter.next(); j++; } assertEquals(3, j); verts.clear(); for (int i = 3; i < 6; ++i) verts.add(i); sub = g.subgraph(verts); assertEquals(3, sub.order()); assertEquals(0, sub.size()); edges = sub.edges(); assertEquals(0, edges.size()); iter = edges.iterator(); assertFalse(iter.hasNext()); } /****************************************************************** * * * SubgraphAdjacencyListView tests * * ******************************************************************/ @Test public void testSubgraphAdjacencyListContains() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); for (int i = 1; i < 5; ++i) assertTrue(adjList.contains(new SimpleDirectedTypedEdge<String>("type-1",0, i))); for (int i = 5; i < 10; ++i) assertFalse(adjList.contains(new SimpleDirectedTypedEdge<String>("type-1",0, i))); } @Test public void testSubgraphAdjacencyListSize() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(1); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(2); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(3); assertEquals(4, adjList.size()); adjList = subgraph.getAdjacencyList(4); assertEquals(4, adjList.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacencyListAddNewVertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> adjList = subgraph.getAdjacencyList(0); // Add an edge to a new vertex assertTrue(adjList.add(new SimpleDirectedTypedEdge<String>("type-1",0, 5))); } /****************************************************************** * * * SubgraphAdjacentVerticesView tests * * ******************************************************************/ @Test public void testSubgraphAdjacentVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(4, adjacent.size()); // check contents for (int i = 1; i < 5; ++i) assertTrue(adjacent.contains(i)); adjacent = subgraph.getNeighbors(1); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(2); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(3); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(4); assertEquals(4, adjacent.size()); adjacent = subgraph.getNeighbors(5); assertEquals(0, adjacent.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesAdd() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); adjacent.add(0); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<Integer> adjacent = subgraph.getNeighbors(0); adjacent.remove(0); } @Test public void testSubgraphAdjacentVerticesIterator() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); vertices.remove(0); // now is the adjacent vertices of 0 Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(vertices, adjacent); Iterator<Integer> it = adjacent.iterator(); int i = 0; while (it.hasNext()) { i++; vertices.remove(it.next()); } assertEquals(4, i); assertEquals(0, vertices.size()); } @Test(expected=UnsupportedOperationException.class) public void testSubgraphAdjacentVerticesIteratorRemove() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); vertices.remove(0); // now is the adjacent vertices of 0 Set<Integer> adjacent = subgraph.getNeighbors(0); assertEquals(vertices, adjacent); Iterator<Integer> it = adjacent.iterator(); assertTrue(it.hasNext()); it.next(); it.remove(); } /****************************************************************** * * * Tests that create a subgraph and then modify the backing graph * * ******************************************************************/ @Test public void testSubgraphWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); g.remove(0); assertEquals(4, subgraph.order()); assertEquals((3 * 4) / 2, subgraph.size()); g.remove(1); assertFalse(subgraph.contains(1)); g.remove(2); assertFalse(subgraph.contains(new SimpleDirectedTypedEdge<String>("type-1",2,3))); } @Test public void testSubgraphVertexIteratorWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); g.remove(0); Iterator<Integer> it = subgraph.vertices().iterator(); int i = 0; while (it.hasNext()) { assertTrue(0 != it.next()); i++; } assertEquals(4, i); } @Test public void testSubgraphEdgesWhenVerticesRemovedFromBacking() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); // fully connected for (int i = 0; i < 10; i++) { for (int j = i+1; j < 10; ++j) g.add(new SimpleDirectedTypedEdge<String>("type-1",i, j)); } // (n * (n-1)) / 2 assertEquals( (10 * 9) / 2, g.size()); assertEquals(10, g.order()); Set<Integer> vertices = new LinkedHashSet<Integer>(); for (int i = 0; i < 5; ++i) vertices.add(i); DirectedMultigraph<String> subgraph = g.subgraph(vertices); Set<DirectedTypedEdge<String>> edges = subgraph.edges(); g.remove(0); assertEquals((4 * 3) / 2, edges.size()); assertFalse(edges.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); } /**************** * * * Tests on graphs with multiple edge types * * ****************/ @Test public void testAddTypedEdges() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(2, g.order()); assertEquals(1, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertEquals(1, g.edgeTypes().size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertEquals(2, g.order()); assertEquals(2, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertEquals(2, g.edgeTypes().size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertEquals(4, g.order()); assertEquals(3, g.size()); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); assertEquals(3, g.edgeTypes().size()); } @Test public void testNeighborsOfDifferentTypes() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 0, 3))); Set<Integer> neighbors = g.getNeighbors(0); assertEquals(3, g.size()); assertEquals(3, neighbors.size()); assertTrue(neighbors.contains(1)); assertTrue(neighbors.contains(2)); assertTrue(neighbors.contains(3)); // Test bi-directional case assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 2, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 0))); neighbors = g.getNeighbors(0); assertEquals(3, neighbors.size()); assertEquals(6, g.size()); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 4, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 5, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 6, 0))); neighbors = g.getNeighbors(0); assertEquals(6, neighbors.size()); assertEquals(9, g.size()); for (int i = 1; i <= 6; ++i) assertTrue(neighbors.contains(i)); } @Test public void testSubgraphOfSubtype() { // set up the network DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); verts.add(0); verts.add(1); Set<String> types = Collections.singleton("type-1"); DirectedMultigraph<String> sub = g.subgraph(g.vertices(), types); assertEquals(1, sub.edgeTypes().size()); assertEquals(3, sub.size()); assertEquals(g.order(), sub.order()); assertFalse(sub.contains(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); } /**************** * * * Tests for copy() * * ****************/ @Test public void testCopyAllVertices() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(g.vertices()); assertEquals(g.order(), copy.order()); assertEquals(g.size(), copy.size()); assertEquals(g, copy); copy.remove(4); assertEquals(4, g.order()); assertEquals(3, copy.order()); } @Test public void testCopy1vertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(Collections.singleton(1)); assertEquals(1, copy.order()); assertEquals(0, copy.size()); } @Test public void testCopy2vertex() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(2, copy.order()); assertEquals(2, copy.size()); } @Test public void testCopy3vertexTriangle() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 2, 0))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 2, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1, 2); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(3, copy.order()); assertEquals(7, copy.size()); } @Test public void testCopy3vertexVee() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 1, 2))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1", 2, 3))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); Set<Integer> verts = new HashSet<Integer>(); Collections.addAll(verts, 0, 1, 2); DirectedMultigraph<String> copy = g.copy(verts); assertEquals(3, copy.order()); assertEquals(5, copy.size()); } @Test public void testEmptyCopy() { DirectedMultigraph<String> g = new DirectedMultigraph<String>(); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-1",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-2",0, 1))); assertTrue(g.add(new SimpleDirectedTypedEdge<String>("type-3", 3, 4))); assertTrue(g.contains(new SimpleDirectedTypedEdge<String>("type-3",3, 4))); DirectedMultigraph<String> copy = g.copy(Collections.<Integer>emptySet()); assertEquals(0, copy.order()); assertEquals(0, copy.size()); assertEquals(new DirectedMultigraph<String>(), copy); copy.add(5); assertTrue(copy.contains(5)); assertFalse(g.contains(5)); } /* * To test: * * - remove vertex causes edge type to no longer be present (graph + subgraph) * - remove a vertex and then add the vertex back in (not present in subgraph) * - all of the DirectedGraph methods * */ }
{ "pile_set_name": "Github" }
package org.matomo.sdk.dispatcher; import androidx.annotation.Nullable; public enum DispatchMode { /** * Dispatch always (default) */ ALWAYS("always"), /** * Dispatch only on WIFI */ WIFI_ONLY("wifi_only"), /** * The dispatcher will assume being offline. This is not persisted and will revert on app restart. * Ensures no information is lost when tracking exceptions. See #247 */ EXCEPTION("exception"); private final String key; DispatchMode(String key) {this.key = key;} @Override public String toString() { return key; } @Nullable public static DispatchMode fromString(String raw) { for (DispatchMode mode : DispatchMode.values()) { if (mode.key.equals(raw)) return mode; } return null; } }
{ "pile_set_name": "Github" }
Certificate: Data: Version: 3 (0x2) Serial Number: 4 (0x4) Signature Algorithm: ecdsa-with-SHA256 Issuer: CN=prime256v1 ecdsa Test intermediate CA Validity Not Before: Apr 22 20:28:41 2016 GMT Not After : Apr 20 20:28:41 2026 GMT Subject: C=US, ST=California, L=Mountain View, O=Test CA, CN=127.0.0.1 Subject Public Key Info: Public Key Algorithm: id-ecPublicKey Public-Key: (256 bit) pub: 04:f5:4f:70:de:c3:d2:11:bb:c8:08:6e:4c:63:d8: 13:80:10:b0:b8:e9:df:9c:fa:d0:f4:e3:61:5e:1e: 1f:fe:65:8e:4b:a9:3f:d4:47:9f:71:e9:89:82:82: d8:10:63:fa:af:37:5b:3b:d1:da:56:05:da:a2:20: e1:20:37:c3:c0 ASN1 OID: prime256v1 X509v3 extensions: X509v3 Basic Constraints: critical CA:FALSE X509v3 Subject Key Identifier: 7E:DD:18:69:14:9C:D6:E5:9C:DD:47:DB:87:60:79:AD:01:07:9A:66 X509v3 Authority Key Identifier: keyid:0D:6B:B6:D7:DD:7F:CD:4E:AD:06:6B:22:E1:11:08:58:10:AB:16:2A X509v3 Extended Key Usage: TLS Web Server Authentication, TLS Web Client Authentication X509v3 Subject Alternative Name: IP Address:127.0.0.1 Signature Algorithm: ecdsa-with-SHA256 30:45:02:20:25:fd:ba:76:81:1b:d3:25:17:82:31:ad:73:72: 50:94:ac:e3:69:a6:b1:58:fe:b7:5e:48:ed:23:0d:a2:05:40: 02:21:00:d5:0e:02:63:c9:1c:7a:5a:10:13:1e:b8:05:87:71: 9c:b5:e2:66:cb:27:c8:17:b3:b1:68:29:c4:5e:b9:ac:5f -----BEGIN CERTIFICATE----- MIICADCCAaagAwIBAgIBBDAKBggqhkjOPQQDAjAwMS4wLAYDVQQDDCVwcmltZTI1 NnYxIGVjZHNhIFRlc3QgaW50ZXJtZWRpYXRlIENBMB4XDTE2MDQyMjIwMjg0MVoX DTI2MDQyMDIwMjg0MVowYDELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlmb3Ju aWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxEDAOBgNVBAoMB1Rlc3QgQ0ExEjAQ BgNVBAMMCTEyNy4wLjAuMTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPVPcN7D 0hG7yAhuTGPYE4AQsLjp35z60PTjYV4eH/5ljkupP9RHn3HpiYKC2BBj+q83WzvR 2lYF2qIg4SA3w8CjgYAwfjAMBgNVHRMBAf8EAjAAMB0GA1UdDgQWBBR+3RhpFJzW 5ZzdR9uHYHmtAQeaZjAfBgNVHSMEGDAWgBQNa7bX3X/NTq0GayLhEQhYEKsWKjAd BgNVHSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwDwYDVR0RBAgwBocEfwAAATAK BggqhkjOPQQDAgNIADBFAiAl/bp2gRvTJReCMa1zclCUrONpprFY/rdeSO0jDaIF QAIhANUOAmPJHHpaEBMeuAWHcZy14mbLJ8gXs7FoKcReuaxf -----END CERTIFICATE-----
{ "pile_set_name": "Github" }
{ "name": "volumetric_lighting_scattering.comp", "properties": { "name": "volumetric_lighting_scattering.comp", "gpuProgramName": "volumetric_lighting_scattering.comp.glsl", "entryPoint": "main", "preprocessorDefines": "", "gpuProgramType": 3 } }
{ "pile_set_name": "Github" }
#!/usr/bin/env python r''' Fix several issues in the Latex file. Latex should be given as input. The following changes are made, and the result is thrown in the standard output: 1. It removes \url{X} and converts it to X for all X that contain a dollar sign. Assumes \url{} doesn't cross line boundaries, which appears to be true. If this is not done, some strange code appears inside the URLs (and it's also made a link, which doesn't make sense). 2. It formats notes, hints and tips the same as warnings. This is because warnings show in a box, which is nice, but the other admonitions only show with a top and bottom line, which can look confusing depending on where in the page it's shown. ''' import re import sys regexp = re.compile(r'''\\url\{ ( [^}]* # Anything (but end of url), \$ # then a dollar sign, [^}]* # then anything (but end of url) ) \} # then end of url ''', flags=re.VERBOSE) def fix_urls(line): return re.sub(regexp, r'\1', line) def fix_admonitions(line): line = line.replace(r'\begin{notice}{tip}', r'\begin{notice}{warning}') line = line.replace(r'\begin{notice}{note}', r'\begin{notice}{warning}') line = line.replace(r'\begin{notice}{hint}', r'\begin{notice}{warning}') return line for line in sys.stdin: line = fix_urls(line) line = fix_admonitions(line) sys.stdout.write(line)
{ "pile_set_name": "Github" }
* Broadcom BCM283x GPIO controller Required properties: - compatible: must be "brcm,bcm2835-gpio" - reg: exactly one register range with length 0xb4
{ "pile_set_name": "Github" }
<?php /** * PHPExcel * * Copyright (C) 2006 - 2014 PHPExcel * * This library 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. * * 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel * @copyright Copyright (c) 2006 - 2014 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ /** Error reporting */ error_reporting(E_ALL); ini_set('display_errors', TRUE); ini_set('display_startup_errors', TRUE); define('EOL',(PHP_SAPI == 'cli') ? PHP_EOL : '<br />'); date_default_timezone_set('Europe/London'); /** Include PHPExcel */ require_once dirname(__FILE__) . '/../Classes/PHPExcel.php'; // Create new PHPExcel object echo date('H:i:s') , " Create new PHPExcel object" , EOL; $objPHPExcel = new PHPExcel(); // Set document properties echo date('H:i:s') , " Set document properties" , EOL; $objPHPExcel->getProperties()->setCreator("Maarten Balliauw") ->setLastModifiedBy("Maarten Balliauw") ->setTitle("Office 2007 XLSX Test Document") ->setSubject("Office 2007 XLSX Test Document") ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.") ->setKeywords("office 2007 openxml php") ->setCategory("Test result file"); // Add some data echo date('H:i:s') , " Add some data" , EOL; $objPHPExcel->setActiveSheetIndex(0); $objPHPExcel->getActiveSheet()->setCellValue('A1', 'Hello'); $objPHPExcel->getActiveSheet()->setCellValue('B2', 'world!'); $objPHPExcel->getActiveSheet()->setCellValue('C1', 'Hello'); $objPHPExcel->getActiveSheet()->setCellValue('D2', 'world!'); // Rename worksheet echo date('H:i:s') , " Rename worksheet" , EOL; $objPHPExcel->getActiveSheet()->setTitle('Simple'); // Set document security echo date('H:i:s') , " Set document security" , EOL; $objPHPExcel->getSecurity()->setLockWindows(true); $objPHPExcel->getSecurity()->setLockStructure(true); $objPHPExcel->getSecurity()->setWorkbookPassword("PHPExcel"); // Set sheet security echo date('H:i:s') , " Set sheet security" , EOL; $objPHPExcel->getActiveSheet()->getProtection()->setPassword('PHPExcel'); $objPHPExcel->getActiveSheet()->getProtection()->setSheet(true); // This should be enabled in order to enable any of the following! $objPHPExcel->getActiveSheet()->getProtection()->setSort(true); $objPHPExcel->getActiveSheet()->getProtection()->setInsertRows(true); $objPHPExcel->getActiveSheet()->getProtection()->setFormatCells(true); // Set active sheet index to the first sheet, so Excel opens this as the first sheet $objPHPExcel->setActiveSheetIndex(0); // Save Excel 95 file echo date('H:i:s') , " Write to Excel5 format" , EOL; $callStartTime = microtime(true); $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); $objWriter->save(str_replace('.php', '.xls', __FILE__)); $callEndTime = microtime(true); $callTime = $callEndTime - $callStartTime; echo date('H:i:s') , " File written to " , str_replace('.php', '.xls', pathinfo(__FILE__, PATHINFO_BASENAME)) , EOL; echo 'Call time to write Workbook was ' , sprintf('%.4f',$callTime) , " seconds" , EOL; // Echo memory usage echo date('H:i:s') , ' Current memory usage: ' , (memory_get_usage(true) / 1024 / 1024) , " MB" , EOL; // Echo memory peak usage echo date('H:i:s') , " Peak memory usage: " , (memory_get_peak_usage(true) / 1024 / 1024) , " MB" , EOL; // Echo done echo date('H:i:s') , " Done writing file" , EOL; echo 'File has been created in ' , getcwd() , EOL;
{ "pile_set_name": "Github" }
/* * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * Defines the <em>{@index rmic rmic}</em> compiler for generating stubs and * skeletons using the Java Remote Method Protocol (JRMP) for remote objects. * * <dl style="font-family:'DejaVu Sans', Arial, Helvetica, sans serif"> * <dt class="simpleTagLabel">Tool Guides: * <dd>{@extLink rmic_tool_reference rmic} * </dl> * * @moduleGraph * @since 9 */ module jdk.rmic { requires jdk.compiler; requires jdk.javadoc; }
{ "pile_set_name": "Github" }
# bedup - Btrfs deduplication # Copyright (C) 2012 Gabriel de Perthuis <[email protected]> # # This file is part of bedup. # # bedup 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. # # bedup 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 bedup. If not, see <http://www.gnu.org/licenses/>. # This file is a workaround for Python2.6 # Also has workarounds for -mtrace import sys try: # For -mtrace sys.path.remove('bedup') except ValueError: pass # -mtrace can't use relative imports either from bedup.__main__ import script_main if __name__ == '__main__': script_main()
{ "pile_set_name": "Github" }
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (C) Alkacon Software (http://www.alkacon.com) * * This library 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. * * 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 * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.cmis; import java.math.BigInteger; import java.util.Iterator; import java.util.List; /** * Helper class to ease implementation of CMIS service methods which support paging.<p> * * This class works as an iterator for a given list, and limits the number of iterations based on skip/max parameters * which are usually passed to the service methods.<p> * * @param <A> the content type of the list */ public class CmsObjectListLimiter<A> implements Iterable<A>, Iterator<A> { /** The list for which this object acts as an iterator. */ private List<A> m_baseList; /** The maximum number of objects which can still be returned. */ private int m_max; /** The index of the next object to return. */ private int m_next; /** * Creates a new instance.<p> * * @param baseList the list over which we want to iterate * @param maxItems the maximum number of items * @param skipCount the number of items to skip */ public CmsObjectListLimiter(List<A> baseList, BigInteger maxItems, BigInteger skipCount) { // skip and max m_baseList = baseList; m_next = (skipCount == null ? 0 : skipCount.intValue()); if (m_next < 0) { m_next = 0; } m_max = (maxItems == null ? Integer.MAX_VALUE : maxItems.intValue()); if (m_max < 0) { m_max = Integer.MAX_VALUE; } } /** * Checks if there are more items left in the base list which were not returned.<p> * * @return true if there are more items left in the base list which were not returned */ public boolean hasMore() { return m_next < m_baseList.size(); } /** * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return (m_next < m_baseList.size()) && (m_max > 0); } /** * @see java.lang.Iterable#iterator() */ public Iterator<A> iterator() { return this; } /** * @see java.util.Iterator#next() */ public A next() { A result = m_baseList.get(m_next); m_next += 1; m_max -= 1; return result; } /** * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } }
{ "pile_set_name": "Github" }
/* Copyright The Kubernetes 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. */ // Code generated by informer-gen. DO NOT EDIT. package v1 import ( "context" time "time" corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" watch "k8s.io/apimachinery/pkg/watch" internalinterfaces "k8s.io/client-go/informers/internalinterfaces" kubernetes "k8s.io/client-go/kubernetes" v1 "k8s.io/client-go/listers/core/v1" cache "k8s.io/client-go/tools/cache" ) // PersistentVolumeInformer provides access to a shared informer and lister for // PersistentVolumes. type PersistentVolumeInformer interface { Informer() cache.SharedIndexInformer Lister() v1.PersistentVolumeLister } type persistentVolumeInformer struct { factory internalinterfaces.SharedInformerFactory tweakListOptions internalinterfaces.TweakListOptionsFunc } // NewPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers) cache.SharedIndexInformer { return NewFilteredPersistentVolumeInformer(client, resyncPeriod, indexers, nil) } // NewFilteredPersistentVolumeInformer constructs a new informer for PersistentVolume type. // Always prefer using an informer factory to get a shared informer instead of getting an independent // one. This reduces memory footprint and number of connections to the server. func NewFilteredPersistentVolumeInformer(client kubernetes.Interface, resyncPeriod time.Duration, indexers cache.Indexers, tweakListOptions internalinterfaces.TweakListOptionsFunc) cache.SharedIndexInformer { return cache.NewSharedIndexInformer( &cache.ListWatch{ ListFunc: func(options metav1.ListOptions) (runtime.Object, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.CoreV1().PersistentVolumes().List(context.TODO(), options) }, WatchFunc: func(options metav1.ListOptions) (watch.Interface, error) { if tweakListOptions != nil { tweakListOptions(&options) } return client.CoreV1().PersistentVolumes().Watch(context.TODO(), options) }, }, &corev1.PersistentVolume{}, resyncPeriod, indexers, ) } func (f *persistentVolumeInformer) defaultInformer(client kubernetes.Interface, resyncPeriod time.Duration) cache.SharedIndexInformer { return NewFilteredPersistentVolumeInformer(client, resyncPeriod, cache.Indexers{cache.NamespaceIndex: cache.MetaNamespaceIndexFunc}, f.tweakListOptions) } func (f *persistentVolumeInformer) Informer() cache.SharedIndexInformer { return f.factory.InformerFor(&corev1.PersistentVolume{}, f.defaultInformer) } func (f *persistentVolumeInformer) Lister() v1.PersistentVolumeLister { return v1.NewPersistentVolumeLister(f.Informer().GetIndexer()) }
{ "pile_set_name": "Github" }
R = degreesRing 1 t = R_0 h = 1-t^2-2*t^5-t^6+2*t^7+3*t^8-2*t^10 assert( h % (1-t) == 0 ) assert( (h // (1-t)) * (1-t) == h ) debug Core S = QQ[x,y]/(x^2-5) assert ( 1//x * x == 1 ) raw (1_S) // (raw x) S = QQ[x]/(x^2-5) assert ( 1//x * x == 1 ) raw (1_S) // (raw x) use ambient S x rawExtendedGCD(raw x, raw(x^2-5)) R = QQ[x] gcdCoefficients(x,x^2-5) rawExtendedGCD(raw x, raw(x^2-5)) -- this never could have worked: -- R = ZZ[x] -- gcdCoefficients(x,x^2-5) -- rawExtendedGCD(raw x, raw(x^2-5)) R = QQ[x,y]/(x^2-5) 1//x R = QQ[x]/(x^2+1)[y] r = 1_R % (x*1_R) q = 1_R // (x*1_R) assert(1_R - x*q - r == 0) 1_R % gb ideal (x*1_R) remquottest = (f,g) -> ( r = f % g; q = f // g; f - q*g - r) S = ZZ[x,y,z]/(3*x^2-y-1) assert(remquottest(1_S, x^2) == 0) assert(remquottest(y^3, x+1) == 0) (x+1)*q T = ZZ[a]/(a^3-a-1) A = T[x,y,z]/(x*a-1) assert(remquottest(1,x) == 0) assert(remquottest(1,x*y) == 0) assert(remquottest(x*y,a+1) == 0) B = GF(8,Variable=>w)[symbol x]/(x^3-w-1) assert(remquottest(x+w, x^23) == 0)
{ "pile_set_name": "Github" }
CMAKE_PROGRESS_1 = 1
{ "pile_set_name": "Github" }
/* Copyright 2017 The Kubernetes 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 v1beta1 import ( "errors" "k8s.io/apimachinery/pkg/util/json" ) var jsTrue = []byte("true") var jsFalse = []byte("false") func (s JSONSchemaPropsOrBool) MarshalJSON() ([]byte, error) { if s.Schema != nil { return json.Marshal(s.Schema) } if s.Schema == nil && !s.Allows { return jsFalse, nil } return jsTrue, nil } func (s *JSONSchemaPropsOrBool) UnmarshalJSON(data []byte) error { var nw JSONSchemaPropsOrBool switch { case len(data) == 0: case data[0] == '{': var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Allows = true nw.Schema = &sch case len(data) == 4 && string(data) == "true": nw.Allows = true case len(data) == 5 && string(data) == "false": nw.Allows = false default: return errors.New("boolean or JSON schema expected") } *s = nw return nil } func (s JSONSchemaPropsOrStringArray) MarshalJSON() ([]byte, error) { if len(s.Property) > 0 { return json.Marshal(s.Property) } if s.Schema != nil { return json.Marshal(s.Schema) } return []byte("null"), nil } func (s *JSONSchemaPropsOrStringArray) UnmarshalJSON(data []byte) error { var first byte if len(data) > 1 { first = data[0] } var nw JSONSchemaPropsOrStringArray if first == '{' { var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.Property); err != nil { return err } } *s = nw return nil } func (s JSONSchemaPropsOrArray) MarshalJSON() ([]byte, error) { if len(s.JSONSchemas) > 0 { return json.Marshal(s.JSONSchemas) } return json.Marshal(s.Schema) } func (s *JSONSchemaPropsOrArray) UnmarshalJSON(data []byte) error { var nw JSONSchemaPropsOrArray var first byte if len(data) > 1 { first = data[0] } if first == '{' { var sch JSONSchemaProps if err := json.Unmarshal(data, &sch); err != nil { return err } nw.Schema = &sch } if first == '[' { if err := json.Unmarshal(data, &nw.JSONSchemas); err != nil { return err } } *s = nw return nil } func (s JSON) MarshalJSON() ([]byte, error) { if len(s.Raw) > 0 { return s.Raw, nil } return []byte("null"), nil } func (s *JSON) UnmarshalJSON(data []byte) error { if len(data) > 0 && string(data) != "null" { s.Raw = data } return nil }
{ "pile_set_name": "Github" }
/** * Returns a Buffer from a "ff 00 ff"-type hex string. */ getBufferFromHexString = function(byteStr) { var bytes = byteStr.split(' '); var buf = new Buffer(bytes.length); for (var i = 0; i < bytes.length; ++i) { buf[i] = parseInt(bytes[i], 16); } return buf; } /** * Returns a hex string from a Buffer. */ getHexStringFromBuffer = function(data) { var s = ''; for (var i = 0; i < data.length; ++i) { s += padl(data[i].toString(16), 2, '0') + ' '; } return s.trim(); } /** * Splits a buffer in two parts. */ splitBuffer = function(buffer) { var b1 = new Buffer(Math.ceil(buffer.length / 2)); buffer.copy(b1, 0, 0, b1.length); var b2 = new Buffer(Math.floor(buffer.length / 2)); buffer.copy(b2, 0, b1.length, b1.length + b2.length); return [b1, b2]; } /** * Performs hybi07+ type masking on a hex string or buffer. */ mask = function(buf, maskString) { if (typeof buf == 'string') buf = new Buffer(buf); var mask = getBufferFromHexString(maskString || '34 83 a8 68'); for (var i = 0; i < buf.length; ++i) { buf[i] ^= mask[i % 4]; } return buf; } /** * Returns a hex string representing the length of a message */ getHybiLengthAsHexString = function(len, masked) { if (len < 126) { var buf = new Buffer(1); buf[0] = (masked ? 0x80 : 0) | len; } else if (len < 65536) { var buf = new Buffer(3); buf[0] = (masked ? 0x80 : 0) | 126; getBufferFromHexString(pack(4, len)).copy(buf, 1); } else { var buf = new Buffer(9); buf[0] = (masked ? 0x80 : 0) | 127; getBufferFromHexString(pack(16, len)).copy(buf, 1); } return getHexStringFromBuffer(buf); } /** * Unpacks a Buffer into a number. */ unpack = function(buffer) { var n = 0; for (var i = 0; i < buffer.length; ++i) { n = (i == 0) ? buffer[i] : (n * 256) + buffer[i]; } return n; } /** * Returns a hex string, representing a specific byte count 'length', from a number. */ pack = function(length, number) { return padl(number.toString(16), length, '0').replace(/([0-9a-f][0-9a-f])/gi, '$1 ').trim(); } /** * Left pads the string 's' to a total length of 'n' with char 'c'. */ padl = function(s, n, c) { return new Array(1 + n - s.length).join(c) + s; }
{ "pile_set_name": "Github" }
fileFormatVersion: 2 guid: c83956915580e42489479d2a109470ab timeCreated: 1470404606 licenseType: Store ShaderImporter: defaultTextures: [] userData: assetBundleName: assetBundleVariant:
{ "pile_set_name": "Github" }
YUI Doc generates API documentation from a modified JavaDoc syntax. Current version (0.3.50) Usage: yuidoc <options> <input path> Common Options: -c, --config, --configfile <filename> A JSON config file to provide configuration data. You can also create a yuidoc.json file and place it anywhere under your source tree and YUI Doc will find it and use it. -e, --extension <comma sep list of file extensions> The list of file extensions to parse for api documentation. (defaults to .js) -x, --exclude <comma sep list of directories> Directories to exclude from parsing (defaults to '.DS_Store,.svn,CVS,.git,build_rollup_tmp,build_tmp') -v, --version Show the current YUIDoc version --project-version Set the doc version for the template -N, --no-color Turn off terminal colors (for automation) -C, --no-code Turn off code generation (don't include source files in output) -n, --norecurse Do not recurse directories (default is to recurse) -S, --selleck Look for Selleck component data and attach to API meta data -V, --view Dump the Handlebars.js view data instead of writing template files -p, --parse-only Only parse the API docs and create the JSON data, do not render templates -o, --outdir <directory path> Path to put the generated files (defaults to ./out) -t, --themedir <directory path> Path to a custom theme directory containing Handlebars templates -H, --helpers <comma separated list of paths to files> Require these file and add Handlebars helpers. See docs for more information --charset CHARSET Use this as the default charset for all file operations. Defaults to 'utf8' -h, --help Show this help -q, --quiet Supress logging output -T, --theme <simple|default> Choose one of the built in themes (default is default) --syntaxtype <js|coffee> Choose comment syntax type (default is js) --server <port> Fire up the YUIDoc server for faster API doc developement. Pass optional port to listen on. (default is 3000) --lint Lint your docs, will print parser warnings and exit code 1 if there are any <input path> Supply a list of paths (shell globbing is handy here)
{ "pile_set_name": "Github" }
"""多线程抓取斗鱼美女主播首页美女主播图片""" ''' @Time : 2018/1/23 下午5:59 @Author : scrappy_zhang @File : net07_douyu_threading.py ''' import urllib.request import re import time import threading max_retry_count = 3 def down_img(url): """ 下载图片 https://rpic.douyucdn.cn/live-cover/appCovers/2017/10/24/12017.jpg """ for i in range(max_retry_count): try: response = urllib.request.urlopen(url) # bytes data = response.read() # 从url中得到文件名 file_name = url[url.rfind('/') + 1:] # 打开文件用以写入 with open("img/" + file_name, "wb") as file: file.write(data) except Exception as e: print("出错 %s 正在重试" % e) else: break if __name__ == '__main__': start = time.time() # 程序大约的开始时间 home = """https://www.douyu.com/directory/game/yz?page=1&isAjax=1""" # 首页地址 # 请求的时候需要带上头部 可以防止初步的反爬措施 headers = { "Host": "www.douyu.com", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/62.0.3202.94 Safari/537.36" } # 构造好请求对象 将请求提交到服务器 获取的响应就是到首页的html代码 request = urllib.request.Request(url=home, headers=headers) # urlopen函数可以直接传入url网址 也可以指定好一个请求对象 response = urllib.request.urlopen(request) # 将收到的响应对象中数据的bytes数据读出出来 并且解码 html_data = response.read().decode() # 使用正则 从所要抓取的网页中 提取出所有美女主播的图片链接,并存入一个列表 img_list = re.findall(r"https://.*?\.(?:jpg)", html_data) # 下载美女主播图片 for img_url in img_list: td = threading.Thread(target=down_img, args=(img_url,)) td.start() # 阻塞程序直到所有线程运行完毕 while True: length = len(threading.enumerate()) if length == 1: break end = time.time() # 程序大约的结束时间 print('耗时:', end - start)
{ "pile_set_name": "Github" }
// Animated Icons // -------------------------- .#{$fa-css-prefix}-spin { animation: fa-spin 2s infinite linear; } .#{$fa-css-prefix}-pulse { animation: fa-spin 1s infinite steps(8); } @keyframes fa-spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
{ "pile_set_name": "Github" }
GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. <one line to give the program's name and a brief idea of what it does.> Copyright (C) <year> <name of author> This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero 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 Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see <http://www.gnu.org/licenses/>.
{ "pile_set_name": "Github" }
<?php session_start(); if(!((($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest')||defined('evolette')) && $_SESSION['authorized']===true)) exit(); ?> <div id="ev-feat" style="display:none"> <h2 class="content-heading h-help">Evolette Features</h2> <p>Evolette has a lot of native scripts for jQuery (no third party hevyweight scripts or plugins). All scripts are well documented, so you'll have no problems to use them. It also powered with TinyMCE WYSIWYG edtor.</p> <h2 class="inner-heading h-help">Security</h2> <p>Evolette is well secured. In a word, security is based on the dynamic sessions.</p> <h2 class="inner-heading h-help">Ajax Features</h2> <p>Ajax features of templates are very easy to use. They are based on adding special CLASS attribute value to links or forms, which allows you to load desired file (or post a form fields values) to content section or to popup window, or just to send them to file without any callback.</p> <h2 class="inner-heading h-help">To Do List</h2> <p>There is an editable To Do list. In this template To Do content is stored in the file. But if your CMS will use not one administrator user, it is better to save it to database for each user. <a class="popup" href="index.php?content=todo">Open To Do</a></p> <h2 class="inner-heading h-help">Mailing engine</h2> <p>Evolette has its own simple mailing engine.</p> <ul> <li>Message Form could be opened empty like this: <a class="popup" href="index.php?content=new-message">open form</a>.</li> <li>By using a special CLASS for link, form could be opened with prefilled email address: <a class="sendMessage" href="[email protected]">open form</a>.</li> <li>Or it can be opened with all prefilled fields by specifying their values in the HREF attribute: <a class="popup" href="?content=new-message&amp;[email protected]&amp;subject=Demo Subject&amp;message=This message posted from link">open form</a>. </li> </ul> <p>You can try to send a message to any email. Mailing Engine is fully functioning!</p> <h2 class="inner-heading h-help">Popup Engine</h2> <p>Evolette has a very simple and powerful popup engine, which allows you to include any file to popup window or to include any text message without including a file. It also allows to open included file with an additional POSTed variables.</p> <h2 class="inner-heading h-help">Forms Handling Engine</h2> <p>As the Evolette is fully Ajax template, so it's impossible to submit forms with a simple POST or GET methods. Therefore there is a Form Handling engine which takes all form fields values and sends them to target file(specified in the ACTION attribute of form) by one of three ways: first way is to open target file with posted vars in the popup window (like Mailing Engine or To Do), second one is to open target file in content section (like on the article adding/editing page), and the last way is to post vars to file without any callback.</p> <p>It's very easy to use form handling, all you'll need is to specify special class for form.</p> <h2 class="inner-heading h-help">Wrappers</h2> <p>There is a few elements wrappers used in Evolette. Their usage make the creation of some elements much faster. For example good-looking button code looks like: <br /> <strong>&lt;span class=&quot;button-l&quot;&gt;&lt;span class=&quot;button-m&quot;&gt;&lt;input type=&quot;submit&quot; class=&quot;button&quot;/&gt;&lt;/span&gt;&lt;/span&gt;</strong></p> <p>But it is not so easy to write this code every time. Here is why we need a wrappers. With wrapper all you need is to write: <strong>&lt;input type=&quot;submit&quot; class=&quot;button&quot;/&gt;</strong> , and script will wrap this button with spans automatically</p> </div>
{ "pile_set_name": "Github" }
{ "images" : [ { "idiom" : "universal", "filename" : "email.pdf", "scale" : "1x" }, { "idiom" : "universal", "scale" : "2x" }, { "idiom" : "universal", "scale" : "3x" } ], "info" : { "version" : 1, "author" : "xcode" }, "properties" : { "preserves-vector-representation" : true } }
{ "pile_set_name": "Github" }
/* Copyright (c) 2015, Apple Inc. All rights reserved. Copyright (c) 2015, Ricardo Sánchez-Sáez. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. 3. Neither the name of the copyright holder(s) nor the names of any contributors may be used to endorse or promote products derived from this software without specific prior written permission. No license is granted to the trademarks of the copyright holders even if such marks are included in this software. 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. */ #import "ORKTintedImageView.h" #import "ORKTintedImageView_Internal.h" #import "ORKHelpers_Internal.h" #define ORKTintedImageLog(...) ORK_INLINE BOOL ORKIsImageAnimated(UIImage *image) { return image.images.count > 1; } UIImage *ORKImageByTintingImage(UIImage *image, UIColor *tintColor, CGFloat scale) { if (!image || !tintColor || !(scale > 0)) { return nil; } ORKTintedImageLog(@"%@ %@ %f", image, tintColor, scale); UIGraphicsBeginImageContextWithOptions(image.size, NO, scale); CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetBlendMode(context, kCGBlendModeNormal); CGContextSetAlpha(context, 1); CGRect r = (CGRect){{0,0},image.size}; CGContextBeginTransparencyLayerWithRect(context, r, NULL); [tintColor setFill]; [image drawInRect:r]; UIRectFillUsingBlendMode(r, kCGBlendModeSourceIn); CGContextEndTransparencyLayer(context); UIImage *outputImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext(); return outputImage; } @interface ORKTintedImageCacheKey : NSObject - (instancetype)initWithImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale; @property (nonatomic, readonly) UIImage *image; @property (nonatomic, readonly) UIColor *tintColor; @property (nonatomic, readonly) CGFloat scale; @end @implementation ORKTintedImageCacheKey { UIImage *_image; UIColor *_tintColor; CGFloat _scale; } - (instancetype)initWithImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale { self = [super init]; if (self) { _image = image; _tintColor = tintColor; _scale = scale; } return self; } - (BOOL)isEqual:(id)object { if ([self class] != [object class]) { return NO; } __typeof(self) castObject = object; return (ORKEqualObjects(self.image, castObject.image) && ORKEqualObjects(self.tintColor, castObject.tintColor) && ORKCGFloatNearlyEqualToFloat(self.scale, castObject.scale)); } @end @interface ORKTintedImageCache () - (UIImage *)tintedImageForImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale; @end @implementation ORKTintedImageCache + (instancetype)sharedCache { static dispatch_once_t onceToken; static id sharedInstance = nil; dispatch_once(&onceToken, ^{ sharedInstance = [[[self class] alloc] init]; }); return sharedInstance; } - (UIImage *)tintedImageForImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale { UIImage *tintedImage = nil; ORKTintedImageCacheKey *key = [[ORKTintedImageCacheKey alloc] initWithImage:image tintColor:tintColor scale:scale]; tintedImage = [self objectForKey:key]; if (!tintedImage) { tintedImage = ORKImageByTintingImage(image, tintColor, scale); if (tintedImage) { [self setObject:tintedImage forKey:key]; } } return tintedImage; } - (void)cacheImage:(UIImage *)image tintColor:(UIColor *)tintColor scale:(CGFloat)scale { [[ORKTintedImageCache sharedCache] tintedImageForImage:image tintColor:tintColor scale:scale]; } @end @implementation ORKTintedImageView { UIImage *_originalImage; UIImage *_tintedImage; UIColor *_appliedTintColor; CGFloat _appliedScaleFactor; } - (void)setShouldApplyTint:(BOOL)shouldApplyTint { _shouldApplyTint = shouldApplyTint; self.image = _originalImage; } - (UIImage *)imageByTintingImage:(UIImage *)image { if (!image || (image.renderingMode == UIImageRenderingModeAlwaysOriginal || (image.renderingMode == UIImageRenderingModeAutomatic && !_shouldApplyTint))) { return image; } UIColor *tintColor = self.tintColor; CGFloat screenScale = self.window.screen.scale; // Use screen.scale; self.contentScaleFactor remains 1.0 until later if (screenScale > 0 && (![_appliedTintColor isEqual:tintColor] || !ORKCGFloatNearlyEqualToFloat(_appliedScaleFactor, screenScale))) { _appliedTintColor = tintColor; _appliedScaleFactor = screenScale; if (!ORKIsImageAnimated(image)) { if (_enableTintedImageCaching) { _tintedImage = [[ORKTintedImageCache sharedCache] tintedImageForImage:image tintColor:tintColor scale:screenScale]; } else { _tintedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; } } else { NSArray *animationImages = image.images; NSMutableArray *tintedAnimationImages = [[NSMutableArray alloc] initWithCapacity:animationImages.count]; for (UIImage *animationImage in animationImages) { UIImage *tintedAnimationImage = nil; if (_enableTintedImageCaching) { tintedAnimationImage = [[ORKTintedImageCache sharedCache] tintedImageForImage:animationImage tintColor:tintColor scale:screenScale]; } else { tintedAnimationImage = ORKImageByTintingImage(animationImage, tintColor, screenScale); } if (tintedAnimationImage) { [tintedAnimationImages addObject:tintedAnimationImage]; } } _tintedImage = [UIImage animatedImageWithImages:tintedAnimationImages duration:image.duration]; } } return _tintedImage; } - (void)setImage:(UIImage *)image { _originalImage = image; image = [self imageByTintingImage:image]; [super setImage:image]; } - (void)tintColorDidChange { [super tintColorDidChange]; // recompute for new tint color self.image = _originalImage; } - (void)didMoveToWindow { [super didMoveToWindow]; // recompute for new screen.scale self.image = _originalImage; } @end
{ "pile_set_name": "Github" }
// // NSImage+Thumbnail.swift // WWDC // // Created by Guilherme Rambo on 21/05/17. // Copyright © 2017 Guilherme Rambo. All rights reserved. // import Cocoa extension NSImage { static func thumbnailImage(with url: URL, maxWidth: CGFloat) -> NSImage? { guard let inputImage = NSImage(contentsOf: url) else { return nil } let aspectRatio = inputImage.size.width / inputImage.size.height let thumbSize = NSSize(width: maxWidth, height: maxWidth * aspectRatio) let outputImage = NSImage(size: thumbSize) outputImage.lockFocus() inputImage.draw(in: NSRect(x: 0, y: 0, width: thumbSize.width, height: thumbSize.height), from: .zero, operation: .sourceOver, fraction: 1) outputImage.unlockFocus() return outputImage } } extension NSImage { func makeFreestandingTemplate(outputSize: NSSize) -> NSImage { let insetPercentage: CGFloat = 0.25 var insetSize = outputSize let widthInset = outputSize.width * insetPercentage let heightInset = outputSize.height * insetPercentage insetSize.width -= 2 * widthInset insetSize.height -= 2 * heightInset let destinationRect = NSRect(origin: CGPoint(x: widthInset, y: heightInset), size: insetSize) // Circle Template let circle = CAShapeLayer() circle.path = CGPath(ellipseIn: CGRect(origin: .zero, size: outputSize), transform: nil) // New image let newImage = NSImage(size: outputSize) newImage.lockFocus() // Render both into new image let ctx = NSGraphicsContext.current!.cgContext circle.render(in: ctx) draw(in: destinationRect, from: .zero, operation: .xor, fraction: 1) newImage.unlockFocus() newImage.isTemplate = true return newImage } }
{ "pile_set_name": "Github" }
<pre class='metadata'> Title: Font Metrics API Level 1 Status: DREAM Group: houdini ED: https://drafts.css-houdini.org/font-metrics-api-1/ Shortname: font-metrics-api Level: 1 Abstract: Editor: Emil A Eklund, [email protected], w3cid 93298 Editor: Alan Stearns, [email protected], w3cid 46659 </pre> <pre class=link-defaults> spec:dom; type:interface; text:Document spec:dom; type:interface; text:Element; spec:cssom-1; type:interface; text:CSS; </pre> Introduction {#intro} ===================== The API exposed by this specification is designed to provide basic font metrics for both in-document and out-of-document content. Note: In a future version of this spec support may be added for exposing information about individual runs of text, including information about directionality, script, and character properties. Measure API {#measure-api} ============================================ <pre class='idl'> partial interface Document { FontMetrics measureElement(Element element); FontMetrics measureText(DOMString text, StylePropertyMapReadOnly styleMap); }; </pre> Two methods are provided for measuring text, one for in-document measurements and another for out-of-document measurements. Both return a {{FontMetrics}} object. {{Document/measureElement()}} takes an {{Element}} and returns a {{FontMetrics}} object. If the {{Element}} is not in the document or isn't rendered an empty {{FontMetrics}} object will be returned. {{Document/measureText()}} takes a {{DOMString}} and a {{StylePropertyMapReadOnly}}, returning a {{FontMetrics}} object. Unless a font is specified as a part of the styleMap the user agents default will be used. Note: The only styles that apply to the {{Document/measureText()}} method are those that are passed in as a part of the styleMap. Document styles do not apply. {{FontMetrics}} object {#fontmetrics-definition} ---------------------------- <pre class='idl'> interface FontMetrics { readonly attribute double width; readonly attribute FrozenArray&lt;double> advances; readonly attribute double boundingBoxLeft; readonly attribute double boundingBoxRight; readonly attribute double height; readonly attribute double emHeightAscent; readonly attribute double emHeightDescent; readonly attribute double boundingBoxAscent; readonly attribute double boundingBoxDescent; readonly attribute double fontBoundingBoxAscent; readonly attribute double fontBoundingBoxDescent; readonly attribute Baseline dominantBaseline; readonly attribute FrozenArray&lt;Baseline> baselines; readonly attribute FrozenArray&lt;Font> fonts; }; </pre> The {{FontMetrics}} object has the following attributes: {{FontMetrics/width}} The advance width of the line box, in CSS pixels. {{FontMetrics/advances}} List of advances for each codepoint in the given text relative to the preceding codepoint, in CSS pixels. Where a glyph is composed of a sequence of codepoints the advance for the all but the first codepoint in the sequence will be zero. {{FontMetrics/boundingBoxLeft}} The distance parallel to the {{FontMetrics/dominantBaseline}} from the alignment point given by the text-align property to the left side of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going left from the given alignment point. Note: The sum of this value and {{FontMetrics/boundingBoxRight}} can be wider than the {{FontMetrics/width}}, in particular with slanted fonts where characters overhang their advance width. {{FontMetrics/boundingBoxRight}} The distance parallel to the {{FontMetrics/dominantBaseline}} from the alignment point given by the text-align property to the right side of the bounding rectangle of the given text, in CSS pixels. Positive numbers indicating a distance going right from the given alignment point. {{FontMetrics/height}} The distance between the highest top and the lowest bottom of the em squares in the line box, in CSS pixels. {{FontMetrics/emHeightAscent}} The distance from the {{FontMetrics/dominantBaseline}} to the highest top of the em squares in the line box, in CSS pixels. Positive numbers indicating that the {{FontMetrics/dominantBaseline}} is below the top of that em square (so this value will usually be positive). Zero if the {{FontMetrics/dominantBaseline}} is the top of that em square. Half the font size if the {{FontMetrics/dominantBaseline}} is the middle of that em square. {{FontMetrics/emHeightDescent}} The distance from the {{FontMetrics/dominantBaseline}} to the lowest bottom of the em squares in the line box, in CSS pixels. Positive numbers indicating that the {{FontMetrics/dominantBaseline}} is below the bottom of that em square (so this value will usually be negative). Zero if the {{FontMetrics/dominantBaseline}} is the bottom of that em square. {{FontMetrics/boundingBoxAscent}} The distance from the {{FontMetrics/dominantBaseline}} to the top of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going up from the {{FontMetrics/dominantBaseline}}. Note: This number can vary greatly based on the input text, even if the first font specified covers all the characters in the input. {{FontMetrics/boundingBoxDescent}} The distance from the {{FontMetrics/dominantBaseline}} to the bottom of the bounding rectangle of the given text, in CSS pixels; positive numbers indicating a distance going down from the {{FontMetrics/dominantBaseline}}. {{FontMetrics/fontBoundingBoxAscent}} The distance from the {{FontMetrics/dominantBaseline}} to the top of the highest bounding rectangle of all the fonts used to render the text, in CSS pixels; positive numbers indicating a distance going up from the {{FontMetrics/dominantBaseline}}. Note: This value and {{FontMetrics/fontBoundingBoxDescent}} are useful when metrics independent of the actual text being measured are desired as the values will be consistent regardless of the text as long as the same fonts are being used. The {{FontMetrics/boundingBoxAscent}} attribute (and its corresponding attribute for the descent) are useful when metrics specific to the given text are desired. {{FontMetrics/fontBoundingBoxDescent}} The distance from the {{FontMetrics/dominantBaseline}} to the bottom of the lowest bounding rectangle of all the fonts used to render the text, in CSS pixels; positive numbers indicating a distance going down from the {{FontMetrics/dominantBaseline}}. {{FontMetrics/dominantBaseline}} Reference to the dominant {{Baseline}} for the given text in the list of {{FontMetrics/baselines}}. {{FontMetrics/baselines}} List of all {{Baseline}}s for the given text. {{Baseline}} object {#baseline-definition} ---------------------------- <pre class='idl'> interface Baseline { readonly attribute DOMString name; readonly attribute double value; }; </pre> Each {{Baseline}} object represents a baseline of the measured text and has the following attributes: {{Baseline/name}} Name of the baseline in question. {{Baseline/value}} Distance from the {{FontMetrics/dominantBaseline}}, in CSS pixels. Positive numbers indicating a distance going down from the {{FontMetrics/dominantBaseline}}. {{Font}} object {#font-definition} ---------------------------- <pre class='idl'> interface Font { readonly attribute DOMString name; readonly attribute unsigned long glyphsRendered; }; </pre> Each {{Font}} object represents a font that was used for at least one glyph in the measured text. It contains the following fields: {{Font/name}} Font family name. {{Font/glyphsRendered}} Number of glyphs used from the specific font. If multiple fonts are required to render the specified text this attribute will indicate how many glyphs where used from each font. Note: Indicates the number of glyphs which may be lower than the number of codepoints.
{ "pile_set_name": "Github" }
[cuckoo] # If turned on, Cuckoo will delete the original file after its analysis # has been completed. delete_original = off # If turned on, Cuckoo will delete the copy of the original file in the # local binaries repository after the analysis has finished. (On *nix this # will also invalidate the file called "binary" in each analysis directory, # as this is a symlink.) delete_bin_copy = off # Specify the name of the machinery module to use, this module will # define the interaction between Cuckoo and your virtualization software # of choice. machinery = virtualbox # Enable creation of memory dump of the analysis machine before shutting # down. Even if turned off, this functionality can also be enabled at # submission. Currently available for: VirtualBox and libvirt modules (KVM). memory_dump = off # When the timeout of an analysis is hit, the VM is just killed by default. # For some long-running setups it might be interesting to terminate the # moinitored processes before killing the VM so that connections are closed. terminate_processes = off # Enable automatically re-schedule of "broken" tasks each startup. # Each task found in status "processing" is re-queued for analysis. reschedule = off # Enable processing of results within the main cuckoo process. # This is the default behavior but can be switched off for setups that # require high stability and process the results in a separate task. process_results = on # Limit the amount of analysis jobs a Cuckoo process goes through. # This can be used together with a watchdog to mitigate risk of memory leaks. max_analysis_count = 0 # Limit the number of concurrently executing analysis machines. # This may be useful on systems with limited resources. # Set to 0 to disable any limits. max_machines_count = 0 # Limit the amount of VMs that are allowed to start in parallel. Generally # speaking starting the VMs is one of the more CPU intensive parts of the # actual analysis. This option tries to avoid maxing out the CPU completely. max_vmstartup_count = 10 # Minimum amount of free space (in MB) available before starting a new task. # This tries to avoid failing an analysis because the reports can't be written # due out-of-diskspace errors. Setting this value to 0 disables the check. # (Note: this feature is currently not supported under Windows.) freespace = 64 # Temporary directory containing the files uploaded through Cuckoo interfaces # (web.py, api.py, Django web interface). tmppath = /tmp # Delta in days from current time to set the guest clocks to for file analyses # A negative value sets the clock back, a positive value sets it forward. # The default of 0 disables this option # Note that this can still be overridden by the per-analysis clock setting # and it is not performed by default for URL analysis as it will generally # result in SSL errors daydelta = 0 [resultserver] # The Result Server is used to receive in real time the behavioral logs # produced by the analyzer. # Specify the IP address of the host. The analysis machines should be able # to contact the host through such address, so make sure it's valid. # NOTE: if you set resultserver IP to 0.0.0.0 you have to set the option # `resultserver_ip` for all your virtual machines in machinery configuration. ip = 192.168.56.1 # Specify a port number to bind the result server on. port = 2042 # Should the server write the legacy CSV format? # (if you have any custom processing on those, switch this on) store_csvs = off # Maximum size of uploaded files from VM (screenshots, dropped files, log) # The value is expressed in bytes, by default 10Mb. upload_max_size = 10485760 [processing] # Set the maximum size of analyses generated files to process. This is used # to avoid the processing of big files which may take a lot of processing # time. The value is expressed in bytes, by default 100Mb. analysis_size_limit = 104857600 # The number of calls per process to process. 0 switches the limit off. # 10000 api calls should be processed in less than 2 minutes analysis_call_limit = 0 # Enable or disable DNS lookups. resolve_dns = on # Enable or disable reverse DNS lookups # This information currently is not displayed in the web interface reverse_dns = off # Use ram to boost processing speed. You will need more than 20GB of RAM for this feature. # Please read "performance" section in the documentation. ram_boost = off # Enable PCAP sorting, needed for the connection content view in the web interface. sort_pcap = on [database] # Specify the database connection string. # Examples, see documentation for more: # sqlite:///foo.db # postgresql://foo:bar@localhost:5432/mydatabase # mysql://foo:bar@localhost/mydatabase # If empty, default is a SQLite in db/cuckoo.db. connection = # Database connection timeout in seconds. # If empty, default is set to 60 seconds. timeout = [timeouts] # Set the default analysis timeout expressed in seconds. This value will be # used to define after how many seconds the analysis will terminate unless # otherwise specified at submission. default = 120 # Set the critical timeout expressed in (relative!) seconds. It will be added # to the default timeout above and after this timeout is hit # Cuckoo will consider the analysis failed and it will shutdown the machine # no matter what. When this happens the analysis results will most likely # be lost. critical = 60 # Maximum time to wait for virtual machine status change. For example when # shutting down a vm. Default is 300 seconds. vm_state = 300
{ "pile_set_name": "Github" }
/* * Copyright 2003-2018 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 jetbrains.mps.idea.java.psi; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiClass; import com.intellij.psi.PsiCodeBlock; import com.intellij.psi.PsiDirectory; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiExpression; import com.intellij.psi.PsiField; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiFileSystemItem; import com.intellij.psi.PsiJavaFile; import com.intellij.psi.PsiMethod; import com.intellij.psi.PsiModifier; import com.intellij.psi.PsiModifierList; import com.intellij.psi.PsiParameter; import com.intellij.psi.PsiParameterList; import com.intellij.psi.PsiReferenceList; import com.intellij.psi.PsiTreeChangeEvent; import com.intellij.psi.PsiTypeParameter; import com.intellij.psi.PsiTypeParameterList; import com.intellij.psi.PsiWhiteSpace; import jetbrains.mps.ide.platform.watching.ReloadParticipant; import jetbrains.mps.idea.java.psi.JavaPsiListener.FSMove; import jetbrains.mps.idea.java.psi.JavaPsiListener.FSRename; import jetbrains.mps.idea.java.psi.JavaPsiListener.PsiEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.mps.openapi.util.ProgressMonitor; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Map.Entry; import java.util.Set; /** * danilla 5/25/13 */ public class PsiChangeProcessor extends ReloadParticipant { // Per project change data // The thing is there's only one instance of reload participant for a given participant class, // whereas PsiChangesWatcher is a project component (as PsiManager) private Map<Project, PsiChangeData> changeData = new HashMap<Project, PsiChangeData>(); public PsiChangeProcessor() { } @Override public boolean wantsToShowProgress() { // we'll not request progress indicator for psi updates return false; } // TODO look with what locks is it called @Override public void update(ProgressMonitor monitor) { monitor.start("PSI update", changeData.size() + 1); try { for (Entry<Project, PsiChangeData> e : changeData.entrySet()) { final Project project = e.getKey(); final PsiChangeData change = e.getValue(); // we do update asynchronously, so we want to check if project is live yet if (project.isDisposed()) { continue; } project.getComponent(PsiChangesWatcher.class).notifyListeners(change); monitor.advance(1); } } finally { // clean-up changeData = new HashMap<>(); } monitor.done(); } @Override public boolean isEmpty() { for (PsiChangeData data : changeData.values()) { if (data.isNotEmpty()) { return false; } } return true; } // The following methods are called by PsiChangesWatcher when it receives a PSI event // We're not PsiTreeChangeAdapter ourselves for a reason: // we're a ReloadParticipant => we can be instantiated by ReloadManager itself and there's only // one instance of us per application, whereas psi listeners exist per project (as well as PsiManager) // todo filter out changes not related to stub structure /*package*/ void childAdded(final PsiTreeChangeEvent event) { if (!filter(event.getChild())) return; PsiChangeData data = projectData(event.getChild()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { data.created.add((PsiFileSystemItem) elem); } else { data.changed.add(elem.getContainingFile()); } } /*package*/ void childRemoved(PsiTreeChangeEvent event) { if (!(event.getChild() instanceof PsiFileSystemItem) && !filter(event.getParent())) { // can't use getChild() here as it's not valid any longer return; } // so, if fs item or passed filtering then proceed PsiChangeData data = projectData(event.getParent()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { data.removed.add((PsiFileSystemItem) elem); } else { // todo fix is parent is a file itself data.changed.add(event.getParent().getContainingFile()); } } /*package*/ void childReplaced(PsiTreeChangeEvent event) { // if both are uninteresting, only then ignore if (!filter(event.getOldChild()) && !filter(event.getNewChild())) return; PsiChangeData data = projectData(event.getNewChild()); // todo Q: should we check if it's PsiFile? data.changed.add(event.getNewChild().getContainingFile()); } /*package*/ void childrenChanged(PsiTreeChangeEvent event) { if (!filter(event.getParent())) return; if (event.getParent() instanceof PsiFile) { // it's some generic notification, we don't need it // (don't remember already what that means) return; } PsiChangeData data = projectData(event.getParent()); data.changed.add(event.getParent().getContainingFile()); } /*package*/ void childMoved(@NotNull PsiTreeChangeEvent event) { if (!filter(event.getChild())) return; PsiChangeData data = projectData(event.getChild()); PsiElement elem = event.getChild(); if (elem instanceof PsiFileSystemItem) { // file item; data.moved.add(new FSMove((PsiFileSystemItem) elem, (PsiFileSystemItem) event.getOldParent(), (PsiFileSystemItem) event.getNewParent())); } else { // todo what if old/new parent is PsiFileSystemItem ? data.changed.add(event.getOldParent().getContainingFile()); data.changed.add(event.getNewParent().getContainingFile()); } } /*package*/ void propertyChanged(@NotNull PsiTreeChangeEvent event) { if (!(event.getElement() instanceof PsiFileSystemItem && (PsiTreeChangeEvent.PROP_FILE_NAME.equals(event.getPropertyName()) || PsiTreeChangeEvent.PROP_DIRECTORY_NAME.equals(event.getPropertyName()))) ) { return; } PsiChangeData data = projectData(event.getElement()); FSRename rename = new FSRename((PsiFileSystemItem) event.getElement(), (String) event.getOldValue()); data.renamed.add(rename); } private PsiChangeData projectData(PsiElement subject) { Project project = subject.getProject(); PsiChangeData data = changeData.get(project); if (data == null) { data = new PsiChangeData(); changeData.put(project, data); } return data; } private boolean filter(PsiElement elem) { if (elem == null || elem instanceof PsiWhiteSpace) { return false; } if (elem instanceof PsiJavaFile || elem instanceof PsiDirectory) { return true; } PsiElement e = elem; do { if (interesting(e)) { return true; } if (notInteresting(e)) { return false; } e = e.getParent(); } while (e != null); return false; } private boolean interesting(PsiElement elem) { if (elem instanceof PsiClass || elem instanceof PsiMethod || elem instanceof PsiField || elem instanceof PsiParameterList || elem instanceof PsiParameter || elem instanceof PsiReferenceList // but not PsiReference ! || elem instanceof PsiModifierList || elem instanceof PsiModifier || elem instanceof PsiTypeParameterList || elem instanceof PsiTypeParameter) { return true; } return false; } private boolean notInteresting(PsiElement elem) { return elem instanceof PsiCodeBlock || elem instanceof PsiExpression; } } class PsiChangeData implements PsiEvent { Set<PsiFileSystemItem> created = new HashSet<PsiFileSystemItem>(); Set<PsiFileSystemItem> removed = new HashSet<PsiFileSystemItem>(); Set<FSMove> moved = new HashSet<FSMove>(); Set<FSRename> renamed = new HashSet<FSRename>(); Set<PsiFile> changed = new HashSet<PsiFile>(); @Override public Iterable<PsiFileSystemItem> getCreated() { return created; } @Override public Iterable<PsiFileSystemItem> getRemoved() { return removed; } @Override public Iterable<FSMove> getMoved() { return moved; } @Override public Iterable<FSRename> getRenamed() { return renamed; } @Override public Set<PsiFile> getChanged() { return changed; } boolean isNotEmpty() { return !(changed.isEmpty() && created.isEmpty() && renamed.isEmpty() && moved.isEmpty() && removed.isEmpty()); } }
{ "pile_set_name": "Github" }
package cnab import ( "testing" "github.com/docker/cli/cli/command" cliflags "github.com/docker/cli/cli/flags" "gotest.tools/assert" ) func TestRequiresBindMount(t *testing.T) { dockerCli, err := command.NewDockerCli() assert.NilError(t, err) err = dockerCli.Initialize(cliflags.NewClientOptions()) assert.NilError(t, err) testCases := []struct { name string targetContextName string targetOrchestrator string expectedRequired bool expectedEndpoint string expectedError string }{ { name: "kubernetes-orchestrator", targetContextName: "target-context", targetOrchestrator: "kubernetes", expectedRequired: false, expectedEndpoint: "", expectedError: "", }, { name: "no-context", targetContextName: "", targetOrchestrator: "swarm", expectedRequired: true, expectedEndpoint: "/var/run/docker.sock", expectedError: "", }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { result, err := RequiredBindMount(testCase.targetContextName, testCase.targetOrchestrator, dockerCli.ContextStore()) if testCase.expectedError == "" { assert.NilError(t, err) } else { assert.Error(t, err, testCase.expectedError) } assert.Equal(t, testCase.expectedRequired, result.required) assert.Equal(t, testCase.expectedEndpoint, result.endpoint) }) } } func TestIsDockerHostLocal(t *testing.T) { testCases := []struct { name string host string expected bool }{ { name: "not-local", host: "tcp://not.local.host", expected: false, }, { name: "no-endpoint", host: "", expected: true, }, { name: "docker-sock", host: "unix:///var/run/docker.sock", expected: true, }, { name: "named-pipe", host: "npipe:////./pipe/docker_engine", expected: true, }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { assert.Equal(t, testCase.expected, isDockerHostLocal(testCase.host)) }) } } func TestSocketPath(t *testing.T) { testCases := []struct { name string host string expected string }{ { name: "unixSocket", host: "unix:///my/socket.sock", expected: "/my/socket.sock", }, { name: "namedPipe", host: "npipe:////./docker", expected: "/var/run/docker.sock", }, { name: "emptyHost", host: "", expected: "/var/run/docker.sock", }, { name: "tcpHost", host: "tcp://my/tcp/endpoint", expected: "/var/run/docker.sock", }, } for _, testCase := range testCases { t.Run(testCase.name, func(t *testing.T) { assert.Equal(t, testCase.expected, socketPath(testCase.host)) }) } }
{ "pile_set_name": "Github" }
Branch
{ "pile_set_name": "Github" }
<!DOCTYPE html> <html> <head> </head> <body style="font-family: Arial;"> <h1 style="border: 1px solid #ccc; color: red;">Hi</h1> <table> <tr> <td class="headline" style="font-size: 24px; padding: 5px;">Some Headline</td> </tr> </table> </body> </html>
{ "pile_set_name": "Github" }
cheats = 2 cheat0_desc = "Extra Characters" cheat0_enable = false cheat0_code = "8113A488 1000;8113A48A 07FF;8113A48C 2000;8113A48E 3FFF" cheat1_desc = "Infinite Creation Points" cheat1_enable = false cheat1_code = "80136245 0000"
{ "pile_set_name": "Github" }
// RUN: %clang_cc1 -verify -fopenmp %s // RUN: %clang_cc1 -verify -fopenmp-simd %s void foo() { } bool foobool(int argc) { return argc; } struct S1; // expected-note 2 {{declared here}} expected-note 2 {{forward declaration of 'S1'}} extern S1 a; class S2 { mutable int a; public: S2() : a(0) {} }; const S2 b; const S2 ba[5]; class S3 { int a; public: S3() : a(0) {} }; const S3 ca[5]; class S4 { int a; S4(); // expected-note {{implicitly declared private here}} public: S4(int v) : a(v) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < v; ++k) ++this->a; } }; class S5 { int a; S5() : a(0) {} // expected-note {{implicitly declared private here}} public: S5(int v) : a(v) {} S5 &operator=(S5 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) // expected-error {{expected variable name or data member of current class}} for (int k = 0; k < s.a; ++k) ++s.a; return *this; } }; template <typename T> class S6 { public: T a; S6() : a(0) {} S6(T v) : a(v) { #pragma omp parallel for private(a) private(this->a) for (int k = 0; k < v; ++k) ++this->a; } S6 &operator=(S6 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) // expected-error {{expected variable name or data member of current class}} for (int k = 0; k < s.a; ++k) ++s.a; return *this; } }; template <typename T> class S7 : public T { T a; S7() : a(0) {} public: S7(T v) : a(v) { #pragma omp parallel for private(a) private(this->a) private(T::a) for (int k = 0; k < a.a; ++k) ++this->a.a; } S7 &operator=(S7 &s) { #pragma omp parallel for private(a) private(this->a) private(s.a) private(s.T::a) // expected-error 2 {{expected variable name or data member of current class}} for (int k = 0; k < s.a.a; ++k) ++s.a.a; return *this; } }; S3 h; #pragma omp threadprivate(h) // expected-note 2 {{defined as threadprivate or thread local}} template <class I, class C> int foomain(I argc, C **argv) { I e(4); I g(5); int i; int &j = i; #pragma omp parallel for private // expected-error {{expected '(' after 'private'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private() // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(a, b) // expected-error {{private variable with incomplete type 'S1'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(e, g) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(h) // expected-error {{threadprivate or thread local variable cannot be private}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for nowait // expected-error {{unexpected OpenMP clause 'nowait' in directive '#pragma omp parallel for'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int v = 0; int i; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) { i = k; v += i; } } #pragma omp parallel shared(i) #pragma omp parallel private(i) #pragma omp parallel for private(j) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; return 0; } namespace A { double x; #pragma omp threadprivate(x) // expected-note {{defined as threadprivate or thread local}} } namespace B { using A::x; } int main(int argc, char **argv) { S4 e(4); S5 g(5); S6<float> s6(0.0) , s6_0(1.0); S7<S6<float> > s7(0.0) , s7_0(1.0); int i; int &j = i; #pragma omp parallel for private // expected-error {{expected '(' after 'private'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private( // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private() // expected-error {{expected expression}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc // expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc, // expected-error {{expected expression}} expected-error {{expected ')'}} expected-note {{to match this '('}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc > 0 ? argv[1] : argv[2]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argc) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(S1) // expected-error {{'S1' does not refer to a value}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(a, b) // expected-error {{private variable with incomplete type 'S1'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(argv[1]) // expected-error {{expected variable name}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(e, g) // expected-error {{calling a private constructor of class 'S4'}} expected-error {{calling a private constructor of class 'S5'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(h, B::x) // expected-error 2 {{threadprivate or thread local variable cannot be private}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for nowait // expected-error {{unexpected OpenMP clause 'nowait' in directive '#pragma omp parallel for'}} for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel { int i; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; } #pragma omp parallel shared(i) #pragma omp parallel private(i) #pragma omp parallel for private(j) for (int k = 0; k < argc; ++k) ++k; #pragma omp parallel for private(i) for (int k = 0; k < argc; ++k) ++k; static int m; #pragma omp parallel for private(m) for (int k = 0; k < argc; ++k) m = k + 2; s6 = s6_0; // expected-note {{in instantiation of member function 'S6<float>::operator=' requested here}} s7 = s7_0; // expected-note {{in instantiation of member function 'S7<S6<float> >::operator=' requested here}} return foomain(argc, argv); // expected-note {{in instantiation of function template specialization 'foomain<int, char>' requested here}} }
{ "pile_set_name": "Github" }
import 'reflect-metadata' import 'react-dates/initialize' import 'map.prototype.tojson' // to visualize Map in Redux Dev Tools import 'set.prototype.tojson' // to visualize Set in Redux Dev Tools import 'src/helpers/errorPrototypeTojson' // to visualize Error in Redux Dev Tools import { enableES5 } from 'immer' import React, { useEffect, useState, Suspense } from 'react' import { AppProps } from 'next/app' import { I18nextProvider } from 'react-i18next' import type { Store } from 'redux' import { ConnectedRouter } from 'connected-next-router' import type { Persistor } from 'redux-persist' import { Layout } from 'src/components/Layout/Layout' import { ThemeProvider } from 'styled-components' import { Provider } from 'react-redux' import { PersistGate } from 'redux-persist/integration/react' import { MDXProvider } from '@mdx-js/react' import { initialize } from 'src/initialize' import { init } from 'src/state/app/init.actions' import i18n from 'src/i18n/i18n' import Loading from 'src/components/Loading/Loading' import { LinkExternal } from 'src/components/Link/LinkExternal' import { SEO } from 'src/components/Common/SEO' import { theme } from 'src/theme' import 'src/styles/global.scss' enableES5() export interface AppState { persistor: Persistor store: Store } export default function MyApp({ Component, pageProps, router }: AppProps) { const [state, setState] = useState<AppState | undefined>() useEffect(() => { initialize({ router }) // eslint-disable-next-line promise/always-return .then((state: AppState) => { setState(state) state.store.dispatch(init()) }) .catch((error: Error) => { throw error }) }, [router]) if (!state) { return <Loading /> } const { store, persistor } = state return ( <Suspense fallback={<Loading />}> <Provider store={store}> <ConnectedRouter> <ThemeProvider theme={theme}> <I18nextProvider i18n={i18n}> <MDXProvider components={{ a: LinkExternal }}> <PersistGate loading={<Loading />} persistor={persistor}> <SEO /> <Layout> <Component {...pageProps} /> </Layout> </PersistGate> </MDXProvider> </I18nextProvider> </ThemeProvider> </ConnectedRouter> </Provider> </Suspense> ) }
{ "pile_set_name": "Github" }
/* * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. 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. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS 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 APPLE INC. OR ITS 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. */ #include "config.h" #include "TypedArrayCTest.h" #include "JavaScript.h" #include <limits.h> #include <math.h> #include <stdio.h> #include <wtf/Assertions.h> extern "C" void JSSynchronousGarbageCollectForDebugging(JSContextRef); static void id(void*, void*) { } static void freePtr(void* ptr, void*) { free(ptr); } static const unsigned numLengths = 3; static const unsigned lengths[numLengths] = { 0, 1, 10, }; static const unsigned byteSizes[kJSTypedArrayTypeArrayBuffer] = { 1, // kJSTypedArrayTypeInt8Array 2, // kJSTypedArrayTypeInt16Array 4, // kJSTypedArrayTypeInt32Array 1, // kJSTypedArrayTypeUint8Array 1, // kJSTypedArrayTypeUint8ClampedArray 2, // kJSTypedArrayTypeUint16Array 4, // kJSTypedArrayTypeUint32Array 4, // kJSTypedArrayTypeFloat32Array 8, // kJSTypedArrayTypeFloat64Array }; static const char* typeToString[kJSTypedArrayTypeArrayBuffer] = { "kJSTypedArrayTypeInt8Array", "kJSTypedArrayTypeInt16Array", "kJSTypedArrayTypeInt32Array", "kJSTypedArrayTypeUint8Array", "kJSTypedArrayTypeUint8ClampedArray", "kJSTypedArrayTypeUint16Array", "kJSTypedArrayTypeUint32Array", "kJSTypedArrayTypeFloat32Array", "kJSTypedArrayTypeFloat64Array", }; inline int unexpectedException(const char* name) { fprintf(stderr, "%s FAILED: unexpected exception\n", name); return 1; } static int assertEqualsAsNumber(JSGlobalContextRef context, JSValueRef value, double expectedValue) { double number = JSValueToNumber(context, value, nullptr); if (number != expectedValue && !(isnan(number) && isnan(expectedValue))) { fprintf(stderr, "assertEqualsAsNumber FAILED: %p, %lf\n", value, expectedValue); return 1; } return 0; } static int testAccess(JSGlobalContextRef context, JSObjectRef typedArray, JSTypedArrayType type, unsigned elementLength, void* expectedPtr = nullptr, JSObjectRef expectedBuffer = nullptr, unsigned expectedOffset = 0) { JSValueRef exception = nullptr; // Test typedArray basic functions. JSTypedArrayType actualType = JSValueGetTypedArrayType(context, typedArray, &exception); if (type != actualType || exception) { fprintf(stderr, "TypedArray type FAILED: %p, got: %s, expected: %s\n", typedArray, typeToString[actualType], typeToString[type]); return 1; } unsigned length = JSObjectGetTypedArrayLength(context, typedArray, &exception); if (elementLength != length || exception) { fprintf(stderr, "TypedArray length FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], length, elementLength); return 1; } unsigned byteLength = JSObjectGetTypedArrayByteLength(context, typedArray, &exception); unsigned expectedLength = byteSizes[type] * elementLength; if (byteLength != expectedLength || exception) { fprintf(stderr, "TypedArray byteLength FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], byteLength, expectedLength); return 1; } unsigned offset = JSObjectGetTypedArrayByteOffset(context, typedArray, &exception); if (expectedOffset != offset || exception) { fprintf(stderr, "TypedArray byteOffset FAILED: %p (%s), got: %d, expected: %d\n", typedArray, typeToString[type], offset, expectedOffset); return 1; } void* ptr = JSObjectGetTypedArrayBytesPtr(context, typedArray, &exception); if (exception) return unexpectedException("TypedArray get bytes ptr"); JSObjectRef buffer = JSObjectGetTypedArrayBuffer(context, typedArray, &exception); if (exception) return unexpectedException("TypedArray get buffer"); void* bufferPtr = JSObjectGetArrayBufferBytesPtr(context, buffer, &exception); if (exception) return unexpectedException("ArrayBuffer get bytes ptr"); if (bufferPtr != ptr) { fprintf(stderr, "FAIL: TypedArray bytes ptr and ArrayBuffer byte ptr were not the same: %p (%s) TypedArray: %p, ArrayBuffer: %p\n", typedArray, typeToString[type], ptr, bufferPtr); return 1; } if (expectedPtr && ptr != expectedPtr) { fprintf(stderr, "FAIL: TypedArray bytes ptr and the ptr used to construct the array were not the same: %p (%s) TypedArray: %p, bytes ptr: %p\n", typedArray, typeToString[type], ptr, expectedPtr); return 1; } if (expectedBuffer && expectedBuffer != buffer) { fprintf(stderr, "FAIL: TypedArray buffer and the ArrayBuffer buffer used to construct the array were not the same: %p (%s) TypedArray buffer: %p, data: %p\n", typedArray, typeToString[type], buffer, expectedBuffer); return 1; } return 0; } static int testConstructors(JSGlobalContextRef context, JSTypedArrayType type, unsigned length) { int failed = 0; JSValueRef exception = nullptr; JSObjectRef typedArray; // Test create with length. typedArray = JSObjectMakeTypedArray(context, type, length, &exception); failed = failed || exception || testAccess(context, typedArray, type, length); void* ptr = calloc(length, byteSizes[type]); // This is to be freed by data JSObjectRef data = JSObjectMakeArrayBufferWithBytesNoCopy(context, ptr, length * byteSizes[type], freePtr, nullptr, &exception); failed = failed || exception; // Test create with existing ptr. typedArray = JSObjectMakeTypedArrayWithBytesNoCopy(context, type, ptr, length * byteSizes[type], id, nullptr, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr); // Test create with existing ArrayBuffer. typedArray = JSObjectMakeTypedArrayWithArrayBuffer(context, type, data, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr, data); // Test create with existing ArrayBuffer and offset. typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, 0, length, &exception); failed = failed || exception || testAccess(context, typedArray, type, length, ptr, data); typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], length-1, &exception); if (!length) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, length-1, ptr, data, byteSizes[type]) || exception; exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], 3, &exception); if (length < 2) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, 3, ptr, data, byteSizes[type]) || exception; if (byteSizes[type] > 1) { exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, 1, length-1, &exception); failed = failed || !exception; } typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], length, &exception); failed = failed || !exception; exception = nullptr; typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, type, data, byteSizes[type], 0, &exception); if (!length) failed = failed || !exception; else failed = failed || testAccess(context, typedArray, type, 0, ptr, data, byteSizes[type]) || exception; return failed; } template <typename Functor> static int forEachTypedArrayType(const Functor& functor) { int failed = 0; for (unsigned i = 0; i < kJSTypedArrayTypeArrayBuffer; i++) failed = failed || functor(static_cast<JSTypedArrayType>(i)); return failed; } int testTypedArrayCAPI() { int failed = 0; JSGlobalContextRef context = JSGlobalContextCreate(nullptr); failed = failed || forEachTypedArrayType([&](JSTypedArrayType type) { int failed = 0; for (unsigned i = 0; i < numLengths; i++) failed = failed || testConstructors(context, type, lengths[i]); return failed; }); // Test making a typedArray from scratch length. volatile JSObjectRef typedArray = JSObjectMakeTypedArray(context, kJSTypedArrayTypeUint32Array, 10, nullptr); JSObjectRef data = JSObjectGetTypedArrayBuffer(context, typedArray, nullptr); unsigned* buffer = static_cast<unsigned*>(JSObjectGetArrayBufferBytesPtr(context, data, nullptr)); ASSERT(JSObjectGetTypedArrayLength(context, typedArray, nullptr) == 10); // Test buffer is connected to typedArray. buffer[1] = 1; JSValueRef v = JSObjectGetPropertyAtIndex(context, typedArray, 1, nullptr); failed = failed || assertEqualsAsNumber(context, v, 1); // Test passing a buffer from a new array to an old array typedArray = JSObjectMakeTypedArrayWithBytesNoCopy(context, kJSTypedArrayTypeUint32Array, buffer, 40, id, nullptr, nullptr); buffer = static_cast<unsigned*>(JSObjectGetTypedArrayBytesPtr(context, typedArray, nullptr)); ASSERT(buffer[1] == 1); buffer[1] = 20; ASSERT(((unsigned*)JSObjectGetArrayBufferBytesPtr(context, data, nullptr))[1] == 20); // Test constructing with data and the data returned are the same even with an offset. typedArray = JSObjectMakeTypedArrayWithArrayBufferAndOffset(context, kJSTypedArrayTypeUint32Array, data, 4, 9, nullptr); failed = failed || assertEqualsAsNumber(context, JSObjectGetPropertyAtIndex(context, typedArray, 0, nullptr), 20); ASSERT(data == JSObjectGetTypedArrayBuffer(context, typedArray, nullptr)); // Test attempting to allocate an array too big for memory. forEachTypedArrayType([&](JSTypedArrayType type) { JSValueRef exception = nullptr; JSObjectMakeTypedArray(context, type, UINT_MAX, &exception); return !exception; }); JSGlobalContextRelease(context); if (!failed) printf("PASS: Typed Array C API Tests.\n"); else printf("FAIL: Some Typed Array C API Tests failed.\n"); return failed; }
{ "pile_set_name": "Github" }
'use strict' var consoleControl = require('console-control-strings') var ThemeSet = require('./theme-set.js') var themes = module.exports = new ThemeSet() themes.addTheme('ASCII', { preProgressbar: '[', postProgressbar: ']', progressbarTheme: { complete: '#', remaining: '.' }, activityIndicatorTheme: '-\\|/', preSubsection: '>' }) themes.addTheme('colorASCII', themes.getTheme('ASCII'), { progressbarTheme: { preComplete: consoleControl.color('inverse'), complete: ' ', postComplete: consoleControl.color('stopInverse'), preRemaining: consoleControl.color('brightBlack'), remaining: '.', postRemaining: consoleControl.color('reset') } }) themes.addTheme('brailleSpinner', { preProgressbar: '⸨', postProgressbar: '⸩', progressbarTheme: { complete: '░', remaining: '⠂' }, activityIndicatorTheme: '⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏', preSubsection: '>' }) themes.addTheme('colorBrailleSpinner', themes.getTheme('brailleSpinner'), { progressbarTheme: { preComplete: consoleControl.color('inverse'), complete: ' ', postComplete: consoleControl.color('stopInverse'), preRemaining: consoleControl.color('brightBlack'), remaining: '░', postRemaining: consoleControl.color('reset') } }) themes.setDefault({}, 'ASCII') themes.setDefault({hasColor: true}, 'colorASCII') themes.setDefault({platform: 'darwin', hasUnicode: true}, 'brailleSpinner') themes.setDefault({platform: 'darwin', hasUnicode: true, hasColor: true}, 'colorBrailleSpinner')
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF 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. --> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.apache.camel</groupId> <artifactId>components</artifactId> <version>3.6.0-SNAPSHOT</version> </parent> <artifactId>camel-lucene</artifactId> <packaging>jar</packaging> <name>Camel :: Lucene</name> <description>Camel Lucene based search component</description> <properties> <camel.osgi.import.additional> org.apache.lucene.*;version="${lucene-version-range}" </camel.osgi.import.additional> </properties> <dependencies> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-support</artifactId> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-core</artifactId> <version>${lucene-version}</version> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-queryparser</artifactId> <version>${lucene-version}</version> </dependency> <dependency> <groupId>org.apache.lucene</groupId> <artifactId>lucene-analyzers-common</artifactId> <version>${lucene-version}</version> </dependency> <!-- test dependencies --> <dependency> <groupId>org.apache.camel</groupId> <artifactId>camel-test-junit5</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.logging.log4j</groupId> <artifactId>log4j-slf4j-impl</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <configuration> <filesets> <fileset> <directory>${basedir}/res</directory> </fileset> </filesets> </configuration> </plugin> </plugins> </build> </project>
{ "pile_set_name": "Github" }
package com.cheng.improve151suggest; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.ListView; import java.util.Arrays; import com.cheng.highqualitycodestudy.R; import com.cheng.improve151suggest.adapter.I151SuggestListAdapter; /** 第10章 性能和效率 建议132: 提升java性能的基本方法 建议133: 若非必要,不要克隆对象 建议134: 推荐使用“望闻问切”的方式诊断性能 建议135: 必须定义性能衡量标准 建议136: 枪打出头鸟—解决首要系统性能问题 建议137: 调整jvm参数以提升性能 建议138: 性能是个大“咕咚” */ public class I151SChapter10Activity extends AppCompatActivity { private static final String TAG = "I151SChapter10Activity"; private ListView mChapterLV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_i151suggestchapter); initView(); initData(); } private void initView() { this.mChapterLV = (ListView) findViewById(R.id.isi_chapter_lv); } private void initData() { String[] suggests = getResources().getStringArray(R.array.i151schapter10); I151SuggestListAdapter adapter = new I151SuggestListAdapter(this, Arrays.asList(suggests)); mChapterLV.setAdapter(adapter); } /** * 建议132: 提升java性能的基本方法 */ private void suggest132() { /* 1)不要在循环条件中计算 如果在循环(如for循环、while循环)条件中计算,则每循环一遍就要计算一次,这会降低系统效率 2)尽可能把变量、方法声明为final static类型 假设要将阿拉伯数字转换为中文数字,其定义如下: public String toChineseNum(int num) { // 中文数字 String[] cns = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; return cns[num]; } 每次调用该方法时都会重新生成一个cns数组,注意该数组不会改变,属于不变数组,在这种情况下,把它声 明为类变量,并且加上final static修饰会更合适,在类加载后就生成了该数组,每次方法调用则不再重新 生成数组对象了,这有助于提高系统性能,代码如下: // 声明为类变量 final static String[] cns = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; public String toChineseNum(int num) { return cns[num]; } 3)缩小变量的作用范围 关于变量,能定义在方法内的就定义在方法内,能定义在一个循环体内的就定义在循环体内,能放置在一个 try...catch块内的就放置在该块内,其目的是加快GC的回收 4)频繁字符串操作使用StringBuilder或StringBuffer 虽然String的联接操作(“+”号)已经做了很多优化,但在大量的追加操作上StringBuilder或StringBuffer 还是比“+”号的性能好很多 5)使用非线性检索 如果在ArrayList中存储了大量的数据,使用indexOf查找元素会比java.utils.Collections.binarySearch 的效率低很多,原因是binarySearch是二分搜索法,而indexOf使用的是逐个元素对比的方法。这里要注意: 使用binarySearch搜索时,元素必须进行排序,否则准确性就不可靠了 6)覆写Exception的fillInStackTrace方法 fillInStackTrace方法是用来记录异常时的栈信息的,这是非常耗时的动作,如果在开发时不需要关注栈信 息,则可以覆盖之,如下覆盖fillInStackTrace的自定义异常会使性能提升10倍以上: class MyException extends Exception { public Throwable fillInStackTrace() { return this; } } 7)不要建立冗余对象 不需要建立的对象就不能建立,说起来很容易,要完全遵循此规则难度就很大了,我们经常就会无意地创建冗 余对象,例如这样一段代码: public void doSomething() { // 异常信息 String exceptionMsg = "我出现异常了,快来救救我"; try { Thread.sleep(10); } catch (Exception e) { // 转换为自定义运行期异常 throw new MyException(e, exceptionMsg); } } 注意看变量exceptionMsg,这个字符串变量在什么时候会被用到?只有在抛出异常时它才有用武之地,那它 是什么时候创建的呢?只要该方法被调用就创建,不管会不会抛出异常。我们知道异常不是我们的主逻辑,不 是我们代码必须或经常要到达的区域,那位了这个不经常出现的场景就每次都多定义一个字符串变量,合适吗? 而且还要占用更多的内存!所以,在catch块中定义exceptionMsg才是正道:需要的时候才创建对象 我们知道运行一段程序需要三种资源:CPU、内存、I/O,提升CPU的处理速度可以加快代码的执行速度,直接 变现就是返回时间缩短了,效率提交了;内存是Java程序必须考虑的问题,在32位的机器上,一个JVM最多只 能使用2GB的内存,而且程序占用的内存越大,寻址效率也就越低,这也是影响效率的一个因素。I/O是程序展 示和存储数据的主要通道,如果它很缓慢就会影响正常的显式效果。所以我们在编程时需要从这三个方面入手 */ /** * 注意 * Java的基本优化方法非常多,但是随着Java的不断升级,很多看似很正确的优化策略就逐渐过时了(或者 * 说已经失效了),这一点还需要注意。最基本的优化方法就是自我验证,找出最佳的优化途径,提高系统性 * 能,不可盲目信任 */ } /** * 建议133: 若非必要,不要克隆对象 */ private void suggest133() { /* 通过clone方法生成一个对象时,就会不再执行构造函数了,只是在内存中进行数据块的拷贝,此方法看上去 似乎比new方法的性能好很多,但是Java的缔造者们也认识到“二八原则”,80%(甚至更多)的对象是通过new 关键字创建出来的,所以对new在生成对象(分配内存、初始化)时做了充分的性能优化,事实上,一般情况 下new生成的对象比clone生成的性能方面要好很多,如下示例代码: private static class Apple implements Cloneable { public Object clone() { // 注:这个实验去掉clone方法的try...catch应该要公平点 try { return super.clone(); } catch (CloneNotSupportedException e) { throw new Error(); } } } public static void main(String[] args) { // 循环10万次 final int maxLoops = 10 * 10000; int loops = 0; // 开始时间 long start = System.nanoTime(); // “母”对象 Apple apple = new Apple(); while (++loops < maxLoops) { apple.clone; } long mid = System.nanoTime(); System.out.println("clone 方法生成对象耗时:" + (mid-start) + " ns"); // new生成对象 while (--loops > 0) { new Apple(); } long end = System.nanoTime(); System.out.println("new 生成对象耗时:" + (end-mid) + " ns"); } 运行查看输出结果,发现用new生成对象竟然比clone方法快很多!原因是Apple的构造函数非常简单,而且 JVM对new做了大量的性能优化,而clone方式只是一个冷僻的生成对象方式,并不是主流,它主要用于构造 函数比较复杂,对象属性比较多,通过new关键字创建一个对象比较耗时的时候 */ /** * 注意 * 克隆对象并不比直接生成对象效率高 */ } /** * 建议134: 推荐使用“望闻问切”的方式诊断性能 */ private void suggest134() { /** * 注意 * 性能诊断遵循“望闻问切”,不可过度急躁 */ } /** * 建议135: 必须定义性能衡量标准 */ private void suggest135() { /* 制定性能衡量标准的原因有两个: 1)性能衡量标准是技术与业务之间的契约 2)性能衡量标准是技术优化的目标 性能优化是无底线的,性能优化得越厉害带来的副作用也就越明显,例如代码的可读性差,可扩展性降低等 */ /** * 注意 * 一个好的性能衡量标准应该包括以下KPI(Key Performance Indicators) * -核心业务的响应时间 * -重要业务的响应时间 */ } /** * 建议136: 枪打出头鸟—解决首要系统性能问题 */ private void suggest136() { /* 在一个系统出现性能问题的时候,很少会出现只有一个功能有性能问题,系统一旦出现性能问题,也就意味 着一批的功能都出现了问题,在这种情况下,我们要做的就是统计出业务人员认为重要而且缓慢的所有功能, 然后按照重要优先级和响应时间进行排序,并找出前三名,而这就是我们要找的“准出头鸟” “准出头鸟”找到了,然后再对这三个功能进行综合分析,运用“望闻问切”策略,找到问题的可能根源,然后 只修正第一个功能的性能缺陷,再来测试检查是否解决了这个问题,紧接着是第二个、第三个,循环之。可 能有疑问:为什么这里只修正第一个缺陷,而不是三个一起全部修正?这是因为第一个性能缺陷才是我们真 正的出头鸟,经验表明性能优化项目中超过80%的只要修正了第一个缺陷,其他的性能问题就会自行解决或 非常容易解决,已经不成为问题了 */ /** * 注意 * 解决性能优化要“单线程”小步前进,避免关注点过多导致精力分散 */ } /** * 建议137: 调整jvm参数以提升性能 */ private void suggest137() { /* 下面提供了四个常用的JVM优化手段,提供参考: 1)调整堆内存大小 在JVM中有两种内存:栈内存(Stack)和堆内存(Heap),栈内存的特点是空间比较小,速度快,用来 存放对象的引用及程序中的基本类型;而堆内存的特点是控件比较大,速度慢,一般对象都会在这里生成、 使用和消亡 栈空间是由线程开辟,线程结束,栈空间由JVM回收,因此它的大小一般不会对性能有太大的影响,但是 它会影响系统的稳定性,在超过栈内存的容量时,系统会报StackOverflowError错误。可以通过“java -Xss <size>”设置内存大小来解决此类问题 堆内存的调整不能太随意,调整得太小,会导致Full GC频繁执行,轻则导致系统性能急速下降,重则导 致系统根本无法使用:调整得太大,一则是浪费资源(当然,若设置了最小堆内存则可以避免此问题), 二则是产生系统不稳定的情况,例如在32位的机器上设置超过1.8GB的内存就有可能产生莫名其妙的错误。 设置初始化堆内存为1GB(也就是最小堆内存),最大堆内存为1.5GB可以用如下的参数: java -Xmx1536 -Xms1024m 2)调整堆内存中各分区的比例 JVM的堆内存包括三部分:新生区(Young Generation Space)、养老取(Tenure Generation Space)、 永久存储区(Permanent Space),其中新生成的对象都在新生区,它又分为伊甸区(Eden Space)、 幸存0区(Survivor 0 Space)和幸存1区(Survivor 1 Space),当程序中使用了new关键字时,首先 在伊甸区生成该对象,如果伊甸区满了,则用垃圾回收器进行回收,然后把剩余的对象移动到幸存区(0区 或1区),可如果幸存区也满了呢?垃圾回收器先进行回收,然后把剩余的对象移动到养老区,那要是养老 区也满了呢?此时就会触发Full GC(这是一个非常危险的动作,JVM会停止所有的执行,所有系统资源都 会让位给垃圾回收器),会对所有的对象过滤一遍,检查是否有可以回收的对象,如果还是没有的话,就 抛出OutOfMemoryError错误,系统不干了 清楚了这个原理,那就可以思考一下如何提升性能了:若扩大新生区,势必会减少养老区,这就可能产生不 稳定的情况,一般情况下,新生区和养老区的比例为1:3左右,设置命令如下: java -XX:NewSize=32 -XX:MaxNewSize=640m -XX:MaxPermSize=1280m -XX:newRatio=5 该配置指定新生代初始化为32MB(也就是新生区最小内存为32M),最大不超过640MB,养老区最大不超过 1280MB,新生区和养老区的比例为1:5 3)变更GC的垃圾回收策略 Java程序性能的最大障碍就是垃圾回收,我们不知道它何时会发生,也不知道它会执行多长时间,但是我们 可以想办法改变它对系统的影响,比如启用并行垃圾回收、规定并行回收的线程数量等,命令格式如下: java -XX:+UserParallelGC -XX:ParallelGCThreads=20 这里启用了并行垃圾回收机制,并且定义了20个收集线程(默认的收集线程等于CPU的数量),这对多CPU的 系统是非常有帮助的,可以大大减少垃圾回收对系统的影响,提高系统性能 当然,垃圾回收的策略还有很多属性可以修改,比如UseSerialGC(启用串行GC,默认值)、 ScavengeBeforeFullGC(新生代GC优先于Full GC执行)、UserConcMarkSweepGC(对老生代采用并发标 记交换算法进行GC)等,这些参数需要在系统中逐步调试 4)更换JVM */ /** * 注意 * 如果程序已经优化到了极致,但还是觉得性能比较低,那JVM的优化就要提到日程上来了。不过,由于 * JVM是系统运行的容器,所以稳定性也是必须考虑的,过度的优化可能就会导致系统故障频繁发生,导 * 致系统质量大幅下降 */ } /** * 建议138: 性能是个大“咕咚” */ private void suggest138() { /* 可以从四个方面分析Java系统的性能问题: 1)没有慢的系统,只有不满足业务的系统 如果有使用者告诉你,”这个系统太慢了“,也就是在间接地提醒您:系统没有满足业务需求,尚需努力 2)没有慢的系统,只有架构不良的系统 在做系统架构设计时,架构师有没有考虑并行计算?有没有考虑云计算技术?有没有负载均衡?...这些都 是解决我们性能问题的良方,只要架构设计得当,效率就不是问题 3)没有慢的系统,只有懒惰的技术人员 这里的技术人员涉及面很大,可以是开发人员,也可以是维护人员,甚至是应用软件的顾问人员等 4)没有慢的系统,只有不愿意投入的系统 这里的投入指的是资源,包括软硬件资源、人员资源及资金资源等,这不是项目组能够单独解决的问题,但 是它会严重影响系统的性能 */ /** * 注意 * 对现代化的系统建设来说,性能就是一个大”咕咚“--看清它的本质吧 */ } }
{ "pile_set_name": "Github" }
{ "pagination": { "GetBotAliases": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBotChannelAssociations": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBotVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBots": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBuiltinIntents": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetBuiltinSlotTypes": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetIntentVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetIntents": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetSlotTypeVersions": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" }, "GetSlotTypes": { "input_token": "nextToken", "output_token": "nextToken", "limit_key": "maxResults" } } }
{ "pile_set_name": "Github" }
//-------------------------------------------------------------------------- // Copyright (C) 2015-2020 Cisco and/or its affiliates. All rights reserved. // // This program is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License Version 2 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // 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 02110-1301, USA. //-------------------------------------------------------------------------- // pp_ips_action_iface.h author Joel Cornett <[email protected]> #ifndef PP_IPS_ACTION_IFACE_H #define PP_IPS_ACTION_IFACE_H #include "lua/lua_iface.h" namespace snort { class IpsAction; } extern const struct Lua::InstanceInterface<snort::IpsAction> IpsActionIface; #endif
{ "pile_set_name": "Github" }
# =================================================================== # # Copyright (c) 2014, Legrandin <[email protected]> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. 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. # # 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 HOLDER 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. # =================================================================== import unittest from binascii import unhexlify from Crypto.SelfTest.loader import load_tests from Crypto.SelfTest.st_common import list_test_cases from Crypto.Util.py3compat import tobytes, _memoryview, is_string from Crypto.Cipher import AES, DES3, DES from Crypto.Hash import SHAKE128 def get_tag_random(tag, length): return SHAKE128.new(data=tobytes(tag)).read(length) class BlockChainingTests(unittest.TestCase): key_128 = get_tag_random("key_128", 16) key_192 = get_tag_random("key_192", 24) iv_128 = get_tag_random("iv_128", 16) iv_64 = get_tag_random("iv_64", 8) data_128 = get_tag_random("data_128", 16) def test_loopback_128(self): cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) pt = get_tag_random("plaintext", 16 * 100) ct = cipher.encrypt(pt) cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2) def test_loopback_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) pt = get_tag_random("plaintext", 8 * 100) ct = cipher.encrypt(pt) cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) pt2 = cipher.decrypt(ct) self.assertEqual(pt, pt2) def test_iv(self): # If not passed, the iv is created randomly cipher = AES.new(self.key_128, self.aes_mode) iv1 = cipher.iv cipher = AES.new(self.key_128, self.aes_mode) iv2 = cipher.iv self.assertNotEqual(iv1, iv2) self.assertEqual(len(iv1), 16) # IV can be passed in uppercase or lowercase cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) ct = cipher.encrypt(self.data_128) cipher = AES.new(self.key_128, self.aes_mode, iv=self.iv_128) self.assertEquals(ct, cipher.encrypt(self.data_128)) cipher = AES.new(self.key_128, self.aes_mode, IV=self.iv_128) self.assertEquals(ct, cipher.encrypt(self.data_128)) def test_iv_must_be_bytes(self): self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, iv = u'test1234567890-*') def test_only_one_iv(self): # Only one IV/iv keyword allowed self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, iv=self.iv_128, IV=self.iv_128) def test_iv_with_matching_length(self): self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode, b"") self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode, self.iv_128[:15]) self.assertRaises(ValueError, AES.new, self.key_128, self.aes_mode, self.iv_128 + b"0") def test_block_size_128(self): cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) self.assertEqual(cipher.block_size, AES.block_size) def test_block_size_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) self.assertEqual(cipher.block_size, DES3.block_size) def test_unaligned_data_128(self): cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) for wrong_length in range(1,16): self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length) cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) for wrong_length in range(1,16): self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length) def test_unaligned_data_64(self): cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) for wrong_length in range(1,8): self.assertRaises(ValueError, cipher.encrypt, b"5" * wrong_length) cipher = DES3.new(self.key_192, self.des3_mode, self.iv_64) for wrong_length in range(1,8): self.assertRaises(ValueError, cipher.decrypt, b"5" * wrong_length) def test_IV_iv_attributes(self): data = get_tag_random("data", 16 * 100) for func in "encrypt", "decrypt": cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) getattr(cipher, func)(data) self.assertEqual(cipher.iv, self.iv_128) self.assertEqual(cipher.IV, self.iv_128) def test_unknown_parameters(self): self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, self.iv_128, 7) self.assertRaises(TypeError, AES.new, self.key_128, self.aes_mode, iv=self.iv_128, unknown=7) # But some are only known by the base cipher (e.g. use_aesni consumed by the AES module) AES.new(self.key_128, self.aes_mode, iv=self.iv_128, use_aesni=False) def test_null_encryption_decryption(self): for func in "encrypt", "decrypt": cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) result = getattr(cipher, func)(b"") self.assertEqual(result, b"") def test_either_encrypt_or_decrypt(self): cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) cipher.encrypt(b"") self.assertRaises(TypeError, cipher.decrypt, b"") cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) cipher.decrypt(b"") self.assertRaises(TypeError, cipher.encrypt, b"") def test_data_must_be_bytes(self): cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) self.assertRaises(TypeError, cipher.encrypt, u'test1234567890-*') cipher = AES.new(self.key_128, self.aes_mode, self.iv_128) self.assertRaises(TypeError, cipher.decrypt, u'test1234567890-*') def test_bytearray(self): data = b"1" * 16 data_ba = bytearray(data) # Encrypt key_ba = bytearray(self.key_128) iv_ba = bytearray(self.iv_128) cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128) ref1 = cipher1.encrypt(data) cipher2 = AES.new(key_ba, self.aes_mode, iv_ba) key_ba[:3] = b'\xFF\xFF\xFF' iv_ba[:3] = b'\xFF\xFF\xFF' ref2 = cipher2.encrypt(data_ba) self.assertEqual(ref1, ref2) self.assertEqual(cipher1.iv, cipher2.iv) # Decrypt key_ba = bytearray(self.key_128) iv_ba = bytearray(self.iv_128) cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128) ref3 = cipher3.decrypt(data) cipher4 = AES.new(key_ba, self.aes_mode, iv_ba) key_ba[:3] = b'\xFF\xFF\xFF' iv_ba[:3] = b'\xFF\xFF\xFF' ref4 = cipher4.decrypt(data_ba) self.assertEqual(ref3, ref4) def test_memoryview(self): data = b"1" * 16 data_mv = memoryview(bytearray(data)) # Encrypt key_mv = memoryview(bytearray(self.key_128)) iv_mv = memoryview(bytearray(self.iv_128)) cipher1 = AES.new(self.key_128, self.aes_mode, self.iv_128) ref1 = cipher1.encrypt(data) cipher2 = AES.new(key_mv, self.aes_mode, iv_mv) key_mv[:3] = b'\xFF\xFF\xFF' iv_mv[:3] = b'\xFF\xFF\xFF' ref2 = cipher2.encrypt(data_mv) self.assertEqual(ref1, ref2) self.assertEqual(cipher1.iv, cipher2.iv) # Decrypt key_mv = memoryview(bytearray(self.key_128)) iv_mv = memoryview(bytearray(self.iv_128)) cipher3 = AES.new(self.key_128, self.aes_mode, self.iv_128) ref3 = cipher3.decrypt(data) cipher4 = AES.new(key_mv, self.aes_mode, iv_mv) key_mv[:3] = b'\xFF\xFF\xFF' iv_mv[:3] = b'\xFF\xFF\xFF' ref4 = cipher4.decrypt(data_mv) self.assertEqual(ref3, ref4) def test_output_param(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) ct = cipher.encrypt(pt) output = bytearray(16) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) res = cipher.encrypt(pt, output=output) self.assertEqual(ct, output) self.assertEqual(res, None) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) res = cipher.decrypt(ct, output=output) self.assertEqual(pt, output) self.assertEqual(res, None) def test_output_param_same_buffer(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) ct = cipher.encrypt(pt) pt_ba = bytearray(pt) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) res = cipher.encrypt(pt_ba, output=pt_ba) self.assertEqual(ct, pt_ba) self.assertEqual(res, None) ct_ba = bytearray(ct) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) res = cipher.decrypt(ct_ba, output=ct_ba) self.assertEqual(pt, ct_ba) self.assertEqual(res, None) def test_output_param_memoryview(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) ct = cipher.encrypt(pt) output = memoryview(bytearray(16)) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) cipher.encrypt(pt, output=output) self.assertEqual(ct, output) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) cipher.decrypt(ct, output=output) self.assertEqual(pt, output) def test_output_param_neg(self): pt = b'5' * 16 cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) ct = cipher.encrypt(pt) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) self.assertRaises(TypeError, cipher.encrypt, pt, output=b'0'*16) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) self.assertRaises(TypeError, cipher.decrypt, ct, output=b'0'*16) shorter_output = bytearray(15) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) self.assertRaises(ValueError, cipher.encrypt, pt, output=shorter_output) cipher = AES.new(b'4'*16, self.aes_mode, iv=self.iv_128) self.assertRaises(ValueError, cipher.decrypt, ct, output=shorter_output) import sys if sys.version[:3] == "2.6": del test_memoryview del test_output_param_memoryview class CbcTests(BlockChainingTests): aes_mode = AES.MODE_CBC des3_mode = DES3.MODE_CBC class NistBlockChainingVectors(unittest.TestCase): def _do_kat_aes_test(self, file_name): test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name, "AES KAT", { "count" : lambda x: int(x) } ) assert(test_vectors) direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc cipher = AES.new(tv.key, self.aes_mode, tv.iv) if direction == "[ENCRYPT]": self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext) elif direction == "[DECRYPT]": self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext) else: assert False # See Section 6.4.2 in AESAVS def _do_mct_aes_test(self, file_name): test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "AES"), file_name, "AES Montecarlo", { "count" : lambda x: int(x) } ) assert(test_vectors) direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc cipher = AES.new(tv.key, self.aes_mode, tv.iv) if direction == '[ENCRYPT]': cts = [ tv.iv ] for count in range(1000): cts.append(cipher.encrypt(tv.plaintext)) tv.plaintext = cts[-2] self.assertEqual(cts[-1], tv.ciphertext) elif direction == '[DECRYPT]': pts = [ tv.iv] for count in range(1000): pts.append(cipher.decrypt(tv.ciphertext)) tv.ciphertext = pts[-2] self.assertEqual(pts[-1], tv.plaintext) else: assert False def _do_tdes_test(self, file_name): test_vectors = load_tests(("Crypto", "SelfTest", "Cipher", "test_vectors", "TDES"), file_name, "TDES CBC KAT", { "count" : lambda x: int(x) } ) assert(test_vectors) direction = None for tv in test_vectors: # The test vector file contains some directive lines if is_string(tv): direction = tv continue self.description = tv.desc if hasattr(tv, "keys"): cipher = DES.new(tv.keys, self.des_mode, tv.iv) else: if tv.key1 != tv.key3: key = tv.key1 + tv.key2 + tv.key3 # Option 3 else: key = tv.key1 + tv.key2 # Option 2 cipher = DES3.new(key, self.des3_mode, tv.iv) if direction == "[ENCRYPT]": self.assertEqual(cipher.encrypt(tv.plaintext), tv.ciphertext) elif direction == "[DECRYPT]": self.assertEqual(cipher.decrypt(tv.ciphertext), tv.plaintext) else: assert False class NistCbcVectors(NistBlockChainingVectors): aes_mode = AES.MODE_CBC des_mode = DES.MODE_CBC des3_mode = DES3.MODE_CBC # Create one test method per file nist_aes_kat_mmt_files = ( # KAT "CBCGFSbox128.rsp", "CBCGFSbox192.rsp", "CBCGFSbox256.rsp", "CBCKeySbox128.rsp", "CBCKeySbox192.rsp", "CBCKeySbox256.rsp", "CBCVarKey128.rsp", "CBCVarKey192.rsp", "CBCVarKey256.rsp", "CBCVarTxt128.rsp", "CBCVarTxt192.rsp", "CBCVarTxt256.rsp", # MMT "CBCMMT128.rsp", "CBCMMT192.rsp", "CBCMMT256.rsp", ) nist_aes_mct_files = ( "CBCMCT128.rsp", "CBCMCT192.rsp", "CBCMCT256.rsp", ) for file_name in nist_aes_kat_mmt_files: def new_func(self, file_name=file_name): self._do_kat_aes_test(file_name) setattr(NistCbcVectors, "test_AES_" + file_name, new_func) for file_name in nist_aes_mct_files: def new_func(self, file_name=file_name): self._do_mct_aes_test(file_name) setattr(NistCbcVectors, "test_AES_" + file_name, new_func) del file_name, new_func nist_tdes_files = ( "TCBCMMT2.rsp", # 2TDES "TCBCMMT3.rsp", # 3TDES "TCBCinvperm.rsp", # Single DES "TCBCpermop.rsp", "TCBCsubtab.rsp", "TCBCvarkey.rsp", "TCBCvartext.rsp", ) for file_name in nist_tdes_files: def new_func(self, file_name=file_name): self._do_tdes_test(file_name) setattr(NistCbcVectors, "test_TDES_" + file_name, new_func) # END OF NIST CBC TEST VECTORS class SP800TestVectors(unittest.TestCase): """Class exercising the CBC test vectors found in Section F.2 of NIST SP 800-3A""" def test_aes_128(self): key = '2b7e151628aed2a6abf7158809cf4f3c' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '7649abac8119b246cee98e9b12e9197d' +\ '5086cb9b507219ee95db113a917678b2' +\ '73bed6b8e3c1743b7116e69e22229516' +\ '3ff1caa1681fac09120eca307586e1a7' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) def test_aes_192(self): key = '8e73b0f7da0e6452c810f32b809079e562f8ead2522c6b7b' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = '4f021db243bc633d7178183a9fa071e8' +\ 'b4d9ada9ad7dedf4e5e738763f69145a' +\ '571b242012fb7ae07fa9baac3df102e0' +\ '08b0e27988598881d920a9e64f5615cd' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) def test_aes_256(self): key = '603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4' iv = '000102030405060708090a0b0c0d0e0f' plaintext = '6bc1bee22e409f96e93d7e117393172a' +\ 'ae2d8a571e03ac9c9eb76fac45af8e51' +\ '30c81c46a35ce411e5fbc1191a0a52ef' +\ 'f69f2445df4f9b17ad2b417be66c3710' ciphertext = 'f58c4c04d6e5f1ba779eabfb5f7bfbd6' +\ '9cfc4e967edb808d679f777bc6702c7d' +\ '39f23369a9d9bacfa530e26304231461' +\ 'b2eb05e2c39be9fcda6c19078c6a9d1b' key = unhexlify(key) iv = unhexlify(iv) plaintext = unhexlify(plaintext) ciphertext = unhexlify(ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.encrypt(plaintext), ciphertext) cipher = AES.new(key, AES.MODE_CBC, iv) self.assertEqual(cipher.decrypt(ciphertext), plaintext) def get_tests(config={}): tests = [] tests += list_test_cases(CbcTests) if config.get('slow_tests'): tests += list_test_cases(NistCbcVectors) tests += list_test_cases(SP800TestVectors) return tests if __name__ == '__main__': suite = lambda: unittest.TestSuite(get_tests()) unittest.main(defaultTest='suite')
{ "pile_set_name": "Github" }
// +build windows package winio import ( "syscall" "unsafe" ) //sys lookupAccountName(systemName *uint16, accountName string, sid *byte, sidSize *uint32, refDomain *uint16, refDomainSize *uint32, sidNameUse *uint32) (err error) = advapi32.LookupAccountNameW //sys convertSidToStringSid(sid *byte, str **uint16) (err error) = advapi32.ConvertSidToStringSidW //sys convertStringSecurityDescriptorToSecurityDescriptor(str string, revision uint32, sd *uintptr, size *uint32) (err error) = advapi32.ConvertStringSecurityDescriptorToSecurityDescriptorW //sys convertSecurityDescriptorToStringSecurityDescriptor(sd *byte, revision uint32, secInfo uint32, sddl **uint16, sddlSize *uint32) (err error) = advapi32.ConvertSecurityDescriptorToStringSecurityDescriptorW //sys localFree(mem uintptr) = LocalFree //sys getSecurityDescriptorLength(sd uintptr) (len uint32) = advapi32.GetSecurityDescriptorLength const ( cERROR_NONE_MAPPED = syscall.Errno(1332) ) type AccountLookupError struct { Name string Err error } func (e *AccountLookupError) Error() string { if e.Name == "" { return "lookup account: empty account name specified" } var s string switch e.Err { case cERROR_NONE_MAPPED: s = "not found" default: s = e.Err.Error() } return "lookup account " + e.Name + ": " + s } type SddlConversionError struct { Sddl string Err error } func (e *SddlConversionError) Error() string { return "convert " + e.Sddl + ": " + e.Err.Error() } // LookupSidByName looks up the SID of an account by name func LookupSidByName(name string) (sid string, err error) { if name == "" { return "", &AccountLookupError{name, cERROR_NONE_MAPPED} } var sidSize, sidNameUse, refDomainSize uint32 err = lookupAccountName(nil, name, nil, &sidSize, nil, &refDomainSize, &sidNameUse) if err != nil && err != syscall.ERROR_INSUFFICIENT_BUFFER { return "", &AccountLookupError{name, err} } sidBuffer := make([]byte, sidSize) refDomainBuffer := make([]uint16, refDomainSize) err = lookupAccountName(nil, name, &sidBuffer[0], &sidSize, &refDomainBuffer[0], &refDomainSize, &sidNameUse) if err != nil { return "", &AccountLookupError{name, err} } var strBuffer *uint16 err = convertSidToStringSid(&sidBuffer[0], &strBuffer) if err != nil { return "", &AccountLookupError{name, err} } sid = syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(strBuffer))[:]) localFree(uintptr(unsafe.Pointer(strBuffer))) return sid, nil } func SddlToSecurityDescriptor(sddl string) ([]byte, error) { var sdBuffer uintptr err := convertStringSecurityDescriptorToSecurityDescriptor(sddl, 1, &sdBuffer, nil) if err != nil { return nil, &SddlConversionError{sddl, err} } defer localFree(sdBuffer) sd := make([]byte, getSecurityDescriptorLength(sdBuffer)) copy(sd, (*[0xffff]byte)(unsafe.Pointer(sdBuffer))[:len(sd)]) return sd, nil } func SecurityDescriptorToSddl(sd []byte) (string, error) { var sddl *uint16 // The returned string length seems to including an aribtrary number of terminating NULs. // Don't use it. err := convertSecurityDescriptorToStringSecurityDescriptor(&sd[0], 1, 0xff, &sddl, nil) if err != nil { return "", err } defer localFree(uintptr(unsafe.Pointer(sddl))) return syscall.UTF16ToString((*[0xffff]uint16)(unsafe.Pointer(sddl))[:]), nil }
{ "pile_set_name": "Github" }
'use strict'; angular.module("ngLocale", [], ["$provide", function($provide) { var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"}; function getDecimals(n) { n = n + ''; var i = n.indexOf('.'); return (i == -1) ? 0 : n.length - i - 1; } function getVF(n, opt_precision) { var v = opt_precision; if (undefined === v) { v = Math.min(getDecimals(n), 3); } var base = Math.pow(10, v); var f = ((n * base) | 0) % base; return {v: v, f: f}; } $provide.value("$locale", { "DATETIME_FORMATS": { "AMPMS": [ "prije podne", "popodne" ], "DAY": [ "nedjelja", "ponedjeljak", "utorak", "srijeda", "\u010detvrtak", "petak", "subota" ], "ERANAMES": [ "Prije nove ere", "Nove ere" ], "ERAS": [ "p. n. e.", "n. e." ], "FIRSTDAYOFWEEK": 0, "MONTH": [ "januar", "februar", "mart", "april", "maj", "juni", "juli", "august", "septembar", "oktobar", "novembar", "decembar" ], "SHORTDAY": [ "ned", "pon", "uto", "sri", "\u010det", "pet", "sub" ], "SHORTMONTH": [ "jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec" ], "STANDALONEMONTH": [ "januar", "februar", "mart", "april", "maj", "juni", "juli", "august", "septembar", "oktobar", "novembar", "decembar" ], "WEEKENDRANGE": [ 5, 6 ], "fullDate": "EEEE, dd. MMMM y.", "longDate": "dd. MMMM y.", "medium": "dd. MMM. y. HH:mm:ss", "mediumDate": "dd. MMM. y.", "mediumTime": "HH:mm:ss", "short": "dd.MM.yy. HH:mm", "shortDate": "dd.MM.yy.", "shortTime": "HH:mm" }, "NUMBER_FORMATS": { "CURRENCY_SYM": "KM", "DECIMAL_SEP": ",", "GROUP_SEP": ".", "PATTERNS": [ { "gSize": 3, "lgSize": 3, "maxFrac": 3, "minFrac": 0, "minInt": 1, "negPre": "-", "negSuf": "", "posPre": "", "posSuf": "" }, { "gSize": 3, "lgSize": 3, "maxFrac": 2, "minFrac": 2, "minInt": 1, "negPre": "-", "negSuf": "\u00a0\u00a4", "posPre": "", "posSuf": "\u00a0\u00a4" } ] }, "id": "bs", "localeID": "bs", "pluralCat": function(n, opt_precision) { var i = n | 0; var vf = getVF(n, opt_precision); if (vf.v == 0 && i % 10 == 1 && i % 100 != 11 || vf.f % 10 == 1 && vf.f % 100 != 11) { return PLURAL_CATEGORY.ONE; } if (vf.v == 0 && i % 10 >= 2 && i % 10 <= 4 && (i % 100 < 12 || i % 100 > 14) || vf.f % 10 >= 2 && vf.f % 10 <= 4 && (vf.f % 100 < 12 || vf.f % 100 > 14)) { return PLURAL_CATEGORY.FEW; } return PLURAL_CATEGORY.OTHER;} }); }]);
{ "pile_set_name": "Github" }
CC-P3-OTTERBOX-OBIPHONE4 CC-P3-OTTERBOX-OBIPHONE5 CC-P3-BELKIN-SILBLKIPH4 CC-P3-BELKIN-SILBLKIPH5 CC-P3-APPLE-BUMPIPHONE4 CC-P4-OTTERBOX-OBDROID4 CC-T7-ZAGG-FOLIOMINI CC-T7-BELKIN-SLEEVE CC-T10-RIM-BBERRYPLAY CC-T11-ZAGG-FOLIO CC-T11-BELKIN-SLEEVE DP-IPHONE4 DP-IPHONE5 DP-NOKLUMIA DP-HTCONE DP-HTCREZOUND DP-HTCDROIDINC DP-MOTDROID2 DP-MOTDROID3 DP-MOTDROIDRAZ DP-SAMSGALAX DP-SAMSGALAX3 DP-SAMSGALAX4 DP-SAMSGALAXTAB BT-HS-BEATSWIRELESS BT-HS-PLANT-M25 BT-HS-PLANT-VOYLEGEND BT-HS-JAWB-ICONTHD BT-HS-JABRA-WAVE BT-HS-SAMS-HM1300 BT-SP-JAWB-JAMBOX BT-SP-JAWB-JAMBOXBIG BT-SP-BOSESNDLNK2 BT-KB-LOGITECH BT-MO-MOT-BTMOUSE BT-CK-JABRA-FREEWAY BT-CK-D-ROADSTER2 BA-MOPHIE-JUICEPACKPLUS BA-MOPHIE-JUICEPACKAIR BA-NOK-LUMIA BA-HTC-REZOUND BA-SAMS-STELLAR MC-SANDISK-MICROSD4GB MC-SANDISK-MICROSD8GB MC-SANDISK-MICROSD16GB MC-SANDISK-MICROSD32GB MC-SANDISK-MICROSD64GB MC-SANDISK-READER MC-INTUIT-CCREADER MC-SQUARE-CCREADER CH-APPLE-5W CH-APPLE-10W CH-APPLE-12W CH-APPLE-5WL CH-APPLE-10WL CH-APPLE-12WL CH-MOT-MICROUSB CH-RIM-MICROUSB CH-SAMS-MICROUSB CH-NOK-INDUCTIVE HS-APPLE-EARBUDS HS-KLIPSCH-IMAGEONE HS-SENNH-CX870 HS-BOSE-MIE2I HS-SKULLC-MERGER HS-MONST-NERGY HS-PLANT-MX200 MO-IBOLT-MOUNT MO-MOT-RAZRM MO-IGRIP-WINDOW MO-IGRIP-VENT AC-ASSTCHARMS AC-BLING AC-SIERRA-HOTSPOT3G AC-SIERRA-HOTSPOT4G AC-MOTO-HOTSPOT3G AC-MOTO-HOTSPOT4G AC-SAMS-NETEXTEND
{ "pile_set_name": "Github" }
/* *********************************************************************************************************************** * * Copyright (c) 2019-2020 Advanced Micro Devices, Inc. All Rights Reserved. * * 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. * **********************************************************************************************************************/ #include "protocols/loggingServer.h" #include "msgChannel.h" #define LOGGING_SERVER_MIN_VERSION 2 #define LOGGING_SERVER_MAX_VERSION 3 namespace DevDriver { namespace LoggingProtocol { static const NamedLoggingCategory kDefaultLoggingCategories[kReservedCategoryCount] = { {kGeneralCategoryMask, "General"}, {kSystemCategoryMask, "System"}, }; static_assert(kGeneralCategoryOffset == 0, "General category offset has changed unexpectedly"); static_assert(kSystemCategoryOffset == 1, "System category offset has changed unexpectedly"); LoggingServer::LoggingServer(IMsgChannel* pMsgChannel) : BaseProtocolServer(pMsgChannel, Protocol::Logging, LOGGING_SERVER_MIN_VERSION, LOGGING_SERVER_MAX_VERSION) , m_categories() , m_activeSessions(pMsgChannel->GetAllocCb()) , m_numCategories(0) { DD_ASSERT(m_pMsgChannel != nullptr); // Initialize the category table memset(&m_categories[0], 0, sizeof(m_categories)); // Initialize default logging categories for (uint32 i = 0; i < kReservedCategoryCount; i++) { // Only initialize valid categorie entries if (kDefaultLoggingCategories[i].category != 0 && kDefaultLoggingCategories[i].name[0] != 0) { // Validate that there hasn't been a mistake made somewhere DD_ASSERT(kDefaultLoggingCategories[i].category == ((LoggingCategory)1 << (kDefinableCategoryCount + i))); // Copy the category definition into our table and increment count m_categories[kDefinableCategoryCount + i] = kDefaultLoggingCategories[i]; m_numCategories++; } } } LoggingServer::~LoggingServer() { } bool LoggingServer::AcceptSession(const SharedPointer<ISession>& pSession) { DD_UNUSED(pSession); return true; } void LoggingServer::SessionEstablished(const SharedPointer<ISession>& pSession) { DD_UNUSED(pSession); // Allocate session data for the newly established session LoggingSession* pSessionData = DD_NEW(LoggingSession, m_pMsgChannel->GetAllocCb())(m_pMsgChannel->GetAllocCb(), pSession); // WA: Force MSVC's static analyzer to ignore unhandled OOM. DD_ASSUME(pSessionData != nullptr); pSessionData->state = SessionState::ReceivePayload; pSessionData->loggingEnabled = false; memset(&pSessionData->scratchPayload, 0, sizeof(pSessionData->scratchPayload)); // Default to all messages enabled. pSessionData->filter.priority = LogLevel::Error; pSessionData->filter.category = kAllLoggingCategories; LockData(); m_activeSessions.PushBack(pSessionData); UnlockData(); pSession->SetUserData(pSessionData); } void LoggingServer::UpdateSession(const SharedPointer<ISession>& pSession) { LoggingSession *pSessionData = reinterpret_cast<LoggingSession*>(pSession->GetUserData()); switch (pSessionData->state) { case SessionState::ReceivePayload: { const Result result = pSession->ReceivePayload(&pSessionData->scratchPayload, kNoWait); if (result == Result::Success) { pSessionData->state = SessionState::ProcessPayload; } else if (result == Result::NotReady) { // If there's no messages to receive, we should send log messages if logging is enabled. if (pSessionData->loggingEnabled) { LockData(); // Send as many log messages from our queue as possible. while (pSessionData->messages.PeekFront() != nullptr) { const SizedPayloadContainer* pPayload = pSessionData->messages.PeekFront(); if (pSessionData->SendPayload(pPayload, kNoWait) == Result::Success) { DD_PRINT(LogLevel::Debug, "Sent Logging Payload To Session %d!", pSession->GetSessionId()); // Pop the message off the queue since it was successfully sent. pSessionData->messages.PopFront(); } else { break; } } UnlockData(); } } break; } case SessionState::ProcessPayload: { SizedPayloadContainer& container = pSessionData->scratchPayload; switch (container.GetPayload<LoggingHeader>().command) { case LoggingMessage::QueryCategoriesRequest: { LockData(); const uint32 numCategories = (m_numCategories <= kMaxCategoryCount) ? m_numCategories : 0; UnlockData(); container.CreatePayload<QueryCategoriesNumResponsePayload>(numCategories); pSessionData->state = SessionState::SendCategoriesNumResponse; break; } case LoggingMessage::EnableLoggingRequest: { DD_PRINT(LogLevel::Debug, "Starting Logging!"); LockData(); pSessionData->filter = container.GetPayload<EnableLoggingRequestPayload>().filter; pSessionData->loggingEnabled = true; UnlockData(); container.CreatePayload<EnableLoggingResponsePayload>(Result::Success); pSessionData->state = SessionState::SendPayload; break; } case LoggingMessage::DisableLogging: { DD_PRINT(LogLevel::Debug, "Stopping Logging!"); LockData(); pSessionData->loggingEnabled = false; pSessionData->state = SessionState::FinishLogging; // We have no additional messages to send so let the client know via the sentinel. SizedPayloadContainer* pPayload = pSessionData->messages.AllocateBack(); if (pPayload != nullptr) { pPayload->CreatePayload<LoggingHeader>(LoggingMessage::LogMessageSentinel); } DD_PRINT(LogLevel::Debug, "Inserted logging sentinel"); UnlockData(); break; } default: { DD_UNREACHABLE(); break; } } break; } case SessionState::FinishLogging: { DD_PRINT(LogLevel::Debug, "Finishing Logging!"); LockData(); // Send as many log messages from our queue as possible. if (pSessionData->messages.Size() > 0) { DD_PRINT(LogLevel::Debug, "Logging messages remaining: %u", pSessionData->messages.Size()); const SizedPayloadContainer* pPayload = pSessionData->messages.PeekFront(); while (pPayload != nullptr) { if (pSessionData->SendPayload(pPayload, kNoWait) == Result::Success) { // Pop the message off the queue since it was successfully sent. pSessionData->messages.PopFront(); // Peek at the next message. pPayload = pSessionData->messages.PeekFront(); } else { break; } } } else { pSessionData->state = SessionState::ReceivePayload; } UnlockData(); break; } case SessionState::SendPayload: { Result result = pSessionData->SendPayload(&pSessionData->scratchPayload, kNoWait); if (result == Result::Success) { pSessionData->state = SessionState::ReceivePayload; } break; } case SessionState::SendCategoriesNumResponse: { Result result = pSessionData->SendPayload(&pSessionData->scratchPayload, kNoWait); if (result == Result::Success) { const QueryCategoriesNumResponsePayload* pQueryCategoriesResponse = reinterpret_cast<QueryCategoriesNumResponsePayload*>(pSessionData->scratchPayload.payload); if (pQueryCategoriesResponse->numCategories > 0) { pSessionData->itemIndex = 0; pSessionData->numItems = 0; pSessionData->state = SessionState::SendCategoriesDataResponse; // Prepare the payload for the first data response if (pSessionData->numItems < m_numCategories) { // If m_numCategories were to get modified and pSessionData->itemIndex is already past // the insertion point this can potentially cause an access violation by iterating past // the array boundary. we prevent this by not allowing modification of this table while // there are clients connected, but this probably needs to be addressed at some point. while (m_categories[pSessionData->itemIndex].category == 0) { // Find first valid category pSessionData->itemIndex++; } const Version sessionVersion = pSession->GetVersion(); LockData(); const NamedLoggingCategory& category = m_categories[pSessionData->itemIndex]; const size_t categoryNameSize = strlen(category.name) + 1; QueryCategoriesDataResponsePayload::WritePayload(m_categories[pSessionData->itemIndex], sessionVersion, categoryNameSize, &pSessionData->scratchPayload); UnlockData(); } } else { pSessionData->state = SessionState::ReceivePayload; } } break; } case SessionState::SendCategoriesDataResponse: { if (pSessionData->numItems < m_numCategories) { while (pSessionData->SendPayload(&pSessionData->scratchPayload, kNoWait) == Result::Success) { pSessionData->numItems++; // Prepare the payload for the next data response if necessary if (pSessionData->numItems < m_numCategories) { // Seek to the next valid category in the table. // TODO: there is a potential issue here where if the number of categories increases // but we've already passed the insertion point this will cause an access violation by // iterating off the array. we prevent this by not allowing modification of this table while // there are clients connected, but this probably needs to be addressed at some point. while (m_categories[++pSessionData->itemIndex].category == 0) { } const Version sessionVersion = pSession->GetVersion(); LockData(); const NamedLoggingCategory& category = m_categories[pSessionData->itemIndex]; const size_t categoryNameSize = strlen(category.name) + 1; QueryCategoriesDataResponsePayload::WritePayload(m_categories[pSessionData->itemIndex], sessionVersion, categoryNameSize, &pSessionData->scratchPayload); UnlockData(); } else { // Break out of the send loop if we've finished sending all of the responses break; } } } else { // We've sent all the responses. Return to normal operation. pSessionData->state = SessionState::ReceivePayload; } break; } default: { DD_UNREACHABLE(); break; } } } void LoggingServer::SessionTerminated(const SharedPointer<ISession>& pSession, Result terminationReason) { DD_UNUSED(terminationReason); LoggingSession *pLoggingSession = reinterpret_cast<LoggingSession*>(pSession->SetUserData(nullptr)); // Free the session data if (pLoggingSession != nullptr) { LockData(); // We should always have at least one session in this list on termination. (This session) DD_ASSERT(m_activeSessions.IsEmpty() == false); m_activeSessions.Remove(pLoggingSession); UnlockData(); DD_DELETE(pLoggingSession, m_pMsgChannel->GetAllocCb()); } } Result LoggingServer::AddCategoryTable(uint32 offset, uint32 count, const char **pCategoryTable) { Result result = Result::Error; LockData(); // Only allow modification if no sessions are connected. // This is explicitly to prevent an issue where the number of categories changes while the server is // trying to respond to QueryCategoriesRequest. if (m_activeSessions.Size() == 0) { // Ensure that the offset is valid and that the count is nonzero if ((offset < kDefinableCategoryCount) & (count > 0)) { bool available = true; // Ee need to make sure each index is valid and unused for (uint32 index = 0; index < count; index++) { size_t catIndex = (index + offset); // If either of these cases are true we abort: // 1) the index is greater than the maximum definable allowed // 2) the category table defines a string and it is already taken // note: this allows null pointers to be ignored in the category table if ((catIndex >= kDefinableCategoryCount) || ((pCategoryTable[index] != nullptr) & (m_categories[catIndex].category != 0))) { available = false; break; } } // If no errors were found if (available) { for (uint32 index = 0; index < count; index++) { // Only do this if the entry in the category table is not null. Allows us to skip entries // by defining null pointers inside the table if (pCategoryTable[index] != nullptr) { const uint32 catIndex = index + offset; const LoggingCategory mask = ((LoggingCategory)1 << catIndex) & kDefinableCategoryMask; if (catIndex < kDefinableCategoryCount && mask != 0) { // Copy the category name into the local category table and calculate the bitmask Platform::Strncpy(m_categories[catIndex].name, pCategoryTable[index], sizeof(NamedLoggingCategory::name)); m_categories[catIndex].category = mask; m_numCategories++; } else { DD_UNREACHABLE(); } } } result = Result::Success; } } } UnlockData(); return result; } void LoggingServer::Log(LogLevel priority, LoggingCategory category, const char* pFormat, va_list args) { // todo: figure out a way to make this threadsafe. right now Log() will cause serialization // of separate threads LockData(); // We only need to do work if there are active sessions to send messages to. if (m_activeSessions.Size() > 0) { // define the filter out here so we just copy it into destination messages LogMessage message = {}; message.filter.priority = priority; message.filter.category = category; Platform::Vsnprintf(message.message, sizeof(LogMessage::message), pFormat, args); // Calculate the message size (including the null terminator). const size_t messageSize = strlen(message.message) + 1; for (auto& pSessionData : m_activeSessions) { const LoggingFilter& currentFilter = pSessionData->filter; const bool sendMessage = (currentFilter.priority <= priority) & ((currentFilter.category & category) != 0); // if the session has logging enabled and the message satisfies the filter of the session if ((pSessionData->loggingEnabled) & sendMessage) { const Version sessionVersion = pSessionData->pSession->GetVersion(); // We can only inline the message sending if the server is currently in the receive payload // state. Otherwise we might end up inserting a log message in between multi-step control // procedures in the server. Doing so would cause unexpected messages to be sent to the client. const bool canInlineMsg = (pSessionData->state == SessionState::ReceivePayload); // Try to send out the log payload immediately if its message queue is empty if (pSessionData->messages.IsEmpty() == true) { SizedPayloadContainer payload = {}; // Write the log message payload LogMessagePayload::WritePayload(message, sessionVersion, messageSize, &payload); // Send the payload if (canInlineMsg && (pSessionData->SendPayload(&payload, kNoWait) == Result::Success)) { DD_PRINT(LogLevel::Debug, "Sent Logging Payload To Session %d!", pSessionData->pSession->GetSessionId()); } else { // Push the payload back to the queue if the sendPayload fails pSessionData->messages.PushBack(payload); } } else { // Allocate a message and copy the message into the buffer of all sessions SizedPayloadContainer* pPayloadContainer = pSessionData->messages.AllocateBack(); if (pPayloadContainer != nullptr) { LogMessagePayload::WritePayload(message, sessionVersion, messageSize, pPayloadContainer); } DD_ASSERT(pSessionData->messages.PeekFront() != nullptr); // Only try to send one front payload rather than all payloads in the queue as we don't want the Log() // thread take up too much time here if (canInlineMsg && (pSessionData->SendPayload(pSessionData->messages.PeekFront(), kNoWait) == Result::Success)) { DD_PRINT(LogLevel::Debug, "Sent Logging Payload To Session %d!", pSessionData->pSession->GetSessionId()); // Pop the message off the queue since it was successfully sent. pSessionData->messages.PopFront(); } } } } } UnlockData(); } void LoggingServer::LockData() { m_mutex.Lock(); } void LoggingServer::UnlockData() { m_mutex.Unlock(); } Result LoggingSession::SendPayload(const SizedPayloadContainer* pPayload, uint32 timeoutInMs) { // If we're running an older logging version, always write the fixed payload size. Otherwise, write the real size. const uint32 payloadSize = (pSession->GetVersion() >= LOGGING_LARGE_MESSAGES_VERSION) ? pPayload->payloadSize : kLegacyLoggingPayloadSize; return pSession->Send(payloadSize, pPayload->payload, timeoutInMs); } } } // DevDriver
{ "pile_set_name": "Github" }
// Copyright (C) 2002-2014 Nikolaus Gebhardt // This file is part of the "irrKlang" library. // For conditions of distribution and use, see copyright notice in irrKlang.h #ifndef __I_IRRKLANG_AUDIO_STREAM_H_INCLUDED__ #define __I_IRRKLANG_AUDIO_STREAM_H_INCLUDED__ #include "ik_IRefCounted.h" #include "ik_SAudioStreamFormat.h" namespace irrklang { //! Reads and decodes audio data into an usable audio stream for the ISoundEngine class IAudioStream : public IRefCounted { public: //! destructor virtual ~IAudioStream() {}; //! returns format of the audio stream virtual SAudioStreamFormat getFormat() = 0; //! sets the position of the audio stream. /** For example to let the stream be read from the beginning of the file again, setPosition(0) would be called. This is usually done be the sound engine to loop a stream after if has reached the end. Return true if sucessful and 0 if not. \param pos: Position in frames.*/ virtual bool setPosition(ik_s32 pos) = 0; //! returns true if the audio stream is seekable /* Some file formats like (MODs) don't support seeking */ virtual bool getIsSeekingSupported() { return true; } //! tells the audio stream to read frameCountToRead audio frames into the specified buffer /** \param target: Target data buffer to the method will write the read frames into. The specified buffer will be at least getFormat().getFrameSize()*frameCountToRead bytes big. \param frameCountToRead: amount of frames to be read. \returns Returns amount of frames really read. Should be frameCountToRead in most cases. */ virtual ik_s32 readFrames(void* target, ik_s32 frameCountToRead) = 0; }; } // end namespace irrklang #endif
{ "pile_set_name": "Github" }
var baseClamp = require('./_baseClamp'), baseToString = require('./_baseToString'), toInteger = require('./toInteger'), toString = require('./toString'); /** * Checks if `string` starts with the given target string. * * @static * @memberOf _ * @since 3.0.0 * @category String * @param {string} [string=''] The string to inspect. * @param {string} [target] The string to search for. * @param {number} [position=0] The position to search from. * @returns {boolean} Returns `true` if `string` starts with `target`, * else `false`. * @example * * _.startsWith('abc', 'a'); * // => true * * _.startsWith('abc', 'b'); * // => false * * _.startsWith('abc', 'b', 1); * // => true */ function startsWith(string, target, position) { string = toString(string); position = position == null ? 0 : baseClamp(toInteger(position), 0, string.length); target = baseToString(target); return string.slice(position, position + target.length) == target; } module.exports = startsWith;
{ "pile_set_name": "Github" }
created_by: Создал about: Описание add_description: Добавить описание phone: Мобильный телефон email: Email
{ "pile_set_name": "Github" }
class Testp convert A '2' B '3' end prechigh left B preclow rule /* comment */ target: A B C nonterminal { action "string" == /regexp/o 1 /= 3 } ; # comment nonterminal: A '+' B = A; /* end */ end ---- driver # driver is old name
{ "pile_set_name": "Github" }
QS prev_prev_son==- { "b^*","ch^*","d^*","dh^*","f^*","g^*","hh^*","jh^*","k^*","p^*","s^*","sh^*","t^*","th^*","v^*","z^*","zh^*" } QS prev_prev_vc==+ { "aa^*","ae^*","ah^*","ao^*","aw^*","ax^*","ay^*","eh^*","er^*","ey^*","ih^*","iy^*","ow^*","oy^*","uh^*","uw^*" } QS prev_prev_cvox==+ { "b^*","d^*","dh^*","g^*","jh^*","l^*","m^*","n^*","ng^*","r^*","v^*","w^*","y^*","z^*","zh^*" } QS prev_prev_ccor==+ { "ch^*","d^*","dh^*","jh^*","l^*","n^*","r^*","s^*","sh^*","t^*","th^*","z^*","zh^*" } QS prev_prev_cont==+ { "dh^*","f^*","hh^*","l^*","r^*","s^*","sh^*","th^*","v^*","w^*","y^*","z^*","zh^*" } QS prev_prev_vrnd==- { "aa^*","ae^*","ah^*","aw^*","ax^*","ay^*","eh^*","er^*","ey^*","ih^*","iy^*" } QS prev_prev_ccor==+&&son==- { "ch^*","d^*","dh^*","jh^*","s^*","sh^*","t^*","th^*","z^*","zh^*" } QS prev_prev_cvox==- { "ch^*","f^*","hh^*","k^*","p^*","s^*","sh^*","t^*","th^*" } QS prev_prev_cont==+&&ccor==+ { "dh^*","l^*","r^*","s^*","sh^*","th^*","z^*","zh^*" } QS prev_prev_cont==-&&cvox==+ { "b^*","d^*","g^*","jh^*","m^*","n^*","ng^*" } QS prev_prev_csib==+ { "ch^*","jh^*","s^*","sh^*","z^*","zh^*" } QS prev_prev_vlng==s { "ae^*","ah^*","eh^*","ih^*","uh^*" } QS prev_prev_vfront==2 { "ah^*","aw^*","ax^*","ay^*","er^*" } QS prev_prev_cvox==-&&ctype==f { "f^*","hh^*","s^*","sh^*","th^*" } QS prev_prev_cvox==+&&cplace==a { "d^*","l^*","n^*","r^*","z^*" } QS prev_prev_cplace==l { "b^*","m^*","p^*","w^*" } QS prev_prev_vheight==1 { "ih^*","iy^*","uh^*","uw^*" } QS prev_prev_vlng==l { "aa^*","ao^*","iy^*","uw^*" } QS prev_prev_vrnd==-&&vheight==3 { "aa^*","ae^*","aw^*","ay^*" } QS prev_prev_cvox==+&&clab==+ { "b^*","m^*","v^*","w^*" } QS prev_prev_cont==+&&cplace==a { "l^*","r^*","s^*","z^*" } QS prev_prev_vfront==2&&vheight==2 { "ah^*","ax^*","er^*" } QS prev_prev_ctype==s&&cplace==a { "d^*","t^*" } QS prev_prev_vfront==1&&vheight==2 { "eh^*","ey^*" } QS prev_prev_cvox==-&&cplace==p { "ch^*","sh^*" } QS prev_prev_name==ey { "ey^*" } QS prev_prev_name==f { "f^*" } QS prev_prev_name==pau { "pau^*" } QS prev_vc==- { "*^b-*","*^ch-*","*^d-*","*^dh-*","*^f-*","*^g-*","*^hh-*","*^jh-*","*^k-*","*^l-*","*^m-*","*^n-*","*^ng-*","*^p-*","*^r-*","*^s-*","*^sh-*","*^t-*","*^th-*","*^v-*","*^w-*","*^y-*","*^z-*","*^zh-*" } QS prev_son==- { "*^b-*","*^ch-*","*^d-*","*^dh-*","*^f-*","*^g-*","*^hh-*","*^jh-*","*^k-*","*^p-*","*^s-*","*^sh-*","*^t-*","*^th-*","*^v-*","*^z-*","*^zh-*" } QS prev_vc==+ { "*^aa-*","*^ae-*","*^ah-*","*^ao-*","*^aw-*","*^ax-*","*^ay-*","*^eh-*","*^er-*","*^ey-*","*^ih-*","*^iy-*","*^ow-*","*^oy-*","*^uh-*","*^uw-*" } QS prev_cvox==+ { "*^b-*","*^d-*","*^dh-*","*^g-*","*^jh-*","*^l-*","*^m-*","*^n-*","*^ng-*","*^r-*","*^v-*","*^w-*","*^y-*","*^z-*","*^zh-*" } QS prev_ccor==+ { "*^ch-*","*^d-*","*^dh-*","*^jh-*","*^l-*","*^n-*","*^r-*","*^s-*","*^sh-*","*^t-*","*^th-*","*^z-*","*^zh-*" } QS prev_cont==+ { "*^dh-*","*^f-*","*^hh-*","*^l-*","*^r-*","*^s-*","*^sh-*","*^th-*","*^v-*","*^w-*","*^y-*","*^z-*","*^zh-*" } QS prev_vrnd==- { "*^aa-*","*^ae-*","*^ah-*","*^aw-*","*^ax-*","*^ay-*","*^eh-*","*^er-*","*^ey-*","*^ih-*","*^iy-*" } QS prev_cont==- { "*^b-*","*^ch-*","*^d-*","*^g-*","*^jh-*","*^k-*","*^m-*","*^n-*","*^ng-*","*^p-*","*^t-*" } QS prev_ccor==+&&son==- { "*^ch-*","*^d-*","*^dh-*","*^jh-*","*^s-*","*^sh-*","*^t-*","*^th-*","*^z-*","*^zh-*" } QS prev_cvox==- { "*^ch-*","*^f-*","*^hh-*","*^k-*","*^p-*","*^s-*","*^sh-*","*^t-*","*^th-*" } QS prev_ctype==f { "*^dh-*","*^f-*","*^hh-*","*^s-*","*^sh-*","*^th-*","*^v-*","*^z-*","*^zh-*" } QS prev_cvox==+&&son==- { "*^b-*","*^d-*","*^dh-*","*^g-*","*^jh-*","*^v-*","*^z-*","*^zh-*" } QS prev_cont==+&&ccor==+ { "*^dh-*","*^l-*","*^r-*","*^s-*","*^sh-*","*^th-*","*^z-*","*^zh-*" } QS prev_cont==+&&cvox==+ { "*^dh-*","*^l-*","*^r-*","*^v-*","*^w-*","*^y-*","*^z-*","*^zh-*" } QS prev_ccor==+&&cvox==+ { "*^d-*","*^dh-*","*^jh-*","*^l-*","*^n-*","*^r-*","*^z-*","*^zh-*" } QS prev_son==+ { "*^l-*","*^m-*","*^n-*","*^ng-*","*^r-*","*^w-*","*^y-*" } QS prev_cont==-&&cvox==+ { "*^b-*","*^d-*","*^g-*","*^jh-*","*^m-*","*^n-*","*^ng-*" } QS prev_cplace==a { "*^d-*","*^l-*","*^n-*","*^r-*","*^s-*","*^t-*","*^z-*" } QS prev_ccor==+&&ctype==f { "*^dh-*","*^s-*","*^sh-*","*^th-*","*^z-*","*^zh-*" } QS prev_csib==+ { "*^ch-*","*^jh-*","*^s-*","*^sh-*","*^z-*","*^zh-*" } QS prev_vfront==3 { "*^aa-*","*^ao-*","*^ow-*","*^oy-*","*^uh-*","*^uw-*" } QS prev_vrnd==+ { "*^ao-*","*^ow-*","*^oy-*","*^uh-*","*^uw-*" } QS prev_vfront==1 { "*^ae-*","*^eh-*","*^ey-*","*^ih-*","*^iy-*" } QS prev_cont==+&&ccor==+&&cvox==+ { "*^dh-*","*^l-*","*^r-*","*^z-*","*^zh-*" } QS prev_ccor==+&&cvox==- { "*^ch-*","*^s-*","*^sh-*","*^t-*","*^th-*" } QS prev_cont==-&&cvox==- { "*^ch-*","*^k-*","*^p-*","*^t-*" } QS prev_son==-&&clab==+ { "*^b-*","*^f-*","*^p-*","*^v-*" } QS prev_vrnd==-&&vlng==s { "*^ae-*","*^ah-*","*^eh-*","*^ih-*" } QS prev_vlng==l { "*^aa-*","*^ao-*","*^iy-*","*^uw-*" } QS prev_cont==+&&son==+ { "*^l-*","*^r-*","*^w-*","*^y-*" } QS prev_ctype==r { "*^er-*","*^r-*","*^w-*","*^y-*" } QS prev_cvox==-&&ctype==s { "*^k-*","*^p-*","*^t-*" } QS prev_vrnd==-&&vlng==d { "*^aw-*","*^ay-*","*^ey-*" } QS prev_son==+&&cplace==a { "*^l-*","*^n-*","*^r-*" } QS prev_ctype==n { "*^m-*","*^n-*","*^ng-*" } QS prev_cont==-&&cplace==a { "*^d-*","*^n-*","*^t-*" } QS prev_ctype==r&&son==+ { "*^r-*","*^w-*","*^y-*" } QS prev_cvox==-&&csib==+ { "*^ch-*","*^s-*","*^sh-*" } QS prev_cont==+&&cvox==+&&cplace==a { "*^l-*","*^r-*","*^z-*" } QS prev_ccor==+&&cvox==-&&ctype==f { "*^s-*","*^sh-*","*^th-*" } QS prev_vheight==1&&vlng==s { "*^ih-*","*^uh-*" } QS prev_son==+&&clab==+ { "*^m-*","*^w-*" } QS prev_cvox==-&&clab==+ { "*^f-*","*^p-*" } QS prev_cvox==+&&son==-&&clab==+ { "*^b-*","*^v-*" } QS prev_ctype==s&&cplace==a { "*^d-*","*^t-*" } QS prev_cvox==-&&cplace==a { "*^s-*","*^t-*" } QS prev_cont==-&&cvox==+&&clab==+ { "*^b-*","*^m-*" } QS prev_cont==+&&son==+&&cplace==a { "*^l-*","*^r-*" } QS prev_vfront==1&&vheight==2 { "*^eh-*","*^ey-*" } QS prev_vheight==2&&vlng==s { "*^ah-*","*^eh-*" } QS prev_ctype==a { "*^ch-*","*^jh-*" } QS prev_cont==-&&cvox==+&&cplace==a { "*^d-*","*^n-*" } QS prev_cvox==+&&cplace==v { "*^g-*","*^ng-*" } QS prev_cont==+&&cvox==+&&cplace==p { "*^y-*","*^zh-*" } QS prev_name==ao { "*^ao-*" } QS prev_name==ax { "*^ax-*" } QS prev_name==dh { "*^dh-*" } QS prev_name==hh { "*^hh-*" } QS prev_name==l { "*^l-*" } QS prev_name==n { "*^n-*" } QS prev_name==pau { "*^pau-*" } QS prev_name==r { "*^r-*" } QS prev_name==sh { "*^sh-*" } QS prev_name==t { "*^t-*" } QS prev_name==x { "*^x-*" } QS prev_name==z { "*^z-*" } QS vc==- { "*-b+*","*-ch+*","*-d+*","*-dh+*","*-f+*","*-g+*","*-hh+*","*-jh+*","*-k+*","*-l+*","*-m+*","*-n+*","*-ng+*","*-p+*","*-r+*","*-s+*","*-sh+*","*-t+*","*-th+*","*-v+*","*-w+*","*-y+*","*-z+*","*-zh+*" } QS son==- { "*-b+*","*-ch+*","*-d+*","*-dh+*","*-f+*","*-g+*","*-hh+*","*-jh+*","*-k+*","*-p+*","*-s+*","*-sh+*","*-t+*","*-th+*","*-v+*","*-z+*","*-zh+*" } QS vc==+ { "*-aa+*","*-ae+*","*-ah+*","*-ao+*","*-aw+*","*-ax+*","*-ay+*","*-eh+*","*-er+*","*-ey+*","*-ih+*","*-iy+*","*-ow+*","*-oy+*","*-uh+*","*-uw+*" } QS cvox==+ { "*-b+*","*-d+*","*-dh+*","*-g+*","*-jh+*","*-l+*","*-m+*","*-n+*","*-ng+*","*-r+*","*-v+*","*-w+*","*-y+*","*-z+*","*-zh+*" } QS ccor==+ { "*-ch+*","*-d+*","*-dh+*","*-jh+*","*-l+*","*-n+*","*-r+*","*-s+*","*-sh+*","*-t+*","*-th+*","*-z+*","*-zh+*" } QS cont==+ { "*-dh+*","*-f+*","*-hh+*","*-l+*","*-r+*","*-s+*","*-sh+*","*-th+*","*-v+*","*-w+*","*-y+*","*-z+*","*-zh+*" } QS vrnd==- { "*-aa+*","*-ae+*","*-ah+*","*-aw+*","*-ax+*","*-ay+*","*-eh+*","*-er+*","*-ey+*","*-ih+*","*-iy+*" } QS cont==- { "*-b+*","*-ch+*","*-d+*","*-g+*","*-jh+*","*-k+*","*-m+*","*-n+*","*-ng+*","*-p+*","*-t+*" } QS ccor==+&&son==- { "*-ch+*","*-d+*","*-dh+*","*-jh+*","*-s+*","*-sh+*","*-t+*","*-th+*","*-z+*","*-zh+*" } QS cvox==- { "*-ch+*","*-f+*","*-hh+*","*-k+*","*-p+*","*-s+*","*-sh+*","*-t+*","*-th+*" } QS cont==+&&cvox==+ { "*-dh+*","*-l+*","*-r+*","*-v+*","*-w+*","*-y+*","*-z+*","*-zh+*" } QS cplace==a { "*-d+*","*-l+*","*-n+*","*-r+*","*-s+*","*-t+*","*-z+*" } QS vheight==2 { "*-ah+*","*-ax+*","*-eh+*","*-er+*","*-ey+*","*-ow+*","*-oy+*" } QS clab==+ { "*-b+*","*-f+*","*-m+*","*-p+*","*-v+*","*-w+*" } QS csib==+ { "*-ch+*","*-jh+*","*-s+*","*-sh+*","*-z+*","*-zh+*" } QS vfront==3 { "*-aa+*","*-ao+*","*-ow+*","*-oy+*","*-uh+*","*-uw+*" } QS ctype==s { "*-b+*","*-d+*","*-g+*","*-k+*","*-p+*","*-t+*" } QS vfront==1 { "*-ae+*","*-eh+*","*-ey+*","*-ih+*","*-iy+*" } QS vlng==d { "*-aw+*","*-ay+*","*-ey+*","*-ow+*","*-oy+*" } QS vlng==s { "*-ae+*","*-ah+*","*-eh+*","*-ih+*","*-uh+*" } QS cvox==-&&ctype==f { "*-f+*","*-hh+*","*-s+*","*-sh+*","*-th+*" } QS cplace==p { "*-ch+*","*-jh+*","*-sh+*","*-y+*","*-zh+*" } QS vheight==3 { "*-aa+*","*-ae+*","*-ao+*","*-aw+*","*-ay+*" } QS ctype==f&&csib==+ { "*-s+*","*-sh+*","*-z+*","*-zh+*" } QS vlng==l { "*-aa+*","*-ao+*","*-iy+*","*-uw+*" } QS cont==+&&son==+ { "*-l+*","*-r+*","*-w+*","*-y+*" } QS ctype==r { "*-er+*","*-r+*","*-w+*","*-y+*" } QS cvox==+&&clab==+ { "*-b+*","*-m+*","*-v+*","*-w+*" } QS cvox==+&&ctype==f { "*-dh+*","*-v+*","*-z+*","*-zh+*" } QS cplace==v { "*-g+*","*-k+*","*-ng+*" } QS son==+&&cplace==a { "*-l+*","*-n+*","*-r+*" } QS cvox==+&&csib==+ { "*-jh+*","*-z+*","*-zh+*" } QS cont==+&&son==+&&cplace==a { "*-l+*","*-r+*" } QS cont==-&&cvox==+&&cplace==a { "*-d+*","*-n+*" } QS cont==+&&cvox==+&&cplace==p { "*-y+*","*-zh+*" } QS vrnd==+&&vheight==1 { "*-uh+*","*-uw+*" } QS name==aa { "*-aa+*" } QS name==aw { "*-aw+*" } QS name==ax { "*-ax+*" } QS name==ay { "*-ay+*" } QS name==ch { "*-ch+*" } QS name==dh { "*-dh+*" } QS name==f { "*-f+*" } QS name==g { "*-g+*" } QS name==hh { "*-hh+*" } QS name==ih { "*-ih+*" } QS name==k { "*-k+*" } QS name==l { "*-l+*" } QS name==n { "*-n+*" } QS name==ow { "*-ow+*" } QS name==oy { "*-oy+*" } QS name==p { "*-p+*" } QS name==r { "*-r+*" } QS name==s { "*-s+*" } QS name==t { "*-t+*" } QS name==v { "*-v+*" } QS name==z { "*-z+*" } QS next_vc==- { "*+b=*","*+ch=*","*+d=*","*+dh=*","*+f=*","*+g=*","*+hh=*","*+jh=*","*+k=*","*+l=*","*+m=*","*+n=*","*+ng=*","*+p=*","*+r=*","*+s=*","*+sh=*","*+t=*","*+th=*","*+v=*","*+w=*","*+y=*","*+z=*","*+zh=*" } QS next_son==- { "*+b=*","*+ch=*","*+d=*","*+dh=*","*+f=*","*+g=*","*+hh=*","*+jh=*","*+k=*","*+p=*","*+s=*","*+sh=*","*+t=*","*+th=*","*+v=*","*+z=*","*+zh=*" } QS next_vc==+ { "*+aa=*","*+ae=*","*+ah=*","*+ao=*","*+aw=*","*+ax=*","*+ay=*","*+eh=*","*+er=*","*+ey=*","*+ih=*","*+iy=*","*+ow=*","*+oy=*","*+uh=*","*+uw=*" } QS next_cvox==+ { "*+b=*","*+d=*","*+dh=*","*+g=*","*+jh=*","*+l=*","*+m=*","*+n=*","*+ng=*","*+r=*","*+v=*","*+w=*","*+y=*","*+z=*","*+zh=*" } QS next_ccor==+ { "*+ch=*","*+d=*","*+dh=*","*+jh=*","*+l=*","*+n=*","*+r=*","*+s=*","*+sh=*","*+t=*","*+th=*","*+z=*","*+zh=*" } QS next_cont==+ { "*+dh=*","*+f=*","*+hh=*","*+l=*","*+r=*","*+s=*","*+sh=*","*+th=*","*+v=*","*+w=*","*+y=*","*+z=*","*+zh=*" } QS next_vrnd==- { "*+aa=*","*+ae=*","*+ah=*","*+aw=*","*+ax=*","*+ay=*","*+eh=*","*+er=*","*+ey=*","*+ih=*","*+iy=*" } QS next_cont==- { "*+b=*","*+ch=*","*+d=*","*+g=*","*+jh=*","*+k=*","*+m=*","*+n=*","*+ng=*","*+p=*","*+t=*" } QS next_ccor==+&&son==- { "*+ch=*","*+d=*","*+dh=*","*+jh=*","*+s=*","*+sh=*","*+t=*","*+th=*","*+z=*","*+zh=*" } QS next_cvox==- { "*+ch=*","*+f=*","*+hh=*","*+k=*","*+p=*","*+s=*","*+sh=*","*+t=*","*+th=*" } QS next_ctype==f { "*+dh=*","*+f=*","*+hh=*","*+s=*","*+sh=*","*+th=*","*+v=*","*+z=*","*+zh=*" } QS next_cont==+&&cvox==+ { "*+dh=*","*+l=*","*+r=*","*+v=*","*+w=*","*+y=*","*+z=*","*+zh=*" } QS next_ccor==+&&cvox==+ { "*+d=*","*+dh=*","*+jh=*","*+l=*","*+n=*","*+r=*","*+z=*","*+zh=*" } QS next_cont==-&&son==- { "*+b=*","*+ch=*","*+d=*","*+g=*","*+jh=*","*+k=*","*+p=*","*+t=*" } QS next_son==+ { "*+l=*","*+m=*","*+n=*","*+ng=*","*+r=*","*+w=*","*+y=*" } QS next_cont==-&&cvox==+ { "*+b=*","*+d=*","*+g=*","*+jh=*","*+m=*","*+n=*","*+ng=*" } QS next_vheight==2 { "*+ah=*","*+ax=*","*+eh=*","*+er=*","*+ey=*","*+ow=*","*+oy=*" } QS next_clab==+ { "*+b=*","*+f=*","*+m=*","*+p=*","*+v=*","*+w=*" } QS next_ctype==s { "*+b=*","*+d=*","*+g=*","*+k=*","*+p=*","*+t=*" } QS next_vfront==1 { "*+ae=*","*+eh=*","*+ey=*","*+ih=*","*+iy=*" } QS next_vfront==2 { "*+ah=*","*+aw=*","*+ax=*","*+ay=*","*+er=*" } QS next_ccor==+&&cvox==+&&son==- { "*+d=*","*+dh=*","*+jh=*","*+z=*","*+zh=*" } QS next_vheight==1 { "*+ih=*","*+iy=*","*+uh=*","*+uw=*" } QS next_cont==-&&ccor==+&&son==- { "*+ch=*","*+d=*","*+jh=*","*+t=*" } QS next_ctype==f&&csib==+ { "*+s=*","*+sh=*","*+z=*","*+zh=*" } QS next_cont==+&&son==+ { "*+l=*","*+r=*","*+w=*","*+y=*" } QS next_ctype==r { "*+er=*","*+r=*","*+w=*","*+y=*" } QS next_cvox==+&&clab==+ { "*+b=*","*+m=*","*+v=*","*+w=*" } QS next_cont==+&&cplace==a { "*+l=*","*+r=*","*+s=*","*+z=*" } QS next_cvox==-&&ctype==s { "*+k=*","*+p=*","*+t=*" } QS next_son==+&&cplace==a { "*+l=*","*+n=*","*+r=*" } QS next_ctype==n { "*+m=*","*+n=*","*+ng=*" } QS next_vfront==1&&vlng==s { "*+ae=*","*+eh=*","*+ih=*" } QS next_ctype==r&&son==+ { "*+r=*","*+w=*","*+y=*" } QS next_cvox==+&&ctype==s { "*+b=*","*+d=*","*+g=*" } QS next_cont==+&&cvox==+&&cplace==a { "*+l=*","*+r=*","*+z=*" } QS next_vfront==3&&vlng==l { "*+aa=*","*+ao=*","*+uw=*" } QS next_cplace==d { "*+dh=*","*+th=*" } QS next_son==+&&clab==+ { "*+m=*","*+w=*" } QS next_vrnd==-&&vheight==1 { "*+ih=*","*+iy=*" } QS next_ctype==s&&cplace==a { "*+d=*","*+t=*" } QS next_cvox==-&&cplace==a { "*+s=*","*+t=*" } QS next_vrnd==-&&vlng==l { "*+aa=*","*+iy=*" } QS next_cont==+&&son==+&&cplace==a { "*+l=*","*+r=*" } QS next_cvox==+&&cplace==v { "*+g=*","*+ng=*" } QS next_cont==-&&ccor==+&&cvox==- { "*+ch=*","*+t=*" } QS next_cvox==+&&son==-&&cplace==a { "*+d=*","*+z=*" } QS next_son==-&&cplace==l { "*+b=*","*+p=*" } QS next_vrnd==+&&vlng==l { "*+ao=*","*+uw=*" } QS next_csib==+&&cplace==a { "*+s=*","*+z=*" } QS next_name==ax { "*+ax=*" } QS next_name==dh { "*+dh=*" } QS next_name==hh { "*+hh=*" } QS next_name==iy { "*+iy=*" } QS next_name==l { "*+l=*" } QS next_name==n { "*+n=*" } QS next_name==ng { "*+ng=*" } QS next_name==p { "*+p=*" } QS next_name==r { "*+r=*" } QS next_name==s { "*+s=*" } QS next_name==t { "*+t=*" } QS next_name==w { "*+w=*" } QS next_name==y { "*+y=*" } QS next_next_son==- { "*=b@*","*=ch@*","*=d@*","*=dh@*","*=f@*","*=g@*","*=hh@*","*=jh@*","*=k@*","*=p@*","*=s@*","*=sh@*","*=t@*","*=th@*","*=v@*","*=z@*","*=zh@*" } QS next_next_ccor==+&&son==- { "*=ch@*","*=d@*","*=dh@*","*=jh@*","*=s@*","*=sh@*","*=t@*","*=th@*","*=z@*","*=zh@*" } QS next_next_cont==-&&son==- { "*=b@*","*=ch@*","*=d@*","*=g@*","*=jh@*","*=k@*","*=p@*","*=t@*" } QS next_next_cont==-&&cvox==+ { "*=b@*","*=d@*","*=g@*","*=jh@*","*=m@*","*=n@*","*=ng@*" } QS next_next_clab==+ { "*=b@*","*=f@*","*=m@*","*=p@*","*=v@*","*=w@*" } QS next_next_cont==-&&ccor==+ { "*=ch@*","*=d@*","*=jh@*","*=n@*","*=t@*" } QS next_next_vheight==3 { "*=aa@*","*=ae@*","*=ao@*","*=aw@*","*=ay@*" } QS next_next_vlng==l { "*=aa@*","*=ao@*","*=iy@*","*=uw@*" } QS next_next_ctype==r { "*=er@*","*=r@*","*=w@*","*=y@*" } QS next_next_son==-&&cplace==a { "*=d@*","*=s@*","*=t@*","*=z@*" } QS next_next_cvox==+&&ctype==f { "*=dh@*","*=v@*","*=z@*","*=zh@*" } QS next_next_cont==+&&cplace==a { "*=l@*","*=r@*","*=s@*","*=z@*" } QS next_next_vlng==a { "*=ax@*","*=er@*" } QS next_next_vheight==1&&vlng==l { "*=iy@*","*=uw@*" } QS next_next_vrnd==-&&vlng==l { "*=aa@*","*=iy@*" } QS next_next_name==er { "*=er@*" } QS next_next_name==n { "*=n@*" } QS next_next_name==x { "*=x@*" } QS pos_in_syl_fw==1 { "*@1_*" } QS pos_in_syl_fw==4 { "*@4_*" } QS pos_in_syl_fw<=1 { "*@x_*","*@1_*" } QS pos_in_syl_bw==1 { "*_1/A:*" } QS pos_in_syl_bw==2 { "*_2/A:*" } QS pos_in_syl_bw==3 { "*_3/A:*" } QS prev_syl_stress==1 { "*/A:1_*" } QS prev_syl_accented==0 { "*_0_*" } QS prev_syl_length==0 { "*_0/B:*" } QS prev_syl_length==3 { "*_3/B:*" } QS prev_syl_length<=0 { "*_0/B:*" } QS syl_stress==0 { "*/B:0-*" } QS syl_stress==1 { "*/B:1-*" } QS syl_length==2 { "*-2@*" } QS syl_length<=2 { "*-x@*","*-1@*","*-2@*" } QS syl_length<=3 { "*-x@*","*-1@*","*-2@*","*-3@*" } QS syl_pos_in_word_fw==1 { "*@1-*" } QS syl_pos_in_word_fw<=1 { "*@x-*","*@1-*" } QS syl_pos_in_word_bw==1 { "*-1&*" } QS syl_pos_in_word_bw==2 { "*-2&*" } QS syl_pos_in_word_bw<=2 { "*-x&*","*-1&*","*-2&*" } QS syl_pos_in_phrase_fw<=1 { "*&x-*","*&1-*" } QS syl_pos_in_phrase_bw==5 { "*-5#*" } QS syl_pos_in_phrase_bw<=1 { "*-x#*","*-1#*" } QS syl_pos_in_phrase_bw<=4 { "*-x#*","*-1#*","*-2#*","*-3#*","*-4#*" } QS syl_pos_in_phrase_bw<=9 { "*-x#*","*-1#*","*-2#*","*-3#*","*-4#*","*-5#*","*-6#*","*-7#*","*-8#*","*-9#*" } QS num_stressed_syls_in_phrase_before_this_syl<=5 { "*#x-*","*#1-*","*#2-*","*#3-*","*#4-*","*#5-*" } QS num_stressed_syls_in_phrase_after_this_syl<=8 { "*-x$*","*-1$*","*-2$*","*-3$*","*-4$*","*-5$*","*-6$*","*-7$*","*-8$*" } QS num_accented_syls_in_phrase_before_this_syl<=2 { "*$x-*","*$1-*","*$2-*" } QS dist_to_prev_stressed_syl_in_phrase==1 { "*!1-*" } QS dist_to_prev_stressed_syl_in_phrase==2 { "*!2-*" } QS dist_to_next_stressed_syl_in_phrase==1 { "*-1;*" } QS dist_to_prev_accented_syl_in_phrase<=3 { "*;x-*","*;0-*","*;1-*","*;2-*","*;3-*" } QS dist_to_next_accented_syl_in_phrase<=2 { "*-x|*","*-0|*","*-1|*","*-2|*" } QS syl_vowel_vfront==3 { "*|aa/C:*","*|ao/C:*","*|ow/C:*","*|oy/C:*","*|uh/C:*","*|uw/C:*" } QS syl_vowel_vheight==1 { "*|ih/C:*","*|iy/C:*","*|uh/C:*","*|uw/C:*" } QS syl_vowel_vrnd==-&&vlng==s { "*|ae/C:*","*|ah/C:*","*|eh/C:*","*|ih/C:*" } QS syl_vowel_vlng==l { "*|aa/C:*","*|ao/C:*","*|iy/C:*","*|uw/C:*" } QS syl_vowel_vfront==1&&vlng==s { "*|ae/C:*","*|eh/C:*","*|ih/C:*" } QS syl_vowel_vheight==1&&vlng==s { "*|ih/C:*","*|uh/C:*" } QS syl_vowel_vlng==a { "*|ax/C:*","*|er/C:*" } QS syl_vowel_vheight==1&&vlng==l { "*|iy/C:*","*|uw/C:*" } QS syl_vowel_vrnd==-&&vlng==l { "*|aa/C:*","*|iy/C:*" } QS syl_vowel_vheight==3&&vlng==d { "*|aw/C:*","*|ay/C:*" } QS syl_vowel==aa { "*|aa/C:*" } QS syl_vowel==ae { "*|ae/C:*" } QS syl_vowel==ao { "*|ao/C:*" } QS syl_vowel==eh { "*|eh/C:*" } QS syl_vowel==er { "*|er/C:*" } QS syl_vowel==ih { "*|ih/C:*" } QS syl_vowel==iy { "*|iy/C:*" } QS syl_vowel==ow { "*|ow/C:*" } QS syl_vowel==oy { "*|oy/C:*" } QS syl_vowel==uw { "*|uw/C:*" } QS next_syl_accented==1 { "*+1+*" } QS next_syl_length<=2 { "*+0/D:*","*+1/D:*","*+2/D:*" } QS prev_word_gpos==content { "*/D:content_*" } QS num_syls_in_prev_word==2 { "*_2/E:*" } QS num_syls_in_prev_word<=0 { "*_0/E:*" } QS word_gpos==aux { "*/E:aux+*" } QS word_gpos==cc { "*/E:cc+*" } QS word_gpos==content { "*/E:content+*" } QS word_gpos==det { "*/E:det+*" } QS word_gpos==in { "*/E:in+*" } QS word_gpos==pps { "*/E:pps+*" } QS word_gpos==wp { "*/E:wp+*" } QS num_syls_in_word<=2 { "*+x@*","*+1@*","*+2@*" } QS word_pos_in_phrase_fw==1 { "*@1+*" } QS word_pos_in_phrase_fw<=1 { "*@x+*","*@1+*" } QS word_pos_in_phrase_fw<=2 { "*@x+*","*@1+*","*@2+*" } QS word_pos_in_phrase_fw<=3 { "*@x+*","*@1+*","*@2+*","*@3+*" } QS num_content_words_in_phrase_before_this_word==2 { "*&2+*" } QS num_content_words_in_phrase_before_this_word==5 { "*&5+*" } QS dist_to_prev_content_word_in_phrase<=0 { "*#x+*","*#0+*" } QS dist_to_prev_content_word_in_phrase<=2 { "*#x+*","*#0+*","*#1+*","*#2+*" } QS dist_to_next_content_word_in_phrase==1 { "*+1/F:*" } QS next_word_gpos==0 { "*/F:0_*" } QS next_word_gpos==det { "*/F:det_*" } QS next_word_gpos==in { "*/F:in_*" } QS next_word_gpos==wp { "*/F:wp_*" } QS num_syls_in_next_word==1 { "*_1/G:*" } QS num_syls_in_next_word<=3 { "*_0/G:*","*_1/G:*","*_2/G:*","*_3/G:*" } QS num_syls_in_prev_phrase==0 { "*/G:0_*" } QS num_words_in_prev_phrase==1 { "*_1/H:*" } QS num_words_in_prev_phrase==2 { "*_2/H:*" } QS num_words_in_prev_phrase<=1 { "*_0/H:*","*_1/H:*" } QS num_syls_in_phrase==2 { "*/H:2=*" } QS num_syls_in_phrase<=8 { "*/H:x=*","*/H:1=*","*/H:2=*","*/H:3=*","*/H:4=*","*/H:5=*","*/H:6=*","*/H:7=*","*/H:8=*" } QS num_syls_in_phrase<=11 { "*/H:x=*","*/H:1=*","*/H:2=*","*/H:3=*","*/H:4=*","*/H:5=*","*/H:6=*","*/H:7=*","*/H:8=*","*/H:9=*","*/H:10=*","*/H:11=*" } QS num_syls_in_phrase<=13 { "*/H:x=*","*/H:1=*","*/H:2=*","*/H:3=*","*/H:4=*","*/H:5=*","*/H:6=*","*/H:7=*","*/H:8=*","*/H:9=*","*/H:10=*","*/H:11=*","*/H:12=*","*/H:13=*" } QS num_syls_in_phrase<=17 { "*/H:x=*","*/H:1=*","*/H:2=*","*/H:3=*","*/H:4=*","*/H:5=*","*/H:6=*","*/H:7=*","*/H:8=*","*/H:9=*","*/H:10=*","*/H:11=*","*/H:12=*","*/H:13=*","*/H:14=*","*/H:15=*","*/H:16=*","*/H:17=*" } QS num_words_in_phrase<=4 { "*=x^*","*=1^*","*=2^*","*=3^*","*=4^*" } QS num_words_in_phrase<=11 { "*=x^*","*=1^*","*=2^*","*=3^*","*=4^*","*=5^*","*=6^*","*=7^*","*=8^*","*=9^*","*=10^*","*=11^*" } QS phrase_pos_in_utt_fw<=2 { "*^x=*","*^1=*","*^2=*" } QS phrase_end_tone==NONE { "*|NONE/I:*" } QS num_syls_in_next_phrase==4 { "*/I:4=*" } QS num_syls_in_next_phrase<=0 { "*/I:0=*" } QS num_syls_in_next_phrase<=2 { "*/I:0=*","*/I:1=*","*/I:2=*" } QS num_syls_in_next_phrase<=4 { "*/I:0=*","*/I:1=*","*/I:2=*","*/I:3=*","*/I:4=*" } QS num_words_in_next_phrase<=0 { "*=0/J:*" } QS num_words_in_next_phrase<=3 { "*=0/J:*","*=1/J:*","*=2/J:*","*=3/J:*" } QS num_words_in_next_phrase<=4 { "*=0/J:*","*=1/J:*","*=2/J:*","*=3/J:*","*=4/J:*" } QS num_words_in_next_phrase<=5 { "*=0/J:*","*=1/J:*","*=2/J:*","*=3/J:*","*=4/J:*","*=5/J:*" } QS num_syls_in_utt==8 { "*/J:8+*" } QS num_syls_in_utt==16 { "*/J:16+*" } QS num_syls_in_utt<=8 { "*/J:1+*","*/J:2+*","*/J:3+*","*/J:4+*","*/J:5+*","*/J:6+*","*/J:7+*","*/J:8+*" } QS num_syls_in_utt<=10 { "*/J:1+*","*/J:2+*","*/J:3+*","*/J:4+*","*/J:5+*","*/J:6+*","*/J:7+*","*/J:8+*","*/J:9+*","*/J:10+*" } QS num_syls_in_utt<=14 { "*/J:1+*","*/J:2+*","*/J:3+*","*/J:4+*","*/J:5+*","*/J:6+*","*/J:7+*","*/J:8+*","*/J:9+*","*/J:10+*","*/J:11+*","*/J:12+*","*/J:13+*","*/J:14+*" } QS num_words_in_utt==7 { "*+7-*" } QS num_words_in_utt==12 { "*+12-*" } QS num_words_in_utt<=5 { "*+1-*","*+2-*","*+3-*","*+4-*","*+5-*" } QS pos_in_word_fw==1 { "*/K:1_*" } QS pos_in_word_fw==2 { "*/K:2_*" } QS pos_in_word_fw<=1 { "*/K:x_*","*/K:1_*" } QS pos_in_word_fw<=2 { "*/K:x_*","*/K:1_*","*/K:2_*" } QS pos_in_word_fw<=3 { "*/K:x_*","*/K:1_*","*/K:2_*","*/K:3_*" } QS pos_in_word_bw==1 { "*_1" } QS pos_in_word_bw==3 { "*_3" } QS pos_in_word_bw==5 { "*_5" } QS pos_in_word_bw<=1 { "*_x","*_1" } QS pos_in_word_bw<=3 { "*_x","*_1","*_2","*_3" } QS pos_in_word_bw<=4 { "*_x","*_1","*_2","*_3","*_4" } QS pos_in_word_bw<=5 { "*_x","*_1","*_2","*_3","*_4","*_5" } {*}[2] { 0 syl_pos_in_phrase_bw<=1 -1 -3 -1 cont==-&&cvox==+&&cplace==a -2 -15 -2 name==ax -4 -18 -3 prev_name==x -9 -51 -4 ctype==s -5 -16 -5 vlng==d -6 -38 -6 pos_in_syl_fw==1 -8 -7 -7 name==dh -13 -42 -8 name==ih -10 -36 -9 vc==- -12 -11 -10 vheight==3 -28 -20 -11 ctype==s -23 -37 -12 name==ax -21 -81 -13 cvox==- -19 -14 -14 name==hh -30 -53 -15 name==n -26 -91 -16 pos_in_syl_fw<=1 -27 -17 -17 cvox==- -33 -25 -18 prev_cont==+&&cvox==+ -45 -83 -19 cvox==+&&clab==+ -34 -35 -20 word_gpos==aux -29 -41 -21 phrase_end_tone==NONE -22 -24 -22 prev_ccor==+&&ctype==f -44 -59 -23 cvox==-&&ctype==f -32 -61 -24 vlng==s -63 -137 -25 name==t -105 -70 -26 prev_name==n -73 -66 -27 prev_son==- -46 -48 -28 cont==+&&cvox==+ -31 -39 -29 next_cont==+&&son==+&&cplace==a -50 -111 -30 prev_son==- -64 -96 -31 ctype==r -43 -234 -32 pos_in_word_bw==1 -88 -62 -33 syl_pos_in_phrase_fw<=1 -187 -228 -34 vlng==s -94 -67 -35 cont==+&&son==+ -128 -112 -36 prev_cont==+&&son==+ -97 -189 -37 name==t -100 -54 -38 pos_in_word_fw==1 -78 -194 -39 prev_cvox==- -40 -80 -40 cvox==+&&ctype==f -69 -49 -41 prev_son==- -173 -222 -42 prev_vc==+ -65 -193 -43 prev_cont==-&&cvox==+ -47 -166 -44 num_words_in_next_phrase<=0 -135 -52 -45 pos_in_word_fw==1 -86 -237 -46 name==t -172 -90 -47 vrnd==+&&vheight==1 -56 -77 -48 name==t "dur_s2_1" -200 -49 next_cvox==- -115 -85 -50 syl_vowel==aa -76 -298 -51 next_vc==+ -214 -152 -52 prev_cvox==-&&cplace==a -71 -162 -53 syl_vowel_vheight==1&&vlng==l -74 -79 -54 pos_in_syl_fw<=1 -55 -252 -55 prev_cvox==- -230 -460 -56 clab==+ -57 -258 -57 vheight==2 -58 -60 -58 prev_name==hh -102 -293 -59 num_words_in_next_phrase<=0 -279 -95 -60 prev_cont==+&&son==+&&cplace==a -82 -84 -61 prev_son==- -98 -147 -62 cont==+&&son==+&&cplace==a -93 -568 -63 syl_vowel_vlng==l -169 -109 -64 prev_syl_length<=0 -72 -206 -65 prev_cont==-&&cvox==+&&cplace==a -132 -516 -66 prev_prev_vrnd==-&&vheight==3 -318 -89 -67 syl_vowel_vheight==1&&vlng==s -68 -110 -68 word_gpos==content -140 -259 -69 ctype==r -163 -117 -70 syl_stress==0 -123 -144 -71 prev_cvox==-&&clab==+ -180 -465 -72 next_son==+ -106 "dur_s2_2" -73 pos_in_word_fw==1 -129 -127 -74 prev_name==pau -75 -266 -75 next_vrnd==-&&vheight==1 -372 -317 -76 next_ctype==n -148 -141 -77 word_gpos==content -122 -167 -78 prev_cont==+&&ccor==+&&cvox==+ -142 -146 -79 num_syls_in_prev_word<=0 -219 "dur_s2_3" -80 next_vrnd==- -301 -159 -81 next_son==+ -467 -327 -82 next_name==r -226 "dur_s2_4" -83 next_son==+ -248 -312 -84 prev_prev_vlng==l -118 "dur_s2_5" -85 ccor==+ "dur_s2_6" -120 -86 syl_pos_in_word_bw==1 -360 -87 -87 next_son==+&&cplace==a -423 -131 -88 cont==+&&son==+ -121 -92 -89 next_cvox==- -321 -437 -90 next_ccor==+&&son==- -134 -633 -91 next_ctype==s&&cplace==a -113 -305 -92 prev_son==- -398 -525 -93 cplace==v -136 "dur_s2_7" -94 vc==+ -116 -124 -95 prev_cvox==-&&cplace==a -196 -571 -96 name==f -157 -304 -97 next_name==ng -108 -204 -98 name==hh -99 -256 -99 next_next_name==x -154 -401 -100 cvox==+ -179 -101 -101 pos_in_word_bw<=1 -217 -195 -102 cont==- -103 -277 -103 prev_vc==- -104 -211 -104 next_cvox==-&&cplace==a "dur_s2_9" "dur_s2_8" -105 next_ccor==+ -233 -197 -106 name==ch -107 "dur_s2_10" -107 prev_vrnd==- -390 -278 -108 prev_name==hh -186 -349 -109 next_ctype==r -183 -410 -110 pos_in_word_fw==1 "dur_s2_11" -174 -111 prev_cvox==-&&clab==+ -188 -587 -112 syl_pos_in_phrase_fw<=1 -133 -441 -113 next_vc==+ -150 -114 -114 pos_in_word_fw==1 -647 -350 -115 next_name==dh -165 -392 -116 prev_vc==+ -224 -119 -117 prev_vlng==l -253 -184 -118 word_gpos==content "dur_s2_12" -325 -119 cvox==+&&csib==+ -238 -336 -120 csib==+ "dur_s2_13" -319 -121 name==dh -125 -294 -122 next_cont==- -249 -338 -123 prev_cont==-&&cplace==a -210 -376 -124 syl_stress==1 -330 -130 -125 cvox==+&&clab==+ -126 "dur_s2_14" -126 cplace==a -316 -156 -127 prev_name==pau -314 "dur_s2_15" -128 name==v -257 -199 -129 next_cont==+&&cplace==a -145 -504 -130 word_gpos==aux -164 -299 -131 next_name==l -261 -356 -132 prev_son==- -326 -216 -133 prev_cvox==- -139 -177 -134 prev_prev_vfront==1&&vheight==2 -207 "dur_s2_16" -135 next_vc==- -182 -254 -136 csib==+ -220 -225 -137 syl_vowel==ih -151 -138 -138 pos_in_word_fw==1 -161 -492 -139 prev_syl_length==3 -383 -255 -140 dist_to_prev_content_word_in_phrase<=0 -153 -176 -141 syl_vowel==ae -292 -191 -142 name==oy -143 -609 -143 syl_vowel_vheight==3&&vlng==d -198 -215 -144 prev_son==- -149 "dur_s2_17" -145 next_ccor==+ -171 -598 -146 name==ow -231 -155 -147 name==hh -359 -574 -148 prev_cont==+&&son==+&&cplace==a -269 -341 -149 pos_in_word_fw==1 -291 "dur_s2_18" -150 next_cplace==d -168 "dur_s2_19" -151 next_cont==+&&son==+ -181 -377 -152 next_vheight==1 -438 -389 -153 next_cvox==+&&clab==+ -232 -160 -154 next_vc==+ -208 -628 -155 prev_name==dh "dur_s2_21" "dur_s2_20" -156 next_cont==-&&ccor==+&&cvox==- -190 "dur_s2_22" -157 next_son==+ -158 "dur_s2_23" -158 prev_cont==+&&cvox==+ -241 -284 -159 word_gpos==content "dur_s2_24" -178 -160 prev_son==- -409 -391 -161 next_name==ng -308 "dur_s2_25" -162 prev_prev_cvox==-&&ctype==f -346 "dur_s2_26" -163 next_son==- -322 -250 -164 vrnd==- -306 -418 -165 ccor==+&&son==- -271 -236 -166 son==- -175 "dur_s2_27" -167 prev_ctype==r -192 -205 -168 next_name==l -311 -429 -169 name==ay -170 -276 -170 pos_in_word_bw<=1 -329 -280 -171 prev_vc==- -223 -613 -172 name==k -513 -209 -173 next_word_gpos==in "dur_s2_29" "dur_s2_28" -174 word_pos_in_phrase_fw<=1 -309 -527 -175 word_gpos==cc -267 -498 -176 pos_in_syl_bw==3 "dur_s2_30" -243 -177 prev_name==t -524 -553 -178 name==r -552 -221 -179 pos_in_syl_fw==1 -273 -547 -180 prev_ctype==n -264 "dur_s2_31" -181 syl_vowel_vfront==1&&vlng==s -452 -282 -182 next_vfront==1&&vlng==s -419 -339 -183 word_gpos==aux -246 "dur_s2_32" -184 next_son==- "dur_s2_33" -185 -185 word_gpos==content -382 -285 -186 next_name==r -262 "dur_s2_34" -187 prev_csib==+ -203 -497 -188 prev_cont==+&&cvox==+&&cplace==p -251 "dur_s2_35" -189 word_gpos==content -387 -202 -190 next_son==- -501 -343 -191 word_gpos==content "dur_s2_37" "dur_s2_36" -192 syl_vowel==uw -388 -365 -193 syl_vowel==er -536 "dur_s2_38" -194 num_syls_in_prev_word<=0 -337 "dur_s2_39" -195 prev_name==ax -395 "dur_s2_40" -196 prev_name==z "dur_s2_41" -584 -197 clab==+ "dur_s2_42" -462 -198 pos_in_word_bw==1 -239 -469 -199 prev_vrnd==- -272 -470 -200 next_son==- -335 -201 -201 num_words_in_prev_phrase==1 "dur_s2_44" "dur_s2_43" -202 next_cvox==+&&cplace==v -240 "dur_s2_45" -203 syl_stress==1 -320 -402 -204 syl_stress==0 "dur_s2_46" -619 -205 next_clab==+ -244 -475 -206 csib==+ "dur_s2_48" "dur_s2_47" -207 next_next_son==-&&cplace==a -434 "dur_s2_49" -208 next_son==- "dur_s2_51" "dur_s2_50" -209 next_son==+ -413 "dur_s2_52" -210 prev_ctype==f -340 "dur_s2_53" -211 prev_name==r -212 -213 -212 name==s -218 -533 -213 syl_stress==1 -461 "dur_s2_54" -214 next_ctype==f -286 -290 -215 next_vrnd==- -302 "dur_s2_55" -216 prev_cvox==+&&son==-&&clab==+ "dur_s2_56" -654 -217 prev_name==pau -281 "dur_s2_57" -218 next_vrnd==-&&vlng==l -427 "dur_s2_58" -219 dist_to_prev_stressed_syl_in_phrase==1 -576 -357 -220 son==- -520 -509 -221 prev_son==-&&clab==+ -447 -468 -222 num_syls_in_next_phrase==4 "dur_s2_60" "dur_s2_59" -223 next_ctype==s -425 "dur_s2_61" -224 name==l -562 -229 -225 prev_son==- -313 "dur_s2_62" -226 word_gpos==wp -227 -643 -227 next_son==- -369 -471 -228 clab==+ "dur_s2_64" "dur_s2_63" -229 next_name==iy -542 -345 -230 num_syls_in_next_word==1 -412 "dur_s2_65" -231 next_cvox==-&&ctype==s -393 -245 -232 next_name==n -611 -508 -233 syl_pos_in_phrase_fw<=1 -260 "dur_s2_66" -234 next_vc==+ -235 -606 -235 syl_stress==1 -315 -566 -236 prev_ccor==+&&son==- -242 "dur_s2_67" -237 prev_cplace==a -328 -495 -238 prev_prev_name==f -287 "dur_s2_68" -239 prev_cvox==-&&ctype==s -478 -380 -240 num_words_in_prev_phrase==2 -283 "dur_s2_69" -241 ctype==f&&csib==+ "dur_s2_71" "dur_s2_70" -242 name==z -494 -554 -243 num_words_in_prev_phrase<=1 "dur_s2_73" "dur_s2_72" -244 vlng==l -640 -247 -245 name==ay "dur_s2_75" "dur_s2_74" -246 name==aa -303 "dur_s2_76" -247 next_cont==- -367 "dur_s2_77" -248 prev_cplace==a "dur_s2_78" -421 -249 next_ctype==f -558 -405 -250 next_ctype==f&&csib==+ -531 "dur_s2_79" -251 prev_son==+&&clab==+ -347 -507 -252 syl_stress==1 -275 "dur_s2_80" -253 prev_cont==-&&cvox==+ -263 -378 -254 next_cvox==+&&ctype==s -295 "dur_s2_81" -255 prev_prev_vrnd==- "dur_s2_83" "dur_s2_82" -256 next_next_cont==-&&cvox==+ -583 "dur_s2_84" -257 prev_cont==-&&cplace==a -463 "dur_s2_85" -258 son==- -307 -265 -259 syl_stress==1 -416 -433 -260 syl_stress==0 -577 -368 -261 num_syls_in_next_word<=3 "dur_s2_87" "dur_s2_86" -262 prev_cvox==+&&son==-&&clab==+ -394 -569 -263 next_son==+&&clab==+ -614 -596 -264 prev_son==- "dur_s2_88" -274 -265 next_son==- "dur_s2_90" "dur_s2_89" -266 next_vrnd==-&&vheight==1 "dur_s2_92" "dur_s2_91" -267 vlng==l -268 -453 -268 next_name==n "dur_s2_93" -624 -269 prev_name==dh -354 -270 -270 prev_word_gpos==content "dur_s2_94" -600 -271 next_son==+ "dur_s2_96" "dur_s2_95" -272 syl_vowel_vlng==a "dur_s2_98" "dur_s2_97" -273 next_next_name==x -543 "dur_s2_99" -274 prev_cont==-&&cvox==+ "dur_s2_100" -457 -275 prev_prev_vc==+ "dur_s2_102" "dur_s2_101" -276 prev_name==l -473 "dur_s2_103" -277 name==ch -404 "dur_s2_104" -278 next_vc==+ "dur_s2_105" -300 -279 prev_word_gpos==content "dur_s2_106" -342 -280 syl_stress==0 "dur_s2_108" "dur_s2_107" -281 syl_stress==1 -440 -472 -282 next_cvox==+ -397 -540 -283 next_ccor==+&&cvox==+ -358 "dur_s2_109" -284 prev_cplace==a "dur_s2_110" -491 -285 prev_name==ao "dur_s2_112" "dur_s2_111" -286 next_son==-&&cplace==l -324 -502 -287 name==l -288 -289 -288 prev_vheight==2&&vlng==s -431 "dur_s2_113" -289 next_vc==- -506 "dur_s2_114" -290 next_next_vheight==1&&vlng==l -456 -489 -291 prev_name==l -351 "dur_s2_115" -292 prev_son==- "dur_s2_117" "dur_s2_116" -293 prev_syl_length==0 -589 "dur_s2_118" -294 prev_cont==-&&cvox==+ "dur_s2_120" "dur_s2_119" -295 prev_cvox==-&&ctype==s -503 -296 -296 prev_prev_vfront==2 -297 "dur_s2_121" -297 next_word_gpos==det -344 "dur_s2_122" -298 prev_cont==+&&cvox==+&&cplace==a -557 "dur_s2_123" -299 num_syls_in_prev_phrase==0 "dur_s2_125" "dur_s2_124" -300 ccor==+ "dur_s2_126" -483 -301 syl_pos_in_word_bw<=2 "dur_s2_127" -400 -302 next_name==l -374 "dur_s2_128" -303 prev_cont==- -355 "dur_s2_129" -304 prev_cont==-&&cplace==a "dur_s2_131" "dur_s2_130" -305 pos_in_syl_bw==2 "dur_s2_132" -379 -306 word_gpos==det -439 "dur_s2_133" -307 next_name==p -399 "dur_s2_134" -308 next_ccor==+&&cvox==+&&son==- -477 "dur_s2_135" -309 next_cont==-&&son==- -323 -310 -310 syl_pos_in_phrase_bw==5 "dur_s2_137" "dur_s2_136" -311 next_name==hh -517 "dur_s2_138" -312 next_cont==+ "dur_s2_140" "dur_s2_139" -313 num_syls_in_next_phrase<=0 "dur_s2_141" -537 -314 next_ctype==r&&son==+ -455 "dur_s2_142" -315 next_cont==+ "dur_s2_143" -484 -316 prev_son==- -604 "dur_s2_144" -317 prev_son==+ -430 -570 -318 pos_in_word_fw<=2 -381 "dur_s2_145" -319 next_name==hh -385 -331 -320 prev_cvox==+&&cplace==v -653 "dur_s2_146" -321 pos_in_word_fw<=3 "dur_s2_148" "dur_s2_147" -322 next_name==r -334 "dur_s2_149" -323 prev_vfront==1 -371 "dur_s2_150" -324 next_word_gpos==wp -560 "dur_s2_151" -325 dist_to_next_stressed_syl_in_phrase==1 "dur_s2_152" -450 -326 prev_syl_stress==1 -428 "dur_s2_153" -327 next_cont==+ "dur_s2_154" -649 -328 prev_vrnd==+ -549 "dur_s2_155" -329 pos_in_syl_fw==1 -332 "dur_s2_156" -330 syl_pos_in_word_fw<=1 -515 -364 -331 pos_in_syl_fw==4 "dur_s2_158" "dur_s2_157" -332 syl_vowel==er -333 "dur_s2_159" -333 prev_cont==+&&ccor==+&&cvox==+ -650 "dur_s2_160" -334 prev_vfront==3 -572 -605 -335 pos_in_syl_bw==1 "dur_s2_162" "dur_s2_161" -336 cont==+ "dur_s2_164" "dur_s2_163" -337 word_gpos==pps -442 -595 -338 prev_name==t "dur_s2_166" "dur_s2_165" -339 prev_ccor==+&&cvox==- -490 "dur_s2_167" -340 syl_pos_in_phrase_fw<=1 -415 "dur_s2_168" -341 prev_prev_vfront==2&&vheight==2 "dur_s2_170" "dur_s2_169" -342 next_syl_accented==1 -348 "dur_s2_171" -343 next_name==s -518 "dur_s2_172" -344 num_syls_in_next_phrase<=4 "dur_s2_173" -639 -345 prev_cont==+&&cvox==+ -631 "dur_s2_174" -346 prev_prev_vlng==s -612 "dur_s2_175" -347 vfront==3 "dur_s2_176" -486 -348 prev_cvox==-&&csib==+ -539 "dur_s2_177" -349 pos_in_word_bw<=5 "dur_s2_178" -448 -350 syl_pos_in_phrase_bw<=9 "dur_s2_180" "dur_s2_179" -351 next_name==r -352 "dur_s2_181" -352 prev_vrnd==-&&vlng==d -353 "dur_s2_182" -353 prev_ctype==r -510 "dur_s2_183" -354 prev_cont==-&&cvox==- "dur_s2_185" "dur_s2_184" -355 syl_stress==1 -406 -555 -356 syl_length<=2 "dur_s2_187" "dur_s2_186" -357 num_syls_in_phrase<=13 "dur_s2_189" "dur_s2_188" -358 syl_length<=3 "dur_s2_190" -532 -359 next_next_name==x -449 "dur_s2_191" -360 next_cont==+&&son==+ -361 "dur_s2_192" -361 prev_cvox==- "dur_s2_193" -362 -362 next_next_cont==-&&son==- "dur_s2_194" -363 -363 syl_pos_in_word_bw==2 "dur_s2_196" "dur_s2_195" -364 next_cont==+&&cvox==+ "dur_s2_198" "dur_s2_197" -365 prev_ccor==+&&son==- -366 "dur_s2_199" -366 next_cont==+&&cvox==+&&cplace==a "dur_s2_201" "dur_s2_200" -367 num_stressed_syls_in_phrase_after_this_syl<=8 "dur_s2_203" "dur_s2_202" -368 pos_in_word_fw<=1 -585 "dur_s2_204" -369 syl_vowel==eh -370 -528 -370 next_clab==+ "dur_s2_206" "dur_s2_205" -371 prev_vc==- "dur_s2_208" "dur_s2_207" -372 syl_vowel_vfront==3 -373 "dur_s2_209" -373 prev_cont==-&&cvox==+ -407 -638 -374 name==aw -375 "dur_s2_210" -375 prev_cont==-&&cvox==+&&clab==+ -420 "dur_s2_211" -376 prev_prev_cont==-&&cvox==+ -424 "dur_s2_212" -377 syl_vowel_vfront==1&&vlng==s "dur_s2_214" "dur_s2_213" -378 prev_cont==-&&cvox==+&&clab==+ -593 "dur_s2_215" -379 num_words_in_next_phrase<=3 "dur_s2_216" -534 -380 next_cont==+&&son==+ "dur_s2_218" "dur_s2_217" -381 dist_to_prev_content_word_in_phrase<=2 "dur_s2_220" "dur_s2_219" -382 next_cont==+&&cvox==+ "dur_s2_222" "dur_s2_221" -383 next_next_cvox==+&&ctype==f -384 -411 -384 prev_vrnd==+ "dur_s2_224" "dur_s2_223" -385 next_ctype==f&&csib==+ "dur_s2_225" -386 -386 word_gpos==content "dur_s2_227" "dur_s2_226" -387 next_son==- "dur_s2_229" "dur_s2_228" -388 next_cont==+ -474 "dur_s2_230" -389 num_words_in_next_phrase<=5 "dur_s2_231" -476 -390 syl_pos_in_word_fw==1 "dur_s2_232" -482 -391 prev_cont==-&&cvox==+ "dur_s2_234" "dur_s2_233" -392 pos_in_word_fw<=3 "dur_s2_236" "dur_s2_235" -393 name==ay "dur_s2_238" "dur_s2_237" -394 next_name==l -417 -499 -395 prev_ctype==n -599 -396 -396 num_syls_in_next_phrase<=2 "dur_s2_240" "dur_s2_239" -397 syl_vowel==eh -426 "dur_s2_241" -398 prev_vc==+ -548 -511 -399 next_cvox==+&&clab==+ -541 "dur_s2_242" -400 prev_ccor==+ "dur_s2_243" -618 -401 name==f -634 "dur_s2_244" -402 clab==+ "dur_s2_245" -403 -403 prev_vc==- "dur_s2_246" -580 -404 next_son==- -651 -459 -405 next_clab==+ -487 "dur_s2_247" -406 word_gpos==det "dur_s2_249" "dur_s2_248" -407 word_gpos==aux "dur_s2_250" -408 -408 prev_vrnd==- -573 "dur_s2_251" -409 num_syls_in_utt==16 -505 "dur_s2_252" -410 syl_vowel==ao "dur_s2_254" "dur_s2_253" -411 word_pos_in_phrase_fw<=2 -567 "dur_s2_255" -412 prev_prev_cont==+&&ccor==+ "dur_s2_257" "dur_s2_256" -413 next_cont==- -414 -526 -414 syl_vowel==eh "dur_s2_259" "dur_s2_258" -415 prev_cont==- -545 "dur_s2_260" -416 next_word_gpos==0 -597 "dur_s2_261" -417 word_gpos==det -632 "dur_s2_262" -418 syl_pos_in_word_fw<=1 "dur_s2_263" -451 -419 prev_cvox==- -446 "dur_s2_264" -420 pos_in_word_bw<=3 "dur_s2_266" "dur_s2_265" -421 next_name==s -422 "dur_s2_267" -422 prev_son==- "dur_s2_269" "dur_s2_268" -423 next_cont==+ "dur_s2_271" "dur_s2_270" -424 prev_ctype==n "dur_s2_273" "dur_s2_272" -425 next_cvox==+ -454 "dur_s2_274" -426 prev_cont==+&&son==+ "dur_s2_276" "dur_s2_275" -427 prev_son==- "dur_s2_277" -466 -428 dist_to_next_accented_syl_in_phrase<=2 "dur_s2_279" "dur_s2_278" -429 next_next_vlng==l "dur_s2_281" "dur_s2_280" -430 prev_ctype==f -575 "dur_s2_282" -431 syl_pos_in_word_fw<=1 "dur_s2_283" -432 -432 ccor==+ -538 "dur_s2_284" -433 pos_in_word_fw==1 -622 "dur_s2_285" -434 prev_syl_length<=0 -435 -436 -435 next_cvox==- -615 -546 -436 prev_prev_name==pau "dur_s2_287" "dur_s2_286" -437 next_name==hh -592 "dur_s2_288" -438 num_syls_in_utt==8 "dur_s2_290" "dur_s2_289" -439 phrase_pos_in_utt_fw<=2 "dur_s2_291" -544 -440 prev_cont==+ "dur_s2_293" "dur_s2_292" -441 word_gpos==in "dur_s2_295" "dur_s2_294" -442 next_name==l -443 "dur_s2_296" -443 name==ay -444 "dur_s2_297" -444 num_syls_in_word<=2 -445 -594 -445 next_vheight==2 "dur_s2_299" "dur_s2_298" -446 prev_word_gpos==content "dur_s2_301" "dur_s2_300" -447 prev_prev_cont==+&&cplace==a -535 "dur_s2_302" -448 dist_to_next_content_word_in_phrase==1 "dur_s2_304" "dur_s2_303" -449 prev_cont==+&&ccor==+ -586 "dur_s2_305" -450 prev_name==l "dur_s2_307" "dur_s2_306" -451 pos_in_word_bw==1 "dur_s2_309" "dur_s2_308" -452 prev_prev_ctype==s&&cplace==a "dur_s2_311" "dur_s2_310" -453 next_name==y -481 "dur_s2_312" -454 pos_in_word_fw==2 -464 "dur_s2_313" -455 prev_cont==- "dur_s2_315" "dur_s2_314" -456 next_cvox==-&&cplace==a "dur_s2_317" "dur_s2_316" -457 prev_prev_ccor==+&&son==- -458 "dur_s2_318" -458 prev_prev_cvox==+ "dur_s2_319" -621 -459 ccor==+ "dur_s2_321" "dur_s2_320" -460 next_next_name==x "dur_s2_323" "dur_s2_322" -461 next_next_vrnd==-&&vlng==l "dur_s2_325" "dur_s2_324" -462 prev_vc==+ "dur_s2_327" "dur_s2_326" -463 prev_prev_cvox==+ -519 -637 -464 syl_vowel_vrnd==-&&vlng==l "dur_s2_329" "dur_s2_328" -465 prev_cont==- "dur_s2_331" "dur_s2_330" -466 prev_name==sh "dur_s2_333" "dur_s2_332" -467 next_clab==+ -500 "dur_s2_334" -468 pos_in_word_bw<=5 "dur_s2_336" "dur_s2_335" -469 syl_vowel==ow "dur_s2_338" "dur_s2_337" -470 syl_vowel_vfront==1&&vlng==s -652 "dur_s2_339" -471 next_cont==-&&ccor==+&&son==- "dur_s2_341" "dur_s2_340" -472 pos_in_syl_fw<=1 "dur_s2_342" -642 -473 next_cvox==- -644 "dur_s2_343" -474 prev_son==- "dur_s2_345" "dur_s2_344" -475 next_cont==+&&son==+ "dur_s2_347" "dur_s2_346" -476 num_words_in_utt<=5 "dur_s2_349" "dur_s2_348" -477 prev_cont==+&&son==+ "dur_s2_351" "dur_s2_350" -478 prev_ccor==+&&cvox==+ -479 "dur_s2_352" -479 next_name==l "dur_s2_353" -480 -480 vrnd==- "dur_s2_355" "dur_s2_354" -481 prev_son==+&&cplace==a -625 -641 -482 next_vfront==2 -578 "dur_s2_356" -483 syl_vowel_vrnd==-&&vlng==s "dur_s2_358" "dur_s2_357" -484 next_next_ctype==r -485 "dur_s2_359" -485 next_name==hh "dur_s2_361" "dur_s2_360" -486 pos_in_word_bw<=4 "dur_s2_362" -629 -487 prev_ccor==+&&son==- "dur_s2_363" -488 -488 next_ccor==+ "dur_s2_365" "dur_s2_364" -489 num_syls_in_utt<=8 -635 "dur_s2_366" -490 prev_prev_cont==+ -579 "dur_s2_367" -491 pos_in_word_bw==3 "dur_s2_369" "dur_s2_368" -492 next_son==+&&cplace==a -493 "dur_s2_370" -493 prev_prev_vheight==1 "dur_s2_372" "dur_s2_371" -494 next_cvox==+ "dur_s2_374" "dur_s2_373" -495 next_name==l -496 "dur_s2_375" -496 prev_cvox==+ "dur_s2_377" "dur_s2_376" -497 name==g "dur_s2_379" "dur_s2_378" -498 next_next_clab==+ "dur_s2_381" "dur_s2_380" -499 pos_in_word_bw<=3 "dur_s2_383" "dur_s2_382" -500 next_cvox==+&&son==-&&cplace==a "dur_s2_385" "dur_s2_384" -501 num_syls_in_phrase==2 "dur_s2_387" "dur_s2_386" -502 num_words_in_next_phrase<=4 "dur_s2_389" "dur_s2_388" -503 prev_cvox==- -620 "dur_s2_390" -504 next_csib==+&&cplace==a "dur_s2_392" "dur_s2_391" -505 syl_pos_in_phrase_bw==5 -530 "dur_s2_393" -506 syl_vowel_vheight==1&&vlng==l "dur_s2_395" "dur_s2_394" -507 pos_in_syl_bw==1 "dur_s2_397" "dur_s2_396" -508 next_next_vlng==l "dur_s2_399" "dur_s2_398" -509 name==v "dur_s2_401" "dur_s2_400" -510 prev_prev_cvox==- -582 "dur_s2_402" -511 ctype==r -512 "dur_s2_403" -512 prev_vheight==1&&vlng==s "dur_s2_405" "dur_s2_404" -513 name==p -630 -514 -514 next_cvox==+ "dur_s2_407" "dur_s2_406" -515 syl_pos_in_word_bw==2 "dur_s2_409" "dur_s2_408" -516 prev_prev_ccor==+ -581 "dur_s2_410" -517 next_cont==-&&cvox==+ -551 "dur_s2_411" -518 num_syls_in_next_phrase==4 "dur_s2_413" "dur_s2_412" -519 prev_name==l "dur_s2_415" "dur_s2_414" -520 num_syls_in_next_phrase<=0 "dur_s2_416" -521 -521 prev_prev_cvox==-&&cplace==p -522 "dur_s2_417" -522 name==n -523 "dur_s2_418" -523 prev_vrnd==- "dur_s2_420" "dur_s2_419" -524 word_gpos==content "dur_s2_422" "dur_s2_421" -525 prev_ctype==s&&cplace==a "dur_s2_424" "dur_s2_423" -526 num_words_in_phrase<=11 "dur_s2_426" "dur_s2_425" -527 next_ccor==+&&son==- "dur_s2_428" "dur_s2_427" -528 next_cont==+ "dur_s2_429" -529 -529 prev_ctype==r&&son==+ "dur_s2_431" "dur_s2_430" -530 prev_name==l "dur_s2_433" "dur_s2_432" -531 syl_vowel==ow -601 "dur_s2_434" -532 num_content_words_in_phrase_before_this_word==2 "dur_s2_436" "dur_s2_435" -533 num_content_words_in_phrase_before_this_word==5 "dur_s2_438" "dur_s2_437" -534 next_next_cont==-&&ccor==+ -626 "dur_s2_439" -535 prev_cplace==a "dur_s2_441" "dur_s2_440" -536 num_syls_in_phrase<=11 "dur_s2_443" "dur_s2_442" -537 cplace==p "dur_s2_445" "dur_s2_444" -538 prev_vlng==l "dur_s2_447" "dur_s2_446" -539 num_syls_in_utt<=14 "dur_s2_449" "dur_s2_448" -540 syl_vowel==eh "dur_s2_451" "dur_s2_450" -541 word_gpos==in -610 "dur_s2_452" -542 prev_cont==+&&ccor==+&&cvox==+ "dur_s2_454" "dur_s2_453" -543 prev_vc==+ "dur_s2_456" "dur_s2_455" -544 next_next_cont==+&&cplace==a "dur_s2_458" "dur_s2_457" -545 syl_vowel_vheight==1 "dur_s2_460" "dur_s2_459" -546 next_syl_accented==1 "dur_s2_462" "dur_s2_461" -547 next_ctype==r&&son==+ -603 "dur_s2_463" -548 cplace==p "dur_s2_465" "dur_s2_464" -549 next_name==n -550 "dur_s2_466" -550 word_pos_in_phrase_fw<=3 "dur_s2_468" "dur_s2_467" -551 next_next_vlng==a "dur_s2_470" "dur_s2_469" -552 pos_in_word_bw<=3 "dur_s2_472" "dur_s2_471" -553 prev_prev_cvox==- "dur_s2_474" "dur_s2_473" -554 word_gpos==content "dur_s2_475" -602 -555 syl_vowel==iy -556 -655 -556 prev_son==+ "dur_s2_477" "dur_s2_476" -557 prev_ccor==+&&cvox==+ "dur_s2_479" "dur_s2_478" -558 prev_ccor==+&&son==- "dur_s2_480" -559 -559 next_cont==+&&son==+ "dur_s2_482" "dur_s2_481" -560 next_name==t -561 "dur_s2_483" -561 next_name==l "dur_s2_485" "dur_s2_484" -562 son==+&&cplace==a -564 -563 -563 prev_name==l -565 "dur_s2_486" -564 prev_son==- "dur_s2_487" -590 -565 next_vrnd==-&&vheight==1 "dur_s2_489" "dur_s2_488" -566 pos_in_word_bw==1 "dur_s2_491" "dur_s2_490" -567 prev_vc==+ "dur_s2_493" "dur_s2_492" -568 ctype==r "dur_s2_495" "dur_s2_494" -569 syl_stress==1 "dur_s2_497" "dur_s2_496" -570 prev_ctype==r "dur_s2_499" "dur_s2_498" -571 num_words_in_utt==7 "dur_s2_501" "dur_s2_500" -572 next_clab==+ -627 "dur_s2_502" -573 prev_son==- "dur_s2_504" "dur_s2_503" -574 next_vrnd==-&&vheight==1 "dur_s2_506" "dur_s2_505" -575 prev_prev_csib==+ -617 "dur_s2_507" -576 dist_to_prev_stressed_syl_in_phrase==2 "dur_s2_509" "dur_s2_508" -577 prev_vc==- "dur_s2_511" "dur_s2_510" -578 word_pos_in_phrase_fw==1 "dur_s2_513" "dur_s2_512" -579 prev_cont==- "dur_s2_515" "dur_s2_514" -580 prev_prev_son==- "dur_s2_517" "dur_s2_516" -581 prev_name==n -608 "dur_s2_518" -582 prev_prev_cvox==+&&clab==+ "dur_s2_520" "dur_s2_519" -583 dist_to_prev_stressed_syl_in_phrase==1 "dur_s2_522" "dur_s2_521" -584 prev_prev_vrnd==- "dur_s2_524" "dur_s2_523" -585 prev_cont==-&&cvox==+ "dur_s2_526" "dur_s2_525" -586 next_vfront==3&&vlng==l "dur_s2_528" "dur_s2_527" -587 word_gpos==in "dur_s2_529" -588 -588 prev_prev_cvox==+&&cplace==a "dur_s2_531" "dur_s2_530" -589 prev_prev_csib==+ "dur_s2_533" "dur_s2_532" -590 cont==+ -591 "dur_s2_534" -591 pos_in_word_bw<=3 "dur_s2_536" "dur_s2_535" -592 next_syl_accented==1 "dur_s2_538" "dur_s2_537" -593 prev_cvox==+&&son==- "dur_s2_540" "dur_s2_539" -594 next_next_vrnd==-&&vlng==l "dur_s2_542" "dur_s2_541" -595 prev_prev_cvox==+ "dur_s2_544" "dur_s2_543" -596 prev_prev_ccor==+&&son==- "dur_s2_546" "dur_s2_545" -597 next_syl_length<=2 "dur_s2_548" "dur_s2_547" -598 num_accented_syls_in_phrase_before_this_syl<=2 "dur_s2_550" "dur_s2_549" -599 prev_cvox==+&&son==- "dur_s2_552" "dur_s2_551" -600 num_syls_in_phrase<=17 "dur_s2_554" "dur_s2_553" -601 next_cvox==+&&cplace==v "dur_s2_556" "dur_s2_555" -602 prev_prev_cplace==l "dur_s2_558" "dur_s2_557" -603 syl_stress==1 "dur_s2_560" "dur_s2_559" -604 cvox==+ "dur_s2_561" -623 -605 next_clab==+ "dur_s2_563" "dur_s2_562" -606 next_vfront==1&&vlng==s -607 "dur_s2_564" -607 next_next_son==-&&cplace==a "dur_s2_566" "dur_s2_565" -608 syl_pos_in_phrase_bw<=4 "dur_s2_568" "dur_s2_567" -609 prev_ctype==a "dur_s2_570" "dur_s2_569" -610 prev_cont==+&&ccor==+ "dur_s2_572" "dur_s2_571" -611 dist_to_prev_accented_syl_in_phrase<=3 "dur_s2_574" "dur_s2_573" -612 prev_prev_name==ey "dur_s2_576" "dur_s2_575" -613 prev_name==r "dur_s2_578" "dur_s2_577" -614 num_syls_in_prev_word<=0 "dur_s2_580" "dur_s2_579" -615 next_syl_length<=2 "dur_s2_581" -616 -616 next_vfront==1 "dur_s2_583" "dur_s2_582" -617 num_syls_in_prev_word==2 "dur_s2_585" "dur_s2_584" -618 next_next_son==- "dur_s2_587" "dur_s2_586" -619 prev_ccor==+&&cvox==-&&ctype==f "dur_s2_589" "dur_s2_588" -620 next_ctype==f&&csib==+ "dur_s2_591" "dur_s2_590" -621 num_syls_in_utt<=10 "dur_s2_593" "dur_s2_592" -622 next_next_name==er "dur_s2_595" "dur_s2_594" -623 cont==+&&cvox==+&&cplace==p "dur_s2_597" "dur_s2_596" -624 vfront==1 "dur_s2_599" "dur_s2_598" -625 syl_length==2 "dur_s2_601" "dur_s2_600" -626 num_words_in_phrase<=4 -645 "dur_s2_602" -627 pos_in_syl_bw==1 "dur_s2_604" "dur_s2_603" -628 next_next_name==n "dur_s2_606" "dur_s2_605" -629 next_next_ccor==+&&son==- "dur_s2_608" "dur_s2_607" -630 prev_vfront==1&&vheight==2 "dur_s2_610" "dur_s2_609" -631 pos_in_word_fw<=3 "dur_s2_612" "dur_s2_611" -632 next_name==s "dur_s2_614" "dur_s2_613" -633 prev_name==n "dur_s2_616" "dur_s2_615" -634 prev_cont==-&&cvox==+ "dur_s2_618" "dur_s2_617" -635 num_words_in_utt==7 -636 "dur_s2_619" -636 num_words_in_utt==12 "dur_s2_621" "dur_s2_620" -637 next_vrnd==+&&vlng==l "dur_s2_623" "dur_s2_622" -638 syl_vowel==ae "dur_s2_625" "dur_s2_624" -639 prev_syl_accented==0 "dur_s2_627" "dur_s2_626" -640 prev_prev_ctype==s&&cplace==a "dur_s2_629" "dur_s2_628" -641 prev_prev_vlng==s "dur_s2_631" "dur_s2_630" -642 pos_in_word_bw==5 "dur_s2_633" "dur_s2_632" -643 vfront==1 "dur_s2_635" "dur_s2_634" -644 prev_son==+&&clab==+ "dur_s2_637" "dur_s2_636" -645 prev_vrnd==-&&vlng==s "dur_s2_638" -646 -646 next_next_vheight==3 "dur_s2_640" "dur_s2_639" -647 next_vheight==1 -648 "dur_s2_641" -648 next_name==ax "dur_s2_643" "dur_s2_642" -649 prev_cont==-&&cplace==a "dur_s2_645" "dur_s2_644" -650 syl_vowel==oy "dur_s2_647" "dur_s2_646" -651 next_name==w "dur_s2_649" "dur_s2_648" -652 pos_in_word_fw==1 "dur_s2_651" "dur_s2_650" -653 num_stressed_syls_in_phrase_before_this_syl<=5 "dur_s2_653" "dur_s2_652" -654 num_syls_in_phrase<=8 "dur_s2_655" "dur_s2_654" -655 next_cont==-&&ccor==+&&son==- "dur_s2_657" "dur_s2_656" }
{ "pile_set_name": "Github" }
949766990624ce317509f3680e69089d frame00000000 984d4251242c09bebf30cf9bb4219218 frame00000001 286d19f66ae198cdb56163d91a3e7921 frame00000002 358b955835be99e3bf0cfca484134676 frame00000003 6d55c71bef2bddf93261b3ea49879904 frame00000004 1de3c18386b9f2b6390276afc8b86c84 frame00000005 eb73c0cc2e9b92ace70072143584f1b4 frame00000006 3d9ef6ea34e70f5d402a792acd14570d frame00000007 d42fb0105ea5f44817860af7c902a031 frame00000008 cc139e6a11a9e07d4e60ad3cc038efca frame00000009 df4eb79e71e5161305f10ea24821eaf3 frame00000010 3ffa41ca9e9e3f3a0e53ebeae55912dd frame00000011 6b04ae74da25f03df54c67f8c1fd26a7 frame00000012 9236ef57e6f2cbd9fb9d87c5daa00e44 frame00000013 ad526cd7f586388f8a23c27c467615f5 frame00000014 69d43917a68c84f5f0dd6d2d2f3f4e14 frame00000015 a393c90d279e8418dcbb0c711a853e2f frame00000016 370251e2208e50aedc6c62b6dd514de8 frame00000017 1f31672ee07ce97c39132aa6973419a6 frame00000018 761499e623ba9e0a6e1611f067126659 frame00000019 498a6ff7da0fa419037e97025213459b frame00000020 0634a2330b150de121ee043229dcf4df frame00000021 ef04e209a43e38b7a2603fa0818fa787 frame00000022 96ce1b661011fd4de386c2a0eea41027 frame00000023 a0af61289c2c4d5856f04e9615794397 frame00000024 92133fa92ce2711c4f980f615c6687fe frame00000025 3f45e37617ab5730070ae4d8bdb531bb frame00000026 c455fc5f35f0a87f388d3487a062709d frame00000027 a83cbf3c05d91035d6f8916b51e8b653 frame00000028 afa9f1c40996e6ddeeab0e1f385acf75 frame00000029 d603863e8d9be7b0f76889a1a375eb4e frame00000030 5dae2d9c68165fad94d2211b4f56fd4f frame00000031 eadef42e2be5cfc5be8720a5b523d617 frame00000032 8ea1c668e31f74ef54ec0e34cf5cc135 frame00000033 09478cf4e5b038be1ae789db5bf5efd7 frame00000034 2a6d575597141a2d675d86e95a14d775 frame00000035 3f02a1fd9ea69daa67a8c80f3989effb frame00000036 4e016a88b221fff1476421cac61b4a2d frame00000037 5df900bc3bd8b9f91e0fd8686cea43cf frame00000038 52bbfd5b0a00e63d8066cde7c79456a5 frame00000039 b3a2ef46cd3fdb55385cf0dab10e055f frame00000040 07b0115d815e42ae0defae7b214d031a frame00000041 32cb902e0bb79a24045e44f7398f6119 frame00000042 3bf7eb348ebf36ad10b45d6b8ef046ae frame00000043 bdf0cddc3f37ed9fc7b47192f0d21e9a frame00000044 eaace1163c89963dd455f05eb92844e8 frame00000045 22a9e5afd2c91b6f555d4f773343ff8a frame00000046 91aa7961b1d8a3e7f6a986cd147a2b4a frame00000047 139b4276a45a305bf0d4c05d739a949c frame00000048 89c82c8d3e8878b00a1a1eac6ffbd6d0 frame00000049 b4d0e6e5a7c264f82f4ae71d85951d87 frame00000050 cb967a3e01e530b69e13c9c478a97c45 frame00000051 514bb22f69d186a172754883b3c7bf9c frame00000052 c8633576d7257929a4d000af07f6d370 frame00000053 5c5d376a55063f027632f309354bf4a0 frame00000054 f3660cd1812ab8753182b52fe520662b frame00000055 d1aa271ae6da5035581585d3423f4d1d frame00000056 63b20728f0488189469b656cf2dd9cb3 frame00000057 c97054884b569b16b155b98c468bf012 frame00000058 10430ef205ee7143cc5ba61cf4bcf4ff frame00000059 a46ab9c1c4918ffc34032a976afb5448 frame00000060 3ac6d62d28131b4b15da3a63f144a915 frame00000061 d468ef5f2e1b6eb7b84796b8af5d713f frame00000062 48235442fbc96a9e2ba9d93f8034c73a frame00000063 7e57a7d9708bbe2a41484102a95fb912 frame00000064 a626cd0bb96de92884a53b4d6197a81f frame00000065 b94fabad35ee0119691cc2dc902ea51b frame00000066 30a4fcddf17ab386060455b25e0acd47 frame00000067 b5a03b3509dca43b55d4998dbbb11e80 frame00000068 0553d9b24728b866f9a87c9a9cce5119 frame00000069 7218596e89d1cdbfb300992a6395dc2a frame00000070 033af528b4337d9cd448f60e11c01d32 frame00000071 ac64d8c0cf5e89411b6cce277cfaf7cc frame00000072 ae03aaa83ae3a3f92731e25fbf35099a frame00000073 2005b41146d4574bec40984703165d64 frame00000074 f4093ef5246fa190b74a2016b18e7d1b frame00000075 d3627ee398669c261fb962128232950b frame00000076 9e981cd5ca6a4316ea36d847d052c7b3 frame00000077 741136e487cec3ffc14247d6a7741ee1 frame00000078 23168bd90a690e4d0d387cc8b90a8bf8 frame00000079 ad1a1e967daca551502cff560bbf15bc frame00000080 0d75e810bfbc7b875b60c0e1909737bf frame00000081 0d75e810bfbc7b875b60c0e1909737bf frame00000082 0d75e810bfbc7b875b60c0e1909737bf frame00000083 0d75e810bfbc7b875b60c0e1909737bf frame00000084 0d75e810bfbc7b875b60c0e1909737bf frame00000085 0d75e810bfbc7b875b60c0e1909737bf frame00000086 0d75e810bfbc7b875b60c0e1909737bf frame00000087 0d75e810bfbc7b875b60c0e1909737bf frame00000088 0d75e810bfbc7b875b60c0e1909737bf frame00000089 0d75e810bfbc7b875b60c0e1909737bf frame00000090 0d75e810bfbc7b875b60c0e1909737bf frame00000091 0d75e810bfbc7b875b60c0e1909737bf frame00000092 0d75e810bfbc7b875b60c0e1909737bf frame00000093 0d75e810bfbc7b875b60c0e1909737bf frame00000094 0d75e810bfbc7b875b60c0e1909737bf frame00000095 0d75e810bfbc7b875b60c0e1909737bf frame00000096 0d75e810bfbc7b875b60c0e1909737bf frame00000097 0d75e810bfbc7b875b60c0e1909737bf frame00000098 0d75e810bfbc7b875b60c0e1909737bf frame00000099 0d75e810bfbc7b875b60c0e1909737bf frame00000100 0d75e810bfbc7b875b60c0e1909737bf frame00000101 0d75e810bfbc7b875b60c0e1909737bf frame00000102 0d75e810bfbc7b875b60c0e1909737bf frame00000103 4473e683c75d6b63de01d02ae6daa8e5 frame00000104 c7bf242e321b2016df9156005803752a frame00000105 4fb66b7081abae77c52860161e66a83f frame00000106 27d209c149ada8cfb3abb7af6a458f68 frame00000107 85ea056ca46f1a2458f0b76a8d69e0fa frame00000108 4d9286898c684874b470d0b201015c51 frame00000109 24f0b3463f594afb3093ef79f5c30cae frame00000110 ac9c5a3ade765878856b7eeda7cc30f3 frame00000111 097e482f184e07d0702907e77ae9763a frame00000112 b57ab38aa28644087037b3765a9a092f frame00000113 32377d0faefc260bc6ea9af219a09693 frame00000114 5fbb013af8fd2c9af218a1de704d5435 frame00000115 fdc68ec8c353b59cc97b17bafc4063bc frame00000116 0b3bcc79a94af787fa31548589fa8c4d frame00000117 384480994571b40ba449cb8318ab753b frame00000118 e430058a8c353d88be85858aea314053 frame00000119 7f5f5ded0957ac04358fa2c19bbbd244 frame00000120 8d0dd4e7c2f26e7637d764f13e3be623 frame00000121 3b0001c57f77090256c41666d6695cdf frame00000122 d1bcf6a9a232819ca63b03274594c077 frame00000123 1091fe61e1e70ca07be72ed9555aafbc frame00000124 32e09d3020610c552ca4f1c545948cc5 frame00000125 c7faeb2834804ac1bb538ebfaf488840 frame00000126 e2b51b5cc77bb37512b2206410dc3023 frame00000127 5218c7ad61730bf0a66a4bebacf48ef4 frame00000128 0e044ed31aee534ce4f19c3350adfe6c frame00000129 5da371fed7b14ae6d1884e4bdfdfa046 frame00000130 e2aa583e06ea3bdaf5fa607324b6bab5 frame00000131 3d6de4be3bc9f049449ae0ffc263eec0 frame00000132 b964fe22d8ce77b1d4f05d8d6e8e7407 frame00000133 113484d62c36c9d88ccc4e2cb86a3283 frame00000134 3aa5376b7729affccde29e55a7c718d0 frame00000135 c09601e15846a9afd2e1eddabefe7c1a frame00000136 66864885bf4baa920fbaec15b00c59b6 frame00000137 449422e28a799a934b3ef7a52400527d frame00000138 4ac07eab61253ec40ec2e56a27003d03 frame00000139 dd2aa0224fed6408c78a17b358008378 frame00000140 7ac41e7b885e447e18d143df214ebd15 frame00000141 7980b4a748fc6570919a28444fb25d21 frame00000142 4f8d09fa1a7f4b8c3e56503ad371e912 frame00000143 0c880bed998990e9a3791f159f22935f frame00000144 3be983494cf555923f464893abad5392 frame00000145 e86eaf56ec351d39319d1846bd721faf frame00000146 f27f38452a7e247db5bcb27b10db71dc frame00000147 87ede291a626b9ff9e3bc5a7e003d082 frame00000148 4466c2e025a328d3bd04c76cb912bca5 frame00000149 ccb873c5c706065f731941601073a164 frame00000150 408b28d587bae3d4454a70221bf73833 frame00000151 572a73b0886d0f307a779fcf278f6851 frame00000152 5003ad892602313d3fd8894fde233d82 frame00000153 3b6f71d591613a55b82e4a02dcc4fd5b frame00000154 e6781e3c176a3454717d3079b1afa034 frame00000155 207b4600a94b96cc2d49ead234d6ea58 frame00000156 2726827bc25d87dbbb573e492c23fd2d frame00000157 d9bd77102dde3549bb1feeb5b750e0e0 frame00000158 b4ea0a11d579906265096ae62e79e245 frame00000159 d8f45e244a0856032762b49e8399ed64 frame00000160 bb36db433e59835a7533a9eb40eb44f7 frame00000161 f477196519d484c89b423f9bd90b5756 frame00000162 2b735c22937bbefe8639fa20e063a56c frame00000163 ebae862def8ee89b3a5f92c781aeae2a frame00000164 b697fa7deaddf95b3d567948301da5e4 frame00000165 1945229e5c1ed0b46a28b586eef86154 frame00000166 cce3ebebe8c6a10d60719700f8f6f49d frame00000167 3e1327daa64180284990592fe22fd4d9 frame00000168 37a47e96e3ca9bd12c7b8d4059446491 frame00000169 c06e0f8dfa1c6fd7dd4178f25716c045 frame00000170 d0b9ccc43c0649f306b7d92e8beaace7 frame00000171 bfe5438786df0c2bb28e59bc8eecbb47 frame00000172 ed86cded6160f94e5b29ddd2c3473009 frame00000173 0c5b36e0142b76f5ae52b95bbbfb1b5e frame00000174 1ebb360c581d542d15fc2e9d21efa0a2 frame00000175 fabd0892f62b49cf383abf96c4dd6cbb frame00000176 4a05c2c4e3ad47e123da520bf483b0e1 frame00000177 22d673f9ac17d54d16611e20ea2f44ba frame00000178 5b4af4fb5ff2d0396c2dd1bc5fb92eaf frame00000179 b1a1e8681041a3d3b30805be9834d478 frame00000180 7d6703280ca7ff68c7b1775ed2dc4548 frame00000181 046cbe08d2804f97991f7826fb3ab102 frame00000182 c38e17a6fed61af8d8edefef6af91403 frame00000183 822099a0f37439aeb55494b134be6c5d frame00000184 ee844ac480956e530ee5283ab9f9a244 frame00000185 923576768935f91d64fcc7fa80ecc06b frame00000186 44ae0aff204077f985ee891f3600a76b frame00000187 c430178e10a1ff2a99351b6caceac693 frame00000188 3a5742f90ee0f3269cda26aaa798f2ae frame00000189 750b799ef92ec7aaf2544d41de0866e6 frame00000190 7ac4eb3aa3c5b2ee57afe82ae533c88c frame00000191 e0b3dd66c92d2f7204d773644ec73a43 frame00000192 b6965bd28691ee014fc5a86aa3de92a6 frame00000193 ce61fc44273f150289afeacc4119e7d6 frame00000194 8fd06769a611b8cd66af965dfb1340e4 frame00000195 521def926acd2c8b94b9efe5d3271072 frame00000196 43659ba3fe64fb0417182d8d088926d2 frame00000197 47001ef7d59ed5208c9f42fdd9e2e9ec frame00000198 5aad946941de9e7aedaff2bb3897ccd1 frame00000199 a0bee4f402040314deb242e77efa233f frame00000200 7bc5c22ed5e1b95ea1550c75efc98e41 frame00000201 0b3823bdaa49b30c570d14bb80bf4b61 frame00000202 5358dab4549419b9da2c07b2e9f8f44b frame00000203 f1e694b205e6460f90fd26fddae9f7e2 frame00000204 a319fd4db1fccb9ca5262ab939c27688 frame00000205 58a205f9b20c7ebf49ea633dd0508a53 frame00000206 1f0fbb697d320922e20a0b318458d09b frame00000207 cef5ad44b9eb63dcecf7c2ad20284280 frame00000208 a4126fac9a987426502312fa7adf24be frame00000209 6e3ea972f1b982d6d752a677cff80e75 frame00000210 0d75e810bfbc7b875b60c0e1909737bf frame00000211 0d75e810bfbc7b875b60c0e1909737bf frame00000212 0d75e810bfbc7b875b60c0e1909737bf frame00000213 29cbbeeed21994063c04407d3158d05c frame00000214 f9ec01ae2161d2ed89a492120b05db73 frame00000215 577856c33f827e4e9f57f4da8a3aca7a frame00000216 064d4932abd77a7a765132ca46ceb1c8 frame00000217 ece48deb620b386839f5217cad943d5b frame00000218 c9488440a86a287f678e15bfe2e3a020 frame00000219 1d22fa0d687ebcc91338266859c4f155 frame00000220 d7b267c98a8db8b231a2ec3fbdb61b6b frame00000221 91ec20ac1b7ce6fb383b54403645cf7a frame00000222 5b62b1ba346fa0298572cd6a2f2d7d87 frame00000223 0106ecc582196c5263e8229655a71171 frame00000224 2e9b645e0715fb731c25f9c45d756aaa frame00000225 0c5955b73345b8f04bcf89422595d02d frame00000226 b9ad34d9c839acd67d04674a990756b1 frame00000227 7e05d706794a85586e7500b91803365e frame00000228 d30e17e92b6e47971c8b8a25855682fb frame00000229 e5a936652c972bafd8659639d82c46e2 frame00000230 a6da8ec1936074cac774ce4cffeb7460 frame00000231 48712f1e78fd9d417a52928246aabe52 frame00000232 72004a23adcc72ef113230a0197358d7 frame00000233 060f997f48fd1c93faebd9175694f9ed frame00000234 0faa22b67009d79df563453f6286a2c6 frame00000235 ff8b05c321335e3d329899a56b2fa0cf frame00000236 6fb3000a53ce8cc9db4d70b681dea00c frame00000237 24e5758abe6372ab3a0329d8c4b0acd3 frame00000238 3e0d14295adf200d60ffcb17bbbb4a13 frame00000239 b117d2c9d0c178c22ab929aea3ed6269 frame00000240 34a65f55e69b138b5ed2cbe5f6ef146a frame00000241 569c17dce5a6f3bf025b5ef7f3d91664 frame00000242 3805a05da91c20b02425594904527a4c frame00000243 880be262908705f07b9c6249b6e10c97 frame00000244 075abeba8e60a96443d325324e59740b frame00000245 a33be29f57c7031874ac3f006f1e3975 frame00000246
{ "pile_set_name": "Github" }
export { default } from './checkout-confirmation'
{ "pile_set_name": "Github" }
package com.rhwayfun.springboot.configuration.property; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.context.annotation.Configuration; /** * 带前缀属性配置 * 使用@ConfigurationProperties将property的配置映射到这个类的属性中 * * property加载顺序: * * 1. Devtools global settings properties on your home directory (~/.spring-boot-devtools.properties when devtools is active). * 2. @TestPropertySource annotations on your tests. * 3. @SpringBootTest#properties annotation attribute on your tests. * 4. Command line arguments. * 5. Properties from SPRING_APPLICATION_JSON (inline JSON embedded in an environment variable or system property) * 6. ServletConfig init parameters. * 7. ServletContext init parameters. * 8. JNDI attributes from java:comp/env. * 9. Java System properties (System.getProperties()). * 10. OS environment variables. * 11. A RandomValuePropertySource that only has properties in random.*. * 12. Profile-specific application properties outside of your packaged jar (application-{profile}.properties and YAML variants) * 13. Profile-specific application properties packaged inside your jar (application-{profile}.properties and YAML variants) * 14. Application properties outside of your packaged jar (application.properties and YAML variants). * 15. Application properties packaged inside your jar (application.properties and YAML variants). * 16. @PropertySource annotations on your @Configuration classes. * 17. Default properties (specified using SpringApplication.setDefaultProperties). * * @author happyxiaofan * @since 0.0.1 */ @Configuration @ConfigurationProperties(prefix = "my.config") public class SimpleProperty { private String app; private String user; private int age; private String email; private String blog; private String github; public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getBlog() { return blog; } public void setBlog(String blog) { this.blog = blog; } public String getGithub() { return github; } public void setGithub(String github) { this.github = github; } }
{ "pile_set_name": "Github" }
0 0 18 74 9 30 0 61 0 15 41 9 0 0 7 14 27 17 0 9 2 17 25 2 30 5 19 36 0 0 0 0 0 26 0 0 5 0 9 12 3 2 45 33 25 33 0 36 34 29 12 5 81 3 0 2 10 29 76 2 0 21 66 0 0 0 0 0 0 2 0 0 0 0 0 41 0 72 0 2 5 5 5 24 0 22 2 31 26 34 5 0 0 27 0 0 0 2 2 47 48 0 37 25 27 28 2 14 7 4 0 23 28 0 0 0 0 0 0 0 0 0 14 24 29 26 0 9 21 24 0 2 3 34 3 3 15 29 0 0 0 2 0 0 0 0 0 45 0 5 2 5 5 40 0 0 2 9 2 84 71 0 0 0 0 0 0 0 0 0 0 4 17 7 2 28 3 0 0 0 2 0 20 2 12 0 2 63 0 3 66 0 25 1 0 70 26 12 39 0 0 0 3 69 0 2 2 3 7 70 31 0 0 0 0 0 29 31 4 26 0 2 56 42 15 36 29 2 0 0 0 0 2 28 0 25 3 0 0 7 0 24 0 0 10 8 0 31 0 23 51 0 0 0 0 23 59 37 0 3 2 63 2 2 0 2 0 2 3 52 0 4 0 0 0 0 0 0 0 0 6 2 8 2 1 4 39 2
{ "pile_set_name": "Github" }
--- layout: feature title: 'Tense' shortdef: 'tense' udver: '2' --- ### Description Tense feature matches the inflectional endings in verbs. In Uralic grammars there have been various practices in refering to present/future tense and past/preterite tense, in Universal dependencies we use `Pres` for common non-past and `Past` for common past, unless language has more complex tense system. Many grammars give descriptions of e.g. perfect and pluperfect tenses, but if it's based on auxiliary verb constructions, this is not marked on UD level.
{ "pile_set_name": "Github" }
<?php /** * Efficiently run operations on batches of results for any function * that supports an options array. * * This is usually used with elgg_get_entities() and friends, * elgg_get_annotations(), and elgg_get_metadata(). * * If you pass a valid PHP callback, all results will be run through that * callback. You can still foreach() through the result set after. Valid * PHP callbacks can be a string, an array, or a closure. * {@link http://php.net/manual/en/language.pseudo-types.php} * * The callback function must accept 3 arguments: an entity, the getter * used, and the options used. * * Results from the callback are stored in callbackResult. If the callback * returns only booleans, callbackResults will be the combined result of * all calls. If no entities are processed, callbackResults will be null. * * If the callback returns anything else, callbackresult will be an indexed * array of whatever the callback returns. If returning error handling * information, you should include enough information to determine which * result you're referring to. * * Don't combine returning bools and returning something else. * * Note that returning false will not stop the foreach. * * @warning If your callback or foreach loop deletes or disable entities * you MUST call setIncrementOffset(false) or set that when instantiating. * This forces the offset to stay what it was in the $options array. * * @example * <code> * // using foreach * $batch = new ElggBatch('elgg_get_entities', array()); * $batch->setIncrementOffset(false); * * foreach ($batch as $entity) { * $entity->disable(); * } * * // using both a callback * $callback = function($result, $getter, $options) { * var_dump("Looking at annotation id: $result->id"); * return true; * } * * $batch = new ElggBatch('elgg_get_annotations', array('guid' => 2), $callback); * </code> * * @package Elgg.Core * @subpackage DataModel * @link http://docs.elgg.org/DataModel/ElggBatch * @since 1.8 */ class ElggBatch implements Iterator { /** * The objects to interator over. * * @var array */ private $results = array(); /** * The function used to get results. * * @var mixed A string, array, or closure, or lamda function */ private $getter = null; /** * The number of results to grab at a time. * * @var int */ private $chunkSize = 25; /** * A callback function to pass results through. * * @var mixed A string, array, or closure, or lamda function */ private $callback = null; /** * Start after this many results. * * @var int */ private $offset = 0; /** * Stop after this many results. * * @var int */ private $limit = 0; /** * Number of processed results. * * @var int */ private $retrievedResults = 0; /** * The index of the current result within the current chunk * * @var int */ private $resultIndex = 0; /** * The index of the current chunk * * @var int */ private $chunkIndex = 0; /** * The number of results iterated through * * @var int */ private $processedResults = 0; /** * Is the getter a valid callback * * @var bool */ private $validGetter = null; /** * The result of running all entities through the callback function. * * @var mixed */ public $callbackResult = null; /** * If false, offset will not be incremented. This is used for callbacks/loops that delete. * * @var bool */ private $incrementOffset = true; /** * Batches operations on any elgg_get_*() or compatible function that supports * an options array. * * Instead of returning all objects in memory, it goes through $chunk_size * objects, then requests more from the server. This avoids OOM errors. * * @param string $getter The function used to get objects. Usually * an elgg_get_*() function, but can be any valid PHP callback. * @param array $options The options array to pass to the getter function. If limit is * not set, 10 is used as the default. In most cases that is not * what you want. * @param mixed $callback An optional callback function that all results will be passed * to upon load. The callback needs to accept $result, $getter, * $options. * @param int $chunk_size The number of entities to pull in before requesting more. * You have to balance this between running out of memory in PHP * and hitting the db server too often. * @param bool $inc_offset Increment the offset on each fetch. This must be false for * callbacks that delete rows. You can set this after the * object is created with {@see ElggBatch::setIncrementOffset()}. */ public function __construct($getter, $options, $callback = null, $chunk_size = 25, $inc_offset = true) { $this->getter = $getter; $this->options = $options; $this->callback = $callback; $this->chunkSize = $chunk_size; $this->setIncrementOffset($inc_offset); if ($this->chunkSize <= 0) { $this->chunkSize = 25; } // store these so we can compare later $this->offset = elgg_extract('offset', $options, 0); $this->limit = elgg_extract('limit', $options, 10); // if passed a callback, create a new ElggBatch with the same options // and pass each to the callback. if ($callback && is_callable($callback)) { $batch = new ElggBatch($getter, $options, null, $chunk_size, $inc_offset); $all_results = null; foreach ($batch as $result) { if (is_string($callback)) { $result = $callback($result, $getter, $options); } else { $result = call_user_func_array($callback, array($result, $getter, $options)); } if (!isset($all_results)) { if ($result === true || $result === false || $result === null) { $all_results = $result; } else { $all_results = array(); } } if (($result === true || $result === false || $result === null) && !is_array($all_results)) { $all_results = $result && $all_results; } else { $all_results[] = $result; } } $this->callbackResult = $all_results; } } /** * Fetches the next chunk of results * * @return bool */ private function getNextResultsChunk() { // reset memory caches after first chunk load if ($this->chunkIndex > 0) { global $DB_QUERY_CACHE, $ENTITY_CACHE; $DB_QUERY_CACHE = $ENTITY_CACHE = array(); } // always reset results. $this->results = array(); if (!isset($this->validGetter)) { $this->validGetter = is_callable($this->getter); } if (!$this->validGetter) { return false; } $limit = $this->chunkSize; // if someone passed limit = 0 they want everything. if ($this->limit != 0) { if ($this->retrievedResults >= $this->limit) { return false; } // if original limit < chunk size, set limit to original limit // else if the number of results we'll fetch if greater than the original limit if ($this->limit < $this->chunkSize) { $limit = $this->limit; } elseif ($this->retrievedResults + $this->chunkSize > $this->limit) { // set the limit to the number of results remaining in the original limit $limit = $this->limit - $this->retrievedResults; } } if ($this->incrementOffset) { $offset = $this->offset + $this->retrievedResults; } else { $offset = $this->offset; } $current_options = array( 'limit' => $limit, 'offset' => $offset ); $options = array_merge($this->options, $current_options); $getter = $this->getter; if (is_string($getter)) { $this->results = $getter($options); } else { $this->results = call_user_func_array($getter, array($options)); } if ($this->results) { $this->chunkIndex++; $this->resultIndex = 0; $this->retrievedResults += count($this->results); return true; } else { return false; } } /** * Increment the offset from the original options array? Setting to * false is required for callbacks that delete rows. * * @param bool $increment Set to false when deleting data * @return void */ public function setIncrementOffset($increment = true) { $this->incrementOffset = (bool) $increment; } /** * Implements Iterator */ /** * PHP Iterator Interface * * @see Iterator::rewind() * @return void */ public function rewind() { $this->resultIndex = 0; $this->retrievedResults = 0; $this->processedResults = 0; // only grab results if we haven't yet or we're crossing chunks if ($this->chunkIndex == 0 || $this->limit > $this->chunkSize) { $this->chunkIndex = 0; $this->getNextResultsChunk(); } } /** * PHP Iterator Interface * * @see Iterator::current() * @return mixed */ public function current() { return current($this->results); } /** * PHP Iterator Interface * * @see Iterator::key() * @return int */ public function key() { return $this->processedResults; } /** * PHP Iterator Interface * * @see Iterator::next() * @return mixed */ public function next() { // if we'll be at the end. if (($this->processedResults + 1) >= $this->limit && $this->limit > 0) { $this->results = array(); return false; } // if we'll need new results. if (($this->resultIndex + 1) >= $this->chunkSize) { if (!$this->getNextResultsChunk()) { $this->results = array(); return false; } $result = current($this->results); } else { // the function above resets the indexes, so only inc if not // getting new set $this->resultIndex++; $result = next($this->results); } $this->processedResults++; return $result; } /** * PHP Iterator Interface * * @see Iterator::valid() * @return bool */ public function valid() { if (!is_array($this->results)) { return false; } $key = key($this->results); return ($key !== NULL && $key !== FALSE); } }
{ "pile_set_name": "Github" }
// Copyright (c) 2012-2014 The Bitcoin developers // Copyright (c) 2014-2015 The Dash developers // Copyright (c) 2015-2018 The Luxcore developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef BITCOIN_RPCSERVER_H #define BITCOIN_RPCSERVER_H #include "amount.h" #include "rpcprotocol.h" #include "uint256.h" #include <list> #include <map> #include <stdint.h> #include <string> #include <httpserver.h> #include <boost/function.hpp> #include "univalue/univalue.h" class CRPCCommand; namespace RPCServer { void OnStarted(boost::function<void ()> slot); void OnStopped(boost::function<void ()> slot); void OnPreCommand(boost::function<void (const CRPCCommand&)> slot); void OnPostCommand(boost::function<void (const CRPCCommand&)> slot); } class CBlockIndex; class CNetAddr; /** Wrapper for UniValue::VType, which includes typeAny: * Used to denote don't care type. Only used by RPCTypeCheckObj */ struct UniValueType { UniValueType(UniValue::VType _type) : typeAny(false), type(_type) {} UniValueType() : typeAny(true) {} bool typeAny; UniValue::VType type; }; class JSONRequest { public: UniValue id; std::string strMethod; UniValue params; bool isLongPolling; /** * If using batch JSON request, this object won't get the underlying HTTPRequest. */ JSONRequest() { id = NullUniValue; params = NullUniValue; req = NULL; isLongPolling = false; }; JSONRequest(HTTPRequest *req); /** * Start long-polling */ void PollStart(); /** * Ping long-poll connection with an empty character to make sure it's still alive. */ void PollPing(); /** * Returns whether the underlying long-poll connection is still alive. */ bool PollAlive(); /** * End a long poll request. */ void PollCancel(); /** * Return the JSON result of a long poll request */ void PollReply(const UniValue& result); void parse(const UniValue& valRequest); // FIXME: make this private? HTTPRequest *req; }; class JSONRPCRequest { public: UniValue id; std::string strMethod; UniValue params; bool fHelp; std::string URI; std::string authUser; bool isLongPolling; /** * If using batch JSON request, this object won't get the underlying HTTPRequest. */ JSONRPCRequest() { id = NullUniValue; params = NullUniValue; fHelp = false; req = NULL; isLongPolling = false; }; JSONRPCRequest(HTTPRequest *_req); /** * Start long-polling */ void PollStart(); /** * Ping long-poll connection with an empty character to make sure it's still alive. */ void PollPing(); /** * Returns whether the underlying long-poll connection is still alive. */ bool PollAlive(); /** * End a long poll request. */ void PollCancel(); /** * Return the JSON result of a long poll request */ void PollReply(const UniValue& result); void parse(const UniValue& valRequest); // FIXME: make this private? HTTPRequest *req; }; /** Query whether RPC is running */ bool IsRPCRunning(); /** * Set * the RPC warmup status. When this is done, all RPC calls will error out * immediately with RPC_IN_WARMUP. */ void SetRPCWarmupStatus(const std::string& newStatus); /* Mark warmup as done. RPC calls will be processed from now on. */ void SetRPCWarmupFinished(); /* returns the current warmup state. */ bool RPCIsInWarmup(std::string* statusOut); /** * Type-check arguments; throws JSONRPCError if wrong type given. Does not check that * the right number of arguments are passed, just that any passed are the correct type. * Use like: RPCTypeCheck(params, boost::assign::list_of(str_type)(int_type)(obj_type)); */ void RPCTypeCheck(const UniValue& params, const std::list<UniValue::VType>& typesExpected, bool fAllowNull = false); /** * Check for expected keys/value types in an Object. * Use like: RPCTypeCheck(object, boost::assign::map_list_of("name", str_type)("value", int_type)); */ void RPCTypeCheckObj(const UniValue& o, const std::map<std::string, UniValueType>& typesExpected, bool fAllowNull = false); /** Opaque base class for timers returned by NewTimerFunc. * This provides no methods at the moment, but makes sure that delete * cleans up the whole state. */ class RPCTimerBase { public: virtual ~RPCTimerBase() {} }; /** * RPC timer "driver". */ class RPCTimerInterface { public: virtual ~RPCTimerInterface() {} /** Implementation name */ virtual const char *Name() = 0; /** Factory function for timers. * RPC will call the function to create a timer that will call func in *millis* milliseconds. * @note As the RPC mechanism is backend-neutral, it can use different implementations of timers. * This is needed to cope with the case in which there is no HTTP server, but * only GUI RPC console, and to break the dependency of pcserver on httprpc. */ virtual RPCTimerBase* NewTimer(boost::function<void(void)>& func, int64_t millis) = 0; }; /** Set the factory function for timers */ void RPCSetTimerInterface(RPCTimerInterface *iface); /** Set the factory function for timer, but only, if unset */ void RPCSetTimerInterfaceIfUnset(RPCTimerInterface *iface); /** Unset factory function for timers */ void RPCUnsetTimerInterface(RPCTimerInterface *iface); /** * Run func nSeconds from now. * Overrides previous timer <name> (if any). */ void RPCRunLater(const std::string& name, boost::function<void(void)> func, int64_t nSeconds); typedef UniValue(*rpcfn_type)(const UniValue& params, bool fHelp); class CRPCCommand { public: std::string category; std::string name; rpcfn_type actor; bool okSafeMode; bool threadSafe; bool reqWallet; }; /** * LUX RPC command dispatcher. */ class CRPCTable { private: std::map<std::string, const CRPCCommand*> mapCommands; public: CRPCTable(); const CRPCCommand* operator[](const std::string& name) const; std::string help(std::string name) const; /** * Execute a method. * @param method Method to execute * @param params Array of arguments (JSON objects) * @returns Result of the call. * @throws an exception (UniValue) when an error happens. */ UniValue execute(const std::string& method, const UniValue& params) const; /** * Returns a list of registered commands * @returns List of registered commands. */ std::vector<std::string> listCommands() const; }; extern const CRPCTable tableRPC; /** * Utilities: convert hex-encoded Values * (throws error if not hex). */ extern uint256 ParseHashV(const UniValue& v, std::string strName); extern uint256 ParseHashO(const UniValue& o, std::string strKey); extern std::vector<unsigned char> ParseHexV(const UniValue& v, std::string strName); extern std::vector<unsigned char> ParseHexO(const UniValue& o, std::string strKey); extern int64_t nWalletUnlockTime; extern CAmount AmountFromValue(const UniValue& value); extern double GetDifficulty(const CBlockIndex* blockindex = NULL); extern CBlockIndex* GetLastBlockOfType(const int nPoS); double GetPoWMHashPS(); double GetPoSKernelPS(); extern std::string HelpRequiringPassphrase(); extern std::string HelpExampleCli(std::string methodname, std::string args); extern std::string HelpExampleRpc(std::string methodname, std::string args); extern void EnsureWalletIsUnlocked(); extern UniValue getconnectioncount(const UniValue& params, bool fHelp); // in rpcnet.cpp extern UniValue getpeerinfo(const UniValue& params, bool fHelp); extern UniValue ping(const UniValue& params, bool fHelp); extern UniValue addnode(const UniValue& params, bool fHelp); //extern UniValue disconnectnode(const UniValue& params, bool fHelp); extern UniValue getaddednodeinfo(const UniValue& params, bool fHelp); extern UniValue getnettotals(const UniValue& params, bool fHelp); extern UniValue setban(const UniValue& params, bool fHelp); extern UniValue listbanned(const UniValue& params, bool fHelp); extern UniValue clearbanned(const UniValue& params, bool fHelp); extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importaddress(const UniValue& params, bool fHelp); extern UniValue importpubkey(const UniValue& params, bool fHelp); extern UniValue dumphdinfo(const UniValue& params, bool fHelp); extern UniValue dumpwallet(const UniValue& params, bool fHelp); extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue bip38encrypt(const UniValue& params, bool fHelp); extern UniValue bip38decrypt(const UniValue& params, bool fHelp); extern UniValue importprunedfunds(const UniValue& params, bool fHelp); extern UniValue removeprunedfunds(const UniValue& params, bool fHelp); extern UniValue dumpprivkey(const UniValue& params, bool fHelp); // in rpcdump.cpp extern UniValue importprivkey(const UniValue& params, bool fHelp); extern UniValue importaddress(const UniValue& params, bool fHelp); extern UniValue dumpwallet(const UniValue& params, bool fHelp); extern UniValue importwallet(const UniValue& params, bool fHelp); extern UniValue bip38encrypt(const UniValue& params, bool fHelp); extern UniValue bip38decrypt(const UniValue& params, bool fHelp); extern UniValue setstakesplitthreshold(const UniValue& params, bool fHelp); extern UniValue getstakesplitthreshold(const UniValue& params, bool fHelp); extern UniValue getgenerate(const UniValue& params, bool fHelp); // in rpcmining.cpp extern UniValue setgenerate(const UniValue& params, bool fHelp); extern UniValue getnetworkhashps(const UniValue& params, bool fHelp); extern UniValue gethashespersec(const UniValue& params, bool fHelp); extern UniValue getmininginfo(const UniValue& params, bool fHelp); extern UniValue prioritisetransaction(const UniValue& params, bool fHelp); extern UniValue getblocktemplate(const UniValue& params, bool fHelp); extern UniValue getwork(const UniValue& params, bool fHelp); extern UniValue submitblock(const UniValue& params, bool fHelp); extern UniValue estimatefee(const UniValue& params, bool fHelp); extern UniValue estimatepriority(const UniValue& params, bool fHelp); extern UniValue estimatesmartfee(const UniValue& params, bool fHelp); extern UniValue estimatesmartpriority(const UniValue& params, bool fHelp); extern UniValue getnewaddress(const UniValue& params, bool fHelp); // in rpcwallet.cpp extern UniValue getaccountaddress(const UniValue& params, bool fHelp); extern UniValue getrawchangeaddress(const UniValue& params, bool fHelp); extern UniValue setaccount(const UniValue& params, bool fHelp); extern UniValue getaccount(const UniValue& params, bool fHelp); extern UniValue getaddressesbyaccount(const UniValue& params, bool fHelp); extern UniValue sendtoaddress(const UniValue& params, bool fHelp); extern UniValue sendtoaddressix(const UniValue& params, bool fHelp); extern UniValue signmessage(const UniValue& params, bool fHelp); extern UniValue verifymessage(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue getreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue getbalance(const UniValue& params, bool fHelp); extern UniValue getunconfirmedbalance(const UniValue& params, bool fHelp); extern UniValue movecmd(const UniValue& params, bool fHelp); extern UniValue sendfrom(const UniValue& params, bool fHelp); extern UniValue sendmany(const UniValue& params, bool fHelp); extern UniValue addmultisigaddress(const UniValue& params, bool fHelp); extern UniValue createmultisig(const UniValue& params, bool fHelp); extern UniValue createwitnessaddress(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaddress(const UniValue& params, bool fHelp); extern UniValue listreceivedbyaccount(const UniValue& params, bool fHelp); extern UniValue listtransactions(const UniValue& params, bool fHelp); extern UniValue listaddressgroupings(const UniValue& params, bool fHelp); extern UniValue listaddressbalances(const UniValue& params, bool fHelp); extern UniValue listaccounts(const UniValue& params, bool fHelp); extern UniValue listsinceblock(const UniValue& params, bool fHelp); extern UniValue gettransaction(const UniValue& params, bool fHelp); extern UniValue abandontransaction(const UniValue& params, bool fHelp); extern UniValue backupwallet(const UniValue& params, bool fHelp); extern UniValue keypoolrefill(const UniValue& params, bool fHelp); extern UniValue walletpassphrase(const UniValue& params, bool fHelp); extern UniValue walletpassphrasechange(const UniValue& params, bool fHelp); extern UniValue walletlock(const UniValue& params, bool fHelp); extern UniValue encryptwallet(const UniValue& params, bool fHelp); extern UniValue validateaddress(const UniValue& params, bool fHelp); extern UniValue getaddressmempool(const UniValue& params, bool fHelp); extern UniValue getaddressutxos(const UniValue& params, bool fHelp); extern UniValue getaddressdeltas(const UniValue& params, bool fHelp); extern UniValue getaddresstxids(const UniValue& params, bool fHelp); extern UniValue getaddressbalance(const UniValue& params, bool fHelp); extern UniValue getspentinfo(const UniValue& params, bool fHelp); extern UniValue purgetxindex(const UniValue& params, bool fHelp); extern UniValue getinfo(const UniValue& params, bool fHelp); extern UniValue getstateinfo(const UniValue& params, bool fHelp); extern UniValue getwalletinfo(const UniValue& params, bool fHelp); extern UniValue getblockchaininfo(const UniValue& params, bool fHelp); extern UniValue getnetworkinfo(const UniValue& params, bool fHelp); extern UniValue setmocktime(const UniValue& params, bool fHelp); extern UniValue reservebalance(const UniValue& params, bool fHelp); extern UniValue multisend(const UniValue& params, bool fHelp); extern UniValue autocombinerewards(const UniValue& params, bool fHelp); extern UniValue getstakingstatus(const UniValue& params, bool fHelp); extern UniValue callcontract(const UniValue& params, bool fHelp); extern UniValue createcontract(const UniValue& params, bool fHelp); extern UniValue sendtocontract(const UniValue& params, bool fHelp); extern UniValue getrawtransaction(const UniValue& params, bool fHelp); // in rcprawtransaction.cpp extern UniValue listunspent(const UniValue& params, bool fHelp); extern UniValue lockunspent(const UniValue& params, bool fHelp); extern UniValue listlockunspent(const UniValue& params, bool fHelp); extern UniValue createrawtransaction(const UniValue& params, bool fHelp); extern UniValue fundrawtransaction(const UniValue& params, bool fHelp); extern UniValue decoderawtransaction(const UniValue& params, bool fHelp); extern UniValue decodescript(const UniValue& params, bool fHelp); extern UniValue signrawtransaction(const UniValue& params, bool fHelp); extern UniValue sendrawtransaction(const UniValue& params, bool fHelp); extern UniValue gethexaddress(const UniValue& params, bool fHelp); extern UniValue fromhexaddress(const UniValue& params, bool fHelp); extern UniValue getblockcount(const UniValue& params, bool fHelp); // in rpcblockchain.cpp extern UniValue getblockhashes(const UniValue& params, bool fHelp); extern UniValue getbestblockhash(const UniValue& params, bool fHelp); extern UniValue getdifficulty(const UniValue& params, bool fHelp); extern UniValue settxfee(const UniValue& params, bool fHelp); extern UniValue getmempoolinfo(const UniValue& params, bool fHelp); extern UniValue getrawmempool(const UniValue& params, bool fHelp); extern UniValue getblockhash(const UniValue& params, bool fHelp); extern UniValue getblock(const UniValue& params, bool fHelp); extern UniValue getblockheader(const UniValue& params, bool fHelp); extern UniValue gettxoutsetinfo(const UniValue& params, bool fHelp); extern UniValue gettxout(const UniValue& params, bool fHelp); extern UniValue verifychain(const UniValue& params, bool fHelp); extern UniValue getchaintips(const UniValue& params, bool fHelp); extern UniValue getchaintxstats(const UniValue& params, bool fHelp); extern UniValue switchnetwork(const UniValue& params, bool fHelp); extern UniValue invalidateblock(const UniValue& params, bool fHelp); extern UniValue reconsiderblock(const UniValue& params, bool fHelp); extern UniValue darksend(const UniValue& params, bool fHelp); extern UniValue spork(const UniValue& params, bool fHelp); extern UniValue masternode(const UniValue& params, bool fHelp); extern UniValue getaccountinfo(const UniValue& params, bool fHelp); //extern UniValue masternodelist(const UniValue& params, bool fHelp); //extern UniValue mnbudget(const UniValue& params, bool fHelp); //extern UniValue mnbudgetvoteraw(const UniValue& params, bool fHelp); //extern UniValue mnfinalbudget(const UniValue& params, bool fHelp); //extern UniValue mnsync(const UniValue& params, bool fHelp); extern UniValue generate(const UniValue& params, bool fHelp); extern UniValue getstorage(const UniValue& params, bool fHelp); extern UniValue listcontracts(const UniValue& params, bool fHelp); extern UniValue gettransactionreceipt(const UniValue& params, bool fHelp); extern UniValue searchlogs(const UniValue& params, bool fHelp); extern UniValue waitforlogs(const UniValue& params, bool fHelp); extern UniValue pruneblockchain(const UniValue& params, bool fHelp); bool StartRPC(); void InterruptRPC(); void StopRPC(); std::string JSONRPCExecBatch(const UniValue& vReq); void RPCNotifyBlockChange(bool ibd, const CBlockIndex* pindex); #endif // BITCOIN_RPCSERVER_H
{ "pile_set_name": "Github" }
/* * 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. */ package com.facebook.fresco.samples.showcase.drawee; import android.graphics.drawable.Animatable; import android.net.Uri; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import androidx.annotation.Nullable; import com.facebook.common.references.CloseableReference; import com.facebook.datasource.RetainingDataSourceSupplier; import com.facebook.drawee.backends.pipeline.Fresco; import com.facebook.drawee.controller.BaseControllerListener; import com.facebook.drawee.controller.ControllerListener; import com.facebook.drawee.view.SimpleDraweeView; import com.facebook.fresco.samples.showcase.BaseShowcaseFragment; import com.facebook.fresco.samples.showcase.R; import com.facebook.imagepipeline.image.CloseableImage; import com.facebook.imagepipeline.image.ImageInfo; import com.facebook.imagepipeline.request.ImageRequest; import java.util.List; public class RetainingDataSourceSupplierFragment extends BaseShowcaseFragment { private List<Uri> mSampleUris; private int mUriIndex = 0; private ControllerListener controllerListener = new BaseControllerListener<ImageInfo>() { @Override public void onFinalImageSet( String id, @Nullable ImageInfo imageInfo, @Nullable Animatable anim) { if (anim != null) { // app-specific logic to enable animation starting anim.start(); } } }; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mSampleUris = sampleUris().getSampleGifUris(); } @Nullable @Override public View onCreateView( LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_drawee_retaining_supplier, container, false); } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final SimpleDraweeView simpleDraweeView = view.findViewById(R.id.drawee_view); final RetainingDataSourceSupplier<CloseableReference<CloseableImage>> retainingSupplier = new RetainingDataSourceSupplier<>(); simpleDraweeView.setController( Fresco.newDraweeControllerBuilder() .setDataSourceSupplier(retainingSupplier) .setControllerListener(controllerListener) .build()); replaceImage(retainingSupplier); simpleDraweeView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View view) { replaceImage(retainingSupplier); } }); } @Override public int getTitleId() { return R.string.drawee_retaining_supplier_title; } private void replaceImage( RetainingDataSourceSupplier<CloseableReference<CloseableImage>> retainingSupplier) { retainingSupplier.replaceSupplier( Fresco.getImagePipeline() .getDataSourceSupplier( ImageRequest.fromUri(getNextUri()), null, ImageRequest.RequestLevel.FULL_FETCH)); } private synchronized Uri getNextUri() { int previousIndex = mUriIndex; mUriIndex = (mUriIndex + 1) % mSampleUris.size(); return mSampleUris.get(previousIndex); } }
{ "pile_set_name": "Github" }
{ "forge_marker": 1, "parent":"thebetweenlands:block/log_rotten_bark_carved", "textures": { "up": "thebetweenlands:blocks/rotten_bark_rotated", "down": "thebetweenlands:blocks/rotten_bark_rotated", "north": "thebetweenlands:blocks/rotten_bark_carved_11", "east": "thebetweenlands:blocks/rotten_bark_carved_11", "south": "thebetweenlands:blocks/rotten_bark_carved_11", "west": "thebetweenlands:blocks/rotten_bark_carved_11" } }
{ "pile_set_name": "Github" }
import { IconDefinition, IconPrefix, IconName } from "@fortawesome/fontawesome-common-types"; export const definition: IconDefinition; export const faPinterest: IconDefinition; export const prefix: IconPrefix; export const iconName: IconName; export const width: number; export const height: number; export const ligatures: string[]; export const unicode: string; export const svgPathData: string;
{ "pile_set_name": "Github" }
/* * CoreShop. * * This source file is subject to the GNU General Public License version 3 (GPLv3) * For the full copyright and license information, please view the LICENSE.md and gpl-3.0.txt * files that are distributed with this source code. * * @copyright Copyright (c) 2015-2020 Dominik Pfaffenbauer (https://www.pfaffenbauer.at) * @license https://www.coreshop.org/license GNU General Public License version 3 (GPLv3) * */ pimcore.registerNS('coreshop.notification.rule.item'); coreshop.notification.rule.item = Class.create(coreshop.rules.item, { iconCls: 'coreshop_icon_notification_rule', url: { save: '/admin/coreshop/notification_rules/save' }, getPanel: function () { var items = this.getItems(); this.panel = new Ext.TabPanel({ activeTab: 0, title: this.data.name, closable: true, deferredRender: false, forceLayout: true, iconCls: this.iconCls, buttons: [{ text: t('save'), iconCls: 'pimcore_icon_apply', handler: this.save.bind(this) }], items: items }); if (this.data.type) { this.reloadTypes(this.data.type); } return this.panel; }, getSettings: function () { var data = this.data; var types = []; this.parentPanel.getConfig().types.forEach(function (type) { types.push([type, t('coreshop_notification_rule_type_' + type)]); }.bind(this)); var typesStore = new Ext.data.ArrayStore({ data: types, fields: ['type', 'typeName'], idProperty: 'type' }); this.settingsForm = Ext.create('Ext.form.Panel', { iconCls: 'coreshop_icon_settings', title: t('settings'), bodyStyle: 'padding:10px;', autoScroll: true, border: false, items: [ { xtype: 'textfield', name: 'name', fieldLabel: t('name'), width: 250, value: data.name }, { xtype: 'checkbox', name: 'active', fieldLabel: t('active'), checked: data.active }, { xtype: 'combo', fieldLabel: t('coreshop_notification_rule_type'), name: 'type', displayField: 'type', valueField: 'type', store: typesStore, value: this.data.type, width: 250, listeners: { change: function (combo, value) { this.reloadTypes(value); }.bind(this) } } ] }); return this.settingsForm; }, getItems: function () { return [ this.getSettings() ]; }, reloadTypes: function (type) { if (this.actions) { this.actions.destroy(); } if (this.conditions) { this.conditions.destroy(); } var items = this.getItemsForType(type); this.panel.add(items); }, getItemsForType: function (type) { var actionContainerClass = this.getActionContainerClass(); var conditionContainerClass = this.getConditionContainerClass(); var allowedActions = this.parentPanel.getActionsForType(type); var allowedConditions = this.parentPanel.getConditionsForType(type); this.actions = new actionContainerClass(allowedActions, type); this.conditions = new conditionContainerClass(allowedConditions, type); var items = [ this.conditions.getLayout(), this.actions.getLayout() ]; // add saved conditions if (this.data.conditions) { Ext.each(this.data.conditions, function (condition) { var conditionType = condition.type.replace(type + '.', ''); if (allowedConditions.indexOf(conditionType) >= 0) { this.conditions.addCondition(conditionType, condition, false); } }.bind(this)); } // add saved actions if (this.data.actions) { Ext.each(this.data.actions, function (action) { var actionType = action.type.replace(type + '.', ''); if (allowedActions.indexOf(actionType) >= 0) { this.actions.addAction(actionType, action, false); } }.bind(this)); } return items; }, getActionContainerClass: function () { return coreshop.notification.rule.action; }, getConditionContainerClass: function () { return coreshop.notification.rule.condition; } });
{ "pile_set_name": "Github" }
// // bind/bind_mf2_cc.hpp - member functions, type<> syntax // // Do not include this header directly. // // Copyright (c) 2001 Peter Dimov and Multi Media Ltd. // Copyright (c) 2008 Peter Dimov // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt // // See http://www.boost.org/libs/bind/bind.html for documentation. // // 0 template<class Rt2, class R, class T, class A1> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf0)<R, T>, typename _bi::list_av_1<A1>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (), A1 a1) { typedef _mfi::BOOST_BIND_MF_NAME(mf0)<R, T> F; typedef typename _bi::list_av_1<A1>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1)); } template<class Rt2, class R, class T, class A1> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf0)<R, T>, typename _bi::list_av_1<A1>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) () const, A1 a1) { typedef _mfi::BOOST_BIND_MF_NAME(cmf0)<R, T> F; typedef typename _bi::list_av_1<A1>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1)); } // 1 template<class Rt2, class R, class T, class B1, class A1, class A2> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf1)<R, T, B1>, typename _bi::list_av_2<A1, A2>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1), A1 a1, A2 a2) { typedef _mfi::BOOST_BIND_MF_NAME(mf1)<R, T, B1> F; typedef typename _bi::list_av_2<A1, A2>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2)); } template<class Rt2, class R, class T, class B1, class A1, class A2> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf1)<R, T, B1>, typename _bi::list_av_2<A1, A2>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1) const, A1 a1, A2 a2) { typedef _mfi::BOOST_BIND_MF_NAME(cmf1)<R, T, B1> F; typedef typename _bi::list_av_2<A1, A2>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2)); } // 2 template<class Rt2, class R, class T, class B1, class B2, class A1, class A2, class A3> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf2)<R, T, B1, B2>, typename _bi::list_av_3<A1, A2, A3>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2), A1 a1, A2 a2, A3 a3) { typedef _mfi::BOOST_BIND_MF_NAME(mf2)<R, T, B1, B2> F; typedef typename _bi::list_av_3<A1, A2, A3>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3)); } template<class Rt2, class R, class T, class B1, class B2, class A1, class A2, class A3> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf2)<R, T, B1, B2>, typename _bi::list_av_3<A1, A2, A3>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2) const, A1 a1, A2 a2, A3 a3) { typedef _mfi::BOOST_BIND_MF_NAME(cmf2)<R, T, B1, B2> F; typedef typename _bi::list_av_3<A1, A2, A3>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3)); } // 3 template<class Rt2, class R, class T, class B1, class B2, class B3, class A1, class A2, class A3, class A4> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf3)<R, T, B1, B2, B3>, typename _bi::list_av_4<A1, A2, A3, A4>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3), A1 a1, A2 a2, A3 a3, A4 a4) { typedef _mfi::BOOST_BIND_MF_NAME(mf3)<R, T, B1, B2, B3> F; typedef typename _bi::list_av_4<A1, A2, A3, A4>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class A1, class A2, class A3, class A4> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf3)<R, T, B1, B2, B3>, typename _bi::list_av_4<A1, A2, A3, A4>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3) const, A1 a1, A2 a2, A3 a3, A4 a4) { typedef _mfi::BOOST_BIND_MF_NAME(cmf3)<R, T, B1, B2, B3> F; typedef typename _bi::list_av_4<A1, A2, A3, A4>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4)); } // 4 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class A1, class A2, class A3, class A4, class A5> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf4)<R, T, B1, B2, B3, B4>, typename _bi::list_av_5<A1, A2, A3, A4, A5>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { typedef _mfi::BOOST_BIND_MF_NAME(mf4)<R, T, B1, B2, B3, B4> F; typedef typename _bi::list_av_5<A1, A2, A3, A4, A5>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class A1, class A2, class A3, class A4, class A5> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf4)<R, T, B1, B2, B3, B4>, typename _bi::list_av_5<A1, A2, A3, A4, A5>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5) { typedef _mfi::BOOST_BIND_MF_NAME(cmf4)<R, T, B1, B2, B3, B4> F; typedef typename _bi::list_av_5<A1, A2, A3, A4, A5>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5)); } // 5 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class A1, class A2, class A3, class A4, class A5, class A6> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf5)<R, T, B1, B2, B3, B4, B5>, typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { typedef _mfi::BOOST_BIND_MF_NAME(mf5)<R, T, B1, B2, B3, B4, B5> F; typedef typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class A1, class A2, class A3, class A4, class A5, class A6> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf5)<R, T, B1, B2, B3, B4, B5>, typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6) { typedef _mfi::BOOST_BIND_MF_NAME(cmf5)<R, T, B1, B2, B3, B4, B5> F; typedef typename _bi::list_av_6<A1, A2, A3, A4, A5, A6>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6)); } // 6 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class A1, class A2, class A3, class A4, class A5, class A6, class A7> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf6)<R, T, B1, B2, B3, B4, B5, B6>, typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { typedef _mfi::BOOST_BIND_MF_NAME(mf6)<R, T, B1, B2, B3, B4, B5, B6> F; typedef typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class A1, class A2, class A3, class A4, class A5, class A6, class A7> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf6)<R, T, B1, B2, B3, B4, B5, B6>, typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7) { typedef _mfi::BOOST_BIND_MF_NAME(cmf6)<R, T, B1, B2, B3, B4, B5, B6> F; typedef typename _bi::list_av_7<A1, A2, A3, A4, A5, A6, A7>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7)); } // 7 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf7)<R, T, B1, B2, B3, B4, B5, B6, B7>, typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { typedef _mfi::BOOST_BIND_MF_NAME(mf7)<R, T, B1, B2, B3, B4, B5, B6, B7> F; typedef typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf7)<R, T, B1, B2, B3, B4, B5, B6, B7>, typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8) { typedef _mfi::BOOST_BIND_MF_NAME(cmf7)<R, T, B1, B2, B3, B4, B5, B6, B7> F; typedef typename _bi::list_av_8<A1, A2, A3, A4, A5, A6, A7, A8>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8)); } // 8 template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class B8, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(mf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8>, typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7, B8), A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { typedef _mfi::BOOST_BIND_MF_NAME(mf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8> F; typedef typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8, a9)); } template<class Rt2, class R, class T, class B1, class B2, class B3, class B4, class B5, class B6, class B7, class B8, class A1, class A2, class A3, class A4, class A5, class A6, class A7, class A8, class A9> _bi::bind_t<Rt2, _mfi::BOOST_BIND_MF_NAME(cmf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8>, typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type> BOOST_BIND(boost::type<Rt2>, R (BOOST_BIND_MF_CC T::*f) (B1, B2, B3, B4, B5, B6, B7, B8) const, A1 a1, A2 a2, A3 a3, A4 a4, A5 a5, A6 a6, A7 a7, A8 a8, A9 a9) { typedef _mfi::BOOST_BIND_MF_NAME(cmf8)<R, T, B1, B2, B3, B4, B5, B6, B7, B8> F; typedef typename _bi::list_av_9<A1, A2, A3, A4, A5, A6, A7, A8, A9>::type list_type; return _bi::bind_t<Rt2, F, list_type>(F(f), list_type(a1, a2, a3, a4, a5, a6, a7, a8, a9)); }
{ "pile_set_name": "Github" }
/* * Copyright (c) 2020, the SerenityOS developers. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. 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. * * 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 HOLDER 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. */ #include <LibELF/Loader.h> #include <stddef.h> #include <stdint.h> extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { ELF::Loader::create(data, size, /*verbose_logging=*/false); return 0; }
{ "pile_set_name": "Github" }
// Load modules var Url = require('url'); var Code = require('code'); var Hawk = require('../lib'); var Lab = require('lab'); // Declare internals var internals = {}; // Test shortcuts var lab = exports.lab = Lab.script(); var describe = lab.experiment; var it = lab.test; var expect = Code.expect; describe('Hawk', function () { var credentialsFunc = function (id, callback) { var credentials = { id: id, key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn', algorithm: (id === '1' ? 'sha1' : 'sha256'), user: 'steve' }; return callback(null, credentials); }; it('generates a header then successfully parse it (configuration)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials1, ext: 'some-app-data' }).field; expect(req.authorization).to.exist(); Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (node request)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (absolute request uri)', function (done) { var req = { method: 'POST', url: 'http://example.com:8080/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' }); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(true); done(); }); }); }); it('generates a header then successfully parse it (no server header options)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts)).to.equal(true); done(); }); }); }); it('generates a header then fails to parse it (missing server header hash)', function (done) { var req = { method: 'POST', url: '/resource/4?filter=a', headers: { host: 'example.com:8080', 'content-type': 'text/plain;x=y' } }; var payload = 'some not so random text'; credentialsFunc('123456', function (err, credentials1) { var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] }); req.headers.authorization = reqHeader.field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload(payload, credentials2, artifacts, req.headers['content-type'])).to.equal(true); var res = { headers: { 'content-type': 'text/plain' } }; res.headers['server-authorization'] = Hawk.server.header(credentials2, artifacts); expect(res.headers['server-authorization']).to.exist(); expect(Hawk.client.authenticate(res, credentials2, artifacts, { payload: 'some reply' })).to.equal(false); done(); }); }); }); it('generates a header then successfully parse it (with hash)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it then validate payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(Hawk.server.authenticatePayload('hola!', credentials2, artifacts)).to.be.true(); expect(Hawk.server.authenticatePayload('hello!', credentials2, artifacts)).to.be.false(); done(); }); }); }); it('generates a header then successfully parses and validates payload', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); done(); }); }); }); it('generates a header then successfully parse it (app)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); done(); }); }); }); it('generates a header then successfully parse it (app, dlg)', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.not.exist(); expect(credentials2.user).to.equal('steve'); expect(artifacts.ext).to.equal('some-app-data'); expect(artifacts.app).to.equal('asd23ased'); expect(artifacts.dlg).to.equal('23434szr3q4d'); done(); }); }); }); it('generates a header then fail authentication due to bad hash', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, payload: 'hola!', ext: 'some-app-data' }).field; Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(err.output.payload.message).to.equal('Bad payload hash'); done(); }); }); }); it('generates a header for one resource then fail to authenticate another', function (done) { var req = { method: 'GET', url: '/resource/4?filter=a', host: 'example.com', port: 8080 }; credentialsFunc('123456', function (err, credentials1) { req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials1, ext: 'some-app-data' }).field; req.url = '/something/else'; Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials2, artifacts) { expect(err).to.exist(); expect(credentials2).to.exist(); done(); }); }); }); });
{ "pile_set_name": "Github" }
Cython==0.29.21 numpy==1.19.1 cachetools==4.1.1 ruamel.yaml==0.16.10 eth-account==0.5.2 aioconsole==0.2.1 aiokafka==0.6.0 SQLAlchemy==1.3.18 binance==0.3 ujson==3.1.0 websockets==8.1 signalr-client-aio==0.0.1.6.2 web3==5.12.0 prompt-toolkit==3.0.5 0x-order-utils==4.0.0 0x-contract-wrappers==2.0.0 eth-bloom==1.0.3 pyperclip==1.8.0 telegram==0.0.1 jwt==1.0.0 mypy-extensions==0.4.3 python-telegram-bot==12.8 python-binance==0.7.5 pandas==1.1.0 aiohttp==3.6.2
{ "pile_set_name": "Github" }
/* * Copyright (c) Enalean, 2019-Present. All Rights Reserved. * * This file is a part of Tuleap. * * Tuleap 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. * * Tuleap 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 Tuleap. If not, see <http://www.gnu.org/licenses/>. */ import Vue from "vue"; import { Component, Prop } from "vue-property-decorator"; import { ColumnDefinition } from "../../../../../type"; @Component export default class ClassesForCollapsedColumnMixin extends Vue { @Prop({ required: true }) readonly column!: ColumnDefinition; get classes(): string[] { if (!this.column.is_collapsed) { return []; } const classes = ["taskboard-cell-collapsed"]; if (this.column.has_hover) { classes.push("taskboard-cell-collapsed-hover"); } return classes; } }
{ "pile_set_name": "Github" }
<?xml version="1.0" encoding="UTF-8"?> <ajxp_plugin label="CONF_MESSAGE[Notification Center]" description="CONF_MESSAGE[Handle users watches and notifications]" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="file:../core.ajaxplorer/ajxp_registry.xsd"> <class_definition classname="Pydio\Notification\Core\NotificationCenter" filename="plugins/core.notifications/NotificationCenter.php"/> <client_settings> <resources> <i18n namespace="notification.tpl.short" path="plugins/core.notifications/templates/short"/> <i18n namespace="notification.tpl.long" path="plugins/core.notifications/templates/long"/> <i18n namespace="notification.tpl.group" path="plugins/core.notifications/templates/group"/> <i18n namespace="notification.tpl.block" path="plugins/core.notifications/templates/block"/> <i18n namespace="notification.tpl.location" path="plugins/core.notifications/templates/location"/> <i18n namespace="notification_center" path="plugins/core.notifications/res/i18n"/> <js className="PydioNotifications" file="plugins/core.notifications/res/build/PydioNotifications.js" depends="React,PydioComponents"/> </resources> </client_settings> <server_settings> <param name="activate_notifications" scope="user" description="CONF_MESSAGE[Activate desktop notifications]" label="CONF_MESSAGE[Desktop Notifications]" type="button" choices="run_client_action:activateDesktopNotifications" expose="true" editable="true"/> <global_param name="USER_EVENTS" description="CONF_MESSAGE[Display a new entry with all events happening on a user workspaces, and alerts. An SQL database must be setup for the FEED_DRIVER configuration.]" label="CONF_MESSAGE[User events and alerts]" type="boolean" default="false"/> <global_param name="SHOW_WORKSPACES_ACTIVITY" label="CONF_MESSAGE[Display Workspaces Activity]" description="CONF_MESSAGE[Display workspaces activity to the users in the right-hand information panel]" type="boolean" default="true"/> <global_param type="plugin_instance:feed" name="UNIQUE_FEED_INSTANCE" group="CONF_MESSAGE[Instance Params]" label="CONF_MESSAGE[Feed Instance]" description="CONF_MESSAGE[Choose the plugin]" mandatory="true" default="feed.sql"/> </server_settings> <registry_contributions> <actions> <action name="get_my_feed"> <processing> <serverCallback methodName="loadUserFeed"/> </processing> </action> <action name="feed"> <rightsContext adminOnly="false" noUser="false" read="false" userLogged="only" write="false"/> <processing> <serverCallback methodName="loadUserFeed" restParams="/feed_type/path+" developerComment="Load an activity feed for the given node. Filtered by what the current user is authorized to see"> <input_param name="path" type="path" description="Optional filter to get activity on a file or a folder"/> <input_param name="format" type="string" description="html, json, xml, array (internal value)"/> <input_param name="feed_type" type="string" description="notif, alert or all"/> <input_param name="offset" type="integer" description="Offset for pagination"/> <input_param name="limit" type="integer" description="Limit for pagination"/> <input_param name="merge_description" type="boolean" description="Wether to merge notification title and description in text"/> <input_param name="merge_description_as_label" type="boolean" description="Wether to merge notification title and description in title"/> <input_param name="current_repository" type="boolean" description="Wether to get activity from current repository (true), or compute all from authorized repositories for user (false)"/> </serverCallback> </processing> </action> <action name="clear_feed"> <processing><serverCallback methodName="clearUserFeed" restParams="/context_type/context_value"> <input_param name="context_type" type="string" description="all|repository|user"/> <input_param name="context_value" type="string" description="Either empty, or a repo ID, or a userId depending on the context_type"/> </serverCallback></processing> </action> <action name="dismiss_user_alert"> <gui text="notification_center.7" title="notification_center.7" iconClass="mdi mdi-close-circle" src="notification_center/ICON_SIZE/feed.png" accessKey="" hasAccessKey="false"> <context selection="true" dir="" recycle="true" actionBar="true" actionBarGroup="inline-notifications" contextMenu="false" infoPanel="false"/> <selectionContext dir="true" file="true" recycle="false" unique="true"/> </gui> <rightsContext adminOnly="false" noUser="true" read="false" userLogged="only" write="false"/> <processing> <clientCallback module="PydioCoreActions.Callbacks.dismissUserAlert"/> <serverCallback methodName="dismissUserAlert" restParams="/alert_id/occurences" developerComment="Dismiss one or more occurences of alerts"> <input_param name="alert_id" type="integer" description="Id passed in /feed action list"/> <input_param name="occurences" type="integer" description="1 or more"/> </serverCallback> </processing> </action> <action name="update_alerts_last_read"> <processing> <serverCallback methodName="updateAlertsLastRead" restParams="/repository_scope"> <input_param name="repository_scope" type="string" description="all|repositoryId"/> </serverCallback> </processing> </action> <action name="load_user_recent_items"> <processing> <serverCallback methodName="loadRecentItemsList" restParams="/"/> </processing> </action> <action name="activateDesktopNotifications"> <gui src="" iconClass="icon-rss" text="notification_center.1" title="notification_title.2"> <context dir="true" recycle="true" selection="false"/> </gui> <processing> <clientCallback module="PydioCoreActions.Callbacks.activateDesktopNotifications"/> </processing> </action> </actions> <hooks> <serverCallback methodName="persistChangeHookToFeed" hookName="node.change" defer="true"/> <serverCallback methodName="persistReadHookToRecentList" hookName="node.read"/> <serverCallback methodName="persistNotificationToAlerts" hookName="msg.notification"/> <serverCallback methodName="loadRepositoryInfo" hookName="repository.load_info"/> <serverCallback methodName="shareAssignRight" hookName="node.share.assign_right"/> </hooks> <client_configs> <component_config component="InfoPanel"> <infoPanel mime="ajxp_root_node,generic_dir,generic_file" reactComponent="PydioNotifications.ActivityPanel"/> </component_config> <component_config component="AjxpReactComponent::left_navigator"> <additional_content id="navigation_alerts" position="0" type="ListProvider" options='{"title":"notification_center.3", "titleClassName":"colorcode-alert", "startOpen":true, "dataModelBadge":{"property":"metadata","metadata_sum":"event_occurence", "className":"alerts_number_badge"}, "fit":"content","silentLoading":true,"actionBarGroups":["inline-notifications"],"nodeProviderProperties":{"get_action":"get_my_feed", "connexion_discrete":true, "format":"xml", "current_repository":"true", "feed_type":"alert", "merge_description":"false"},"reloadOnServerMessage":"tree/reload_user_feed", "connexion_discrete":true, "tipAttribute":"event_description_long", "emptyChildrenMessage":"notification_center.8"}'/> </component_config> </client_configs> </registry_contributions> <dependencies> <activePlugin pluginName="core.conf"/> </dependencies> </ajxp_plugin>
{ "pile_set_name": "Github" }
// Copyright (c) 2009-2019 The Regents of the University of Michigan // This file is part of the HOOMD-blue project, released under the BSD 3-Clause License. // Maintainers: jglaser, pschwende /*! \file GlobalArray.h \brief Defines the GlobalArray class */ /*! GlobalArray internally uses managed memory to store data, to allow buffers being accessed from multiple devices. cudaMemAdvise() can be called on GlobalArray's data, which is obtained using ::get(). GlobalArray<> supports all functionality that GPUArray<> does, and should eventually replace GPUArray. In fact, for performance considerations in single GPU situations, GlobalArray internally falls back on GPUArray (and whenever it doesn't have an ExecutionConfiguration). This behavior is controlled by the result of ExecutionConfiguration::allConcurrentManagedAccess(). One difference to GPUArray is that GlobalArray doesn't zero its memory space, so it is important to explicitly initialize the data. Internally, GlobalArray<> uses a smart pointer to comply with RAII semantics. As for GPUArray, access to the data is provided through ArrayHandle<> objects, with proper access_mode and access_location flags. */ #pragma once #ifdef ENABLE_CUDA #include <cuda_runtime.h> #endif #include <memory> #include "GPUArray.h" #include "MemoryTraceback.h" #include <type_traits> #include <string> #include <unistd.h> #include <vector> #include <sstream> #define checkAcquired(a) { \ assert(!(a).m_acquired); \ if ((a).m_acquired) \ { \ throw std::runtime_error("GlobalArray already acquired - ArrayHandle scoping mistake?"); \ } \ } #define TAG_ALLOCATION(array) { \ array.setTag(std::string(#array)); \ } namespace hoomd { namespace detail { #ifdef __GNUC__ #define GCC_VERSION (__GNUC__ * 10000 \ + __GNUC_MINOR__ * 100 \ + __GNUC_PATCHLEVEL__) /* Test for GCC < 5.0 */ #if GCC_VERSION < 50000 // work around GCC missing feature #define NO_STD_ALIGN // https://stackoverflow.com/questions/27064791/stdalign-not-supported-by-g4-9 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=57350 inline void *my_align( std::size_t alignment, std::size_t size, void *&ptr, std::size_t &space ) { std::uintptr_t pn = reinterpret_cast< std::uintptr_t >( ptr ); std::uintptr_t aligned = ( pn + alignment - 1 ) & - alignment; std::size_t padding = aligned - pn; if ( space < size + padding ) return nullptr; space -= padding; return ptr = reinterpret_cast< void * >( aligned ); } #endif #endif template<class T> class managed_deleter { public: //! Default constructor managed_deleter() : m_use_device(false), m_N(0), m_allocation_ptr(nullptr), m_allocation_bytes(0) {} //! Ctor /*! \param exec_conf Execution configuration \param use_device whether the array is managed or on the host \param N number of elements \param allocation_ptr true start of allocation, before alignment \param allocation_bytes Size of allocation */ managed_deleter(std::shared_ptr<const ExecutionConfiguration> exec_conf, bool use_device, std::size_t N, void *allocation_ptr, size_t allocation_bytes) : m_exec_conf(exec_conf), m_use_device(use_device), m_N(N), m_allocation_ptr(allocation_ptr), m_allocation_bytes(allocation_bytes) { } //! Set the tag void setTag(const std::string& tag) { m_tag = tag; } //! Destroy the items and delete the managed array /*! \param ptr Start of aligned memory allocation */ void operator()(T *ptr) { if (ptr == nullptr) return; if (!m_exec_conf) return; #ifdef ENABLE_CUDA if (m_use_device) { cudaDeviceSynchronize(); CHECK_CUDA_ERROR(); } #endif // we used placement new in the allocation, so call destructors explicitly for (std::size_t i = 0; i < m_N; ++i) { ptr[i].~T(); } #ifdef ENABLE_CUDA if (m_use_device) { std::ostringstream oss; oss << "Freeing " << m_allocation_bytes << " bytes of managed memory"; if (m_tag != "") oss << " [" << m_tag << "]"; oss << std::endl; this->m_exec_conf->msg->notice(10) << oss.str(); cudaFree(m_allocation_ptr); CHECK_CUDA_ERROR(); } else #endif { free(m_allocation_ptr); } // update memory allocation table if (m_exec_conf->getMemoryTracer()) this->m_exec_conf->getMemoryTracer()->unregisterAllocation(reinterpret_cast<const void *>(ptr), sizeof(T)*m_N); } private: std::shared_ptr<const ExecutionConfiguration> m_exec_conf; //!< The execution configuration bool m_use_device; //!< Whether to use cudaMallocManaged unsigned int m_N; //!< Number of elements in array void *m_allocation_ptr; //!< Start of unaligned allocation size_t m_allocation_bytes; //!< Size of actual allocation std::string m_tag; //!< Name of the array }; #ifdef ENABLE_CUDA class event_deleter { public: //! Default constructor event_deleter() {} //! Constructor with execution configuration /*! \param exec_conf The execution configuration (needed for CHECK_CUDA_ERROR) */ event_deleter(std::shared_ptr<const ExecutionConfiguration> exec_conf) : m_exec_conf(exec_conf) { } //! Destroy the event and free the memory location /*! \param ptr Start of memory area */ void operator()(cudaEvent_t *ptr) { cudaEventDestroy(*ptr); CHECK_CUDA_ERROR(); delete ptr; } private: std::shared_ptr<const ExecutionConfiguration> m_exec_conf; //!< The execution configuration }; #endif } // end namespace detail } // end namespace hoomd //! Forward declarations template<class T> class GlobalArrayDispatch; template<class T> class ArrayHandle; //! Definition of GlobalArray using CRTP template<class T> class GlobalArray : public GPUArrayBase<T, GlobalArray<T> > { public: //! Empty constructor GlobalArray() : m_num_elements(0), m_pitch(0), m_height(0), m_acquired(false), m_align_bytes(0), m_is_managed(false) { } /*! Allocate a 1D array in managed memory \param num_elements Number of elements in array \param exec_conf The current execution configuration */ GlobalArray(unsigned int num_elements, std::shared_ptr<const ExecutionConfiguration> exec_conf, const std::string& tag = std::string(), bool force_managed=false) : m_exec_conf(exec_conf), #ifndef ALWAYS_USE_MANAGED_MEMORY // explicit copy should be elided m_fallback((exec_conf->allConcurrentManagedAccess() || (force_managed && exec_conf->isCUDAEnabled())) ? GPUArray<T>() : GPUArray<T>(num_elements, exec_conf)), #endif m_num_elements(num_elements), m_pitch(num_elements), m_height(1), m_acquired(false), m_tag(tag), m_align_bytes(0), m_is_managed(exec_conf->allConcurrentManagedAccess() || (force_managed && exec_conf->isCUDAEnabled())) { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!(m_is_managed)) return; #endif assert(this->m_exec_conf); #ifdef ENABLE_CUDA if (this->m_exec_conf->isCUDAEnabled()) { // use OS page size as minimum alignment m_align_bytes = getpagesize(); } #endif if (m_num_elements > 0) allocate(); } //! Destructor virtual ~GlobalArray() { } //! Copy constructor GlobalArray(const GlobalArray& from) noexcept : m_exec_conf(from.m_exec_conf), #ifndef ALWAYS_USE_MANAGED_MEMORY m_fallback(from.m_fallback), #endif m_num_elements(from.m_num_elements), m_pitch(from.m_pitch), m_height(from.m_height), m_acquired(false), m_tag(from.m_tag), m_align_bytes(from.m_align_bytes), m_is_managed(false) { if (from.m_data.get()) { allocate(); #ifdef ENABLE_CUDA if (this->m_exec_conf && this->m_exec_conf->isCUDAEnabled()) { // synchronize all active GPUs auto gpu_map = this->m_exec_conf->getGPUIds(); for (int idev = this->m_exec_conf->getNumActiveGPUs() - 1; idev >= 0; --idev) { cudaSetDevice(gpu_map[idev]); cudaDeviceSynchronize(); } } #endif std::copy(from.m_data.get(), from.m_data.get()+from.m_num_elements, m_data.get()); } } //! = operator GlobalArray& operator=(const GlobalArray& rhs) noexcept { m_exec_conf = rhs.m_exec_conf; #ifndef ALWAYS_USE_MANAGED_MEMORY m_fallback = rhs.m_fallback; #endif if (&rhs != this) { m_num_elements = rhs.m_num_elements; m_pitch = rhs.m_pitch; m_height = rhs.m_height; m_acquired = false; m_align_bytes = rhs.m_align_bytes; m_tag = rhs.m_tag; if (rhs.m_data.get()) { allocate(); #ifdef ENABLE_CUDA if (this->m_exec_conf && this->m_exec_conf->isCUDAEnabled()) { // synchronize all active GPUs auto gpu_map = this->m_exec_conf->getGPUIds(); for (int idev = this->m_exec_conf->getNumActiveGPUs() - 1; idev >= 0; --idev) { cudaSetDevice(gpu_map[idev]); cudaDeviceSynchronize(); } } #endif std::copy(rhs.m_data.get(), rhs.m_data.get()+rhs.m_num_elements, m_data.get()); } else { m_data.reset(); } } return *this; } //! Move constructor, provided for convenience, so std::swap can be used GlobalArray(GlobalArray&& other) noexcept : m_exec_conf(std::move(other.m_exec_conf)), #ifndef ALWAYS_USE_MANAGED_MEMORY m_fallback(std::move(other.m_fallback)), #endif m_data(std::move(other.m_data)), m_num_elements(std::move(other.m_num_elements)), m_pitch(std::move(other.m_pitch)), m_height(std::move(other.m_height)), m_acquired(std::move(other.m_acquired)), m_tag(std::move(other.m_tag)), m_align_bytes(std::move(other.m_align_bytes)), m_is_managed(std::move(other.m_is_managed)) #ifdef ENABLE_CUDA , m_event(std::move(other.m_event)) #endif { } //! Move assignment operator GlobalArray& operator=(GlobalArray&& other) noexcept { // call base clas method if (&other != this) { m_exec_conf = std::move(other.m_exec_conf); #ifndef ALWAYS_USE_MANAGED_MEMORY m_fallback = std::move(other.m_fallback); #endif m_data = std::move(other.m_data); m_num_elements = std::move(other.m_num_elements); m_pitch = std::move(other.m_pitch); m_height = std::move(other.m_height); m_acquired = std::move(other.m_acquired); m_tag = std::move(other.m_tag); m_align_bytes = std::move(other.m_align_bytes); m_is_managed = std::move(other.m_is_managed); #ifdef ENABLE_CUDA m_event = std::move(other.m_event); #endif } return *this; } /*! Allocate a 2D array in managed memory \param width Width of the 2-D array to allocate (in elements) \param height Number of rows to allocate in the 2D array \param exec_conf Shared pointer to the execution configuration for managing CUDA initialization and shutdown */ GlobalArray(unsigned int width, unsigned int height, std::shared_ptr<const ExecutionConfiguration> exec_conf, bool force_managed=false) : m_exec_conf(exec_conf), #ifndef ALWAYS_USE_MANAGED_MEMORY // explicit copy should be elided m_fallback((exec_conf->allConcurrentManagedAccess() || (force_managed && exec_conf->isCUDAEnabled())) ? GPUArray<T>() : GPUArray<T>(width, height, exec_conf)), #endif m_height(height), m_acquired(false), m_align_bytes(0), m_is_managed(exec_conf->allConcurrentManagedAccess() || (force_managed && exec_conf->isCUDAEnabled())) { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!m_is_managed) return; #endif // make m_pitch the next multiple of 16 larger or equal to the given width m_pitch = (width + (16 - (width & 15))); m_num_elements = m_pitch * m_height; #ifdef ENABLE_CUDA if (this->m_exec_conf->isCUDAEnabled()) { // use OS page size as minimum alignment m_align_bytes = getpagesize(); } #endif if (m_num_elements > 0) allocate(); } //! Swap the pointers of two GlobalArrays inline void swap(GlobalArray &from) { checkAcquired(from); checkAcquired(*this); std::swap(m_exec_conf, from.m_exec_conf); std::swap(m_num_elements, from.m_num_elements); std::swap(m_data, from.m_data); std::swap(m_pitch,from.m_pitch); std::swap(m_height,from.m_height); std::swap(m_tag, from.m_tag); std::swap(m_align_bytes, from.m_align_bytes); std::swap(m_is_managed, from.m_is_managed); #ifdef ENABLE_CUDA std::swap(m_event, from.m_event); #endif #ifndef ALWAYS_USE_MANAGED_MEMORY m_fallback.swap(from.m_fallback); #endif } //! Get the underlying raw pointer /*! \returns the content of the underlying smart pointer \warning This method doesn't sync the device, so if you are using the pointer to read from while a kernel is writing to it on some stream, this may cause undefined behavior It may be used to pass the pointer to API functions, e.g., to set memory hints or prefetch data asynchronously */ const T *get() const { return m_data.get(); } //! Get the number of elements /*! - For 1-D allocated GPUArrays, this is the number of elements allocated. - For 2-D allocated GPUArrays, this is the \b total number of elements (\a pitch * \a height) allocated */ inline unsigned int getNumElements() const { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!this->m_exec_conf || !m_is_managed) return m_fallback.getNumElements(); #endif return m_num_elements; } //! Test if the GPUArray is NULL inline bool isNull() const { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!this->m_exec_conf || ! m_is_managed) return m_fallback.isNull(); #endif return !m_data; } //! Get the width of the allocated rows in elements /*! - For 2-D allocated GPUArrays, this is the total width of a row in memory (including the padding added for coalescing) - For 1-D allocated GPUArrays, this is the simply the number of elements allocated. */ inline unsigned int getPitch() const { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!this->m_exec_conf || ! m_is_managed) return m_fallback.getPitch(); #endif return m_pitch; } //! Get the number of rows allocated /*! - For 2-D allocated GPUArrays, this is the height given to the constructor - For 1-D allocated GPUArrays, this is the simply 1. */ inline unsigned int getHeight() const { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!this->m_exec_conf || ! m_is_managed) return m_fallback.getHeight(); #endif return m_height; } //! Resize the GlobalArray /*! This method resizes the array by allocating a new array and copying over the elements from the old array. Resizing is a slow operation. */ inline void resize(unsigned int num_elements) { #ifndef ALWAYS_USE_MANAGED_MEMORY if (! this->m_exec_conf || ! m_is_managed) { m_fallback.resize(num_elements); return; } #endif checkAcquired(*this); #ifdef ENABLE_CUDA if (this->m_exec_conf && this->m_exec_conf->isCUDAEnabled()) { // synchronize all active GPUs auto gpu_map = this->m_exec_conf->getGPUIds(); for (int idev = this->m_exec_conf->getNumActiveGPUs() - 1; idev >= 0; --idev) { cudaSetDevice(gpu_map[idev]); cudaDeviceSynchronize(); } } #endif // store old data in temporary vector std::vector<T> old(m_num_elements); std::copy(m_data.get(), m_data.get()+m_num_elements, old.begin()); unsigned int num_copy_elements = m_num_elements > num_elements ? num_elements : m_num_elements; m_num_elements = num_elements; assert(m_num_elements > 0); allocate(); std::copy(old.begin(), old.begin() + num_copy_elements, m_data.get()); m_pitch = m_num_elements; m_height = 1; } //! Resize a 2D GlobalArray inline void resize(unsigned int width, unsigned int height) { assert(this->m_exec_conf); #ifndef ALWAYS_USE_MANAGED_MEMORY if (! m_is_managed) { m_fallback.resize(width, height); return; } #endif checkAcquired(*this); // make m_pitch the next multiple of 16 larger or equal to the given width unsigned int pitch = (width + (16 - (width & 15))); #ifdef ENABLE_CUDA if (this->m_exec_conf->isCUDAEnabled()) { // synchronize all active GPUs auto gpu_map = this->m_exec_conf->getGPUIds(); for (int idev = this->m_exec_conf->getNumActiveGPUs() - 1; idev >= 0; --idev) { cudaSetDevice(gpu_map[idev]); cudaDeviceSynchronize(); } } #endif // store old data in temporary vector std::vector<T> old(m_num_elements); std::copy(m_data.get(), m_data.get()+m_num_elements, old.begin()); m_num_elements = pitch * height; assert(m_num_elements > 0); allocate(); // copy over data // every column is copied separately such as to align with the new pitch unsigned int num_copy_rows = m_height > height ? height : m_height; unsigned int num_copy_columns = m_pitch > pitch ? pitch : m_pitch; for (unsigned int i = 0; i < num_copy_rows; i++) std::copy(old.begin() + i*m_pitch, old.begin() + i*m_pitch + num_copy_columns, m_data.get() + i * pitch); m_height = height; m_pitch = pitch; } //! Set an optional tag for memory profiling /*! tag The name of this allocation */ inline void setTag(const std::string& tag) { // update the tag m_tag = tag; if (this->m_exec_conf && this->m_exec_conf->getMemoryTracer() && get() ) this->m_exec_conf->getMemoryTracer()->updateTag(reinterpret_cast<const void*>(get()), sizeof(T)*m_num_elements, m_tag); // set tag on deleter so it can be displayed upon free if (!isNull()) m_data.get_deleter().setTag(tag); } protected: inline ArrayHandleDispatch<T> acquire(const access_location::Enum location, const access_mode::Enum mode #ifdef ENABLE_CUDA , bool async = false #endif ) const; //! Release the data pointer inline void release() const { m_acquired = false; } //! Returns the acquire state inline bool isAcquired() const { return m_acquired; } //! Need to be friends with ArrayHandle friend class ArrayHandle<T>; friend class ArrayHandleAsync<T>; friend class GPUArrayBase<T, GlobalArray<T> >; friend class GlobalArrayDispatch<T>; std::shared_ptr<const ExecutionConfiguration> m_exec_conf; //!< execution configuration for working with CUDA private: #ifndef ALWAYS_USE_MANAGED_MEMORY //! We hold a GPUArray<T> object for fallback onto zero-copy memory GPUArray<T> m_fallback; #endif std::unique_ptr<T, hoomd::detail::managed_deleter<T> > m_data; //!< Smart ptr to managed or host memory, with custom deleter unsigned int m_num_elements; //!< Number of elements in array unsigned int m_pitch; //!< Pitch of 2D array unsigned int m_height; //!< Height of 2D array mutable bool m_acquired; //!< Tracks if the array is already acquired std::string m_tag; //!< Name tag of this buffer (optional) unsigned int m_align_bytes; //!< Size of alignment in bytes bool m_is_managed; //!< Whether or not this array is stored using managed memory. #ifdef ENABLE_CUDA std::unique_ptr<cudaEvent_t, hoomd::detail::event_deleter> m_event; //! CUDA event for synchronization #endif //! Allocate the managed array and construct the items void allocate() { assert(m_num_elements); void *ptr = nullptr; void *allocation_ptr = nullptr; bool use_device = this->m_exec_conf && this->m_exec_conf->isCUDAEnabled(); size_t allocation_bytes; #ifdef ENABLE_CUDA if (use_device) { allocation_bytes = m_num_elements*sizeof(T); // always reserve an extra page if (m_align_bytes) allocation_bytes += m_align_bytes; this->m_exec_conf->msg->notice(10) << "Allocating " << allocation_bytes << " bytes of managed memory." << std::endl; cudaMallocManaged(&ptr, allocation_bytes, cudaMemAttachGlobal); CHECK_CUDA_ERROR(); allocation_ptr = ptr; if (m_align_bytes) { // align to align_size #ifndef NO_STD_ALIGN ptr = std::align(m_align_bytes,m_num_elements*sizeof(T),ptr,allocation_bytes); #else ptr = hoomd::detail::my_align(m_align_bytes,m_num_elements*sizeof(T),ptr,allocation_bytes); #endif if (!ptr) throw std::runtime_error("GlobalArray: Error aligning managed memory"); } } else #endif { int retval = posix_memalign((void **) &ptr, 32, m_num_elements*sizeof(T)); if (retval != 0) { throw std::runtime_error("Error allocating aligned memory"); } allocation_bytes = m_num_elements*sizeof(T); allocation_ptr = ptr; } #ifdef ENABLE_CUDA if (use_device) { cudaDeviceSynchronize(); CHECK_CUDA_ERROR(); } if (use_device) { m_event = std::unique_ptr<cudaEvent_t, hoomd::detail::event_deleter>( new cudaEvent_t, hoomd::detail::event_deleter(this->m_exec_conf)); cudaEventCreate(m_event.get(), cudaEventDisableTiming); CHECK_CUDA_ERROR(); } #endif // store allocation and custom deleter in unique_ptr hoomd::detail::managed_deleter<T> deleter(this->m_exec_conf,use_device, m_num_elements, allocation_ptr, allocation_bytes); deleter.setTag(m_tag); m_data = std::unique_ptr<T, decltype(deleter)>(reinterpret_cast<T *>(ptr), deleter); // construct objects explicitly using placement new for (std::size_t i = 0; i < m_num_elements; ++i) ::new ((void **) &((T *)ptr)[i]) T; // register new allocation if (this->m_exec_conf && this->m_exec_conf->getMemoryTracer()) this->m_exec_conf->getMemoryTracer()->registerAllocation(reinterpret_cast<const void *>(m_data.get()), sizeof(T)*m_num_elements, typeid(T).name(), m_tag); } }; //************************************************ // ArrayHandleDispatch specialization for GPUArray // *********************************************** template<class T> class GlobalArrayDispatch : public ArrayHandleDispatch<T> { public: GlobalArrayDispatch(T* const _data, const GlobalArray<T>& _global_array) : ArrayHandleDispatch<T>(_data), global_array(_global_array) { } virtual ~GlobalArrayDispatch() { assert(global_array.isAcquired()); global_array.release(); } private: const GlobalArray<T>& global_array; }; // *********************************************** // GlobalArray implementation // *********************************************** template<class T> inline ArrayHandleDispatch<T> GlobalArray<T>::acquire(const access_location::Enum location, const access_mode::Enum mode #ifdef ENABLE_CUDA , bool async #endif ) const { #ifndef ALWAYS_USE_MANAGED_MEMORY if (!this->m_exec_conf || ! m_is_managed) return m_fallback.acquire(location, mode #ifdef ENABLE_CUDA , async #endif ); #endif checkAcquired(*this); m_acquired = true; // make sure a null array can be acquired if (!this->m_exec_conf || isNull() ) return GlobalArrayDispatch<T>(nullptr, *this); if (this->m_exec_conf && this->m_exec_conf->inMultiGPUBlock()) { // we throw this error because we are not syncing all GPUs upon acquire throw std::runtime_error("GlobalArray should not be acquired in a multi-GPU block."); } #ifdef ENABLE_CUDA bool use_device = this->m_exec_conf && this->m_exec_conf->isCUDAEnabled(); if (!isNull() && use_device && location == access_location::host && !async) { // synchronize GPU 0 cudaEventRecord(*m_event); cudaEventSynchronize(*m_event); if (this->m_exec_conf->isCUDAErrorCheckingEnabled()) CHECK_CUDA_ERROR(); } #endif return GlobalArrayDispatch<T>(m_data.get(), *this); }
{ "pile_set_name": "Github" }
K 10 svn:ignore V 4 obj END
{ "pile_set_name": "Github" }
// Copyright 2019 The MediaPipe 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. #include "mediapipe/gpu/gl_context.h" #include <sys/types.h> #include <cmath> #include <memory> #include <string> #include <utility> #include "absl/base/dynamic_annotations.h" #include "absl/memory/memory.h" #include "absl/synchronization/mutex.h" #include "mediapipe/framework/port/logging.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" #include "mediapipe/gpu/gl_context_internal.h" #ifndef __EMSCRIPTEN__ #include "absl/debugging/leak_check.h" #include "mediapipe/gpu/gl_thread_collector.h" #endif #ifndef GL_MAJOR_VERSION #define GL_MAJOR_VERSION 0x821B #endif #ifndef GL_MINOR_VERSION #define GL_MINOR_VERSION 0x821C #endif namespace mediapipe { static void SetThreadName(const char* name) { #if defined(__GLIBC_PREREQ) #define LINUX_STYLE_SETNAME_NP __GLIBC_PREREQ(2, 12) #elif defined(__BIONIC__) #define LINUX_STYLE_SETNAME_NP 1 #endif // __GLIBC_PREREQ #if LINUX_STYLE_SETNAME_NP char thread_name[16]; // Linux requires names (with nul) fit in 16 chars strncpy(thread_name, name, sizeof(thread_name)); thread_name[sizeof(thread_name) - 1] = '\0'; int res = pthread_setname_np(pthread_self(), thread_name); if (res != 0) { LOG_FIRST_N(INFO, 1) << "Can't set pthread names: name: \"" << name << "\"; error: " << res; } #elif __APPLE__ pthread_setname_np(name); #endif ANNOTATE_THREAD_NAME(name); } GlContext::DedicatedThread::DedicatedThread() { CHECK_EQ(pthread_create(&gl_thread_id_, nullptr, ThreadBody, this), 0); } GlContext::DedicatedThread::~DedicatedThread() { if (IsCurrentThread()) { CHECK(self_destruct_); CHECK_EQ(pthread_detach(gl_thread_id_), 0); } else { // Give an invalid job to signal termination. PutJob({}); CHECK_EQ(pthread_join(gl_thread_id_, nullptr), 0); } } void GlContext::DedicatedThread::SelfDestruct() { self_destruct_ = true; // Give an invalid job to signal termination. PutJob({}); } GlContext::DedicatedThread::Job GlContext::DedicatedThread::GetJob() { absl::MutexLock lock(&mutex_); while (jobs_.empty()) { has_jobs_cv_.Wait(&mutex_); } Job job = std::move(jobs_.front()); jobs_.pop_front(); return job; } void GlContext::DedicatedThread::PutJob(Job job) { absl::MutexLock lock(&mutex_); jobs_.push_back(std::move(job)); has_jobs_cv_.SignalAll(); } void* GlContext::DedicatedThread::ThreadBody(void* instance) { DedicatedThread* thread = static_cast<DedicatedThread*>(instance); thread->ThreadBody(); return nullptr; } #ifdef __APPLE__ #define AUTORELEASEPOOL @autoreleasepool #else #define AUTORELEASEPOOL #endif // __APPLE__ void GlContext::DedicatedThread::ThreadBody() { SetThreadName("mediapipe_gl_runner"); #ifndef __EMSCRIPTEN__ GlThreadCollector::ThreadStarting(); #endif // The dedicated GL thread is not meant to be used on Apple platforms, but // in case it is, the use of an autorelease pool here will reap each task's // temporary allocations. while (true) AUTORELEASEPOOL { Job job = GetJob(); // Lack of a job means termination. Or vice versa. if (!job) { break; } job(); } if (self_destruct_) { delete this; } #ifndef __EMSCRIPTEN__ GlThreadCollector::ThreadEnding(); #endif } ::mediapipe::Status GlContext::DedicatedThread::Run(GlStatusFunction gl_func) { // Neither ENDO_SCOPE nor ENDO_TASK seem to work here. if (IsCurrentThread()) { return gl_func(); } bool done = false; // Guarded by mutex_ after initialization. ::mediapipe::Status status; PutJob([this, gl_func, &done, &status]() { status = gl_func(); absl::MutexLock lock(&mutex_); done = true; gl_job_done_cv_.SignalAll(); }); absl::MutexLock lock(&mutex_); while (!done) { gl_job_done_cv_.Wait(&mutex_); } return status; } void GlContext::DedicatedThread::RunWithoutWaiting(GlVoidFunction gl_func) { // Note: this is invoked by GlContextExecutor. To avoid starvation of // non-calculator tasks in the presence of GL source calculators, calculator // tasks must always be scheduled as new tasks, or another solution needs to // be set up to avoid starvation. See b/78522434. CHECK(gl_func); PutJob(std::move(gl_func)); } bool GlContext::DedicatedThread::IsCurrentThread() { return pthread_equal(gl_thread_id_, pthread_self()); } bool GlContext::ParseGlVersion(absl::string_view version_string, GLint* major, GLint* minor) { size_t pos = version_string.find('.'); if (pos == absl::string_view::npos || pos < 1) { return false; } // GL_VERSION is supposed to start with the version number; see, e.g., // https://www.khronos.org/registry/OpenGL-Refpages/es3/html/glGetString.xhtml // https://www.khronos.org/opengl/wiki/OpenGL_Context#OpenGL_version_number // However, in rare cases one will encounter non-conforming configurations // that have some prefix before the number. To deal with that, we walk // backwards from the dot. size_t start = pos - 1; while (start > 0 && isdigit(version_string[start - 1])) --start; if (!absl::SimpleAtoi(version_string.substr(start, (pos - start)), major)) { return false; } auto rest = version_string.substr(pos + 1); pos = rest.find(' '); size_t pos2 = rest.find('.'); if (pos == absl::string_view::npos || (pos2 != absl::string_view::npos && pos2 < pos)) { pos = pos2; } if (!absl::SimpleAtoi(rest.substr(0, pos), minor)) { return false; } return true; } bool GlContext::HasGlExtension(absl::string_view extension) const { return gl_extensions_.find(extension) != gl_extensions_.end(); } // Function for GL3.0+ to query for and store all of our available GL extensions // in an easily-accessible set. The glGetString call is actually *not* required // to work with GL_EXTENSIONS for newer GL versions, so we must maintain both // variations of this function. ::mediapipe::Status GlContext::GetGlExtensions() { gl_extensions_.clear(); // glGetStringi only introduced in GL 3.0+; so we exit out this function if // we don't have that function defined, regardless of version number reported. // The function itself is also fully stubbed out if we're linking against an // API version without a glGetStringi declaration. Although Emscripten // sometimes provides this function, its default library implementation // appears to only provide glGetString, so we skip this for Emscripten // platforms to avoid possible undefined symbol or runtime errors. #if (GL_VERSION_3_0 || GL_ES_VERSION_3_0) && !defined(__EMSCRIPTEN__) if (!SymbolAvailable(&glGetStringi)) { LOG(ERROR) << "GL major version > 3.0 indicated, but glGetStringi not " << "defined. Falling back to deprecated GL extensions querying " << "method."; return ::mediapipe::InternalError("glGetStringi not defined, but queried"); } int num_extensions = 0; glGetIntegerv(GL_NUM_EXTENSIONS, &num_extensions); if (glGetError() != 0) { return ::mediapipe::InternalError( "Error querying for number of extensions"); } for (int i = 0; i < num_extensions; ++i) { const GLubyte* res = glGetStringi(GL_EXTENSIONS, i); if (glGetError() != 0 || res == nullptr) { return ::mediapipe::InternalError( "Error querying for an extension by index"); } const char* signed_res = reinterpret_cast<const char*>(res); gl_extensions_.insert(signed_res); } return ::mediapipe::OkStatus(); #else return ::mediapipe::InternalError("GL version mismatch in GlGetExtensions"); #endif // (GL_VERSION_3_0 || GL_ES_VERSION_3_0) && !defined(__EMSCRIPTEN__) } // Same as GetGlExtensions() above, but for pre-GL3.0, where glGetStringi did // not exist. ::mediapipe::Status GlContext::GetGlExtensionsCompat() { gl_extensions_.clear(); const GLubyte* res = glGetString(GL_EXTENSIONS); if (glGetError() != 0 || res == nullptr) { LOG(ERROR) << "Error querying for GL extensions"; return ::mediapipe::InternalError("Error querying for GL extensions"); } const char* signed_res = reinterpret_cast<const char*>(res); gl_extensions_ = absl::StrSplit(signed_res, ' '); return ::mediapipe::OkStatus(); } ::mediapipe::Status GlContext::FinishInitialization(bool create_thread) { if (create_thread) { thread_ = absl::make_unique<GlContext::DedicatedThread>(); MP_RETURN_IF_ERROR(thread_->Run([this] { return EnterContext(nullptr); })); } return Run([this]() -> ::mediapipe::Status { // Clear any GL errors at this point: as this is a fresh context // there shouldn't be any, but if we adopted an existing context (e.g. in // some Emscripten cases), there might be some existing tripped error. ForceClearExistingGlErrors(); absl::string_view version_string( reinterpret_cast<const char*>(glGetString(GL_VERSION))); // We will decide later whether we want to use the version numbers we query // for, or instead derive that information from the context creation result, // which we cache here. GLint gl_major_version_from_context_creation = gl_major_version_; // Let's try getting the numeric version if possible. glGetIntegerv(GL_MAJOR_VERSION, &gl_major_version_); GLenum err = glGetError(); if (err == GL_NO_ERROR) { glGetIntegerv(GL_MINOR_VERSION, &gl_minor_version_); } else { // GL_MAJOR_VERSION is not supported on GL versions below 3. We have to // parse the version std::string. if (!ParseGlVersion(version_string, &gl_major_version_, &gl_minor_version_)) { LOG(WARNING) << "invalid GL_VERSION format: '" << version_string << "'; assuming 2.0"; gl_major_version_ = 2; gl_minor_version_ = 0; } } // If our platform-specific CreateContext already set a major GL version, // then we use that. Otherwise, we use the queried-for result. We do this // as a workaround for a Swiftshader on Android bug where the ES2 context // can report major version 3 instead of 2 when queried. Therefore we trust // the result from context creation more than from query. See b/152519932 // for more details. if (gl_major_version_from_context_creation > 0 && gl_major_version_ != gl_major_version_from_context_creation) { LOG(WARNING) << "Requested a context with major GL version " << gl_major_version_from_context_creation << " but context reports major version " << gl_major_version_ << ". Setting to " << gl_major_version_from_context_creation << ".0"; gl_major_version_ = gl_major_version_from_context_creation; gl_minor_version_ = 0; } LOG(INFO) << "GL version: " << gl_major_version_ << "." << gl_minor_version_ << " (" << glGetString(GL_VERSION) << ")"; if (gl_major_version_ >= 3) { auto status = GetGlExtensions(); if (status.ok()) { return ::mediapipe::OkStatus(); } } return GetGlExtensionsCompat(); }); } GlContext::GlContext() {} GlContext::~GlContext() { // Note: on Apple platforms, this object contains Objective-C objects. // The destructor will release them, but ARC must be on. #ifdef __OBJC__ #if !__has_feature(objc_arc) #error This file must be built with ARC. #endif #endif // __OBJC__ if (thread_) { auto status = thread_->Run([this] { if (profiling_helper_) { profiling_helper_->LogAllTimestamps(); } return ExitContext(nullptr); }); LOG_IF(ERROR, !status.ok()) << "Failed to deactivate context on thread: " << status; if (thread_->IsCurrentThread()) { thread_.release()->SelfDestruct(); } } DestroyContext(); } void GlContext::SetProfilingContext( std::shared_ptr<mediapipe::ProfilingContext> profiling_context) { // Create the GlProfilingHelper if it is uninitialized. if (!profiling_helper_ && profiling_context) { profiling_helper_ = profiling_context->CreateGlProfilingHelper(); } } ::mediapipe::Status GlContext::SwitchContextAndRun(GlStatusFunction gl_func) { ContextBinding saved_context; MP_RETURN_IF_ERROR(EnterContext(&saved_context)) << " (entering GL context)"; auto status = gl_func(); LogUncheckedGlErrors(CheckForGlErrors()); MP_RETURN_IF_ERROR(ExitContext(&saved_context)) << " (exiting GL context)"; return status; } ::mediapipe::Status GlContext::Run(GlStatusFunction gl_func, int node_id, Timestamp input_timestamp) { ::mediapipe::Status status; if (profiling_helper_) { gl_func = [=] { profiling_helper_->MarkTimestamp(node_id, input_timestamp, /*is_finish=*/false); auto status = gl_func(); profiling_helper_->MarkTimestamp(node_id, input_timestamp, /*is_finish=*/true); return status; }; } if (thread_) { bool had_gl_errors = false; status = thread_->Run([this, gl_func, &had_gl_errors] { auto status = gl_func(); had_gl_errors = CheckForGlErrors(); return status; }); LogUncheckedGlErrors(had_gl_errors); } else { status = SwitchContextAndRun(gl_func); } return status; } void GlContext::RunWithoutWaiting(GlVoidFunction gl_func) { if (thread_) { // Add ref to keep the context alive while the task is executing. auto context = shared_from_this(); thread_->RunWithoutWaiting([this, context, gl_func] { gl_func(); LogUncheckedGlErrors(CheckForGlErrors()); }); } else { // TODO: queue up task instead. auto status = SwitchContextAndRun([gl_func] { gl_func(); return ::mediapipe::OkStatus(); }); if (!status.ok()) { LOG(ERROR) << "Error in RunWithoutWaiting: " << status; } } } std::weak_ptr<GlContext>& GlContext::CurrentContext() { // Workaround for b/67878799. #ifndef __EMSCRIPTEN__ absl::LeakCheckDisabler disable_leak_check; #endif ABSL_CONST_INIT thread_local std::weak_ptr<GlContext> current_context; return current_context; } ::mediapipe::Status GlContext::SwitchContext(ContextBinding* saved_context, const ContextBinding& new_context) ABSL_NO_THREAD_SAFETY_ANALYSIS { std::shared_ptr<GlContext> old_context_obj = CurrentContext().lock(); std::shared_ptr<GlContext> new_context_obj = new_context.context_object.lock(); if (saved_context) { saved_context->context_object = old_context_obj; GetCurrentContextBinding(saved_context); } // Check that the context object is consistent with the native context. if (old_context_obj && saved_context) { DCHECK(old_context_obj->context_ == saved_context->context); } if (new_context_obj) { DCHECK(new_context_obj->context_ == new_context.context); } if (new_context_obj && (old_context_obj == new_context_obj)) { return ::mediapipe::OkStatus(); } if (old_context_obj) { // 1. Even if we cannot restore the new context, we want to get out of the // old one (we may be deliberately trying to exit it). // 2. We need to unset the old context before we unlock the old mutex, // Therefore, we first unset the old one before setting the new one. MP_RETURN_IF_ERROR(SetCurrentContextBinding({})); old_context_obj->context_use_mutex_.Unlock(); CurrentContext().reset(); } if (new_context_obj) { new_context_obj->context_use_mutex_.Lock(); auto status = SetCurrentContextBinding(new_context); if (status.ok()) { CurrentContext() = new_context_obj; } else { new_context_obj->context_use_mutex_.Unlock(); } return status; } else { return SetCurrentContextBinding(new_context); } } ::mediapipe::Status GlContext::EnterContext(ContextBinding* saved_context) { DCHECK(HasContext()); return SwitchContext(saved_context, ThisContextBinding()); } ::mediapipe::Status GlContext::ExitContext( const ContextBinding* saved_context) { ContextBinding no_context; if (!saved_context) { saved_context = &no_context; } return SwitchContext(nullptr, *saved_context); } std::shared_ptr<GlContext> GlContext::GetCurrent() { return CurrentContext().lock(); } void GlContext::GlFinishCalled() { absl::MutexLock lock(&mutex_); ++gl_finish_count_; wait_for_gl_finish_cv_.SignalAll(); } class GlFinishSyncPoint : public GlSyncPoint { public: explicit GlFinishSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context), gl_finish_count_(gl_context_->gl_finish_count()) {} void Wait() override { gl_context_->WaitForGlFinishCountPast(gl_finish_count_); } bool IsReady() override { return gl_context_->gl_finish_count() > gl_finish_count_; } private: // Number of glFinish calls done before the creation of this token. int64_t gl_finish_count_ = -1; }; class GlFenceSyncPoint : public GlSyncPoint { public: explicit GlFenceSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context) { gl_context_->Run([this] { sync_ = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glFlush(); }); } ~GlFenceSyncPoint() { if (sync_) { GLsync sync = sync_; gl_context_->RunWithoutWaiting([sync] { glDeleteSync(sync); }); } } GlFenceSyncPoint(const GlFenceSyncPoint&) = delete; GlFenceSyncPoint& operator=(const GlFenceSyncPoint&) = delete; void Wait() override { if (!sync_) return; gl_context_->Run([this] { GLenum result = glClientWaitSync(sync_, 0, std::numeric_limits<uint64_t>::max()); if (result == GL_ALREADY_SIGNALED || result == GL_CONDITION_SATISFIED) { glDeleteSync(sync_); sync_ = nullptr; } // TODO: do something if the wait fails? }); } void WaitOnGpu() override { if (!sync_) return; // TODO: do not wait if we are already on the same context? glWaitSync(sync_, 0, GL_TIMEOUT_IGNORED); } bool IsReady() override { if (!sync_) return true; bool ready = false; // TODO: we should not block on the original context if possible. gl_context_->Run([this, &ready] { GLenum result = glClientWaitSync(sync_, 0, 0); if (result == GL_ALREADY_SIGNALED || result == GL_CONDITION_SATISFIED) { glDeleteSync(sync_); sync_ = nullptr; ready = true; } }); return ready; } private: GLsync sync_; }; void GlMultiSyncPoint::Add(std::shared_ptr<GlSyncPoint> new_sync) { for (auto& sync : syncs_) { if (sync->GetContext() == new_sync->GetContext()) { sync = std::move(new_sync); return; } } syncs_.emplace_back(std::move(new_sync)); } void GlMultiSyncPoint::Wait() { for (auto& sync : syncs_) { sync->Wait(); } // At this point all the syncs have been reached, so clear them out. syncs_.clear(); } void GlMultiSyncPoint::WaitOnGpu() { for (auto& sync : syncs_) { sync->WaitOnGpu(); } // TODO: when do we clear out these syncs? } bool GlMultiSyncPoint::IsReady() { syncs_.erase( std::remove_if(syncs_.begin(), syncs_.end(), std::bind(&GlSyncPoint::IsReady, std::placeholders::_1)), syncs_.end()); return syncs_.empty(); } // Set this to 1 to disable syncing. This can be used to verify that a test // correctly detects sync issues. #define MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG 0 #if MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG class GlNopSyncPoint : public GlSyncPoint { public: explicit GlNopSyncPoint(const std::shared_ptr<GlContext>& gl_context) : GlSyncPoint(gl_context) {} void Wait() override {} bool IsReady() override { return true; } }; #endif std::shared_ptr<GlSyncPoint> GlContext::CreateSyncToken() { std::shared_ptr<GlSyncPoint> token; #if MEDIAPIPE_DISABLE_GL_SYNC_FOR_DEBUG token.reset(new GlNopSyncPoint(shared_from_this())); #else #ifdef __EMSCRIPTEN__ // In Emscripten the glWaitSync function is non-null depending on linkopts, // but only works in a WebGL2 context, so fall back to use Finish if it is a // WebGL1/ES2 context. // TODO: apply this more generally once b/152794517 is fixed. bool useFenceSync = gl_major_version() > 2; #else bool useFenceSync = SymbolAvailable(&glWaitSync); #endif // __EMSCRIPTEN__ if (useFenceSync) { token.reset(new GlFenceSyncPoint(shared_from_this())); } else { token.reset(new GlFinishSyncPoint(shared_from_this())); } #endif return token; } std::shared_ptr<GlSyncPoint> GlContext::TestOnly_CreateSpecificSyncToken( SyncTokenTypeForTest type) { std::shared_ptr<GlSyncPoint> token; switch (type) { case SyncTokenTypeForTest::kGlFinish: token.reset(new GlFinishSyncPoint(shared_from_this())); return token; } return nullptr; } // Atomically set var to the greater of its current value or target. template <typename T> static void assign_larger_value(std::atomic<T>* var, T target) { T current = var->load(); while (current < target && !var->compare_exchange_weak(current, target)) { } } // Note: this can get called from an arbitrary thread which is dealing with a // GlFinishSyncPoint originating from this context. void GlContext::WaitForGlFinishCountPast(int64_t count_to_pass) { if (gl_finish_count_ > count_to_pass) return; // If we've been asked to do a glFinish, note the count we need to reach and // signal the context our thread may currently be blocked on. { absl::MutexLock lock(&mutex_); assign_larger_value(&gl_finish_count_target_, count_to_pass + 1); wait_for_gl_finish_cv_.SignalAll(); if (context_waiting_on_) { context_waiting_on_->wait_for_gl_finish_cv_.SignalAll(); } } auto finish_task = [this, count_to_pass]() { // When a GlFinishSyncToken is created it takes the current finish count // from the GlContext, and we must wait for gl_finish_count_ to pass it. // Therefore, we need to do at most one more glFinish call. This DCHECK // is used for documentation and sanity-checking purposes. DCHECK(gl_finish_count_ >= count_to_pass); if (gl_finish_count_ == count_to_pass) { glFinish(); GlFinishCalled(); } }; if (IsCurrent()) { // If we are already on the current context, we cannot call // RunWithoutWaiting, since that task will not run until this function // returns. Instead, call it directly. finish_task(); return; } std::shared_ptr<GlContext> other = GetCurrent(); if (other) { // If another context is current, make a note that it is blocked on us, so // it can signal the right condition variable if it is asked to do a // glFinish. absl::MutexLock other_lock(&other->mutex_); DCHECK(!other->context_waiting_on_); other->context_waiting_on_ = this; } // We do not schedule this action using Run because we don't necessarily // want to wait for it to complete. If another job calls GlFinishCalled // sooner, we are done. RunWithoutWaiting(std::move(finish_task)); { absl::MutexLock lock(&mutex_); while (gl_finish_count_ <= count_to_pass) { if (other && other->gl_finish_count_ < other->gl_finish_count_target_) { // If another context's dedicated thread is current, it is blocked // waiting for this context to issue a glFinish call. But this context // may also block waiting for the other context to do the same: this can // happen when two contexts are handling each other's GlFinishSyncPoints // (e.g. a producer and a consumer). To avoid a deadlock a context that // is waiting on another context must still service Wait calls it may // receive from its own GlFinishSyncPoints. // // We unlock this context's mutex to avoid holding both at the same // time. mutex_.Unlock(); { glFinish(); other->GlFinishCalled(); } mutex_.Lock(); // Because we temporarily unlocked mutex_, we cannot wait on the // condition variable wait away; we need to go back to re-checking the // condition. Otherwise we might miss a signal. continue; } wait_for_gl_finish_cv_.Wait(&mutex_); } } if (other) { // The other context is no longer waiting on us. absl::MutexLock other_lock(&other->mutex_); other->context_waiting_on_ = nullptr; } } void GlContext::WaitSyncToken(const std::shared_ptr<GlSyncPoint>& token) { CHECK(token); token->Wait(); } bool GlContext::SyncTokenIsReady(const std::shared_ptr<GlSyncPoint>& token) { CHECK(token); return token->IsReady(); } void GlContext::ForceClearExistingGlErrors() { LogUncheckedGlErrors(CheckForGlErrors(/*force=*/true)); } bool GlContext::CheckForGlErrors() { return CheckForGlErrors(false); } bool GlContext::CheckForGlErrors(bool force) { #if UNSAFE_EMSCRIPTEN_SKIP_GL_ERROR_HANDLING if (!force) { LOG_FIRST_N(WARNING, 1) << "MediaPipe OpenGL error checking is disabled"; return false; } #endif if (!HasContext()) return false; GLenum error; bool had_error = false; while ((error = glGetError()) != GL_NO_ERROR) { had_error = true; switch (error) { case GL_INVALID_ENUM: LOG(INFO) << "Found unchecked GL error: GL_INVALID_ENUM"; break; case GL_INVALID_VALUE: LOG(INFO) << "Found unchecked GL error: GL_INVALID_VALUE"; break; case GL_INVALID_OPERATION: LOG(INFO) << "Found unchecked GL error: GL_INVALID_OPERATION"; break; case GL_INVALID_FRAMEBUFFER_OPERATION: LOG(INFO) << "Found unchecked GL error: GL_INVALID_FRAMEBUFFER_OPERATION"; break; case GL_OUT_OF_MEMORY: LOG(INFO) << "Found unchecked GL error: GL_OUT_OF_MEMORY"; break; default: LOG(INFO) << "Found unchecked GL error: UNKNOWN ERROR"; break; } } return had_error; } void GlContext::LogUncheckedGlErrors(bool had_gl_errors) { if (had_gl_errors) { // TODO: ideally we would print a backtrace here, or at least // the name of the current calculator, to make it easier to find the // culprit. In practice, getting a backtrace from Android without crashing // is nearly impossible, so screw it. Just change this to LOG(FATAL) when // you want to debug. LOG(WARNING) << "Ignoring unchecked GL error."; } } } // namespace mediapipe
{ "pile_set_name": "Github" }
namespace Scada.Scheme.Model.PropertyGrid { partial class FrmFontDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.lblFontName = new System.Windows.Forms.Label(); this.lblFontSize = new System.Windows.Forms.Label(); this.btnCancel = new System.Windows.Forms.Button(); this.btnOK = new System.Windows.Forms.Button(); this.cbFontSize = new System.Windows.Forms.ComboBox(); this.gbStyle = new System.Windows.Forms.GroupBox(); this.chkUnderline = new System.Windows.Forms.CheckBox(); this.chkItalic = new System.Windows.Forms.CheckBox(); this.chkBold = new System.Windows.Forms.CheckBox(); this.cbFontName = new System.Windows.Forms.ComboBox(); this.gbStyle.SuspendLayout(); this.SuspendLayout(); // // lblFontName // this.lblFontName.AutoSize = true; this.lblFontName.Location = new System.Drawing.Point(9, 9); this.lblFontName.Name = "lblFontName"; this.lblFontName.Size = new System.Drawing.Size(28, 13); this.lblFontName.TabIndex = 0; this.lblFontName.Text = "Font"; // // lblFontSize // this.lblFontSize.AutoSize = true; this.lblFontSize.Location = new System.Drawing.Point(165, 9); this.lblFontSize.Name = "lblFontSize"; this.lblFontSize.Size = new System.Drawing.Size(27, 13); this.lblFontSize.TabIndex = 2; this.lblFontSize.Text = "Size"; // // btnCancel // this.btnCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.btnCancel.Location = new System.Drawing.Point(193, 153); this.btnCancel.Name = "btnCancel"; this.btnCancel.Size = new System.Drawing.Size(75, 23); this.btnCancel.TabIndex = 6; this.btnCancel.Text = "Cancel"; this.btnCancel.UseVisualStyleBackColor = true; // // btnOK // this.btnOK.Location = new System.Drawing.Point(112, 153); this.btnOK.Name = "btnOK"; this.btnOK.Size = new System.Drawing.Size(75, 23); this.btnOK.TabIndex = 5; this.btnOK.Text = "OK"; this.btnOK.UseVisualStyleBackColor = true; this.btnOK.Click += new System.EventHandler(this.btnOK_Click); // // cbFontSize // this.cbFontSize.FormattingEnabled = true; this.cbFontSize.Items.AddRange(new object[] { "8", "9", "10", "11", "12", "14", "16", "18", "20", "22", "24", "26", "28", "36", "48", "72"}); this.cbFontSize.Location = new System.Drawing.Point(168, 25); this.cbFontSize.Name = "cbFontSize"; this.cbFontSize.Size = new System.Drawing.Size(100, 21); this.cbFontSize.TabIndex = 3; // // gbStyle // this.gbStyle.Controls.Add(this.chkUnderline); this.gbStyle.Controls.Add(this.chkItalic); this.gbStyle.Controls.Add(this.chkBold); this.gbStyle.Location = new System.Drawing.Point(12, 52); this.gbStyle.Name = "gbStyle"; this.gbStyle.Padding = new System.Windows.Forms.Padding(10, 3, 10, 10); this.gbStyle.Size = new System.Drawing.Size(256, 95); this.gbStyle.TabIndex = 4; this.gbStyle.TabStop = false; this.gbStyle.Text = "Style"; // // chkUnderline // this.chkUnderline.AutoSize = true; this.chkUnderline.Location = new System.Drawing.Point(13, 65); this.chkUnderline.Name = "chkUnderline"; this.chkUnderline.Size = new System.Drawing.Size(71, 17); this.chkUnderline.TabIndex = 2; this.chkUnderline.Text = "Underline"; this.chkUnderline.UseVisualStyleBackColor = true; // // chkItalic // this.chkItalic.AutoSize = true; this.chkItalic.Location = new System.Drawing.Point(13, 42); this.chkItalic.Name = "chkItalic"; this.chkItalic.Size = new System.Drawing.Size(48, 17); this.chkItalic.TabIndex = 1; this.chkItalic.Text = "Italic"; this.chkItalic.UseVisualStyleBackColor = true; // // chkBold // this.chkBold.AutoSize = true; this.chkBold.Location = new System.Drawing.Point(13, 19); this.chkBold.Name = "chkBold"; this.chkBold.Size = new System.Drawing.Size(47, 17); this.chkBold.TabIndex = 0; this.chkBold.Text = "Bold"; this.chkBold.UseVisualStyleBackColor = true; // // cbFontName // this.cbFontName.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawVariable; this.cbFontName.FormattingEnabled = true; this.cbFontName.Location = new System.Drawing.Point(12, 25); this.cbFontName.Name = "cbFontName"; this.cbFontName.Size = new System.Drawing.Size(150, 21); this.cbFontName.TabIndex = 1; this.cbFontName.DrawItem += new System.Windows.Forms.DrawItemEventHandler(this.cbFontName_DrawItem); this.cbFontName.MeasureItem += new System.Windows.Forms.MeasureItemEventHandler(this.cbFontName_MeasureItem); // // FrmFontDialog // this.AcceptButton = this.btnOK; this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.btnCancel; this.ClientSize = new System.Drawing.Size(281, 188); this.Controls.Add(this.cbFontName); this.Controls.Add(this.gbStyle); this.Controls.Add(this.cbFontSize); this.Controls.Add(this.btnOK); this.Controls.Add(this.btnCancel); this.Controls.Add(this.lblFontSize); this.Controls.Add(this.lblFontName); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "FrmFontDialog"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Font"; this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.FrmFontDialog_FormClosed); this.Load += new System.EventHandler(this.FrmFontDialog_Load); this.gbStyle.ResumeLayout(false); this.gbStyle.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label lblFontName; private System.Windows.Forms.Label lblFontSize; private System.Windows.Forms.Button btnCancel; private System.Windows.Forms.Button btnOK; private System.Windows.Forms.ComboBox cbFontSize; private System.Windows.Forms.GroupBox gbStyle; private System.Windows.Forms.CheckBox chkUnderline; private System.Windows.Forms.CheckBox chkItalic; private System.Windows.Forms.CheckBox chkBold; private System.Windows.Forms.ComboBox cbFontName; } }
{ "pile_set_name": "Github" }
# class ClassPropertyDescriptor: """ ClassPropertyDescriptor """ def __init__(self, fget, fset=None): self.fget = fget self.fset = fset def __get__(self, obj, klass=None): """ __get__ """ if klass is None: klass = type(obj) return self.fget.__get__(obj, klass)() def __set__(self, obj, value): """ __set__ """ if not self.fset: raise AttributeError("can't set attribute") type_ = type(obj) return self.fset.__get__(obj, type_)(value) def setter(self, func): """ setter """ if not isinstance(func, (classmethod, staticmethod)): func = classmethod(func) self.fset = func return self def classproperty(func): """ classproperty """ if not isinstance(func, (classmethod, staticmethod)): func = classmethod(func) return ClassPropertyDescriptor(func)
{ "pile_set_name": "Github" }
/* Command line option handling. Copyright (C) 2002-2020 Free Software Foundation, Inc. This file is part of GCC. GCC 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, or (at your option) any later version. GCC 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 GCC; see the file COPYING3. If not see <http://www.gnu.org/licenses/>. */ #ifndef GCC_OPTS_H #define GCC_OPTS_H #include "obstack.h" /* Specifies how a switch's VAR_VALUE relates to its FLAG_VAR. */ enum cl_var_type { /* The switch is enabled when FLAG_VAR is nonzero. */ CLVC_BOOLEAN, /* The switch is enabled when FLAG_VAR == VAR_VALUE. */ CLVC_EQUAL, /* The switch is enabled when VAR_VALUE is not set in FLAG_VAR. */ CLVC_BIT_CLEAR, /* The switch is enabled when VAR_VALUE is set in FLAG_VAR. */ CLVC_BIT_SET, /* The switch is enabled when FLAG_VAR is less than HOST_WIDE_INT_M1U. */ CLVC_SIZE, /* The switch takes a string argument and FLAG_VAR points to that argument. */ CLVC_STRING, /* The switch takes an enumerated argument (VAR_ENUM says what enumeration) and FLAG_VAR points to that argument. */ CLVC_ENUM, /* The switch should be stored in the VEC pointed to by FLAG_VAR for later processing. */ CLVC_DEFER }; struct cl_option { /* Text of the option, including initial '-'. */ const char *opt_text; /* Help text for --help, or NULL. */ const char *help; /* Error message for missing argument, or NULL. */ const char *missing_argument_error; /* Warning to give when this option is used, or NULL. */ const char *warn_message; /* Argument of alias target when positive option given, or NULL. */ const char *alias_arg; /* Argument of alias target when negative option given, or NULL. */ const char *neg_alias_arg; /* Alias target, or N_OPTS if not an alias. */ unsigned short alias_target; /* Previous option that is an initial substring of this one, or N_OPTS if none. */ unsigned short back_chain; /* Option length, not including initial '-'. */ unsigned char opt_len; /* Next option in a sequence marked with Negative, or -1 if none. For a single option with both a negative and a positve form (such as -Wall and -Wno-all), NEG_IDX is equal to the option's own index (i.e., cl_options[IDX].neg_idx == IDX holds). */ int neg_index; /* CL_* flags for this option. */ unsigned int flags; /* Disabled in this configuration. */ BOOL_BITFIELD cl_disabled : 1; /* Options marked with CL_SEPARATE take a number of separate arguments (1 to 4) that is one more than the number in this bit-field. */ unsigned int cl_separate_nargs : 2; /* Option is an alias when used with separate argument. */ BOOL_BITFIELD cl_separate_alias : 1; /* Alias to negative form of option. */ BOOL_BITFIELD cl_negative_alias : 1; /* Option takes no argument in the driver. */ BOOL_BITFIELD cl_no_driver_arg : 1; /* Reject this option in the driver. */ BOOL_BITFIELD cl_reject_driver : 1; /* Reject no- form. */ BOOL_BITFIELD cl_reject_negative : 1; /* Missing argument OK (joined). */ BOOL_BITFIELD cl_missing_ok : 1; /* Argument is an integer >=0. */ BOOL_BITFIELD cl_uinteger : 1; /* Argument is a HOST_WIDE_INT. */ BOOL_BITFIELD cl_host_wide_int : 1; /* Argument should be converted to lowercase. */ BOOL_BITFIELD cl_tolower : 1; /* Report argument with -fverbose-asm */ BOOL_BITFIELD cl_report : 1; /* Argument is an unsigned integer with an optional byte suffix. */ BOOL_BITFIELD cl_byte_size: 1; /* Offset of field for this option in struct gcc_options, or (unsigned short) -1 if none. */ unsigned short flag_var_offset; /* Index in cl_enums of enum used for this option's arguments, for CLVC_ENUM options. */ unsigned short var_enum; /* How this option's value is determined and sets a field. */ enum cl_var_type var_type; /* Value or bit-mask with which to set a field. */ HOST_WIDE_INT var_value; /* Range info minimum, or -1. */ int range_min; /* Range info maximum, or -1. */ int range_max; }; /* Records that the state of an option consists of SIZE bytes starting at DATA. DATA might point to CH in some cases. */ struct cl_option_state { const void *data; size_t size; char ch; }; extern const struct cl_option cl_options[]; extern const unsigned int cl_options_count; extern const char *const lang_names[]; extern const unsigned int cl_lang_count; #define CL_PARAMS (1U << 16) /* Fake entry. Used to display --param info with --help. */ #define CL_WARNING (1U << 17) /* Enables an (optional) warning message. */ #define CL_OPTIMIZATION (1U << 18) /* Enables an (optional) optimization. */ #define CL_DRIVER (1U << 19) /* Driver option. */ #define CL_TARGET (1U << 20) /* Target-specific option. */ #define CL_COMMON (1U << 21) /* Language-independent. */ #define CL_MIN_OPTION_CLASS CL_PARAMS #define CL_MAX_OPTION_CLASS CL_COMMON /* From here on the bits describe attributes of the options. Before this point the bits have described the class of the option. This distinction is important because --help will not list options which only have these higher bits set. */ #define CL_JOINED (1U << 22) /* If takes joined argument. */ #define CL_SEPARATE (1U << 23) /* If takes a separate argument. */ #define CL_UNDOCUMENTED (1U << 24) /* Do not output with --help. */ #define CL_NO_DWARF_RECORD (1U << 25) /* Do not add to producer string. */ #define CL_PCH_IGNORE (1U << 26) /* Do compare state for pch. */ /* Flags for an enumerated option argument. */ #define CL_ENUM_CANONICAL (1 << 0) /* Canonical for this value. */ #define CL_ENUM_DRIVER_ONLY (1 << 1) /* Only accepted in the driver. */ /* Structure describing an enumerated option argument. */ struct cl_enum_arg { /* The argument text, or NULL at the end of the array. */ const char *arg; /* The corresponding integer value. */ int value; /* Flags associated with this argument. */ unsigned int flags; }; /* Structure describing an enumerated set of option arguments. */ struct cl_enum { /* Help text, or NULL if the values should not be listed in --help output. */ const char *help; /* Error message for unknown arguments, or NULL to use a generic error. */ const char *unknown_error; /* Array of possible values. */ const struct cl_enum_arg *values; /* The size of the type used to store a value. */ size_t var_size; /* Function to set a variable of this type. */ void (*set) (void *var, int value); /* Function to get the value of a variable of this type. */ int (*get) (const void *var); }; extern const struct cl_enum cl_enums[]; extern const unsigned int cl_enums_count; /* Possible ways in which a command-line option may be erroneous. These do not include not being known at all; an option index of OPT_SPECIAL_unknown is used for that. */ #define CL_ERR_DISABLED (1 << 0) /* Disabled in this configuration. */ #define CL_ERR_MISSING_ARG (1 << 1) /* Argument required but missing. */ #define CL_ERR_WRONG_LANG (1 << 2) /* Option for wrong language. */ #define CL_ERR_UINT_ARG (1 << 3) /* Bad unsigned integer argument. */ #define CL_ERR_INT_RANGE_ARG (1 << 4) /* Bad unsigned integer argument. */ #define CL_ERR_ENUM_ARG (1 << 5) /* Bad enumerated argument. */ #define CL_ERR_NEGATIVE (1 << 6) /* Negative form of option not permitted (together with OPT_SPECIAL_unknown). */ /* Structure describing the result of decoding an option. */ struct cl_decoded_option { /* The index of this option, or an OPT_SPECIAL_* value for non-options and unknown options. */ size_t opt_index; /* Any warning to give for use of this option, or NULL if none. */ const char *warn_message; /* The string argument, or NULL if none. For OPT_SPECIAL_* cases, the option or non-option command-line argument. */ const char *arg; /* The original text of option plus arguments, with separate argv elements concatenated into one string with spaces separating them. This is for such uses as diagnostics and -frecord-gcc-switches. */ const char *orig_option_with_args_text; /* The canonical form of the option and its argument, for when it is necessary to reconstruct argv elements (in particular, for processing specs and passing options to subprocesses from the driver). */ const char *canonical_option[4]; /* The number of elements in the canonical form of the option and arguments; always at least 1. */ size_t canonical_option_num_elements; /* For a boolean option, 1 for the true case and 0 for the "no-" case. For an unsigned integer option, the value of the argument. 1 in all other cases. */ HOST_WIDE_INT value; /* Any flags describing errors detected in this option. */ int errors; }; /* Structure describing an option deferred for handling after the main option handlers. */ struct cl_deferred_option { /* Elements from struct cl_decoded_option used for deferred options. */ size_t opt_index; const char *arg; int value; }; /* Structure describing a single option-handling callback. */ struct cl_option_handler_func { /* The function called to handle the option. */ bool (*handler) (struct gcc_options *opts, struct gcc_options *opts_set, const struct cl_decoded_option *decoded, unsigned int lang_mask, int kind, location_t loc, const struct cl_option_handlers *handlers, diagnostic_context *dc, void (*target_option_override_hook) (void)); /* The mask that must have some bit in common with the flags for the option for this particular handler to be used. */ unsigned int mask; }; /* Structure describing the callbacks used in handling options. */ struct cl_option_handlers { /* Callback for an unknown option to determine whether to give an error for it, and possibly store information to diagnose the option at a later point. Return true if an error should be given, false otherwise. */ bool (*unknown_option_callback) (const struct cl_decoded_option *decoded); /* Callback to handle, and possibly diagnose, an option for another language. */ void (*wrong_lang_callback) (const struct cl_decoded_option *decoded, unsigned int lang_mask); /* Target option override hook. */ void (*target_option_override_hook) (void); /* The number of individual handlers. */ size_t num_handlers; /* The handlers themselves. */ struct cl_option_handler_func handlers[3]; }; /* Hold command-line options associated with stack limitation. */ extern const char *opt_fstack_limit_symbol_arg; extern int opt_fstack_limit_register_no; /* Input file names. */ extern const char **in_fnames; /* The count of input filenames. */ extern unsigned num_in_fnames; extern char *opts_concat (const char *first, ...); /* Obstack for option strings. */ extern struct obstack opts_obstack; size_t find_opt (const char *input, unsigned int lang_mask); extern HOST_WIDE_INT integral_argument (const char *arg, int * = NULL, bool = false); extern bool enum_value_to_arg (const struct cl_enum_arg *enum_args, const char **argp, int value, unsigned int lang_mask); extern void decode_cmdline_options_to_array (unsigned int argc, const char **argv, unsigned int lang_mask, struct cl_decoded_option **decoded_options, unsigned int *decoded_options_count); extern void init_options_once (void); extern void init_options_struct (struct gcc_options *opts, struct gcc_options *opts_set); extern void init_opts_obstack (void); extern void decode_cmdline_options_to_array_default_mask (unsigned int argc, const char **argv, struct cl_decoded_option **decoded_options, unsigned int *decoded_options_count); extern void set_default_handlers (struct cl_option_handlers *handlers, void (*target_option_override_hook) (void)); extern void decode_options (struct gcc_options *opts, struct gcc_options *opts_set, struct cl_decoded_option *decoded_options, unsigned int decoded_options_count, location_t loc, diagnostic_context *dc, void (*target_option_override_hook) (void)); extern int option_enabled (int opt_idx, unsigned lang_mask, void *opts); extern bool get_option_state (struct gcc_options *, int, struct cl_option_state *); extern void set_option (struct gcc_options *opts, struct gcc_options *opts_set, int opt_index, HOST_WIDE_INT value, const char *arg, int kind, location_t loc, diagnostic_context *dc); extern void *option_flag_var (int opt_index, struct gcc_options *opts); bool handle_generated_option (struct gcc_options *opts, struct gcc_options *opts_set, size_t opt_index, const char *arg, HOST_WIDE_INT value, unsigned int lang_mask, int kind, location_t loc, const struct cl_option_handlers *handlers, bool generated_p, diagnostic_context *dc); void generate_option (size_t opt_index, const char *arg, HOST_WIDE_INT value, unsigned int lang_mask, struct cl_decoded_option *decoded); void generate_option_input_file (const char *file, struct cl_decoded_option *decoded); extern void read_cmdline_option (struct gcc_options *opts, struct gcc_options *opts_set, struct cl_decoded_option *decoded, location_t loc, unsigned int lang_mask, const struct cl_option_handlers *handlers, diagnostic_context *dc); extern void control_warning_option (unsigned int opt_index, int kind, const char *arg, bool imply, location_t loc, unsigned int lang_mask, const struct cl_option_handlers *handlers, struct gcc_options *opts, struct gcc_options *opts_set, diagnostic_context *dc); extern char *write_langs (unsigned int mask); extern void print_ignored_options (void); extern void handle_common_deferred_options (void); unsigned int parse_sanitizer_options (const char *, location_t, int, unsigned int, int, bool); unsigned int parse_no_sanitize_attribute (char *value); extern bool common_handle_option (struct gcc_options *opts, struct gcc_options *opts_set, const struct cl_decoded_option *decoded, unsigned int lang_mask, int kind, location_t loc, const struct cl_option_handlers *handlers, diagnostic_context *dc, void (*target_option_override_hook) (void)); extern bool target_handle_option (struct gcc_options *opts, struct gcc_options *opts_set, const struct cl_decoded_option *decoded, unsigned int lang_mask, int kind, location_t loc, const struct cl_option_handlers *handlers, diagnostic_context *dc, void (*target_option_override_hook) (void)); extern void finish_options (struct gcc_options *opts, struct gcc_options *opts_set, location_t loc); extern void print_help (struct gcc_options *opts, unsigned int lang_mask, const char *help_option_argument); extern void default_options_optimization (struct gcc_options *opts, struct gcc_options *opts_set, struct cl_decoded_option *decoded_options, unsigned int decoded_options_count, location_t loc, unsigned int lang_mask, const struct cl_option_handlers *handlers, diagnostic_context *dc); extern void set_struct_debug_option (struct gcc_options *opts, location_t loc, const char *value); extern bool opt_enum_arg_to_value (size_t opt_index, const char *arg, int *value, unsigned int lang_mask); extern const struct sanitizer_opts_s { const char *const name; unsigned int flag; size_t len; bool can_recover; } sanitizer_opts[]; extern vec<const char *> help_option_arguments; extern void add_misspelling_candidates (auto_vec<char *> *candidates, const struct cl_option *option, const char *base_option); extern const char *candidates_list_and_hint (const char *arg, char *&str, const auto_vec <const char *> & candidates); extern bool parse_and_check_align_values (const char *flag, const char *name, auto_vec<unsigned> &result_values, bool report_error, location_t loc); extern void parse_options_from_collect_gcc_options (const char *, obstack *, int *); extern void prepend_xassembler_to_collect_as_options (const char *, obstack *); /* Set OPTION in OPTS to VALUE if the option is not set in OPTS_SET. */ #define SET_OPTION_IF_UNSET(OPTS, OPTS_SET, OPTION, VALUE) \ do \ { \ if (!(OPTS_SET)->x_ ## OPTION) \ (OPTS)->x_ ## OPTION = VALUE; \ } \ while (false) #endif
{ "pile_set_name": "Github" }
# frozen_string_literal: true require 'spec_helper' describe 'Rake task buttons', type: :feature do before do sign_in_as_user FactoryGirl.create(:superuser) # The following is necessary to "undo" a stub / mock called for all feature # specs that was designed to avoid weird issues with persistent AppConfig # settings across tests. In principle, we shouldn't really be using mock # data in feature specs, but rather than try to fix all specs we're going to # just make sure that for these specs we get an actual AppConfig object so # that the form renders correctly. For reference, the stub occurs in # spec/support/app_config_helpers.rb, called in # spec/support/feature_helpers.rb. FactoryGirl.create(:app_config).tap do |ac| allow(AppConfig).to receive(:first).and_return(ac) end end it 'works for daily tasks' do visit root_path click_on 'Settings' click_on 'Run Daily Tasks' expect(page).to have_css('.alert-success', text: /Daily tasks queued and running/) end it 'works for hourly tasks' do visit root_path click_on 'Settings' click_on 'Run Hourly Tasks' expect(page).to have_css('.alert-success', text: /Hourly tasks queued and running/) end end
{ "pile_set_name": "Github" }
#ifndef DEMO_MODEL_H #define DEMO_MODEL_H #include <Aabb.h> #include <Timer.h> #include <DX12_ResourceDescTable.h> #include <SkinnedDecals.h> #define CURRENT_DEMO_MODEL_VERSION 1 #define SKINNING_THREAD_GROUP_SIZE 64 class DX12_PipelineState; class DX12_Buffer; class DX12_TimerQuery; class Material; class Shading; struct WeightIndex { UINT firstIndex; UINT numIndices; }; struct Weight { UINT jointIndex; float weight; Vector3 position; Vector3 normal; Vector3 tangent; }; struct Joint { Vector3 translation; Quat rotation; }; struct AnimFrame { Joint *joints; Aabb bounds; }; struct DemoSubModel { DemoSubModel(): baseNoDecalsPS(nullptr), baseWithDecalsPS(nullptr), material(nullptr), firstIndex(0), numIndices(0) { } DX12_PipelineState *baseNoDecalsPS; DX12_PipelineState *baseWithDecalsPS; DX12_ResourceDescTable materialDT; Material *material; UINT firstIndex; UINT numIndices; }; // DemoModel // // Simple model format (".model") for storing animated models (only one animation set is supported). // Data generated by loading a MD5 model, precalculating all information that is required for culling, // skinning and rendering the model, and storing these information into a binary file format. class DemoModel { public: friend class SkinnedDecals; struct ModelConstData { Matrix4 transformMatrix; UINT numVertices; UINT debugDecalMask; }; DemoModel(): subModels(nullptr), animFrames(nullptr), numSubModels(0), numJoints(0), numAnimFrames(0), currentAnimFrameIndex(0), nextAnimFrameIndex(0), pauseAnim(false), visible(false), useDecals(true), debugDecalMask(false), indexBuffer(nullptr), weightIndexSB(nullptr), weightSB(nullptr), jointSB(nullptr), vertexPositionSB(nullptr), vertexNormalSB(nullptr), vertexTangentSB(nullptr), vertexUvHandednessSB(nullptr), modelCB(nullptr), skinningPS(nullptr), skinningTQ(nullptr), basePassTQ(nullptr), skinnedDecals(nullptr), shadingPP(nullptr) { interpAnimFrame.joints = nullptr; } ~DemoModel() { Release(); } void Release(); bool Load(const char *filename); bool InitSkinnedDecals(const char** materialNames, UINT numMaterials); void Render(); const DemoSubModel* GetSubModel(UINT index) const { assert(index < numSubModels); return &subModels[index]; } UINT GetNumSubModels() const { return numSubModels; } void SetPosition(const Vector3 &position) { this->position = position; } Vector3 GetPosition() const { return position; } void SetRotation(const Vector3 &rotation) { this->rotation = rotation; } Vector3 GetRotation() const { return rotation; } const Aabb& GetBounds() const { return interpAnimFrame.bounds; } void PauseAnim(bool pauseAnim) { this->pauseAnim = pauseAnim; } bool IsAnimPaused() const { return pauseAnim; } void UseDecals(bool useDecals) { this->useDecals = useDecals; } bool AreDecalsUsed() const { return useDecals; } void EnableDebugDecalMask(bool enable) { debugDecalMask = enable; } bool IsDebugDecalMaskEnabled() const { return debugDecalMask; } float GetSkinningGpuTime() const { return skinningTQ->GetGpuElapsedTime(); } float GetBasePassGpuTime() const { return basePassTQ->GetGpuElapsedTime(); } SkinnedDecals *GetSkinnedDecals() { return skinnedDecals; } private: void UpdateSkeleton(); void UpdateBuffers(); void PerformSkinning(); void RenderBasePass(); DemoSubModel *subModels; AnimFrame *animFrames; AnimFrame interpAnimFrame; Timer animTimer; UINT numSubModels; UINT numJoints; UINT numAnimFrames; UINT currentAnimFrameIndex, nextAnimFrameIndex; ModelConstData modelConstData; Vector3 position; Vector3 rotation; bool pauseAnim; bool visible; bool useDecals; bool debugDecalMask; DX12_Buffer *indexBuffer; DX12_Buffer *weightIndexSB; DX12_Buffer *weightSB; DX12_Buffer *jointSB; DX12_Buffer *vertexPositionSB; DX12_Buffer *vertexNormalSB; DX12_Buffer *vertexTangentSB; DX12_Buffer *vertexUvHandednessSB; DX12_Buffer *modelCB; DX12_PipelineState *skinningPS; DX12_ResourceDescTable skinningDT; DX12_ResourceDescTable basePassVertexDT; DX12_TimerQuery *skinningTQ; DX12_TimerQuery *basePassTQ; SkinnedDecals *skinnedDecals; Shading *shadingPP; }; #endif
{ "pile_set_name": "Github" }
use strict; use warnings; use Net::EmptyPort qw(check_port empty_port); use Test::More; use t::Util; plan skip_all => 'curl not found' unless prog_exists('curl'); plan skip_all => 'curl does not support HTTP/2' unless curl_supports_http2(); my $upstream_port = empty_port(); $| = 1; my $socket = new IO::Socket::INET ( LocalHost => '127.0.0.1', LocalPort => $upstream_port, Proto => 'tcp', Listen => 1, Reuse => 1 ); die "cannot create socket $!\n" unless $socket; check_port($upstream_port) or die "can't connect to server socket"; # accept and close check_port's connection my $client_socket = $socket->accept(); close($client_socket); my $server = spawn_h2o(<< "EOT"); hosts: default: paths: "/": proxy.reverse.url: http://127.0.0.1:$upstream_port EOT sub doone { my $cmd = shift; my $upstream_response = shift; my $expected = shift; my $test_description = shift; die unless pipe(my $reader, my $writer); my $pid = fork(); die if not defined $pid; if ($pid == 0) { $| = 1; close($reader); print $writer qx{$cmd}; close($writer); exit(0); } close($writer); my $req; $client_socket = $socket->accept(); $client_socket->recv($req, 1024); $client_socket->send($upstream_response); close($client_socket); my $curl_output = do { local $/; <$reader> }; like $curl_output, qr{$expected}, $test_description; close($reader); wait(); } sub doit { my $proto = shift; my $cmd = "curl -k -svo /dev/null --http${proto} https://127.0.0.1:$server->{'tls_port'}/ 2>&1"; my $resp_preface = "HTTP/1.1 200 Ok\r\nTransfer-encoding:chunked\r\n\r\n"; my $err_string = "Illegal or missing hexadecimal sequence in chunked-encoding"; if ($proto == "2") { # curl-7.57.0 includes "was not closed cleanly" # curl-7.68.0 includes "left intact" $err_string = qr{(?:left intact|was not closed cleanly)}; } doone($cmd, $resp_preface."1\r\na", "left intact", "HTTP/$proto curl reports a clean connection on missing \\r\\n0\\r\\n"); doone($cmd, $resp_preface, $err_string, "HTTP/$proto curl reports a broken connection when upstream sent no chunks"); doone($cmd, $resp_preface."2\r\na", $err_string, "HTTP/$proto curl reports a broken connection on truncated chunk"); doone($cmd, $resp_preface."1", $err_string, "HTTP/$proto curl reports a broken connection on truncated chunk size"); } subtest "HTTP/1.1" => sub { doit("1.1"); }; subtest "HTTP/2" => sub { doit("2"); }; $socket->close(); done_testing();
{ "pile_set_name": "Github" }
#include <CtrlLib/CtrlLib.h> #include <plugin/jpg/jpg.h> using namespace Upp; static void sLoadImage(const String& path, Image& result) { result = StreamRaster::LoadFileAny(path); } GUI_APP_MAIN { FileSel fs; fs.AllFilesType(); fs.Type("Text", "*.txt"); fs.WhenIconLazy = sLoadImage; fs.ExecuteOpen(); }
{ "pile_set_name": "Github" }
"""runpy.py - locating and running Python code using the module namespace Provides support for locating and running Python scripts using the Python module namespace instead of the native filesystem. This allows Python code to play nicely with non-filesystem based PEP 302 importers when locating support scripts as well as when importing modules. """ # Written by Nick Coghlan <ncoghlan at gmail.com> # to implement PEP 338 (Executing Modules as Scripts) import sys import imp from pkgutil import read_code try: from imp import get_loader except ImportError: from pkgutil import get_loader __all__ = [ "run_module", "run_path", ] class _TempModule(object): """Temporarily replace a module in sys.modules with an empty namespace""" def __init__(self, mod_name): self.mod_name = mod_name self.module = imp.new_module(mod_name) self._saved_module = [] def __enter__(self): mod_name = self.mod_name try: self._saved_module.append(sys.modules[mod_name]) except KeyError: pass sys.modules[mod_name] = self.module return self def __exit__(self, *args): if self._saved_module: sys.modules[self.mod_name] = self._saved_module[0] else: del sys.modules[self.mod_name] self._saved_module = [] class _ModifiedArgv0(object): def __init__(self, value): self.value = value self._saved_value = self._sentinel = object() def __enter__(self): if self._saved_value is not self._sentinel: raise RuntimeError("Already preserving saved value") self._saved_value = sys.argv[0] sys.argv[0] = self.value def __exit__(self, *args): self.value = self._sentinel sys.argv[0] = self._saved_value def _run_code(code, run_globals, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in nominated namespace""" if init_globals is not None: run_globals.update(init_globals) run_globals.update(__name__ = mod_name, __file__ = mod_fname, __loader__ = mod_loader, __package__ = pkg_name) exec code in run_globals return run_globals def _run_module_code(code, init_globals=None, mod_name=None, mod_fname=None, mod_loader=None, pkg_name=None): """Helper to run code in new namespace with sys modified""" with _TempModule(mod_name) as temp_module, _ModifiedArgv0(mod_fname): mod_globals = temp_module.module.__dict__ _run_code(code, mod_globals, init_globals, mod_name, mod_fname, mod_loader, pkg_name) # Copy the globals of the temporary module, as they # may be cleared when the temporary module goes away return mod_globals.copy() # This helper is needed due to a missing component in the PEP 302 # loader protocol (specifically, "get_filename" is non-standard) # Since we can't introduce new features in maintenance releases, # support was added to zipimporter under the name '_get_filename' def _get_filename(loader, mod_name): for attr in ("get_filename", "_get_filename"): meth = getattr(loader, attr, None) if meth is not None: return meth(mod_name) return None # Helper to get the loader, code and filename for a module def _get_module_details(mod_name): loader = get_loader(mod_name) if loader is None: raise ImportError("No module named %s" % mod_name) if loader.is_package(mod_name): if mod_name == "__main__" or mod_name.endswith(".__main__"): raise ImportError("Cannot use package as __main__ module") try: pkg_main_name = mod_name + ".__main__" return _get_module_details(pkg_main_name) except ImportError, e: raise ImportError(("%s; %r is a package and cannot " + "be directly executed") %(e, mod_name)) code = loader.get_code(mod_name) if code is None: raise ImportError("No code object available for %s" % mod_name) filename = _get_filename(loader, mod_name) return mod_name, loader, code, filename def _get_main_module_details(): # Helper that gives a nicer error message when attempting to # execute a zipfile or directory by invoking __main__.py main_name = "__main__" try: return _get_module_details(main_name) except ImportError as exc: if main_name in str(exc): raise ImportError("can't find %r module in %r" % (main_name, sys.path[0])) raise # This function is the actual implementation of the -m switch and direct # execution of zipfiles and directories and is deliberately kept private. # This avoids a repeat of the situation where run_module() no longer met the # needs of mainmodule.c, but couldn't be changed because it was public def _run_module_as_main(mod_name, alter_argv=True): """Runs the designated module in the __main__ namespace Note that the executed module will have full access to the __main__ namespace. If this is not desirable, the run_module() function should be used to run the module code in a fresh namespace. At the very least, these variables in __main__ will be overwritten: __name__ __file__ __loader__ __package__ """ try: if alter_argv or mod_name != "__main__": # i.e. -m switch mod_name, loader, code, fname = _get_module_details(mod_name) else: # i.e. directory or zipfile execution mod_name, loader, code, fname = _get_main_module_details() except ImportError as exc: msg = "%s: %s" % (sys.executable, str(exc)) sys.exit(msg) pkg_name = mod_name.rpartition('.')[0] main_globals = sys.modules["__main__"].__dict__ if alter_argv: sys.argv[0] = fname return _run_code(code, main_globals, None, "__main__", fname, loader, pkg_name) def run_module(mod_name, init_globals=None, run_name=None, alter_sys=False): """Execute a module's code without importing it Returns the resulting top level namespace dictionary """ mod_name, loader, code, fname = _get_module_details(mod_name) if run_name is None: run_name = mod_name pkg_name = mod_name.rpartition('.')[0] if alter_sys: return _run_module_code(code, init_globals, run_name, fname, loader, pkg_name) else: # Leave the sys module alone return _run_code(code, {}, init_globals, run_name, fname, loader, pkg_name) # XXX (ncoghlan): Perhaps expose the C API function # as imp.get_importer instead of reimplementing it in Python? def _get_importer(path_name): """Python version of PyImport_GetImporter C API function""" cache = sys.path_importer_cache try: importer = cache[path_name] except KeyError: # Not yet cached. Flag as using the # standard machinery until we finish # checking the hooks cache[path_name] = None for hook in sys.path_hooks: try: importer = hook(path_name) break except ImportError: pass else: # The following check looks a bit odd. The trick is that # NullImporter raises ImportError if the supplied path is a # *valid* directory entry (and hence able to be handled # by the standard import machinery) try: importer = imp.NullImporter(path_name) except ImportError: return None cache[path_name] = importer return importer def _get_code_from_file(fname): # Check for a compiled file first with open(fname, "rb") as f: code = read_code(f) if code is None: # That didn't work, so try it as normal source code with open(fname, "rU") as f: code = compile(f.read(), fname, 'exec') return code def run_path(path_name, init_globals=None, run_name=None): """Execute code located at the specified filesystem location Returns the resulting top level namespace dictionary The file path may refer directly to a Python script (i.e. one that could be directly executed with execfile) or else it may refer to a zipfile or directory containing a top level __main__.py script. """ if run_name is None: run_name = "<run_path>" importer = _get_importer(path_name) if isinstance(importer, imp.NullImporter): # Not a valid sys.path entry, so run the code directly # execfile() doesn't help as we want to allow compiled files code = _get_code_from_file(path_name) return _run_module_code(code, init_globals, run_name, path_name) else: # Importer is defined for path, so add it to # the start of sys.path sys.path.insert(0, path_name) try: # Here's where things are a little different from the run_module # case. There, we only had to replace the module in sys while the # code was running and doing so was somewhat optional. Here, we # have no choice and we have to remove it even while we read the # code. If we don't do this, a __loader__ attribute in the # existing __main__ module may prevent location of the new module. main_name = "__main__" saved_main = sys.modules[main_name] del sys.modules[main_name] try: mod_name, loader, code, fname = _get_main_module_details() finally: sys.modules[main_name] = saved_main pkg_name = "" with _TempModule(run_name) as temp_module, \ _ModifiedArgv0(path_name): mod_globals = temp_module.module.__dict__ return _run_code(code, mod_globals, init_globals, run_name, fname, loader, pkg_name).copy() finally: try: sys.path.remove(path_name) except ValueError: pass if __name__ == "__main__": # Run the module specified as the next command line argument if len(sys.argv) < 2: print >> sys.stderr, "No module specified for execution" else: del sys.argv[0] # Make the requested module sys.argv[0] _run_module_as_main(sys.argv[0])
{ "pile_set_name": "Github" }
@ECHO OFF FOR /F "tokens=*" %%G IN ('DIR /B /AD /S _ReSharper.*') DO echo "%%G" && rd /Q /S "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /AD /S *Debug*') DO echo "%%G" && rd /Q /S "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /AD /S *Release*') DO echo "%%G" && rd /Q /S "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /AD /S *ipch') DO echo "%%G" && rd /Q /S "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.user') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.bak') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.ncb') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.zip') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.xml') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S *.sdf') DO echo "%%G" && del /Q "%%G" FOR /F "tokens=*" %%G IN ('DIR /B /S /AH *.suo') DO echo "%%G" && del /Q /AH "%%G"
{ "pile_set_name": "Github" }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>CSS Test: Attribute selectors with hyphens and underscores</title> <link rel="author" title="Microsoft" href="http://www.microsoft.com/" /> <link rel="help" href="http://www.w3.org/TR/CSS21/syndata.html" /> <link rel="match" href="../reference/filler-text-below-green.xht"/> <meta name="flags" content="" /> <meta name="assert" content="Attribute selectors are valid if they begin with hyphens and then underscores." /> <style type="text/css"> [-_hyphenunderscore="true"], div { color: green; } </style> </head> <body> <p>Test passes if the "Filler Text" below is green.</p> <div>Filler Text</div> </body> </html>
{ "pile_set_name": "Github" }
" Author: Sumner Evans <[email protected]> " Description: write-good for Texinfo files call ale#handlers#writegood#DefineLinter('texinfo')
{ "pile_set_name": "Github" }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using Newtonsoft.Json; using Duplicati.Library.Interface; namespace Duplicati.Library.Main.Volumes { public class IndexVolumeWriter : VolumeWriterBase { private StreamWriter m_streamwriter = null; private JsonWriter m_writer = null; private long m_volumes = 0; private long m_blocks = 0; private long m_blocklists = 0; public long VolumeCount { get { return m_volumes; } } public long BlockCount { get { return m_blocks; } } public long Blocklists { get { return m_blocklists; } } public IndexVolumeWriter(Options options) : base(options) { } public override RemoteVolumeType FileType { get { return RemoteVolumeType.Index; } } public void StartVolume(string filename) { if (m_writer != null || m_streamwriter != null) throw new InvalidOperationException("Previous volume not finished, call FinishVolume before starting a new volume"); m_volumes++; m_streamwriter = new StreamWriter(m_compression.CreateFile(INDEX_VOLUME_FOLDER + filename, CompressionHint.Compressible, DateTime.UtcNow)); m_writer = new JsonTextWriter(m_streamwriter); m_writer.WriteStartObject(); m_writer.WritePropertyName("blocks"); m_writer.WriteStartArray(); } public void AddBlock(string hash, long size) { m_writer.WriteStartObject(); m_writer.WritePropertyName("hash"); m_writer.WriteValue(hash); m_writer.WritePropertyName("size"); m_writer.WriteValue(size); m_writer.WriteEndObject(); m_blocks++; } public void FinishVolume(string volumehash, long volumesize) { m_writer.WriteEndArray(); m_writer.WritePropertyName("volumehash"); m_writer.WriteValue(volumehash); m_writer.WritePropertyName("volumesize"); m_writer.WriteValue(volumesize); m_writer.WriteEndObject(); try { m_writer.Close(); } finally { m_writer = null; } try { m_streamwriter.Dispose(); } finally { m_streamwriter = null; } } public void WriteBlocklist(string hash, byte[] data, int offset, int size) { if (size % m_blockhashsize != 0) throw new InvalidDataException($"Attempted to write a blocklist with {size} bytes which is not evenly divisible with {m_blockhashsize}"); m_blocklists++; //Filenames are encoded with "modified Base64 for URL" https://en.wikipedia.org/wiki/Base64#URL_applications, using (var s = m_compression.CreateFile(INDEX_BLOCKLIST_FOLDER + Library.Utility.Utility.Base64PlainToBase64Url(hash), CompressionHint.Noncompressible, DateTime.UtcNow)) s.Write(data, offset, size); } public void WriteBlocklist(string hash, Stream source) { m_blocklists++; //Filenames are encoded with "modified Base64 for URL" https://en.wikipedia.org/wiki/Base64#URL_applications, using (var s = m_compression.CreateFile(INDEX_BLOCKLIST_FOLDER + Library.Utility.Utility.Base64PlainToBase64Url(hash), CompressionHint.Noncompressible, DateTime.UtcNow)) { var size = Library.Utility.Utility.CopyStream(source, s); if (size % m_blockhashsize != 0) throw new InvalidDataException($"Wrote a blocklist with {size} bytes which is not evenly divisible with {m_blockhashsize}"); } } public void CopyFrom(IndexVolumeReader rd, Func<string, string> filename_mapping) { foreach(var n in rd.Volumes) { this.StartVolume(filename_mapping(n.Filename)); foreach(var x in n.Blocks) this.AddBlock(x.Key, x.Value); this.FinishVolume(n.Hash, n.Length); } foreach(var b in rd.BlockLists) using(var s = b.Data) this.WriteBlocklist(b.Hash, s); } public override void Dispose() { if (m_writer != null || m_streamwriter != null) throw new InvalidOperationException("Attempted to dispose an index volume that was being written"); base.Dispose(); } } }
{ "pile_set_name": "Github" }
------------------- 基本的根据条件检索 | ------------------- # 可以一次性检索多个index * 直接检索多个index GET /<index>,<index>/_search * 一次性检索所有的index GET /_all/_search * 通过 * 来匹配多个index GET /<prefix>*,*<sufix>/_search ------------------- 基本的根据条件检索 | ------------------- # 请求 GET /<index>/_search?q=<query> { "took" : 2, * 执行搜索的时间(以毫秒为单位) "timed_out" : false, * 搜索是否超时 "_shards" : { "total" : 1, * 搜索了多少个分片 "successful" : 1, * 搜索成功的分片数量 "skipped" : 0, * 跳过的分片数量 "failed" : 0 * 搜索失败的分片数量 }, "hits" : { "total" : { "value" : 13, "relation" : "eq" }, "max_score" : 1.0, "hits" : [ { "_index" : "customer", "_type" : "_doc", "_id" : "TsVMQGsBor31qRgUxQmS", "_score" : 1.0, "_source" : { "name" : "KevinBlandy" } } ] } } ------------------- query参数 | ------------------- # 过滤参数:q q=* * 检索所有, q=* q=<value> * 任何字段, 只要包含该值就满足条件 * 搜索的是_all field q=<field>:<value> * 全文检索, 只要是指定字段中有关键字的都OK, :q=name:KevinBlandy * 有多个匹配value值, 使用逗号分隔 q=<field>:<+/-><value> * + 表示必须包含, - 表示必须不包含: q=-author.name:Litch # 排序擦数:sort sort=<field>:<asc/desc> * 如果有多个, 使用逗号分隔:sort=age:asc,_id:desc # 分页参数:size & from * size,每页显示的记录数量, 默认10 * from,从第几条数据开始检索,默认0(表示第一条) * deep paging问题 * deep paging,简单来说,就是搜索得特别深,比如1000000条数据,每页显示10条,此时需要检索最后一页的数据 * 符合请求的数据,可能存在于多个primary shard,replica shard,于是就要把所有数据汇总到 coordinating node(协调节点) * 由协调节点进行排序,取出最符合条件的数据,按照分页返回 * 这个过程耗费带宽,内存,网络计算,这个就是deep paging问题,我们的开发尽量要避免这种情 # _source 数据过滤参数: _source * 检索数据是否要携带 _source 数据, 值可以是 true/false * 也可以通过该参数来指定要检索的字段 GET /goods/_doc/1?_source=author.name,author.age _source_includes _source_excludes * 过滤/包含指定的 _source 数据 * 支持有多个值, 使用否号分割 * 支持通配符:* GET /goods/_doc/1?_source=*.name # stored_fields //TODO # timeout 超时参数 * 默认无超时 # df # analyzer # analyze_wildcard # batched_reduce_size # default_operator # lenient # explain # track_scores # track_total_hits # terminate_after # search_type # allow_partial_search_results # scroll * 滚动搜索(有点像迭代器的感觉) * 每次仅仅响应一批数据, 直到响应完毕所有 * 第一次检索的时候, 会生成快照, 在响应完毕之前, doc的修改不可见(可重复读的感觉) # filter_path * 可以过滤整个JSON结果的字段, 包括元数据信息 * 支持对象导航 GET /<index>/_search?filter_path=hits.hits // 仅仅显示hits信息 # error_trace * true/false, 是否在异常的时候, 响应堆栈信息
{ "pile_set_name": "Github" }
package controllers; import java.math.BigDecimal; import apimodels.Client; import java.time.LocalDate; import java.time.OffsetDateTime; import apimodels.OuterComposite; import apimodels.User; import play.mvc.Controller; import play.mvc.Result; import play.mvc.Http; import java.util.List; import java.util.Map; import java.util.ArrayList; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.JsonNode; import com.google.inject.Inject; import java.io.File; import swagger.SwaggerUtils; import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; import play.Configuration; import swagger.SwaggerUtils.ApiAction; public class FakeApiController extends Controller { private final FakeApiControllerImpInterface imp; private final ObjectMapper mapper; private final Configuration configuration; @Inject private FakeApiController(Configuration configuration, FakeApiControllerImpInterface imp) { this.imp = imp; mapper = new ObjectMapper(); this.configuration = configuration; } @ApiAction public Result fakeOuterBooleanSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); Boolean body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Boolean.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } Boolean obj = imp.fakeOuterBooleanSerialize(body); JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterCompositeSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); OuterComposite body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), OuterComposite.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } OuterComposite obj = imp.fakeOuterCompositeSerialize(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterNumberSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); BigDecimal body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), BigDecimal.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } BigDecimal obj = imp.fakeOuterNumberSerialize(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result fakeOuterStringSerialize() throws Exception { JsonNode nodebody = request().body().asJson(); String body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), String.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { body = null; } String obj = imp.fakeOuterStringSerialize(body); JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result testBodyWithQueryParams() throws Exception { JsonNode nodebody = request().body().asJson(); User body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), User.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { throw new IllegalArgumentException("'body' parameter is required"); } String valuequery = request().getQueryString("query"); String query; if (valuequery != null) { query = valuequery; } else { throw new IllegalArgumentException("'query' parameter is required"); } imp.testBodyWithQueryParams(body, query); return ok(); } @ApiAction public Result testClientModel() throws Exception { JsonNode nodebody = request().body().asJson(); Client body; if (nodebody != null) { body = mapper.readValue(nodebody.toString(), Client.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(body); } } else { throw new IllegalArgumentException("'body' parameter is required"); } Client obj = imp.testClientModel(body); if (configuration.getBoolean("useOutputBeanValidation")) { SwaggerUtils.validate(obj); } JsonNode result = mapper.valueToTree(obj); return ok(result); } @ApiAction public Result testEndpointParameters() throws Exception { String valueinteger = (request().body().asMultipartFormData().asFormUrlEncoded().get("integer"))[0]; Integer integer; if (valueinteger != null) { integer = Integer.parseInt(valueinteger); } else { integer = null; } String valueint32 = (request().body().asMultipartFormData().asFormUrlEncoded().get("int32"))[0]; Integer int32; if (valueint32 != null) { int32 = Integer.parseInt(valueint32); } else { int32 = null; } String valueint64 = (request().body().asMultipartFormData().asFormUrlEncoded().get("int64"))[0]; Long int64; if (valueint64 != null) { int64 = Long.parseLong(valueint64); } else { int64 = null; } String valuenumber = (request().body().asMultipartFormData().asFormUrlEncoded().get("number"))[0]; BigDecimal number; if (valuenumber != null) { number = new BigDecimal(valuenumber); } else { throw new IllegalArgumentException("'number' parameter is required"); } String value_float = (request().body().asMultipartFormData().asFormUrlEncoded().get("float"))[0]; Float _float; if (value_float != null) { _float = Float.parseFloat(value_float); } else { _float = null; } String value_double = (request().body().asMultipartFormData().asFormUrlEncoded().get("double"))[0]; Double _double; if (value_double != null) { _double = Double.parseDouble(value_double); } else { throw new IllegalArgumentException("'double' parameter is required"); } String valuestring = (request().body().asMultipartFormData().asFormUrlEncoded().get("string"))[0]; String string; if (valuestring != null) { string = valuestring; } else { string = null; } String valuepatternWithoutDelimiter = (request().body().asMultipartFormData().asFormUrlEncoded().get("pattern_without_delimiter"))[0]; String patternWithoutDelimiter; if (valuepatternWithoutDelimiter != null) { patternWithoutDelimiter = valuepatternWithoutDelimiter; } else { throw new IllegalArgumentException("'pattern_without_delimiter' parameter is required"); } String value_byte = (request().body().asMultipartFormData().asFormUrlEncoded().get("byte"))[0]; byte[] _byte; if (value_byte != null) { _byte = value_byte.getBytes(); } else { throw new IllegalArgumentException("'byte' parameter is required"); } String valuebinary = (request().body().asMultipartFormData().asFormUrlEncoded().get("binary"))[0]; byte[] binary; if (valuebinary != null) { binary = valuebinary.getBytes(); } else { binary = null; } String valuedate = (request().body().asMultipartFormData().asFormUrlEncoded().get("date"))[0]; LocalDate date; if (valuedate != null) { date = LocalDate.parse(valuedate); } else { date = null; } String valuedateTime = (request().body().asMultipartFormData().asFormUrlEncoded().get("dateTime"))[0]; OffsetDateTime dateTime; if (valuedateTime != null) { dateTime = OffsetDateTime.parse(valuedateTime); } else { dateTime = null; } String valuepassword = (request().body().asMultipartFormData().asFormUrlEncoded().get("password"))[0]; String password; if (valuepassword != null) { password = valuepassword; } else { password = null; } String valueparamCallback = (request().body().asMultipartFormData().asFormUrlEncoded().get("callback"))[0]; String paramCallback; if (valueparamCallback != null) { paramCallback = valueparamCallback; } else { paramCallback = null; } imp.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); return ok(); } @ApiAction public Result testEnumParameters() throws Exception { String[] enumQueryStringArrayArray = request().queryString().get("enum_query_string_array"); List<String> enumQueryStringArrayList = SwaggerUtils.parametersToList("csv", enumQueryStringArrayArray); List<String> enumQueryStringArray = new ArrayList<String>(); for (String curParam : enumQueryStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumQueryStringArray.add(curParam); } } String valueenumQueryString = request().getQueryString("enum_query_string"); String enumQueryString; if (valueenumQueryString != null) { enumQueryString = valueenumQueryString; } else { enumQueryString = "-efg"; } String valueenumQueryInteger = request().getQueryString("enum_query_integer"); Integer enumQueryInteger; if (valueenumQueryInteger != null) { enumQueryInteger = Integer.parseInt(valueenumQueryInteger); } else { enumQueryInteger = null; } String[] enumFormStringArrayArray = request().body().asMultipartFormData().asFormUrlEncoded().get("enum_form_string_array"); List<String> enumFormStringArrayList = SwaggerUtils.parametersToList("csv", enumFormStringArrayArray); List<String> enumFormStringArray = new ArrayList<String>(); for (String curParam : enumFormStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumFormStringArray.add(curParam); } } String valueenumFormString = (request().body().asMultipartFormData().asFormUrlEncoded().get("enum_form_string"))[0]; String enumFormString; if (valueenumFormString != null) { enumFormString = valueenumFormString; } else { enumFormString = "-efg"; } String valueenumQueryDouble = (request().body().asMultipartFormData().asFormUrlEncoded().get("enum_query_double"))[0]; Double enumQueryDouble; if (valueenumQueryDouble != null) { enumQueryDouble = Double.parseDouble(valueenumQueryDouble); } else { enumQueryDouble = null; } String[] enumHeaderStringArrayArray = request().headers().get("enum_header_string_array"); List<String> enumHeaderStringArrayList = SwaggerUtils.parametersToList("csv", enumHeaderStringArrayArray); List<String> enumHeaderStringArray = new ArrayList<String>(); for (String curParam : enumHeaderStringArrayList) { if (!curParam.isEmpty()) { //noinspection UseBulkOperation enumHeaderStringArray.add(curParam); } } String valueenumHeaderString = request().getHeader("enum_header_string"); String enumHeaderString; if (valueenumHeaderString != null) { enumHeaderString = valueenumHeaderString; } else { enumHeaderString = "-efg"; } imp.testEnumParameters(enumFormStringArray, enumFormString, enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble); return ok(); } @ApiAction public Result testInlineAdditionalProperties() throws Exception { JsonNode nodeparam = request().body().asJson(); Object param; if (nodeparam != null) { param = mapper.readValue(nodeparam.toString(), Object.class); if (configuration.getBoolean("useInputBeanValidation")) { SwaggerUtils.validate(param); } } else { throw new IllegalArgumentException("'param' parameter is required"); } imp.testInlineAdditionalProperties(param); return ok(); } @ApiAction public Result testJsonFormData() throws Exception { String valueparam = (request().body().asMultipartFormData().asFormUrlEncoded().get("param"))[0]; String param; if (valueparam != null) { param = valueparam; } else { throw new IllegalArgumentException("'param' parameter is required"); } String valueparam2 = (request().body().asMultipartFormData().asFormUrlEncoded().get("param2"))[0]; String param2; if (valueparam2 != null) { param2 = valueparam2; } else { throw new IllegalArgumentException("'param2' parameter is required"); } imp.testJsonFormData(param, param2); return ok(); } }
{ "pile_set_name": "Github" }
/* eslint-disable max-len, max-statements, complexity, default-case */ // Copyright 2014 The Chromium Authors. 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 Google Inc. 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. /** * Copyright 2018-2020 Florian Bruhin (The Compiler) <[email protected]> * * This file is part of qutebrowser. * * qutebrowser 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. * * qutebrowser 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 qutebrowser. If not, see <http://www.gnu.org/licenses/>. */ /** * Ported chrome-caretbrowsing extension. * https://cs.chromium.org/chromium/src/ui/accessibility/extensions/caretbrowsing/ * * The behavior is based on Mozilla's spec whenever possible: * http://www.mozilla.org/access/keyboard/proposal * * The one exception is that Esc is used to escape out of a form control, * rather than their proposed key (which doesn't seem to work in the * latest Firefox anyway). * * Some details about how Chrome selection works, which will help in * understanding the code: * * The Selection object (window.getSelection()) has four components that * completely describe the state of the caret or selection: * * base and anchor: this is the start of the selection, the fixed point. * extent and focus: this is the end of the selection, the part that * moves when you hold down shift and press the left or right arrows. * * When the selection is a cursor, the base, anchor, extent, and focus are * all the same. * * There's only one time when the base and anchor are not the same, or the * extent and focus are not the same, and that's when the selection is in * an ambiguous state - i.e. it's not clear which edge is the focus and which * is the anchor. As an example, if you double-click to select a word, then * the behavior is dependent on your next action. If you press Shift+Right, * the right edge becomes the focus. But if you press Shift+Left, the left * edge becomes the focus. * * When the selection is in an ambiguous state, the base and extent are set * to the position where the mouse clicked, and the anchor and focus are set * to the boundaries of the selection. * * The only way to set the selection and give it direction is to use * the non-standard Selection.setBaseAndExtent method. If you try to use * Selection.addRange(), the anchor will always be on the left and the focus * will always be on the right, making it impossible to manipulate * selections that move from right to left. * * Finally, Chrome will throw an exception if you try to set an invalid * selection - a selection where the left and right edges are not the same, * but it doesn't span any visible characters. A common example is that * there are often many whitespace characters in the DOM that are not * visible on the page; trying to select them will fail. Another example is * any node that's invisible or not displayed. * * While there are probably many possible methods to determine what is * selectable, this code uses the method of determining if there's a valid * bounding box for the range or not - keep moving the cursor forwards until * the range from the previous position and candidate next position has a * valid bounding box. */ "use strict"; window._qutebrowser.caret = (function() { function isElementInViewport(node) { let i; let boundingRect = (node.getClientRects()[0] || node.getBoundingClientRect()); if (boundingRect.width <= 1 && boundingRect.height <= 1) { const rects = node.getClientRects(); for (i = 0; i < rects.length; i++) { if (rects[i].width > rects[0].height && rects[i].height > rects[0].height) { boundingRect = rects[i]; } } } if (boundingRect === undefined) { return null; } if (boundingRect.top > innerHeight || boundingRect.left > innerWidth) { return null; } if (boundingRect.width <= 1 || boundingRect.height <= 1) { const children = node.children; let visibleChildNode = false; for (i = 0; i < children.length; ++i) { boundingRect = (children[i].getClientRects()[0] || children[i].getBoundingClientRect()); if (boundingRect.width > 1 && boundingRect.height > 1) { visibleChildNode = true; break; } } if (visibleChildNode === false) { return null; } } if (boundingRect.top + boundingRect.height < 10 || boundingRect.left + boundingRect.width < -10) { return null; } const computedStyle = window.getComputedStyle(node, null); if (computedStyle.visibility !== "visible" || computedStyle.display === "none" || node.hasAttribute("disabled") || parseInt(computedStyle.width, 10) === 0 || parseInt(computedStyle.height, 10) === 0) { return null; } return boundingRect.top >= -20; } function positionCaret() { const walker = document.createTreeWalker(document.body, -1); let node; const textNodes = []; let el; while ((node = walker.nextNode())) { if (node.nodeType === 3 && node.nodeValue.trim() !== "") { textNodes.push(node); } } for (let i = 0; i < textNodes.length; i++) { const element = textNodes[i].parentElement; if (isElementInViewport(element)) { el = element; break; } } if (el !== undefined) { /* eslint-disable no-use-before-define */ const start = new Cursor(el, 0, ""); const end = new Cursor(el, 0, ""); const nodesCrossed = []; const result = TraverseUtil.getNextChar( start, end, nodesCrossed, true); if (result === null) { return; } CaretBrowsing.setAndValidateSelection(start, start); /* eslint-enable no-use-before-define */ } } /** * Return whether a node is focusable. This includes nodes whose tabindex * attribute is set to "-1" explicitly - these nodes are not in the tab * order, but they should still be focused if the user navigates to them * using linear or smart DOM navigation. * * Note that when the tabIndex property of an Element is -1, that doesn't * tell us whether the tabIndex attribute is missing or set to "-1" explicitly, * so we have to check the attribute. * * @param {Object} targetNode The node to check if it's focusable. * @return {boolean} True if the node is focusable. */ function isFocusable(targetNode) { if (!targetNode || typeof (targetNode.tabIndex) !== "number") { return false; } if (targetNode.tabIndex >= 0) { return true; } if (targetNode.hasAttribute && targetNode.hasAttribute("tabindex") && targetNode.getAttribute("tabindex") === "-1") { return true; } return false; } const axs = {}; axs.dom = {}; axs.color = {}; axs.utils = {}; axs.dom.parentElement = function(node) { if (!node) { return null; } const composedNode = axs.dom.composedParentNode(node); if (!composedNode) { return null; } switch (composedNode.nodeType) { case Node.ELEMENT_NODE: return composedNode; default: return axs.dom.parentElement(composedNode); } }; axs.dom.shadowHost = function(node) { if ("host" in node) { return node.host; } return null; }; axs.dom.composedParentNode = function(node) { if (!node) { return null; } if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { return axs.dom.shadowHost(node); } const parentNode = node.parentNode; if (!parentNode) { return null; } if (parentNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { return axs.dom.shadowHost(parentNode); } if (!parentNode.shadowRoot) { return parentNode; } const points = node.getDestinationInsertionPoints(); if (points.length > 0) { return axs.dom.composedParentNode(points[points.length - 1]); } return null; }; axs.color.Color = function(red, green, blue, alpha) { this.red = red; this.green = green; this.blue = blue; this.alpha = alpha; }; axs.color.parseColor = function(colorText) { if (colorText === "transparent") { return new axs.color.Color(0, 0, 0, 0); } let match = colorText.match(/^rgb\((\d+), (\d+), (\d+)\)$/); if (match) { const blue = parseInt(match[3], 10); const green = parseInt(match[2], 10); const red = parseInt(match[1], 10); return new axs.color.Color(red, green, blue, 1); } match = colorText.match(/^rgba\((\d+), (\d+), (\d+), (\d*(\.\d+)?)\)/); if (match) { const red = parseInt(match[1], 10); const green = parseInt(match[2], 10); const blue = parseInt(match[3], 10); const alpha = parseFloat(match[4]); return new axs.color.Color(red, green, blue, alpha); } return null; }; axs.color.flattenColors = function(color1, color2) { const colorAlpha = color1.alpha; return new axs.color.Color( ((1 - colorAlpha) * color2.red) + (colorAlpha * color1.red), ((1 - colorAlpha) * color2.green) + (colorAlpha * color1.green), ((1 - colorAlpha) * color2.blue) + (colorAlpha * color2.blue), color1.alpha + (color2.alpha * (1 - color1.alpha))); }; axs.utils.getParentBgColor = function(_el) { let el = _el; let el2 = el; let iter = null; el = []; for (iter = null; (el2 = axs.dom.parentElement(el2));) { const style = window.getComputedStyle(el2, null); if (style) { const color = axs.color.parseColor(style.backgroundColor); if (color && (style.opacity < 1 && (color.alpha *= style.opacity), color.alpha !== 0 && (el.push(color), color.alpha === 1))) { iter = !0; break; } } } if (!iter) { el.push(new axs.color.Color(255, 255, 255, 1)); } for (el2 = el.pop(); el.length;) { iter = el.pop(); el2 = axs.color.flattenColors(iter, el2); } return el2; }; axs.utils.getFgColor = function(el, el2, color) { let color2 = axs.color.parseColor(el.color); if (!color2) { return null; } if (color2.alpha < 1) { color2 = axs.color.flattenColors(color2, color); } if (el.opacity < 1) { const el3 = axs.utils.getParentBgColor(el2); color2.alpha *= el.opacity; color2 = axs.color.flattenColors(color2, el3); } return color2; }; axs.utils.getBgColor = function(el, elParent) { let color = axs.color.parseColor(el.backgroundColor); if (!color) { return null; } if (el.opacity < 1) { color.alpha *= el.opacity; } if (color.alpha < 1) { const bgColor = axs.utils.getParentBgColor(elParent); if (bgColor === null) { return null; } color = axs.color.flattenColors(color, bgColor); } return color; }; axs.color.colorChannelToString = function(_color) { const color = Math.round(_color); if (color < 15) { return `0${color.toString(16)}`; } return color.toString(16); }; axs.color.colorToString = function(color) { if (color.alpha === 1) { const red = axs.color.colorChannelToString(color.red); const green = axs.color.colorChannelToString(color.green); const blue = axs.color.colorChannelToString(color.blue); return `#${red}${green}${blue}`; } const arr = [color.red, color.green, color.blue, color.alpha].join(); return `rgba(${arr})`; }; /** * A class to represent a cursor location in the document, * like the start position or end position of a selection range. * * Later this may be extended to support "virtual text" for an object, * like the ALT text for an image. * * Note: we cache the text of a particular node at the time we * traverse into it. Later we should add support for dynamically * reloading it. * @param {Node} node The DOM node. * @param {number} index The index of the character within the node. * @param {string} text The cached text contents of the node. * @constructor */ // eslint-disable-next-line func-style const Cursor = function(node, index, text) { this.node = node; this.index = index; this.text = text; }; /** * @return {Cursor} A new cursor pointing to the same location. */ Cursor.prototype.clone = function() { return new Cursor(this.node, this.index, this.text); }; /** * Modify this cursor to point to the location that another cursor points to. * @param {Cursor} otherCursor The cursor to copy from. */ Cursor.prototype.copyFrom = function(otherCursor) { this.node = otherCursor.node; this.index = otherCursor.index; this.text = otherCursor.text; }; /** * Utility functions for stateless DOM traversal. * @constructor */ const TraverseUtil = {}; /** * Gets the text representation of a node. This allows us to substitute * alt text, names, or titles for html elements that provide them. * @param {Node} node A DOM node. * @return {string} A text string representation of the node. */ TraverseUtil.getNodeText = function(node) { if (node.constructor === Text) { return node.data; } return ""; }; /** * Return true if a node should be treated as a leaf node, because * its children are properties of the object that shouldn't be traversed. * * TODO(dmazzoni): replace this with a predicate that detects nodes with * ARIA roles and other objects that have their own description. * For now we just detect a couple of common cases. * * @param {Node} node A DOM node. * @return {boolean} True if the node should be treated as a leaf node. */ TraverseUtil.treatAsLeafNode = function(node) { return node.childNodes.length === 0 || node.nodeName === "SELECT" || node.nodeName === "OBJECT"; }; /** * Return true only if a single character is whitespace. * From https://developer.mozilla.org/en/Whitespace_in_the_DOM, * whitespace is defined as one of the characters * "\t" TAB \u0009 * "\n" LF \u000A * "\r" CR \u000D * " " SPC \u0020. * * @param {string} c A string containing a single character. * @return {boolean} True if the character is whitespace, otherwise false. */ TraverseUtil.isWhitespace = function(ch) { return (ch === " " || ch === "\n" || ch === "\r" || ch === "\t"); }; /** * Use the computed CSS style to figure out if this DOM node is currently * visible. * @param {Node} node A HTML DOM node. * @return {boolean} Whether or not the html node is visible. */ TraverseUtil.isVisible = function(node) { if (!node.style) { return true; } const style = window.getComputedStyle(node, null); return (Boolean(style) && style.display !== "none" && style.visibility !== "hidden"); }; /** * Use the class name to figure out if this DOM node should be traversed. * @param {Node} node A HTML DOM node. * @return {boolean} Whether or not the html node should be traversed. */ TraverseUtil.isSkipped = function(_node) { let node = _node; if (node.constructor === Text) { node = node.parentElement; } if (node.className === "CaretBrowsing_Caret") { return true; } return false; }; /** * Moves the cursor forwards until it has crossed exactly one character. * @param {Cursor} cursor The cursor location where the search should start. * On exit, the cursor will be immediately to the right of the * character returned. * @param {Array<Node>} nodesCrossed Any HTML nodes crossed between the * initial and final cursor position will be pushed onto this array. * @return {?string} The character found, or null if the bottom of the * document has been reached. */ TraverseUtil.forwardsChar = function(cursor, nodesCrossed) { for (;;) { let childNode = null; if (!TraverseUtil.treatAsLeafNode(cursor.node)) { for (let i = cursor.index; i < cursor.node.childNodes.length; i++) { const node = cursor.node.childNodes[i]; if (TraverseUtil.isSkipped(node)) { nodesCrossed.push(node); } else if (TraverseUtil.isVisible(node)) { childNode = node; break; } } } if (childNode) { cursor.node = childNode; cursor.index = 0; cursor.text = TraverseUtil.getNodeText(cursor.node); if (cursor.node.constructor !== Text) { nodesCrossed.push(cursor.node); } } else { // Return the next character from this leaf node. if (cursor.index < cursor.text.length) { return cursor.text[cursor.index++]; } // Move to the next sibling, going up the tree as necessary. while (cursor.node !== null) { // Try to move to the next sibling. let siblingNode = null; for (let node = cursor.node.nextSibling; node !== null; node = node.nextSibling) { if (TraverseUtil.isSkipped(node)) { nodesCrossed.push(node); } else if (TraverseUtil.isVisible(node)) { siblingNode = node; break; } } if (siblingNode) { cursor.node = siblingNode; cursor.text = TraverseUtil.getNodeText(siblingNode); cursor.index = 0; if (cursor.node.constructor !== Text) { nodesCrossed.push(cursor.node); } break; } // Otherwise, move to the parent. const parentNode = cursor.node.parentNode; if (parentNode && parentNode.constructor !== HTMLBodyElement) { cursor.node = cursor.node.parentNode; cursor.text = null; cursor.index = 0; } else { return null; } } } } }; /** * Finds the next character, starting from endCursor. Upon exit, startCursor * and endCursor will surround the next character. If skipWhitespace is * true, will skip until a real character is found. Otherwise, it will * attempt to select all of the whitespace between the initial position * of endCursor and the next non-whitespace character. * @param {Cursor} startCursor On exit, points to the position before * the char. * @param {Cursor} endCursor The position to start searching for the next * char. On exit, will point to the position past the char. * @param {Array<Node>} nodesCrossed Any HTML nodes crossed between the * initial and final cursor position will be pushed onto this array. * @param {boolean} skipWhitespace If true, will keep scanning until a * non-whitespace character is found. * @return {?string} The next char, or null if the bottom of the * document has been reached. */ TraverseUtil.getNextChar = function( startCursor, endCursor, nodesCrossed, skipWhitespace) { // Save the starting position and get the first character. startCursor.copyFrom(endCursor); let fChar = TraverseUtil.forwardsChar(endCursor, nodesCrossed); if (fChar === null) { return null; } // Keep track of whether the first character was whitespace. const initialWhitespace = TraverseUtil.isWhitespace(fChar); // Keep scanning until we find a non-whitespace or non-skipped character. while ((TraverseUtil.isWhitespace(fChar)) || (TraverseUtil.isSkipped(endCursor.node))) { fChar = TraverseUtil.forwardsChar(endCursor, nodesCrossed); if (fChar === null) { return null; } } if (skipWhitespace || !initialWhitespace) { // If skipWhitepace is true, or if the first character we encountered // was not whitespace, return that non-whitespace character. startCursor.copyFrom(endCursor); startCursor.index--; return fChar; } for (let i = 0; i < nodesCrossed.length; i++) { if (TraverseUtil.isSkipped(nodesCrossed[i])) { // We need to make sure that startCursor and endCursor aren't // surrounding a skippable node. endCursor.index--; startCursor.copyFrom(endCursor); startCursor.index--; return " "; } } // Otherwise, return all of the whitespace before that last character. endCursor.index--; return " "; }; /** * The class handling the Caret Browsing implementation in the page. * Sets up communication with the background page, and then when caret * browsing is enabled, response to various key events to move the caret * or selection within the text content of the document. * @constructor */ const CaretBrowsing = {}; /** * Is caret browsing enabled? * @type {boolean} */ CaretBrowsing.isEnabled = false; /** * Keep it enabled even when flipped off (for the options page)? * @type {boolean} */ CaretBrowsing.forceEnabled = false; /** * What to do when the caret appears? * @type {string} */ CaretBrowsing.onEnable = undefined; /** * What to do when the caret jumps? * @type {string} */ CaretBrowsing.onJump = undefined; /** * Is this window / iframe focused? We won't show the caret if not, * especially so that carets aren't shown in two iframes of the same * tab. * @type {boolean} */ CaretBrowsing.isWindowFocused = false; /** * Is the caret actually visible? This is true only if isEnabled and * isWindowFocused are both true. * @type {boolean} */ CaretBrowsing.isCaretVisible = false; /** * Selection modes. * NOTE: Values need to line up with SelectionState in browsertab.py! * * @type {enum} */ CaretBrowsing.SelectionState = { "NONE": "none", "NORMAL": "normal", "LINE": "line", }; /** * The actual caret element, an absolute-positioned flashing line. * @type {Element} */ CaretBrowsing.caretElement = undefined; /** * The x-position of the caret, in absolute pixels. * @type {number} */ CaretBrowsing.caretX = 0; /** * The y-position of the caret, in absolute pixels. * @type {number} */ CaretBrowsing.caretY = 0; /** * The width of the caret in pixels. * @type {number} */ CaretBrowsing.caretWidth = 0; /** * The height of the caret in pixels. * @type {number} */ CaretBrowsing.caretHeight = 0; /** * The foregroundc color. * @type {string} */ CaretBrowsing.caretForeground = "#000"; /** * The backgroundc color. * @type {string} */ CaretBrowsing.caretBackground = "#fff"; /** * Is the selection collapsed, i.e. are the start and end locations * the same? If so, our blinking caret image is shown; otherwise * the Chrome selection is shown. * @type {boolean} */ CaretBrowsing.isSelectionCollapsed = false; /** * Whether we're running on Windows. * @type {boolean} */ CaretBrowsing.isWindows = null; /** * Whether we're running on on old Qt 5.7.1. * There, we need to use -webkit-filter. * @type {boolean} */ CaretBrowsing.needsFilterPrefix = null; /** * The id returned by window.setInterval for our stopAnimation function, so * we can cancel it when we call stopAnimation again. * @type {number?} */ CaretBrowsing.animationFunctionId = null; /** * Check if a node is a control that normally allows the user to interact * with it using arrow keys. We won't override the arrow keys when such a * control has focus, the user must press Escape to do caret browsing outside * that control. * @param {Node} node A node to check. * @return {boolean} True if this node is a control that the user can * interact with using arrow keys. */ CaretBrowsing.isControlThatNeedsArrowKeys = function(node) { if (!node) { return false; } if (node === document.body || node !== document.activeElement) { return false; } if (node.constructor === HTMLSelectElement) { return true; } if (node.constructor === HTMLInputElement) { switch (node.type) { case "email": case "number": case "password": case "search": case "text": case "tel": case "url": case "": return true; // All of these are text boxes. case "datetime": case "datetime-local": case "date": case "month": case "radio": case "range": case "week": return true; // These are other input elements that use arrows. } } // Handle focusable ARIA controls. if (node.getAttribute && isFocusable(node)) { const role = node.getAttribute("role"); switch (role) { case "combobox": case "grid": case "gridcell": case "listbox": case "menu": case "menubar": case "menuitem": case "menuitemcheckbox": case "menuitemradio": case "option": case "radiogroup": case "scrollbar": case "slider": case "spinbutton": case "tab": case "tablist": case "textbox": case "tree": case "treegrid": case "treeitem": return true; } } return false; }; CaretBrowsing.injectCaretStyles = function() { const prefix = CaretBrowsing.needsFilterPrefix ? "-webkit-" : ""; const style = ` .CaretBrowsing_Caret { position: absolute; z-index: 2147483647; min-height: 1em; min-width: 0.2em; animation: blink 1s step-end infinite; --inherited-color: inherit; background-color: var(--inherited-color, #000); color: var(--inherited-color, #000); mix-blend-mode: difference; ${prefix}filter: invert(85%); } @keyframes blink { 50% { visibility: hidden; } } `; const node = document.createElement("style"); node.innerHTML = style; document.body.appendChild(node); }; /** * If there's no initial selection, set the cursor just before the * first text character in the document. */ CaretBrowsing.setInitialCursor = function() { const selectionRange = window.getSelection().toString().length; if (selectionRange === 0) { positionCaret(); } CaretBrowsing.injectCaretStyles(); CaretBrowsing.toggle(); CaretBrowsing.initiated = true; if (selectionRange > 0) { CaretBrowsing.selectionState = CaretBrowsing.SelectionState.NORMAL; } else { CaretBrowsing.selectionState = CaretBrowsing.SelectionState.NONE; } }; /** * Try to set the window's selection to be between the given start and end * cursors, and return whether or not it was successful. * @param {Cursor} start The start position. * @param {Cursor} end The end position. * @return {boolean} True if the selection was successfully set. */ CaretBrowsing.setAndValidateSelection = function(start, end) { const sel = window.getSelection(); sel.setBaseAndExtent(start.node, start.index, end.node, end.index); if (sel.rangeCount !== 1) { return false; } return (sel.anchorNode === start.node && sel.anchorOffset === start.index && sel.focusNode === end.node && sel.focusOffset === end.index); }; /** * Set focus to a node if it's focusable. If it's an input element, * select the text, otherwise it doesn't appear focused to the user. * Every other control behaves normally if you just call focus() on it. * @param {Node} node The node to focus. * @return {boolean} True if the node was focused. */ CaretBrowsing.setFocusToNode = function(nodeArg) { let node = nodeArg; while (node && node !== document.body) { if (isFocusable(node) && node.constructor !== HTMLIFrameElement) { node.focus(); if (node.constructor === HTMLInputElement && node.select) { node.select(); } return true; } node = node.parentNode; } return false; }; /** * Set the caret element's normal style, i.e. not when animating. */ CaretBrowsing.setCaretElementNormalStyle = function() { const element = CaretBrowsing.caretElement; element.className = "CaretBrowsing_Caret"; if (CaretBrowsing.isSelectionCollapsed) { element.style.opacity = "1.0"; } else { element.style.opacity = "0.0"; } element.style.left = `${CaretBrowsing.caretX}px`; element.style.top = `${CaretBrowsing.caretY}px`; element.style.width = `${CaretBrowsing.caretWidth}px`; element.style.height = `${CaretBrowsing.caretHeight}px`; element.style.color = CaretBrowsing.caretForeground; }; /** * Create the caret element. This assumes that caretX, caretY, * caretWidth, and caretHeight have all been set. The caret is * animated in so the user can find it when it first appears. */ CaretBrowsing.createCaretElement = function() { const element = document.createElement("div"); element.className = "CaretBrowsing_Caret"; document.body.appendChild(element); CaretBrowsing.caretElement = element; CaretBrowsing.setCaretElementNormalStyle(); }; /** * Recreate the caret element, triggering any intro animation. */ CaretBrowsing.recreateCaretElement = function() { if (CaretBrowsing.caretElement) { CaretBrowsing.caretElement.parentElement.removeChild( CaretBrowsing.caretElement); CaretBrowsing.caretElement = null; CaretBrowsing.updateIsCaretVisible(); } }; /** * Get the rectangle for a cursor position. This is tricky because * you can't get the bounding rectangle of an empty range, so this function * computes the rect by trying a range including one character earlier or * later than the cursor position. * @param {Cursor} cursor A single cursor position. * @return {{left: number, top: number, width: number, height: number}} * The bounding rectangle of the cursor. */ CaretBrowsing.getCursorRect = function(cursor) { let node = cursor.node; const index = cursor.index; const rect = { "left": 0, "top": 0, "width": 1, "height": 0, }; if (node.constructor === Text) { let left = index; let right = index; const max = node.data.length; const newRange = document.createRange(); while (left > 0 || right < max) { if (left > 0) { left--; newRange.setStart(node, left); newRange.setEnd(node, index); const rangeRect = newRange.getBoundingClientRect(); if (rangeRect && rangeRect.width && rangeRect.height) { rect.left = rangeRect.right; rect.top = rangeRect.top; rect.height = rangeRect.height; break; } } if (right < max) { right++; newRange.setStart(node, index); newRange.setEnd(node, right); const rangeRect = newRange.getBoundingClientRect(); if (rangeRect && rangeRect.width && rangeRect.height) { rect.left = rangeRect.left; rect.top = rangeRect.top; rect.height = rangeRect.height; break; } } } } else { rect.height = node.offsetHeight; while (node !== null) { rect.left += node.offsetLeft; rect.top += node.offsetTop; node = node.offsetParent; } } rect.left += window.pageXOffset; rect.top += window.pageYOffset; return rect; }; /** * Compute the new location of the caret or selection and update * the element as needed. * @param {boolean} scrollToSelection If true, will also scroll the page * to the caret / selection location. */ CaretBrowsing.updateCaretOrSelection = function(scrollToSelection) { const sel = window.getSelection(); if (sel.rangeCount === 0) { if (CaretBrowsing.caretElement) { CaretBrowsing.isSelectionCollapsed = false; CaretBrowsing.caretElement.style.opacity = "0.0"; } return; } const range = sel.getRangeAt(0); if (!range) { if (CaretBrowsing.caretElement) { CaretBrowsing.isSelectionCollapsed = false; CaretBrowsing.caretElement.style.opacity = "0.0"; } return; } if (CaretBrowsing.isControlThatNeedsArrowKeys( document.activeElement)) { let node = document.activeElement; CaretBrowsing.caretWidth = node.offsetWidth; CaretBrowsing.caretHeight = node.offsetHeight; CaretBrowsing.caretX = 0; CaretBrowsing.caretY = 0; while (node.offsetParent) { CaretBrowsing.caretX += node.offsetLeft; CaretBrowsing.caretY += node.offsetTop; node = node.offsetParent; } CaretBrowsing.isSelectionCollapsed = false; } else if (range.startOffset !== range.endOffset || range.startContainer !== range.endContainer) { const rect = range.getBoundingClientRect(); if (!rect) { return; } CaretBrowsing.caretX = rect.left + window.pageXOffset; CaretBrowsing.caretY = rect.top + window.pageYOffset; CaretBrowsing.caretWidth = rect.width; CaretBrowsing.caretHeight = rect.height; CaretBrowsing.isSelectionCollapsed = false; } else { const rect = CaretBrowsing.getCursorRect( new Cursor(range.startContainer, range.startOffset, TraverseUtil.getNodeText(range.startContainer))); CaretBrowsing.caretX = rect.left; CaretBrowsing.caretY = rect.top; CaretBrowsing.caretWidth = rect.width; CaretBrowsing.caretHeight = rect.height; CaretBrowsing.isSelectionCollapsed = true; } if (CaretBrowsing.caretElement) { const element = CaretBrowsing.caretElement; if (CaretBrowsing.isSelectionCollapsed) { element.style.opacity = "1.0"; element.style.left = `${CaretBrowsing.caretX}px`; element.style.top = `${CaretBrowsing.caretY}px`; element.style.width = `${CaretBrowsing.caretWidth}px`; element.style.height = `${CaretBrowsing.caretHeight}px`; } else { element.style.opacity = "0.0"; } } else { CaretBrowsing.createCaretElement(); } let elem = range.startContainer; if (elem.constructor === Text) { elem = elem.parentElement; } const style = window.getComputedStyle(elem); const bg = axs.utils.getBgColor(style, elem); const fg = axs.utils.getFgColor(style, elem, bg); CaretBrowsing.caretBackground = axs.color.colorToString(bg); CaretBrowsing.caretForeground = axs.color.colorToString(fg); if (scrollToSelection) { // Scroll just to the "focus" position of the selection, // the part the user is manipulating. const rect = CaretBrowsing.getCursorRect( new Cursor(sel.focusNode, sel.focusOffset, TraverseUtil.getNodeText(sel.focusNode))); const yscroll = window.pageYOffset; const pageHeight = window.innerHeight; const caretY = rect.top; const caretHeight = Math.min(rect.height, 30); if (yscroll + pageHeight < caretY + caretHeight) { window.scroll(0, (caretY + caretHeight - pageHeight + 100)); } else if (caretY < yscroll) { window.scroll(0, (caretY - 100)); } } }; CaretBrowsing.reverseSelection = () => { const sel = window.getSelection(); sel.setBaseAndExtent( sel.extentNode, sel.extentOffset, sel.baseNode, sel.baseOffset ); }; CaretBrowsing.selectLine = function() { const sel = window.getSelection(); sel.modify("extend", "right", "lineboundary"); CaretBrowsing.reverseSelection(); sel.modify("extend", "left", "lineboundary"); CaretBrowsing.reverseSelection(); }; CaretBrowsing.updateLineSelection = function(direction, granularity) { if (granularity !== "character" && granularity !== "word") { window. getSelection(). modify("extend", direction, granularity); CaretBrowsing.selectLine(); } }; CaretBrowsing.move = function(direction, granularity, count = 1) { let action = "move"; if (CaretBrowsing.selectionState !== CaretBrowsing.SelectionState.NONE) { action = "extend"; } for (let i = 0; i < count; i++) { if (CaretBrowsing.selectionState === CaretBrowsing.SelectionState.LINE) { CaretBrowsing.updateLineSelection(direction, granularity); } else { window. getSelection(). modify(action, direction, granularity); } } if (CaretBrowsing.isWindows && (direction === "forward" || direction === "right") && granularity === "word") { CaretBrowsing.move("left", "character"); } }; CaretBrowsing.finishMove = function() { window.setTimeout(() => { CaretBrowsing.updateCaretOrSelection(true); }, 0); CaretBrowsing.stopAnimation(); }; CaretBrowsing.moveToBlock = function(paragraph, boundary, count = 1) { let action = "move"; if (CaretBrowsing.selectionState !== CaretBrowsing.SelectionState.NONE) { action = "extend"; } for (let i = 0; i < count; i++) { window. getSelection(). modify(action, paragraph, "paragraph"); window. getSelection(). modify(action, boundary, "paragraphboundary"); if (CaretBrowsing.selectionState === CaretBrowsing.SelectionState.LINE) { CaretBrowsing.selectLine(); } } }; CaretBrowsing.toggle = function(value) { if (CaretBrowsing.forceEnabled) { CaretBrowsing.recreateCaretElement(); return; } if (value === undefined) { CaretBrowsing.isEnabled = !CaretBrowsing.isEnabled; } else { CaretBrowsing.isEnabled = value; } CaretBrowsing.updateIsCaretVisible(); }; /** * Event handler, called when the mouse is clicked. Chrome already * sets the selection when the mouse is clicked, all we need to do is * update our cursor. * @param {Event} evt The DOM event. * @return {boolean} True if the default action should be performed. */ CaretBrowsing.onClick = function() { if (!CaretBrowsing.isEnabled) { return true; } window.setTimeout(() => { CaretBrowsing.updateCaretOrSelection(false); }, 0); return true; }; /** * Update whether or not the caret is visible, based on whether caret browsing * is enabled and whether this window / iframe has focus. */ CaretBrowsing.updateIsCaretVisible = function() { CaretBrowsing.isCaretVisible = (CaretBrowsing.isEnabled && CaretBrowsing.isWindowFocused); if (CaretBrowsing.isCaretVisible && !CaretBrowsing.caretElement) { CaretBrowsing.setInitialCursor(); CaretBrowsing.updateCaretOrSelection(true); } else if (!CaretBrowsing.isCaretVisible && CaretBrowsing.caretElement) { if (CaretBrowsing.caretElement) { CaretBrowsing.isSelectionCollapsed = false; CaretBrowsing.caretElement.parentElement.removeChild( CaretBrowsing.caretElement); CaretBrowsing.caretElement = null; } } }; CaretBrowsing.onWindowFocus = function() { CaretBrowsing.isWindowFocused = true; CaretBrowsing.updateIsCaretVisible(); }; CaretBrowsing.onWindowBlur = function() { CaretBrowsing.isWindowFocused = false; CaretBrowsing.updateIsCaretVisible(); }; CaretBrowsing.startAnimation = function() { if (CaretBrowsing.caretElement) { CaretBrowsing.caretElement.style.animationIterationCount = "infinite"; } }; CaretBrowsing.stopAnimation = function() { if (CaretBrowsing.caretElement) { CaretBrowsing.caretElement.style.animationIterationCount = 0; window.clearTimeout(CaretBrowsing.animationFunctionId); CaretBrowsing.animationFunctionId = window.setTimeout(() => { CaretBrowsing.startAnimation(); }, 1000); } }; CaretBrowsing.init = function() { CaretBrowsing.isWindowFocused = document.hasFocus(); document.addEventListener("click", CaretBrowsing.onClick, false); window.addEventListener("focus", CaretBrowsing.onWindowFocus, false); window.addEventListener("blur", CaretBrowsing.onWindowBlur, false); }; window.setTimeout(() => { if (!window.caretBrowsingLoaded) { window.caretBrowsingLoaded = true; CaretBrowsing.init(); if (document.body && document.body.getAttribute("caretbrowsing") === "on") { CaretBrowsing.forceEnabled = true; CaretBrowsing.isEnabled = true; CaretBrowsing.updateIsCaretVisible(); } } }, 0); const funcs = {}; funcs.setInitialCursor = () => { if (!CaretBrowsing.initiated) { CaretBrowsing.setInitialCursor(); return CaretBrowsing.selectionState !== CaretBrowsing.SelectionState.NONE; } if (window.getSelection().toString().length === 0) { positionCaret(); } CaretBrowsing.toggle(); return CaretBrowsing.selectionState !== CaretBrowsing.SelectionState.NONE; }; funcs.setFlags = (flags) => { CaretBrowsing.isWindows = flags.includes("windows"); CaretBrowsing.needsFilterPrefix = flags.includes("filter-prefix"); }; funcs.disableCaret = () => { CaretBrowsing.toggle(false); }; funcs.toggle = () => { CaretBrowsing.toggle(); }; funcs.moveRight = (count = 1) => { CaretBrowsing.move("right", "character", count); CaretBrowsing.finishMove(); }; funcs.moveLeft = (count = 1) => { CaretBrowsing.move("left", "character", count); CaretBrowsing.finishMove(); }; funcs.moveDown = (count = 1) => { CaretBrowsing.move("forward", "line", count); CaretBrowsing.finishMove(); }; funcs.moveUp = (count = 1) => { CaretBrowsing.move("backward", "line", count); CaretBrowsing.finishMove(); }; funcs.moveToEndOfWord = (count = 1) => { CaretBrowsing.move("forward", "word", count); CaretBrowsing.finishMove(); }; funcs.moveToNextWord = (count = 1) => { CaretBrowsing.move("forward", "word", count); CaretBrowsing.move("right", "character"); CaretBrowsing.finishMove(); }; funcs.moveToPreviousWord = (count = 1) => { CaretBrowsing.move("backward", "word", count); CaretBrowsing.finishMove(); }; funcs.moveToStartOfLine = () => { CaretBrowsing.move("left", "lineboundary"); CaretBrowsing.finishMove(); }; funcs.moveToEndOfLine = () => { CaretBrowsing.move("right", "lineboundary"); CaretBrowsing.finishMove(); }; funcs.moveToStartOfNextBlock = (count = 1) => { CaretBrowsing.moveToBlock("forward", "backward", count); CaretBrowsing.finishMove(); }; funcs.moveToStartOfPrevBlock = (count = 1) => { CaretBrowsing.moveToBlock("backward", "backward", count); CaretBrowsing.finishMove(); }; funcs.moveToEndOfNextBlock = (count = 1) => { CaretBrowsing.moveToBlock("forward", "forward", count); CaretBrowsing.finishMove(); }; funcs.moveToEndOfPrevBlock = (count = 1) => { CaretBrowsing.moveToBlock("backward", "forward", count); CaretBrowsing.finishMove(); }; funcs.moveToStartOfDocument = () => { CaretBrowsing.move("backward", "documentboundary"); CaretBrowsing.finishMove(); }; funcs.moveToEndOfDocument = () => { CaretBrowsing.move("forward", "documentboundary"); CaretBrowsing.finishMove(); }; funcs.dropSelection = () => { window.getSelection().removeAllRanges(); }; funcs.getSelection = () => window.getSelection().toString(); funcs.toggleSelection = (line) => { if (line) { CaretBrowsing.selectionState = CaretBrowsing.SelectionState.LINE; CaretBrowsing.selectLine(); CaretBrowsing.finishMove(); } else if (CaretBrowsing.selectionState !== CaretBrowsing.SelectionState.NORMAL) { CaretBrowsing.selectionState = CaretBrowsing.SelectionState.NORMAL; } else { CaretBrowsing.selectionState = CaretBrowsing.SelectionState.NONE; } return CaretBrowsing.selectionState; }; funcs.reverseSelection = () => { CaretBrowsing.reverseSelection(); }; return funcs; })();
{ "pile_set_name": "Github" }
/* * JBoss, Home of Professional Open Source * Copyright 2015, Red Hat, Inc. and/or its affiliates, and individual * contributors by the @authors tag. See the copyright.txt in the * distribution for a full listing of individual contributors. * * 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.jboss.as.quickstarts.loggingToolsQS.loggers; import org.jboss.logging.BasicLogger; import org.jboss.logging.Logger; import org.jboss.logging.Logger.Level; import org.jboss.logging.annotations.Cause; import org.jboss.logging.annotations.LogMessage; import org.jboss.logging.annotations.Message; import org.jboss.logging.annotations.MessageLogger; @MessageLogger(projectCode = "GTRDATES") public interface DateLogger extends BasicLogger { DateLogger LOGGER = Logger.getMessageLogger(DateLogger.class, DateLogger.class.getPackage().getName()); @LogMessage(level = Level.ERROR) @Message(id = 3, value = "Invalid date passed as string: %s") void logStringCouldntParseAsDate(String dateString, @Cause Throwable exception); @LogMessage @Message(id = 4, value = "Requested number of days until '%s'") void logDaysUntilRequest(String dateString); }
{ "pile_set_name": "Github" }